text:
<title>
The fight facing German workers
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

VIEWS AND VOICES

The fight facing German workers

July 20, 2007 | Page 6

VERDI, GERMANY'S second-biggest trade union, was dealt a bitter blow a few weeks ago when it caved in to Telekom management after more than five weeks of strikes.

Telekom is the largest European telecommunications company and a spin-off of the former state-owned Deutsche Bundespost after its privatization in the mid-1990s. Verdi was born out of a fusion of five independent trade unions in 2001 and currently has about 2.3 million members. Its primary focus is on public-sector service workers, but media workers as well as the banking and insurance sector are also covered.

At the heart of the struggle is a major reorganization that will affect some 50,000 employees. The plan is to reshuffle them into smaller "service companies."

The reason is the same heard from companies the world over: "Due to the pressure of globalization we'll have to get leaner and meaner if we want to remain competitive." The results for the average worker are as expected, too: More work for less pay.

Verdi still claims to have reached an agreement that won't result in less pay. The reality of the deal, however, looks quite different. It is true that Telekom will make up the difference in pay for those who end up in the new "service companies" and keep them 100 percent whole. However, this only holds true for the first 18 months.

In 2009, the employees' wages will be reduced by 2.2 percent and in 2010, by 4.3 percent. Telekom will stop all "make up" payments at the end of 2010, so that from 2011 on, the pay cut will be at 6.5 percent. At the same time, the workweek goes up from 34 to 38 hours and overtime will no longer be paid for Saturdays. This results in a loss of approximately 11 percent when converted into hourly wages.

Even more alarming is that this compromise could serve as a blueprint for docking pay in other former public sector industries. In this context, the ongoing battle over the privatization of Germany's railroad sector (officially privatized in the mid-1990s as well, but 100 percent of the stock is still owned by the Federal Republic of Germany) and the current train engineer strike is crucial.

Germany's train engineers have their own union and are against a privatization of Deutsche Bahn, while Germany's railroad sector unions Transnet and GDBA are pro-privatization. More battles are also ahead in the mail sector of former Deutsche Bundespost, where management's promise in the last agreement (to not sack workers for economic reasons) will expire in March 2008, and layoffs are to be expected.

Ultimately, this shows the dilemma of reformist trade unions working within a capitalist framework. Even when operating with arguably good intentions, they are vulnerable to be blackmailed into undesirable outcomes. In the process, improvements that took decades of struggle to implement are given up in a few rounds of "negotiations."

In the final analysis, it is only the power of the working class itself not trade union bureaucrats that can bring about lasting and fundamental change.

Folko Mueller, Houston, Texas

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import extractViewBox from '../lib/extract/extractViewBox';
import Shape from './Shape';
import { RNSVGSymbol } from './NativeComponents';

export default class Symbol extends Shape<{
  id?: string;
  viewBox?: string;
  preserveAspectRatio?: string;
}> {
  static displayName = 'Symbol';

  render() {
    const { props } = this;
    const { id, children } = props;
    return (
      <RNSVGSymbol ref={this.refMethod} name={id} {...extractViewBox(props)}>
        {children}
      </RNSVGSymbol>
    );
  }
}


text:
<?php

return [
    UPLOAD_ERR_INI_SIZE => 'file size exceeds MAX_FILE_SIZE in php.ini limit',
    UPLOAD_ERR_FORM_SIZE => 'file size exceeds MAX_FILE_SIZE in form limit',
    UPLOAD_ERR_PARTIAL => 'upload file is not complete',
    UPLOAD_ERR_NO_FILE => 'no files uploaded',
    UPLOAD_ERR_NO_TMP_DIR => 'no temporary directory found',
    UPLOAD_ERR_CANT_WRITE => 'fail to write file',

    'ERROR_TMP_FILE' => 'create temporary file error',
    'ERROR_TMP_FILE_NOT_FOUND' => 'can\'t find a temporary file',
    'ERROR_SIZE_EXCEED' => 'file size beyond the site restrictions',
    'ERROR_TYPE_NOT_ALLOWED' => 'file type does not allowed',
    'ERROR_CREATE_DIR' => 'directory creation fails',
    'ERROR_DIR_NOT_WRITEABLE' => 'directory does not have write permission',
    'ERROR_FILE_MOVE' => 'file save error',
    'ERROR_FILE_NOT_FOUND' => 'can\'t find the uploaded file',
    'ERROR_WRITE_CONTENT' => 'error writing file content',
    'ERROR_UNKNOWN' => 'An unknown error',
    'ERROR_DEAD_LINK' => 'link is not available',
    'ERROR_HTTP_LINK' => 'not a HTTP link',
    'ERROR_HTTP_CONTENTTYPE' => 'link contentType incorrect',
    'ERROR_UNKNOWN_MODE' => 'Please Config the core.mode',
];


text:
import React, { PropTypes } from 'react'
import styled, { css } from 'styled-components'
import material from 'google-material-color'

const ColorWrapper = styled.div`
  display: flex;
  flex-grow: 1;
  flex-shrink: 0;
  background-color: ${props => material.get((props.color || 'Blue Grey'), props.hue || 500)};
  color: ${props => material.getText((props.color || 'Blue Grey'), props.hue || '500')};
  transition: all .3s;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  margin: 0;
  padding: 1rem;
  box-shadow: 0 0 0 rgba(0,0,0,0);

  &:hover {
    box-shadow: 0 3px 10px rgba(0,0,0,.23), 0 3px 10px rgba(0,0,0,.16);
    transform: scale(1.025);
  }

  ${props => props.active && css`
    box-shadow: 0 3px 10px rgba(0,0,0,.23), 0 3px 10px rgba(0,0,0,.16);
    transform: scale(1.025);
  `}
`
ColorWrapper.displayName = 'ColorWrapper'

const Color = ({ color, onClick, active, title, hue }) => (
  <ColorWrapper color={color} onClick={onClick} active={active} hue={hue}>
    {title || color}
    {hue && {hue}}
  </ColorWrapper>
)

Color.propTypes = {
  color: PropTypes.string,
  onClick: PropTypes.func,
  active: PropTypes.bool,
  title: PropTypes.string,
  hue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}

export default Color


text:
require('should');
var assert = require('assert');
var js = require('../../../lib/javascript');
var sinon = require('sinon');

describe('javascript.js unit tests', function(){
  describe('#className(obj)', function(){
    it('should return undefined when passed undefined', function() {
      js.className(undefined).should.equal("undefined");
    });

    it('should return Array when passed [1]', function(){
      js.className([1]).should.equal("Array");
    });

    it('should return String when passed \'ab\'', function(){
      js.className('ab').should.equal("String");
    });

    it('should return Object when passed {}', function(){
      js.className({}).should.equal("Object");
    });

    it('should return Number when passed 1', function(){
      js.className(1).should.equal("Number");
    });

    it('should return function when passed fn', function(){
      js.className(function() { }).should.equal("Function");
    });
  });

 describe('#isHex(obj) test', function(){
    it('should return true for "10"', function(){
      js.isHex('10').should.be.true;
    });

    it('should return true for "deadbeef"', function(){
      js.isHex('deadbeef').should.be.true;
      js.isHex('DEADBEEF').should.be.true;
    });

    it('should return false for "undefined"', function(){
      js.isHex(undefined).should.be.false;
    });

    it('should return false for "jason"', function(){
      js.isHex('jason').should.be.false;
    });

  });

  describe('#assertClassName(obj)', function(){
    it('should not throw for appropriate types', function() {
      js.assertClassName([1], "Array");
      js.assertClassName('ab', "String");
      js.assertClassName(1, "Number");
      js.assertClassName(function() { }, "Function");
      js.assertClassName({ }, "Object");
    });

    it('should throw for inappropriate types', function() {
      (function () { js.assertClassName([1], "Number") }).should.throw();
      (function () { js.assertClassName([1], "Object") }).should.throw();
      (function () { js.assertClassName({}, "String") }).should.throw();
    });

  });

  describe('#assertClass(obj)', function(){
    it('should not throw for appropriate types', function() {
      js.assertClass([1], Array);
      js.assertClass('ab', String);
      js.assertClass(1, Number);
      js.assertClass(function() { }, Function);
      js.assertClass({ }, Object);
    });

    it('should throw for inappropriate types', function() {
      (function () { js.assertClass([1], Number) }).should.throw();
      (function () { js.assertClass([1], Object) }).should.throw();
      (function () { js.assertClass({}, String) }).should.throw();
    });

  });

  describe('#xor(obj)', function(){
    it('should implement xor', function() {
      js.xor(true,false).should.be.true;
      js.xor(false,true).should.be.true;
      js.xor(false,false).should.be.false;
      js.xor(true,true).should.be.false;
    });
  });

  describe('#zeroFill(number,width)', function() {
    it("should return 00000 for zeroFill(0,5)", function() {
      js.zeroFill(0,5).should.equal("00000");
    });
    it("should return 1 for zeroFill(1,1)", function() {
      js.zeroFill(1,1).should.equal("1");
    });
    it("should return 0000100 for zeroFill(100,7)", function() {
      js.zeroFill(100,7).should.equal("0000100");
    });
  });

  describe('#pathValue', function() {
    it("should return appropriate values (lame description)", function() {
      js.pathValue({a: 1}, ['a']).should.equal(1);
      js.pathValue({a: {b: 1}}, ['a', 'b']).should.equal(1);
      js.pathValue({a: {b: {c: 1}}}, ['a', 'b', 'c']).should.equal(1);

      assert.ok(js.pathValue({a: 1}, ['a','b']) === undefined);
      assert.ok(js.pathValue({a: 1}, ['b']) === undefined);
      assert.ok(js.pathValue({a: 1}, []) === undefined);

      assert.ok(js.pathValue({a: {b: 1}}, ['b', 'a']) === undefined);
      assert.ok(js.pathValue({a: {b: 1}}, ['a', 'b', 'c']) === undefined);
    });
  });

  describe('#String.trunc', function() {
    it("should not truncate something in range", function() {
      assert.ok("hi there".trunc(25) === "hi there");
    });
    it("should trunc empty string", function() {
      assert.ok("".trunc(5) === "");
    });
    it("should trunc simple case with ellipsis", function() {
      assert.ok("hi there".trunc(5) === "hi...");
    });
    it("should trunc really long string 1 word", function() {
      console.log('"hithereasdfladsjf".trunc(5)' + "hithereasdfladsjf".trunc(5));
      assert.ok("hithereasdfladsjf".trunc(5) === "hithe...");
    });
    it("should trunc really long string 2 words", function() {
      assert.ok("hi thereasdfladsjf".trunc(10) === "hi...");
    });

  });
});


