text:
package semtech

import "time"

// Proxies handle annoying json fields like datr and time
type payloadProxy struct {
	ProxRXPK []rxpkProxy `json:"rxpk,omitempty"`
	ProxStat *statProxy  `json:"stat,omitempty"`
	ProxTXPK *txpkProxy  `json:"txpk,omitempty"`
}

type statProxy struct {
	*Stat
	Time *Timeparser `json:"time,omitempty"`
}

type rxpkProxy struct {
	*RXPK
	Datr *Datrparser `json:"datr,omitempty"`
	Time *Timeparser `json:"time,omitempty"`
}

type txpkProxy struct {
	*TXPK
	Datr *Datrparser `json:"datr,omitempty"`
	Time *Timeparser `json:"time,omitempty"`
}

// datrParser is used as a proxy to Unmarshal datr field in json payloads.
// Depending on the modulation type, the datr type could be either a string or a number.
// We're gonna parse it as a string in any case.
type Datrparser struct {
	Kind  string
	Value string // The parsed value
}

// timeParser is used as a proxy to Unmarshal JSON objects with different date types as the time
// module parse RFC3339 by default
type Timeparser struct {
	Layout string
	Value  *time.Time // The parsed time value
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SEQUOIA</title>

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

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Cabin:700' rel='stylesheet' type='text/css'>

    <link href="css/grayscale_serv.css" rel="stylesheet">
    <link href="css/goz.css" rel="stylesheet">
    <link href="css/landing-page.css" rel="stylesheet">

            SEQUOIA

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu

        </button>

              Impuestos

              Consultoría

              Contabilidad

              Precios de Transferencía

              Desarrollo Profesional

PRECIOS DE TRANSFERENCIA

10 años de experiencia  con grupos nacionales y multinacionales

Analizamos procedimientos, políticas, objetivos, procesos y todos los aspectos que permiten la sinergia de un grupo para que el Estudio de Precios de Transferencia se convierta en una herramienta clave, en la toma de decisiones dentro de la organización.

Consultoría en Precios de Transferencia

·       Análisis / Opinión previa para fijación de precios de transferencia.

·       Estudio de Precios de Transferencia

·       Llenado de anexos de SIPRED relativos a precios de transferencia.

·       Declaración informativa múltiple de operaciones con partes relacionadas en el extranjero.

·       Declaraciones globales, locales y maestras de precios de transferencia.

·       Acuerdos anticipados de precios (APA)

Obligados al Estudio de Precios de Transferencia

· ·       Empresas que realicen operaciones con partes relacionadas nacionales o extranjeras y que reporten ingresos acumulables iguales o mayores a trece millones de pesos en el ejercicio.

·       Personas físicas que realicen operaciones con partes relacionadas nacionales o extranjeras y que reporten ingresos acumulables iguales o mayores a tres millones de pesos en el ejercicio.

En Sequoia BI creamos estudios a la medida de cada grupo empresarial, para que los Precios de Transferencia sean un elemento clave en la estrategia de la organización.

PLATIQUEMOS.

E-mail: info@sequoia.mx
 Whatsapp: +52 22 23 25 10 61

Copyright © SEQUOIA 2017
Torre Setri 6109 Int 202 Puebla, Pue.

redpajama_set_name: RedPajamaGithub


text:
package org.revapi.java.spi;

import javax.annotation.Nonnull;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.ExecutableType;

/**
 * Elements in the element forest that represent Java methods, will implement this interface.
 *
 * @author Lukas Krejci
 *
 * @since 0.1
 */
public interface JavaMethodElement extends JavaModelElement {
    @Override
    ExecutableType getModelRepresentation();

    @Override
    ExecutableElement getDeclaringElement();

    @Override
    @Nonnull
    JavaTypeElement getParent();
}


text:
package org.ocpsoft.rewrite.config;

import org.apache.http.client.methods.HttpGet;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.ocpsoft.rewrite.Root;
import org.ocpsoft.rewrite.test.HttpAction;
import org.ocpsoft.rewrite.test.RewriteTest;

/**
 * @author Lincoln Baxter, III
 *
 */
public class RelocatingConfigurationLoaderTest extends RewriteTest
{

   @Deployment(testable = false)
   public static WebArchive getDeployment()
   {
      WebArchive deployment = RewriteTest
               .getDeployment()
               .addPackages(true, Root.class.getPackage())
               .addAsServiceProvider(ConfigurationProvider.class,
                        RelocatingConfigurationProvider1.class, RelocatingConfigurationProvider2.class,
                        RelocatingConfigurationProvider3.class);
      return deployment;
   }

   @Test
   public void testRelocatedRuleExecutesInNewOrderUp() throws Exception
   {
      HttpAction<HttpGet> action = get("/priority");
      Assert.assertEquals(201, action.getResponse().getStatusLine().getStatusCode());
   }

   @Test
   public void testRelocatedRuleExecutesInNewOrderDown() throws Exception
   {
      HttpAction<HttpGet> action = get("/priority2");
      Assert.assertEquals(202, action.getResponse().getStatusLine().getStatusCode());
   }

   @Test
   public void testRelocatedRuleExecutesInNewOrderUpUp() throws Exception
   {
      HttpAction<HttpGet> action = get("/priority3");
      Assert.assertEquals(203, action.getResponse().getStatusLine().getStatusCode());
   }

   @Test
   public void testRelocatedRulePriorityOverlapFollowsProviderPriorityOrder() throws Exception
   {
      HttpAction<HttpGet> action = get("/priority4");
      Assert.assertEquals(202, action.getResponse().getStatusLine().getStatusCode());
   }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Atlas page test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="all" href="css/atlas.css" />

        Home
        Help

    <form name="searchform" class="searchform">
        <input type="search" name="search-input" placeholder="Search here" />
    </form>

Map: Tectonic map of Texas

            First we quote original comments for the image, then follow with
            misc notes and errata (if needed).

            Can play with styling this I guess.

            Follow up with links to others in series [if in one] and related images.
            The concept is to have an atlas you can browse chronologically so links are important.
            In fact a useful UI is more important than the super basic style I made.

            University of Texas at Austin,
            Bureau of Economic Geology, 1997

            TAGS: #Texas #geology #tectonic #economic #1997 [all links obviously]

            File size 209kb

            Image size 779px by 1028px [images over 800 px or 250kb -should- get thumbnails!]


text:
<?php

namespace common\models\rate;

use common\models\ActiveRecordTimestamp;
use Yii;
use common\models\quote\Quote;

/**
 * This is the model class for table "rate".
 *
 * @property integer $rateid
 * @property integer $quoteid
 * @property string $openrate
 * @property string $closerate
 * @property string $ratedate
 * @property string $minimum
 * @property string $maximum
 * @property string $lastdeal
 * @property integer $deals
 * @property string $wa
 * @property integer $dayval
 * @property integer $dayvol
 * @property integer $ActiveFlag
 * @property string $ChangeDate
 *
 * @property Quote $quote
 */
class Rate extends ActiveRecordTimestamp
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'rate';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['quoteid', 'ratedate', 'openrate', 'closerate', 'minimum', 'maximum'], 'required'],
            [['quoteid', 'deals', 'dayval', 'dayvol', 'ActiveFlag'], 'integer'],
            [['openrate', 'closerate', 'minimum', 'maximum', 'lastdeal', 'wa'], 'number'],
            [['ratedate', 'ChangeDate'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'rateid' => 'Rateid',
            'quoteid' => 'Quote',
            'openrate' => 'Open rate',
            'closerate' => 'Close rate',
            'ratedate' => 'Rate date',
            'minimum' => 'Minimum',
            'maximum' => 'Maximum',
            'lastdeal' => 'Last deal',
            'deals' => 'Deals',
            'wa' => 'Wa',
            'dayval' => 'Day value',
            'dayvol' => 'Day volume',
            'ActiveFlag' => 'Active Flag',
            'ChangeDate' => 'Change Date',
        ];
    }

    public function extraFields()
    {
        return ['quote'];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuote()
    {
        return $this->hasOne(Quote::className(), ['qid' => 'quoteid']);
    }

    // get the percentage difference with the previous day
    /**
     * @return string
     */
    public function getDiffFromTheDayBefore(){
        $val = $this->find()->select('lastdeal')
                    ->where(['<','ratedate',$this->ratedate])
                    ->andWhere(['quoteid' => $this->quote->qid])
                    ->orderBy('ratedate DESC')
                    ->limit(1)->scalar();
        if($val){
            return round(($this->lastdeal/$val - 1) * 100,2);
        }else{
            return 'No data';
        }
    }

    /**
     * @param $period string: 'day','month', 'year', 'all'
     */
    public static function getDatesForLiderTab($period){
        $startdate = null;
        $enddate = Yii::$app->db->createCommand('SELECT DISTINCT ratedate FROM rate ORDER BY ratedate DESC LIMIT 1')->queryScalar();
        switch($period){
            case 'day':
                $startdate = Yii::$app->db->createCommand('SELECT DISTINCT ratedate FROM rate ORDER BY ratedate DESC LIMIT 1,1')->queryScalar();
                break;
            case 'month':
                $startdate = Yii::$app->db->createCommand('SELECT ratedate
                                                          FROM rate
                                                          WHERE ratedate >= DATE_SUB(:enddate, INTERVAL DAYOFMONTH(:enddate)-1 DAY)
                                                          ORDER BY ratedate ASC
                                                          LIMIT 1',[":enddate" => $enddate])->queryScalar();
                break;
            case 'year':
                $startdate = Yii::$app->db->createCommand('SELECT ratedate
                                                          FROM rate
                                                          WHERE ratedate >= DATE_SUB(:enddate, INTERVAL DAYOFYEAR(:enddate)-1 DAY)
                                                          ORDER BY ratedate ASC
                                                          LIMIT 1',[":enddate" => $enddate])->queryScalar();
                break;
            case 'all':
                $startdate = Yii::$app->db->createCommand('SELECT DISTINCT ratedate FROM rate ORDER BY ratedate ASC LIMIT 1')->queryScalar();
                break;
            //assume default as the 1st case
            default:
                $startdate = Yii::$app->db->createCommand('SELECT DISTINCT ratedate FROM rate ORDER BY ratedate DESC LIMIT 1,1')->queryScalar();
        }
        return [$startdate,$enddate];
    }

    /**
     * @param $startdate date
     * @param $enddate date
     * @param bool $lider
     * @param int $limit
     * @return array
     */
    public static function getLidersBetweenSelectedDates($startdate,$enddate,$lider=true,$limit = 10){
        $order = $lider ? 'DESC' : 'ASC';
        $sub = static::find()->where(['ratedate' => $startdate]);
        return static::find()->select(['rate.closerate as closeEnd'
                                        ,'rate.ratedate as dateCloseEnd'
                                        ,'u.closerate as closeStart'
                                        ,'u.ratedate as dateCloseStart'
                                        ,'quote.qid'
                                        ,'quote.fullname'
                                        ,'quote.acronym'
                                        ,'quote.shortname'
                                        ,'round((rate.lastdeal/u.lastdeal - 1)*100,2) as diff'])
            ->innerJoin(['u' => $sub],'u.quoteid = rate.quoteid')
            ->innerJoin('quote','quote.qid = rate.quoteid')
            ->where(['rate.ratedate' => $enddate])
            ->orderBy("diff $order")
            ->limit($limit)
            ->asArray()
            ->all();
    }

    // get the percentage difference with the selected date
    /**
     * @param $date datetime
     * @return float
     */
//    public function getDiffFromTheDay($date){
//
//    }
}


text:
<?php

include "functions.php";

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <meta name="google-signin-client_id" content="575498541884-dl7r3sns0rf1khmbe09sp7qqlml2rjrm.apps.googleusercontent.com">

    <title>Group Share</title>

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

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Group Share

                    <?php createGroupRequests(null); ?>

 Profile

                         Sign out

                                <input type="text" class="form-control input-sm" placeholder="Search for a group" />
                                <button class="btn btn-info dropdown-toggle btn-sm" type="button" data-toggle="dropdown">

                                </button>
                                <?php groupSearch(null) ?>

 Private Files

            <?php
                include 'p_list_files.php';///////////////////////////////////////////////////////////////////////
            ?>

        <form action="p_add_file.php" method="post" enctype="multipart/form-data">
            <input type="file" name="uploaded_file">

            <input type="submit" value="Upload file">
        </form>


text:
import { createSelector } from 'reselect';
import NAME from './NAME';

export const getSubstate = state => state[NAME].locationBeforeTransitions;

export const getQuery = createSelector(
  getSubstate,
  substate => substate.query
);

export const getPathname = createSelector(
  getSubstate,
  substate => substate.pathname
);


text:
package org.fiteagle.adapters.ACSclient.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class RequestedParameters implements Serializable{

  private List<Parameter> parameters;

  public RequestedParameters(){
    this.parameters = new ArrayList<Parameter>();
  }

  public void setParameters(Parameter parameter){
    this.parameters.add(parameter);
  }

  public List<Parameter> getParameters(){
    return this.parameters;
  }

}


text:
package org.apache.geronimo.deployment.remote;

import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.gbean.GBeanInfo;

/**
 * Just a placeholder so things can look this up.
 *
 * @version $Rev$ $Date$
 */
public class RemoteDeployGBean implements RemoteDeployToken {
    public RemoteDeployGBean() {
    }

    public static final GBeanInfo GBEAN_INFO;

    static {
        GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(RemoteDeployGBean.class);
        infoFactory.addInterface(RemoteDeployToken.class);
        infoFactory.setConstructor(new String[0]);
        GBEAN_INFO = infoFactory.getBeanInfo();
    }

    public static GBeanInfo getGBeanInfo() {
        return GBEAN_INFO;
    }
}


text: it's a simple describe


text:
import { Collection } from "wonder-commonlib/dist/es2015/Collection";

var list = Collection.create();

list.addChild(1);


text:
using System;
using Elasticsearch.Net;
using Newtonsoft.Json;
using System.Linq.Expressions;

namespace Nest
{
	public partial interface ITermVectorsRequest<TDocument>
		where TDocument : class
	{
		/// <summary>
		/// An optional document to get termvectors for instead of using an already indexed document
		/// </summary>
		[JsonProperty("doc")]
		TDocument Document { get; set; }

		[JsonProperty("per_field_analyzer")]
		IPerFieldAnalyzer PerFieldAnalyzer { get; set; }

		[JsonProperty("filter")]
		ITermVectorFilter Filter { get; set; }
	}

	public partial class TermVectorsRequest<TDocument>
		where TDocument : class
	{
		HttpMethod IRequest.HttpMethod => (this.Document != null || this.Filter != null) ? HttpMethod.POST : HttpMethod.GET;

		public TDocument Document { get; set; }

		public IPerFieldAnalyzer PerFieldAnalyzer { get; set; }

		public ITermVectorFilter Filter { get; set; }

		partial void DocumentFromPath(TDocument document)
		{
			Self.Document = document;
			if (Self.Document != null)
				Self.RouteValues.Remove("id");
		}
	}

	[DescriptorFor("Termvectors")]
	public partial class TermVectorsDescriptor<TDocument> where TDocument : class
	{
		HttpMethod IRequest.HttpMethod => (Self.Document != null || Self.Filter != null) ? HttpMethod.POST : HttpMethod.GET;

		TDocument ITermVectorsRequest<TDocument>.Document { get; set; }

		IPerFieldAnalyzer ITermVectorsRequest<TDocument>.PerFieldAnalyzer { get; set; }

		ITermVectorFilter ITermVectorsRequest<TDocument>.Filter { get; set; }

		public TermVectorsDescriptor<TDocument> Document(TDocument document) => Assign(a => a.Document = document);

		public TermVectorsDescriptor<TDocument> PerFieldAnalyzer(Func<PerFieldAnalyzerDescriptor<TDocument>, IPromise<IPerFieldAnalyzer>> analyzerSelector) =>
			Assign(a => a.PerFieldAnalyzer = analyzerSelector?.Invoke(new PerFieldAnalyzerDescriptor<TDocument>())?.Value);

		public TermVectorsDescriptor<TDocument> Filter(Func<TermVectorFilterDescriptor, ITermVectorFilter> filterSelector) =>
			Assign(a => a.Filter = filterSelector?.Invoke(new TermVectorFilterDescriptor()));
	}
}


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

using System;
using System.Text;

namespace tainicom.Helpers
{
    public class CommonHelper
    {
        public Random Random;

         #region implement Sigleton
        static CommonHelper _instance;
        public static CommonHelper Current {get { return (_instance == null) ? new CommonHelper() : _instance; } }
        #endregion

        private CommonHelper()
        {
            Random = new Random((int)DateTime.Now.Ticks);
            CommonHelper._instance = this;
        }

        //static classes for bound cheking,parameter checking, Crossplaform P-Trace, etc
#if DEBUG
        public static void Trace(string message)
        {
            #if (WP7 || WP8 || WP8_1 || W8_1 || W10)
                System.Diagnostics.Debug.WriteLine(message);
            #elif WINDOWS
                System.Diagnostics.Trace.WriteLine(message);
            #endif
        }
        public static void Trace(StringBuilder message)
        {
            Trace(message.ToString());
        }
        public static void Trace(Object message)
        {
            Trace(message.ToString());
        }

        public static void ArgumentNotNullOrEmptyString(string argumentValue, string argumentName)
        {
            ArgumentNotNull(argumentValue, argumentName);
            if (argumentValue.Length == 0) throw new ArgumentException("String cannot be empty.", argumentName);
            return;
        }

        public static void ArgumentNotNull(object argumentValue, string argumentName)
        {
            if (argumentValue == null) throw new ArgumentNullException(argumentName);
            return;
        }
#endif
        public static void ShowDialog(string message)
        {
            #if WP7 || WP8
            System.Windows.MessageBox.Show(message);
            #elif WP8_1 || W8_1 || W10

            #endif
        }

    }
}


text:
package org.projectodd.stilts.stomp.protocol;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.handler.codec.embedder.EncoderEmbedder;
import org.junit.Before;
import org.junit.Test;
import org.projectodd.stilts.stomp.DefaultHeaders;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomp.StompMessages;
import org.projectodd.stilts.stomp.protocol.StompFrame.Header;
import org.projectodd.stilts.stomp.protocol.StompFrame.Version;

public class StompFrameEncoderTest {

    private EncoderEmbedder<ChannelBuffer> encoder;

    @Before
    public void setUp() {
        this.encoder = new EncoderEmbedder<ChannelBuffer>( new StompFrameEncoder() );
    }

    @Test
    public void testAckFrame() {
        StompFrame frame = StompFrames.newAckFrame( new DefaultHeaders() );
        frame.setHeader( Header.SUBSCRIPTION, "subscription-42" );
        frame.setHeader( Header.MESSAGE_ID, "message-84" );

        boolean result = this.encoder.offer( frame );
        assertTrue( result );

        List<String> lines = getFrameLines();

        assertEquals( "ACK", lines.get(0) );
        assertContainsLine( "subscription:subscription-42", lines );
        assertContainsLine( "message-id:message-84", lines );
    }

    @Test
    public void testConnectedFrame() {
        StompFrame frame = StompFrames.newConnectedFrame( "session-42", Version.VERSION_1_1 );

        boolean result = this.encoder.offer( frame );
        assertTrue( result );

        List<String> lines = getFrameLines();

        assertEquals( "CONNECTED", lines.get(0) );
        assertContainsLine( "session:session-42", lines );
        assertContainsLine( "version:1.1", lines );
    }

    @Test
    public void testErrorFrame() {
        StompMessage message = StompMessages.createStompMessage();
        message.getHeaders().put( Header.RECEIPT, "some-frame" );
        StompFrame inReplyTo = StompFrames.newSendFrame( message );
        StompFrame frame = StompFrames.newErrorFrame( "It broke", inReplyTo );

        boolean result = this.encoder.offer( frame );
        assertTrue( result );

        List<String> lines = getFrameLines();

        assertEquals( "ERROR", lines.get(0) );
        assertContainsLine( "receipt-id:some-frame", lines );
        assertContainsContent( "It broke", lines );
    }

    protected void assertContainsLine(String expected, List<String> lines) {
        assertTrue( lines.indexOf( expected ) >= 0 );
    }

    protected void assertContainsContent(String expected, List<String> lines) {
        String actual = lines.get( lines.size()-1 );
        assertEquals( expected, actual.substring( 0, expected.length() ) );
        byte[] bytes = actual.getBytes();
        assertEquals( 0, bytes[ bytes.length - 1 ] );
    }

    protected List<String> getFrameLines() {
        ChannelBuffer buffer = this.encoder.poll();
        assertNotNull( buffer );

        List<String> lines = new ArrayList<String>();

        String content = buffer.toString( Charset.forName( "UTF-8"  ) );

        StringTokenizer tokenizer = new StringTokenizer( content, "\n"  );

        while ( tokenizer.hasMoreTokens() ) {
            lines.add(  tokenizer.nextToken() );
        }

        return lines;

    }

}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using RevolutionaryStuff.Core;
using RevolutionaryStuff.Core.Database;

namespace RevolutionaryStuff.TheLoader
{
    public class SocrataMetadata
    {
        public Uri SocrataUrl { get; set; }
        public string Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime Updated { get; set; }
        public string Category { get; set; }
        public string ODataUrl { get; set; }
        public Uri PageUrl { get; set; }
        public string TableName { get; set; }
        public string Owner { get; set; }
        public int? Size { get; set; }

        private static readonly Regex InitialStateJsonExpr = new Regex(@"var\s+initialState\s+=\s+{(.+?)}\s+;", RegexOptions.Compiled);

        private static string TrimPlus(string s)
        {
            s = s ?? "";
            s = RegexHelpers.Common.Whitespace.Replace(s, " ");
            s = s.Replace("&", "&");
            return StringHelpers.TrimOrNull(s);
        }

        public static SocrataMetadata Fetch(Uri sourceUrl, string id)
        {
            var url = new Uri($"{sourceUrl.GetComponents(UriComponents.HostAndPort | UriComponents.SchemeAndServer, UriFormat.Unescaped)}/d/{id}");

            var client = new HttpClient();
            var resp = DelegateHelpers.CallAndRetryOnFailure(() => client.GetAsync(url).ExecuteSynchronously());
            var html = resp.Content.ReadAsStringAsync().ExecuteSynchronously();
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            Match m;

            var nodes = doc.DocumentNode.SelectNodes("//script[@type=\"text/javascript\"]");
            string initialStateJson = null;
            foreach (HtmlAgilityPack.HtmlNode node in nodes)
            {
                m = InitialStateJsonExpr.Match(node.InnerText);
                if (!m.Success) continue;
                initialStateJson = "{" + m.Groups[1].Value + "}";
                break;
            }
            if (initialStateJson == null) return null;
            Socrata.Rootobject socrataRoot;
            try
            {
                socrataRoot = JsonConvert.DeserializeObject<Socrata.Rootobject>(initialStateJson);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                return null;
            }

            var md = new SocrataMetadata
            {
                Id = id,
                Title = socrataRoot.view.name,
                Description = TrimPlus(socrataRoot.view.description),
                Updated = socrataRoot.view.lastUpdatedAt,
                Category = socrataRoot.view.category,
                ODataUrl = socrataRoot.view.odataUrlV4,
                PageUrl = sourceUrl,
                Owner = socrataRoot.view.ownerName,
                SocrataUrl = url
            };
            md.TableName = (RegexHelpers.Common.NonWordChars.Replace(md.Title, " ").ToUpperCamelCase() + "_" + id.Replace("-", "")).TruncateWithMidlineEllipsis(SqlServerHelpers.MaxTableNameLength, "___");

            int size = 0;
            foreach (var col in socrataRoot.view.columns.Where(zz => zz.cachedContents != null))
            {
                size = Stuff.Max(size, col.cachedContents.non_null);
            }
            if (size > 0)
            {
                md.Size = size;
            }
            return md;
        }
    }
}


text:
require 'yaml'
require 'go_cd/last_green_build_fetcher'

module GoWatchdogHelper

  def last_green_build_time
    pipeline_config = watchdog_config['pipeline']
    auth_config = watchdog_config['credentials']
    fetcher = GoCD::LastGreenBuildFetcher.new(:protocol => pipeline_config['protocol'] || 'https',
                                        :host => pipeline_config['host'],
                                        :port => pipeline_config['port'] || 443,
                                        :username => auth_config['username'],
                                        :password => auth_config['password'],
                                        :pipeline_name => pipeline_config['name'],
                                        :stage_name => pipeline_config['stage'])
    fetcher.fetch.tap do |green_build|
      return green_build.completed_at if green_build
    end
  end

end


text:
omxremote is a mobile friendly webinterface to remote control omxplayer.bin on your raspberry pi. connect the pi to a tv/beamer, and use omxremote with your mobile phone to control video playback.

##STATUS
Currently under development. I'd say it's in beta phase.
What works:
 - chose video and start playback
 - play/pause and stop
 - volume and subtitle control

##TODO
 - implement skip forward/backward, skip to movie-position
 - bugfixes
 - create debian apt repository for raspbian

##INSTALL
```
apt-get install python-dbus
git clone https://github.com/flurischt/omxremote.git
cd omxremote/
# maybe create a virtualenv before running setup.py install
pip install -r requirements.txt
python setup.py install
```
##RUN
Do NOT expose gunicorn to the internet. Use nginx. (TODO: document this)

```OMXREMOTE_MOVIE_DIR=/PATH/TO/YOUR/MOVIES gunicorn -w 2 -b 127.0.0.1:5000 omxremote:app```


text:
var mongoose = require('mongoose');
var _ = require('lodash');
var safeHTML = require('../utils/safeHTML.js');

/* 数据表 */
var Tag = require('../models/Tag.js');
var Category = require('../models/Category.js');
var Blog = require('../models/Blog.js');

/* 邮件 */
var mail = require('../sendEmail.js');

/* 日期格式化 */
var dateFormat = require('../utils/dateFormat.js');

/*
	请求分类列表
*/
exports.tags = function(req, res) {

	Tag.fetchAll(function(err, tags) {

		if ( err ) {
			return errorHandler(err, res);
		}

		return res.json({
			result: 'success',
			tags: tags || [],
		});

	});

};

function errorHandler(err, res) {
	console.log(err);
	return res.json({
		result: 'error',
		reason: '数据库错误',
	});
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NSubstitute;
using NUnit.Framework;
using RestSharp;
using YouTrack.Rest.Factories;
using YouTrack.Rest.Requests;

namespace YouTrack.Rest.Tests.Factories
{
    class RestFileRequestFactoryTests : TestFor<RestFileRequestFactory>
    {
        private IRestRequestFactory restRequestFactory;
        private IYouTrackPostWithFileRequest postWithFileRequest;
        private ISession session;
        private IRestRequest restRequest;

        protected override RestFileRequestFactory CreateSut()
        {
            restRequestFactory = Mock<IRestRequestFactory>();

            return new RestFileRequestFactory(restRequestFactory);
        }

        protected override void SetupDependencies()
        {
            session = Mock<ISession>();
            postWithFileRequest = Mock<IYouTrackPostWithFileRequest>();

            restRequest = Mock<IRestRequest>();
            restRequest.Parameters.Returns(new List<Parameter>());
            restRequest.Parameters.Add(new Parameter() { Name = "Accept", Value = "foo"});

            restRequestFactory.CreateRestRequest(postWithFileRequest, session, Method.POST)
                              .Returns(restRequest);

        }

        private IRestRequest GetRestRequestWithFile()
        {
            return Sut.CreateRestRequestWithFile(postWithFileRequest, session, Method.POST);
        }

        [Test]
        public void PostingFileRequestUsesJson()
        {
            IRestRequest restRequestWithFile = GetRestRequestWithFile();

            Assert.That(restRequestWithFile.Parameters.Single(p => p.Name == "Accept").Value, Is.EqualTo("application/json"));
        }

        [Test]
        public void FileIsPostedWithName()
        {
            postWithFileRequest.Name.Returns("files");

            IRestRequest restRequestWithFile = GetRestRequestWithFile();

            restRequestWithFile.Received().AddFile("files", Arg.Any<String>());
        }

        [Test]
        public void FileIsPostedWithFilePath()
        {
            postWithFileRequest.FilePath.Returns("foo.jpg");

            IRestRequest restRequestWithFile = GetRestRequestWithFile();

            restRequestWithFile.Received().AddFile(Arg.Any<String>(), "foo.jpg");
        }

        [Test]
        public void FileIsPostedWithBytes()
        {
            byte[] bytes = new byte[512];
            string filename = "foo.txt";

            postWithFileRequest.HasBytes.Returns(true);
            postWithFileRequest.Bytes.Returns(bytes);
            postWithFileRequest.FileName.Returns(filename);

            IRestRequest restRequestWithFile = GetRestRequestWithFile();

            restRequestWithFile.Received().AddFile(Arg.Any<String>(), bytes, filename);
        }
    }
}


text:
const express = require("express");
const JobController = require("../dbConnections/jobController");
const jobQuery = require("../constants/queryString");
const { status, responseText } = require("../constants/responseAndStatus");
const logger = require("../logger/log");
const program = require("../constants/config");
const redisClient = require("../messageQueue/redisClient");
const router = express.Router();
const jobController = new JobController(jobQuery);
router.get("/job/:id", (req, res) => {
    if (!req.params.id) {
        return res.status(status.bad_request).json({
            "error": responseText.bad_request
        });
    } else {
        jobController.getJob(req.params.id)
            .then(result => {
                logger.info(result.message);
                res.status(result.status);
                if (result.data !== null) {
                    res.json({
                        "data": result.data
                    });
                } else {
                    res.json({
                        "info": result.message
                    });
                }
            });
    }
});

router.post("/jobs", (req, res) => {
    if (!req.body) {
        return res.status(status.bad_request).json({
            "error": responseText.bad_request
        });
    } else {
        jobController.createJob(req.body.name, req.body.description, req.body.frequency, req.body.script,req.body.repeat)
            .then(result => {
                if (result.data !== null) {
                    let jobId = result.locationHeader.split("/").reverse()[0];
                    redisClient.publish(program.CHANNEL, jobId);
                    redisClient.sadd(program.JOB_STORE, jobId);
                    res.set("Location", result.locationHeader);
                }
                logger.info(result.message);
                res.status(result.status).json({
                    "info": result.message
                });
            });
    }
});

module.exports = router;


text:
package com.hp.alm.ali.idea.services;

import com.hp.alm.ali.ServerVersion;
import com.hp.alm.ali.idea.IntellijTest;
import com.hp.alm.ali.idea.rest.ServerType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CustomizationServiceTest extends IntellijTest {

    private CustomizationService customizationService;

    public CustomizationServiceTest() {
        super(ServerVersion.ALM11);
    }

    @Before
    public void preClean() throws Throwable {
        customizationService = getComponent(CustomizationService.class);
        customizationService.connectedTo(ServerType.NONE);

        handler.addRequest("GET", "/qcbin/rest/domains/domain/projects/project/customization/extensions/dev/preferences", 200)
                .content("customizationServiceTest.xml");
    }

    @Test
    public void testGetNewDefectStatus() {
        handler.async();
        String status = customizationService.getNewDefectStatus(new NonDispatchTestCallback<String>(handler) {
            @Override
            protected void evaluate(String data) {
                Assert.assertEquals("New", data);

                // served from cache
                Assert.assertEquals("New", customizationService.getNewDefectStatus(null));
            }
        });
        Assert.assertNull(status);

        // served from cache
        customizationService.getNewDefectStatus(new NonDispatchTestCallback<String>(handler) {
            @Override
            protected void evaluate(String data) {
                Assert.assertEquals("New", data);

                // served from cache
                Assert.assertEquals("New", customizationService.getNewDefectStatus(null));
            }
        });
    }

    @Test
    public void testGetNewDefectStatus_dispatch() {
        handler.async();
        String status = customizationService.getNewDefectStatus(new DispatchTestCallback<String>(handler) {
            @Override
            protected void evaluate(String data) {
                Assert.assertEquals("New", data);
                Assert.assertEquals("New", customizationService.getNewDefectStatus(null));
            }
        });
        Assert.assertNull(status);

        // served from cache
        customizationService.getNewDefectStatus(new DispatchTestCallback<String>(handler) {
            @Override
            protected void evaluate(String data) {
                Assert.assertEquals("New", data);
                Assert.assertEquals("New", customizationService.getNewDefectStatus(null));
            }
        });
    }
}


text:
nv-websocket-client
===================

Overview
--------

High-quality WebSocket client implementation in Java which

- complies with [RFC 6455](http://tools.ietf.org/html/rfc6455) (The WebSocket Protocol),
- works on Java SE 1.5+ and Android,
- supports all the frame types (continuation, binary, text, close, ping and pong),
- provides a method to send a fragmented frame in addition to methods for unfragmented frames,
- provides a method to get the underlying raw socket of a web socket to configure it,
- provides a method for [Basic Authentication](http://tools.ietf.org/html/rfc2617),
- provides a factory class which utilizes javax.net.SocketFactory interface,
- provides a rich listener interface to hook web socket events,
- has fine-grained error codes for fine-grained controllability on errors,
- allows to disable validity checks on RSV1/RSV2/RSV3 bits and opcode of frames,
- supports HTTP proxy, especially "Secure WebSocket" (`wss`) through "Secure Proxy" (`https`),
- and supports [RFC 7692](http://tools.ietf.org/html/rfc7692) (Compression Extensions for WebSocket),
  also known as _permessage-deflate_ (not enabled by default).

License
-------

Apache License, Version 2.0

Maven
-----

```xml
<dependency>
    <groupId>com.neovisionaries</groupId>
    <artifactId>nv-websocket-client</artifactId>
    <version>1.22</version>
</dependency>
```

Gradle
------

```Gradle
dependencies {
    compile 'com.neovisionaries:nv-websocket-client:1.22'
}
```

OSGi
----

    Bundle-SymbolicName: com.neovisionaries.ws.client
    Export-Package: com.neovisionaries.ws.client;version="1.22.0"

Source Code
-----------

  https://github.com/TakahikoKawasaki/nv-websocket-client.git

JavaDoc
-------

  http://TakahikoKawasaki.github.io/nv-websocket-client/

Description
-----------

#### Create WebSocketFactory

`WebSocketFactory` is a factory class that creates `WebSocket` instances. The
first step is to create a `WebSocketFactory` instance.

```java
// Create a WebSocketFactory instance.
WebSocketFactory factory = new WebSocketFactory();
```

By default, `WebSocketFactory` uses `SocketFactory.getDefault()` for non-secure
WebSocket connections (`ws:`) and `SSLSocketFactory.getDefault()` for secure
WebSocket connections (`wss:`). You can change this default behavior by using
`WebSocketFactory.setSocketFactory` method, `WebSocketFactory.setSSLSocketFactory`
method and `WebSocketFactory.setSSLContext` method. Note that you don't have to
call a `setSSL*` method at all if you use the default SSL configuration. Also
note that calling `setSSLSocketFactory` method has no meaning if you have called
`setSSLContext` method. See the
[description](http://takahikokawasaki.github.io/nv-websocket-client/com/neovisionaries/ws/client/WebSocketFactory.html#createSocket-java.net.URI-)
of `WebSocketFactory.createSocket(URI)` method for details.

The following is an example to set a custom SSL context to a `WebSocketFactory`
instance. (Again, you don't have to call a `setSSL*` method if you use the default
SSL configuration.)

```java
// Create a custom SSL context.
SSLContext context = NaiveSSLContext.getInstance("TLS");

// Set the custom SSL context.
factory.setSSLContext(context);
```

[NaiveSSLContext](https://gist.github.com/TakahikoKawasaki/d07de2218b4b81bf65ac)
used in the above example is a factory class to create an `SSLContext` which
naively accepts all certificates without verification. It's enough for testing
purposes. When you see an error message "unable to find valid certificate path
to requested target" while testing, try `NaiveSSLContext`.

#### HTTP Proxy

If a WebSocket endpoint needs to be accessed via an HTTP proxy, information
about the proxy server has to be set to a `WebSocketFactory` instance before
creating a `WebSocket` instance. Proxy settings are represented by
`ProxySettings` class. A `WebSocketFactory` instance has an associated
`ProxySettings` instance and it can be obtained by calling
`WebSocketFactory.getProxySettings()` method.

```java
// Get the associated ProxySettings instance.
ProxySettings settings = factory.getProxySettings();
```

`ProxySettings` class has methods to set information about a proxy server such
as `setHost` method and `setPort` method. The following is an example to set a
secure (`https`) proxy server.

```java
// Set a proxy server.
settings.setServer("https://proxy.example.com");
```

If credentials are required for authentication at a proxy server, `setId`
method and `setPassword` method, or `setCredentials` method can be used to set
the credentials. Note that, however, the current implementation supports only
Basic Authentication.

```java
// Set credentials for authentication at a proxy server.
settings.setCredentials(id, password);
```

#### Create WebSocket

`WebSocket` class represents a web socket. Its instances are created by calling
one of `createSocket` methods of a `WebSocketFactory` instance. Below is the
simplest example to create a `WebSocket` instance.

```java
// Create a web socket. The scheme part can be one of the following:
// 'ws', 'wss', 'http' and 'https' (case-insensitive). The user info
// part, if any, is interpreted as expected. If a raw socket failed
// to be created, an IOException is thrown.
WebSocket ws = new WebSocketFactory().createSocket("ws://localhost/endpoint");
```

There are two ways to set a timeout value for socket connection. The first way
is to call `setConnectionTimeout(int timeout)` method of `WebSocketFactory`.

```java
// Create a web socket factory and set 5000 milliseconds as a timeout
// value for socket connection.
WebSocketFactory factory = new WebSocketFactory().setConnectionTimeout(5000);

// Create a web socket. The timeout value set above is used.
WebSocket ws = factory.createSocket("ws://localhost/endpoint");
```

The other way is to give a timeout value to a `createSocket` method.

```java
// Create a web socket factory. The timeout value remains 0.
WebSocketFactory factory = new WebSocketFactory();

// Create a web socket with a socket connection timeout value.
WebSocket ws = factory.createSocket("ws://localhost/endpoint", 5000);
```

The timeout value is passed to `connect(SocketAddress, int)` method of
`java.net.Socket`.

#### Register Listener

After creating a `WebSocket` instance, you should call `addListener` method
to register a `WebSocketListener` that receives web socket events.
`WebSocketAdapter` is an empty implementation of `WebSocketListener` interface.

```java
// Register a listener to receive web socket events.
ws.addListener(new WebSocketAdapter() {
    @Override
    public void onTextMessage(WebSocket websocket, String message) throws Exception {
        // Received a text message.
        ......
    }
});
```

The table below is the list of callback methods defined in `WebSocketListener`
interface.

| Method                        | Description                                          |
|:------------------------------|:-----------------------------------------------------|
| `handleCallbackError`         | Called when an `onXxx()` method threw a `Throwable`. |
| `onBinaryFrame`               | Called when a binary frame was received.             |
| `onBinaryMessage`             | Called when a binary message was received.           |
| `onCloseFrame`                | Called when a close frame was received.              |
| `onConnected`                 | Called after the opening handshake succeeded.        |
| `onConnectError`              | Called when `connectAsynchronously()` failed.        |
| `onContinuationFrame`         | Called when a continuation frame was received.       |
| `onDisconnected`              | Called after a WebSocket connection was closed.      |
| `onError`                     | Called when an error occurred.                       |
| `onFrame`                     | Called when a frame was received.                    |
| `onFrameError`                | Called when a frame failed to be read.               |
| `onFrameSent`                 | Called when a frame was sent.                        |
| `onFrameUnsent`               | Called when a frame was not sent.                    |
| `onMessageDecompressionError` | Called when a message failed to be decompressed.     |
| `onMessageError`              | Called when a message failed to be constructed.      |
| `onPingFrame`                 | Called when a ping frame was received.               |
| `onPongFrame`                 | Called when a pong frame was received.               |
| `onSendError`                 | Called when an error occurred on sending a frame.    |
| `onSendingFrame`              | Called before a frame is sent.                       |
| `onSendingHandshake`          | Called before an opening handshake is sent.          |
| `onStateChanged`              | Called when the state of WebSocket changed.          |
| `onTextFrame`                 | Called when a text frame was received.               |
| `onTextMessage`               | Called when a text message was received.             |
| `onTextMessageError`          | Called when a text message failed to be constructed. |
| `onUnexpectedError`           | Called when an uncaught throwable was detected.      |

#### Configure WebSocket

Before starting a WebSocket [opening handshake]
(http://tools.ietf.org/html/rfc6455#section-4) with the server, you can
configure the web socket instance by using the following methods.

| METHOD              | DESCRIPTION                                             |
|---------------------|---------------------------------------------------------|
| `addProtocol`       | Adds an element to `Sec-WebSocket-Protocol`.            |
| `addExtension`      | Adds an element to `Sec-WebSocket-Extensions`.          |
| `addHeader`         | Adds an arbitrary HTTP header.                          |
| `setUserInfo`       | Adds `Authorization` header for Basic Authentication.   |
| `getSocket`         | Gets the underlying `Socket` instance to configure it.  |
| `setExtended`       | Disables validity checks on RSV1/RSV2/RSV3 and opcode.  |
| `setFrameQueueSize` | Set the size of the frame queue for congestion control. |

Note that `permessage-deflate` extension ([RFC 7692](http://tools.ietf.org/html/rfc7692))
has been supported since version 1.17. To enable the extension, call `addExtension`
method with `permessage-deflate`.

```java
// Enable "permessage-deflate" extension (RFC 7692).
ws.addExtension(WebSocketExtension.PERMESSAGE_DEFLATE);
```

The `permessage-deflate` support is new and needs testing. Feedback is welcome.

#### Connect To Server

By calling `connect()` method, connection to the server is established and a
WebSocket opening handshake is performed synchronously. If an error occurred
during the handshake, a `WebSocketException` would be thrown. Instead, if
the handshake succeeds, the `connect()` implementation creates threads and
starts them to read and write web socket frames asynchronously.

```java
try
{
    // Connect to the server and perform an opening handshake.
    // This method blocks until the opening handshake is finished.
    ws.connect();
}
catch (OpeningHandshakeException e)
{
    // A violation against the WebSocket protocol was detected
    // during the opening handshake.
}
catch (WebSocketException e)
{
    // Failed to establish a WebSocket connection.
}
```

In some cases, `connect()` method throws `OpeningHandshakeException` which
is a subclass of `WebSocketException` (since version 1.19).
`OpeningHandshakeException` provides additional methods such as
`getStatusLine()`, `getHeaders()` and `getBody()` to access the response
from a server. The following snippet is an example to print information
that the exception holds.

```java
catch (OpeningHandshakeException e)
{
    // Status line.
    StatusLine sl = e.getStatusLine();
    System.out.println("=== Status Line ===");
    System.out.format("HTTP Version  = %s\n", sl.getHttpVersion());
    System.out.format("Status Code   = %d\n", sl.getStatusCode());
    System.out.format("Reason Phrase = %s\n", sl.getReasonPhrase());

    // HTTP headers.
    Map<String, List<String>> headers = e.getHeaders();
    System.out.println("=== HTTP Headers ===");
    for (Map.Entry<String, List<String>> entry : headers.entrySet())
    {
        // Header name.
        String name = entry.getKey();

        // Values of the header.
        List<String> values = entry.getValue();

        if (values == null || values.size() == 0)
        {
            // Print the name only.
            System.out.println(name);
            continue;
        }

        for (String value : values)
        {
            // Print the name and the value.
            System.out.format("%s: %s\n", name, value);
        }
    }
}
```

#### Connect To Server Asynchronously

The simplest way to call `connect()` method asynchronously is to use
`connectAsynchronously()` method. The implementation of the method creates
a thread and calls `connect()` method in the thread. When the `connect()`
call failed, `onConnectError()` of `WebSocketListener` would be called.
Note that `onConnectError()` is called only when `connectAsynchronously()`
was used and the `connect()` call executed in the background thread failed.
Neither direct synchronous `connect()` nor `connect(ExecutorService)`
(described below) will trigger the callback method.

```java
// Connect to the server asynchronously.
ws.connectAsynchronously();
```

Another way to call `connect()` method asynchronously is to use
`connect(ExecutorService)` method. The method performs a WebSocket opening
handshake asynchronously using the given `ExecutorService`.

```java
// Prepare an ExecutorService.
ExecutorService es = Executors.newSingleThreadExecutor();

// Connect to the server asynchronously.
Future<WebSocket> future = ws.connect(es);

try
{
    // Wait for the opening handshake to complete.
    future.get();
}
catch (ExecutionException e)
{
    if (e.getCause() instanceof WebSocketException)
    {
        ......
    }
}
```

The implementation of `connect(ExecutorService)` method creates a
`Callable<WebSocket>` instance by calling `connectable()` method and
passes the instance to `submit(Callable)` method of the given
`ExecutorService`. What the implementation of `call()` method of the
`Callable` instance does is just to call the synchronous `connect()`.

#### Send Frames

Web socket frames can be sent by `sendFrame` method. Other `sendXxx`
methods such as `sendText` are aliases of `sendFrame` method. All of
the `sendXxx` methods work asynchronously. However, under some
conditions, `sendXxx` methods may block. See Congestion Control for
details.

Below are some examples of `sendXxx` methods. Note that in normal
cases, you don't have to call `sendClose` method and `sendPong`
method (or their variants) explicitly because they are called
automatically when appropriate.

```java
// Send a text frame.
ws.sendText("Hello.");

// Send a binary frame.
byte[] binary = ......;
ws.sendBinary(binary);

// Send a ping frame.
ws.sendPing("Are you there?");
```

If you want to send fragmented frames, you have to know the details of the
specification ([5.4. Fragmentation](https://tools.ietf.org/html/rfc6455#section-5.4)).
Below is an example to send a text message (`"How are you?"`) which consists
of 3 fragmented frames.

```java
// The first frame must be either a text frame or a binary frame.
// And its FIN bit must be cleared.
WebSocketFrame firstFrame = WebSocketFrame
    .createTextFrame("How ")
    .setFin(false);

// Subsequent frames must be continuation frames. The FIN bit of
// all continuation frames except the last one must be cleared.
// Note that the FIN bit of frames returned from
// WebSocketFrame.createContinuationFrame() method is cleared,
// so the example below does not clear the FIN bit explicitly.
WebSocketFrame secondFrame = WebSocketFrame
    .createContinuationFrame("are ");

// The last frame must be a continuation frame with the FIN bit
// set. Note that the FIN bit of frames returned from
// WebSocketFrame.createContinuationFrame methods is cleared,
// so the FIN bit of the last frame must be set explicitly.
WebSocketFrame lastFrame = WebSocketFrame
    .createContinuationFrame("you?")
    .setFin(true);

// Send a text message which consists of 3 frames.
ws.sendFrame(firstFrame)
  .sendFrame(secondFrame)
  .sendFrame(lastFrame);
```

Alternatively, the same as above can be done like this.

```java
ws.sendText("How ", false)
  .sendContinuation("are ")
  .sendContinuation("you?", true);
```

#### Send Ping/Pong Frames Periodically

You can send ping frames periodically by calling `setPingInterval` method
with an interval in milliseconds between ping frames. This method can be
called both before and after `connect()` method. Passing zero stops the
periodical sending.

```java
// Send a ping per 60 seconds.
ws.setPingInterval(60 * 1000);

// Stop the periodical sending.
ws.setPingInterval(0);
```

Likewise, you can send pong frames periodically by calling `setPongInterval`
method. "_A Pong frame MAY be sent **unsolicited**._" ([RFC 6455, 5.5.3. Pong]
(https://tools.ietf.org/html/rfc6455#section-5.5.3))

You can customize payload of ping/pong frames that are sent automatically
by using `setPingPayloadGenerator()` and `setPongPayloadGenerator()` methods.
Both methods take an instance of `PayloadGenerator` interface. The following
is an example to use the string representation of the current date as payload
of ping frames.

```java
ws.setPingPayloadGenerator(new PayloadGenerator() {
    @Override
    public byte[] generate() {
        // The string representation of the current date.
        return new Date().toString().getBytes();
    }
});
```

Note that the maximum payload length of control frames (e.g. ping frames)
is 125. Therefore, the length of a byte array returned from `generate()`
method must not exceed 125.

### Auto Flush

By default, a frame is automatically flushed to the server immediately
after `sendFrame` method is executed. This automatic flush can be disabled
by calling `setAutoFlush(false)`.

```java
// Disable auto-flush.
ws.setAutoFlush(false);
```

To flush frames manually, call `flush()` method. Note that this method
works asynchronously.

```java
// Flush frames to the server manually.
ws.flush();
```

### Congestion Control

`sendXxx` methods queue a `WebSocketFrame` instance to the internal queue.
By default, no upper limit is imposed on the queue size, so `sendXxx`
methods do not block. However, this behavior may cause a problem if your
WebSocket client application sends too many WebSocket frames in a short
time for the WebSocket server to process. In such a case, you may want
`sendXxx` methods to block when many frames are queued.

You can set an upper limit on the internal queue by calling
`setFrameQueueSize(int)` method. As a result, if the number of frames
in the queue has reached the upper limit when a `sendXxx` method is called,
the method blocks until the queue gets spaces. The code snippet below is
an example to set 5 as the upper limit of the internal frame queue.

```java
// Set 5 as the frame queue size.
ws.setFrameQueueSize(5);
```

Note that under some conditions, even if the queue is full, `sendXxx`
methods do not block. For example, in the case where the thread to send
frames (`WritingThread`) is going to stop or has already stopped. In
addition, method calls to send a
[control frame](https://tools.ietf.org/html/rfc6455#section-5.5) (e.g.
`sendClose()` and `sendPing()`) do not block.

#### Disconnect WebSocket

Before a web socket is closed, a closing handshake is performed. A closing
handshake is started (1) when the server sends a close frame to the client
or (2) when the client sends a close frame to the server. You can start a
closing handshake by calling `disconnect()` method (or by sending a close
frame manually).

```java
// Close the web socket connection.
ws.disconnect();
```

`disconnect()` method has some variants. If you want to change the close
code and the reason phrase of the close frame that this client will send
to the server, use a variant method such as `disconnect(int, String)`.
`disconnect()` itself is an alias of
`disconnect(WebSocketCloseCode.NORMAL, null)`.

#### Reconnection

`WebSocket.connect()` method can be called at most only once regardless of
whether the method succeeded or failed. If you want to re-connect to the
WebSocket endpoint, you have to create a new `WebSocket` instance again
by calling one of `createSocket` methods of a `WebSocketFactory`. You may
find `recreate()` method useful if you want to create a new `WebSocket`
instance that has the same settings as the original instance. Note that,
however, settings you made on the raw socket of the original `WebSocket`
instance are not copied.

```java
// Create a new WebSocket instance and connect to the same endpoint.
ws = ws.recreate().connect();
```

There is a variant of `recreate()` method that takes a timeout value for
socket connection. If you want to use a timeout value that is different
from the one used when the existing `WebSocket` instance was created,
use `recreate(int timeout)` method.

Note that you should not trigger reconnection in `onError()` method because
`onError()` may be called multiple times due to one error. Instead,
`onDisconnected()` is the right place to trigger reconnection.

#### Error Handling

`WebSocketListener` has some `onXxxError()` methods such as `onFrameError()`
and `onSendError()`. Among such methods, `onError()` is a special one. It
is always called before any other `onXxxError()` is called. For example,
in the implementation of `run()` method of `ReadingThread`, `Throwable` is
caught and `onError()` and `onUnexpectedError()` are called in this order.
The following is the implementation.

```java
@Override
public void run()
{
    try
    {
        main();
    }
    catch (Throwable t)
    {
        // An uncaught throwable was detected in the reading thread.
        WebSocketException cause = new WebSocketException(
            WebSocketError.UNEXPECTED_ERROR_IN_READING_THREAD,
            "An uncaught throwable was detected in the reading thread", t);

        // Notify the listeners.
        ListenerManager manager = mWebSocket.getListenerManager();
        manager.callOnError(cause);
        manager.callOnUnexpectedError(cause);
    }
}
```

So, you can handle all error cases in `onError()` method. However, note that
`onError()` may be called multiple times for one error cause, so don't try to
trigger reconnection in `onError()`. Instead, `onDisconnected()` is the right
place to trigger reconnection.

All `onXxxError()` methods receive a `WebSocketException` instance as the
second argument (the first argument is a `WebSocket` instance). The exception
class provides `getError()` method which returns a `WebSocketError` enum entry.
Entries in `WebSocketError` enum are possible causes of errors that may occur
in the implementation of this library. The error causes are so granular that
they can make it easy for you to find the root cause when an error occurs.

`Throwable`s thrown by implementations of `onXxx()` callback methods are
passed to `handleCallbackError()` of `WebSocketListener`.

```java
public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception {
    // Throwables thrown by onXxx() callback methods come here.
}
```

Sample Application
------------------

The following is a sample application that connects to the echo server on
[websocket.org](https://www.websocket.org) (`ws://echo.websocket.org`) and
repeats to (1) read a line from the standard input, (2) send the read line
to the server and (3) prints the response from the server, until `exit` is
entered. The source code can be downloaded from [Gist]
(https://gist.github.com/TakahikoKawasaki/e79d36bf91bf9508ddd2).

```java
import java.io.*;
import com.neovisionaries.ws.client.*;

public class EchoClient
{
    /**
     * The echo server on websocket.org.
     */
    private static final String SERVER = "ws://echo.websocket.org";

    /**
     * The timeout value in milliseconds for socket connection.
     */
    private static final int TIMEOUT = 5000;

    /**
     * The entry point of this command line application.
     */
    public static void main(String[] args) throws Exception
    {
        // Connect to the echo server.
        WebSocket ws = connect();

        // The standard input via BufferedReader.
        BufferedReader in = getInput();

        // A text read from the standard input.
        String text;

        // Read lines until "exit" is entered.
        while ((text = in.readLine()) != null)
        {
            // If the input string is "exit".
            if (text.equals("exit"))
            {
                // Finish this application.
                break;
            }

            // Send the text to the server.
            ws.sendText(text);
        }

        // Close the web socket.
        ws.disconnect();
    }

    /**
     * Connect to the server.
     */
    private static WebSocket connect() throws IOException, WebSocketException
    {
        return new WebSocketFactory()
            .setConnectionTimeout(TIMEOUT)
            .createSocket(SERVER)
            .addListener(new WebSocketAdapter() {
                // A text message arrived from the server.
                public void onTextMessage(WebSocket websocket, String message) {
                    System.out.println(message);
                }
            })
            .addExtension(WebSocketExtension.PERMESSAGE_DEFLATE)
            .connect();
    }

    /**
     * Wrap the standard input with BufferedReader.
     */
    private static BufferedReader getInput() throws IOException
    {
        return new BufferedReader(new InputStreamReader(System.in));
    }
}
```

Limitations
-----------

* According to the specification ([RFC 6455](https://tools.ietf.org/html/rfc6455)),
  the maximum length of the payload part of a frame is (2^63 - 1), but this
  library cannot treat frames whose payload length is greater than (2^31 - 1).

* HTTP response codes other than "101 Switching Protocols" from a WebSocket
  endpoint are not supported. Note that this means redirection (3xx) is not
  supported.

* Currently, by default, `permessage-deflate` extension is not enabled.

* As for [RFC 7692](http://tools.ietf.org/html/rfc7692). The current implementation
  does not support context takeover on the client side. Also, if the agreed size of
  the sliding window on the client side is less than the maximum size allowed by the
  specification (32,768) (this happens when a WebSocket server returns
  `client_max_window_bits` parameter with a value that is less than 15), outgoing
  frames are not compressed when the payload size before compression is bigger than
  the agreed sliding window size.

See Also
--------

- [RFC 6455](http://tools.ietf.org/html/rfc6455) The WebSocket Protocol
- [RFC 7692](http://tools.ietf.org/html/rfc7692) Compression Extensions for WebSocket

Author
------

[Authlete, Inc.](https://www.authlete.com/) & Neo Visionaries Inc.

Takahiko Kawasaki <taka@authlete.com>


text:
<?php
/**
 * A helper class to allow easy programmatic construction of TinyQ expressions.
 * @author InterExperts Webontwikkeling <webontwikkeling@interexperts.nl>
 */

namespace InterExperts\TinyQ;

/**
 * A helper class to allow easy programmatic construction of TinyQ expressions.
 * @method Builder and() Add the TinyQ equivalent of the "AND" operator to the expression.
 * @method Builder or() Add the TinyQ equivalent of the "OR" operator to the expression.
 */
class Builder{
	/**
	 * Query string currently being created.
	 * @var string $queryString
	 */
	protected $queryString = '';

	const GREATER                       = ".g";
	const GREATER_OR_EQUAL              = ".h";
	const LESS                          = ".l";
	const LESS_OR_EQUAL                 = ".m";
	const NOT_EQUAL                     = ".n";
	const NOT                           = ".t";
	const _AND                          = ".a";
	const _OR                           = ".o";
	const LIKE                          = ".k";
	const LPAREN                        = ".s";
	const RPAREN                        = ".f";
	const EQUAL                         = ".e";
	const ESCAPE_DOT                    = "..";
	const ESCAPE_LIKE_WILDCARD_ONE      = "_";
	const ESCAPE_LIKE_WILDCARD_MULTIPLE = "-";
	const LIKE_WILDCARD_ONE             = "._";
	const LIKE_WILDCARD_MULTIPLE        = ".-";

	/**
	 * Construct an instance.
	 * @example examples/basic.php 5 Example of creating a Buildquery
	 */
	public function __construct(){}

	/**
	 * Escape key and value query parts.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @param string $operator TinyQ operator
	 * @return string
	 */
	protected function createEscapedString($key, $value, $operator){
		return $this->escape($key) . $operator . $this->escape($value);
	}

	/**
	 * Add the TinyQ equivalent of the ">" operator to the expression.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @return Builder
	 */
	public function greater($key, $value){
		$this->queryString .= $this->createEscapedString($key, $value, self::GREATER);
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "<=" operator to the expression.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @return Builder
	 */
	public function greaterOrEqual($key, $value){
		$this->queryString .= $this->createEscapedString($key, $value, self::GREATER_OR_EQUAL);
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "<" operator to the expression.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @return Builder
	 */
	public function less($key, $value){
		$this->queryString .= $this->createEscapedString($key, $value, self::LESS);
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "<=" operator to the expression.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @return Builder
	 */
	public function lessOrEqual($key, $value){
		$this->queryString .= $this->createEscapedString($key, $value, self::LESS_OR_EQUAL);
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "!=" operator to the expression.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @return Builder
	 */
	public function notEqual($key, $value){
		$this->queryString .= $this->createEscapedString($key, $value, self::NOT_EQUAL);
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "NOT" operator to the expression.
	 * @return Builder
	 */
	public function not(){
		$this->queryString .= self::NOT;
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "AND" operator to the expression. Method for reserved `and` keyword.
	 * @return Builder
	 */
	protected function _and(){
		$this->queryString .= self::_AND;
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "OR" operator to the expression. Method for reserved `or` keyword.
	 * @return Builder
	 */
	protected function _or(){
		$this->queryString .= self::_OR;
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "LIKE" operator to the expression.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @return Builder
	 */
	public function like($key, $value){
		$this->queryString .= $this->createEscapedString($key, $value, self::LIKE);
		return $this;
	}

	/**
	 * Append the equivalent of a left parenthesis (the left grouping operator);
	 * @return Builder
	 */
	public function lparen(){
		$this->queryString .= self::LPAREN;
		return $this;
	}

	/**
	 * Append the equivalent of a right parenthesis (the right grouping operator);
	 * @return Builder
	 */
	public function rparen(){
		$this->queryString .= self::RPAREN;
		return $this;
	}

	/**
	 * Add the TinyQ equivalent of the "==" operator to the expression.
	 * @param string $key Property to search
	 * @param mixed $value Searchterm
	 * @return Builder
	 */
	public function equal($key, $value){
		$this->queryString .= $this->createEscapedString($key, $value, self::EQUAL);
		return $this;
	}

	/**
	 * Reset the instance so another expression can be built.
	 * @return Builder
	 */
	public function reset(){
		$this->queryString = '';
		return $this;
	}

	/**
	 * Return the TinyQ language expression.
	 * @return string
	 */
	public function build(){
		return $this->queryString;
	}

	/**
	 * Overloading to be able to use `and`, `or` methods.
	 * @ignore
	 * @param string $method Magic method to call
	 * @param mixed[] $args Arguments to pass to the magic method
	 */
	public function __call($method, $args){
		if($method == 'and'){
			return call_user_func_array(array($this,"_and"), $args);
		}elseif($method == 'or'){
			return call_user_func_array(array($this,"_or"), $args);
		}else{
			throw new \BadMethodCallException("Method {$method} doesn't exists");
		}
	}

	/**
	 * Escape the query paramaters.
	 * @param string $string String to be escaped
	 * @return string
	 */
	protected function escape($string){
		$string = str_replace('.', self::ESCAPE_DOT, $string);
		$string = str_replace('.' . self::LIKE_WILDCARD_MULTIPLE, self::LIKE_WILDCARD_MULTIPLE, $string);
		$string = str_replace('.' . self::LIKE_WILDCARD_ONE, self::LIKE_WILDCARD_ONE, $string);
		return $string;
	}

	/**
	 * Escape queries to be used in LIKE statements.
	 * @param string $string String to be escaped
	 * @return string
	 */
	public function escapeLike($string){
		$string = str_replace(self::ESCAPE_LIKE_WILDCARD_MULTIPLE, self::LIKE_WILDCARD_MULTIPLE, $string);
		$string = str_replace(self::ESCAPE_LIKE_WILDCARD_ONE, self::LIKE_WILDCARD_ONE, $string);
		return $string;
	}

}


text:
package org.elasticsearch.indices.analysis;

import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.elasticsearch.Version;
import org.elasticsearch.index.analysis.TokenFilterFactory;
import org.elasticsearch.indices.analysis.PreBuiltCacheFactory.CachingStrategy;

public enum PreBuiltTokenizers {

    STANDARD(CachingStrategy.ONE) {
        @Override
        protected Tokenizer create(Version version) {
            return new StandardTokenizer();
        }
    }

    ;

    protected abstract  Tokenizer create(Version version);

    protected TokenFilterFactory getMultiTermComponent(Version version) {
        return null;
    }

    private final CachingStrategy cachingStrategy;

    PreBuiltTokenizers(CachingStrategy cachingStrategy) {
        this.cachingStrategy = cachingStrategy;
    }

    public CachingStrategy getCachingStrategy() {
        return cachingStrategy;
    }
}


text:
using System.Collections.Generic;

namespace DelimitedStringParser
{
    public interface IObjectMetadataReader<T>
    {
        bool IsVersionedData { get; }

        /// <summary>
        /// The delimiter character separating each field.
        /// </summary>
        char Delimiter { get; }

        /// <summary>
        /// The quote character wrapping every field.
        /// If this is null, the field is not wrapped.
        /// </summary>
        char? Quote { get; }

        /// <summary>
        /// The escape character letting insert quotation characters inside a quoted field.
        /// If this is null, the quote character will be used.
        /// If the quote character is also null, the fields are not escaped (field value can not contains delimiter).
        /// </summary>
        char? Escape { get; }

        IEnumerable<FieldMetadata> FieldList { get; }
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

### 1500 Posts, DevDay and Storing a Dictionary

I returned safe and sound to Europe from Autodesk University 2016 in Las Vegas and recuperated from jetlag over the weekend.

Today I discuss upcoming events, new simple samples to embed a Forge viewer in a web page or blog post, and strategies to embed a dictionary into the Revit database:

- [DevDay Europe in Munich](#2)
- [AEC Symposium in New York](#3)
- [Embedding a Forge viewer](#4)
- [Storing a dictionary – use `DataStorage`, not `ProjectInfo`](#5)

####DevDay Europe in Munich

Autodesk University ended, and all went well,
including [the classes I presented](http://thebuildingcoder.typepad.com/blog/2016/10/au-revit-20171-and-rex-freezedrawing.html#2) and
the [DevDay conference](http://thebuildingcoder.typepad.com/blog/2016/11/devday-conference-at-autodesk-university.html) held
the day before AU proper started:

- [AEC breakout](http://thebuildingcoder.typepad.com/blog/2016/11/devday-conference-at-autodesk-university.html#3)
    - [Revit API news, roadmap and idea station](http://thebuildingcoder.typepad.com/blog/2016/11/devday-conference-at-autodesk-university.html#4)
    - [BIM 360](http://thebuildingcoder.typepad.com/blog/2016/11/devday-conference-at-autodesk-university.html#5)
    - [InfraWorks 360 and Civil 3D](http://thebuildingcoder.typepad.com/blog/2016/11/devday-conference-at-autodesk-university.html#6)

The next DevDay conference is coming up fast, the one and only European one this year, followed by four days of joint hacking, research and learning, in Munich, Germany:

- DevDay conference – December 5, 2016
- DevLab and Forge Accelerator – December 6-9, 2016

Read all about the annual, worldwide Developer Day Conferences and Accelerator workshops
at [autodeskdevdays.com](http://autodeskdevdays.com).

Registration is easy and open for all.

Simply visit the [event website](http://autodeskdevdays.com) and click on
the [Register button](http://autodeskdevdays.com/register).

That is the next thing for me to prepare for now.

####AEC Symposium in New York

If you are unable to attend the European DevDay in Munich, you may be interested in visiting New York instead.

[CORE Studio at Thornton Tomasetti](http://core.thorntontomasetti.com) is hosting
the [AEC Technology Symposium and Hackathon 2016](http://core.thorntontomasetti.com/event/aec-technology-symposium-and-hackathon-2016) there
on Thursday December 8.

Workshops Include:

- **Dynamo: Mandrill** – Konrad Sobon and Leland Jobson of Grimshaw hosting a workshop to learn how to use Dynamo to tap into Revit and extract data (information about families, warnings etc.) from it and a data visualization plug-in called Mandrill to generate charts and graphs, advanced list management techniques, formatting data to create  visualizations, tell stories and combine them into a report page that can be printed and linked into your software (InDesign, Illustrator, Word etc.)
- **An introduction to Computational Fluid Dynamics with Butterfly** – Mostapha Sadeghipour Roudsari presents a workshop introducing Butterfly, the newest addition to the insect community of Ladybug + Honeybee. Butterfly enables setting up and running advanced Computational Fluid Dynamics (CFD) simulations inside Grasshopper using the validated open source engine OpenFOAM. Grasshopper is used for hands-on exercises and similar examples and workflows are shown with DynamoBIM.
- **Dynamo Dev Zero-touch to NodeModel** – Robert Cervellione presents a workshop focused on setting up the development environment to create nodes in Dynamo using C# in Visual Studio. Start simple with zero-touch nodes,  introduce the Dynamo API and how to access geometry under the hood, dive into package creation for local hosting and package manager publishing, and dive deeper into WPF and custom node UI creation to access the full power of .NET and create fully custom nodes.

Please refer to
the [AEC Technology Symposium and Hackathon 2016](http://core.thorntontomasetti.com/event/aec-technology-symposium-and-hackathon-2016) for
all further details.

####Embedding a Forge Viewer

I repeatedly mentioned
the recent [BIM and Forge workshop at TuDa](http://thebuildingcoder.typepad.com/blog/2016/11/bimtuda-devdays-forge-news-and-more-events.html).

Our hosts at the uni there implemented a web page to share the agenda, [www.bim.tu-darmstadt.de](http://www.bim.tu-darmstadt.de).

After the single day workshop on Friday, they continued exploring Forge over the weekend and updated the web site to display the university building in an embedded Forge viewer over the weekend.

You can check it out yourself and view source to see the single line of code to add the `iframe` tag hosting the embedded A360 viewer.

Another take on this is provided by the
TrueVis [A360 embedder WordPress plugin](http://truevis.com/a360-embedder-wordpress-plugin) and
accompanying [A360 embedder examples](http://truevis.com/a360-embedder-examples).

Using those, you can completely automate the viewer embedding in a WordPress blog post.

And now, back to the Revit API.

####Storing a Dictionary – Use `DataStorage`, not `ProjectInfo`

I had an interesting discussion with my colleagues Simon Jones, Miroslav Schonauer and Scott Conover on storing a dictionary in the Revit database – note that the AutoCAD ObjectARX environment provides support for so-called named dictionaries:

**Question:** Is there a way of defining named dictionary storage for data in a Revit project?

The only option I can find is to use Extensible Storage on an arbitrary element placed in the model – but is there a way that avoids the requirement for an inserted element (and the risk that someone deletes it)?

**Answer 1:** Yes.

Officially, extensible storage is the only way... if you place it onto the `ProjectInformation` instance, that is equivalent of per-doc data as `ProjectInformation` is GUARANTEED to be a singleton in RVT.

I personally use a mechanism that I devised a few releases before extensible storage had been introduced – serialising a class into binary stream, encoding it via `String64` and then storing into an invisible string parameter. I found it much quicker to design my custom data-class than fiddling with extensible storage definitions…

But in either case, the `ProjectInfo` element is the way to get per-doc data…

**Answer 2:** No!

Sorry, but please stop using the `ProjectInfo` class in that manner immediately.

I used to recommend that earlier as well, and have stopped since learning better last year.

This is extremely important due to issues with worksharing.

Scott Conover explains that very explicitly in his AU class on [add-ins that cooperate with worksharing](http://thebuildingcoder.typepad.com/blog/2014/10/worksharing-and-duplicating-element-geometry.html#2).

At the same time as the introduction of extensible storage, the `DataStorage` element was introduced.

That is a new Revit database element class whose sole purpose is to host extensible storage data.

You can create as many of these as you like, and tag them in any way you like in order to make your one and only or several of them with all the associated element-specific or projectwide data easily accessible.

The Building Coder defines a dedicated topic group on [extensible storage](http://thebuildingcoder.typepad.com/blog/about-the-author.html#5.23).

One of its entries actually points to a discussion quite similar to what you are asking for,
[named GUID storage for project identification](http://thebuildingcoder.typepad.com/blog/2016/04/named-guid-storage-for-project-identification.html).
All you would need to do to adapt it to your requirements would be to replace the GUID that is stores by a suitable dictionary.

Here is some more on
the [DataStorage element hosting extensible storage in a worksharing environment](http://thebuildingcoder.typepad.com/blog/2015/02/extensible-storage-in-a-worksharing-environment.html).

**Answer 3:** If worksharing is involved, I agree   :-)   most of the tools we are involved with would have many serious issues with worksharing, i.e., they are by-design used only for a central-model style workflow.

In any case, if starting from scratch, I agree that `DataStorage` should be used!

**Answer 4:** If you are certain that Worksharing will not be involved, there's not much difference between using `ProjectInfo` and `DataStorage`, except that using `DataStorage` provides better encapsulation from another add-in accidentally deleting your data from `ProjectInfo` when it accesses its own.

If Worksharing is to be involved, you should definitely avoid using the `ProjectInfo` instance.

Please refer to [The Building Coder topic group on extensible storage](http://thebuildingcoder.typepad.com/blog/about-the-author.html#5.23) for more information on it in all its aspects.


text:
namespace Macabresoft.Macabre2D.Framework;

/// <summary>
/// An asset which contains a <see cref="IScene" />.
/// </summary>
public class SceneAsset : Asset<Scene> {
    /// <summary>
    /// The file extension for a serialized <see cref="Scene" />.
    /// </summary>
    public const string FileExtension = ".m2dscene";

    /// <inheritdoc />
    public override bool IncludeFileExtensionInContentPath => true;
}


text:
import { Quad } from 'rdf-js';

declare function quad(quad: Quad): string;

export = quad;


text:
"""
$URL: svn+ssh://svn/repos/trunk/durus/test/utest_history.py $
$Id: utest_history.py 28338 2006-05-04 21:45:03Z dbinger $
"""
from schevo.store.connection import Connection
from schevo.store.file_storage import FileStorage2
from schevo.store.history import HistoryConnection
from schevo.store.persistent import PersistentTester as Persistent
from schevo.test import raises

import os
import tempfile

class TestHistory(object):

    def test_a(self):
        filename = tempfile.mktemp()
        s = FileStorage2(filename)
        connection = Connection(s)
        root = connection.get_root()
        root['a'] = Persistent()
        root['a'].b = 1
        connection.commit()
        root['a'].b = 2
        connection.commit()
        s.close()
        hc = HistoryConnection(filename)
        a = hc.get_root()['a']
        assert len(hc.get_storage().index.history) == 4
        assert a.b == 2
        hc.previous()
        assert a.b == 1
        hc.next()
        assert a.b == 2
        hc.previous()
        assert a.b == 1
        hc.previous()
        assert a._p_is_ghost()
        assert not hasattr(a, '__dict__')
        assert isinstance(a, Persistent)
        assert raises(KeyError, getattr, a, 'b')
        assert hc.get(a._p_oid) is a
        hc.next()
        assert a.b == 1
        hc.get_storage().fp.close()
        os.unlink(filename)

    def test_b(self):
        filename = tempfile.mktemp()
        s = FileStorage2(filename)
        connection = Connection(s)
        root = connection.get_root()
        root['a'] = Persistent()
        root['a'].b = 1
        connection.commit()
        root['b'] = Persistent()
        connection.commit()
        root['b'].a = root['a']
        root['a'].b = 2
        connection.commit()
        root['a'].b = 3
        connection.commit()
        s.close()
        hc = HistoryConnection(filename)
        a = hc.get_root()['a']
        assert len(hc.get_storage().index.history) == 6
        hc.previous_instance(a)
        assert a.b == 2
        hc.previous_instance(a)
        assert a.b == 1
        hc.previous_instance(a)
        assert not hasattr(a, '__dict__')
        assert hc.get_root().keys() == []
        hc.get_storage().fp.close()
        os.unlink(filename)


text:
<?php

namespace SofaChamps\Bundle\CoreBundle\Request\ParamConverter;

use Doctrine\ORM\EntityManager;
use JMS\DiExtraBundle\Annotation as DI;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use SofaChamps\Bundle\CoreBundle\Entity\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * UserParamConverter
 *
 * @DI\Service("sofachamps.param_converter.user")
 * @DI\Tag("request.param_converter", attributes={"priority"=1})
 */
class UserParamConverter implements ParamConverterInterface
{
    protected $em;

    /**
     * @DI\InjectParams({
     *      "em" = @DI\Inject("doctrine.orm.default_entity_manager")
     * })
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function apply(Request $request, ConfigurationInterface $configuration)
    {
        $options = $configuration->getOptions();
        $param = array_key_exists('id', $options) ? $options['id'] : 'userId';
        $userId = $request->attributes->get($param);

        $user = $this->em->getRepository('SofaChampsCoreBundle:User')->find($userId);
        if (!$user) {
            throw new NotFoundHttpException(sprintf('User with id: %s could not be found', $userId));
        }

        $request->attributes->set($configuration->getName(), $user);
    }

    public function supports(ConfigurationInterface $configuration)
    {
        return in_array($configuration->getClass(), array('SofaChamps\Bundle\CoreBundle\Entity\User', ''));
    }
}


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

package com.google.testing.testify.risk.frontend.client.view.widgets;

import com.google.gwt.user.client.ui.RootPanel;
import com.google.testing.testify.risk.frontend.client.TaClientTest;
import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent;
import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent.DialogResult;
import com.google.testing.testify.risk.frontend.client.event.DialogClosedHandler;

import junit.framework.Assert;

/**
 * Unit tests for the StandardDialogBox widget.
 *
 * @author chrsmith@google.com (Chris Smith)
 */
public class StandardDialogBoxTest extends TaClientTest {

  /**
   * Test implementation of the DialogClosedHandler.
   */
  public class TestDialogClosedHandler implements DialogClosedHandler {

    private DialogResult result = null;

    public void reset() {
      result = null;
    }

    public DialogResult getDialogResult() {
      return result;
    }

    @Override
    public void onDialogClosed(DialogClosedEvent event) {
      result = event.getResult();
    }
  }

  public void testOK() {
    TestDialogClosedHandler handlerTest = new TestDialogClosedHandler();
    StandardDialogBox widget = new StandardDialogBox();

    RootPanel.get().clear();
    RootPanel.get().add(widget);
    widget.addDialogClosedHandler(handlerTest);

    widget.okButton.click();
    Assert.assertEquals(DialogResult.OK, handlerTest.getDialogResult());

    RootPanel.get().clear();
  }

  public void testCancel() {
    TestDialogClosedHandler handlerTest = new TestDialogClosedHandler();
    StandardDialogBox widget = new StandardDialogBox();

    RootPanel.get().clear();
    RootPanel.get().add(widget);
    widget.addDialogClosedHandler(handlerTest);

    widget.cancelButton.click();
    Assert.assertEquals(DialogResult.Cancel, handlerTest.getDialogResult());

    RootPanel.get().clear();
  }
}


text:
def find_project(service, project_name)
  # TODO: subclass GithubProject , BitbucketProject , etc. (:host becomes :type)
  project = Project.where(host: service, full_name: project_name).first
  project or raise "Project '#{project_name.inspect}' not found"
end


text:
package uk.ac.sussex.gdsc.analytics;

import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

@SuppressWarnings("javadoc")
class SessionTest {
  @Test
  void testReset() {
    final Session session = new Session();
    Assertions.assertTrue(session.refresh());
    Assertions.assertFalse(session.refresh());
    session.reset();
    Assertions.assertTrue(session.refresh());
  }

  @SuppressWarnings("unused")
  @Test
  void testTimeout() {
    Assertions.assertThrows(IllegalArgumentException.class, () -> {
      new Session(-1);
    });
    Assertions.assertThrows(IllegalArgumentException.class, () -> {
      new Session().setTimeout(-1);
    });

    final UniformRandomProvider rg = RandomSource.create(RandomSource.SPLIT_MIX_64);
    for (int i = 0; i < 5; i++) {
      final long timeout = rg.nextLong(1000000L);
      final Session session = new Session(timeout);
      Assertions.assertEquals(0, session.getTimeStamp());
      Assertions.assertEquals(timeout, session.getTimeout());
      session.refresh();
      Assertions.assertFalse(0L == session.getTimeStamp(), "Timestamp has not changed");
    }

    // 0 millisecond timeout
    final Session session = new Session(Session.ALWAYS_TIMEOUT);
    Assertions.assertFalse(session.hasExpired());
    Assertions.assertTrue(session.refresh());
    Assertions.assertTrue(session.hasExpired());
    Assertions.assertTrue(session.refresh());
    Assertions.assertTrue(session.hasExpired());
    Assertions.assertTrue(session.refresh());
    Assertions.assertTrue(session.hasExpired());

    // Never timeout. This should work on the same session
    // session = new Session(Session.NEVER_TIMEOUT);
    session.setTimeout(Session.NEVER_TIMEOUT);
    Assertions.assertEquals(Long.MAX_VALUE, session.getTimeout());
    Assertions.assertFalse(session.hasExpired());
    Assertions.assertFalse(session.refresh());
    Assertions.assertFalse(session.hasExpired());
    Assertions.assertFalse(session.refresh());
    session.reset();
    Assertions.assertTrue(session.refresh());
    Assertions.assertFalse(session.hasExpired());
    Assertions.assertFalse(session.refresh());
    Assertions.assertFalse(session.hasExpired());
    Assertions.assertFalse(session.refresh());
  }
}


text:
<?php

namespace Wedeto\DB\Query;

use PHPUnit\Framework\TestCase;

require_once "ProvideMockDb.php";
use Wedeto\DB\MockDB;

class ConstantArrayTest extends TestCase
{
    public function testConstruct()
    {
        $a = new ConstantArray([]);

        $expected = [];
        $actual = $a->getValue();
        $this->assertEquals($expected, $actual);

        $a = new ConstantArray(1, 2, 3, 4, 5);
        $expected = [1, 2, 3, 4, 5];
        $actual = $a->getValue();
        $this->assertEquals($expected, $actual);

        $a = new ConstantArray([1, 2, 3, 4, 5]);
        $expected = [1, 2, 3, 4, 5];
        $actual = $a->getValue();
        $this->assertEquals($expected, $actual);

        $a = new ConstantArray([1, 2, 3, 4, 5], [6, 7, 8, 9]);
        $expected = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        $actual = $a->getValue();
        $this->assertEquals($expected, $actual);
    }

    public function testInvalidValue()
    {
        $a = new ConstantArray([]);
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Cannot assign non-array");

        $a->setValue(null);
    }

    public function testInvalidValues()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessagE("Not a scalar");
        $a = new ConstantArray(new \StdClass, new \StdClass);
    }

    public function testArrayWithAutoUpdate()
    {
        $func = function ($value) { return implode('-', $value); };

        $mock = $this->prophesize(Parameters::class);
        $params = $mock->reveal();

        $a = new ConstantArray([]);
        $mock->set('fookey', '', \PDO::PARAM_STR)->shouldBeCalled();
        $a->bind($params, 'fookey', $func);

        $mock->set('fookey', '1-2-3-4', \PDO::PARAM_STR)->shouldBeCalled();
        $a->setValue([1, 2, 3, 4]);
    }

    public function testToSQL()
    {
        $db = new MockDB();
        $drv = $db->getDriver();
        $params = new Parameters($drv);

        $val = new ConstantArray([1, 3, 5, 7]);
        $sql = $val->toSQL($params, false);
        $this->assertEquals(':c0', $sql);
        $this->assertEquals('{1,3,5,7}', $params->get('c0'));

        $val = new ConstantArray([1, "foo", 5, 7]);
        $sql = $val->toSQL($params, false);
        $this->assertEquals(':c1', $sql);
        $this->assertEquals('{1,"foo",5,7}', $params->get('c1'));

        $val = new ConstantArray([1, 'fo""o', 5, 7]);
        $sql = $val->toSQL($params, false);
        $this->assertEquals(':c2', $sql);
        $this->assertEquals('{1,"fo\\"\\"o",5,7}', $params->get('c2'));

        // Repetition should give the same results
        $sql = $val->toSQL($params, false);
        $this->assertEquals(':c2', $sql);
        $this->assertEquals('{1,"fo\\"\\"o",5,7}', $params->get('c2'));

        // New parameters should reset
        $params = new Parameters($drv);
        $sql = $val->toSQL($params, false);
        $this->assertEquals(':c0', $sql);
        $this->assertEquals('{1,"fo\\"\\"o",5,7}', $params->get('c0'));
    }
}


text:
"""

Revision ID: 0311_add_inbound_sms_history
Revises: 0310_returned_letters_table
Create Date: 2019-12-20 15:38:53.358509

"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision = "0311_add_inbound_sms_history"
down_revision = "0310_returned_letters_table"

def upgrade():
    op.create_table(
        "inbound_sms_history",
        sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("service_id", postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column("notify_number", sa.String(), nullable=False),
        sa.Column("provider_date", sa.DateTime(), nullable=True),
        sa.Column("provider_reference", sa.String(), nullable=True),
        sa.Column("provider", sa.String(), nullable=False),
        sa.ForeignKeyConstraint(
            ["service_id"],
            ["services.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_inbound_sms_history_service_id"), "inbound_sms_history", ["service_id"], unique=False)

def downgrade():
    op.drop_index(op.f("ix_inbound_sms_history_service_id"), table_name="inbound_sms_history")
    op.drop_table("inbound_sms_history")


text:
require "rails_helper"

RSpec.describe WordsController, type: :routing do
  describe "routing" do
    it "routes to #index" do
      expect(:get => "/word_lists/:word_list_id/words").to route_to("words#index", :word_list_id => ":word_list_id")
    end

    it "routes to #new" do
      expect(:get => "/word_lists/:word_list_id/words/new").to route_to("words#new", :word_list_id => ":word_list_id")
    end

    it "routes to #create" do
      expect(:post => "/word_lists/:word_list_id/words").to route_to("words#create", :word_list_id => ":word_list_id")
    end

    it "routes to #destroy" do
      expect(:delete => "/word_lists/:word_list_id/words/1").to route_to("words#destroy", :word_list_id => ":word_list_id", :id => "1")
    end
  end
end


text:
use libfuzzer_sys::fuzz_target;
use textwrap::{Options, WrapAlgorithm};

fuzz_target!(|input: (String, usize)| {
    if input.0.len() > 100_000 {
        return; // Avoid timeouts in OSS-Fuzz.
    }

    let options = Options::new(input.1).wrap_algorithm(WrapAlgorithm::new_optimal_fit());
    let _ = textwrap::fill(&input.0, &options);
});


text:
import {Injectable} from '@angular/core'
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { environment } from '../../../../environments/environment';
import { ApiHelper } from '../../../shared';
import { StageDetailsDTO } from '../../../model/models';

@Injectable()
export class StagedetailsService {

    constructor(
        private apihelper: ApiHelper,
        private http: Http
    ) { }

    public save(dto: StageDetailsDTO): Observable<boolean> {
        let url = `${environment.api}stage`;
        let body = JSON.stringify(dto);
        return this.http.put(url, dto, this.apihelper.JsonOptions())
            .map(this.apihelper.extractJson)
            .catch(this.apihelper.handleError);
    }

}