text:
static int              running = 1;
static STACK            *states_stack;
static APP_STATE       *allstates;
static size_t           states_num;

NEON_API void
application_next_state(unsigned int state) {
    if (state > states_num) {
        LOG_ERROR("State(%d) out of range", state);
        exit(EXIT_FAILURE);
    }

    push_stack(states_stack, &allstates[state]);

    ((APP_STATE*)top_stack(states_stack))->on_init();

    frame_flush();
}

NEON_API void
application_back_state(void) {
    ((APP_STATE*)pop_stack(states_stack))->on_cleanup();
    frame_flush();
}

static void
application_cleanup(void) {
    configs_cleanup();
    asset_close();

    audio_cleanup();
    video_cleanup();

    while (!is_stack_empty(states_stack))
        application_back_state();

    delete_stack(states_stack);
}

#ifdef OPENAL_BACKEND
#define SDL_INIT_FLAGS (SDL_INIT_VIDEO | SDL_INIT_TIMER)
#else
#define SDL_INIT_FLAGS (SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)
#endif

NEON_API int
application_exec(const char *title, APP_STATE *states, size_t states_n) {
    allstates = states;
    states_num = states_n;

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        LOG_ERROR("%s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    atexit(SDL_Quit);

    if (TTF_Init() < 0) {
        LOG_ERROR("%s\n", TTF_GetError());
        return EXIT_FAILURE;
    }

    atexit(TTF_Quit);

    if ((states_stack = new_stack(sizeof(APP_STATE), states_n + 1)) == NULL) {
        LOG_ERROR("%s\n", "Can\'t create game states stack");
        return EXIT_FAILURE;
    }

    LOG("%s launched...\n", title);
    LOG("Platform: %s\n", SDL_GetPlatform());

    video_init(title);
    audio_init();

    atexit(application_cleanup);

    application_next_state(0);

    if (is_stack_empty(states_stack)) {
        LOG_CRITICAL("%s\n", "No game states");
        exit(EXIT_FAILURE);
    }

    SDL_Event event;

    Uint64 current = 0;
    Uint64 last = 0;

    float accumulator = 0.0f;

    while(running) {
        frame_begin();

        while(SDL_PollEvent(&event)) {
            ((APP_STATE*)top_stack(states_stack))->on_event(&event);
        }

        asset_process();
        resources_process();

        last = current;
        current = SDL_GetPerformanceCounter();
        Uint64 freq = SDL_GetPerformanceFrequency();

        float delta = (double)(current - last) / (double)freq;

        accumulator += CLAMP(delta, 0.f, 0.2f);

        while(accumulator >= TIMESTEP) {
            accumulator -= TIMESTEP;
            ((APP_STATE*)top_stack(states_stack))->on_update(TIMESTEP);
        }

        ((APP_STATE*)top_stack(states_stack))->on_present(screen.width, screen.height, accumulator / TIMESTEP);
        video_swap_buffers();

        frame_end();

        SDL_Delay(1);
    }

    return EXIT_SUCCESS;
}

NEON_API void
application_quit(void) {
    running = 0;
}


text:
<?php

if ( ! class_exists( 'Kirki_Section' ) ) {

	/**
	 * Each section is a separate instrance of the Kirki_Section object.
	 */
	class Kirki_Section {

		/**
		 * An array of our section types.
		 *
		 * @access private
		 * @var array
		 */
		private $section_types = array(
			'kirki-default'  => 'Kirki_Sections_Default_Section',
			'kirki-expanded' => 'Kirki_Sections_Expanded_Section',
			'kirki-hover'    => 'Kirki_Sections_Hover_Section',
		);

		/**
		 * The object constructor.
		 *
		 * @access public
		 * @param array $args The section parameters.
		 */
		public function __construct( $args ) {

			$this->section_types = apply_filters( 'kirki/section_types', $this->section_types );
			$this->add_section( $args );

		}

		/**
		 * Adds the section using the WordPress Customizer API.
		 *
		 * @access public
		 * @param array $args The section parameters.
		 */
		public function add_section( $args ) {

			global $wp_customize;

			if ( ! isset( $args['type'] ) || ! array_key_exists( $args['type'], $this->section_types ) ) {
				$args['type'] = 'kirki-default';
			}
			$section_classname = $this->section_types[ $args['type'] ];

			if ( isset( $args['icon'] ) && ! empty( $args['icon'] ) ) {
				$args['title'] = ' ' . esc_html( $args['title'] );
			}

			// Add the section.
			$wp_customize->add_section( new $section_classname( $wp_customize, sanitize_key( $args['id'] ), $args ) );

		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = function( images, callback ){

  if ( Object.prototype.toString.call( images ) !== '[object Array]' ) {

    var req = {};

    if ( process.env.HOST_PORT === '2376' ) {

      req.url  = 'https://' + process.env.HOST_IP + ':2376/images/json?all=true';
      req.cert = fs.readFileSync( __dirname + '/../cert/cert.pem' );
      req.key  = fs.readFileSync( __dirname + '/../cert/key.pem' );
      req.ca   = fs.readFileSync( __dirname + '/../cert/ca.pem' );

    } else {
      req.url = 'http://' + process.env.HOST_IP + ':2375/images/json?all=true';
    }

    request.get( req, function( error, http, body ){

      images = new Array();
      body = JSON.parse( body );

      for (var i = 0; i < body.length; i++) {
        images = body[i].RepoTags.filter(function ( image ) {
          return image.indexOf(':latest');
        });
      }

      updateImage( images, callback );
    });

  } else {
    updateImage( images, callback );
  }

};

function updateImage( images, callback ) {

  async.map( images, function ( image, callback ) {

    var req = {

      headers : {

        'X-Registry-Auth' : new Buffer( JSON.stringify({

          username : process.env.REGISTRY_USER || '',
          password : process.env.REGISTRY_PASS || '',
          email    : process.env.REGISTRY_MAIL || ''

        }) ).toString('base64')

      }

    };

    if ( process.env.HOST_PORT === '2376' ) {

      req.url  = 'https://' + process.env.HOST_IP + ':2376/images/create?fromImage=' + image;
      req.cert = fs.readFileSync( __dirname + '/../cert/cert.pem' );
      req.key  = fs.readFileSync( __dirname + '/../cert/key.pem' );
      req.ca   = fs.readFileSync( __dirname + '/../cert/ca.pem' );

    } else {
      req.url = 'http://' + process.env.HOST_IP + ':2375/images/create?fromImage=' + image;
    }

    request.post( req, function ( error, http, body ) {
      callback( error, body );
    });

  }, function ( err, res ) {
    callback(err, JSON.parse(res[0].split('\r\n')[2]).status);
  });
}


text:
module ShooterSubQuery
    ( requestSubResult
    ) where

import Network.HTTP
import Network.URL
import Network.URI
import Data.Maybe
import ShooterSubQueryResult

shooterURLStringURL :: URL
shooterURLStringURL = fromJust $ importURL "http://www.shooter.cn/api/subapi.php"

shooterQueryList :: String -> String -> [(String, String)]
shooterQueryList fileHash pathInfo = [("filehash", fileHash),
                                      ("pathinfo", pathInfo),
                                      ("format", "json"),
                                      ("lang", "Chn")]

shooterSubRequest ::  [(String, String)] -> Request_String
shooterSubRequest params = postRequest urlString
                           where urlString = exportURL shooterURLStringURL ++ "?" ++ urlEncodeVars params

requestSubResult :: String -> String -> IO (Either String [SubQueryResult])
requestSubResult fileHash pathInfo = do
            let request = shooterSubRequest $ shooterQueryList fileHash pathInfo
                              -- putStrLn $ show request
            response <- simpleHTTP request >>= getResponseBody
            return $ decodeSubQueryResult response


text:
/****************************************************/
/****************[ Mage_CSS_B Clears ]***************/
/****************************************************/

.page-head:after,
.page-head-alt:after,
.clear:after,
.col2-set:after,
.col3-set:after,
.col4-set:after,
.col2-alt-set:after,
.head:after,
.inner-head:after,
.header-top:after,
.quick-access:after,
.header-nav:after,
#nav:after,
.middle:after,
.product-essential:after,
.button-set:after,
.actions:after,
.legend:after,
.form-list li:after,
.button-container:after,
.ratings:after,
.page-head:after,
.page-head-alt:after,
.group-select li:after,
.search-autocomplete li:after,
.side-col li:after,
.account-box li:after,
.address-list li:after,
.generic-product-list li:after,
.listing-type-list .listing-item:after,
.listing-type-list .product-info .product-reviews:after,
.my-review-detail:after {
	content:".";
	display:block;
	clear:both;
	height:0;
	font-size:0;
	line-height:0em;
	visibility:hidden;
	overflow:hidden;
	}
.middle {display:inline-block;}


text:
import React from 'react';
import AppZhuSuItems from 'components/AppZhuSuItems';
import {Link} from 'react-router';

class AppZhuSu extends React.Component{
	render(){
		if(!Array.isArray(this.props.DetailsData)) throw new Error('this.props.DetailsData问题必须是数组');

		let ZhuSuItems=this.props.DetailsData.map(function(value,index){
			return (
				<AppZhuSuItems  key={index}
								title={value.title}
								id={index}
								kezhu={value.number}
								suoimgurl={value.pics[0].url}
								price={value.price}
								handleAppCartDisplay={this.props.handleAppCartDisplay}/>
				);
		}.bind(this));

		return (

住宿

					{ZhuSuItems}

					<Link to="/rooms">查看更多</Link>

			);
	}
}

export default AppZhuSu;


text:
import Style from "./Style";
import EventNode from "./EventNode";
import { idArray as idList, classArray as classList } from "./adminIdClass"; // Todo: appendとremoveの反映

class BaseNode extends EventNode {

  public childNodes = [];
  public attributes = [];
  public parentNode;
  public tagName: string;
  public nodeName: string;
  public ownerDocument;
  public style;

  private attrList = {};
  private _id;
  private _className;

  get id(): string {
      return this._id;
  }
  set id( value: string ) {
    if ( this._id ) {
      delete idList[ this._id ];
    }
    this._id = value;
    idList[ value ] = this;
  }

  get className(): string {
      return this.getAttribute( "class" );
  }
  set className( value: string ) {
    if ( !value ) { return; } // Todo: removeClass

    if ( this._className ) {
      this._className.split( " " ).forEach( className => {
        classList[ className ].splice( classList[ className ].indexOf( this ), 1 );
        if ( !classList[ className ].length ) {
          delete classList[ className ];
        }
      });
    }

    this._className = value;
    value.split( " " ).forEach( className => {
      const list = classList[ className ] || [];
      list.push( this );
      classList[ className ] = list;
    });
  }

  public setAttrHook( name, value ) { return; }
  public getAttrHook( name ) { return this.attrList[ name ] ? this.attrList[ name ].value : null; }
  public removeHook( childNode ) { return; }
  public appendHook( childNode ) { return; }

  public setAttribute( name: string, value: any ): void {
    if ( this.attrList[ name ] ) {
      this.attrList[ name ].value = value;
    } else {
      this.attributes.push( this.attrList[ name ] = {
        name,
        value,
      });
    }

    switch ( name ) {
    case "id":
      this.id = value;
      break;
    case "class":
      this.className = value;
      break;
    }

    this.setAttrHook( name, value );
  }

  public getAttribute( name: string ) {
    return this.getAttrHook( name );
  }

  public appendChild( child ): void {
    if ( child.parentNode ) {
      child.parentNode.removeChild( child );
    }

    this.childNodes.push( child );
    child.parentNode = this;
    this._resetChildHandlerTypeList();
    this.appendHook( child );
  }

  public insertBefore( newNode, node ): void {
    if ( newNode.parentNode ) {
      newNode.parentNode.removeChild( newNode );
    }

    const index = this.childNodes.indexOf( node );
    if ( index === -1 ) {
      this.childNodes.push( newNode );
    } else {
      this.childNodes.splice( index, 0, newNode );
    }
    newNode.parentNode = this;
    this._resetChildHandlerTypeList();
    this.appendHook( newNode );
  }

  public removeChild( childNode ): void {
    const index = this.childNodes.indexOf( childNode );
    if ( index !== -1 ) {
      this.childNodes.splice( index, 1 );
      childNode.parentNode = null;
      this._resetChildHandlerTypeList();
      this.removeHook( childNode );
    }
  }

  public querySelector( selector: string ) {
    if ( /^#/.test( selector ) ) {
      return idList[ selector.slice( 1 ) ] || null;
    } else if ( /^\./.test( selector ) ) {
      let list = classList[ selector.slice( 1 ) ];
      return list ? list[ 0 ] : null;
    }
  }

  public querySelectorAll( selector: string ) {
    const arr = [];
    if ( /^#/.test( selector ) ) {
      let elem = idList[ selector.slice( 1 ) ];
      if ( elem ) {
        arr.push( elem );
      }
    } else if ( /^\./.test( selector ) ) {
      let list = classList[ selector.slice( 1 ) ];
      if ( list ) {
        Array.prototype.push.apply( arr, list );
      }
    }
    return arr;
  }

  constructor( tagName: string, gomlDoc ) {
    super();
    this.tagName = this.nodeName = tagName;
    this.ownerDocument = gomlDoc;
    this.style = new Style( this );
  }
}

export default BaseNode;


text:
@interface JKRightViewController ()

@end

@implementation JKRightViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor greenColor]];
    UILabel* label = [[UILabel alloc] initWithFrame: CGRectInset(self.view.bounds, 50, 150)];
    label.text = @"Right view";
    [self.view addSubview: label];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
package jetbrick.template;

import java.util.*;

/**
 * 存放模板的 context 数据, 支持 chain
 */
public class JetContext {
    private final JetContext parent;
    private final Map<String, Object> context;
    private JetGlobalVariables globalVariables;

    public JetContext() {
        this(null, null);
    }

    public JetContext(Map<String, Object> context) {
        this(null, context);
    }

    public JetContext(JetContext parent, Map<String, Object> context) {
        this.parent = parent;

        if (context == null) {
            this.context = new HashMap<String, Object>();
        } else {
            this.context = new HashMap<String, Object>(context);
        }
    }

    protected boolean isSimpleModel() {
        return parent == null && JetContext.class.equals(getClass());
    }

    protected Map<String, Object> getContext() {
        return context;
    }

    public JetContext getParent() {
        return parent;
    }

    public Set<String> keySet() {
        return context.keySet();
    }

    public Object get(String name) {
        Object value = context.get(name);
        if (value == null && parent != null) {
            value = parent.get(name);
        }
        if (value == null && globalVariables != null) {
            value = globalVariables.get(this, name);
            if (value != null) {
                put(name, value); // resolved
            }
        }
        return value;
    }

    protected void setGlobalVariables(JetGlobalVariables globalVariables) {
        this.globalVariables = globalVariables;
    }

    /**
     * 只修改自己 Context,不影响 Parent
     * #set 指令用
     */
    public void put(String name, Object value) {
        context.put(name, value);
    }

    /**
     * 同 put(name, value)
     */
    public void putAll(Map<String, Object> context) {
        this.context.putAll(context);
    }

    /**
     * 修改所有的父 Context (支持子模板返回变量到父模板)
     * #put 指令用
     */
    public void putAsParents(String name, Object value) {
        context.put(name, value);
        if (parent != null) {
            parent.putAsParents(name, value);
        }
    }
}


text:
"""Request tests."""
import json
import tempfile
import unittest

from mock import Mock, patch
import requests
import requests.exceptions

import tests.helper

import snowfloat.errors
import snowfloat.geometry
import snowfloat.settings

class RequestTests(unittest.TestCase):
    """Request tests."""

    # pylint: disable=C0103
    def setUp(self):
        snowfloat.settings.HOST = 'api.snowfloat.com:443'
        snowfloat.settings.API_KEY_ID = 'QWE948OCAYX16G1XVGJM'
        snowfloat.settings.API_SECRET_KEY = \
            'tYCbpb2ozfSDAzHDtu/zJqsptmw9tyO0kg+aWhne'

    def test_get_hmac_sha(self):
        """Get message HMAC-SHA signature."""
        msg = 'test_msg'
        private_key = 'test_private_key'
        res = snowfloat.request._get_hmac_sha(msg, private_key)
        self.assertEqual(res, 'w5YfAjs+VUh79G1jYgHZFWLA4w9W+MNDRX/9z8kFJKY=')

    def test_get_sha_file(self):
        """Get file SHA checksum."""
        tfile = tempfile.NamedTemporaryFile(delete=False)
        tfile.write(''.join('a' for e in xrange(10000)))
        tfile.close()
        tfile = open(tfile.name)
        res = snowfloat.request._get_sha(tfile)
        self.assertEqual(res, 'J90fYbhntqD26dikHEMjHeUhB+U65CTej4R7gh20txE=')
        tfile.close()

    def test_get_sha_str(self):
        """Get string SHA checksum."""
        res = snowfloat.request._get_sha('test_message')
        self.assertEqual(res, 'O3SR3AFqwaCy4CNyQCyGH6+kWSlAh+fL4J9wTVgtkx8=')

    def test_format_url_https(self):
        """Format full path https URL."""
        res = snowfloat.request._format_url('/test_uri')
        self.assertEqual(res, 'https://api.snowfloat.com:443/test_uri')

    def test_format_url_http(self):
        """Format full path http URL."""
        snowfloat.settings.HOST = 'api.snowfloat.com:80'
        res = snowfloat.request._format_url('/test_uri')
        self.assertEqual(res, 'http://api.snowfloat.com:80/test_uri')

    def test_format_params_query_distance(self):
        """Format params for query with distance."""
        point = snowfloat.geometry.Point([1, 2, 3])
        kwargs = {'query': 'test_query',
                  'geometry': point,
                  'distance': 1}
        exclude = ('geometry', 'distance')
        res = snowfloat.request.format_params(kwargs, exclude)
        geojson = {'type': 'Point',
                   'coordinates': [1, 2, 3],
                   'properties': {'distance': 1}}
        self.assertDictEqual(res,
            {'geometry__test_query': json.dumps(geojson)})

    def test_format_params_query_distance_missing(self):
        """Format params for query with distance missing."""
        point = snowfloat.geometry.Point([1, 2, 3])
        kwargs = {'query': 'test_query',
                  'geometry': point}
        exclude = ('geometry', 'distance')
        res = snowfloat.request.format_params(kwargs, exclude)
        geojson = {'type': 'Point',
                   'coordinates': [1, 2, 3],
                   'properties': {'distance': None}}
        self.assertDictEqual(res,
            {'geometry__test_query': json.dumps(geojson)})

    def test_format_params_query_slice_start(self):
        """Format params for query with query_slice single item."""
        kwargs = {'query_slice': (1,)}
        res = snowfloat.request.format_params(kwargs)
        self.assertDictEqual(res,
            {'slice_start': 1})

    def test_format_params_query_slice_stop(self):
        """Format params for query with query_slice two items."""
        kwargs = {'query_slice': (1, 2)}
        res = snowfloat.request.format_params(kwargs)
        self.assertDictEqual(res,
            {'slice_start': 1,
             'slice_end': 2})

    @patch.object(snowfloat.request, '_get_headers')
    @patch.object(requests, 'get')
    def test_send_get(self, get_mock, get_headers_mock):
        """Send function with get method."""
        get_mock.__name__ = 'get'
        m = Mock()
        m.status_code = 200
        m.json.return_value = 'test_response'
        get_mock.return_value = m
        get_headers_mock.return_value = {'header_1': 'test_header_1'}
        uri = '/test_uri'
        params = {'param': 'test_param'}
        headers = {'header_2': 'test_header_2'}
        res = snowfloat.request.send(get_mock, uri, params=params,
            headers=headers)
        self.assertEqual(res, 'test_response')
        get_mock.assert_called_with(
            '%s/test_uri' % (tests.helper.URL_PREFIX),
            headers={'header_1': 'test_header_1',
                     'header_2': 'test_header_2'},
            params={'param': 'test_param'},
            data={},
            timeout=10,
            verify=False)

    @patch.object(requests, 'get')
    def test_get_headers(self, get_mock):
        """Test _get_headers."""
        get_mock.__name__ = 'get'
        uri = '/test_uri'
        request_params = {'param': 'test_param'}
        request_data = {}
        headers = snowfloat.request._get_headers(get_mock, uri, request_data,
            request_params)
        self.assertEqual(headers['Authorization'],
                'GEO QWE948OCAYX16G1XVGJM:'\
                'azh8WQmu8IwP15TFbWafei1s5VWZGAkMzNivHXBlqD4=')

    @patch.object(requests, 'get')
    def test_get_headers_sharing(self, get_mock):
        """Test _get_headers with user sharing keys."""
        get_mock.__name__ = 'get'
        uri = '/test_uri'
        request_params = {'param': 'test_param'}
        request_data = {}
        snowfloat.settings.USER_API_KEY_ID = 'test_user_api_key_id'
        snowfloat.settings.USER_API_SHARING_KEY = 'test_user_api_sharing_key'
        headers = snowfloat.request._get_headers(get_mock, uri, request_data,
            request_params)
        self.assertEqual(headers['X-User-API-Key-ID'],
            'test_user_api_key_id')
        self.assertEqual(headers['X-User-API-Sharing-Key'],
            'test_user_api_sharing_key')
        snowfloat.settings.USER_API_KEY_ID = ''
        snowfloat.settings.USER_API_SHARING_KEY = ''

class RequestErrorTests(unittest.TestCase):
    """Request error tests."""
    def test_request_error(self):
        """Request error test."""
        req = snowfloat.errors.RequestError(500, 1, 'test_message',
            'test_more')
        self.assertEqual(str(req),
            'RequestError: status=500, code=1, message=test_message, ' \
            'more=test_more')
        req = eval('snowfloat.errors.' + repr(req))
        self.assertTrue(isinstance(req, snowfloat.errors.RequestError))
        self.assertEqual(req.status, 500)
        self.assertEqual(req.code, 1)
        self.assertEqual(req.message, 'test_message')
        self.assertEqual(req.more, 'test_more')


text:
import test from 'ava'
import { graphql } from 'graphql'
import schemaRelay from '../../test-api/schema-paginated/index'
import { partial } from 'lodash'
import { errCheck } from '../_util'

const run = partial(graphql, schemaRelay)

test('should handle limit at the root', async t => {
  const query = `{
    usersFirst2 {
      fullName
    }
  }`
  const { data, errors } = await run(query)
  errCheck(t, errors)
  const expect = {
    usersFirst2: [
      { fullName: 'andrew carlson' },
      { fullName: 'matt elder' }
    ]
  }
  t.deepEqual(expect, data)
})

test('should handle limit for one-to-many', async t => {
  const query = `{
    user(id: 1) {
      commentsLast2 {
        id
      }
    }
  }`
  const { data, errors } = await run(query)
  errCheck(t, errors)
  const expect = {
    user: {
      commentsLast2: [
        { id: 'Q29tbWVudDo4' },
        { id: 'Q29tbWVudDo2' }
      ]
    }
  }
  t.deepEqual(expect, data)
})

test('should handle limit for many-to-many', async t => {
  const query = `{
    user(id: 3) {
      followingFirst {
        fullName
      }
    }
  }`
  const { data, errors } = await run(query)
  errCheck(t, errors)
  const expect = {
    user: {
      followingFirst: [
        { fullName: 'andrew carlson' }
      ]
    }
  }
  t.deepEqual(expect, data)
})


text:
#include "warnings.h"
#include <windows.h>
#include <windowsx.h>
#include "amctrls.h"
#include "amctrli.h"

#define  SIZE_BLOCK     10

/* The PROBAR structure holds information for one progress bar
 */
typedef struct tagPROBAR {
   UINT nMinRange;            /* The minimum range of the progress bar */
   UINT nMaxRange;            /* The maximum range of the progress bar */
   UINT nPos;                 /* The current position of the bar */
   UINT nStepInc;             /* The increments by which the bar steps */
   HFONT hFont;               /* The font used in the progress bar */
} PROBAR;

#define  GWW_EXTRA            4
#define  GetBlock(h)          ((PROBAR FAR *)GetWindowLong((h),0))
#define  PutBlock(h,b)        (SetWindowLong((h),0,(LONG)(b)))

LRESULT EXPORT CALLBACK ProgressWndFn( HWND,  UINT, WPARAM, LPARAM );

/* This function registers the progress bar class window to the system.
 */
BOOL FASTCALL RegisterProgressClass( HINSTANCE hInst )
{
   WNDCLASS wc;

   wc.hCursor        = LoadCursor( NULL, IDC_ARROW );
   wc.hIcon          = NULL;
   wc.lpszMenuName   = NULL;
   wc.lpszClassName  = PROGRESS_CLASS;
   wc.hbrBackground  = (HBRUSH)( COLOR_BTNFACE+1 );
   wc.hInstance      = hInst;
   wc.style          = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
   wc.lpfnWndProc    = (WNDPROC)ProgressWndFn;
   wc.cbClsExtra     = 0;
   wc.cbWndExtra     = GWW_EXTRA;
   return( RegisterClass( &wc ) );
}

LRESULT EXPORT CALLBACK ProgressWndFn( HWND hwnd,  UINT message, WPARAM wParam, LPARAM lParam )
{
   PROBAR FAR * pProBar;

#ifdef _DEBUG
   /* Help us to catch NULL pointers...
    */
   pProBar = NULL;
#endif
   switch( message )
      {
      case WM_CREATE: {
         static PROBAR FAR * pNewProBar;

         INITIALISE_PTR(pNewProBar);
         if( fNewMemory( &pNewProBar, sizeof( PROBAR ) ) )
            {
            pNewProBar->nMinRange = 0;
            pNewProBar->nMaxRange = 100;
            pNewProBar->nPos = 0;
            pNewProBar->nStepInc = 10;
            pNewProBar->hFont = GetStockFont( SYSTEM_FONT );
            PutBlock( hwnd, pNewProBar );
            }
         return( pNewProBar ? 0 : -1 );
         }

      case PBM_GETPOS:
         /* Return the current progress bar position.
          * NEW for 1.2!
          */
         pProBar = GetBlock( hwnd );
         return( pProBar->nPos );

      case PBM_SETPOS: {
         UINT nPrevPos;

         pProBar = GetBlock( hwnd );
         nPrevPos = pProBar->nPos;
         if( wParam != nPrevPos )
            {
            if( ( pProBar->nPos = wParam ) > pProBar->nMaxRange )
               pProBar->nPos = pProBar->nMinRange;
            InvalidateRect( hwnd, NULL, TRUE );
            UpdateWindow( hwnd );
            }
         return( nPrevPos );
         }

      case PBM_STEPIT: {
         UINT nPrevPos;

         pProBar = GetBlock( hwnd );
         nPrevPos = pProBar->nPos;
         if( ( pProBar->nPos += pProBar->nStepInc ) > pProBar->nMaxRange )
            pProBar->nPos = pProBar->nMinRange;
         InvalidateRect( hwnd, NULL, TRUE );
         UpdateWindow( hwnd );
         return( nPrevPos );
         }

      case PBM_DELTAPOS: {
         UINT nPrevPos;

         pProBar = GetBlock( hwnd );
         nPrevPos = pProBar->nPos;
         if( ( pProBar->nPos += wParam ) > pProBar->nMaxRange )
            pProBar->nPos -= pProBar->nMaxRange;
         InvalidateRect( hwnd, NULL, TRUE );
         UpdateWindow( hwnd );
         return( nPrevPos );
         }

      case PBM_GETRANGE: {
         PBRANGE FAR * lppbr;

         /* Return a 32-bit range. If lParam is non-NULL, it should be a
          * pointer to a PBRANGE structure. Otherwise wParam specifies
          * which of the low/high range is returned.
          * NEW for 1.2!
          */
         lppbr = (PBRANGE FAR *)lParam;
         pProBar = GetBlock( hwnd );
         if( NULL != lppbr )
            {
            lppbr->iLow = pProBar->nMinRange;
            lppbr->iHigh = pProBar->nMaxRange;
            return( TRUE );
            }
         return( wParam ? pProBar->nMinRange : pProBar->nMaxRange );
         }

   #ifdef WIN32
      case PBM_SETRANGE32:
         /* Set a 32-bit range. No return value.
          * NEW for 1.2!
          */
         pProBar = GetBlock( hwnd );
         pProBar->nMinRange = wParam;
         pProBar->nMaxRange = lParam;
         InvalidateRect( hwnd, NULL, TRUE );
         UpdateWindow( hwnd );
         return( 0L );
   #endif

      case PBM_SETRANGE: {
         DWORD nPrevRange;

         pProBar = GetBlock( hwnd );
         nPrevRange = MAKELPARAM( pProBar->nMinRange, pProBar->nMaxRange );
         pProBar->nMinRange = LOWORD( lParam );
         pProBar->nMaxRange = HIWORD( lParam );
         InvalidateRect( hwnd, NULL, TRUE );
         UpdateWindow( hwnd );
         return( nPrevRange );
         }

      case PBM_SETSTEP: {
         DWORD nPrevStep;

         pProBar = GetBlock( hwnd );
         nPrevStep = pProBar->nStepInc;
         pProBar->nStepInc = wParam;
         return( nPrevStep );
         }

      case WM_SETFONT: {
         HFONT hOldFont;

         pProBar = GetBlock( hwnd );
         hOldFont = pProBar->hFont;
         pProBar->hFont = wParam ? (HFONT)wParam : GetStockFont( SYSTEM_FONT );
         if( LOWORD( lParam ) )
            {
            InvalidateRect( hwnd, NULL, TRUE );
            UpdateWindow( hwnd );
            }
         return( (LRESULT)(LPSTR)hOldFont );
         }

      case WM_GETFONT:
         pProBar = GetBlock( hwnd );
         return( (LRESULT)(LPSTR)pProBar->hFont );

      case WM_ERASEBKGND: {
         HDC hdc;
         HPEN hpenWhite;
         HPEN hpenGray;
         HPEN hOldPen;
         RECT rc;

         hdc = (HDC)wParam;
         hpenWhite = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_BTNHIGHLIGHT ) );
         hpenGray = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_BTNSHADOW ) );
         GetClientRect( hwnd, &rc );
         hOldPen = SelectPen( hdc, hpenGray );
         MoveToEx( hdc, rc.left, rc.bottom - 2, NULL );
         LineTo( hdc, rc.left, rc.top );
         LineTo( hdc, rc.right - 1, rc.top );
         SelectPen( hdc, hpenWhite );
         MoveToEx( hdc, rc.left, rc.bottom - 1, NULL );
         LineTo( hdc, rc.right - 1, rc.bottom  - 1 );
         LineTo( hdc, rc.right - 1, rc.top - 1 );
         SelectPen( hdc, hOldPen );
         DeletePen( hpenGray );
         DeletePen( hpenWhite );
         return( TRUE );
         }

      case WM_PAINT: {
         PAINTSTRUCT ps;
         HBRUSH hbrBlock;
         HBRUSH hbrFace;
         int cBlocks;
         UINT nRange;
         RECT rcBlock;
         int nRightEdge;
         int c, x;
         RECT rc;
         HDC hdc;

         hdc = BeginPaint( hwnd, &ps );
         pProBar = GetBlock( hwnd );
         GetClientRect( hwnd, &rc );
         InflateRect( &rc, -1, -2 );
         nRange = max( pProBar->nMaxRange - pProBar->nMinRange, 1 );
         x = (WORD)( ( (DWORD)pProBar->nPos * ( rc.right - rc.left ) ) / nRange ) + 1;
         if( GetWindowStyle( hwnd ) & PBS_SMOOTH )
            {
            int nPercentage;
            char ach[ 30 ];
            SIZE size;
            RECT rc1;
            RECT rc2;
            int dx;
            int dy;

            /* Smooth mode, so show progress as a gradual bar with the
             * percentage inside it.
             */
            if( ( nPercentage = (WORD)( ( (DWORD)pProBar->nPos * 100 ) / nRange ) ) > 100 )
               nPercentage = 100;
            wsprintf( ach, "%3d%%", nPercentage );
            GetTextExtentPoint( hdc, ach, 4, &size );
            rc1 = rc;
            rc2 = rc;
            dx = rc1.right;
            dy = rc1.bottom;
            rc1.right = x;
            rc2.left  = x;
            SetBkColor( hdc, GetSysColor( COLOR_HIGHLIGHT ) );
            SetTextColor( hdc, GetSysColor( COLOR_HIGHLIGHTTEXT ) );
            ExtTextOut( hdc, ( dx - size.cx ) / 2,
                        ( dy - size.cy ) / 2,
                        ETO_OPAQUE | ETO_CLIPPED, &rc1, ach, 4, NULL );
            SetBkColor( hdc, GetSysColor( COLOR_HIGHLIGHTTEXT ) );
            SetTextColor( hdc, GetSysColor( COLOR_HIGHLIGHT ) );
            ExtTextOut( hdc, ( dx - size.cx ) / 2,
                        ( dy - size.cy ) / 2,
                        ETO_OPAQUE | ETO_CLIPPED, &rc2, ach, 4, NULL );
            }
         else
            {
            /* Block mode, so show progress as a series of fixed width
             * blocks running right to left.
             */
            cBlocks = x / SIZE_BLOCK;
            hbrBlock = CreateSolidBrush( GetSysColor( COLOR_HIGHLIGHT ) );
            nRightEdge = rc.left;
            for( c = 0; c < cBlocks; ++c )
               {
               SetRect( &rcBlock, rc.left + ( c * SIZE_BLOCK ) + 1, rc.top, ( c * SIZE_BLOCK ) + SIZE_BLOCK, rc.bottom );
               FillRect( hdc, &rcBlock, hbrBlock );
               nRightEdge = rcBlock.right;
               }
            hbrFace = CreateSolidBrush( GetSysColor( COLOR_BTNFACE ) );
            rc.left = nRightEdge;
            FillRect( hdc, &rc, hbrFace );
            DeleteBrush( hbrFace );
            DeleteBrush( hbrBlock );
            }
         EndPaint( hwnd, &ps );
         return( 0L );
         }

      case WM_DESTROY:
         pProBar = GetBlock( hwnd );
         FreeMemory( &pProBar );
         break;
      }
   return( DefWindowProc( hwnd, message, wParam, lParam ) );
}


