text:
import {looseIdentical, stringify} from '../../util';
import {isJsObject} from '../change_detection_util';
import {ChangeDetectorRef} from '../change_detector_ref';

import {KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDifferFactory} from './keyvalue_differs';

export class DefaultKeyValueDifferFactory<K, V> implements KeyValueDifferFactory {
  constructor() {}
  supports(obj: any): boolean { return obj instanceof Map || isJsObject(obj); }

  create<K, V>(): DefaultKeyValueDiffer<K, V>;

  /**
   * @deprecated v4.0.0 - ChangeDetectorRef is not used and is no longer a parameter
   */
  create<K, V>(cd?: ChangeDetectorRef): KeyValueDiffer<K, V> {
    return new DefaultKeyValueDiffer<K, V>();
  }
}

export class DefaultKeyValueDiffer<K, V> implements KeyValueDiffer<K, V>, KeyValueChanges<K, V> {
  private _records: Map<K, V> = new Map<K, V>();
  private _mapHead: KeyValueChangeRecord_<K, V> = null;
  private _previousMapHead: KeyValueChangeRecord_<K, V> = null;
  private _changesHead: KeyValueChangeRecord_<K, V> = null;
  private _changesTail: KeyValueChangeRecord_<K, V> = null;
  private _additionsHead: KeyValueChangeRecord_<K, V> = null;
  private _additionsTail: KeyValueChangeRecord_<K, V> = null;
  private _removalsHead: KeyValueChangeRecord_<K, V> = null;
  private _removalsTail: KeyValueChangeRecord_<K, V> = null;

  get isDirty(): boolean {
    return this._additionsHead !== null || this._changesHead !== null ||
        this._removalsHead !== null;
  }

  forEachItem(fn: (r: KeyValueChangeRecord<K, V>) => void) {
    let record: KeyValueChangeRecord_<K, V>;
    for (record = this._mapHead; record !== null; record = record._next) {
      fn(record);
    }
  }

  forEachPreviousItem(fn: (r: KeyValueChangeRecord<K, V>) => void) {
    let record: KeyValueChangeRecord_<K, V>;
    for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
      fn(record);
    }
  }

  forEachChangedItem(fn: (r: KeyValueChangeRecord<K, V>) => void) {
    let record: KeyValueChangeRecord_<K, V>;
    for (record = this._changesHead; record !== null; record = record._nextChanged) {
      fn(record);
    }
  }

  forEachAddedItem(fn: (r: KeyValueChangeRecord<K, V>) => void) {
    let record: KeyValueChangeRecord_<K, V>;
    for (record = this._additionsHead; record !== null; record = record._nextAdded) {
      fn(record);
    }
  }

  forEachRemovedItem(fn: (r: KeyValueChangeRecord<K, V>) => void) {
    let record: KeyValueChangeRecord_<K, V>;
    for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
      fn(record);
    }
  }

  diff(map: Map<any, any>|{[k: string]: any}): any {
    if (!map) {
      map = new Map();
    } else if (!(map instanceof Map || isJsObject(map))) {
      throw new Error(`Error trying to diff '${map}'`);
    }

    return this.check(map) ? this : null;
  }

  onDestroy() {}

  check(map: Map<any, any>|{[k: string]: any}): boolean {
    this._reset();
    const records = this._records;
    let oldSeqRecord: KeyValueChangeRecord_<K, V> = this._mapHead;
    let lastOldSeqRecord: KeyValueChangeRecord_<K, V> = null;
    let lastNewSeqRecord: KeyValueChangeRecord_<K, V> = null;
    let seqChanged: boolean = false;

    this._forEach(map, (value: any, key: any) => {
      let newSeqRecord: any;
      if (oldSeqRecord && key === oldSeqRecord.key) {
        newSeqRecord = oldSeqRecord;
        this._maybeAddToChanges(newSeqRecord, value);
      } else {
        seqChanged = true;
        if (oldSeqRecord !== null) {
          this._removeFromSeq(lastOldSeqRecord, oldSeqRecord);
          this._addToRemovals(oldSeqRecord);
        }
        if (records.has(key)) {
          newSeqRecord = records.get(key);
          this._maybeAddToChanges(newSeqRecord, value);
        } else {
          newSeqRecord = new KeyValueChangeRecord_<K, V>(key);
          records.set(key, newSeqRecord);
          newSeqRecord.currentValue = value;
          this._addToAdditions(newSeqRecord);
        }
      }

      if (seqChanged) {
        if (this._isInRemovals(newSeqRecord)) {
          this._removeFromRemovals(newSeqRecord);
        }
        if (lastNewSeqRecord == null) {
          this._mapHead = newSeqRecord;
        } else {
          lastNewSeqRecord._next = newSeqRecord;
        }
      }
      lastOldSeqRecord = oldSeqRecord;
      lastNewSeqRecord = newSeqRecord;
      oldSeqRecord = oldSeqRecord && oldSeqRecord._next;
    });
    this._truncate(lastOldSeqRecord, oldSeqRecord);
    return this.isDirty;
  }

  /** @internal */
  _reset() {
    if (this.isDirty) {
      let record: KeyValueChangeRecord_<K, V>;
      // Record the state of the mapping
      for (record = this._previousMapHead = this._mapHead; record !== null; record = record._next) {
        record._nextPrevious = record._next;
      }

      for (record = this._changesHead; record !== null; record = record._nextChanged) {
        record.previousValue = record.currentValue;
      }

      for (record = this._additionsHead; record != null; record = record._nextAdded) {
        record.previousValue = record.currentValue;
      }

      this._changesHead = this._changesTail = null;
      this._additionsHead = this._additionsTail = null;
      this._removalsHead = this._removalsTail = null;
    }
  }

  private _truncate(lastRecord: KeyValueChangeRecord_<K, V>, record: KeyValueChangeRecord_<K, V>) {
    while (record !== null) {
      if (lastRecord === null) {
        this._mapHead = null;
      } else {
        lastRecord._next = null;
      }
      const nextRecord = record._next;
      this._addToRemovals(record);
      lastRecord = record;
      record = nextRecord;
    }

    for (let rec: KeyValueChangeRecord_<K, V> = this._removalsHead; rec !== null;
         rec = rec._nextRemoved) {
      rec.previousValue = rec.currentValue;
      rec.currentValue = null;
      this._records.delete(rec.key);
    }
  }

  private _maybeAddToChanges(record: KeyValueChangeRecord_<K, V>, newValue: any): void {
    if (!looseIdentical(newValue, record.currentValue)) {
      record.previousValue = record.currentValue;
      record.currentValue = newValue;
      this._addToChanges(record);
    }
  }

  private _isInRemovals(record: KeyValueChangeRecord_<K, V>) {
    return record === this._removalsHead || record._nextRemoved !== null ||
        record._prevRemoved !== null;
  }

  private _addToRemovals(record: KeyValueChangeRecord_<K, V>) {
    if (this._removalsHead === null) {
      this._removalsHead = this._removalsTail = record;
    } else {
      this._removalsTail._nextRemoved = record;
      record._prevRemoved = this._removalsTail;
      this._removalsTail = record;
    }
  }

  private _removeFromSeq(prev: KeyValueChangeRecord_<K, V>, record: KeyValueChangeRecord_<K, V>) {
    const next = record._next;
    if (prev === null) {
      this._mapHead = next;
    } else {
      prev._next = next;
    }
    record._next = null;
  }

  private _removeFromRemovals(record: KeyValueChangeRecord_<K, V>) {
    const prev = record._prevRemoved;
    const next = record._nextRemoved;
    if (prev === null) {
      this._removalsHead = next;
    } else {
      prev._nextRemoved = next;
    }
    if (next === null) {
      this._removalsTail = prev;
    } else {
      next._prevRemoved = prev;
    }
    record._prevRemoved = record._nextRemoved = null;
  }

  private _addToAdditions(record: KeyValueChangeRecord_<K, V>) {
    if (this._additionsHead === null) {
      this._additionsHead = this._additionsTail = record;
    } else {
      this._additionsTail._nextAdded = record;
      this._additionsTail = record;
    }
  }

  private _addToChanges(record: KeyValueChangeRecord_<K, V>) {
    if (this._changesHead === null) {
      this._changesHead = this._changesTail = record;
    } else {
      this._changesTail._nextChanged = record;
      this._changesTail = record;
    }
  }

  toString(): string {
    const items: any[] = [];
    const previous: any[] = [];
    const changes: any[] = [];
    const additions: any[] = [];
    const removals: any[] = [];
    let record: KeyValueChangeRecord_<K, V>;

    for (record = this._mapHead; record !== null; record = record._next) {
      items.push(stringify(record));
    }
    for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
      previous.push(stringify(record));
    }
    for (record = this._changesHead; record !== null; record = record._nextChanged) {
      changes.push(stringify(record));
    }
    for (record = this._additionsHead; record !== null; record = record._nextAdded) {
      additions.push(stringify(record));
    }
    for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
      removals.push(stringify(record));
    }

    return 'map: ' + items.join(', ') + '\n' +
        'previous: ' + previous.join(', ') + '\n' +
        'additions: ' + additions.join(', ') + '\n' +
        'changes: ' + changes.join(', ') + '\n' +
        'removals: ' + removals.join(', ') + '\n';
  }

  /** @internal */
  private _forEach<K, V>(obj: Map<K, V>|{[k: string]: V}, fn: (v: V, k: any) => void) {
    if (obj instanceof Map) {
      obj.forEach(fn);
    } else {
      Object.keys(obj).forEach(k => fn(obj[k], k));
    }
  }
}

/**
 * @stable
 */
class KeyValueChangeRecord_<K, V> implements KeyValueChangeRecord<K, V> {
  previousValue: V = null;
  currentValue: V = null;

  /** @internal */
  _nextPrevious: KeyValueChangeRecord_<K, V> = null;
  /** @internal */
  _next: KeyValueChangeRecord_<K, V> = null;
  /** @internal */
  _nextAdded: KeyValueChangeRecord_<K, V> = null;
  /** @internal */
  _nextRemoved: KeyValueChangeRecord_<K, V> = null;
  /** @internal */
  _prevRemoved: KeyValueChangeRecord_<K, V> = null;
  /** @internal */
  _nextChanged: KeyValueChangeRecord_<K, V> = null;

  constructor(public key: K) {}

  toString(): string {
    return looseIdentical(this.previousValue, this.currentValue) ?
        stringify(this.key) :
        (stringify(this.key) + '[' + stringify(this.previousValue) + '->' +
         stringify(this.currentValue) + ']');
  }
}