text:
<?php
namespace packages\base\IO;
abstract class File extends Node implements \Serializable {
	/**
	 * @param callable(File\Local):mixed $callback
	 */
	public static function insureLocal(File $file, $callback = null): File\Local {
		if ($file instanceof File\Local) {
			$localFile = $file;
		} else {
			$localFile = new File\Tmp();
			if ($file->exists()) {
				$file->copyTo($localFile);
			}
		}
		$originalMd5 = $file->exists() ? $localFile->md5() : null;
		if ($callback !== null) {
			call_user_func($callback, $localFile);
			if ($localFile !== $file) {
				if ($localFile->exists()) {
					if ($originalMd5 !== $localFile->md5()) {
						$localFile->copyTo($file);
					}
				} else {
					$file->delete();
				}
			}
		}

		return $localFile;
	}

	abstract public function copyTo(file $dest): bool;
	abstract public function move(file $dest):bool;
	abstract public function read(int $length = 0): string;
	abstract public function write(string $data): bool;
	abstract public function size(): int;
	public function copyFrom(file $source): bool{
		return $source->copyTo($this);
	}
	public function getExtension(): string {
		$dot = strrpos($this->basename, '.');
		if ($dot === false) {
			return "";
		}
		return substr($this->basename, $dot + 1);
	}
	public function isEmpty():bool{
		return $this->size() == 0;
	}
}


text:
package org.sakaiproject.kernel.api.locking;

/**
 * Lock manager provides a mechanism for locking uniquely identified objects across the
 * cluster.
 */
public interface LockManager {

  /**
   * @param id
   * @return
   */
  Lock getLock(String id);

  /**
   * @param id
   * @param create
   * @return
   */
  Lock getLock(String id, boolean create);

  /**
   * @param id
   * @return
   * @throws LockTimeoutException
   *           indicates that a lock was not achieved within the a timeout (30s)
   */
  Lock waitForLock(String id) throws LockTimeoutException;

  /**
   * clear the locks associated with this request.
   */
  void clearLocks();

}


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

	var booksList = {
		templateUrl: 'app/entities/book/_partials/books-list.html',
		controller: 'BooksListController',
		controllerAs: 'vm',
		bindings: {
			books: '<'
		}
	};

	angular
		.module('app.book.partial')
		.component('booksList', booksList);
})();


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<servico xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://servicos.gov.br/v3/schema ../servico.xsd">
    <nome>Certidão Conjunta de Débitos Relativos a Tributos Federais e à Dívida Ativa da União</nome>
    <sigla/>
    <nomes-populares/>
    <descricao>Solicitar emissão de certidão da pessoa física, exceto de contribuições previdenciárias.</descricao>
    <gratuito/>
    <solicitantes/>
    <tempo-total-estimado>
        <descricao/>
    </tempo-total-estimado>
    <etapas>
        <etapa>
            <titulo/>
            <descricao/>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao tipo="web">
                        <descricao>http://www.receita.fazenda.gov.br/Aplicacoes/ATSPO/Certidao/CndConjuntaInter/InformaNICertidao.asp?Tipo=2</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/77"/>
    <segmentos-da-sociedade>
        <item>Cidadãos</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Economia e Finanças</item>
    </areas-de-interesse>
    <palavras-chave/>
    <legislacoes/>
</servico>


text:
/**
 * Emulates very small parts of cachedTypes.js and itemFields.js APIs for use with connector
 */

/**
 * @namespace
 */
Zotero.Connector_Types = new function() {
	/**
	 * Initializes types
	 * @param {Object} typeSchema typeSchema generated by Zotero.Connector.GetData#_generateTypeSchema
	 */
	this.init = function() {
		const schemaTypes = ["itemTypes", "creatorTypes", "fields"];

		// attach IDs and make referenceable by either ID or name
		for (var i = 0; i < schemaTypes.length; i++) {
			var schemaType = schemaTypes[i];
			this[schemaType] = Zotero.Utilities.deepCopy(Zotero.Connector_Types.schema[schemaType]);
			for (var id in Zotero.Connector_Types.schema[schemaType]) {
				var entry = this[schemaType][id];
				entry.unshift(parseInt(id, 10));
				this[schemaType][entry[1] /* name */ ] = entry;
			}
		}

		var itemTypes = Zotero.Connector_Types["itemTypes"];
		var creatorTypes = Zotero.Connector_Types["creatorTypes"];
		var fields = Zotero.Connector_Types["fields"];

		Zotero.CachedTypes = function() {
			var thisType = Zotero.Connector_Types[this.schemaType];

			this.getID = function(idOrName) {
				var type = thisType[idOrName];
				return (type ? type[0] /* id */ : false);
			};

			this.getName = function(idOrName) {
				var type = thisType[idOrName];
				return (type ? type[1] /* name */ : false);
			};

			this.getLocalizedString = function(idOrName) {
				var type = thisType[idOrName];
				return (type ? type[2] /* localizedString */ : false);
			};
		}

		Zotero.ItemTypes = new function() {
			this.schemaType = "itemTypes";
			Zotero.CachedTypes.call(this);

			this.getImageSrc = function(idOrName) {
				var itemType = Zotero.Connector_Types["itemTypes"][idOrName];
				var icon = itemType ? itemType[6] /* icon */ : "treeitem-" + idOrName + ".png";

				if (Zotero.isBookmarklet) {
					return ZOTERO_CONFIG.BOOKMARKLET_URL + "images/" + icon;
				} else if (Zotero.isBrowserExt) {
					return browser.extension.getURL("images/" + icon);
				} else if (Zotero.isSafari) {
					return safari.extension.baseURI + "images/" + icon;
				}
			};
		}

		Zotero.CreatorTypes = new function() {
			this.schemaType = "creatorTypes";
			Zotero.CachedTypes.call(this);

			this.getTypesForItemType = function(idOrName) {
				var itemType = itemTypes[idOrName];
				if (!itemType) return false;

				var itemCreatorTypes = itemType[3]; // creatorTypes
				if (!itemCreatorTypes
					// TEMP: 'note' and 'attachment' have an array containing false
					||
					(itemCreatorTypes.length == 1 && !itemCreatorTypes[0])) {
					return [];
				}
				var n = itemCreatorTypes.length;
				var outputTypes = new Array(n);

				for (var i = 0; i < n; i++) {
					var creatorType = creatorTypes[itemCreatorTypes[i]];
					outputTypes[i] = {
						"id": creatorType[0] /* id */ ,
						"name": creatorType[1] /* name */
					};
				}
				return outputTypes;
			};

			this.getPrimaryIDForType = function(idOrName) {
				var itemType = itemTypes[idOrName];
				if (!itemType) return false;
				return itemType[3] /* creatorTypes */ [0];
			};

			this.isValidForItemType = function(creatorTypeID, itemTypeID) {
				let itemType = itemTypes[itemTypeID];
				return itemType[3] /* creatorTypes */ .includes(creatorTypeID);
			};
		};

		Zotero.ItemFields = new function() {
			this.schemaType = "fields";
			Zotero.CachedTypes.call(this);

			this.isValidForType = function(fieldIdOrName, typeIdOrName) {
				var field = fields[fieldIdOrName],
					itemType = itemTypes[typeIdOrName];

				// mimics itemFields.js
				if (!field || !itemType) return false;

				/* fields */
				/* id */
				return itemType[4].indexOf(field[0]) !== -1;
			};

			this.isBaseField = function(fieldID) {
				return fields[fieldID][2];
			};

			this.getFieldIDFromTypeAndBase = function(typeIdOrName, fieldIdOrName) {
				var baseField = fields[fieldIdOrName],
					itemType = itemTypes[typeIdOrName];

				if (!baseField || !itemType) return false;

				// get as ID
				baseField = baseField[0] /* id */ ;

				// loop through base fields for item type
				var baseFields = itemType[5];
				for (var i in baseFields) {
					if (baseFields[i] === baseField) {
						return i;
					}
				}

				return false;
			};

			this.getBaseIDFromTypeAndField = function(typeIdOrName, fieldIdOrName) {
				var field = fields[fieldIdOrName],
					itemType = itemTypes[typeIdOrName];
				if (!field || !itemType) {
					throw new Error("Invalid field or type ID");
				}

				var baseField = itemType[5] /* baseFields */ [field[0] /* id */ ];
				return baseField ? baseField : false;
			};

			this.getItemTypeFields = function(typeIdOrName) {
				return itemTypes[typeIdOrName][4] /* fields */ .slice();
			};
		}
	};

	/**
	 * Passes schema to a callback
	 * @param {Function} callback
	 */
	this.getSchema = function(callback) {
		callback(Zotero.Connector_Types.schema);
	};
}


text:
package org.apache.excalibur.instrument.client;

import java.io.File;

import org.apache.avalon.framework.logger.ConsoleLogger;

/**
 *
 * @author Avalon Development Team
 * @version CVS $Revision: 1.4 $ $Date: 2004/02/28 11:47:23 $
 * @since 4.1
 */
public class Main
{
    /*---------------------------------------------------------------
     * Methods
     *-------------------------------------------------------------*/
    private static void showUsage()
    {
        System.out.println( "Usage:");
        System.out.println( "java -classpath {classpath} org.apache.excalibur.instrument.client.Main [-debug] [state file]" );
        System.out.println();
        System.out.println( "    -debug     - Enables debug output." );
        System.out.println( "    state file - Name of a state file to read at startup.  Defaults to: ../conf/default.desktop" );
        System.out.println();
    }

    /*---------------------------------------------------------------
     * Main Method
     *-------------------------------------------------------------*/
    /**
     * Main method used to lauch an InstrumentClient application.
     */
    public static void main( String args[] )
    {
        // Parse the command line.  Want to replace this with something more powerful later.
        boolean debug = false;
        String defaultStateFileName = "../conf/default.desktop";
        switch( args.length )
        {
        case 0:
            break;

        case 1:
            if ( args[0].equalsIgnoreCase( "-debug" ) )
            {
                debug = true;
            }
            else
            {
                defaultStateFileName = args[0];
            }
            break;

        case 2:
            if ( args[0].equalsIgnoreCase( "-debug" ) )
            {
                debug = true;
            }
            else
            {
                showUsage();
                System.exit( 1 );
            }
            defaultStateFileName = args[1];
            break;

        default:
            showUsage();
            System.exit( 1 );
        }

        File defaultStateFile = new File( defaultStateFileName );

        InstrumentClientFrame client = new InstrumentClientFrame( "Instrument Client" );
        int logLevel = ( debug ? ConsoleLogger.LEVEL_DEBUG : ConsoleLogger.LEVEL_INFO );
        client.enableLogging( new ConsoleLogger( logLevel ) );
        client.initialize();
        client.setDefaultStateFile( defaultStateFile );
        client.show();
    }
}


