text:
from cinder_data.model import DjangoModel
from cinder_data.store import Store
from cinder_data.cache import MemoryCache
from schematics.types import StringType

class Manufacturer(DjangoModel):
    """Cinder data model for Manufacturer api endpoint."""

    name = StringType()

class Car(DjangoModel):
    """Cinder data model for Car api endpoint."""

    name = StringType()

class CinderDataLibrary(object):
    """Robot framework cinder data libary for the example server."""

    def __init__(self):
        """Initialise the store with an in-memory cache."""
        cache = MemoryCache()
        self._store = Store('http://server:8000', 'api/v1', cache=cache)

    @staticmethod
    def _get_model_class(model_name):
        """A help function to a turn a string into the class of the same name.

        Needed because arguments from robot test scripts are strings.
        """
        if model_name == 'Manufacturer':
            return Manufacturer
        if model_name == 'Car':
            return Car

    def get_model(self, model, model_id):
        """Get a single model from the server.

        Args:
            model (string): The class as a string.
            model_id (string): The integer ID as a string.

        Returns:
            :class:`cinder_data.model.CinderModel`: A instance of the model.
        """
        return self._store.find_record(self._get_model_class(model), int(model_id))

    def get_models(self, model, page=None):
        """Get all the models from the server.

        Args:
            model (string): The class as a string.
            page (string, optional): The page number as a string

        Returns:
            list: A list of instances of the requested model.
        """
        if page is not None:
            return self._store.find_all(self._get_model_class(model), params={'page': int(page)})
        else:
            return self._store.find_all(self._get_model_class(model))

    def peek_models(self, model):
        """Get all the models from the stores cache.

        Args:
            model (string): A class as a string.

        Returns:
            list: A list of instances of the requested model.
        """
        return self._store.peek_all(self._get_model_class(model))


text:
/**
 * The VFS Service
 *
 * The VFS Service, a collection of endpoints used by the application
 *
 * @module services/vfs.service
 * @property {String} name The name of the module.
 */