text:
package com.llb.app;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class MyHttpClient{
	private static HttpClient httpClient=null;//整个App共享这一个
//	@Override
//	public void onCreate() {//在Activity Service等创建之前就执行了
//		super.onCreate();
//		httpClient=MyApp.createHttpClient();
//	}
	/**
	 * 创建HttpClient实例,主要是设置http client的各项连接参数和连接管理器
	 * @return 返回一个线程安全的HttpClient实例
	 */
	private static HttpClient createHttpClient() {
		HttpParams params=new BasicHttpParams();
		//设置http连接的基本参数
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);//协议版本号
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);//设置编码方式
		//向服务器发送数据的时候,需要先向服务器发起一个请求看服务器是否愿意接受客户端将要发送的数据
		HttpProtocolParams.setUseExpectContinue(params, true);//这个参数的设置要小心点
		HttpProtocolParams.setUserAgent(params,"Mozilla/5.0 (Linux;U;Android 2.2.1;en-us;Nexus One Build/FRG83)"+
		" AppleWebKit/533.1(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1" );

		ConnManagerParams.setTimeout(params, 2000);//从连接池中取连接的超时时间
		int connectionTimeOut = 4000;//连接超时时间
//		if (!HttpUtils.isWifiDataEnable(context)) {
//			connectionTimeOut = 10000;
//		}
		HttpConnectionParams.setConnectionTimeout(params, connectionTimeOut);
		HttpConnectionParams.setSoTimeout(params, 5000);//设置Socket请求超时

		SchemeRegistry sRegistry=new SchemeRegistry();//设置HttpClient支持HTTP和HTTPS两种模式
		sRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		sRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		ThreadSafeClientConnManager threadSafeCCM=new ThreadSafeClientConnManager(params, sRegistry);
		return new DefaultHttpClient(threadSafeCCM, params);
	}
	/**
	 * 对外提供获取httpclient实例的方法
	 * @return
	 */
	public static HttpClient getHttpClient() {
		if(null==httpClient){
			httpClient=createHttpClient();
		}
		return httpClient;
	}
	/**
	 * 通过post方式请求数据
	 * @param url 请求接口地址
	 * @param pairs NameValuePair数据
	 * @return String格式的请求结果
	 */
	public static String postByHttpClient(String url,NameValuePair...pairs){
		//封装需要post的数据
		List<NameValuePair> nameParams=new ArrayList<NameValuePair>();
		for(NameValuePair np:pairs){//保存传递进来的各项参数
			nameParams.add(np);
		}

//		JSONObject json = new JSONObject();
//        Object email = null;
//        json.put("email", email);
//        Object pwd = null;
//        json.put("password", pwd);
//        StringEntity se = new StringEntity( "JSON: " + json.toString());
//        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
//        post.setEntity(se);

		UrlEncodedFormEntity entity=null;
		try {
			entity = new UrlEncodedFormEntity(nameParams, HTTP.UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Log.i("zgr","数据封装编码出错了");
			return null;
		}
		//创建post请求
		HttpPost postRequest=new HttpPost(url);
		postRequest.setEntity(entity);
		//发送post请求
		HttpClient hClient=getHttpClient();
		HttpResponse response=null;
		try {
			response=hClient.execute(postRequest);
		}catch(IOException e) {
			e.printStackTrace();
			return null;
		}
		//检查请求状态码
		if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
			throw new RuntimeException("请求数据失败!");
		}
		//检查并返回请求的数据
		HttpEntity responseEntity=response.getEntity();
		try {
			return (null==responseEntity) ? null:EntityUtils.toString(responseEntity);//, HTTP.UTF_8);
		} catch (ParseException e) {
			e.printStackTrace();
			Log.i("zgr","数据转换失败");
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("zgr","数据转换失败");
			return null;
		}
	}
	/**
	 * 通过get方式请求网络数据
	 * @param url 请求地址
	 * @param pairs 请求需要的各个参数
	 * @return HttpEntity 请求结果数据
	 */
	public static HttpEntity getByHttpClient(String url,NameValuePair...pairs)throws IOException,ClientProtocolException{
		StringBuilder sBuilder=new StringBuilder();
		sBuilder.append(url);
		if(null!=pairs && pairs.length>0){
			sBuilder.append("?");
			for(int i=0;i<pairs.length;i++){
				if(i>0){
					sBuilder.append("&");
				}
				sBuilder.append(String.format("%s=%s",pairs[i].getName(),pairs[i].getValue()));//拼参数
			}
		}
		String path=sBuilder.toString();
		Log.i("llb",path);
		HttpGet getRequest=new HttpGet(path);
//		try {//getHttpClient() new DefaultHttpClient()
			HttpResponse response=getHttpClient().execute(getRequest);
			if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){//检查状态码
				throw new RuntimeException("数据请求失败");
			}
			HttpEntity resEntity=response.getEntity();//获得传回来的信息
			return resEntity;
//			sBuilder=null;
//			sBuilder=new StringBuilder();//干脆重新声明一个变量
////			sBuilder.delete(0, sBuilder.length());//清空之前的变量
//
//			BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(resEntity.getContent()));
//			String s=null;
//			while((s=bufferedReader.readLine())!=null){
//				sBuilder.append(s);//逐行读取数据
//				s=null;//清空
//			}
//
//			Log.i("zgr","resEntity="+sBuilder.toString());
////			return (null==resEntity)? null :resEntity.toString();//返回数据
//			return sBuilder.toString();
//		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
name: AUTODNSSEC_OFF
---

AUTODNSSEC_OFF tells the provider to disable AutoDNSSEC. It takes no
parameters.

See `AUTODNSSEC_ON` for further details.


text:
<html>
<head>
    <script src="../node_modules/babel-polyfill/dist/polyfill.js"></script>
    <script src="../node_modules/d3/build/d3.js"></script>
    <script src="../../d3fc-extent/build/d3fc-extent.js"></script>
    <script src="../../d3fc-random-data/build/d3fc-random-data.js"></script>
    <script src="../../d3fc-shape/build/d3fc-shape.js"></script>
    <script src="../../d3fc-data-join/build/d3fc-data-join.js"></script>
    <script src="../../d3fc-rebind/build/d3fc-rebind.js"></script>
    <script src="../build/d3fc-series.js"></script>
</head>
<body>
    <svg id="bar-svg" width="500" height="250"></svg>
    <canvas id="bar-canvas"  width="500" height="250"></canvas>
    <script src="autoBandwidth.js"></script>
</body>
</html>


text:
/**
 * \file nvcuvid.h
 *   NvCuvid API provides Video Decoding interface to NVIDIA GPU devices.
 * \date 2015-2015
 *  This file contains the interface constants, structure definitions and function prototypes.
 */

#if !defined(__NVCUVID_H__)
#define __NVCUVID_H__

#include "dynlink_cuviddec.h"

#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus */

/*********************************
** Initialization
*********************************/
CUresult  CUDAAPI cuvidInit(unsigned int Flags);

////////////////////////////////////////////////////////////////////////////////////////////////
//
// High-level helper APIs for video sources
//

typedef void *CUvideosource;
typedef void *CUvideoparser;
typedef long long CUvideotimestamp;

/**
 * \addtogroup VIDEO_PARSER Video Parser
 * @{
 */

/*!
 * \enum cudaVideoState
 * Video Source State
 */
typedef enum {
    cudaVideoState_Error   = -1,    /**< Error state (invalid source)  */
    cudaVideoState_Stopped = 0,     /**< Source is stopped (or reached end-of-stream)  */
    cudaVideoState_Started = 1      /**< Source is running and delivering data  */
} cudaVideoState;

/*!
 * \enum cudaAudioCodec
 * Audio compression
 */
typedef enum {
    cudaAudioCodec_MPEG1=0,         /**< MPEG-1 Audio  */
    cudaAudioCodec_MPEG2,           /**< MPEG-2 Audio  */
    cudaAudioCodec_MP3,             /**< MPEG-1 Layer III Audio  */
    cudaAudioCodec_AC3,             /**< Dolby Digital (AC3) Audio  */
    cudaAudioCodec_LPCM             /**< PCM Audio  */
} cudaAudioCodec;

/*!
 * \struct CUVIDEOFORMAT
 * Video format
 */
typedef struct
{
    cudaVideoCodec codec;                   /**< Compression format  */
   /**
    * frame rate = numerator / denominator (for example: 30000/1001)
    */
    struct {
        unsigned int numerator;             /**< frame rate numerator   (0 = unspecified or variable frame rate) */
        unsigned int denominator;           /**< frame rate denominator (0 = unspecified or variable frame rate) */
    } frame_rate;
    unsigned char progressive_sequence;     /**< 0=interlaced, 1=progressive */
    unsigned char bit_depth_luma_minus8;    /**< high bit depth Luma */
    unsigned char bit_depth_chroma_minus8;  /**< high bit depth Chroma */
    unsigned char reserved1;                /**< Reserved for future use */
    unsigned int coded_width;               /**< coded frame width */
    unsigned int coded_height;              /**< coded frame height  */
   /**
    *   area of the frame that should be displayed
    * typical example:
    *   coded_width = 1920, coded_height = 1088
    *   display_area = { 0,0,1920,1080 }
    */
    struct {
        int left;                           /**< left position of display rect  */
        int top;                            /**< top position of display rect  */
        int right;                          /**< right position of display rect  */
        int bottom;                         /**< bottom position of display rect  */
    } display_area;
    cudaVideoChromaFormat chroma_format;    /**<  Chroma format */
    unsigned int bitrate;                   /**< video bitrate (bps, 0=unknown) */
   /**
    * Display Aspect Ratio = x:y (4:3, 16:9, etc)
    */
    struct {
        int x;
        int y;
    } display_aspect_ratio;
    /**
    * Video Signal Description
    */
    struct {
        unsigned char video_format          : 3;
        unsigned char video_full_range_flag : 1;
        unsigned char reserved_zero_bits    : 4;
        unsigned char color_primaries;
        unsigned char transfer_characteristics;
        unsigned char matrix_coefficients;
    } video_signal_description;
    unsigned int seqhdr_data_length;          /**< Additional bytes following (CUVIDEOFORMATEX)  */
} CUVIDEOFORMAT;

/*!
 * \struct CUVIDEOFORMATEX
 * Video format including raw sequence header information
 */
typedef struct
{
    CUVIDEOFORMAT format;
    unsigned char raw_seqhdr_data[1024];
} CUVIDEOFORMATEX;

/*!
 * \struct CUAUDIOFORMAT
 * Audio Formats
 */
typedef struct
{
    cudaAudioCodec codec;       /**< Compression format  */
    unsigned int channels;      /**< number of audio channels */
    unsigned int samplespersec; /**< sampling frequency */
    unsigned int bitrate;       /**< For uncompressed, can also be used to determine bits per sample */
    unsigned int reserved1;     /**< Reserved for future use */
    unsigned int reserved2;     /**< Reserved for future use */
} CUAUDIOFORMAT;

/*!
 * \enum CUvideopacketflags
 * Data packet flags
 */