text: Distributed computing platform for solving humanity's newest problems.


text:
{{WidgetMedia.item.data.title}}

{{WidgetMedia.item.data.summary}}

                Listen
                Watch

                View Source
                More Options


text:
package main

// typedef struct {
//     char *value;
//     int len;
// } buf;
//
// typedef struct path_t {
//     buf   nlri;
//     buf** path_attributes;
//     int   path_attributes_len;
//     int   path_attributes_cap;
// } path;
// extern path* new_path();
// extern void free_path(path*);
// extern int append_path_attribute(path*, int, char*);
// extern buf* get_path_attribute(path*, int);
import "C"

import (
	"encoding/json"
	"strings"

	"github.com/osrg/gobgp/gobgp/cmd"
	"github.com/osrg/gobgp/packet"
)

//export get_route_family
func get_route_family(input *C.char) C.int {
	rf, err := bgp.GetRouteFamily(C.GoString(input))
	if err != nil {
		return C.int(-1)
	}
	return C.int(rf)
}

//export serialize_path
func serialize_path(rf C.int, input *C.char) *C.path {
	args := strings.Split(C.GoString(input), " ")
	p, err := cmd.ParsePath(bgp.RouteFamily(rf), args)
	if err != nil {
		return nil
	}
	path := C.new_path()
	if len(p.Nlri) > 0 {
		path.nlri.len = C.int(len(p.Nlri))
		path.nlri.value = C.CString(string(p.Nlri))
	}
	for _, attr := range p.Pattrs {
		C.append_path_attribute(path, C.int(len(attr)), C.CString(string(attr)))
	}
	return path
}

//export decode_path
func decode_path(p *C.path) *C.char {
	var buf []byte
	var nlri bgp.AddrPrefixInterface
	if p.nlri.len > 0 {
		buf = []byte(C.GoStringN(p.nlri.value, p.nlri.len))
		nlri = &bgp.IPAddrPrefix{}
		err := nlri.DecodeFromBytes(buf)
		if err != nil {
			return nil
		}
	}
	pattrs := make([]bgp.PathAttributeInterface, 0, int(p.path_attributes_len))
	for i := 0; i < int(p.path_attributes_len); i++ {
		b := C.get_path_attribute(p, C.int(i))
		buf = []byte(C.GoStringN(b.value, b.len))
		pattr, err := bgp.GetPathAttribute(buf)
		if err != nil {
			return nil
		}

		err = pattr.DecodeFromBytes(buf)
		if err != nil {
			return nil
		}

		switch pattr.GetType() {
		case bgp.BGP_ATTR_TYPE_MP_REACH_NLRI:
			mpreach := pattr.(*bgp.PathAttributeMpReachNLRI)
			if len(mpreach.Value) != 1 {
				return nil
			}
			nlri = mpreach.Value[0]
		}

		pattrs = append(pattrs, pattr)
	}
	j, _ := json.Marshal(struct {
		Nlri      bgp.AddrPrefixInterface      `json:"nlri"`
		PathAttrs []bgp.PathAttributeInterface `json:"attrs"`
	}{
		Nlri:      nlri,
		PathAttrs: pattrs,
	})
	return C.CString(string(j))
}

//export decode_capabilities
func decode_capabilities(p *C.buf) *C.char {
	buf := []byte(C.GoStringN(p.value, p.len))
	c, err := bgp.DecodeCapability(buf)
	if err != nil {
		return nil
	}
	j, _ := json.Marshal(c)
	return C.CString(string(j))

}

func main() {
	// We need the main function to make possible
	// CGO compiler to compile the package as C shared library
}