define(
    [
      "../../components/utils"
    ],
    function (utils) {
      "use strict";

      var factoryArray = ["helperService", "$http", "$q", factory];
      var module = {
        name: "vfsService",
        factory: factoryArray
      };

      return module;

      /**
       * The dataService factory
       *
       * @param {Object} helperService
       * @param {Object} $http - The $http angular helper service
       * @param {Object} $q
       *
       * @return {Object} The dataService api
       */
      function factory(helperService, $http, $q) {
        var baseUrl = "/cxf/browser-new";
        return {
          provider: "vfs",
          order: 0,
          root: "VFS Connections",
          matchPath: matchPath,
          selectFolder: selectFolder,
          getBreadcrumbPath: getBreadcrumbPath,
          getPath: getPath,
          getFilesByPath: getFilesByPath,
          createFolder: createFolder,
          addFolder: addFolder,
          deleteFiles: deleteFiles,
          renameFile: renameFile,
          isCopy: isCopy,
          open: open,
          save: save,
          resolvePath: resolvePath
        };

        function resolvePath(path, properties) {
          var self = this;
          return $q(function (resolve, reject) {
            if (path.indexOf("pvfs://") === 0) {
              resolve(self.root + "/" + path.replace("pvfs://", ''));
            } else if (properties && properties.connection) {
              resolve(self.root + "/" + properties.connection + "/" + path.replace(/^[\w]+:\/\//, ''));
            } else {
              reject(path);
            }
          });
        }

        function getPath(file) {
          return file.root ? _getTreePath(file) : file.path;
        }

        function matchPath(path) {
          return (path && path.match(/^[\w]+:\/\//) != null) ? .5 : 0;
        }

        function selectFolder(folder, filters, useCache) {
          return $q(function (resolve, reject) {
            if ((folder.path && !folder.loaded) || (!folder.path && !folder.loaded && folder.connection)) {
              getFiles(folder, filters, useCache).then(function (response) {
                folder.children = response.data;
                folder.loaded = true;
                for (var i = 0; i < folder.children.length; i++) {
                  folder.children[i].connection = folder.connection;
                  folder.children[i].provider = folder.provider;
                }
                resolve();
              });
            } else {
              resolve();
            }
          });
        }

        function getBreadcrumbPath(file) {
          return {
            type: "vfs",
            fileType: file.type ? file.type : "folder",
            prefix: _getFilePrefix(file),
            uri: _getFilePath(file),
            path: _getTreePath(file)
          };
        }

        function _getFilePrefix(file) {
          if (file.root) {
            return null;
          }
          return file.path ? file.path.match(/^[\w]+:\/\//)[0] : null;
        }

        function _getTreePath(folder) {
          if (!folder.path) {
            return folder.root ? folder.root + "/" + folder.name : folder.name;
          }
          if (folder.connection) {
            return folder.root + "/" + (folder.connection ? folder.connection + "/" : "") + folder.path.replace(/^[\w]+:\/\//, "");
          }
          return folder.path.replace(/^[\w]+:\/\//, "");
        }

        function _getFilePath(file) {
          if (file.connectionPath) {
            return file.connectionPath;
          }
          return file.path ? file.path : null;
        }

        /**
         *
         * @param node
         * @param name
         * @returns {*}
         */
        function createFolder(node, name) {
          return $q(function (resolve, reject) {
            if ((node.path && !node.loaded) || (!node.path && !node.loaded && node.connection)) {
              getFiles(node).then(function (response) {
                node.loaded = true;
                resolve(response.data);
              });
            } else {
              reject();
            }
          });
        }

        function getFilesByPath(path, useCache) {
          return getFiles({path: path, provider: "vfs"}, undefined, useCache);
        }

        /**
         * Gets the directory tree for the currently connected repository
         *
         * @return {Promise} - a promise resolved once data is returned
         */
        function getFiles(folder, filters, useCache) {
          var parameters = {
            "filters": filters,
            "useCache": useCache
          };
          return helperService.httpPost([baseUrl, "getFiles"].join("/") + utils.buildParameters(parameters), folder);
        }

        function addFolder(folder) {
          return helperService.httpPut([baseUrl, "add"].join("/"), folder);
        }

        function deleteFiles(files) {
          return helperService.httpPost([baseUrl, "delete"].join("/"), files);
        }

        function renameFile(file, newPath) {
          return $q(function (resolve, reject) {
            helperService.httpPost([baseUrl, "rename"].join("/") + "?newPath=" + newPath, file).then(function (response) {
              file.path = newPath;
            });
          });
        }

        function isCopy(from, to) {
          return from.provider !== to.provider || from.connection !== to.connection;
        }

        function open(file) {
          select(null, file.name, _getFilePath(file), file.parent, file.connection, file.provider, null);
        }

        function save(filename, folder, currentFilename, override) {
          select(null, filename, null, folder.path, folder.connection, folder.provider, null);
          return $q.resolve();
        }
      }
    });

redpajama_set_name: RedPajamaGithub


text:
from ..lib import elasticbeanstalk, aws
from ..core import io
from . import commonops

def deploy(app_name, env_name, version, label, message, staged=False,
           timeout=5):
    region_name = aws.get_region_name()

    io.log_info('Deploying code to ' + env_name + " in region " + (region_name or 'default'))

    if version:
        app_version_label = version
    else:
        # Create app version
        app_version_label = commonops.create_app_version(
            app_name, label=label, message=message, staged=staged)

    # swap env to new app version
    request_id = elasticbeanstalk.update_env_application_version(
        env_name, app_version_label)

    commonops.wait_for_success_events(request_id,
                                      timeout_in_minutes=timeout,
                                      can_abort=True)


text:
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template5", checking_point=8, path_list=[
		[TestAction.create_vm, 'vm1', 'flag=sblk'],
		[TestAction.create_volume, 'volume1', 'flag=ceph,scsi'],
		[TestAction.attach_volume, 'vm1', 'volume1'],
		[TestAction.create_volume, 'volume2', 'flag=sblk,scsi'],
		[TestAction.attach_volume, 'vm1', 'volume2'],
		[TestAction.create_volume, 'volume3', 'flag=ceph,scsi'],
		[TestAction.attach_volume, 'vm1', 'volume3'],
		[TestAction.create_volume_snapshot, 'volume2', 'volume2-snapshot1'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.use_volume_snapshot, 'volume2-snapshot1'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot2'],
		[TestAction.reboot_vm, 'vm1'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.use_volume_snapshot, 'volume2-snapshot1'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot6'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.use_vm_snapshot, 'vm1-snapshot2'],
		[TestAction.start_vm, 'vm1'],
])

'''
The final status:
Running:['vm1']
Stopped:[]
Enadbled:['volume2-snapshot1', 'vm1-snapshot2', 'volume1-snapshot2', 'volume2-snapshot2', 'volume3-snapshot2', 'vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6', 'volume3-snapshot6']
attached:['volume1', 'volume2', 'volume3']
Detached:[]
Deleted:[]
Expunged:[]
Ha:[]
Group:
	vm_snap2:['vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6', 'volume3-snapshot6']---vm1volume1_volume2_volume3
	vm_snap1:['vm1-snapshot2', 'volume1-snapshot2', 'volume2-snapshot2', 'volume3-snapshot2']---vm1volume1_volume2_volume3
'''


text:
rm -rf main-cookbooks/kubernetes-stack-cookbook/Berksfile.lock # always install the latest

berks vendor -b main-cookbooks/kubernetes-stack-cookbook/Berksfile --delete && rm -rf berks-cookbooks/kubernetes-stack-cookbook

chown 1000:1000 main-cookbooks/kubernetes-stack-cookbook/Berksfile.lock


text:
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc import sstruct
from . import DefaultTable
import array

hdmxHeaderFormat = """
	>   # big endian!
	version:	H
	numRecords:	H
	recordSize:	l
"""

try:
	from collections.abc import Mapping
except:
	from UserDict import DictMixin as Mapping

class _GlyphnamedList(Mapping):

	def __init__(self, reverseGlyphOrder, data):
		self._array = data
		self._map = dict(reverseGlyphOrder)

	def __getitem__(self, k):
		return self._array[self._map[k]]

	def __len__(self):
		return len(self._map)

	def __iter__(self):
		return iter(self._map)

	def keys(self):
		return self._map.keys()

class table__h_d_m_x(DefaultTable.DefaultTable):

	def decompile(self, data, ttFont):
		numGlyphs = ttFont['maxp'].numGlyphs
		glyphOrder = ttFont.getGlyphOrder()
		dummy, data = sstruct.unpack2(hdmxHeaderFormat, data, self)
		self.hdmx = {}
		for i in range(self.numRecords):
			ppem = byteord(data[0])
			maxSize = byteord(data[1])
			widths = _GlyphnamedList(ttFont.getReverseGlyphMap(), array.array("B", data[2:2+numGlyphs]))
			self.hdmx[ppem] = widths
			data = data[self.recordSize:]
		assert len(data) == 0, "too much hdmx data"

	def compile(self, ttFont):
		self.version = 0
		numGlyphs = ttFont['maxp'].numGlyphs
		glyphOrder = ttFont.getGlyphOrder()
		self.recordSize = 4 * ((2 + numGlyphs + 3) // 4)
		pad = (self.recordSize - 2 - numGlyphs) * b"\0"
		self.numRecords = len(self.hdmx)
		data = sstruct.pack(hdmxHeaderFormat, self)
		items = sorted(self.hdmx.items())
		for ppem, widths in items:
			data = data + bytechr(ppem) + bytechr(max(widths.values()))
			for glyphID in range(len(glyphOrder)):
				width = widths[glyphOrder[glyphID]]
				data = data + bytechr(width)
			data = data + pad
		return data

	def toXML(self, writer, ttFont):
		writer.begintag("hdmxData")
		writer.newline()
		ppems = sorted(self.hdmx.keys())
		records = []
		format = ""
		for ppem in ppems:
			widths = self.hdmx[ppem]
			records.append(widths)
			format = format + "%4d"
		glyphNames = ttFont.getGlyphOrder()[:]
		glyphNames.sort()
		maxNameLen = max(map(len, glyphNames))
		format = "%" + repr(maxNameLen) + 's:' + format + ' ;'
		writer.write(format % (("ppem",) + tuple(ppems)))
		writer.newline()
		writer.newline()
		for glyphName in glyphNames:
			row = []
			for ppem in ppems:
				widths = self.hdmx[ppem]
				row.append(widths[glyphName])
			if ";" in glyphName:
				glyphName = "\\x3b".join(glyphName.split(";"))
			writer.write(format % ((glyphName,) + tuple(row)))
			writer.newline()
		writer.endtag("hdmxData")
		writer.newline()

	def fromXML(self, name, attrs, content, ttFont):
		if name != "hdmxData":
			return
		content = strjoin(content)
		lines = content.split(";")
		topRow = lines[0].split()
		assert topRow[0] == "ppem:", "illegal hdmx format"
		ppems = list(map(int, topRow[1:]))
		self.hdmx = hdmx = {}
		for ppem in ppems:
			hdmx[ppem] = {}
		lines = (line.split() for line in lines[1:])
		for line in lines:
			if not line:
				continue
			assert line[0][-1] == ":", "illegal hdmx format"
			glyphName = line[0][:-1]
			if "\\" in glyphName:
				from fontTools.misc.textTools import safeEval
				glyphName = safeEval('"""' + glyphName + '"""')
			line = list(map(int, line[1:]))
			assert len(line) == len(ppems), "illegal hdmx format"
			for i in range(len(ppems)):
				hdmx[ppems[i]][glyphName] = line[i]


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2017 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="@integer/list_item_level_default" android:drawable="@drawable/oval_surface_1" />
    <item android:maxLevel="@integer/list_item_level_selected">
        <shape android:shape="oval">
            <solid android:color="@macro/default_control_color_active" />
        </shape>
    </item>
    <item android:maxLevel="@integer/list_item_level_incognito">
        <shape android:shape="oval">
            <solid android:color="@color/white_alpha_70" />
        </shape>
    </item>
</level-list>


text:
import os
import logging

import redis

from portingdb import htmlreport

level = logging.INFO
logging.basicConfig(level=level)
logging.getLogger('sqlalchemy.engine').setLevel(level)

sqlite_path = os.getcwd() + '/portingdb.sqlite'

db_url = 'sqlite:///' + sqlite_path

redis_configured = all(
    var in os.environ for var in
    ('REDIS_SERVICE_HOST', 'REDIS_SERVICE_PORT', 'REDIS_PASSWORD'))

cache_config = {
    'backend': 'dogpile.cache.redis',
    'expiration_time': 3600,  # 1h
    'arguments': {
        'host': os.environ['REDIS_SERVICE_HOST'],
        'port': os.environ['REDIS_SERVICE_PORT'],
        'password': os.environ['REDIS_PASSWORD'],
        'db': 0,
        'redis_expiration_time': 3600 + 600,  # 1h 10min
        'distributed_lock': True
    }
} if redis_configured else None

application = htmlreport.create_app(db_url=db_url, cache_config=cache_config)

if __name__ == '__main__':
    if redis_configured:
        # Clear the Redis cache
        r = redis.StrictRedis(
            host=os.environ['REDIS_SERVICE_HOST'],
            port=os.environ['REDIS_SERVICE_PORT'],
            password=os.environ['REDIS_PASSWORD'],
            db=0,
        )
        r.flushdb()
    application.run(host='0.0.0.0', port=8080)


text:
namespace _geom{
	namespace R3{
		typedef int3 GridIndex;
		typedef list<GridIndex> GridIndexList;

		typedef grid::GridTopology<3> Grid;

		template <class type> class ObjectGrid : public grid::ObjectGrid<type,3,Grid>{
		private:
			typedef grid::ObjectGrid<type,3,Grid> parent;
		public:
			ObjectGrid(const int3 & size = int3(0,0,0),double CellSize = 1.0):parent(size,CellSize){
			};
		};
	};
};

#endif


text:
A proof-of-concept Argon2 GPU password cracker.

**This project is discontinued!** See [here](https://gitlab.com/omos/argon2-gpu) for a better, rewritten version.


text:
{% set scriptdir = '../common/js/' %}
{% set cssdir = '../common/css/' %}
{% extends "templates/base.tmpl" %}
{% block pagetitle %}Juno{% endblock %}
{% block title %}{% endblock %}
{% block header %}
{% endblock header %}
{% block content %}

Welcome to OpenStack Documentation

                    What is OpenStack? OpenStack is a cloud operating system that controls large pools of compute, storage, and networking resources throughout a datacenter, all managed through a dashboard that gives administrators control while empowering their users to provision resources through a web interface.

What are the next steps?

                View The Docs
                Get OpenStack
                Get Training
                <form class="docs-main-search-form">

       <gcse:search gname="standard" as_sitesearch="docs.openstack.org">
       </gcse:search>
       </form>

Documentation for Juno (October 2014)

This is an earlier OpenStack release. Use the menu to select a later release, if needed.

            {% include 'templates/dropdown_releases_and_languages.tmpl' %}

 Install Guides

Getting started with the most commonly used OpenStack services

                        Installation Guide for openSUSE 13.1 and SUSE Linux Enterprise Server 11
                        Installation Guide for Red Hat Enterprise Linux 7, CentOS 7, and Fedora 20
                        Installation Guide for Ubuntu 14.04 (LTS)

                        {% include 'templates/ops_and_admin_guides.tmpl' %}
                        Networking Guide

Deploy and manage OpenStack Networking (neutron)

 Configuration Guides

                        Configuration Reference

Installation and configuration options for OpenStack

                    {% include 'templates/api_guides.tmpl' %}

                    {% include 'templates/user_guides.tmpl' %}
                    {% include 'templates/project_guides.tmpl' %}
                    {% include 'templates/contributor_guides.tmpl' %}
                    {% include 'templates/training_guides.tmpl' %}

Documentation treated like code, powered by the community - interested?

                    How To Contribute

{% endblock content %}


text:
@extends(soda_cms_view_path('layouts.inner'))

@section('breadcrumb')

        @section('breadcrumb')

Home

Reports

Individual Votes

        @stop

@stop

@section('head.cms')
    <title>Individual Votes | Reports</title>
@endsection

@section('content-heading-button')
    @include(soda_cms_view_path('partials.buttons.create'), ['url' => route('voting.categories.get.modify')])
@endsection

@include(soda_cms_view_path('partials.heading'), [
    'icon'        => 'fa fa-copy',
    'title'       => 'Individual Votes',
])

@section('content')

        {!! $filter !!}

        {!! $grid  !!}

@endsection


text:
mkdir temp && cp -r ./meta.json ./README.md ./images/* temp
perl -i -0777 -pe 's/(<!--toc-->).*(<!--endtoc-->)/'"$"'$2/s' ./temp/README.md
sed -i.bak 's|https://rawgit.com/mgechev/angularjs-in-patterns/master/images|.|g' ./temp/README.md
rm -rf ./temp/*.bak
mv ./temp/README.md ./temp/index.md
./node_modules/.bin/generate-md --layout minko-book --input ./temp --output ../angularjs-in-patterns-gh-pages
rm -rf temp


text:
using DragonSpark.Extensions;
using DragonSpark.Sources.Parameterized.Caching;
using DragonSpark.TypeSystem;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;

namespace DragonSpark.Sources.Parameterized
{
	public abstract class TypeLocatorBase : FactoryCache<Type, Type>
	{
		readonly ImmutableArray<TypeAdapter> adapters;
		readonly Func<TypeInfo, bool> isAssignable;
		readonly Func<Type[], Type> selector;

		protected TypeLocatorBase( params Type[] types ) : this( types.Select( type => type.Adapt() ).ToImmutableArray() ) {}

		TypeLocatorBase( ImmutableArray<TypeAdapter> adapters )
		{
			this.adapters = adapters;
			isAssignable = IsAssignable;
			selector = From;
		}

		protected override Type Create( Type parameter )
		{
			var result = parameter.Append( parameter.Adapt().GetAllInterfaces() )
								  .AsTypeInfos()
								  .Where( isAssignable )
								  .Select( info => info.GenericTypeArguments )
								  .Select( selector )
								  .FirstOrDefault();
			return result;
		}

		bool IsAssignable( TypeInfo type ) => type.IsGenericType && adapters.IsAssignableFrom( type.GetGenericTypeDefinition() );

		protected abstract Type From( IEnumerable<Type> genericTypeArguments );
	}
}


text:
<?php

namespace winzou\Bundle\EbaySDKBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use DTS\eBaySDK\Constants\GlobalIds;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $treeBuilder
            ->root('winzou_ebay_sdk')
            ->children()
                ->scalarNode('app_id')->isRequired()->end()
                ->scalarNode('global_id')->defaultValue(GlobalIds::US)->end()
                ->booleanNode('sandbox')->defaultFalse()->end()
            ->end()
        ;

        return $treeBuilder;
    }
}


text:
  #include <Streaming.h>
#endif

template <size_t MAX_SIZE>
IntArray<MAX_SIZE>::IntArray()
{
  clear();
}

template <size_t MAX_SIZE>
IntArray<MAX_SIZE>::IntArray(int _startRange, int _endRange) {
  clear();
  range(_startRange, _endRange);
}

template <size_t MAX_SIZE>
void IntArray<MAX_SIZE>::range(int _startRange, int _endRange) {
  clear();

  if(_endRange < _startRange) {
    return;
  }

  for(int i = _startRange; i <= _endRange; i++) {

    #ifdef DEBUG_INT_ARRAY
      Serial << "IntArray #range - pushing:" << i << endl;
    #endif

    push(i);
  }
}

#endif


text:
We made thousands of pre-made source code pieces for easy implementation in your own programming projects. Want to read barcode from memory in your C++ (Unmanaged) app? ByteScout BarCode Reader SDK is designed for it. ByteScout BarCode Reader SDK is the SDK for barcode decoding. Can read all popular types from Code 128, GS1, UPC and Code 39 to QR Code, Datamatrix, PDF417. Images, pdf, TIF images and live web camera are supported as input. Designed to handle documents with noise and defects. Includes optional splitter and merger for pdf and tiff based on barcodes. Batch mode is optimized for high performance with multiple threads. Decoded values can be exported to XML, JSON, CSV or into custom data format.

This code snippet below for ByteScout BarCode Reader SDK works best when you need to quickly read barcode from memory in your C++ (Unmanaged) application. This C++ (Unmanaged) sample code is all you need for your app. Just copy and paste the code, add references (if needs to) and you are all set! Code testing will allow the function to be tested and work properly with your data.

Download free trial version of ByteScout BarCode Reader SDK from our website with this and other source code samples for C++ (Unmanaged).

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20BarCode%20Reader%20SDK%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20BarCode%20Reader%20SDK%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=EARSPJFIJMU](https://www.youtube.com/watch?v=EARSPJFIJMU)

<!-- code block begin -->

##### ****ReadFromMemory.cpp:**

```
// ReadFromMemory.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "atlbase.h"

#import "c:\\Program Files\\Bytescout BarCode Reader SDK\\net4.00\\Bytescout.BarCodeReader.tlb" raw_interfaces_only
using namespace Bytescout_BarCodeReader;

int _tmain(int argc, _TCHAR* argv[])
{
	// Initialize COM.
	HRESULT hr = CoInitialize(NULL);

	// Create the interface pointer.
	IReaderPtr pIReader(__uuidof(Reader));

	// set the registration name and key
	BSTR regname = ::SysAllocString(L"DEMO");
	pIReader->put_RegistrationName(regname);
	SysFreeString(regname);
	BSTR regkey = ::SysAllocString(L"DEMO");
	pIReader->put_RegistrationKey(regkey);
	SysFreeString(regkey);

	// Set barcode type to find
	_BarcodeTypeSelectorPtr pBarcodeTypesToFind;
	pIReader->get_BarcodeTypesToFind(&pBarcodeTypesToFind);
	pBarcodeTypesToFind->put_GS1DataBarExpanded(VARIANT_TRUE);

	// Get full path of sample barcode image file
	WCHAR file[MAX_PATH];
	::GetFullPathName(L"GS1DataBarExpanded.png", MAX_PATH, file, NULL);

	// Load file content to byte array (for demonstration purpose)
	HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	DWORD fileSize = GetFileSize(hFile, NULL);
	byte* pBuffer = new byte[fileSize];
	DWORD numberOfBytesRead;
	ReadFile(hFile, pBuffer, fileSize, &numberOfBytesRead, NULL);
	CloseHandle(hFile);

	// Read barcode from memory
	IStream* stream = SHCreateMemStream(pBuffer, fileSize);
	hr = pIReader->ReadFromStream(stream);

	stream->Release();
	delete[] pBuffer;

	// Get found barcode count
	long count;
	pIReader->get_FoundCount(&count);

	// Get found barcode information
	for (int i = 0; i < count; i++)
	{
		SymbologyType type;
		hr = pIReader->GetFoundBarcodeType(i, &type);
		wprintf(L"Barcode type: %d\n", type);

		float confidence;
		hr = pIReader->GetFoundBarcodeConfidence(i, &confidence);
		wprintf(L"Barcode confidence: %f\n", confidence);

		BSTR bstrValue;
		hr = pIReader->GetFoundBarcodeValue(i, &bstrValue);
		wprintf(L"Barcode value: %s\n", bstrValue);
		::SysFreeString(bstrValue);

		wprintf(L"\n");
	}

	if (count == 0)
	{
		wprintf(L"no barcodes found");
	}

	// Uninitialize COM.
	CoUninitialize();

	wprintf(L"\nHit key to continue\n");
	getchar();

	return 0;
}

```

<!-- code block end -->

<!-- code block begin -->

##### ****ReadFromMemory.sln:**

```

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.40629.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ReadFromMemory", "ReadFromMemory.vcxproj", "{ABBECC62-8779-458A-B8DC-F949363D29AF}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Win32 = Debug|Win32
		Release|Win32 = Release|Win32
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{ABBECC62-8779-458A-B8DC-F949363D29AF}.Debug|Win32.ActiveCfg = Debug|Win32
		{ABBECC62-8779-458A-B8DC-F949363D29AF}.Debug|Win32.Build.0 = Debug|Win32
		{ABBECC62-8779-458A-B8DC-F949363D29AF}.Release|Win32.ActiveCfg = Release|Win32
		{ABBECC62-8779-458A-B8DC-F949363D29AF}.Release|Win32.Build.0 = Release|Win32
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal

```

<!-- code block end -->

<!-- code block begin -->

##### ****stdafx.cpp:**

```
// stdafx.cpp : source file that includes just the standard includes
// ReadFromMemory.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

```

<!-- code block end -->

<!-- code block begin -->

##### ****stdafx.h:**

```
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here

```

<!-- code block end -->

<!-- code block begin -->

##### ****targetver.h:**

```
#pragma once

// Including SDKDDKVer.h defines the highest available Windows platform.

// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.

#include <SDKDDKVer.h>

```

<!-- code block end -->


text:
package com.github.agjacome.httpserver.server.http;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.github.agjacome.httpserver.util.URIs;

import static java.util.Collections.unmodifiableList;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;

public final class HttpQueryParameter implements HttpRequestMatcher, Iterable<String> {

    private final String       key;
    private final List<String> values;

    public static Map<String, HttpQueryParameter> parseQueryParams(
        final String rawQuery
    ) {
        final Map<String, HttpQueryParameter> params = new LinkedHashMap<>();

        URIs.parseParams(rawQuery).forEach(
            (k, vs) -> params.put(k, new HttpQueryParameter(k, vs))
        );

        return params;
    }

    public HttpQueryParameter(final String key, final String ... values) {
        this(key, Arrays.asList(values));
    }

    public HttpQueryParameter(final String key, final List<String> values) {
        this.key    = requireNonNull(key);
        this.values = requireNonNull(values);
    }

    @Override
    public boolean matches(final HttpRequest request) {
        return request.getQueryParameter(key)
              .filter(that -> that.values.containsAll(this.values))
              .isPresent();
    }

    @Override
    public Iterator<String> iterator() {
        return values.iterator();
    }

    public String getKey() {
        return key;
    }

    public Optional<String> getFirst() {
        return values.isEmpty() ? Optional.empty() : Optional.of(values.get(0));
    }

    public List<String> getValues() {
        return unmodifiableList(values);
    }

    @Override
    public boolean equals(final Object that) {
        return this == that
            || nonNull(that)
            && that instanceof HttpQueryParameter
            && key.equals(((HttpQueryParameter) that).key);
    }

    @Override
    public int hashCode() {
        return key.hashCode();
    }

    @Override
    public String toString() {
        final String encodedKey = URIs.encodeUTF8toURL(key);
        return values.stream().map(
            value -> value.isEmpty()
                   ? encodedKey
                   : encodedKey + "=" + URIs.encodeUTF8toURL(value)
        ).collect(joining("&"));
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 20(no. 93): 2 (1891)

#### Original name
Hydnum ayresii Berk. ex Cooke

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <FrameLayout android:id="@id/ptr_content" android:background="?android:colorBackground" android:layout_width="fill_parent" android:layout_height="48.0dip">
        <TextView android:textAppearance="?android:textAppearanceMedium" android:gravity="center" android:id="@id/ptr_text" android:layout_width="fill_parent" android:layout_height="fill_parent" />
    </FrameLayout>
    <com.shanbay.ProgressBar.SmoothProgressBar android:id="@id/ptr_progress" android:layout_width="fill_parent" android:layout_height="wrap_content" android:minHeight="@dimen/ptr_progress_bar_stroke_width" />
</RelativeLayout>


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs for page modifier.escape.php</title>
			<link rel="stylesheet" href="../../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

/libs/plugins/modifier.escape.php

Description

					Description |
															Functions

Smarty plugin

Functions

			Description |
															Functions

		smarty_modifier_escape (line 24)

Smarty escape modifier plugin

Type:     modifier
  Name:     escape
  Purpose:  escape string for output

return: escaped input string

author: Monte Ohrt <at ohrt dot com monte at ohrt dot com>

link: http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual)

		string

			smarty_modifier_escape

					(string $string, [string $esc_type = 'html'], [string $char_set = null], [boolean $double_encode = true])

				string
				$string: input string

				string
				$esc_type: escape type

				string
				$char_set: character set, used for htmlspecialchars() or htmlentities()

				boolean
				$double_encode: encode already encoded entitites again, used for htmlspecialchars() or htmlentities()

		Documentation generated on Sat, 24 Sep 2011 20:23:13 +0200 by phpDocumentor 1.4.1


text:
int litehtml::render_item_flex::_render_content(int x, int y, int max_width, bool second_pass, int ret_width)
{
    return 0;
}

void litehtml::render_item_flex::draw_children(uint_ptr hdc, int x, int y, const position* clip, draw_flag flag, int zindex)
{

}

std::shared_ptr<litehtml::render_item> litehtml::render_item_flex::init()
{
    auto doc = src_el()->get_document();
    decltype(m_children) new_children;
    decltype(m_children) inlines;

    auto convert_inlines = [&]()
        {
        if(!inlines.empty())
        {
            // Find last not space
            auto not_space = std::find_if(inlines.rbegin(), inlines.rend(), [&](const std::shared_ptr<render_item>& el)
                {
                return !el->src_el()->is_space();
                });
            if(not_space != inlines.rend())
            {
                // Erase all spaces at the end
                inlines.erase((not_space.base()), inlines.end());
            }

            auto anon_el = std::make_shared<html_tag>(doc);
            anon_el->add_style("display: block", "");
            anon_el->parent(src_el());
            anon_el->parse_styles();
            auto anon_ri = std::make_shared<render_item_block>(anon_el);
            for(const auto& inl : inlines)
            {
                anon_ri->add_child(inl);
            }
            anon_ri->parent(shared_from_this());

            new_children.push_back(anon_ri->init());
            inlines.clear();
        }
        };

    for (const auto& el : m_children)
    {
        if(el->src_el()->css().get_display() == display_inline_text)
        {
            if(!inlines.empty())
            {
                inlines.push_back(el);
            } else
            {
                if (!el->src_el()->is_white_space())
                {
                    inlines.push_back(el);
                }
            }
        } else
        {
            convert_inlines();
            if(el->src_el()->is_block_box())
            {
                // Add block boxes as is
                el->parent(shared_from_this());
                new_children.push_back(el->init());
            } else
            {
                // Wrap inlines with anonymous block box
                auto anon_el = std::make_shared<html_tag>(doc);
                anon_el->add_style("display: block", "");
                anon_el->parent(el->src_el());
                anon_el->parse_styles();
                auto anon_ri = std::make_shared<render_item_block>(anon_el);
                anon_ri->add_child(el->init());
                anon_ri->parent(shared_from_this());
                new_children.push_back(anon_ri->init());
            }
        }
    }
    convert_inlines();
    children() = new_children;
    for(const auto& el : children())
    {
        m_flex_items.emplace_back(new flex_item(el));
    }

    return shared_from_this();
}


text:
import './index';
import { entry, fakeNow } from './test_data';
import { testOnlySetSettings } from '../settings';
import { ByBlameEntrySk } from './byblameentry-sk';

Date.now = () => fakeNow;
testOnlySetSettings({
  baseRepoURL: 'https://skia.googlesource.com/skia.git',
});

const byBlameEntrySk = new ByBlameEntrySk();
byBlameEntrySk.byBlameEntry = entry;
byBlameEntrySk.corpus = 'gm';
document.body.appendChild(byBlameEntrySk);


text:
module API
  module Entities
    class IssueLink < Grape::Entity
      expose :source, as: :source_issue, using: ::API::Entities::IssueBasic
      expose :target, as: :target_issue, using: ::API::Entities::IssueBasic
      expose :link_type
    end
  end
end


text:
package org.apache.metron.dataloads.extractor;

import org.apache.metron.dataloads.extractor.csv.CSVExtractor;
import org.apache.metron.dataloads.extractor.stix.StixExtractor;

import java.util.Map;

public enum Extractors implements ExtractorCreator {
    CSV(new ExtractorCreator() {

        @Override
        public Extractor create() {
            return new CSVExtractor();
        }
    })
    ,STIX(new ExtractorCreator() {
        @Override
        public Extractor create() {
            return new StixExtractor();
        }
    })
    ;
    ExtractorCreator _creator;
    Extractors(ExtractorCreator creator) {
        this._creator = creator;
    }
    @Override
    public Extractor create() {
        return _creator.create();
    }
    public static Extractor create(String extractorName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        try {
            ExtractorCreator ec = Extractors.valueOf(extractorName);
            return ec.create();
        }
        catch(IllegalArgumentException iae) {
            Extractor ex = (Extractor) Class.forName(extractorName).newInstance();
            return ex;
        }
    }
}


text:
class ChangeNamesOfTablesAndColumns < ActiveRecord::Migration
  def up
    change_column_default :spree_subscriptions, :quantity, 0
    change_column_null :spree_subscriptions, :quantity, false
    change_column_null :spree_subscription_frequencies, :title, false
    change_column :spree_subscriptions, :last_recurrence_at, :datetime
    change_column :spree_subscriptions, :end_date, :datetime
    change_column :spree_subscriptions, :cancelled_at, :datetime
    change_column :spree_order_subscriptions, :failed_at, :datetime
    rename_table :spree_order_subscriptions, :spree_orders_subscriptions
    rename_column :spree_products, :subscribable, :is_subscribable
    rename_column :spree_subscriptions, :last_recurrence_at, :last_occurrence_at
  end

  def down
    change_column_default :spree_subscriptions, :quantity, nil
    change_column_null :spree_subscriptions, :quantity, true
    change_column_null :spree_subscription_frequencies, :string, true
    change_column :spree_subscriptions, :last_occurrence_at, :date
    change_column :spree_subscriptions, :end_date, :date
    change_column :spree_subscriptions, :cancelled_at, :date
    change_column :spree_orders_subscriptions, :failed_at, :date
    rename_table :spree_orders_subscriptions, :spree_order_subscriptions
    rename_column :spree_subscriptions, :last_occurrence_at, :last_recurrence_at
    rename_column :spree_products, :is_subscribable, :subscribable
  end
end


text:
{% include_relative _includes/jquery/jquery.min.js %}
{% include_relative _includes/headroom.js/headroom.min.js %}
{% include_relative _includes/headroom.js/jquery.headroom.min.js %}
{% include_relative _includes/base.js %}


text:
// Copyright (c) 2015 hugula
// direct https://github.com/tenvick/hugula
//
using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Text;
using Hugula.Cryptograph;

namespace Hugula.Utils
{
    /// <summary>
    /// lua helper类
    /// </summary>

    public static class LuaHelper
    {
        private static byte[] key = new byte[] { 0x32, 0x0f, 0x8d, 0xe9, 0x3b, 0x24, 0xa5, 0xd3, 0xf2, 0xd3, 0x64, 0x58, 0xb7, 0xae, 0x3f, 0x28 };
        private static byte[] iv = new byte[] { 0x08, 0xf3, 0xd3, 0x23, 0x8b, 0xc2, 0x90, 0x7d, 0xe9, 0x73, 0x4f, 0x80, 0x84, 0xcc, 0x25, 0x6e };

        /// <summary>
        /// Destroy object
        /// </summary>
        /// <param name="original"></param>
        public static void Destroy(Object original)
        {
            GameObject.Destroy(original);
        }

        public static void Destroy(Object original, float t)
        {
            GameObject.Destroy(original, t);
        }

        public static void DestroyImmediate(Object original)
        {
            GameObject.DestroyImmediate(original);
        }

        public static void DestroyImmediate(Object original, bool allowDestroyingAssets)
        {
            GameObject.DestroyImmediate(original, allowDestroyingAssets);
        }

        public static void DelayDestroy(Object obj)
        {

            GameObject gobj = null;
            if (obj is GameObject)
            {
                gobj = (GameObject)obj;
            }
            else if (obj is Component)
            {
                gobj = ((Component)obj).gameObject;
            }
            if (gobj == null) return;

            var delay = gobj.GetComponent<Hugula.Framework.IDelayDestory>();
            if (delay != null)
            {
                delay.onDelayCompleted = () =>
                {
                    ResLoader.ReleaseInstance(gobj);
                };
                delay.DelayDestory();
            }
            else
            {
                ResLoader.ReleaseInstance(gobj);
            }
        }

        public static void DontDestroyOnLoad(Object target)
        {
            Object.DontDestroyOnLoad(target);
        }

        // public static void Active(Component comp)
        // {
        //     Active(comp.gameObject);
        // }

        public static void Active(Object obj,int activeIndex=0)
        {
            GameObject gobj = null;
            if (obj is GameObject)
            {
                gobj = (GameObject)obj;
            }
            else if (obj is Component)
            {
                gobj = ((Component)obj).gameObject;
            }

            if (gobj == null) return;

            var delay = gobj.GetComponents<Hugula.Framework.IDelayCancel>();
            if (delay != null && delay.Length > 0)
            {
                foreach (var dela in delay)
                    dela.CancelDelay();
            }

            gobj.SetActive(true);
        }

        public static void DelayDeActive(Object obj)
        {
            GameObject gobj = null;
            if (obj is GameObject)
            {
                gobj = (GameObject)obj;
            }
            else if (obj is Component)
            {
                gobj = ((Component)obj).gameObject;
            }

            if (gobj == null) return;

            var delay = gobj.GetComponents<Hugula.Framework.IDelayDeactive>();
            if (delay != null && delay.Length > 0)
            {
                foreach (var dela in delay)
                    dela.DelayDeactive();
            }
            else
                gobj.SetActive(false);

        }

        /// <summary>
        /// Instantiate Object
        /// </summary>
        /// <param name="original"></param>
        /// <returns></returns>
        public static GameObject Instantiate(GameObject original)
        {
            GameObject clone = GameObject.Instantiate(original);
#if UNITY_EDITOR
            LuaHelper.RefreshShader(clone as GameObject);
#endif
            return clone;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="original"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static GameObject InstantiateLocal(GameObject original, GameObject parent)
        {
            return InstantiateLocal(original, parent, Vector3.zero);
        }

        public static GameObject InstantiateLocal(GameObject original)
        {
            return InstantiateLocal(original, null, Vector3.zero);
        }

        public static GameObject InstantiateLocal(GameObject original, Vector3 pos)
        {
            return InstantiateLocal(original, null, pos);
        }

        public static GameObject InstantiateLocal(GameObject original, GameObject parent, Vector3 pos)
        {
            var tranformTa = original.transform;
            if (pos == Vector3.zero) pos = tranformTa.localPosition;
            Quaternion rota = tranformTa.localRotation;
            Vector3 scale = tranformTa.localScale;
            GameObject clone = (GameObject)GameObject.Instantiate(original);
#if UNITY_EDITOR
            if (clone is GameObject)
            {
                LuaHelper.RefreshShader(clone as GameObject);
            }
#endif
            var transform = clone.transform;
            if (parent != null) clone.transform.SetParent(parent.transform);
            transform.localPosition = pos;
            transform.localScale = scale;
            transform.localRotation = rota;
            return clone;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="original"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static GameObject InstantiateGlobal(GameObject original, GameObject parent = null)
        {
            var tranformTa = original.transform;
            var pos = tranformTa.position;
            Quaternion rota = tranformTa.rotation;
            Vector3 scale = tranformTa.localScale;
            GameObject clone = (GameObject)GameObject.Instantiate(original);
#if UNITY_EDITOR
            if (clone is GameObject)
            {
                LuaHelper.RefreshShader(clone as GameObject);
            }
#endif
            var transform = clone.transform;
            if (parent != null) clone.transform.SetParent(parent.transform);
            transform.position = pos;
            transform.localScale = scale;
            transform.rotation = rota;
            return clone;
        }

        /// <summary>
        /// 创建一个新的GameObject
        /// </summary>
        public static GameObject CreateNewGameObject(string rName)
        {
            return new GameObject(rName);
        }

        /// <summary>
        /// 设置父对象
        /// </summary>
        /// <param name="child"></param>
        /// <param name="parent"></param>
        public static void SetParent(GameObject child, GameObject parent)
        {
            var tranformTa = child.transform;
            var pos = tranformTa.localPosition;
            var rota = tranformTa.localRotation;
            var scale = tranformTa.localScale;

            child.transform.SetParent(parent.transform);
            tranformTa.localPosition = pos;
            tranformTa.localScale = scale;
            tranformTa.localRotation = rota;
        }

        /// <summary>
        /// Sets the layer.
        /// </summary>
        /// <param name="obj">Object.</param>
        /// <param name="layer">Layer.</param>
        public static void SetLayer(Transform transform, int layer)
        {
            transform.gameObject.layer = layer;
            int c = transform.childCount;
            for (int i = 0; i < c; i++)
            {
                var child = transform.GetChild(i);
                SetLayer(child, layer);
            }
        }

        /// <summary>
        ///  the Layersmask
        /// </summary>
        /// <returns>The mask get mask.</returns>
        /// <param name="args">Arguments.</param>
        public static int GetLayerMask(string args)
        {
            string[] a = args.Split(',');
            return LayerMask.GetMask(a);
        }

        /// <summary>
        /// getType
        /// </summary>
        /// <param name="classname"></param>
        /// <returns></returns>
        public static System.Type GetClassType(string classname)
        {
            if (string.IsNullOrEmpty(classname)) return null;

            System.Type t = null;
            Assembly[] assbs = System.AppDomain.CurrentDomain.GetAssemblies();
            Assembly assb = null;
            for (int i = 0; i < assbs.Length; i++)
            {
                assb = assbs[i];
                t = assb.GetType(classname);
                if (t != null) return t;
            }

            return null;
        }

        /// <summary>
        /// 寻找GAMEOBJECT
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static GameObject Find(string name)
        {
            return GameObject.Find(name);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public static GameObject FindWithTag(string tag)
        {
            return GameObject.FindWithTag(tag);
        }

        /// <summary>
        /// GetComponentInChildren
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="classname"></param>
        /// <returns></returns>
        public static Component GetComponentInChildren(GameObject obj, string classname)
        {
            System.Type t = GetClassType(classname);
            return GetComponentInChildren(obj, t);
        }

        public static Component GetComponentInChildren(GameObject obj, System.Type t)
        {
            Component comp = null;
            if (t != null && obj != null) comp = obj.GetComponentInChildren(t);
            return comp;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="classname"></param>
        /// <returns></returns>
        public static Component GetComponent(GameObject obj, string classname)
        {
            System.Type t = GetClassType(classname);
            return GetComponent(obj, t);
        }

        public static Component GetComponent(GameObject obj, System.Type t)
        {
            Component comp = null;
            if (obj != null && t != null) comp = obj.GetComponent(t);
            return comp;
        }

        public static Component AddComponent(GameObject obj, string className)
        {
            System.Type t = GetClassType(className);
            return AddComponent(obj, t);
        }

        public static Component AddComponent(GameObject obj, System.Type t)
        {
            Component comp = null;
            comp = GetComponent(obj, t);
            if (comp == null) comp = obj.AddComponent(t);

            return comp;
        }

        public static void RemoveComponent(GameObject obj, string className)
        {
            Component comp = GetComponent(obj, className);
            if (comp != null) RemoveComponent(comp);
        }

        public static void RemoveComponent(Component comp)
        {
            Destroy(comp);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="classname"></param>
        /// <returns></returns>
        public static Component[] GetComponents(GameObject obj, string classname)
        {
            System.Type t = GetClassType(classname);
            return GetComponents(obj, t);
        }

        public static Component[] GetComponents(GameObject obj, System.Type t)
        {
            Component[] comp = null;
            if (obj != null && t != null) comp = obj.GetComponents(t);
            return comp;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="classname"></param>
        /// <returns></returns>
        public static Component[] GetComponentsInChildren(GameObject obj, string classname)
        {
            System.Type t = GetClassType(classname);
            return GetComponentsInChildren(obj, t);
        }

        public static Component[] GetComponentsInChildren(GameObject obj, System.Type t)
        {
            if (t != null && obj != null) return obj.transform.GetComponentsInChildren(t);
            return null;
        }

        public static void SetBehaviourEnabled(Behaviour behaviour, bool enabled)
        {
            if (behaviour == null) return;
            behaviour.enabled = enabled;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Transform[] GetAllChild(GameObject obj)
        {
            Transform[] child = null;
            int count = obj.transform.childCount;
            child = new Transform[count];
            for (int i = 0; i < count; i++)
            {
                child[i] = obj.transform.GetChild(i);
            }
            return child;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="eachFn"></param>
        public static void ForeachChild(GameObject parent, System.Action<int, GameObject> eachFn)
        {
            Transform pr = parent.transform;
            int count = pr.childCount;
            Transform child = null;
            for (int i = 0; i < count; i++)
            {
                child = pr.GetChild(i);
                eachFn.Invoke(i, child.gameObject);
            }
        }

        /// <summary>
        /// Raycast the specified ray.
        /// </summary>
        /// <param name="ray">Ray.</param>
        public static object Raycast(Ray ray)
        {
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                return hit;
            }
            return null;
        }

        //        /// <summary>
        //        /// 得到类型
        //        /// </summary>
        //        /// <param name="obj"></param>
        //        /// <returns></returns>
        //        public static System.Type GetType(object obj)
        //        {
        //            return obj.GetType();
        //        }

        /// <summary>
        /// 刷新shader
        /// </summary>
        /// <param name="assetBundle"></param>
        public static void RefreshShader(AssetBundle assetBundle)
        {
            UnityEngine.Material[] materials = assetBundle.LoadAllAssets<Material>();
            //foreach (UnityEngine.Object m in materials)
            for (int i = 0; i < materials.Length; i++)
            {
                Material mat = materials[i];
                string shaderName = mat.shader.name;
                Shader newShader = Shader.Find(shaderName);
                if (newShader != null)
                {
                    mat.shader = newShader;  //    Debug.Log("refresh shader: " + shaderName + " in material " + mat.name);
                }
                else
                {
                    Debug.LogWarning("unable to refresh shader: " + shaderName + " in material " + mat.name);
                }
            }
        }

        public static void RefreshShader(GameObject obj)
        {
            List<Renderer> meshrs = new List<Renderer>(obj.GetComponentsInChildren<Renderer>(false));
            List<Material> mats = new List<Material>();

            for (int i = 0; i < meshrs.Count; i++)
            {
                Material[] mat = meshrs[i].sharedMaterials;
                if (mat == null) mat = meshrs[i].materials;
                if (mat != null)
                {
                    mats.AddRange(mat);
                }
            }

            for (int i = 0; i < mats.Count; i++)
            {
                Material mat = mats[i];
                if (mat != null)
                {
                    string shaderName = mat.shader.name;
                    Shader newShader = Shader.Find(shaderName);
                    if (newShader != null)
                    {
                        mat.shader = newShader;
                    }
                }
            }

        }

        /// <summary>
        /// 得到两个点之间的夹角
        /// </summary>
        /// <param name="p1x"></param>
        /// <param name="p1y"></param>
        /// <param name="p2x"></param>
        /// <param name="p2y"></param>
        /// <returns></returns>
        public static float GetAngle(float p1x, float p1y, float p2x, float p2y)
        {
            var tmpx = p2x - p1x;
            var tmpy = p2y - p1y;
            var angle = Mathf.Atan2(tmpy, tmpx) * (180.0f / Mathf.PI);
            return angle;
        }

        /// <summary>
        /// 获取utf8字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string GetUTF8String(System.Array bytes)
        {
            return System.Text.Encoding.UTF8.GetString((byte[])bytes);
        }

        /// <summary>
        /// 获取bytes
        /// </summary>
        /// <param name="utf8Str"></param>
        /// <returns></returns>
        public static byte[] GetBytes(string utf8Str)
        {
            return System.Text.Encoding.UTF8.GetBytes(utf8Str);
        }

        /// <summary>
        /// Creates from byte array.
        /// </summary>
        /// <returns>The from byte array.</returns>
        /// <param name="bytes">Bytes.</param>
        public static AssetBundle LoadFromMemory(System.Array bytes)
        {
            byte[] bts = (byte[])bytes;
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
			AssetBundle ab = AssetBundle.CreateFromMemoryImmediate(bts);
#else
            AssetBundle ab = AssetBundle.LoadFromMemory(bts);
#endif
            return ab;
        }

        /// <summary>
        /// 调用GC.Collect
        /// </summary>
        public static void GCCollect()
        {
            System.GC.Collect();
        }

        /// <summary>
        /// str 转换为hash code
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int StringToHash(string str)
        {
            int hash = Animator.StringToHash(str);
            return hash;
        }

        /// <summary>
        /// 播放动画片段
        /// </summary>
        /// <param name="anim"></param>
        /// <param name="name"></param>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static AnimationState PlayAnimation(Animation anim, string name, AnimationDirection dir)
        {
            if (string.IsNullOrEmpty(name)) name = anim.clip.name;
            var state = anim[name];
            if (state)
            {
                float speed = state.speed;
                if (dir == AnimationDirection.Toggle)
                {
                    if (speed > 0 && state.time == 0)
                        dir = AnimationDirection.Reverse;
                    else
                        dir = AnimationDirection.Forward;
                }

                if (dir == AnimationDirection.Reverse && state.time == 0f)
                {
                    state.time = state.length;
                }
                else if (dir == AnimationDirection.Forward && state.time == state.length)
                {
                    state.time = 0f;
                }

                state.speed = Mathf.Abs(speed) * (int)dir;

                anim.Play(name);
                anim.Sample();
            }
            return state;
        }

        public static Vector2 GetCanvasPos(Transform tr, Vector3 screenPos)
        {
            Vector2 pos = Vector2.zero;
            Canvas canvas = tr.root.GetComponentInChildren<Canvas>();
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, screenPos, canvas.worldCamera, out pos))
            {

            }

            return pos;
        }

        /// <summary>
        /// 播放动画片段
        /// </summary>
        /// <param name="anim"></param>
        /// <param name="name"></param>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static AnimatorStateInfo PlayAnimator(Animator anim, string name, AnimationDirection dir)
        {

            var state = anim.GetCurrentAnimatorStateInfo(0);
            float speed = anim.GetFloat("speed");
            float normalizedTime = 1;
            if (dir == AnimationDirection.Toggle)
            {
                if (speed > 0)
                    dir = AnimationDirection.Reverse;
                else
                    dir = AnimationDirection.Forward;
            }

            if (dir == AnimationDirection.Reverse)
            {
                anim.SetFloat("speed", -1 * Mathf.Abs(speed));
                normalizedTime = 1;
            }
            else if (dir == AnimationDirection.Forward)
            {
                anim.SetFloat("speed", Mathf.Abs(speed));
                normalizedTime = 0;
            }

            if (!string.IsNullOrEmpty(name))
                anim.Play(name, 0, normalizedTime);
            else
                anim.Play(state.fullPathHash, 0, normalizedTime);

            return state;
        }

        /// <summary>
        /// 卸载场景
        /// </summary>
        /// <param name="scenename"></param>
        public static void UnloadScene(string sceneName)
        {
            Hugula.ResLoader.UnloadSceneAsync(sceneName, null, null);
            // Hugula.Loader.ResourcesLoader.UnloadScene(sceneName);

            //UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync(sceneName);
        }

        // /// <summary>
        // /// Loads the scene.
        // /// </summary>
        // /// <param name="sceneName">Scene name.</param>
        // /// <param name="isAdditive">If set to <c>true</c> is additive.</param>
        // public static void LoadScene(string sceneName, bool isAdditive)
        // {
        //     Hugula.Loader.ResourcesLoader.LoadScene(sceneName.ToLower() + Common.CHECK_ASSETBUNDLE_SUFFIX, sceneName, null, null, null, true, isAdditive ? UnityEngine.SceneManagement.LoadSceneMode.Additive : UnityEngine.SceneManagement.LoadSceneMode.Single);
        //     //UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName, isAdditive ? UnityEngine.SceneManagement.LoadSceneMode.Additive : UnityEngine.SceneManagement.LoadSceneMode.Single);
        // }

        /// <summary>
        /// check Object is Null
        /// </summary>
        /// <param name="scenename"></param>
        public static bool IsNull(Object obj)
        {
            return obj == null || !obj;
        }

        /// <summary>
        /// 本地存储
        /// </summary>
        public static bool SaveLocalData(string fileName, string saveData)
        {
            string fullPath = CUtils.PathCombine(CUtils.GetRealPersistentDataPath(), fileName);
            FileInfo fileInfo = new FileInfo(fullPath);
            if (!fileInfo.Directory.Exists) fileInfo.Directory.Create();
            // if (!fileInfo.Exists) fileInfo.Create();
            using (var sw = fileInfo.OpenWrite())
            {
#if UNITY_EDITOR
                Debug.LogFormat("SaveLocalData(file={0}) content={1} ", fileName, saveData);
#endif
                var outBytes = Encoding.UTF8.GetBytes(saveData);
                byte[] bytes = CryptographHelper.Encrypt(outBytes,key,iv);
                sw.Write(bytes, 0, bytes.Length);
                sw.Flush();
            }

            return true;
        }

        public static string LoadLocalData(string fileName)
        {
            string fullPath = CUtils.PathCombine(CUtils.GetRealPersistentDataPath(), fileName);
            FileInfo fileInfo = new FileInfo(fullPath);
            string loadData = string.Empty;

            if (fileInfo.Exists)
            {
                using (FileStream fs = fileInfo.OpenRead())
                {

                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    try
                    {
                        var reBytes = CryptographHelper.Decrypt(bytes,key,iv);
                        if (reBytes == null)
                        {
                            //delete file
                            fileInfo.Delete();
#if UNITY_EDITOR
                            Debug.LogFormat("delete file (file={0})", fileName);
#endif
                        }
                        else
                            loadData = Encoding.UTF8.GetString(reBytes);
                    }
                    catch (System.Exception ex)
                    {

                        fileInfo.Delete();
                        Debug.LogError(ex);
                    }

#if UNITY_EDITOR
                    Debug.LogFormat("LoadLocalData(file={0}) content={1} ", fileName, loadData);
#endif
                    return loadData;
                }
            }
            return loadData;
        }
    }
    // [LuaCallCSharp]
    public static class UnityEngineObjectExtention
    {
        public static bool IsNull(this UnityEngine.Object o)
        {
            return o == null;
        }
    }
}
//namespace AnimationOrTween
//{

public enum AnimationDirection
{
    Reverse = -1,
    Toggle = 0,
    Forward = 1,
}
//}

/// <summary>
/// 用来加载场景的type类型
/// </summary>

public class AssetBundleScene
{

}


text:
@(field: Field, label: String = "", help: String = "", icon: String = "")

<div class="form-group has-feedback @if(field.hasErrors) {has-error}">
    @label:
    <textarea class="form-control autosize" rows="3" id="@field.id" name="@field.name">@field.value.getOrElse("")</textarea>
</div>


text:
from django.conf.urls import patterns, url, include
from django.contrib.auth.decorators import login_required
from outside_listing import views
from django.contrib import admin

urlpatterns = patterns('',
                       url(r'^$', views.index, name="index"),
                       url(r'^map/$', views.map, name="map"),
                       url(r'^lead/(?P<id>[0-9]+)/$', views.lead_detail, name="lead-detail"),
                       url(r'^lead/(?P<id>[0-9]+)/closed/$', login_required(views.LeadClosedView.as_view()), name="lead-closed"),
                       url(r'^lead/(?P<id>[0-9]+)/repeat/$', login_required(views.LeadRepeatView.as_view()), name="lead-repeat"),
                       url(r'^lead/(?P<id>[0-9]+)/feedback/$', login_required(views.LeadFeedbackView.as_view()), name="lead-feedback"),
                       url(r'^admin/', include(admin.site.urls)),

                       )


text:
//-----------------------------------------------------------------------
// <copyright file="Log4NetInMemoryStreamAppenderManagerTest.cs" company="Copacetic Software">
// Copyright (c) Copacetic Software.
// <author>Philip Pittle</author>
// <date>Wednesday, January 29, 2014 10:57:24 PM</date>
// Licensed under the Apache License, Version 2.0,
// you may not use this file except in compliance with this 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.
// </copyright>
//-----------------------------------------------------------------------

using System.Linq;
using System.Reflection;
using CopaceticSoftware.pMixins.Attributes;
using CopaceticSoftware.pMixins.CodeGenerator.Infrastructure;
using CopaceticSoftware.pMixins.Tests.Common;
using NBehave.Spec.NUnit;
using NUnit.Framework;

namespace CopaceticSoftware.pMixins.CodeGenerator.Tests.UnitTests.Infrastructure
{
    [TestFixture]
    public class Log4NetInMemoryStreamAppenderManagerTest : TestBase
    {
        private const string _logMessage = "Test Log Message";

        private readonly log4net.ILog _log =
            log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private Log4NetInMemoryStreamAppenderManager _log4NetInMemoryStreamAppenderManager;

        protected override void Establish_context()
        {
            //Note: _log4NetInMemoryStreamAppenderManager
            //must be initialized here, otherwise the TestBase
            //constructor will reinitialize the log4net environment
            _log4NetInMemoryStreamAppenderManager =
                new Log4NetInMemoryStreamAppenderManager();

            _log.Info(_logMessage);
        }

        protected override void Cleanup()
        {
            _log4NetInMemoryStreamAppenderManager.Dispose();
        }

        [Test]
        public void Can_Read_Logs()
        {
            _log4NetInMemoryStreamAppenderManager.GetLoggingEvents(LoggingVerbosity.All).Count()
                .ShouldEqual(1);

            _log4NetInMemoryStreamAppenderManager.GetLoggingEvents(LoggingVerbosity.All).First().RenderedMessage
                .ShouldContain(_logMessage);
        }

        [Test]
        public void Rendered_Log_Message_Should_Start_With_Comment()
        {
            _log4NetInMemoryStreamAppenderManager.GetRenderedLoggingEvents(LoggingVerbosity.All).First()
                .ShouldStartWith("//");
        }

        [Test]
        public void LoggingVerbosity_Flag_Should_Be_Respected()
        {
            _log4NetInMemoryStreamAppenderManager.GetLoggingEvents(LoggingVerbosity.Warning).Count()
                .ShouldEqual(0);
        }
    }
}


text:
package org.apache.camel.component.cm.exceptions;

/**
 * CM Camel component s configuration is based on URI. This exception is raised
 * when the uri provided for configuration is wrong
 *
 */
public class InvalidUriEndpointException extends CMValidationException {

    public InvalidUriEndpointException() {
        super();
    }

    public InvalidUriEndpointException(final String message) {
        super(message);
    }
}


text:
<?php

namespace Swarming\SubscribePro\Test\Unit\Model\CatalogRule\Inspector;

use Swarming\SubscribePro\Model\CatalogRule\Inspector\ConfigurableProduct;
use Magento\Catalog\Model\Product\Configuration\Item\Option as ProductConfigurationOption;

class ConfigurableProductTest extends AbstractInspector
{
    /**
     * @var \Swarming\SubscribePro\Model\CatalogRule\Inspector\ConfigurableProduct
     */
    protected $configurableProduct;

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

        $this->configurableProduct = new ConfigurableProduct(
            $this->customerSession,
            $this->storeManager,
            $this->localeDate,
            $this->rulePricesStorage
        );
    }

    public function testIsAppliedIfChildHasSpecialPrice() {
        $price = 100;
        $basePrice = 110;

        $childProduct = $this->prepareProductMockWithSpecialPrice($price, $basePrice);

        $option = $this->getMockBuilder(ProductConfigurationOption::class)
            ->disableOriginalConstructor()
            ->setMethods(['getProduct'])
            ->getMock();
        $option->expects($this->atLeastOnce())
            ->method('getProduct')
            ->willReturn($childProduct);

        $product = $this->createProductMock();
        $product->expects($this->atLeastOnce())
            ->method('getCustomOption')
            ->with('simple_product')
            ->willReturn($option);

        $this->rulePricesStorage->expects($this->never())->method('getRulePrice');

        $this->assertTrue($this->configurableProduct->isApplied($product));
    }

    public function testIsAppliedIfHasSpecialPrice() {
        $price = 100;
        $basePrice = 110;

        $product = $this->prepareProductMockWithSpecialPrice($price, $basePrice);

        $this->rulePricesStorage->expects($this->never())->method('getRulePrice');

        $this->assertTrue($this->configurableProduct->isApplied($product));
    }

    /**
     * @param bool $isApplied
     * @param int $rulePrice
     * @param float $price
     * @param string $productId
     * @param bool $customerGroupId
     * @param string $sessionCustomerGroupId
     * @param string $storeId
     * @param string $websiteId
     * @param string $dateString
     * @dataProvider isAppliedDataProvider
     */
    public function testIsApplied(
        $isApplied,
        $rulePrice,
        $price,
        $productId,
        $customerGroupId,
        $sessionCustomerGroupId,
        $storeId,
        $websiteId,
        $dateString
    ) {
        $this->prepareDateMock($dateString, $storeId);

        $this->prepareStoreMock($storeId, $websiteId);

        $product = $this->prepareChildProductMock($price, $productId, $customerGroupId, $storeId);

        if (!$customerGroupId) {
            $this->prepareCustomerSession($sessionCustomerGroupId);
        }

        $customerGroupId = $customerGroupId ?: $sessionCustomerGroupId;
        $this->prepareRulePriceStorage($rulePrice, $dateString, $websiteId, $customerGroupId, $productId);

        $this->assertEquals($isApplied, $this->configurableProduct->isApplied($product));
    }

    /**
     * @param float $price
     * @param int $productId
     * @param int $customerGroupId
     * @param int $storeId
     * @return \Magento\Catalog\Model\Product|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function prepareChildProductMock($price, $productId, $customerGroupId, $storeId)
    {
        $childProduct = $this->prepareProductMock($price, $productId, $customerGroupId, $storeId);

        $option = $this->getMockBuilder(ProductConfigurationOption::class)
            ->disableOriginalConstructor()
            ->setMethods(['getProduct'])
            ->getMock();
        $option->expects($this->atLeastOnce())
            ->method('getProduct')
            ->willReturn($childProduct);

        $product = $this->createProductMock();
        $product->expects($this->atLeastOnce())
            ->method('getCustomOption')
            ->with('simple_product')
            ->willReturn($option);

        return $product;
    }

    /**
     * @param bool $isApplied
     * @param int $rulePrice
     * @param float $price
     * @param string $productId
     * @param bool $customerGroupId
     * @param string $sessionCustomerGroupId
     * @param string $storeId
     * @param string $websiteId
     * @param string $dateString
     * @dataProvider isAppliedDataProvider
     */
    public function testIsAppliedIfNoChildProduct(
        $isApplied,
        $rulePrice,
        $price,
        $productId,
        $customerGroupId,
        $sessionCustomerGroupId,
        $storeId,
        $websiteId,
        $dateString
    ) {
        $this->prepareDateMock($dateString, $storeId);

        $this->prepareStoreMock($storeId, $websiteId);

        $product = $this->prepareProductMock($price, $productId, $customerGroupId, $storeId);
        $product->expects($this->atLeastOnce())
            ->method('getCustomOption')
            ->with('simple_product')
            ->willReturn(false);

        if (!$customerGroupId) {
            $this->prepareCustomerSession($sessionCustomerGroupId);
        }

        $customerGroupId = $customerGroupId ?: $sessionCustomerGroupId;
        $this->prepareRulePriceStorage($rulePrice, $dateString, $websiteId, $customerGroupId, $productId);

        $this->assertEquals($isApplied, $this->configurableProduct->isApplied($product));
    }

    /**
     * @return array
     */
    public function isAppliedDataProvider()
    {
        return [
            'applied' => [
                'isApplied' => true,
                'rulePrice' => '3.1',
                'price' => '50',
                'productId' => 76,
                'customerGroupId' => 1,
                'sessionCustomerGroupId' => 1,
                'storeId' => 1,
                'websiteId' => 2,
                'dateString' => 'date_format'
            ],
            'not applied' => [
                'isApplied' => false,
                'rulePrice' => false,
                'price' => '60',
                'productId' => 43,
                'customerGroupId' => 3,
                'sessionCustomerGroupId' => 5,
                'storeId' => 3,
                'websiteId' => 1,
                'dateString' => 'date_format_3'
            ],
            'not applied with 0. rule price' => [
                'isApplied' => false,
                'rulePrice' => '0.0',
                'price' => '70',
                'productId' => 7,
                'customerGroupId' => 2,
                'sessionCustomerGroupId' => 2,
                'storeId' => 3,
                'websiteId' => 1,
                'dateString' => 'date_format_4'
            ],
        ];
    }
}


text:
{% extends 'base.html' %}

{% block body %}
    {% include 'navbar.html' %}

Random Forest

        {% highlight 'python' %}
    # Get intrusions data
    intrusions = get_data_sql()

    # Clean up data frame
    intrusions.set_index('key_column', inplace=True)
    del intrusions['Unnamed: 0']
    intrusions['attack_cat'] = intrusions['attack'].astype('category')
    del intrusions['attack']
    dummy = pd.get_dummies(intrusions, prefix=['Protocol', 'Service', 'Flag'],
        prefix_sep='_', columns=['protocol_type', 'service', 'flag'])

    # Train model
    X = dummy.ix[:,(dummy.columns != 'attack_cat')]
    y = dummy['attack_cat']
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=10)

    rf = RandomForestClassifier()
    rf.fit(X_train, y_train)
    y_pred = rf.predict(X_test)
        {% endhighlight %}

Gradient Boosting

            {% highlight 'python' %}
    # Get intrusions data
    intrusions = get_data_sql()

    # Clean up data frame
    intrusions.set_index('key_column', inplace=True)
    del intrusions['Unnamed: 0']

    label_encoder = LabelEncoder()
    label_encoder = label_encoder.fit(intrusions['attack'])
    label_encoded_y = label_encoder.transform(intrusions['attack'])
    label_key = label_encoder.inverse_transform([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22])
    dummy = pd.get_dummies(intrusions, prefix=['Protocol', 'Service', 'Flag'], prefix_sep='_', columns=['protocol_type', 'service', 'flag'])

    # Train model
    X = dummy.ix[:,(dummy.columns != 'attack')]
    y = dummy['attack']
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=10)

    xg = xgb.XGBClassifier(learning_rate=0.3, objective='multi:softmax', silent=True)
    eval_set = [(X_train, y_train), (X_test, y_test)]
    xg.fit(X_train, y_train, eval_metric=["merror", "mlogloss"], eval_set=eval_set, verbose=True, early_stopping_rounds=5)
    y_pred = xg.predict(X_test)
            {% endhighlight %}

{% endblock body %}

{% block js %}

{% endblock js %}


text:
package org.glowroot.microbenchmarks.support;

import org.glowroot.agent.plugin.api.Agent;
import org.glowroot.agent.plugin.api.ThreadContext;
import org.glowroot.agent.plugin.api.Timer;
import org.glowroot.agent.plugin.api.TimerName;
import org.glowroot.agent.plugin.api.weaving.BindTraveler;
import org.glowroot.agent.plugin.api.weaving.OnAfter;
import org.glowroot.agent.plugin.api.weaving.OnBefore;
import org.glowroot.agent.plugin.api.weaving.Pointcut;

public class TimerWorthyAspect {

    @Pointcut(className = "org.glowroot.microbenchmarks.core.support.TimerWorthy",
            methodName = "doSomethingTimerWorthy", methodParameterTypes = {},
            timerName = "timer worthy")
    public static class TimerWorthyAdvice {

        private static final TimerName timerName = Agent.getTimerName(TimerWorthyAdvice.class);

        @OnBefore
        public static Timer onBefore(ThreadContext context) {
            return context.startTimer(timerName);
        }

        @OnAfter
        public static void onAfter(@BindTraveler Timer timer) {
            timer.stop();
        }
    }

    @Pointcut(className = "org.glowroot.microbenchmarks.core.support.TimerWorthy",
            methodName = "doSomethingTimerWorthyB", methodParameterTypes = {},
            timerName = "timer worthy B")
    public static class TimerWorthyAdviceB {

        private static final TimerName timerName = Agent.getTimerName(TimerWorthyAdviceB.class);

        @OnBefore
        public static Timer onBefore(ThreadContext context) {
            return context.startTimer(timerName);
        }

        @OnAfter
        public static void onAfter(@BindTraveler Timer timer) {
            timer.stop();
        }
    }
}


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name='HandheldFriendly' content='True'>
<meta name='MobileOptimized' content='480'>
<meta name='format-detection' content='telephone=no'>
<meta name='viewport' content='initial-scale=1.0,width=device-width, minimum-scale=1.0, maximum-scale=1.0'>
<meta http-equiv='cleartype' content='on'>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) 版权 2005"/>
<meta name="DC.rights.owner" content="(C) 版权 2005"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<meta name="DC.Type" content="task"/>
<meta name="DC.Title" content="Huawei handwriting mode"/>
<meta name="DC.subject" content="Huawei handwriting mode"/>
<meta name="keywords" content="Huawei handwriting mode"/>
<meta name="DC.Relation" scheme="URI" content="../../product_content/basics/topic_enter_text.html"/>
<meta name="DC.Relation" scheme="URI" content="../../index.html"/>
<meta name="DC.Relation" scheme="URI" content="../../product_content/basics/topic_enter_text.html"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="task_change_hand_input"/>
<meta name="DC.Language" content="zh-cn"/>
<link rel="stylesheet" type="text/css" href="../../css/commonltr.css"/>
<link rel="stylesheet" type="text/css" href="../../css/my.css"/>
<title>Huawei handwriting mode</title>

    <link rel="stylesheet" type="text/css" href="css/my.css"/>

            Huawei handwriting mode

Touch  on the top of the onscreen keyboard to switch to Huawei handwriting mode.


text:
var input = function foo () {};

export default input;
export { input as __moduleExports };


text:
#include <string>
#include <vector>
#include <iostream>
#include <QGraphicsItem>

#ifndef POS
#define POS "pos"
#endif //pos
#ifndef NEG
#define NEG "neg"
#endif //neg

class Node
{
    protected:
        std::vector<Node*> posConnections;
        std::vector<Node*> negConnections;
        std::string cluster;
        int tolerance;
        int x;
        int y;
    private:
        QGraphicsRectItem* visRep;

    public:
        std::vector<Node*> getPosConnections(){return posConnections;}
        void setCluster(std::string c){cluster = c;}
        std::string getCluster(){return cluster;}
        QGraphicsRectItem* getVisual(){return visRep;}
        void setTolerance(int i){tolerance = i;}
        int getTolerance(){return tolerance;}
        int getX(){return x;}
        void setX(int ex){x=ex;}
        int getY(){return y;}
        void setY(int why){y=why;}
        void setVisual(QGraphicsRectItem* qgri){visRep = qgri;}
        Node(){tolerance=0; x=0; y=0;}
        ~Node(){delete visRep;}
        void addConnection(Node* n, std::string type)
        {
            if(type == POS)
            {
                posConnections.push_back(n);
                return;
            }
            else if(type == NEG)
            {
                negConnections.push_back(n);
            }
            else
            {
                std::cerr<< "CONNECTION NEVER ADDED!  DID NOT SPECIFY TYPE (pos/neg)!";
            }
        }
};

#endif // NODE_H


text:
<?php

namespace Tim\CatalogBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;

class ProductAdmin extends Admin
{
	protected $context = 'default';

	protected $datagridValues = array(
		'_sort_order' => 'DESC',
		'_sort_by' => 'created'
	);

	protected function configureFormFields(FormMapper $formMapper)
	{
		$formMapper
			->add('title')
			->add('category')
			->add('imageFile', 'file', [
				'required' => false,
				'label' => 'Main Image',
				'data_class' => 'Symfony\Component\HttpFoundation\File\File'])
			->add('description')
			->add('cost')
			->add('productMedia', 'sonata_type_collection', [
				'cascade_validation' => true,
				'label' => 'Additional Images'
			], array(
				'edit' => 'inline',
				'inline' => 'table',
				'sortable' => 'position',
				'link_parameters' => array(
					'context' => $this->context,
				),
			))
			->add('attributes', 'sonata_type_collection', [
				'cascade_validation' => true,
				'label' => 'Attributes'
			], array(
				'edit' => 'inline',
				'inline' => 'table',
				'sortable' => 'position'
			));

	}

	protected function configureDatagridFilters(DatagridMapper $datagridMapper)
	{
		$datagridMapper
			->add('category')
			->add('title')
			->add('description')
			->add('cost')
			->add('created');
	}

	protected function configureListFields(ListMapper $listMapper)
	{
		$listMapper
			->addIdentifier('title')
			->add('slug')
			->add('description')
			->add('cost')
			->add('created')
			->add('category')
			->add('_action', 'actions', array(
				'actions' => array(
					'show' => array(),
					'edit' => array(),
					'delete' => array(),
				)
			));
	}

	protected function configureShowField(ShowMapper $showMapper)
	{
		$showMapper
			->add('category')
			->add('title')
			->add('slug')
			->add('description')
			->add('created')
			->add('updated')
			->add('imageFile', 'string', array('template' => 'TimCatalogBundle:ProductAdmin:list_image.html.twig'));

	}

	public function prePersist($product)
	{
		$product->setProductMedia($product->getProductMedia());
		$product->setAttributes($product->getAttributes());

	}

	public function preUpdate($product)
	{
		$product->setProductMedia($product->getProductMedia());
		$product->setAttributes($product->getAttributes());
	}

}


text:
<?php

namespace Homie\Expression\Functions;

use BrainExe\Core\EventDispatcher\Events\TimingEvent;
use Generator;
use Homie\Expression\Annotation\ExpressionLanguage as ExpressionLanguageAnnotation;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

/**
 * @ExpressionLanguageAnnotation
 */
class Timing implements ExpressionFunctionProviderInterface
{

    /**
     * @return Generator|ExpressionFunction[] An array of Function instances
     */
    public function getFunctions()
    {
        yield new ExpressionFunction('isTiming', function (string $timingId) {
            return sprintf(
                '($eventName === \'%s\' && $event->getTimingId() === %s)',
                TimingEvent::TIMING_EVENT,
                $timingId
            );
        }, function (array $parameters, string $isTiming) {
            if ($parameters['eventName'] !== TimingEvent::TIMING_EVENT) {
                return false;
            }

            return $parameters['event']->getTimingId() === $isTiming;
        });
    }
}


text:
Phpfastcache has some options that you may want to know before using them.

### Global options
The global options are defined in `\Phpfastcache\Config\ConfigurationOption` ([ConfigurationOption.php](../lib/Phpfastcache/Config/ConfigurationOption.php))

### Driver-specific options *
The driver-specific options are defined in `Config.php` file located in each driver [directory](../lib/Phpfastcache/Drivers).
Each driver-specific `Config` class file extends `\Phpfastcache\Config\ConfigurationOption`


text:
Search/List your Google Drive's Documents.

Requirements:
- Ruby 2.0.0 or higher

# Installation

This script is originated by google-api-ruby-client-samples.

https://github.com/google/google-api-ruby-client-samples/tree/master/drive

- Get your client_secrets.json file from Google API Console
- Save your client_secrets.json to project root

For installation:

```
bundle
```

# Usage

```
bundle exec ./google-drive-permission-search.rb --verbose --type excel
```

# Options

- -type: "excel" or "tsv" is available (default: excel)
- -f FILE_NAME: specify output file name (default: result.(xls|tsv)])
- -v, --verbose: output debug messages
- --only-includes TEXT: output data which includes "TEXT" string only


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

import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;

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

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

/**
 * LogGroup JSON Unmarshaller
 */
public class LogGroupJsonUnmarshaller implements
        Unmarshaller<LogGroup, JsonUnmarshallerContext> {

    public LogGroup unmarshall(JsonUnmarshallerContext context)
            throws Exception {
        LogGroup logGroup = new LogGroup();

        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 null;

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

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("logGroupName", targetDepth)) {
                    context.nextToken();
                    logGroup.setLogGroupName(context.getUnmarshaller(
                            String.class).unmarshall(context));
                }
                if (context.testExpression("creationTime", targetDepth)) {
                    context.nextToken();
                    logGroup.setCreationTime(context
                            .getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("retentionInDays", targetDepth)) {
                    context.nextToken();
                    logGroup.setRetentionInDays(context.getUnmarshaller(
                            Integer.class).unmarshall(context));
                }
                if (context.testExpression("metricFilterCount", targetDepth)) {
                    context.nextToken();
                    logGroup.setMetricFilterCount(context.getUnmarshaller(
                            Integer.class).unmarshall(context));
                }
                if (context.testExpression("arn", targetDepth)) {
                    context.nextToken();
                    logGroup.setArn(context.getUnmarshaller(String.class)
                            .unmarshall(context));
                }
                if (context.testExpression("storedBytes", targetDepth)) {
                    context.nextToken();
                    logGroup.setStoredBytes(context.getUnmarshaller(Long.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 logGroup;
    }

    private static LogGroupJsonUnmarshaller instance;

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


text:
<?php
/**
 * @author Florent HAZARD <f.hazard@sowapps.com>
 */

namespace Orpheus\Controller;

use Orpheus\Exception\UserException;
use Orpheus\InputController\CliController\CliController;
use Orpheus\InputController\CliController\CliResponse;
use Orpheus\InputController\HttpController\HttpController;
use Orpheus\InputController\HttpController\HttpRequest;

class EmptyDefaultCliController extends CliController {

	/**
	 * Prepare environment for this request
	 *
	 * @param HttpRequest $request
	 * @throws UserException
	 */
	public function prepare($request) {
		$this->request = $request;
	}

	/**
	 * Run the controller
	 *
	 * @param HttpRequest $request The input HTTP request
	 * @see HttpController::run()
	 */
	public function run($request): CliResponse {
		return new CliResponse();
	}

}