typedef enum {
    CUVID_PKT_ENDOFSTREAM   = 0x01,   /**< Set when this is the last packet for this stream  */
    CUVID_PKT_TIMESTAMP     = 0x02,   /**< Timestamp is valid  */
    CUVID_PKT_DISCONTINUITY = 0x04    /**< Set when a discontinuity has to be signalled  */
} CUvideopacketflags;

/*!
 * \struct CUVIDSOURCEDATAPACKET
 * Data Packet
 */
typedef struct _CUVIDSOURCEDATAPACKET
{
    unsigned long flags;            /**< Combination of CUVID_PKT_XXX flags */
    unsigned long payload_size;     /**< number of bytes in the payload (may be zero if EOS flag is set) */
    const unsigned char *payload;   /**< Pointer to packet payload data (may be NULL if EOS flag is set) */
    CUvideotimestamp timestamp;     /**< Presentation timestamp (10MHz clock), only valid if CUVID_PKT_TIMESTAMP flag is set */
} CUVIDSOURCEDATAPACKET;

// Callback for packet delivery
typedef int (CUDAAPI *PFNVIDSOURCECALLBACK)(void *, CUVIDSOURCEDATAPACKET *);

/*!
 * \struct CUVIDSOURCEPARAMS
 * Source Params
 */
typedef struct _CUVIDSOURCEPARAMS
{
    unsigned int ulClockRate;                   /**< Timestamp units in Hz (0=default=10000000Hz)  */
    unsigned int uReserved1[7];                 /**< Reserved for future use - set to zero  */
    void *pUserData;                            /**< Parameter passed in to the data handlers  */
    PFNVIDSOURCECALLBACK pfnVideoDataHandler;   /**< Called to deliver audio packets  */
    PFNVIDSOURCECALLBACK pfnAudioDataHandler;   /**< Called to deliver video packets  */
    void *pvReserved2[8];                       /**< Reserved for future use - set to NULL */
} CUVIDSOURCEPARAMS;

/*!
 * \enum CUvideosourceformat_flags
 * CUvideosourceformat_flags
 */
typedef enum {
    CUVID_FMT_EXTFORMATINFO = 0x100             /**< Return extended format structure (CUVIDEOFORMATEX) */
} CUvideosourceformat_flags;

#if !defined(__APPLE__)
/**
 * \fn CUresult CUDAAPI cuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams)
 * Create Video Source
 */
typedef CUresult CUDAAPI tcuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams);

/**
 * \fn CUresult CUDAAPI cuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams)
 * Create Video Source
 */
typedef CUresult CUDAAPI tcuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams);

/**
 * \fn CUresult CUDAAPI cuvidDestroyVideoSource(CUvideosource obj)
 * Destroy Video Source
 */
typedef CUresult CUDAAPI tcuvidDestroyVideoSource(CUvideosource obj);

/**
 * \fn CUresult CUDAAPI cuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state)
 * Set Video Source state
 */
typedef CUresult CUDAAPI tcuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state);

/**
 * \fn cudaVideoState CUDAAPI cuvidGetVideoSourceState(CUvideosource obj)
 * Get Video Source state
 */
typedef cudaVideoState CUDAAPI tcuvidGetVideoSourceState(CUvideosource obj);

/**
 * \fn CUresult CUDAAPI cuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags)
 * Get Video Source Format
 */
typedef CUresult CUDAAPI tcuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags);

/**
 * \fn CUresult CUDAAPI cuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags)
 * Set Video Source state
 */
typedef CUresult CUDAAPI tcuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags);

#endif

/**
 * \struct CUVIDPARSERDISPINFO
 */
typedef struct _CUVIDPARSERDISPINFO
{
    int picture_index;         /**<                 */
    int progressive_frame;     /**<                 */
    int top_field_first;       /**<                 */
    int repeat_first_field;    /**< Number of additional fields (1=ivtc, 2=frame doubling, 4=frame tripling, -1=unpaired field)  */
    CUvideotimestamp timestamp; /**<     */
} CUVIDPARSERDISPINFO;

//
// Parser callbacks
// The parser will call these synchronously from within cuvidParseVideoData(), whenever a picture is ready to
// be decoded and/or displayed.
//
typedef int (CUDAAPI *PFNVIDSEQUENCECALLBACK)(void *, CUVIDEOFORMAT *);
typedef int (CUDAAPI *PFNVIDDECODECALLBACK)(void *, CUVIDPICPARAMS *);
typedef int (CUDAAPI *PFNVIDDISPLAYCALLBACK)(void *, CUVIDPARSERDISPINFO *);

/**
 * \struct CUVIDPARSERPARAMS
 */
typedef struct _CUVIDPARSERPARAMS
{
    cudaVideoCodec CodecType;               /**< cudaVideoCodec_XXX  */
    unsigned int ulMaxNumDecodeSurfaces;    /**< Max # of decode surfaces (parser will cycle through these) */
    unsigned int ulClockRate;               /**< Timestamp units in Hz (0=default=10000000Hz) */
    unsigned int ulErrorThreshold;          /**< % Error threshold (0-100) for calling pfnDecodePicture (100=always call pfnDecodePicture even if picture bitstream is fully corrupted) */
    unsigned int ulMaxDisplayDelay;         /**< Max display queue delay (improves pipelining of decode with display) - 0=no delay (recommended values: 2..4) */
    unsigned int uReserved1[5];             /**< Reserved for future use - set to 0 */
    void *pUserData;                        /**< User data for callbacks */
    PFNVIDSEQUENCECALLBACK pfnSequenceCallback; /**< Called before decoding frames and/or whenever there is a format change */
    PFNVIDDECODECALLBACK pfnDecodePicture;      /**< Called when a picture is ready to be decoded (decode order) */
    PFNVIDDISPLAYCALLBACK pfnDisplayPicture;    /**< Called whenever a picture is ready to be displayed (display order)  */
    void *pvReserved2[7];                       /**< Reserved for future use - set to NULL */
    CUVIDEOFORMATEX *pExtVideoInfo;             /**< [Optional] sequence header data from system layer */
} CUVIDPARSERPARAMS;

/**
 * \fn CUresult CUDAAPI cuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams)
 */
typedef CUresult CUDAAPI tcuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams);

/**
 * \fn CUresult CUDAAPI cuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket)
 */
typedef CUresult CUDAAPI tcuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket);

/**
 * \fn CUresult CUDAAPI cuvidDestroyVideoParser(CUvideoparser obj)
 */
typedef CUresult CUDAAPI tcuvidDestroyVideoParser(CUvideoparser obj);

extern tcuvidCreateVideoSource               *cuvidCreateVideoSource;
extern tcuvidCreateVideoSourceW              *cuvidCreateVideoSourceW;
extern tcuvidDestroyVideoSource              *cuvidDestroyVideoSource;
extern tcuvidSetVideoSourceState             *cuvidSetVideoSourceState;
extern tcuvidGetVideoSourceState             *cuvidGetVideoSourceState;
extern tcuvidGetSourceVideoFormat            *cuvidGetSourceVideoFormat;
extern tcuvidGetSourceAudioFormat            *cuvidGetSourceAudioFormat;

extern tcuvidCreateVideoParser               *cuvidCreateVideoParser;
extern tcuvidParseVideoData                  *cuvidParseVideoData;
extern tcuvidDestroyVideoParser              *cuvidDestroyVideoParser;

/** @} */  /* END VIDEO_PARSER */
////////////////////////////////////////////////////////////////////////////////////////////////

#if defined(__cplusplus)
}
#endif /* __cplusplus */

#endif // __NVCUVID_H__


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

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
MutableTreeNode (Java Platform SE 6)
</TITLE>

<META NAME="date" CONTENT="2007-03-19">

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

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

javax.swing.tree

接口 MutableTreeNode

所有超级接口:
TreeNode

所有已知实现类:
DefaultMutableTreeNode, JTree.DynamicUtilTreeNode

public interface MutableTreeNode
extends TreeNode

定义针对树节点对象的要求,这些树节点可以通过以下操作更改:添加或移除子节点,或更改该节点中存储的用户对象的内容。

另请参见:
DefaultMutableTreeNode,
JTree

方法摘要

 void
insert(MutableTreeNode child,
       int index)

          将 child 添加到 index 位置的接收者。

 void
remove(int index)

          从接收者移除 index 位置的子节点。

 void
remove(MutableTreeNode node)

          从接收者移除 node。

 void
removeFromParent()

          从其父对象移除接收者。

 void
setParent(MutableTreeNode newParent)

          将接收者的父对象设置为 newParent。

 void
setUserObject(Object object)

          将接收者的用户对象重新设置为 object。

从接口 javax.swing.tree.TreeNode 继承的方法

children, getAllowsChildren, getChildAt, getChildCount, getIndex, getParent, isLeaf

方法详细信息

insert

void insert(MutableTreeNode child,
            int index)

将 child 添加到 index 位置的接收者。child 通过 setParent 接收消息。

remove

void remove(int index)

从接收者移除 index 位置的子节点。

remove

void remove(MutableTreeNode node)

从接收者移除 node。对 node 发送 setParent 消息。

setUserObject

void setUserObject(Object object)

将接收者的用户对象重新设置为 object。

removeFromParent

void removeFromParent()

从其父对象移除接收者。

setParent

void setParent(MutableTreeNode newParent)

将接收者的父对象设置为 newParent。

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

提交错误或意见
有关更多的 API 参考资料和开发人员文档,请参阅 Java SE 开发人员文档。该文档包含更详细的、面向开发人员的描述,以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 2007 Sun Microsystems, Inc. 保留所有权利。 请遵守许可证条款。另请参阅文档重新分发政策。


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Vendor'
        db.create_table(u'entry_vendor', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('account_number', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True)),
            ('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['entry.EntryCategory'])),
        ))
        db.send_create_signal(u'entry', ['Vendor'])

        # Adding model 'Bill'
        db.create_table(u'entry_bill', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('created_by_user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('created_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('due_date', self.gf('django.db.models.fields.DateField')()),
            ('amount', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=2)),
            ('reference_number', self.gf('django.db.models.fields.CharField')(max_length=40, null=True, blank=True)),
            ('vendor', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['entry.Vendor'])),
        ))
        db.send_create_signal(u'entry', ['Bill'])

    def backwards(self, orm):
        # Deleting model 'Vendor'
        db.delete_table(u'entry_vendor')

        # Deleting model 'Bill'
        db.delete_table(u'entry_bill')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'entry.bill': {
            'Meta': {'object_name': 'Bill'},
            'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),
            'created_by_user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
            'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'due_date': ('django.db.models.fields.DateField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'reference_number': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}),
            'vendor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['entry.Vendor']"})
        },
        u'entry.entry': {
            'Meta': {'ordering': "['incurred_date']", 'unique_together': "(['incurred_date', 'name'],)", 'object_name': 'Entry'},
            'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),
            'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['entry.EntryCategory']"}),
            'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
            'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'incurred_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'recurrance_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['entry.RecurranceType']", 'null': 'True', 'blank': 'True'}),
            'recurring': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'reference_number': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'})
        },
        u'entry.entrycategory': {
            'Meta': {'object_name': 'EntryCategory'},
            'debit_credit': ('django.db.models.fields.IntegerField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
        },
        u'entry.recurrancetype': {
            'Meta': {'object_name': 'RecurranceType'},
            'day_of_month': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
            'quantity': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'unit_of_measure': ('django.db.models.fields.IntegerField', [], {})
        },
        u'entry.vendor': {
            'Meta': {'object_name': 'Vendor'},
            'account_number': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['entry.EntryCategory']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        }
    }

    complete_apps = ['entry']