text:
package com.amazonaws.services.iot.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DescribeThingGroupResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeThingGroupResultJsonUnmarshaller implements Unmarshaller<DescribeThingGroupResult, JsonUnmarshallerContext> {

    public DescribeThingGroupResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        DescribeThingGroupResult describeThingGroupResult = new DescribeThingGroupResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return describeThingGroupResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("thingGroupName", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setThingGroupName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("thingGroupId", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setThingGroupId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("thingGroupArn", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setThingGroupArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("version", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setVersion(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("thingGroupProperties", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setThingGroupProperties(ThingGroupPropertiesJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("thingGroupMetadata", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setThingGroupMetadata(ThingGroupMetadataJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("indexName", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setIndexName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("queryString", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setQueryString(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("queryVersion", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setQueryVersion(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("status", targetDepth)) {
                    context.nextToken();
                    describeThingGroupResult.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return describeThingGroupResult;
    }

    private static DescribeThingGroupResultJsonUnmarshaller instance;

    public static DescribeThingGroupResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DescribeThingGroupResultJsonUnmarshaller();
        return instance;
    }
}


text:
from importlib import import_module
from jet.dashboard import settings

def get_current_dashboard(location):
    if location == 'index':
        path = settings.JET_INDEX_DASHBOARD
    elif location == 'app_index':
        path = settings.JET_APP_INDEX_DASHBOARD
    else:
        raise ValueError('Unknown dashboard location: %s' % location)

    module, cls = path.rsplit('.', 1)

    try:
        module = import_module(module)
        index_dashboard_cls = getattr(module, cls)
        return index_dashboard_cls
    except ImportError:
        return None


text:
<?php

namespace Laravel\Achievements\Tests;

use Illuminate\Support\Facades\Event;
use Laravel\Achievements\AchievementCriteriaModel;
use Laravel\Achievements\AchievementModel;
use Laravel\Achievements\AchievementsStorage;
use Laravel\Achievements\Events\AchievementsCompleted;
use Laravel\Achievements\Events\CriteriaUpdated;
use Laravel\Achievements\Tests\Stubs\User;
use Zurbaev\Achievements\Achievement;
use Zurbaev\Achievements\AchievementCriteria;
use Zurbaev\Achievements\AchievementCriteriaProgress;

class AchievementsStorageTest extends TestCase
{
    /**
     * @var User
     */
    protected $user;

    /**
     * @var AchievementsStorage
     */
    protected $storage;

    public function setUp()
    {
        parent::setUp();

        $this->seedAchievements();
        $this->user = User::create(['name' => 'John Doe']);
        $this->storage = app(AchievementsStorage::class);

        Event::fake();
    }

    public function testGetOwnerCriteriasByType()
    {
        $criterias = $this->storage->getOwnerCriteriasByType($this->user, 'reach_level');
        $this->assertInternalType('array', $criterias);
        $this->assertSame(3, count($criterias));

        foreach ($criterias as $criteria) {
            $this->assertInstanceOf(AchievementCriteria::class, $criteria);
            /**
             * @var AchievementCriteria $criteria
             */
            $this->assertSame('reach_level', $criteria->type());
        }
    }

    public function testGetAchievementsByCriterias()
    {
        $criterias = $this->storage->getOwnerCriteriasByType($this->user, 'reach_level');
        $this->assertInternalType('array', $criterias);
        $this->assertSame(3, count($criterias));

        $achievements = $this->storage->getAchievementsByCriterias($criterias);
        $this->assertInternalType('array', $achievements);
        $this->assertSame(3, count($achievements));

        foreach ($achievements as $achievement) {
            $this->assertInstanceOf(Achievement::class, $achievement);
            /**
             * @var Achievement $achievement
             */
            $this->assertFalse($achievement->completed());
            $this->assertSame(1, count($achievement->criterias()));
        }
    }

    public function testGetAchievementForCriteria()
    {
        $criterias = $this->storage->getOwnerCriteriasByType($this->user, 'reach_level');
        $achievements = $this->storage->getAchievementsByCriterias($criterias);

        /**
         * @var Achievement $expected
         * @var Achievement $actual
         */
        $expected = $achievements[0];
        $actual = $this->storage->getAchievementForCriteria($expected->criterias()[0], $achievements);

        $this->assertInstanceOf(Achievement::class, $actual);
        $this->assertSame($expected->id(), $actual->id());
    }

    public function testGetAchievementsWithProgressFor()
    {
        /**
         * @var AchievementCriteriaModel $criteria
         */
        $criteria = AchievementCriteriaModel::find(1); // Reach level 10.
        $this->user->achievementCriterias()->attach($criteria->id, ['value' => 6]);
        $this->user = $this->user->fresh();

        $achievements = $this->storage->getAchievementsWithProgressFor($this->user, [$criteria->achievement_id]);
        $this->assertInternalType('array', $achievements);
        $this->assertSame(1, count($achievements));

        /**
         * @var Achievement         $achievement
         * @var AchievementCriteria $achievementCriteria
         */
        $achievement = $achievements[0];
        $achievementCriteria = $achievement->criterias()[0];

        $this->assertInstanceOf(AchievementCriteria::class, $achievementCriteria);
        $this->assertTrue($achievementCriteria->hasProgress());
        $this->assertSame(6, $achievementCriteria->progress()->value);
    }

    public function testSetCriteriaProgressUpdated()
    {
        $achievement = $this->storage->convertAchievementModelWithCriterias(
            AchievementModel::find(1)
        );
        /**
         * @var AchievementCriteria $criteria
         */
        $criteria = $achievement->criterias()[0];

        $this->assertSame(0, count($this->user->achievementCriterias));

        $result = $this->storage->setCriteriaProgressUpdated(
            $this->user, $criteria, $achievement, new AchievementCriteriaProgress(6, true, false, ['hello' => 'world'])
        );

        $this->assertTrue($result);

        $this->user = $this->user->fresh();
        $this->assertSame(1, count($this->user->achievementCriterias));
        $userCriteria = $this->user->achievementCriterias()->find($criteria->id());
        $this->assertInstanceOf(AchievementCriteriaModel::class, $userCriteria);
        $this->assertSame($criteria->id(), $userCriteria->id);
        $this->assertSame(6, intval($userCriteria->pivot->value));
        $this->assertSame(['hello' => 'world'], json_decode($userCriteria->pivot->progress_data, true));

        Event::assertDispatched(CriteriaUpdated::class);
    }

    public function testSetAchievementsCompleted()
    {
        $this->assertSame(0, count($this->user->achievements));
        $this->assertSame(0, $this->user->achievementPoints());

        $achievements = $this->storage->convertAchievementModelsWithCriterias(
            AchievementModel::whereIn('id', [1, 2, 3])->get()
        );

        $this->storage->setAchievementsCompleted($this->user, $achievements);

        $this->user = $this->user->fresh();
        $this->assertSame(3, count($this->user->achievements));
        $this->assertSame(30, $this->user->achievementPoints());

        Event::assertDispatched(AchievementsCompleted::class);
    }
}


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

namespace ScrambleSquaresPuzzleSolver
{
    public class Graphic
    {
        public string Name { get; set; }
        public bool IsFront { get; set; }
    }
}


text:
setopt completeinword
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'


text:
This modal has video

  ×


text:
package org.onsteroids.eve.api;

import com.eveonline.api.ApiService;

/**
 * @author Tobias Sarnowski
 */
public interface Api {

    /**
	 * @param apiService the API service type to retrieve
	 * @param <T> the service definition
	 * @return the ready-to-use API service instance
	 */
	<T extends ApiService> T get(Class<T> apiService);

}


text:
package org.ovirt.engine.ui.common.widget.editor;

import java.util.List;

import org.ovirt.engine.ui.common.widget.AbstractValidatedWidgetWithLabel;
import org.ovirt.engine.ui.common.widget.VisibilityRenderer;
import org.ovirt.engine.ui.common.widget.renderer.StringRenderer;

import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.editor.client.IsEditor;
import com.google.gwt.text.shared.Renderer;

/**
 * Composite Editor that uses {@link ListModelRadioGroup}.
 *
 * @param <T>
 *            Radio box item type.
 */
public class ListModelRadioGroupEditor<T> extends AbstractValidatedWidgetWithLabel<T, ListModelRadioGroup<T>>
        implements IsEditor<WidgetWithLabelEditor<T, ListModelRadioGroupEditor<T>>> {

    private final WidgetWithLabelEditor<T, ListModelRadioGroupEditor<T>> editor;

    public ListModelRadioGroupEditor() {
        this(new StringRenderer<T>());
    }

    public ListModelRadioGroupEditor(VisibilityRenderer visibilityRenderer) {
        this(new StringRenderer<T>(), visibilityRenderer);
    }

    public ListModelRadioGroupEditor(Renderer<T> renderer, VisibilityRenderer visibilityRenderer) {
        super(new ListModelRadioGroup<T>(renderer), visibilityRenderer);
        this.editor = WidgetWithLabelEditor.of(getContentWidget().asEditor(), this);
    }

    public ListModelRadioGroupEditor(Renderer<T> renderer) {
        this(renderer, new VisibilityRenderer.SimpleVisibilityRenderer());
    }

    public RadioGroup<T> asRadioGroup() {
        return getContentWidget();
    }

    @Override
    public WidgetWithLabelEditor<T, ListModelRadioGroupEditor<T>> asEditor() {
        return editor;
    }

    @Override
    public void markAsValid() {
        super.markAsValid();
        getValidatedWidgetStyle().setBorderStyle(BorderStyle.NONE);
    }

    @Override
    public void markAsInvalid(List<String> validationHints) {
        super.markAsInvalid(validationHints);
        getValidatedWidgetStyle().setBorderStyle(BorderStyle.SOLID);
    }

}


text:
layout: leaf-node
title: "Udemy"
title-url: "https://www.udemy.com/"
author: "Udemy"
groups: technologies
categories: [online-learning,moocs]
topics: ongoing-projects
summary: |
    "Udemy is a global marketplace for learning and teaching online where students
    are mastering new skills and achieving their goals by learning from an extensive
    library of over 45,000 courses taught by expert instructors."
cite: |
    About Us. (2017). Udemy.  Retrieved April 15, 2017 from: https://about.udemy.com/
pub-date: 2017-04-15
added-date: 2017-04-15
resource-type: external-page
---


text:
package com.smartsheet.api.models.enums;

/**
 * Represents the system column types.
 * @see Column Types Help
 */
public enum SystemColumnType {
    /**
     * Represents the AUTO_NUMBER system column type.
     */
    AUTO_NUMBER,

    /**
     * Represents the MODIFIED_DATE system column type.
     */
    MODIFIED_DATE,

    /**
     * Represents the MODIFIED_BY system column type.
     */
    MODIFIED_BY,

    /**
     * Represents the CREATED_DATE system column type.
     */
    CREATED_DATE,

    /**
     * Represents the CREATED_BY system column type.
     */
    CREATED_BY;

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<protected-elements>

    <protected-element name="add-users">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-users">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="edit-users">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="create-users">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="delete-users">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="search-users">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="change-user-password">
        <role name="RegisteredUser"/>
        <role name="Guest"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-groups">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-messages">
        <role name="RegisteredUser"/>
        <role name="Guest"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="delete-messages">
        <role name="RegisteredUser"/>
        <role name="Guest"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="read-messages">
        <role name="RegisteredUser"/>
        <role name="Guest"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-contact-requests">
        <role name="RegisteredUser"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="review-contact-requests">
        <role name="RegisteredUser"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="delete-contact-requests">
        <role name="RegisteredUser"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="request-contact">
        <role name="RegisteredUser"/>
        <role name="Guest"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="adjust-preferences">
        <role name="RegisteredUser"/>
        <role name="Guest"/>
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-roles">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-protected-elements">
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-security-policy">
        <role name="Administrator"/>
        <role name="Guest"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="deploy-application">
        <role name="Administrator"/>
        <role name="SuperAdministrator"/>
    </protected-element>

    <protected-element name="list-deployments">
        <role name="Administrator"/>
        <role name="RegisteredUser"/>
        <role name="Guest"/>
        <role name="SuperAdministrator"/>
    </protected-element>

</protected-elements>


text:
package com.gu.mobile.notifications.football.lib

import java.util.UUID

import com.gu.mobile.notifications.client.models.NotificationPayload
import com.gu.mobile.notifications.football.{Configuration, Logging}
import okhttp3._
import play.api.libs.json._

import scala.util.{Failure, Success, Try}
import scala.util.control.NonFatal

case class Response(id: String)
object Response {
  implicit val responseJF: Reads[Response] = Json.reads[Response]
}

class NotificationsApiClient(config: Configuration) extends Logging {
  private val client = new OkHttpClient.Builder()
    .retryOnConnectionFailure(true)
    .build()

  def send(notification: NotificationPayload): Either[String, UUID] = {
    val url = s"${config.notificationsHost}/push/topic"

    val mediaType = MediaType.parse(s"application/json; charset=utf-8")
    val authHeader = s"Bearer ${config.notificationsApiKey}"
    val body = RequestBody.create(mediaType, Json.toBytes(Json.toJson(notification)))
    val request = new Request.Builder()
      .url(url)
      .header("Authorization", authHeader)
      .post(body)
      .build()

    val result = Try(client.newCall(request).execute()).map { response =>
      val status = response.code
      val responseBody = response.body.string()

      if (status >= 200 && status < 300) {
        parse(responseBody) match {
          case Some(id) => Right(id)
          case None => Left(s"Notification was sent but unable to parse the response. Got status $status and body $responseBody")
        }

      } else {
        Left(s"Unable to send notification, got status $status and body $responseBody")
      }
    }

    result match {
      case Success(value) => value
      case Failure(NonFatal(e)) =>
        logger.error("Unable to send notification", e)
        Left(s"Unable to send notification: ${e.getMessage}")
      case Failure(_) =>
        logger.error("Unable to send notification")
        Left(s"Unable to send notification")
    }
  }

  def parse(response: String): Option[UUID] = {
    def toUUID(idAttribute: JsValue): Option[UUID] = idAttribute match {
      case JsString(id) => Some(UUID.fromString(id))
      case _ => None
    }

    val parsed = Json.parse(response)
    parsed match {
      case JsObject(attributes) => attributes.get("id").flatMap(toUUID)
      case _ => None
    }
  }

}


text:
self.addEventListener('install', evt => {
    console.log('Service worker installed');
});

// activate event
self.addEventListener('activate', evt => {
    console.log('Service worker activated');
});

// fetch event
self.addEventListener('fetch', evt => {
    console.log('Service worker fetched', evt);
});


text:
import "./shared1";
import "./common1";

it("should be able to load the split chunk on demand (shared)", () => {
	return import(/* webpackChunkName: "theName" */ "./shared2");
});

it("should be able to load the split chunk on demand (common)", () => {
	return Promise.all([
		import(/* webpackChunkName: "otherName1" */ "./common2"),
		import(/* webpackChunkName: "otherName2" */ "./common3")
	]);
});


text:
#include "../common.h"
#include "pt.h"

#include <linux/perf_event.h>
#include <inttypes.h>

#include "../log.h"
#include "../util.h"

#ifdef _HF_LINUX_INTEL_PT_LIB

#include <intel-pt.h>

/*
 * Copyright (c) 2013-2016, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  * Neither the name of Intel Corporation nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/* Keeping track of the last-ip in Intel PT packets. */
struct pt_last_ip {
    /* The last IP. */
    uint64_t ip;

    /* Flags governing the handling of IP updates and queries:
     *
     * - we have seen an IP update.
     */
    uint32_t have_ip:1;
    /* - the IP has been suppressed in the last update. */
    uint32_t suppressed:1;
};

inline static void pt_last_ip_init(struct pt_last_ip *last_ip)
{
    if (!last_ip)
        return;

    last_ip->ip = 0ull;
    last_ip->have_ip = 0;
    last_ip->suppressed = 0;
}

inline static int pt_last_ip_query(uint64_t * ip, const struct pt_last_ip *last_ip)
{
    if (!last_ip)
        return -pte_invalid;

    if (!last_ip->have_ip) {
        if (ip)
            *ip = 0ull;
        return -pte_noip;
    }

    if (last_ip->suppressed) {
        if (ip)
            *ip = 0ull;
        return -pte_ip_suppressed;
    }

    if (ip)
        *ip = last_ip->ip;

    return 0;
}

/* Sign-extend a uint64_t value. */
inline static uint64_t sext(uint64_t val, uint8_t sign)
{
    uint64_t signbit, mask;

    signbit = 1ull << (sign - 1);
    mask = ~0ull << sign;

    return val & signbit ? val | mask : val & ~mask;
}

inline static int pt_last_ip_update_ip(struct pt_last_ip *last_ip,
                                       const struct pt_packet_ip *packet,
                                       const struct pt_config *config)
{
    (void)config;

    if (!last_ip || !packet)
        return -pte_invalid;

    switch (packet->ipc) {
    case pt_ipc_suppressed:
        last_ip->suppressed = 1;
        return 0;

    case pt_ipc_sext_48:
        last_ip->ip = sext(packet->ip, 48);
        last_ip->have_ip = 1;
        last_ip->suppressed = 0;
        return 0;

    case pt_ipc_update_16:
        last_ip->ip = (last_ip->ip & ~0xffffull)
            | (packet->ip & 0xffffull);
        last_ip->have_ip = 1;
        last_ip->suppressed = 0;
        return 0;

    case pt_ipc_update_32:
        last_ip->ip = (last_ip->ip & ~0xffffffffull)
            | (packet->ip & 0xffffffffull);
        last_ip->have_ip = 1;
        last_ip->suppressed = 0;
        return 0;

    case pt_ipc_update_48:
        last_ip->ip = (last_ip->ip & ~0xffffffffffffull)
            | (packet->ip & 0xffffffffffffull);
        last_ip->have_ip = 1;
        last_ip->suppressed = 0;
        return 0;

    case pt_ipc_full:
        last_ip->ip = packet->ip;
        last_ip->have_ip = 1;
        last_ip->suppressed = 0;
        return 0;
    }

    return -pte_bad_packet;
}

inline static void perf_ptAnalyzePkt(honggfuzz_t * hfuzz, fuzzer_t * fuzzer,
                                     struct pt_packet *packet, struct pt_config *ptc,
                                     struct pt_last_ip *last_ip)
{
    switch (packet->type) {
    case ppt_tip:
    case ppt_fup:
    case ppt_tip_pge:
    case ppt_tip_pgd:
        break;
    default:
        return;
    }

    int errcode = pt_last_ip_update_ip(last_ip, &(packet->payload.ip), ptc);
    if (errcode < 0) {
        LOG_F("pt_last_ip_update_ip() failed: %s", pt_errstr(errcode));
    }

    /* Update only on TIP, other packets don't indicate a branch */
    if (packet->type == ppt_tip) {
        uint64_t ip;
        errcode = pt_last_ip_query(&ip, last_ip);
        if (errcode == 0) {
            ip &= _HF_PERF_BITMAP_BITSZ_MASK;
            register uint8_t prev = ATOMIC_BTS(hfuzz->feedback->bbMapPc, ip);
            if (!prev) {
                fuzzer->linux.hwCnts.newBBCnt++;
            }
        }
    }
    return;
}

void arch_ptAnalyze(honggfuzz_t * hfuzz, fuzzer_t * fuzzer)
{
    struct perf_event_mmap_page *pem = (struct perf_event_mmap_page *)fuzzer->linux.perfMmapBuf;

    struct pt_config ptc;
    pt_config_init(&ptc);
    ptc.begin = &fuzzer->linux.perfMmapAux[pem->aux_tail];
    ptc.end = &fuzzer->linux.perfMmapAux[pem->aux_head - 1];

    int errcode = pt_cpu_errata(&ptc.errata, &ptc.cpu);
    if (errcode < 0) {
        LOG_F("pt_errata() failed: %s", pt_errstr(errcode));
    }

    struct pt_packet_decoder *ptd = pt_pkt_alloc_decoder(&ptc);
    if (ptd == NULL) {
        LOG_F("pt_pkt_alloc_decoder() failed");
    }
    defer {
        pt_pkt_free_decoder(ptd);
    };

    errcode = pt_pkt_sync_forward(ptd);
    if (errcode < 0) {
        LOG_W("pt_pkt_sync_forward() failed: %s", pt_errstr(errcode));
        return;
    }

    struct pt_last_ip last_ip;
    pt_last_ip_init(&last_ip);
    for (;;) {
        struct pt_packet packet;
        errcode = pt_pkt_next(ptd, &packet, sizeof(packet));
        if (errcode == -pte_eos) {
            break;
        }
        if (errcode < 0) {
            LOG_W("pt_pkt_next() failed: %s", pt_errstr(errcode));
            break;
        }
        perf_ptAnalyzePkt(hfuzz, fuzzer, &packet, &ptc, &last_ip);
    }
}

#else                           /* _HF_LINUX_INTEL_PT_LIB */

void arch_ptAnalyze(honggfuzz_t * hfuzz UNUSED, fuzzer_t * fuzzer UNUSED)
{
    LOG_F
        ("The program has not been linked against the Intel's Processor Trace Library (libipt.so)");
}

#endif                          /* _HF_LINUX_INTEL_PT_LIB */


text:
/**
 * @module node-opcua-address-space
 */
export { AddressSpace } from "./address_space";
export * from "../source/session_context";
export * from "../source/helpers/dump_tools";
export * from "../source/helpers/adjust_browse_direction";
export * from "../source/pseudo_session";
export * from "../source/helpers/make_optionals_map";
export * from "../source/helpers/check_event_clause";
export * from "../source/helpers/argument_list";
export * from "../source/helpers/call_helpers";
export * from "../source/helpers/ensure_secure_access";
export * from "../source/interfaces/alarms_and_conditions/condition_info_i";
export { UACertificateExpirationAlarm }  from "./alarms_and_conditions";
export { ensureDatatypeExtractedWithCallback } from "../source/loader/load_nodeset2";
export {ContinuationPointManager } from "../source/continuation_points/continuation_point_manager";

export { generateAddressSpace } from "../source";
export { promoteToStateMachine } from "./state_machine/finite_state_machine";

export * from "./namespace";
export * from "./base_node";
export * from "./extension_object_array_node";
export * from "./event_data";

export { NamespaceOptions } from "./namespace";
export { dumpXml } from "./nodeset_to_xml";
export * from "./data_access/ua_analog_item";
export * from "./data_access/ua_data_item";
export * from "./data_access/ua_multistate_discrete";
export * from "./data_access/ua_mutlistate_value_discrete";
export * from "./alarms_and_conditions/condition_info";
export * from "../test_helpers";
export { VariableHistorian } from "./historical_access/address_space_historical_data_node";


text:
import * as FrontendHelpers from '../../../../../test/unittests/front_end/helpers/EnvironmentHelpers.js';
import * as ComponentHelpers from '../../helpers/helpers.js';
import * as TextEditor from '../../text_editor/text_editor.js';

await ComponentHelpers.ComponentServerSetup.setup();
await FrontendHelpers.initializeGlobalVars();

const component = new TextEditor.TextEditor.TextEditor();

document.getElementById('container')?.appendChild(component);


text:
<?php
/**
 * Report to show pages scheduled to be deleted
 *
 * @package cmsworkflow
 * @subpackage reports
 */
class PagesScheduledForDeletionReport extends SS_Report
{
    public function title()
    {
        return _t('PagesScheduledForDeletionReport.TITLE', "Published pages with Expiry on");
    }

    public function parameterFields()
    {
        $params = new FieldSet();

        $params->push($startDate = Object::create('DatetimeField', 'StartDate', 'Start date'));
        $params->push($endDate = Object::create('DatetimeField', 'EndDate', 'End date'));
        $startDate->getTimeField()->setValue('23:59:59');
        $endDate->getTimeField()->setValue('23:59:59');

        return $params;
    }

    public function columns()
    {
        $fields = array(
            "Title" => array(
                "title" => "Page name",
                'formatting' => '$value'
            ),
            'ExpiryDate' => array(
                'title' => 'Will be deleted at',
                'casting' => 'SS_Datetime->Full'
            ),
            'ApproverName' => 'Approver',
            'AbsoluteLink' => array(
                'title' => 'URL',
                'formatting' => '$value " . ($AbsoluteLiveLink ? "(live)" : "") . " (draft) (view site on expiry date)'
            ),
            "BacklinkCount" => array(
                "title" => "Incoming links",
                'formatting' => '".($value ? "yes, $value" : "none") . "',
                'csvFormatting' => '".($value ? "yes" : "no") . "'
            ),
        );

        return $fields;
    }

    public function sourceRecords($params, $sort, $limit)
    {
        increase_time_limit_to(120);

        // Emulate Form->loadDataFrom()
        $fields = $this->parameterFields();
        foreach ($fields as $field) {
            if (isset($params[$field->Name()])) {
                $val = $params[$field->Name()];
                if ($val) {
                    $field->setValue($val);
                }
            }
        }

        $wheres = array();
        $startDate = !empty($params['StartDate']) ? $params['StartDate'] : null;
        $endDate = !empty($params['EndDate']) ? $params['EndDate'] : null;

        if ($startDate) {
            $startDate = $fields->dataFieldByName('StartDate')->dataValue();
        }
        if ($endDate) {
            $endDate = $fields->dataFieldByName('EndDate')->dataValue();
        }

        if ($startDate && $endDate) {
            $wheres[] = "\"ExpiryDate\" >= '".Convert::raw2sql($startDate)."' AND \"ExpiryDate\" <= '".Convert::raw2sql($endDate)."'";
        } elseif ($startDate && !$endDate) {
            $wheres[] = "\"ExpiryDate\" >= '".Convert::raw2sql($startDate)."'";
        } elseif (!$startDate && $endDate) {
            $wheres[] = "\"ExpiryDate\" <= '".Convert::raw2sql($endDate)."'";
        } else {
            $wheres[] = "\"ExpiryDate\" >= '".SS_Datetime::now()->URLDate()."'";
        }

        $stage = Versioned::current_stage();
        Versioned::reading_stage('Live');

        $query = singleton("SiteTree")->extendedSQL(join(' AND ', $wheres), null, null,
            'LEFT JOIN "WorkflowRequest" on "WorkflowRequest"."ID" = "SiteTree_Live"."LatestCompletedWorkflowRequestID"'
        );

        $query->from[] = "LEFT JOIN \"Member\" AS \"Approver\" ON \"WorkflowRequest\".\"ApproverID\" = \"Approver\".\"ID\"";
        $query->select[] = Member::get_title_sql('Approver').' AS "ApproverName"';

        $join = '';
        if ($sort) {
            $parts = explode(' ', $sort);
            $field = $parts[0];
            $direction = $parts[1];

            if ($field == 'AbsoluteLink') {
                $sort = '"URLSegment" ' . $direction;
            }

            if ($field == 'Subsite.Title') {
                $query->from[] = 'LEFT JOIN "Subsite" ON "Subsite"."ID" = "SiteTree"."SubsiteID"';
            }

            if ($field == 'BacklinkCount') {
                $query->select[] = '(SELECT COUNT(*) FROM "SiteTree_LinkTracking" WHERE "SiteTree_LinkTracking"."ChildID" = "SiteTree"."ID") AS "BacklinkCount"';
            }
        }

        // Turn a query into records
        if ($sort) {
            $query->orderby = $sort;
        }

        // Postgres and MSSQL require these fields in the groupby[] array:
        $query->groupby[]="\"Approver\".\"Surname\"";
        $query->groupby[]="\"Approver\".\"FirstName\"";

        $records = singleton('SiteTree')->buildDataObjectSet($query->execute(), 'DataObjectSet', $query);

        Versioned::reading_stage($stage);

        // Backwards compat method signature with 2.4
        $fn = (method_exists('SiteTree', 'prepopulate_permission_cache')) ? 'prepopulate_permission_cache' : 'prepopuplate_permission_cache';
        if ($records) {
            SiteTree::$fn('edit', $records->column('ID'));
        }

        // Filter to only those with canEdit permission
        $filteredRecords = new DataObjectSet();
        if ($records) {
            foreach ($records as $record) {
                $record->BacklinkCount = $record->DependentPagesCount(false);
                if (class_exists('Subsite')) {
                    $record->PageDomain = $record->Subsite()->absoluteBaseURL();
                } else {
                    $record->PageDomain = Director::absoluteBaseURL();
                }
                if ($record->canEdit()) {
                    $filteredRecords->push($record);
                // Add any related pages to the list as well to ensure authors
                // can review what they're actually scheduling
                $virtualPages = $record->VirtualPages();
                    if ($virtualPages) {
                        foreach ($virtualPages as $virtualPage) {
                            // Simulate custom SQL fields from WorkflowRequest join
                    $virtualPage->ExpiryDate = $record->ExpiryDate;
                            $virtualPage->ApproverName = $record->ApproverName;
                            $filteredRecords->push($virtualPage);
                        }
                    }
                }
            }
        }

        // Apply limit after that filtering.
        if ($limit && $limit['limit']) {
            return $filteredRecords->getRange($limit['start'], $limit['limit']);
        } else {
            return $filteredRecords;
        }
    }
}


text:
    <meta content='text/html;charset=UTF-8' http-equiv='Content-Type' />
    <title>buildr — {{ page.title }}</title>

    <meta content='Official Buildr documentation from the people in the know' name='subject' />
    <link href='images/favicon.png' rel='shortcut icon' />

Start Here

Welcome

Download

User Guide (PDF)

Community Wiki

Using Buildr

Getting Started

Projects

Building

Artifacts

Packaging

Testing

Settings/Profiles

Languages

More Stuff

Extending Buildr

How-Tos

Reference

API

Rake

Antwrap

Troubleshooting

Get Involved

Mailing Lists

Issues/Bugs

Contributing

Specs

Coverage

        <form action='http://www.google.com/cse' id='searchbox_003673095760649043902:ogcgrzu0l2y'>
          <input name='cx' type='hidden' value='003673095760649043902:ogcgrzu0l2y' />
          <input name='cof' type='hidden' value='FORID:0' />
          <input name='q' size='20' type='text' />
          <input name='sa' type='submit' value='Search' />

        </form>

{{ page.title }}

        {{ content | toc }}
        {{ content }}

Copyright © 2007-2009 The Apache Software Foundation


text:
layout: post
title:  "Using Jekyll _includes as custom liquid functions"
author: Hamish Willee
description: This post shows how you can use files in the Jekyll **_includes** directory to implement function-like behaviour.
tags:
- jekyll
---

{{ page.description}}

## Introduction

One of the frustrating limitations of [Liquid](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers) (Jekyll's templating language) is that there is no obvious way to declare your own functions. As a result, when you get started with Jekyll you may find yourself repeating blocks of template code, and even deciding that some actions are simply too complicated to safely implement without a plugin.

This was the problem I had when implementing the table of contents (TOC) on my Jekyll-bootstrap documentation theme. Without functions, traversing a nested YAML list to create the TOC HTML would result in progressively complicated and unmaintainable code for every level of nesting required.

What may not be obvious at first glance is that you can use Jekylls [includes](http://jekyllrb.com/docs/templates/#includes) as functions, passing in parameters and "returning" either text or variables for use in other functions. You can even include files recursively.

## How does it work?

### Creating the function

"Functions" are simply files, typically with the extension **.html**, in the site **_includes** directory (or a subdirectory of that folder). These can contain any HTML, markup, or [Liquid code](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers).

### Calling the function

You call the function to include the contents of the file using the ```include``` tag as shown:

{% highlight liquid %}
{% raw %}
{% include your_function.html %}
{% endraw %}
{% endhighlight %}

### Passing in parameters

If you need to pass in parameters you can do that too. The fragment below shows how you might pass in a string ```"a value"``` and a variable ```variable_name```.

{% highlight liquid %}
{% raw %}
{% include your_function.html some_parameter="a value" another_parameter=variable_name %}
{% endraw %}
{% endhighlight %}

Within the file you can access those parameters using ```{% raw %}{{ include.some_parameter }}{% endraw %}``` and ```{% raw %}{{ include.another_parameter }}{% endraw %}``` respectively.

The parameters can be considered to be static const - they can't be changed within the function and you can't use them to return values.

### Return values

The "return value" of the function is whatever text you output, i.e. a string.

Sometimes you will want to further process the output of a function. In this case you can use the [Liquid capture tag](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers#variable-assignment) to assign the result of the function to a variable, and then run standard filters on it.

You cannot return an "array" or any other variable than a string.

If you need to do so, then convert the variable into some string format that you can then capture and reconvert into variable in the caller.

## A real example

The [Jekyll-bootstrap documentation theme](http://hamishwillee.github.io/jekyll-bootstrap-docsite/) defines a table of contents using a YAML list with an arbitrarily deep nesting structure. Each level of the list can specify a ```url``` to a document or external site (with an optional ```name```) or a ```folder``` name, which contains other urls and/or folders.

A simple example of a structure with a nested folder is given below.

{% highlight yaml %}
- folder: A folder
  contents:
   - url: /somepath/anydoc.html
   - url: /anypath/anotherdoc.html

   - folder: Nested Folder
     contents:
      - url: /anypath/anydoc1.html
      - url: /anypath/anydoc2.html

- folder: Another (peer) folder
  contents:
   - url: /anypath/anydoc3.html
     name: TOC defined name

- url: /anypath/anydoc4.html
{% endhighlight %}

In order to open up the menu to the correct place when a page is loaded we need to mark its parent folder nodes as open in the HTML. Unfortunately this means that we need to iterate the structure twice: once to determine the breadcrumb of folders to the current article, and again to build the TOC using this information.

The function we use for the first iteration is [/_includes/functions/f_navtree_open.html](https://github.com/hamishwillee/jekyll-bootstrap-docsite/blob/gh-pages/_includes/functions/f_navtree_open.html). The function is initially called with the TOC for the whole menu as a parameter.

{% highlight liquid %}
{% raw %}

{% for navitem in include.theTOC %}

  {% if navitem.folder %}

    {% capture iterfolders %}{% if include.folders %}{{include.folders}},{% endif %}{{navitem.folder}}{% endcapture %}

    {% if navitem.contents %}
      {% include /functions/f_navtree_open.html theTOC=navitem.contents folders=iterfolders %}
    {% endif %}

  {% elsif navitem.url %}
    {% if page.url == navitem.url %}{{include.folders}}{% endif %}
  {% endif %}

{% endfor %}
{% endraw %}
{% endhighlight %}

The function iterates through the items in the first level of the passed TOC (```include.theTOC```):

* If it encounters a folder, the function recursively calls itself to handle the next level of TOC. In this case the function is passed the TOC sub-tree and a comma separated list of all folders above the current point (```include.folders```).
* If it finds an URL that matches the current page, the function outputs the current value of ```{% raw %}{{include.folders}}{% endraw %}```. This is the "result" - a comma separated list of folders in the direct path above the current article.

The function is used in [/_includes/sidebar_tree.html](https://github.com/hamishwillee/jekyll-bootstrap-docsite/blob/gh-pages/_includes/sidebar_tree.html) as shown below:

{% highlight liquid %}
{% raw %}
{% capture openfolder_array %}{% include /functions/f_navtree_open.html theTOC=toc %}{% endcapture %}
{% assign openfolder_array = openfolder_array | strip_newlines | split: "," %}
{% include /functions/f_navtree.html theTOC=toc outer='true' opentree =openfolder_array %}
{% endraw %}
{% endhighlight %}

First the function block is run within a ```capture``` block with the full TOC. The capture block assigns the returned comma separated list of folders (simply a string) to the ```openfolder_array``` variable. The variable is then stripped of newlines and split into an ```array``` object, and then ```assign```ed to the same variable name. Finally, the array is passed to the [/functions/f_navtree.html](https://github.com/hamishwillee/jekyll-bootstrap-docsite/blob/gh-pages/_includes/functions/f_navtree.html) where is is used to build the TOC.

## Tips

#### *Liquid* does not provide tags to allow you to dynamically build arrays.

Use the [split](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers#standard-filters) function to split up a string to create an array. This approach is used above to turn the folder names list into an array/list so that it can be iterated.

#### Comments, space and newlines in functions are part of the output.

Whatever code or comments, or even whitespace you put in a function will become part of the output HTML. Often this is fine, but if you want to further parse the content, this can result in unpredictable output.

In functions where it matters omit all comments, left align all the rows, and remove spaces. You will still have line breaks, but these can be stripped using a filter.

#### strip_html just removes the tags

Stripping HTML removes the tags, but not the contained content. Unfortunately you can't use HTML stripping to remove comments before displaying your function output!

#### Parameters are "static const"

Parameters passed into a function (```include.param```) cannot be modified in the function.

#### Scope is unclear - reset your temporaries

The scope of variables is a little unclear to me. I've found it "good practice" to reset temporary variables used in my functions before using them.

## Summary

Using *includes* as functions can allow you to perform quite complicated calculations in liquid, without having to resort to plugins.


text:
**If** you use [Alfred](http://alfredapp.com), [LaunchBar](http://www.obdev.at/products/launchbar/index.html), [QuickSilver](http://qsapp.com/) or other similar products (and if you don't, you really should!), then you already know what this is all about.

**Else, if** you haven't and you are at least familiar with "Open Quickly" (default CMD+Shift+O), then you also know what this is all about -- it's like "Open Quickly" but for all menu bar actions, code snippets, unit tests, custom built-in actions that can operate on text or any other kind of custom action you'd like (just as long as you implement it)

**Else** Read along ... :)

###Demo:

Sorting lines demo:
![image](demo.gif)

Built-in __Add Prefix to Line(s)__ and __Add Suffix to Line(s)__ demo:
![image](demo2.gif)

Built-in __Surround With NSNumber Literal__ and __Surround With NSString Literal__ demo:
![image](demo3.gif)

###Motivation:

I always try to accomplish as much as I possibly can without ever moving my hands away from the keyboard, there's simply no other means of input that feels quite as natural or efficient.
Shortcuts are great, but there's only so many combinations of keys the average person can memorize. On top of that, the more shortcuts you have, the more likely you are to have to rely on multiple modifier key combinations, which may not always make them very comfortable to type.

It's much simpler and natural to type commands that actually describe what you want to achieve. I'm sure most people will agree that it's quicker to type `fold` or `unfold`than it is to type a four-key shortcut (which is basically as long as typing `fold`and probably doesn't feel as natural).

Note: This is preliminary documentation as this is very much work in progress.

###What can it do?

Here's the executive summary in three simple examples:

Example #1: Built in actions

1. Place the carret on the line you'd like to move up
2. Double tap `CMD` or press `CMD+SHIFT+8`
3. Type `m l u`
4. Return
5. Double tap `ALT` or press `CMD+ALT+7` to repeat the last action as many times as you'd like (this works for any action)

Example #2: Custom actions

1. Select a block of text
2. Double tap `CMD` or press `CMD+SHIFT+8`
3. Type `nsl`
4. Return

Notice as the selected block of text is automatically surrounded with `NSLog(@"your text selection")`
Hint: type `surround` for a list of available "Surround Text With" actions

Example #3: Code snippets

1. Place the carret where you'd like to expand the snippet
2. Double tap `CMD` or press `CMD+SHIFT+8`
3. Type `inline`
4. Select `C inline block as variable`
5. [fuckingblocksyntax.com](fuckingblocksyntax.com) suddenly becomes less necessary

Hopefully these short examples showcase some of the features **XCActionBar** currently supports.
I'll continue adding features and making things generally better, so expect lots of changes in the coming weeks.

### Searching

Action search currently operates on a few data sets:

* Menu Bar items and sub-items (recursively)
* Code snippet library (system and user-defined)
* Custom plugin vended actions

The current searching strategy is very simple and naive but does the job quite effectively. While it doesn't yet support fuzzy matching, it's quite flexible in how it handles partial matches. Take a look at the examples above for a few examples. I'll be working on improving this very soon, but at this stage it does seem to be quite effective.

To bring up the action bar, type in the default shortcut `CMD+SHIFT+8` and enter your search terms. After performing an action, you can repeat it by typing in the repeat command shortcut `CMD+ALT+7`.

**UPDATED**:
* You can now present/dismiss the acion bar by simply double pressing `CMD` quickly
* You can now repeat the last executed action by simply double pressing `ALT`

The original shortcuts still work. I've also added a general configuration file `XCSurroundWithActions` which can be used to tweak these two shortcuts -- currently it only supports the following:

```
NSAlternateKeyMask
NSCommandKeyMask
NSControlKeyMask
NSFunctionKeyMask
NSShiftKeyMask
```

This is all very much experimental so do expect changes.

### Actions

As mentioned above, the plugin comes bundled with a few custom actions. Following is a catalog of all of them and a short summary of what they do:

* `XCAddPrefixToLinesAction` **prepends** the string contents of the pasteboard to each selected line
* `XCAddSuffixToLinesAction` **appends** the string contents of the pasteboard to each selected line
* `XCCopyActiveDocumentFilePathAction` *copies* the active file path to the pasteboard. Supports `file://`, `POSIX` and `POSIX escaped` (useful for copying to the terminal)
* `XCCopyActiveDocumentDirectoryAction` *copies* the active file directory to the pasteboard. Supports `file://`, `POSIX` and `POSIX escaped` (useful for copying to the terminal)
* `XCDeleteBlankLinesAction` **deletes** all empty strings in the selected range
* `XCDeleteLineAction` deletes the line the carret is currently positioned in
* `XCDuplicateLineAction` duplicates the line the carret is currently positioned in, or the selected lines
* `XCSortSelectionAction` performs line sorting (ascending or descending) of the selected lines
* `XCSurroundWithAction` surrounds the selected text block with an arbitrary prefix/suffix
* `XCSurroundLineWithAction` surrounds each selected line with an arbitrary prefix/suffix
* `XCTrimWhitespaceAction` trims whitespace for each selected line (supports leading; trailing or both)

* `XCOpenActiveDocumentPathInTerminalAction` opens the active document's directory in the terminal app (currently supports `iTerm.app` and `Terminal.app` but more can be added in `XCActionBarConfiguration.plist` under `XCSupportedTerminalApplications`

I've bundled a few `XCSurroundLineWithAction` and `XCSurroundWithAction`S:

* Autorelease pool `@autoreleasepool { ... }`
* Square Brackets `[ ... ]`
* Curly Braces `{ ... }`
* Inline Block `void (^BlockVariable)(void) = ^{ ... }`
* NSLog `NSLog(@" ... ")`
* NSNumber `@( ... )`
* NSString `@" ... "`
* NSStringWithFormat `[NSString stringWithFormat:...]`
* Parenthesis `( ... )`
* Audit Non-null region `NS_ASSUME_NONNULL_BEGIN ... NS_ASSUME_NONNULL_END`
* Pragma diagnostic region
* Double Quotes `" ... "`
* Single Quotes `' ... '`
* Try/Catch `@try{ ...} catch(NSException *exception) {}`
* While `While(expression) { ... }`
* Do/While `do { ... } while(expression)`

There's also a very __meta__ action called `XCSurroundWithSnippetAction` that surrounds the selected block of the with a snippet from the library. There are some caveats though:
* the snippet will only show up on the list if it contains at least one `<# Token #>` (otherwise we wouldn't know what would be the prefix/suffix)
* the **first** `<# Token #>` is replaced by the selected block of text

Similarly, you use `XCSurroundWithTextSnippetAction` to perform the same action as above, with the difference that it uses a text snippet from the pasteboard, meaning you can do ad-hoc surround operations without having to create a new snippet.

Just type `surr` in the action bar to get a list of all available actions.

Note: currently none of these perform any character escaping
Some of the don't really make much sense when applied to **each line** so I might strip some out in the future

Continue reading for more details on how to add your own custom actions.

### Extensibility

There are quite a lot of ideas floating around regarding extensibility, but for a first-pass implementation there's at least a little bit you can play with, in the form of `SurroundWith` actions. These are currently managed by an external property list file named `XCSurroundWithActions.plist` which can be found in the plugin's resource folder.
You're free to add your own entries or remove the stuff you don't need.

The format for each entry is a simple dictionary with the following keys:

* `XCSurroundWithActionIdentifier` a unique string identifier for the action
* `XCSurroundWithActionTitle` the action's title, displayed in the action bar
* `XCSurroundWithActionSummary` additional info that shows in the action bar's subtitle field
* `XCSurroundWithActionPrefix` the block of text that's prepended to the text you want to surround
* `XCSurroundWithActionSuffix` the block of text that's appended to the text you want to surround

If you're feeling more adventurous you can currently specify arbitrary actions by subclassing `XCCustomAction`. This is still very much in _flux_ in terms of design and is likely to change in the future, but the way this currently works is:

When you select an action from the search results list, ultimately the `- (BOOL)executeAction:(id<XCIDEContext>)context` action's method will be invoked. The `context` object provides some information about the current IDE state (active source code document, current text selection range, etc.) which is currently mostly useful for actions that need to manipulate text (pretty much all of them at the time of writing). This may change in the future.

If you do choose to muck around and implement your own custom actions, the final step is to _register_ them. To do so, all you need to do is to add them to `XCActionBar.m` under `- (void)buildActionProviders`:

```objc
////////////////////////////////////////////////////////////////////////////////
// Built-in Actions
////////////////////////////////////////////////////////////////////////////////
NSMutableArray *textActions =
    @[
      // Duplicate/Delete Lines
      [[XCDeleteLineAction alloc] init],
      [[XCDuplicateLineAction alloc] init],

      // Sort Selection
      [[XCSortSelectionAction alloc] initWithSortOrder:NSOrderedAscending],
      [[XCSortSelectionAction alloc] initWithSortOrder:NSOrderedDescending],

      // Sort Contents
      [[XCSortContentsAction alloc] initWithSortOrder:NSOrderedAscending],
      [[XCSortContentsAction alloc] initWithSortOrder:NSOrderedDescending],

      // Add your custom action here
      ];
```

These actions don't yet show up in the menu bar, but they will get automatically indexed by the plugin. Soon you'll be able to manage custom actions and their groupings via an external property list file which will also be used to derive action groups under the menu bar, so stay tuned.

### Setup - Using custom shortcuts

The default hotkey to bring up Action Bar is `CMD+SHIFT+8`.
You can change this hotkey via the _Keyboard Shortcuts_ Panel in the System Preferences.

* Open System Preferences
* Go to `Keyboard`
* Switch to the `Shortcuts` tab
* Select `App Shortcuts` and click the `+` Button.
    * Select `Xcode.app`
    * Enter `Action Bar` as Menu Title
    * Enter the Shortcut you want

![image](custom_hotkey.png)

Alternatively you can use (my preferred) shortcuts:
* Double press the `CMD` key to present/dismiss the bar
* Double press the `ALT` key to repeat the last action

These can also be customized but required a slightly more involved (but simple) process:
* Find and open the file `XCActionBarConfiguration.plist` under the plugin installation folder (`Library/Application Support/Developer/Shared/Xcode/Plug-ins/XCActionBar.xcplugin/Contents/Resources`)
* Under the `Shortcuts` key you'll find `XCActionBarHotKey` and `XCRepeatLastActionHotKey`
* Tweak the values to your preferences

Here's a quick explanation of the configuration keys:

* `XCHotKeyListenerHotKeyMask` specifies the modifier key mask. Possible values are (declared in `NSEvent.h`):
    * `NSAlternateKeyMask`
    * `NSCommandKeyMask`
    * `NSControlKeyMask`
    * `NSFunctionKeyMask`
    * `NSShiftKeyMask`

Just use the enum's value (for example `NSCommandKeyMask = 1 << 20`, so you'd use `1048576`)
Please note that while these are bitmasks, **XCActionBar** currently only supports the definition of **one** key, so attempting to setup something like `NSAlternateKeyMask | NSCommandKeyMask` **won't work**.

* `XCHotKeyListenerRepeatCount` specifies the number of required key presses (currently only supports `2` or `3`)
* `XCHotKeyListenerRepeatDelay` specifies the maximum delay that can occur between the keypresses for the shortcut to trigger - tweak this if you feel the defaults are too sensitive for you

Feedback is greatly appreciated -- love it? hate it? suggestions? I'd love to hear about it!

Cheers,
Pedro.


text:
package com.taobao.tae.buyingdemo.model;

import java.io.Serializable;

public class CategoryDO implements Serializable {

    private int id;
    /*标题*/
    private String name;

    /*父分类ID*/
    private int father;

    /*分类图标*/
    private String pic;

    /*分类展示序号*/
    private int sequence;

    /*创建时间*/
    private String gmtCreated;

    /*修改时间*/
    private String gmtModified;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getFather() {
        return father;
    }

    public void setFather(int father) {
        this.father = father;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public int getSequence() {
        return sequence;
    }

    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    public String getGmtCreated() {
        return gmtCreated;
    }

    public void setGmtCreated(String gmtCreated) {
        this.gmtCreated = gmtCreated;
    }

    public String getGmtModified() {
        return gmtModified;
    }

    public void setGmtModified(String gmtModified) {
        this.gmtModified = gmtModified;
    }
}


text:
/**
 *   \file array.h
 *   \author Adapted by Lukas Habegger (lukas.habegger@yale.edu)
 */

#ifndef DEF_ARRAY_H
#define DEF_ARRAY_H

/* #define ARRAY_CHECK either here or in a single file to
   check the bounds on arru() and arrp() calls
   if defined here can be removed from specific C files by defining
   ARRAY_NO_CHECK
*/

/* #define ARRAY_CHECK */

/**
 * Array.
 */
typedef struct ArrayStruct
{ char* base ;    // char* since need to do pointer arithmetic in bytes
  int   dim ;     // length of alloc'ed space
  int   size ;
  int   max ;     // largest element accessed via array() -1
} *Array ;

/* NB we need the full definition for arru() for macros to work
   do not use it in user programs - it is private.
*/

extern Array   uArrayCreate (int n, int size) ;
extern void    uArrayDestroy (Array a) ;
extern char    *uArray (Array a, int index) ;
extern char    *uArrCheck (Array a, int index) ;
extern char    *uArrayCheck (Array a, int index) ;
extern char    *uArrPop(Array a) ;

/**
 * Create an Array of n elements having type type.
 */
#define arrayCreate(n,type)	uArrayCreate(n,sizeof(type))

/**
 * Destroy Array a.
 */
#define arrayDestroy(a)		((a) ? uArrayDestroy(a), a=NULL, 1 : 0)

/**
 * Return the number of elements in the array.
 */
#define arrayMax(ar)   ((ar)->max)

#if (defined(ARRAY_CHECK) && !defined(ARRAY_NO_CHECK))
#define arrp(ar,i,type)	((type*)uArrCheck(ar,i))
#define arru(ar,i,type)	(*(type*)uArrCheck(ar,i))
#define arrayp(ar,i,type)	((type*)uArrayCheck(ar,i))
#define array(ar,i,type)	(*(type*)uArrayCheck(ar,i))
#else
#define arru(ar,i,type)	((*(type*)((ar)->base + (i)*(ar)->size)))
#define arrp(ar,i,type)	(((type*)((ar)->base + (i)*(ar)->size)))
#define arrayp(ar,i,type)	((type*)uArray(ar,i))
#define array(ar,i,type)	(*(type*)uArray(ar,i))
#endif
/* only use arru()/arrp() when accessing an existing element */

extern Array  arrayCopy (Array a) ;
extern void   arrayMove(Array from, int start, int end, Array to) ;
extern void   arrayClear(Array a) ;

/* use with care -- arguments are evaluated twice (macro) */
#define arraySetMax(ar,j) (uArray(ar,j), (ar)->max = (j))

extern int arrayNumber(void) ;

/* JTM's package to hold sorted arrays of ANY TYPE, extended by Roche */
#define ARRAYORDERF int(*)(void *,void *)
#define arrayInsert(a,elem,order) arrayFindInsert(a,elem,NULL,order)
extern int     arrayFindInsert(Array a, void *s, int *ip, int (*order)(void*,void*));
extern int     arrayRemove(Array a, void * s, int (*order)(void*,void*));
extern int     arrayRemoveD(Array a,int i);
extern void    arraySort(Array a, int (*order)(void*,void*)) ;
extern int     arrayFind(Array a, void *s, int *ip, int (*order)(void*,void*));
extern int     arrayIsEntry(Array a, int i, void *s);
extern int     arrayStrcmp(char **s1, char **s2) ;
extern int     arrayIntcmp(int *ip1, int *ip2) ;
extern void    arrayByteUniq(Array a) ;
extern void    arrayUniq(Array a, Array b, int (*order)(void*,void*)) ;
extern int     arrayDoublecmp(double *dp1, double *dp2) ;

/* using an Array as a push/pop stack */
/* boundary checking: arrayTop() and arrayTopp() check for
   empty Array only if ARRAY_CHECK is in effect.
   arrayPop() always checks for stack underflow
*/

#define Stacka Array
#define stackCreate  arrayCreate
#define stackDestroy arrayDestroy
#define stackDepth    arrayMax
#define stackPush(a,elem,type)  (array(a,arrayMax(a),type)=(elem))
#define stackTopp(a,type)	(arrp(a,arrayMax(a)-1,type))
#define stackTop(a,type)	(arru(a,arrayMax(a)-1,type))
#define stackPop(a,type)        ((*(type*)uArrPop(a)))

#endif


text:
<!DOCTYPE HTML>

<title>All Classes</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2019-04-28">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="jquery/jquery-ui.css" title="Style">

All Classes

AbstractArmature

AbstractAxes

AbstractBone

AbstractBone.frameType

AbstractIKPin

AbstractKusudama

AbstractLimitCone

Armature

AxesExample

AxisDependancy

Basis

BoneExample

CanLoad

Constants

Constraint

DoubleDict

DoubleList

EulerLimits

ExampleRay

ExampleVector

FloatDict

FloatList

G

IKExceptions

IKExceptions.NullParentForBoneException

IKPinExample

IKVector

IntDict

Interpolation

Interpolation.Bounce

Interpolation.BounceIn

Interpolation.BounceOut

Interpolation.Elastic

Interpolation.ElasticIn

Interpolation.ElasticOut

Interpolation.Exp

Interpolation.ExpIn

Interpolation.ExpOut

Interpolation.Pow

Interpolation.PowIn

Interpolation.PowOut

Interpolation.Swing

Interpolation.SwingIn

Interpolation.SwingOut

IntList

JSONArray

JSONObject

JSONTokener

KusudamaExample

LimitCone

LongDict

LongList

MathUtils

Matrix3d

Matrix3f

Matrix4d

Matrix4f

MRotation

Precision

Quaternion

Quaternionf

RandomXS128

Rot

RotationOrder

SegmentedArmature

sgRay

SGVec_2d

SGVec_2f

SGVec_3d

SGVec_3f

Sort

StrandedArmature

StringDict

StringFuncs

StringList

TableRow

Vec

Vec2d

Vec2f

Vec3d

Vec3f

Vecd

Vecf

Vector


text:
package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

type ARFileHeader struct {
	Filename  string // Offset 0, up to 16 chars for short names.
	Timestamp string // Offset 16
	OwnerID   string // Offset 28
	GroupID   string // Offset 34
	FileMode  string // Offset 40
	FileSize  uint32 // Offset 48
}

func (h *ARFileHeader) String() string {
	return fmt.Sprintf("{Filename: %s\n Timestamp: %s\n OwnerID: %s\n "+
		"GroupID: %s\n FileMode: %s\n FileSize: %d}\n",
		h.Filename, h.Timestamp, h.OwnerID, h.GroupID,
		h.FileMode, h.FileSize)
}

type ARFileHeaderContents struct {
	Header   ARFileHeader
	Contents []byte
}

type ARFile map[string]ARFileHeaderContents

// Specialized AR file holding only ELF files.
type ARElfFile struct {
	Header ARFileHeader
	File   ElfFile
}

func translateFilename(fname string, lf_file []byte) string {
	if fname[0] == '/' {
		// It's a long filename, which is /[0-9]+, or one of the special files.
		fname = strings.TrimSpace(fname)
		if fname == "/" || fname == "//" {
			return fname
		}
		offset, err := strconv.Atoi(fname[1:])
		if err != nil {
			panic("Failed to parse long filename offset " + err.Error())
		}
		end := bytes.IndexByte(lf_file[offset:], '/')
		return string(lf_file[offset : offset+end])
	} else {
		end := strings.IndexByte(fname, '/')
		return fname[:end]
	}
}

func ReadPlainARFile(f *os.File) ARFile {
	ar_file := make(map[string]ARFileHeaderContents)
	per_file_header_size := 60
	hbuf := make([]byte, per_file_header_size)
	// Assume magic number header is already read.
	offset := int64(len(AR_MAGIC))
	special_long_filename_file := make([]byte, 0)
	// Go through the AR, reading more and more file-headers + file-bodies.
	for {
		n, err := f.ReadAt(hbuf, offset)
		if err == io.EOF && n == 0 {
			break
		}
		if err != nil {
			panic("Failed to read AR sub-file header: " + err.Error() +
				" reading " + string(n))
		}
		// Okay, hbuf now has the header contents.
		offset += int64(n)
		fsize, err := strconv.Atoi(strings.TrimSpace(string(hbuf[48:58])))
		if err != nil {
			panic("Failed to parse AR file size: " + err.Error())
		}
		filename := translateFilename(string(hbuf[0:16]),
			special_long_filename_file)
		new_header := ARFileHeader{
			Filename:  filename,
			Timestamp: strings.TrimSpace(string(hbuf[16:28])),
			OwnerID:   strings.TrimSpace(string(hbuf[28:34])),
			GroupID:   strings.TrimSpace(string(hbuf[34:40])),
			FileMode:  strings.TrimSpace(string(hbuf[40:48])),
			FileSize:  uint32(fsize)}
		body_buf := make([]byte, fsize)
		_, err2 := f.ReadAt(body_buf, offset)
		if err2 != nil {
			panic("Failed to read AR sub-file contents: " + err2.Error())
		}
		if filename == "/" {
			// Skipping the special GNU symbol-table file.
			// (not adding it to the ar_file map)
		} else if filename == "//" {
			// This is the long-filename file.
			// (not adding it to the ar_file map)
			special_long_filename_file = append(special_long_filename_file,
				body_buf...)
		} else {
			// Normal file, index it!
			ar_file[filename] = ARFileHeaderContents{new_header, body_buf}
		}
		offset += int64(fsize)
		// Data section should be aligned to 2 bytes.
		if offset%2 != 0 {
			offset += 1
		}
	}
	return ar_file
}

func ReadARFile(f *os.File, typ FileType) ARFile {
	switch typ {
	case AR_FILE:
		return ReadPlainARFile(f)
	case THIN_AR_FILE:
		panic("TODO(jvoung): Handle thin archives")
	default:
		panic("Unknown AR file type: " + string(typ))
	}
}

func (f *ARFile) WrapARElf() map[string]ARElfFile {
	result := make(map[string]ARElfFile, len(*f))
	for fname, arsubfile := range *f {
		result[fname] = ARElfFile{
			Header: arsubfile.Header,
			File:   ReadElfFile(arsubfile.Contents)}
	}
	return result
}


text:
package com.ddhigh.fragmentt.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.ddhigh.fragmentt.fragments.FragmentMain;
import com.ddhigh.fragmentt.fragments.FragmentSecond;

public class FragmentAdapter extends FragmentPagerAdapter {
    static FragmentMain main;
    static FragmentSecond second;

    public FragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        if (i == 0) {
            if (main == null)
                main = new FragmentMain();
            return main;
        } else if (i == 1) {
            if (second == null)
                second = new FragmentSecond();
            return second;
        } else {
            return null;
        }
    }

    @Override
    public int getCount() {
        return 2;
    }
}