text:
package org.openo.orchestrator.nfv.nsoc.ia.vnfm.etsi.entity.process;

public class ScheduleResponse {
    private int nextStepNo;
    private String status;
    private String progressJson;
    public int getNextStepNo() {
        return nextStepNo;
    }
    public void setNextStepNo(int nextStepNo) {
        this.nextStepNo = nextStepNo;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getProgressJson() {
        return progressJson;
    }
    public void setProgressJson(String progressJson) {
        this.progressJson = progressJson;
    }

}


text:
Easily add permalink support to a model.

## Example

    # models/post.rb
    class Post < ActiveRecord::Base
      has_permalink :title
    end

## Installation

    $ script/plugin install git://github.com/sbfaulkner/has_permalink.git

## Legal

**Author:** S. Brent Faulkner <brentf@unwwwired.net>
**License:** Copyright © 2008 unwwwired.net, released under the MIT license


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

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Storage;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Compute.Extension.Diagnostics
{
    [Cmdlet(
        VerbsCommon.Add,
        ProfileNouns.VirtualMachineScaleSetDiagnosticsExtension,
        SupportsShouldProcess = true)]
    [OutputType(typeof(VirtualMachineScaleSet))]
    public class AddAzureRmVmssDiagnosticsExtension : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
    {
        private string extensionName = DiagnosticsExtensionConstants.ExtensionDefaultName;
        private string version = "1.7";
        private bool autoUpgradeMinorVersion = true;

        [Parameter(
            Mandatory = true,
            Position = 0,
            ValueFromPipeline = true,
            ValueFromPipelineByPropertyName = true)]
        public VirtualMachineScaleSet VirtualMachineScaleSet { get; set; }

        [Parameter(
            Mandatory = true,
            Position = 1,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Public diagnostics configuration in JSON.")]
        [ValidateNotNullOrEmpty]
        public string SettingFilePath { get; set; }

        [Parameter(
            Mandatory = false,
            Position = 2,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Private diagnostics configuration in JSON.")]
        public string ProtectedSettingFilePath { get; set; }

        [Alias("ExtensionName")]
        [Parameter(
            Mandatory = false,
            Position = 3,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The extension name.")]
        public string Name
        {
            get
            {
                return this.extensionName;
            }
            set
            {
                this.extensionName = value;
            }
        }

        [Alias("HandlerVersion", "Version")]
        [Parameter(
            Mandatory = false,
            Position = 4,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The extension version.")]
        public string TypeHandlerVersion
        {
            get
            {
                return this.version;
            }
            set
            {
                this.version = value;
            }
        }

        [Parameter(
            Mandatory = false,
            Position = 5,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Pass a boolean value indicating whether auto upgrade diagnostics extension minor version.")]
        public bool AutoUpgradeMinorVersion
        {
            get
            {
                return this.autoUpgradeMinorVersion;
            }
            set
            {
                this.autoUpgradeMinorVersion = value;
            }
        }

        [Parameter(Mandatory = false,
            HelpMessage = "To force the overwritting of the diagnostics extension to the VM scale set.")]
        public SwitchParameter Force { get; set; }

        protected override void ProcessRecord()
        {
            if (ShouldProcess(this.VirtualMachineScaleSet.Name, Properties.Resources.AddVmssDiagnosticsExtensionAction))
            {
                // VirtualMachineProfile
                if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
                {
                    this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
                }

                // ExtensionProfile
                if (this.VirtualMachineScaleSet.VirtualMachineProfile.ExtensionProfile == null)
                {
                    this.VirtualMachineScaleSet.VirtualMachineProfile.ExtensionProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetExtensionProfile();
                }

                // Extensions
                if (this.VirtualMachineScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions == null)
                {
                    this.VirtualMachineScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions = new List<Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetExtension>();
                }

                bool shouldContinue = true;

                // Warning if there's already a diagnostics extension.
                var extensions = this.VirtualMachineScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions;
                if (extensions.Any(DiagnosticsHelper.IsDiagnosticsExtension))
                {
                    if (Force.IsPresent
                        || ShouldContinue(Properties.Resources.DiagnosticsExtensionOverwrittingConfirmation, Properties.Resources.DiagnosticsExtensionOverwrittingCaption))
                    {
                        WriteWarning(Properties.Resources.DiagnosticsExtensionOverwriting);

                        // Remove all existing diagnostics extensions
                        this.VirtualMachineScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions = extensions.Where(extension => !DiagnosticsHelper.IsDiagnosticsExtension(extension)).ToList();
                    }
                    else
                    {
                        shouldContinue = false;
                    }
                }

                if (shouldContinue)
                {
                    var storageClient = AzureSession.Instance.ClientFactory.CreateArmClient<StorageManagementClient>(DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.ResourceManager);

                    // Parse configs, and auto fill incomplete parts
                    Tuple<Hashtable, Hashtable> settings = DiagnosticsHelper.GetConfigurationsFromFiles(this.SettingFilePath, this.ProtectedSettingFilePath, this.VirtualMachineScaleSet.Id, this, storageClient);

                    var newDiagnosticsExtension = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetExtension();

                    newDiagnosticsExtension.Name = this.Name;
                    newDiagnosticsExtension.Publisher = DiagnosticsExtensionConstants.ExtensionPublisher;
                    newDiagnosticsExtension.Type = DiagnosticsExtensionConstants.ExtensionType;
                    newDiagnosticsExtension.TypeHandlerVersion = this.TypeHandlerVersion;
                    newDiagnosticsExtension.AutoUpgradeMinorVersion = this.AutoUpgradeMinorVersion;
                    newDiagnosticsExtension.Settings = settings.Item1;
                    newDiagnosticsExtension.ProtectedSettings = settings.Item2;
                    this.VirtualMachineScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions.Add(newDiagnosticsExtension);
                }
            }

            WriteObject(this.VirtualMachineScaleSet);
        }
    }
}


text:
/**
 *
 */
package jframe.yunsms.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

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

import jframe.core.plugin.annotation.InjectPlugin;
import jframe.core.plugin.annotation.InjectService;
import jframe.core.plugin.annotation.Injector;
import jframe.core.plugin.annotation.Start;
import jframe.core.plugin.annotation.Stop;
import jframe.httpclient.service.HttpClientService;
import jframe.yunsms.YunsmsConfig;
import jframe.yunsms.YunsmsPlugin;
import jframe.yunsms.service.YunsmsService;

/**
 * @author dzh
 * @date Jul 9, 2016 3:36:15 PM
 * @since 1.0
 */
@Injector
public class YunsmsServiceImpl implements YunsmsService {

    static Logger LOG = LoggerFactory.getLogger(YunsmsServiceImpl.class);

    @InjectPlugin
    static YunsmsPlugin plugin;

    @InjectService(id = "jframe.service.httpclient")
    static HttpClientService _http;

    static String FILE_CONF = "file.yunsms";

    static YunsmsConfig _config = new YunsmsConfig();

    static Map<String, String> HTTP_PARAS = new HashMap<String, String>(1, 1);

    static {
        // HTTP_PARAS.put(HttpClientService.P_MIMETYPE,
        // "application/x-www-form-urlencoded");
        // HTTP_PARAS.put(HttpClientService.P_METHOD, "post");
    }

    @Override
    public boolean send(String id, String mobile, String content) {
        String data;
        try {
            data = "uid=" + _config.getConf(id, YunsmsConfig.Uid) + "&pwd=" + _config.getConf(id, YunsmsConfig.Pwd) + "&mobile=" + mobile
                    + "&content=" + java.net.URLEncoder.encode(content, "utf-8") + "&encode=utf8";

            String res = _http.send(id, _config.getConf(id, YunsmsConfig.HttpTx), data, null, HTTP_PARAS);
            LOG.debug("id-{} mobile-{} res-{}", id, mobile, res);

            return "100".equals(res) ? true : false;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e.fillInStackTrace());
        }
        return false;
    }

    @Start
    void start() {
        try {
            String conf = plugin.getConfig(FILE_CONF);
            if (!new File(conf).exists()) {
                LOG.error("Not found yunsms.properties -> {}", conf);
                return;
            }

            start(new FileInputStream(conf));
            LOG.info("YunsmsService start successfully!");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e.fillInStackTrace());
        }
    }

    public void start(InputStream is) throws Exception {
        _config.init(is);
        HTTP_PARAS.put("rsp.charset", _config.getConf(null, YunsmsConfig.HttpEncode, "gbk"));
    }

    @Stop
    void stop() {
        _config = null;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using PeanutButter.XmlUtils;
// ReSharper disable MemberCanBePrivate.Global

namespace NugetPackageVersionIncrementer
{
    public class NuspecVersionIncrementer
    {
        public string Version { get; set; }
        public string PackageId { get; private set; }
        private XDocument _doc;

        public NuspecVersionIncrementer(string nuspec)
        {
            if (string.IsNullOrWhiteSpace(nuspec)) throw new ArgumentException("Nuspec is not valid XML", nameof(nuspec));
            Parse(nuspec.Trim());
        }

        private void Parse(string nuspec)
        {
            try
            {
                _doc = XDocument.Parse(nuspec);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Nuspec is not valid XML: " + ex.Message, nameof(nuspec));
            }
            GrokVersion();
            GrokPackageId();
        }

        private void GrokPackageId()
        {
            var idNode = _doc.XPathSelectElements("/package/metadata/id").FirstOrDefault();
            if (idNode == null) throw new Exception("No package id node found");
            PackageId = idNode.Text();
        }

        private void GrokVersion()
        {
            var node = FindVersionNode();
            if (node == null) return;
            Version = node.Text();
        }

        private XElement FindVersionNode()
        {
            return _doc.XPathSelectElements("/package/metadata/version").FirstOrDefault();
        }

        public void IncrementMinorVersion()
        {
            if (string.IsNullOrEmpty(Version))
            {
                Version = "0.0.1";
                return;
            }
            var versionNumbers = GetVersionAsNumbers().ToArray();
            var minor = versionNumbers.Last();
            var preMinor = versionNumbers.Reverse().Skip(1).Reverse();
            var incremented = new List<int>(preMinor) {minor + 1};
            Version = string.Join(".", incremented);
        }

        private IEnumerable<int> GetVersionAsNumbers()
        {
            return Version.Split('.').Select(GetIntFrom);
        }

        private int GetIntFrom(string part)
        {
            int result;
            if (int.TryParse(part, out result))
                return result;
            return 0;
        }

        public string GetUpdatedNuspec()
        {
            var versionNode = FindVersionNode();
            if (versionNode == null) throw new Exception("Unable to find version node in nuspec");
            versionNode.Value = Version;
            return _doc.ToString();
        }
    }
}


text:
<component name="libraryTable">
  <library name="Maven: org.jenkins-ci.lib:lib-jenkins-maven-artifact-manager:1.2">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jenkins-ci/lib/lib-jenkins-maven-artifact-manager/1.2/lib-jenkins-maven-artifact-manager-1.2.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/jenkins-ci/lib/lib-jenkins-maven-artifact-manager/1.2/lib-jenkins-maven-artifact-manager-1.2-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jenkins-ci/lib/lib-jenkins-maven-artifact-manager/1.2/lib-jenkins-maven-artifact-manager-1.2-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
This takes an input list of "IPv7 Addresses" and counts the number of addresses
that support "TLS" (Transport-Layer Snooping)

An IP supports TLS if it has an "ABBA" sequence of characters anywhere in its
address, for example a sequence like `xyyx` or `abba`. However, if it contains
an ABBA inside the square bracket parts of the address, then it **DOES NOT**
support TLS.

For examples:

- `abba[mnop]qrst` supports TLS (`abba` outside square brackets)
- `abcd[bddb]xyyx` does **not** (`bddb` is inside square brackets, even though
  `xyyx` is outside brackets)
- `aaaa[qwer]tyui` does **not** (`aaaa` is invalid; the interior characters
  must be different)
- `ioxxoj[asdfgh]zxcvbn` supports TLS (`oxxo` is outside square brackets,
  even though it's within a larger string)

It also counts the IP addresses that support "SSL" (Super-Secret Listening).
An IP supports SSL if it has an "ABA" sequence anywhere in the non-bracketed
parts, and additionally a "BAB" inside the bracketed parts.

An ABA is any three-character sequence that consists of the same character
twice with a different character between them, such as `xyx` or `aba`. A
corresponding BAB is the same characters but in reversed positions: `yxy` and
`bab`, respectively.

Examples:

- `aba[bab]xyz` supports SSL (`aba` outside sqaure brackets and `bab` inside)
- `xyx[xyx]xyx` does NOT support SSL (`xyx` but no corresponding `yxy`)
- `aaa[kek]eke` supports SSL (`eke` outside the brackets and `kek` inside)
- `zazbz[bzb]cdb` supports SSL (`zaz` has no corresponding `aza`, but `zbz`
  has a corresponding `bzb`, even though `zaz` and `zbz` overlap)

## Implementation Details

Something I particularly like in my code is my `SlidingWindow` function, which
handles the logic of moving a sliding window of arbitrary size across an input
string, calls a comparator function for each slice to determine whether it's
what the caller wanted, and lets the caller abort the loop and return the last
result checked.

For example, to find the first ABBA sequence and stop:

```go
abba := SlidingWindow(input, 4, func(slice string) bool {
    return slice[0] == slice[3] && slice[1] == slice[2] && slice[0] != slice[1]
})
```

Or to populate a map of *all* valid ABA/BAB sequences (the loop doesn't
terminate early like in the above example):

```go
SlidingWindow(input, 3, func(slice string) bool {
    if slice[0] == slice[2] && slice[0] != slice[1] {
        result[slice] = true
    }
    return false
})
```


text:
namespace TraktApiSharp.Requests.Search
{
    using Enums;
    using Extensions;
    using System;
    using System.Collections.Generic;

    internal sealed class SearchIdLookupRequest : ASearchRequest
    {
        internal TraktSearchIdType IdType { get; set; }

        internal string LookupId { get; set; }

        public override string UriTemplate => "search/{id_type}/{id}{?type,extended,page,limit}";

        public override IDictionary<string, object> GetUriPathParameters()
        {
            var uriParams = base.GetUriPathParameters();

            uriParams.Add("id_type", IdType.UriName);
            uriParams.Add("id", LookupId);

            if (ResultTypes != null && ResultTypes != TraktSearchResultType.Unspecified)
                uriParams.Add("type", ResultTypes.UriName);

            return uriParams;
        }

        public override void Validate()
        {
            if (IdType == null)
                throw new ArgumentNullException(nameof(IdType));

            if (IdType == TraktSearchIdType.Unspecified)
                throw new ArgumentException("id type must not be unspecified", nameof(IdType));

            if (LookupId == null)
                throw new ArgumentNullException(nameof(LookupId));

            if (LookupId == string.Empty || LookupId.ContainsSpace())
                throw new ArgumentException("lookup id is not valid", nameof(LookupId));
        }
    }
}


text:
#ifndef PERFMON_H
#define PERFMON_H

extern int perfmon_start(void);

#endif   /* PERFMON_H */


text:
/**
 * @file
 * @brief Internal string buffer handing.  Unless you're writing a
 *        json_object_to_json_string_fn implementation for use with
 *        json_object_set_serializer() direct use of this is not
 *        recommended.
 */
#ifndef _printbuf_h_
#define _printbuf_h_

#ifdef __cplusplus
extern "C" {
#endif

struct printbuf {
  char *buf;
  int bpos;
  int size;
};
typedef struct printbuf printbuf;

extern struct printbuf*
printbuf_new(void);

/* As an optimization, printbuf_memappend_fast() is defined as a macro
 * that handles copying data if the buffer is large enough; otherwise
 * it invokes printbuf_memappend() which performs the heavy
 * lifting of realloc()ing the buffer and copying data.
 *
 * Your code should not use printbuf_memappend() directly unless it
 * checks the return code. Use printbuf_memappend_fast() instead.
 */
extern int
printbuf_memappend(struct printbuf *p, const char *buf, int size);

#define printbuf_memappend_fast(p, bufptr, bufsize)          \
do {                                                         \
  if ((p->size - p->bpos) > bufsize) {                       \
    memcpy(p->buf + p->bpos, (bufptr), bufsize);             \
    p->bpos += bufsize;                                      \
    p->buf[p->bpos]= '\0';                                   \
  } else {  printbuf_memappend(p, (bufptr), bufsize); }      \
} while (0)

#define printbuf_length(p) ((p)->bpos)

/**
 * Results in a compile error if the argument is not a string literal.
 */
#define _printbuf_check_literal(mystr) ("" mystr)

/**
 * This is an optimization wrapper around printbuf_memappend() that is useful
 * for appending string literals. Since the size of string constants is known
 * at compile time, using this macro can avoid a costly strlen() call. This is
 * especially helpful when a constant string must be appended many times. If
 * you got here because of a compilation error caused by passing something
 * other than a string literal, use printbuf_memappend_fast() in conjunction
 * with strlen().
 *
 * See also:
 *   printbuf_memappend_fast()
 *   printbuf_memappend()
 *   sprintbuf()
 */
#define printbuf_strappend(pb, str) \
   printbuf_memappend ((pb), _printbuf_check_literal(str), sizeof(str) - 1)

/**
 * Set len bytes of the buffer to charvalue, starting at offset offset.
 * Similar to calling memset(x, charvalue, len);
 *
 * The memory allocated for the buffer is extended as necessary.
 *
 * If offset is -1, this starts at the end of the current data in the buffer.
 */
extern int
printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len);

/**
 * Formatted print to printbuf.
 *
 * This function is the most expensive of the available functions for appending
 * string data to a printbuf and should be used only where convenience is more
 * important than speed. Avoid using this function in high performance code or
 * tight loops; in these scenarios, consider using snprintf() with a static
 * buffer in conjunction with one of the printbuf_*append() functions.
 *
 * See also:
 *   printbuf_memappend_fast()
 *   printbuf_memappend()
 *   printbuf_strappend()
 */
extern int
sprintbuf(struct printbuf *p, const char *msg, ...);

extern void
printbuf_reset(struct printbuf *p);

extern void
printbuf_free(struct printbuf *p);

#ifdef __cplusplus
}
#endif

#endif


text:
@class SCCard;

@interface SCDeck : NSObject

- (void)addCard:(SCCard *)card;
- (void)addCard:(SCCard *)card atTop:(BOOL)atTop;

- (SCCard *)drawRandomCard;

@end


text:
package sign

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rand"

	"github.com/open-policy-agent/opa/topdown/internal/jwx/jwa"

	"github.com/pkg/errors"
)

var ecdsaSignFuncs = map[jwa.SignatureAlgorithm]ecdsaSignFunc{}

func init() {
	algs := map[jwa.SignatureAlgorithm]crypto.Hash{
		jwa.ES256: crypto.SHA256,
		jwa.ES384: crypto.SHA384,
		jwa.ES512: crypto.SHA512,
	}

	for alg, h := range algs {
		ecdsaSignFuncs[alg] = makeECDSASignFunc(h)
	}
}

func makeECDSASignFunc(hash crypto.Hash) ecdsaSignFunc {
	return ecdsaSignFunc(func(payload []byte, key *ecdsa.PrivateKey) ([]byte, error) {
		curveBits := key.Curve.Params().BitSize
		keyBytes := curveBits / 8
		// Curve bits do not need to be a multiple of 8.
		if curveBits%8 > 0 {
			keyBytes++
		}
		h := hash.New()
		h.Write(payload)
		r, s, err := ecdsa.Sign(rand.Reader, key, h.Sum(nil))
		if err != nil {
			return nil, errors.Wrap(err, "failed to sign payload using ecdsa")
		}

		rBytes := r.Bytes()
		rBytesPadded := make([]byte, keyBytes)
		copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)

		sBytes := s.Bytes()
		sBytesPadded := make([]byte, keyBytes)
		copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)

		out := append(rBytesPadded, sBytesPadded...)
		return out, nil
	})
}

func newECDSA(alg jwa.SignatureAlgorithm) (*ECDSASigner, error) {
	signfn, ok := ecdsaSignFuncs[alg]
	if !ok {
		return nil, errors.Errorf(`unsupported algorithm while trying to create ECDSA signer: %s`, alg)
	}

	return &ECDSASigner{
		alg:  alg,
		sign: signfn,
	}, nil
}

// Algorithm returns the signer algorithm
func (s ECDSASigner) Algorithm() jwa.SignatureAlgorithm {
	return s.alg
}

// Sign signs payload with a ECDSA private key
func (s ECDSASigner) Sign(payload []byte, key interface{}) ([]byte, error) {
	if key == nil {
		return nil, errors.New(`missing private key while signing payload`)
	}

	privateKey, ok := key.(*ecdsa.PrivateKey)
	if !ok {
		return nil, errors.Errorf(`invalid key type %T. *ecdsa.PrivateKey is required`, key)
	}

	return s.sign(payload, privateKey)
}


text:
(function () {
  if (typeof require === 'undefined' && typeof window !== 'undefined') {

    var modules = {};
    window.require = baseRequire();

    function resolve(basePath, path) {
      if (path.substr(-3) !== '.js') {
        path = path + '.js';
      }
      var pathSegments;
      if (path[0] === '/') {
        pathSegments = ['']; // '/'.split().pop()
      }
      else {
        pathSegments = basePath.split('/');
        pathSegments.pop();
      }
      var segment;
      var segments = path.split('/');
      for (var i = 0; i < segments.length; i++) {
        segment = segments[i];
        if (segment === '..') {
          pathSegments.pop();
        }
        else if (segment !== '' && segment !== '.') {
          pathSegments.push(segment);
        }
      }
      return pathSegments.join('/');
    }

    function loadFile(path) {
      var request = new XMLHttpRequest();
      request.open('GET', path, false);  // `false` makes the request synchronous
      request.send(null);

      if (request.status === 200) {
        return request.responseText;
      }
      else {
        throw new Error('cannot load file');
      }
    }

    function loadScript(path) {
      var script = document.createElement("script")
      script.type = "text/javascript";
      script.src = path;
      document.getElementsByTagName("head")[0].appendChild(script);
    }

    function loadModule(origin, path, module) {
      var code = loadFile(path);
      // adds the code to the source view of chrome dev tools
      code = code + '//# sourceURL=' + origin + path;
      var fn;
      try {
        fn = new Function('require', 'module', 'exports', code);
      }
      catch (e) {
        if (e instanceof SyntaxError) {
          // there is a syntax error in the file
          // load the file as a script so the browser should display the location of the syntax error
          loadScript(path);
          return;
        }
        else {
          throw e;
        }
      }
      fn.displayName = path; // sets a friendly name for the call stack
      var exports = module.exports = {};
      var moduleRequire = baseRequire(origin, path);
      fn(moduleRequire, module, exports);
      module.path = path;
    }

    function getPathInfo() {
      var currentScript = document.currentScript || (function() {
        var scripts = document.getElementsByTagName('script');
        return scripts[scripts.length - 1];
      })();
      var location;
      var baseUrl = currentScript.attributes.getNamedItem('src');
      if (baseUrl !== null) {
        location = baseUrl.value;
      } else {
        location = window.location.href;
      }
      var a = document.createElement('a');
      a.href = location;
      var origin = a.origin;
      var pathName = a.pathname;
      var basePath = pathName.substring(0, pathName.lastIndexOf('/') + 1);
      return {
        origin: origin,
        basePath: basePath
      };
    }

    function baseRequire(origin, basePath) {
      function require(path) {
        if (require.basePath == null) {
          var pathInfo = getPathInfo();
          require.origin = pathInfo.origin;
          require.basePath = pathInfo.basePath;
        }
        var modulePath = resolve(require.basePath, path);
        var module;
        if (modulePath in modules) {
          module = modules[modulePath];
        }
        else {
          // this fixes cyclic modules
          module = modules[modulePath] = {};
          loadModule(require.origin, modulePath, module);
        }
        return module.exports;
      }
      require.origin = origin;
      require.basePath = basePath;
      return require;
    }
  }
}());