text:
package almhirt.i18n

import scalaz.Validation.FlatMap._
import almhirt.common._
import almhirt.almvalidation.kit._
import org.scalatest._
import com.ibm.icu.util.ULocale
import MeasuredImplicits._

class ResourcesAndKeysTests extends FunSuite with Matchers {
  //val resourcesWithFallbackAllowed = AlmResources.fromXmlInResources("localization", "test", getClass.getClassLoader, true).forceResult
  val resourcesWithoutFallback =
    try {
      AlmResources.fromXmlInResources("localization", "test", getClass.getClassLoader, true, false, true).forceResult
    } catch {
      case exn: ResultForcedFromValidationException ⇒
        info(exn.problem.toString)
        AlmResources.empty
      case scala.util.control.NonFatal(exn) ⇒
        throw exn
    }

  val key1 = ResourceKey("section_1", "group_1", "key_1")
  val key2 = ResourceKey("section_1", "group_1", "key_2")
  val group = ResourceGroup("section_1", "group_1")

  test("""render 'de-AT' which is a plain string""") {
    resourcesWithoutFallback.getFormatter(key1, new ULocale("de-AT")).flatMap(_.format()) should equal(scalaz.Success("de_AT"))
  }

  test("""render a key with a nonformatted value(integer: 2)""") {
    resourcesWithoutFallback.getFormatter(key2, new ULocale("en")).flatMap(_.formatValues(2)) should equal(scalaz.Success("en: 2"))
  }

  test("""render the length measured value 1.0m in "en".""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("length"), "en")
    info(formatable.forceFormat("length" -> 1.0))
  }

  test("""render the length measured value 100000.0m in "en".""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("length"), "en")
    info(formatable.forceFormat("length" -> 100000.0))
  }

  test("""render the length measured value 100000.0m in "en" with anglo american units.""") {
    val formatable = resourcesWithoutFallback.getMeasureFormatter(group.withKey("length"), "en").forceResult
    info(formatable.formatMeasure(100000.0.meter, Some(UnitsOfMeasurementSystem.US)).forceResult)
  }

  test("""render the length measured value 1.0m in "de".""") {
    val formatable = resourcesWithoutFallback.getMeasureFormatter(group.withKey("length"), "de").forceResult
    info(formatable.forceFormat("length" -> 1.0))
  }

  test("""render the length measured value 1000.0m in "de".""") {
    val formatable = resourcesWithoutFallback.getMeasureFormatter(group.withKey("length"), "de").forceResult
    info(formatable.forceFormat("length" -> 1000.0))
  }

  test("""render the length measured value 1000.0m in "de" with anglo american units.""") {
    val formatable = resourcesWithoutFallback.getMeasureFormatter(group.withKey("length"), "de").forceResult
    info(formatable.formatMeasure(1000.0.meter, Some(UnitsOfMeasurementSystem.US)).forceResult)
  }

  test("""render the length measured range 1000.0m - 2km in "de" with anglo american units.""") {
    val formatable = resourcesWithoutFallback.getMeasureFormatter(group.withKey("length"), "de").forceResult
    info(formatable.formatMeasureRange(1000.0.meter, 2.0.kilometer, Some(UnitsOfMeasurementSystem.US)).forceResult)
  }

  test("""render a number without a style in en.""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("number"), "en")
    info(formatable.forceFormatValues(12345.67))
  }

  test("""render a number explicitly without a style in en.""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("number-nostyle"), "en")
    info(formatable.forceFormatValues(12345.67))
  }

  test("""render a number with style integer in en.""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("number-integer"), "en")
    info(formatable.forceFormatValues(12345.67))
  }

  test("""render a number with style scientific in en.""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("number-scientific"), "en")
    info(formatable.forceFormatValues(12345.67))
  }

  test("""render a number with style percentage in en.""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("number-percentage"), "en")
    info(formatable.forceFormatValues(12345.67))
  }

  test("""render the boolean in en when true.""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("yesno"), "en")
    formatable.forceFormatValues(true) should equal("Yes!")
  }

  test("""render the boolean in en when false.""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("yesno"), "en")
    formatable.forceFormatValues(false) should equal("No!")
  }

  test("""render the boolean in en via the lookups extension methods.""") {
    import ResourceLookup.UnsafeFormattingImplicits._
    resourcesWithoutFallback.forceFormatValues(group.withKey("yesno"), "en", true) should equal("Yes!")
  }

  test("""select an existing text(alternative a).""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("select"), "en")
    info(formatable.forceFormatValues("a"))
  }

  test("""select an existing text(alternative b).""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("select"), "en")
    info(formatable.forceFormatValues("b"))
  }

  test("""select an existing text(non existing).""") {
    val formatable = resourcesWithoutFallback.forceFormatter(group.withKey("select"), "en")
    info(formatable.forceFormatValues("c"))
  }
}


text:
package io.enmasse.controller.standard;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.enmasse.address.model.Address;
import io.enmasse.address.model.AddressSpecForwarder;
import io.enmasse.address.model.AddressStatusForwarder;
import io.enmasse.address.model.BrokerStatus;

class RouterStatus {
    private static final Logger log = LoggerFactory.getLogger(RouterStatus.class);

    private final String routerId;
    private final List<String> addresses;
    private final List<List<String>> autoLinks;
    private final List<List<String>> linkRoutes;
    private final List<String> connections;
    private final List<List<String>> links;

    RouterStatus(String routerId, List<String> addresses, List<List<String>> autoLinks, List<List<String>> linkRoutes, List<String> connections, List<List<String>> links) {
        this.routerId = routerId;
        this.addresses = addresses;
        this.autoLinks = autoLinks;
        this.linkRoutes = linkRoutes;
        this.connections = connections;
        this.links = links;
    }

    public String getRouterId() {
        return routerId;
    }

    public int checkAddress(Address address) {

        int ok = 0;
        final String addressName = address.getSpec().getAddress();

        boolean found = this.addresses.contains(addressName);
        if (!found) {
            var msg = "Address " + addressName + " not found on " + this.routerId;
            log.debug(msg);
            address.getStatus().setReady(false).appendMessage(msg);
        } else {
            ok++;
            log.debug("Address found for '{}'", addressName);
        }

        return ok;
    }

    public int checkAutoLinks(Address address, int expectedAutoLinks) {

        int ok = 0;
        final String addressName = address.getSpec().getAddress();

        for (List<String> autoLink : autoLinks) {
            String addr = autoLink.get(0);

            if (addressName.equals(addr)) {
                ok++;
            }
        }

        if (ok < expectedAutoLinks) {
            var msg = "Address " + addressName + " is missing autoLinks on " + routerId;
            log.debug(msg);
            address.getStatus().setReady(false).appendMessage(msg);
        } else {
            log.debug("Address {} has all required auto links", addressName);
        }

        return ok;
    }

    public int checkLinkRoutes(Address address) {
        int ok = 0;
        final String addressName = address.getSpec().getAddress();

        for (List<String> linkRoute : linkRoutes) {
            if (linkRoute.size() > 0) {
                String prefix = linkRoute.get(0);

                // Pooled topics have active link routes
                if (addressName.equals(prefix)) {
                    ok++;
                }
            }
        }

        if (ok < 2) {
            var msg = "Address " + addressName + " is missing linkRoutes on " + this.routerId;
            log.debug(msg);
            address.getStatus().setReady(false).appendMessage(msg);
        } else {
            log.debug("Address {} has all required link routes", addressName);
        }

        return ok;
    }

    public static int checkActiveAutoLink(Address address, List<RouterStatus> routerStatusList, int expectedActiveAutoLink) {
        int ok = 0;
        final Set<String> active = new HashSet<>();
        final String addressName = address.getSpec().getAddress();

        for (RouterStatus routerStatus : routerStatusList) {

            log.debug("Router Auto Links: {}", routerStatus.autoLinks);

            for (List<String> autoLink : routerStatus.autoLinks) {
                if (autoLink.size() > 3) {
                    String addr = autoLink.get(0);
                    String dir = autoLink.get(2);
                    String operStatus = autoLink.get(3);

                    log.debug("Addr: {}, Dir: {}, operStatus: {}", addr, dir, operStatus);

                    if (addressName.equals(addr) && "active".equals(operStatus)) {
                        active.add(dir);
                        log.debug("  Match!");
                    }
                }
            }
        }

        if (active.size() < expectedActiveAutoLink) {
            var msg = "Address " + addressName + " is missing active autoLink (active in dirs: " + active + ")";
            log.debug(msg);
            address.getStatus().setReady(false).appendMessage(msg);
        } else {
            log.debug("Address {} has all required auto links: {}", addressName, active);
            ok++;
        }
        return ok;
    }

    public static int checkActiveLinkRoute(Address address, List<RouterStatus> routerStatusList) {
        int ok = 0;
        Set<String> active = new HashSet<>();
        final String addressName = address.getSpec().getAddress();

        for (RouterStatus routerStatus : routerStatusList) {

            for (List<String> linkRoute : routerStatus.linkRoutes) {
                if (linkRoute.size() > 3) {
                    String addr = linkRoute.get(0);
                    @SuppressWarnings("unused")
                    String containerId = linkRoute.get(1);
                    String dir = linkRoute.get(2);
                    String operStatus = linkRoute.get(3);

                    if (addressName.equals(addr) && "active".equals(operStatus)) {
                        active.add(dir);
                    }
                }
            }
        }

        if (active.size() < 2) {
            var msg = "Address " + addressName + " is missing active linkRoute (active in dirs: " + active + ")";
            log.debug(msg);
            address.getStatus().setReady(false).appendMessage(msg);
        } else {
            log.debug("Address {} has all required link routes: {}", addressName, active);
            ok++;
        }
        return ok;
    }

    public static int checkConnection(Address address, List<RouterStatus> routerStatusList) {
        int ok = 0;
        for (RouterStatus routerStatus : routerStatusList) {
            for (String containerId : routerStatus.connections) {
                boolean found = false;
                for (BrokerStatus brokerStatus : address.getStatus().getBrokerStatuses()) {
                    if (containerId.startsWith(brokerStatus.getClusterId())) {
                        ok++;
                        found = true;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }
        }

        final String addressName = address.getSpec().getAddress();
        if (ok == 0) {
            var msg = "Address " + addressName + " is missing connection from broker";
            log.debug(msg);
            address.getStatus().setReady(false).appendMessage(msg);
        } else {
            log.debug("Address {} has all required connections", addressName);
        }
        return ok;
    }

    public static int checkForwarderLinks(Address address, List<RouterStatus> routerStatusList) {
        if (address.getSpec().getForwarders() == null || address.getSpec().getForwarders().isEmpty()) {
            return 0;
        }

        final String addressName = address.getSpec().getAddress();

        int ok = 0;
        for (AddressSpecForwarder forwarder : address.getSpec().getForwarders()) {
            boolean found = false;
            boolean isUp = false;
            for (RouterStatus routerStatus : routerStatusList) {
                for (List<String> entry : routerStatus.links) {
                    String linkName = entry.get(0);
                    if (address.getForwarderLinkName(forwarder).equals(linkName)) {
                        found = true;
                        String operStatus = entry.get(1);

                        if ("up".equals(operStatus)) {
                            isUp = true;
                        }
                        break;
                    }
                }
            }

            final String forwarderName = forwarder.getName();
            if (!found) {
                updateForwarderStatus(addressName, forwarderName, false, "Unable to find link for forwarder '" + forwarderName + "'", address.getStatus().getForwarders());
            } else if (!isUp) {
                updateForwarderStatus(addressName, forwarderName, false, "Unable to find link in the up state for forwarder '" + forwarderName + "'", address.getStatus().getForwarders());
            } else {
                ok++;
                log.debug("Forwarder {} for address {} is ok", forwarder.getName(), address.getSpec().getAddress());
            }
        }
        return ok;
    }

    private static void updateForwarderStatus(String addressName, String forwarderName, boolean isReady, String message, List<AddressStatusForwarder> forwarderStatuses) {
        log.debug("Address: {} - {}", addressName, message);
        forwarderStatuses.stream()
                .filter(c -> c.getName().equals(forwarderName))
                .findFirst().ifPresent(s -> {
            s.setReady(isReady);
            s.appendMessage(message);
        });
    }

    @Override
    public String toString() {
        return new StringBuilder()
                .append("{routerId=").append(routerId).append(",")
                .append("addresses=").append(addresses).append(",")
                .append("autoLinks=").append(autoLinks).append(",")
                .append("linkRoutes=").append(linkRoutes).append(",")
                .append("connections=").append(connections).append(",")
                .append("links=").append(links).append("}")
                .toString();
    }
}


text:
class SearchLocation < ApplicationRecord
  # Validations
  validates :query, presence: true, uniqueness: true
  validates :latitude, presence: true
  validates :longitude, presence: true

  before_validation :normalize_query
  before_save :set_geoloc

  # Geocoding
  geocoded_by :query
  before_validation :geocode

  # Methods

  def self.normalize query
    query.strip.titleize
  end

  private

  def normalize_query
    self.query = SearchLocation.normalize(self.query) if self.query
  end

  def set_geoloc
    self.geoloc = Geolocation.new(self).to_s
  end
end


text:
using namespace llvm;

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

static cl::opt<unsigned>
TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
                 cl::value_desc("N"),
                 cl::desc("Repeat compilation N times for timing"));

static cl::opt<bool>
NoIntegratedAssembler("no-integrated-as", cl::Hidden,
                      cl::desc("Disable integrated assembler"));

// Determine optimization level.
static cl::opt<char>
OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));

static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
                              cl::desc("Do not verify input module"));

static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
                                             cl::desc("Disable simplify-libcalls"));

static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
                                    cl::desc("Show encoding in .s output"));

static cl::opt<bool> EnableDwarfDirectory(
    "enable-dwarf-directory", cl::Hidden,
    cl::desc("Use .file directives with an explicit directory."));

static cl::opt<bool> AsmVerbose("asm-verbose",
                                cl::desc("Add comments to directives."),
                                cl::init(true));

static int compileModule(char **, LLVMContext &);

static std::unique_ptr<tool_output_file>
GetOutputStream(const char *TargetName, Triple::OSType OS,
                const char *ProgName) {
  // If we don't yet have an output filename, make one.
  if (OutputFilename.empty()) {
    if (InputFilename == "-")
      OutputFilename = "-";
    else {
      // If InputFilename ends in .bc or .ll, remove it.
      StringRef IFN = InputFilename;
      if (IFN.endswith(".bc") || IFN.endswith(".ll"))
        OutputFilename = IFN.drop_back(3);
      else
        OutputFilename = IFN;

      switch (FileType) {
      case TargetMachine::CGFT_AssemblyFile:
        if (TargetName[0] == 'c') {
          if (TargetName[1] == 0)
            OutputFilename += ".cbe.c";
          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
            OutputFilename += ".cpp";
          else
            OutputFilename += ".s";
        } else
          OutputFilename += ".s";
        break;
      case TargetMachine::CGFT_ObjectFile:
        if (OS == Triple::Win32)
          OutputFilename += ".obj";
        else
          OutputFilename += ".o";
        break;
      case TargetMachine::CGFT_Null:
        OutputFilename += ".null";
        break;
      }
    }
  }

  // Decide if we need "binary" output.
  bool Binary = false;
  switch (FileType) {
  case TargetMachine::CGFT_AssemblyFile:
    break;
  case TargetMachine::CGFT_ObjectFile:
  case TargetMachine::CGFT_Null:
    Binary = true;
    break;
  }

  // Open the file.
  std::error_code EC;
  sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
  if (!Binary)
    OpenFlags |= sys::fs::F_Text;
  auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
                                                   OpenFlags);
  if (EC) {
    errs() << EC.message() << '\n';
    return nullptr;
  }

  return FDOut;
}

// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllTargetMCs();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  // Initialize codegen and IR passes used by llc so that the -print-after,
  // -print-before, and -stop-after options work.
  PassRegistry *Registry = PassRegistry::getPassRegistry();
  initializeCore(*Registry);
  initializeCodeGen(*Registry);
  initializeLoopStrengthReducePass(*Registry);
  initializeLowerIntrinsicsPass(*Registry);
  initializeUnreachableBlockElimPass(*Registry);

  // Register the target printer for --version.
  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Compile the module TimeCompilations times to give better compile time
  // metrics.
  for (unsigned I = TimeCompilations; I; --I)
    if (int RetVal = compileModule(argv, Context))
      return RetVal;
  return 0;
}

static int compileModule(char **argv, LLVMContext &Context) {
  // Load the module to be compiled...
  SMDiagnostic Err;
  std::unique_ptr<Module> M;
  Triple TheTriple;

  bool SkipModule = MCPU == "help" ||
                    (!MAttrs.empty() && MAttrs.front() == "help");

  // If user just wants to list available options, skip module loading
  if (!SkipModule) {
    M = parseIRFile(InputFilename, Err, Context);
    if (!M) {
      Err.print(argv[0], errs());
      return 1;
    }

    // Verify module immediately to catch problems before doInitialization() is
    // called on any passes.
    if (!NoVerify && verifyModule(*M, &errs())) {
      errs() << argv[0] << ": " << InputFilename
             << ": error: input module is broken!\n";
      return 1;
    }

    // If we are supposed to override the target triple, do so now.
    if (!TargetTriple.empty())
      M->setTargetTriple(Triple::normalize(TargetTriple));
    TheTriple = Triple(M->getTargetTriple());
  } else {
    TheTriple = Triple(Triple::normalize(TargetTriple));
  }

  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getDefaultTargetTriple());

  // Get the target specific parser.
  std::string Error;
  const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
                                                         Error);
  if (!TheTarget) {
    errs() << argv[0] << ": " << Error;
    return 1;
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (!MAttrs.empty() || MCPU == "native") {
    SubtargetFeatures Features;

    // If user asked for the 'native' CPU, we need to autodetect features.
    // This is necessary for x86 where the CPU might not support all the
    // features the autodetected CPU name lists in the target. For example,
    // not all Sandybridge processors support AVX.
    if (MCPU == "native") {
      StringMap<bool> HostFeatures;
      if (sys::getHostCPUFeatures(HostFeatures))
        for (auto &F : HostFeatures)
          Features.AddFeature(F.first(), F.second);
    }

    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  // If user asked for the 'native' CPU, autodetect here. If autodection fails,
  // this will set the CPU to an empty string which tells the target to
  // pick a basic default.
  if (MCPU == "native")
    MCPU = sys::getHostCPUName();

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
  Options.DisableIntegratedAS = NoIntegratedAssembler;
  Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
  Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
  Options.MCOptions.AsmVerbose = AsmVerbose;

  std::unique_ptr<TargetMachine> Target(
      TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
                                     Options, RelocModel, CMModel, OLvl));
  assert(Target && "Could not allocate target machine!");

  // If we don't have a module then just exit now. We do this down
  // here since the CPU/Feature help is underneath the target machine
  // creation.
  if (SkipModule)
    return 0;

  assert(M && "Should have exited if we didn't have a module!");

  if (GenerateSoftFloatCalls)
    FloatABIForCalls = FloatABI::Soft;

  // Figure out where we are going to send the output.
  std::unique_ptr<tool_output_file> Out =
      GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
  if (!Out) return 1;

  // Build up all of the passes that we want to do to the module.
  legacy::PassManager PM;

  // Add an appropriate TargetLibraryInfo pass for the module's triple.
  TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));

  // The -disable-simplify-libcalls flag actually disables all builtin optzns.
  if (DisableSimplifyLibCalls)
    TLII.disableAllFunctions();
  PM.add(new TargetLibraryInfoWrapperPass(TLII));

  // Add the target data from the target machine, if it exists, or the module.
  if (const DataLayout *DL = Target->getDataLayout())
    M->setDataLayout(*DL);

  if (RelaxAll.getNumOccurrences() > 0 &&
      FileType != TargetMachine::CGFT_ObjectFile)
    errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";

  {
    raw_pwrite_stream *OS = &Out->os();
    std::unique_ptr<buffer_ostream> BOS;
    if (FileType != TargetMachine::CGFT_AssemblyFile &&
        !Out->os().supportsSeeking()) {
      BOS = make_unique<buffer_ostream>(*OS);
      OS = BOS.get();
    }

    AnalysisID StartAfterID = nullptr;
    AnalysisID StopAfterID = nullptr;
    const PassRegistry *PR = PassRegistry::getPassRegistry();
    if (!StartAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StartAfter);
      if (!PI) {
        errs() << argv[0] << ": start-after pass is not registered.\n";
        return 1;
      }
      StartAfterID = PI->getTypeInfo();
    }
    if (!StopAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StopAfter);
      if (!PI) {
        errs() << argv[0] << ": stop-after pass is not registered.\n";
        return 1;
      }
      StopAfterID = PI->getTypeInfo();
    }

    // Ask the target to add backend passes as necessary.
    if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, StartAfterID,
                                    StopAfterID)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      return 1;
    }

    // Before executing passes, print the final values of the LLVM options.
    cl::PrintOptionValues();

    PM.run(*M);
  }

  // Declare success.
  Out->keep();

  return 0;
}


text:
import contextlib
import gc
import itertools
import random
import re

import pytest

from distributed.metrics import thread_time
from distributed.utils_perf import FractionalTimer, GCDiagnosis, disable_gc_diagnosis
from distributed.utils_test import captured_logger, run_for

class RandomTimer(object):
    """
    A mock timer producing random (but monotonic) values.
    """

    def __init__(self):
        self.last = 0.0
        self.timings = []
        self.durations = ([], [])
        self.i_durations = itertools.cycle((0, 1))
        self.random = random.Random(42)

    def __call__(self):
        dt = self.random.expovariate(1.0)
        self.last += dt
        self.timings.append(self.last)
        self.durations[next(self.i_durations)].append(dt)
        return self.last

def test_fractional_timer():
    N = 10

    def check_fraction(timer, ft):
        # The running fraction should be approximately equal to the
        # sum of last N "measurement" intervals over the sum of last
        # 2N intervals (not 2N - 1 or 2N + 1)
        actual = ft.running_fraction
        expected = sum(timer.durations[1][-N:]) / (
            sum(timer.durations[0][-N:] + timer.durations[1][-N:])
        )
        assert actual == pytest.approx(expected)

    timer = RandomTimer()
    ft = FractionalTimer(n_samples=N, timer=timer)
    for i in range(N):
        ft.start_timing()
        ft.stop_timing()
    assert len(timer.timings) == N * 2
    assert ft.running_fraction is None

    ft.start_timing()
    ft.stop_timing()
    assert len(timer.timings) == (N + 1) * 2
    assert ft.running_fraction is not None
    check_fraction(timer, ft)

    for i in range(N * 10):
        ft.start_timing()
        ft.stop_timing()
        check_fraction(timer, ft)

@contextlib.contextmanager
def enable_gc_diagnosis_and_log(diag, level="INFO"):
    disable_gc_diagnosis(force=True)  # just in case
    if gc.callbacks:
        print("Unexpected gc.callbacks", gc.callbacks)

    with captured_logger("distributed.utils_perf", level=level, propagate=False) as sio:
        gc.disable()
        gc.collect()  # drain any leftover from previous tests
        diag.enable()
        try:
            yield sio
        finally:
            diag.disable()
            gc.enable()

def test_gc_diagnosis_cpu_time():
    diag = GCDiagnosis(warn_over_frac=0.75)
    diag.N_SAMPLES = 3  # shorten tests

    with enable_gc_diagnosis_and_log(diag, level="WARN") as sio:
        # Spend some CPU time doing only full GCs
        for i in range(diag.N_SAMPLES):
            gc.collect()
        assert not sio.getvalue()
        gc.collect()
        lines = sio.getvalue().splitlines()
        assert len(lines) == 1
        # Between 80% and 100%
        assert re.match(
            r"full garbage collections took (100|[89][0-9])% " r"CPU time recently",
            lines[0],
        )

    with enable_gc_diagnosis_and_log(diag, level="WARN") as sio:
        # Spend half the CPU time doing full GCs
        for i in range(diag.N_SAMPLES + 1):
            t1 = thread_time()
            gc.collect()
            dt = thread_time() - t1
            run_for(dt, timer=thread_time)
        # Less than 75% so nothing printed
        assert not sio.getvalue()

@pytest.mark.xfail(reason="unknown")
def test_gc_diagnosis_rss_win():
    diag = GCDiagnosis(info_over_rss_win=10e6)

    def make_refcycle(nbytes):
        l = [b"x" * nbytes]
        l.append(l)
        return

    with enable_gc_diagnosis_and_log(diag) as sio:
        make_refcycle(100 * 1024)
        gc.collect()
        # Too small, nothing printed
        assert not sio.getvalue()

        # NOTE: need to allocate a very large value to make sure RSS
        # really shrinks (depending on the system memory allocator,
        # "small" memory deallocations may keep the memory in the pool)
        make_refcycle(200 * 1024 * 1024)
        gc.collect()
        lines = sio.getvalue().splitlines()
        assert len(lines) == 1
        # Several MB released, and at least 1 reference cycles
        assert re.match(
            r"full garbage collection released [\d\.]+ MB "
            r"from [1-9]\d* reference cycles",
            lines[0],
        )


text:
cask "browserosaurus" do
  arch = Hardware::CPU.intel? ? "x64" : "arm64"

  version "17.3.0"

  if Hardware::CPU.intel?
    sha256 "23e51064c8a0eb6745932f14f4c2ab81e8241771e9f80fd8f11bbeb863276907"
  else
    sha256 "db04b58ea91abff53bec0a266af39486ebb7483f3740572b55b4515a85d8fc90"
  end

  url "https://github.com/will-stone/browserosaurus/releases/download/v#{version}/Browserosaurus-darwin-#{arch}-#{version}.zip"
  name "Browserosaurus"
  desc "Open-source browser prompter"
  homepage "https://github.com/will-stone/browserosaurus"

  auto_updates true

  app "Browserosaurus.app"

  zap trash: [
    "~/Library/Application Support/Browserosaurus",
    "~/Library/Preferences/com.browserosaurus.plist",
  ]
end


text:
'use strict';

var defaults = require('./defaults');
var utils = require('./utils');
var dispatchRequest = require('./core/dispatchRequest');
var InterceptorManager = require('./core/InterceptorManager');

var axios = module.exports = function (config) {
  // Allow for axios('example/url'[, config]) a la fetch API
  if (typeof config === 'string') {
    config = utils.merge({
      url: arguments[0]
    }, arguments[1]);
  }

  config = utils.merge({
    method: 'get',
    headers: {},
    timeout: defaults.timeout,
    transformRequest: defaults.transformRequest,
    transformResponse: defaults.transformResponse
  }, config);

  // Don't allow overriding defaults.withCredentials
  config.withCredentials = config.withCredentials || defaults.withCredentials;

  // Hook up interceptors middleware
  var chain = [dispatchRequest, undefined];
  var promise = Promise.resolve(config);

  axios.interceptors.request.forEach(function (interceptor) {
    chain.unshift(interceptor.fulfilled, interceptor.rejected);
  });

  axios.interceptors.response.forEach(function (interceptor) {
    chain.push(interceptor.fulfilled, interceptor.rejected);
  });

  while (chain.length) {
    promise = promise.then(chain.shift(), chain.shift());
  }

  return promise;
};

// Expose defaults
axios.defaults = defaults;

// Expose all/spread
axios.all = function (promises) {
  return Promise.all(promises);
};
axios.spread = require('./helpers/spread');

// Expose interceptors
axios.interceptors = {
  request: new InterceptorManager(),
  response: new InterceptorManager()
};

// Provide aliases for supported request methods
(function () {
  function createShortMethods() {
    utils.forEach(arguments, function (method) {
      axios[method] = function (url, config) {
        return axios(utils.merge(config || {}, {
          method: method,
          url: url
        }));
      };
    });
  }

  function createShortMethodsWithData() {
    utils.forEach(arguments, function (method) {
      axios[method] = function (url, data, config) {
        return axios(utils.merge(config || {}, {
          method: method,
          url: url,
          data: data
        }));
      };
    });
  }

  createShortMethods('delete', 'get', 'head');
  createShortMethodsWithData('post', 'put', 'patch');
})();


text:
/* You can add global styles to this file, and also import other style files */

body {
    font-family: 'Open Sans', sans-serif;
}


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\Admin\ConfigurationUI
 */

/**
 * Class WPSEO_Config_Field_Success_Message
 */
class WPSEO_Config_Field_Success_Message extends WPSEO_Config_Field {

	/**
	 * WPSEO_Config_Field_Success_Message constructor.
	 */
	public function __construct() {
		parent::__construct( 'successMessage', 'FinalStep' );

		$success_message = sprintf(
			/* translators: %1$s expands to Yoast SEO. */
			__( '%1$s will now take care of all the needed technical optimization of your site. To really improve your site\'s performance in the search results, it\'s important to start creating content that ranks well for keyphrases you care about. Check out this video in which we explain how to use the %1$s metabox when you edit posts or pages.', 'wordpress-seo' ),
			'Yoast SEO'
		);

		$this->set_property( 'title', __( 'You\'ve done it!', 'wordpress-seo' ) );
		$this->set_property( 'message', $success_message );

		/* translators: %1$s expands to Yoast SEO. */
		$video_title = __( '%1$s video tutorial', 'wordpress-seo' );
		$video_args  = array(
			'url'   => WPSEO_Shortlinker::get( 'https://yoa.st/metabox-screencast' ),
			'title' => sprintf( $video_title, 'Yoast SEO' ),
		);
		$this->set_property( 'video', $video_args );
	}
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <freerdp/utils/tcp.h>
#include <freerdp/utils/sleep.h>
#include <freerdp/utils/stream.h>
#include <freerdp/utils/memory.h>
#include <freerdp/utils/hexdump.h>
#include <freerdp/errorcodes.h>

#include <time.h>
#include <errno.h>
#include <fcntl.h>

#ifndef _WIN32
#include <netdb.h>
#include <sys/socket.h>
#endif

#include "tpkt.h"
#include "fastpath.h"
#include "transport.h"

#include <freerdp/crypto/nla.h>

#define BUFFER_SIZE 16384

STREAM* transport_recv_stream_init(rdpTransport* transport, int size)
{
	STREAM* s = transport->recv_stream;
	stream_check_size(s, size);
	stream_set_pos(s, 0);
	return s;
}

STREAM* transport_send_stream_init(rdpTransport* transport, int size)
{
	STREAM* s = transport->send_stream;
	stream_check_size(s, size);
	stream_set_pos(s, 0);
	return s;
}

void transport_attach(rdpTransport* transport, int sockfd)
{
	transport->tcp->sockfd = sockfd;
}

boolean transport_disconnect(rdpTransport* transport)
{
	if (transport->layer == TRANSPORT_LAYER_TLS)
		tls_disconnect(transport->tls);

	return tcp_disconnect(transport->tcp);
}

boolean transport_connect_rdp(rdpTransport* transport)
{
	/* RDP encryption */

	return true;
}

boolean transport_connect_tls(rdpTransport* transport)
{
	if (transport->tls == NULL)
		transport->tls = tls_new(transport->settings);

	transport->layer = TRANSPORT_LAYER_TLS;
	transport->tls->sockfd = transport->tcp->sockfd;

	if (tls_connect(transport->tls) != true)
	{
		if (!connectErrorCode)
			connectErrorCode = TLSCONNECTERROR;

		tls_free(transport->tls);
		transport->tls = NULL;
		return false;
	}

	return true;
}

boolean transport_connect_nla(rdpTransport* transport)
{
	freerdp* instance;
	rdpSettings* settings;

	if (transport->tls == NULL)
		transport->tls = tls_new(transport->settings);

	transport->layer = TRANSPORT_LAYER_TLS;
	transport->tls->sockfd = transport->tcp->sockfd;

	if (tls_connect(transport->tls) != true)
	{
		if (!connectErrorCode)
			connectErrorCode = TLSCONNECTERROR;

		tls_free(transport->tls);
		transport->tls = NULL;
		return false;
	}

	/* Network Level Authentication */

	if (transport->settings->authentication != true)
		return true;

	settings = transport->settings;
	instance = (freerdp*) settings->instance;

	if (transport->credssp == NULL)
		transport->credssp = credssp_new(instance, transport->tls, settings);

	if (credssp_authenticate(transport->credssp) < 0)
	{
		if (!connectErrorCode)
			connectErrorCode = AUTHENTICATIONERROR;

		printf("Authentication failure, check credentials.\n"
			"If credentials are valid, the NTLMSSP implementation may be to blame.\n");

		credssp_free(transport->credssp);
		return false;
	}

	credssp_free(transport->credssp);

	return true;
}

boolean transport_tsg_connect(rdpTransport* transport, const char* hostname, uint16 port)
{
	rdpTsg* tsg = tsg_new(transport);

	tsg->transport = transport;
	transport->tsg = tsg;

	if (transport->tls_in == NULL)
		transport->tls_in = tls_new(transport->settings);

	transport->tls_in->sockfd = transport->tcp_in->sockfd;

	if (transport->tls_out == NULL)
		transport->tls_out = tls_new(transport->settings);

	transport->tls_out->sockfd = transport->tcp_out->sockfd;

	if (tls_connect(transport->tls_in) != true)
		return false;

	if (tls_connect(transport->tls_out) != true)
		return false;

	if (!tsg_connect(tsg, hostname, port))
		return false;

	return true;
}

boolean transport_connect(rdpTransport* transport, const char* hostname, uint16 port)
{
	boolean status = false;
	rdpSettings* settings = transport->settings;

	if (transport->settings->ts_gateway)
	{
		transport->layer = TRANSPORT_LAYER_TSG;
		transport->tcp_out = tcp_new(settings);

		status = tcp_connect(transport->tcp_in, settings->tsg_hostname, 443);

		if (status)
			status = tcp_connect(transport->tcp_out, settings->tsg_hostname, 443);

		if (status)
			status = transport_tsg_connect(transport, hostname, port);
	}
	else
	{
		status = tcp_connect(transport->tcp, hostname, port);
	}

	return status;
}

boolean transport_accept_rdp(rdpTransport* transport)
{
	/* RDP encryption */

	return true;
}

boolean transport_accept_tls(rdpTransport* transport)
{
	if (transport->tls == NULL)
		transport->tls = tls_new(transport->settings);

	transport->layer = TRANSPORT_LAYER_TLS;
	transport->tls->sockfd = transport->tcp->sockfd;

	if (tls_accept(transport->tls, transport->settings->cert_file, transport->settings->privatekey_file) != true)
		return false;

	return true;
}

boolean transport_accept_nla(rdpTransport* transport)
{
	freerdp* instance;
	rdpSettings* settings;

	if (transport->tls == NULL)
		transport->tls = tls_new(transport->settings);

	transport->layer = TRANSPORT_LAYER_TLS;
	transport->tls->sockfd = transport->tcp->sockfd;

	if (tls_accept(transport->tls, transport->settings->cert_file, transport->settings->privatekey_file) != true)
		return false;

	/* Network Level Authentication */

	if (transport->settings->authentication != true)
		return true;

	settings = transport->settings;
	instance = (freerdp*) settings->instance;

	if (transport->credssp == NULL)
		transport->credssp = credssp_new(instance, transport->tls, settings);

	if (credssp_authenticate(transport->credssp) < 0)
	{
		printf("client authentication failure\n");
		credssp_free(transport->credssp);
		return false;
	}

	/* don't free credssp module yet, we need to copy the credentials from it first */

	return true;
}

int transport_read(rdpTransport* transport, STREAM* s)
{
	int status = -1;

	while (true)
	{
		if (transport->layer == TRANSPORT_LAYER_TLS)
			status = tls_read(transport->tls, stream_get_tail(s), stream_get_left(s));
		else if (transport->layer == TRANSPORT_LAYER_TCP)
			status = tcp_read(transport->tcp, stream_get_tail(s), stream_get_left(s));
		else if (transport->layer == TRANSPORT_LAYER_TSG)
			status = tsg_read(transport->tsg, stream_get_tail(s), stream_get_left(s));

		if (status == 0 && transport->blocking)
		{
			freerdp_usleep(transport->usleep_interval);
			continue;
		}

		break;
	}

#ifdef WITH_DEBUG_TRANSPORT
	if (status > 0)
	{
		printf("Local < Remote\n");
		freerdp_hexdump(s->data, status);
	}
#endif

	return status;
}

static int transport_read_nonblocking(rdpTransport* transport)
{
	int status;

	stream_check_size(transport->recv_buffer, 4096);
	status = transport_read(transport, transport->recv_buffer);

	if (status <= 0)
		return status;

	stream_seek(transport->recv_buffer, status);

	return status;
}

int transport_write(rdpTransport* transport, STREAM* s)
{
	int status = -1;
	int length;

	length = stream_get_length(s);
	stream_set_pos(s, 0);

#ifdef WITH_DEBUG_TRANSPORT
	if (length > 0)
	{
		printf("Local > Remote\n");
		freerdp_hexdump(s->data, length);
	}
#endif

	while (length > 0)
	{
		if (transport->layer == TRANSPORT_LAYER_TLS)
			status = tls_write(transport->tls, stream_get_tail(s), length);
		else if (transport->layer == TRANSPORT_LAYER_TCP)
			status = tcp_write(transport->tcp, stream_get_tail(s), length);
		else if (transport->layer == TRANSPORT_LAYER_TSG)
			status = tsg_write(transport->tsg, stream_get_tail(s), length);

		if (status < 0)
			break; /* error occurred */

		if (status == 0)
		{
			/* blocking while sending */
			freerdp_usleep(transport->usleep_interval);

			/* when sending is blocked in nonblocking mode, the receiving buffer should be checked */
			if (!transport->blocking)
			{
				/* and in case we do have buffered some data, we set the event so next loop will get it */
				if (transport_read_nonblocking(transport) > 0)
					wait_obj_set(transport->recv_event);
			}
		}

		length -= status;
		stream_seek(s, status);
	}

	if (status < 0)
	{
		/* A write error indicates that the peer has dropped the connection */
		transport->layer = TRANSPORT_LAYER_CLOSED;
	}

	return status;
}

void transport_get_fds(rdpTransport* transport, void** rfds, int* rcount)
{
#ifdef _WIN32
	rfds[*rcount] = transport->tcp->wsa_event;
#else
	rfds[*rcount] = (void*)(long)(transport->tcp->sockfd);
#endif
	(*rcount)++;
	wait_obj_get_fds(transport->recv_event, rfds, rcount);
}

int transport_check_fds(rdpTransport** ptransport)
{
	int pos;
	int status;
	uint16 length;
	STREAM* received;
	rdpTransport* transport = *ptransport;

#ifdef _WIN32
	WSAResetEvent(transport->tcp->wsa_event);
#endif
	wait_obj_clear(transport->recv_event);

	status = transport_read_nonblocking(transport);

	if (status < 0)
		return status;

	while ((pos = stream_get_pos(transport->recv_buffer)) > 0)
	{
		stream_set_pos(transport->recv_buffer, 0);
		if (tpkt_verify_header(transport->recv_buffer)) /* TPKT */
		{
			/* Ensure the TPKT header is available. */
			if (pos <= 4)
			{
				stream_set_pos(transport->recv_buffer, pos);
				return 0;
			}
			length = tpkt_read_header(transport->recv_buffer);
		}
		else /* Fast Path */
		{
			/* Ensure the Fast Path header is available. */
			if (pos <= 2)
			{
				stream_set_pos(transport->recv_buffer, pos);
				return 0;
			}
			/* Fastpath header can be two or three bytes long. */
			length = fastpath_header_length(transport->recv_buffer);
			if (pos < length)
			{
				stream_set_pos(transport->recv_buffer, pos);
				return 0;
			}
			length = fastpath_read_header(NULL, transport->recv_buffer);
		}

		if (length == 0)
		{
			printf("transport_check_fds: protocol error, not a TPKT or Fast Path header.\n");
			freerdp_hexdump(stream_get_head(transport->recv_buffer), pos);
			return -1;
		}

		if (pos < length)
		{
			stream_set_pos(transport->recv_buffer, pos);
			return 0; /* Packet is not yet completely received. */
		}

		/*
		 * A complete packet has been received. In case there are trailing data
		 * for the next packet, we copy it to the new receive buffer.
		 */
		received = transport->recv_buffer;
		transport->recv_buffer = stream_new(BUFFER_SIZE);

		if (pos > length)
		{
			stream_set_pos(received, length);
			stream_check_size(transport->recv_buffer, pos - length);
			stream_copy(transport->recv_buffer, received, pos - length);
		}

		stream_set_pos(received, length);
		stream_seal(received);
		stream_set_pos(received, 0);

		if (transport->recv_callback(transport, received, transport->recv_extra) == false)
			status = -1;

		stream_free(received);

		if (status < 0)
			return status;

		/* transport might now have been freed by rdp_client_redirect and a new rdp->transport created */
		transport = *ptransport;

		if (transport->process_single_pdu)
		{
			/* one at a time but set event if data buffered
			 * so the main loop will call freerdp_check_fds asap */
			if (stream_get_pos(transport->recv_buffer) > 0)
				wait_obj_set(transport->recv_event);
			break;
		}

	}

	return 0;
}

boolean transport_set_blocking_mode(rdpTransport* transport, boolean blocking)
{
	transport->blocking = blocking;
	return tcp_set_blocking_mode(transport->tcp, blocking);
}

rdpTransport* transport_new(rdpSettings* settings)
{
	rdpTransport* transport;

	transport = (rdpTransport*) xzalloc(sizeof(rdpTransport));

	if (transport != NULL)
	{
		transport->tcp = tcp_new(settings);
		transport->tcp_in = tcp_new(settings);

		transport->settings = settings;

		/* a small 0.1ms delay when transport is blocking. */
		transport->usleep_interval = 100;

		/* receive buffer for non-blocking read. */
		transport->recv_buffer = stream_new(BUFFER_SIZE);
		transport->recv_event = wait_obj_new();

		/* buffers for blocking read/write */
		transport->recv_stream = stream_new(BUFFER_SIZE);
		transport->send_stream = stream_new(BUFFER_SIZE);

		transport->blocking = true;

		transport->layer = TRANSPORT_LAYER_TCP;
	}

	return transport;
}

void transport_free(rdpTransport* transport)
{
	if (transport != NULL)
	{
		stream_free(transport->recv_buffer);
		stream_free(transport->recv_stream);
		stream_free(transport->send_stream);
		wait_obj_free(transport->recv_event);

		if (transport->tls)
			tls_free(transport->tls);

		tcp_free(transport->tcp);
		tcp_free(transport->tcp_in);
		tsg_free(transport->tsg);

		xfree(transport);
	}
}


text:
"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Import the include() function: from django.conf.urls import url, include
    3. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include,url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
    url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
    url(r'', include('blog.urls')),
]


text:
package com.rackspacecloud.blueflood.service;

import com.codahale.metrics.Timer;
import com.rackspacecloud.blueflood.exceptions.CacheException;
import com.rackspacecloud.blueflood.cache.MetadataCache;
import com.rackspacecloud.blueflood.exceptions.IncomingMetricException;
import com.rackspacecloud.blueflood.exceptions.IncomingTypeException;
import com.rackspacecloud.blueflood.exceptions.IncomingUnitException;
import com.rackspacecloud.blueflood.types.IMetric;
import com.rackspacecloud.blueflood.types.Metric;
import com.rackspacecloud.blueflood.types.MetricMetadata;
import com.rackspacecloud.blueflood.types.Locator;
import com.rackspacecloud.blueflood.utils.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class IncomingMetricMetadataAnalyzer {
    private static final Logger log = LoggerFactory.getLogger(IncomingMetricMetadataAnalyzer.class);
    private static Timer scanMetricsTimer = Metrics.timer(IncomingMetricMetadataAnalyzer.class, "Scan meta for metrics");
    private static Timer checkMetaTimer = Metrics.timer(IncomingMetricMetadataAnalyzer.class, "Check meta");

    private final MetadataCache cache;

    public IncomingMetricMetadataAnalyzer(MetadataCache cache) {
        this.cache = cache;
    }

    public Collection<IncomingMetricException> scanMetrics(Collection<IMetric> metrics) {
        List<IncomingMetricException> problems = new ArrayList<IncomingMetricException>();

        Timer.Context ctx = scanMetricsTimer.time();
        for (IMetric metric : metrics) {
            try {
                if (metric instanceof Metric) {
                    Collection<IncomingMetricException> metricProblems = checkMetric((Metric)metric);
                    if (metricProblems != null) {
                        problems.addAll(metricProblems);
                    }
                }
            } catch (CacheException ex) {
                log.warn(ex.getMessage(), ex);
            }
        }
        ctx.stop();

        return problems;
    }

    private IncomingMetricException checkMeta(Locator locator, String key, String incoming) throws CacheException {
        Timer.Context ctx = checkMetaTimer.time();
        try {
            String existing = cache.get(locator, key, String.class);

            // always update the cache. it is smart enough to avoid needless writes.
            cache.put(locator, key, incoming);

            boolean differs = existing != null && !incoming.equals(existing);
            if (differs) {
                if (key.equals(MetricMetadata.UNIT.name().toLowerCase())) {
                    return new IncomingUnitException(locator, existing, incoming);
                } else {
                    return new IncomingTypeException(locator, existing, incoming);
                }
            }
        } finally {
            ctx.stop();
        }

        return null;
    }

    private Collection<IncomingMetricException> checkMetric(Metric metric) throws CacheException {
        if (metric == null) {
            return null;
        }

        List<IncomingMetricException> problems = new ArrayList<IncomingMetricException>();

        IncomingMetricException typeProblem = checkMeta(metric.getLocator(), MetricMetadata.TYPE.name().toLowerCase(),
                metric.getDataType().toString());
        IncomingMetricException unitProblem = checkMeta(metric.getLocator(), MetricMetadata.UNIT.name().toLowerCase(),
                metric.getUnit());

        if (typeProblem != null) {
            problems.add(typeProblem);
        }
        if (unitProblem != null) {
            problems.add(unitProblem);
        }

        return problems;
    }
}


text:
import LogRouter from 'OpenOrchestra/Application/Router/Log/LogRouter'

/**
 * @class LogSubApplication
 */
class LogSubApplication
{
    /**
     * Run sub Application
     */
    run() {
        this._initRouter();
    }

    /**
     * Initialize router
     * @private
     */
    _initRouter() {
        new LogRouter();
    }
}

export default (new LogSubApplication);


text:
Abstract class grouping Territorial Capitals data.

See subclasses for details.


text:
package com.speedment.fika.codegen.internal.model.value;

import com.speedment.fika.codegen.internal.model.ValueImpl;

/**
 *
 * @author Emil Forslund
 */
public final class NullValue extends ValueImpl<Number> {

	public NullValue() {
		super(0);
	}

	@Override
	public NullValue copy() {
		return this;
	}
}


text:
layout: page
title: Case Systems Trade Fair
date: 2016-05-24
author: Mildred Richards
tags: weekly links, java
status: published
summary: Curabitur augue velit, laoreet eu euismod nec, accumsan.
banner: images/banner/wedding.jpg
booking:
  startDate: 07/11/2016
  endDate: 07/14/2016
  ctyhocn: MCOGWHX
  groupCode: CSTF
published: true
---
Morbi sed sodales neque. Nulla eget imperdiet diam, et elementum augue. Curabitur nec odio tincidunt, imperdiet metus nec, varius leo. Aliquam a risus aliquet elit dictum lacinia. Maecenas sed auctor nisi. Nunc feugiat, dui eget sagittis consectetur, nibh felis mattis eros, eget consectetur odio diam vel libero. Fusce iaculis nulla ac turpis dignissim dapibus. Donec dui mauris, ultricies nec iaculis ut, mollis sed ante. Duis vehicula arcu est, et eleifend arcu tempor eget.
Fusce maximus sem ex, id congue nisi volutpat accumsan. Donec auctor mauris id nibh hendrerit, non consectetur justo dignissim. Donec lectus leo, laoreet eget ligula id, varius fringilla sem. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In nec est quis sapien luctus eleifend. Nunc vel facilisis ipsum. Sed vestibulum sit amet magna id vestibulum. Vivamus metus velit, convallis at dui faucibus, interdum convallis justo. Integer ac neque quis sapien vestibulum eleifend vitae eu nulla. Aliquam lacinia nulla vitae commodo suscipit.

* Maecenas ultrices nunc non ligula molestie, eget imperdiet urna luctus
* Cras vulputate nisl at blandit porta.

Suspendisse quis urna vel libero porta feugiat. Praesent et condimentum ex, id pharetra nunc. Cras nisl sem, commodo posuere nibh et, semper accumsan felis. Sed sollicitudin risus ut justo facilisis sodales. Integer non consectetur magna, mattis varius orci. Nam ut nulla odio. In lacus ante, malesuada posuere leo nec, sodales hendrerit purus. Pellentesque eu dolor erat. Donec vitae rutrum ipsum. Ut id lacus tempus, tempor arcu et, hendrerit magna. Nam malesuada augue nec ex elementum, sit amet elementum risus rhoncus.


text:
package com.jetbrains.python.refactoring.classes.membersManager;

import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.PyClass;
import com.jetbrains.python.psi.PyElement;
import com.jetbrains.python.refactoring.classes.PyClassRefactoringUtil;
import org.jetbrains.annotations.NotNull;

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

/**
 * Moves members checking types at runtime.
 *
 * @author Ilya.Kazakevich
 */
class TypeSafeMovingStrategy<T extends PyElement> {
  @NotNull private final PyClass myFrom;
  @NotNull private final MembersManager<T> myManager;
  @NotNull private final Collection<PyMemberInfo<T>> myMemberInfoCollection;
  private final PyClass @NotNull [] myTo;

  /**
   * Move members.
   * @param from source
   * @param manager manager to be used
   * @param memberInfoCollection what to move
   * @param to where
   */
  @SuppressWarnings({"unchecked", "rawtypes"}) //We check types at runtime
  static void moveCheckingTypesAtRunTime(@NotNull final PyClass from,
                   @NotNull final MembersManager<?> manager,
                   @NotNull final Collection<? extends PyMemberInfo<PyElement>> memberInfoCollection,
                   final PyClass @NotNull ... to) {
    manager.checkElementTypes((Collection)MembersManager.fetchElements(memberInfoCollection));
    new TypeSafeMovingStrategy(from, manager, memberInfoCollection, to).moveTyped();
  }

  private TypeSafeMovingStrategy(@NotNull final PyClass from,
                                 @NotNull final MembersManager<T> manager,
                                 @NotNull final Collection<PyMemberInfo<T>> memberInfoCollection,
                                 final PyClass @NotNull [] to) {
    myFrom = from;
    myManager = manager;
    myMemberInfoCollection = new ArrayList<>(memberInfoCollection);
    myTo = to.clone();
  }

  /**
   * While types are already checked at runtime, this method could move everything in type-safe manner.
   */
  private void moveTyped() {
    final Collection<T> elementsCollection = MembersManager.fetchElements(myMemberInfoCollection);
    final Collection<? extends PyElement> references = myManager.getElementsToStoreReferences(elementsCollection);

    // Store references to add required imports
    for (final PyElement element : references) {
      PyClassRefactoringUtil.rememberNamedReferences(element, PyNames.CANONICAL_SELF); //"self" is not reference we need to move
    }

    // Move
    final Collection<PyElement> newElements = myManager.moveMembers(myFrom, myMemberInfoCollection, myTo);

    // Restore references to add appropriate imports
    for (final PyElement element : newElements) {
      PyClassRefactoringUtil.restoreNamedReferences(element);
    }
  }
}


text:
- Drop an an image into images/sprites
- Run 'gulp sprites'

Images will automatically be turned into one sprite. Plus, a Sass file will automatically be generated containing the sprite details.

https://github.com/twolfson/gulp.spritesmith


text:
package com.example.fw;

public class HelperBase {
	protected final ApplicationManager manager;

	public HelperBase(ApplicationManager applicationManager) {
		this.manager = applicationManager;
	}

}


text:
<?php

namespace GW2Treasures\GW2Api\V2\Localization;

use GW2Treasures\GW2Api\V2\EndpointTrait;

trait LocalizedEndpoint {
    use EndpointTrait;

    /** @var string $language */
    protected $language = 'en';

    /**
     * Change the language of this endpoint.
     *
     * @param string $lang
     * @return $this
     */
    public function lang( $lang ) {
        $this->language = $lang;
        return $this;
    }

    /**
     * Get the current language.
     *
     * @return string
     */
    public function getLang() {
        return $this->language;
    }
}


text:
@interface CoredataManager : NSObject
@property(nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property(nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property(nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
-(void)resetAll;
- (NSURL *)applicationDocumentsDirectory; // nice to have to reference files for core data
@end