text
stringlengths
2
99.9k
meta
dict
exports = module.exports = cmd var npm = require('../npm.js') var usage = require('./usage.js') function cmd (stage) { function CMD (args, cb) { npm.commands['run-script']([stage].concat(args), cb) } CMD.usage = usage(stage, 'npm ' + stage + ' [-- <args>]') var installedShallow = require('./completion/installed-shallow.js') CMD.completion = function (opts, cb) { installedShallow(opts, function (d) { return d.scripts && d.scripts[stage] }, cb) } return CMD }
{ "pile_set_name": "Github" }
# From http://lists.x.org/archives/xorg-announce/2013-September/002310.html sha256 23ceeca94e3e20a6c26a703ac7f789066d4517f8d2cb717ae7cb28a617d97dd0 xclock-1.0.7.tar.bz2
{ "pile_set_name": "Github" }
package deepq import ( "fmt" "math/rand" "time" envv1 "github.com/aunum/gold/pkg/v1/env" "github.com/aunum/log" "github.com/gammazero/deque" "gorgonia.org/tensor" ) // Event is an event that occurred. type Event struct { *envv1.Outcome // State by which the action was taken. State *tensor.Dense // Action that was taken. Action int i int } // NewEvent returns a new event func NewEvent(state *tensor.Dense, action int, outcome *envv1.Outcome) *Event { return &Event{ State: state, Action: action, Outcome: outcome, } } // Print the event. func (e *Event) Print() { log.Infof("event --> \n state: %v \n action: %v \n reward: %v \n done: %v \n obv: %v\n\n", e.State, e.Action, e.Reward, e.Done, e.Observation) } // Memory for the dqn agent. type Memory struct { *deque.Deque } // NewMemory returns a new Memory store. func NewMemory() *Memory { return &Memory{ Deque: &deque.Deque{}, } } // Sample from the memory with the given batch size. func (m *Memory) Sample(batchsize int) ([]*Event, error) { if m.Len() < batchsize { return nil, fmt.Errorf("queue size %d is less than batch size %d", m.Len(), batchsize) } events := []*Event{} rand.Seed(time.Now().UnixNano()) for i, value := range rand.Perm(m.Len()) { if i >= batchsize { break } event := m.At(value).(*Event) event.i = value events = append(events, event) } return events, nil }
{ "pile_set_name": "Github" }
--- title: "RegionalSettings element (Regional Settings)" manager: soliver ms.date: 3/9/2015 ms.audience: Developer ms.topic: reference ms.prod: sharepoint localization_priority: Normal api_name: - Regional Settings schema api_type: - schema ms.assetid: d0d3ccfc-881f-4c50-8811-dd875b9555c9 description: Contains the regional settings for currency, language, locale, and time zone that are used in the deployment of Microsoft SharePoint Foundation. --- # RegionalSettings element (Regional Settings) **Applies to:** SharePoint 2016 | SharePoint Foundation 2013 | SharePoint Online | SharePoint Server 2013 Contains the regional settings for currency, language, locale, and time zone that are used in the deployment of Microsoft SharePoint Foundation. Used in TIMEZONE.XML (%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\CONFIG) and RGNLSTNG.XML (%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\1033\XML). ```XML <RegionalSettings> </RegionalSettings> ``` ## Elements and attributes The following sections describe attributes, child elements, and parent elements. ### Attributes None ### Child elements - [Currencies](currencies-element-regional-settings.md) - [Languages](languages-element-regional-settings.md) - [Locales](locales-element-regional-settings.md) - [TimeZones](timezones-element-regional-settings.md) ### Parent elements None ### Occurrences - Minimum: 0 - Maximum: 1 ## Example The following example outlines the structure of the file TIMEZONE.XML. ```XML <RegionalSettings> <TimeZones> ... <TimeZone ID="13" Name="(GMT-08:00) Pacific Time (US and Canada); Tijuana" Hidden="FALSE"> <Bias>480</Bias> <StandardTime> <Bias>0</Bias> <Date> <Month>10</Month> <Day>5</Day> <Hour>2</Hour> </Date> </StandardTime> <DaylightTime> <Bias>-60</Bias> <Date> <Month>4</Month> <Day>1</Day> <Hour>2</Hour> </Date> </DaylightTime> </TimeZone> <TimeZone ID="14" Name="(GMT-09:00) Alaska" Hidden="FALSE"> <Bias>540</Bias> <StandardTime> <Bias>0</Bias> <Date> <Month>10</Month> <Day>5</Day> <Hour>2</Hour> </Date> </StandardTime> <DaylightTime> <Bias>-60</Bias> <Date> <Month>4</Month> <Day>1</Day> <Hour>2</Hour> </Date> </DaylightTime> </TimeZone> ... </TimeZones> </RegionalSettings> ```
{ "pile_set_name": "Github" }
# Copyright (C) 2006-2013 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # menu "Global build settings" config ALL_KMODS bool "Select all kernel module packages by default" default ALL config ALL bool "Select all userspace packages by default" default n config SIGNED_PACKAGES bool "Cryptographically signed package lists" default y comment "General build options" config DISPLAY_SUPPORT bool "Show packages that require graphics support (local or remote)" default n config BUILD_PATENTED default y bool "Compile with support for patented functionality" help When this option is disabled, software which provides patented functionality will not be built. In case software provides optional support for patented functionality, this optional support will get disabled for this package. config BUILD_NLS default n bool "Compile with full language support" help When this option is enabled, packages are built with the full versions of iconv and GNU gettext instead of the default OpenWrt stubs. If uClibc is used, it is also built with locale support. config SHADOW_PASSWORDS bool prompt "Enable shadow password support" default y help Enable shadow password support. config CLEAN_IPKG bool prompt "Remove ipkg/opkg status data files in final images" default n help This removes all ipkg/opkg status data files from the target directory before building the root filesystem. config COLLECT_KERNEL_DEBUG bool prompt "Collect kernel debug information" select KERNEL_DEBUG_INFO default n help This collects debugging symbols from the kernel and all compiled modules. Useful for release builds, so that kernel issues can be debugged offline later. comment "Kernel build options" source "config/Config-kernel.in" comment "Package build options" config DEBUG bool prompt "Compile packages with debugging info" default n help Adds -g3 to the CFLAGS. config IPV6 bool prompt "Enable IPv6 support in packages" default y help Enables IPv6 support in kernel (builtin) and packages. config PKG_BUILD_PARALLEL bool prompt "Compile certain packages parallelized" default y help This adds a -jX option to certain packages that are known to behave well for parallel build. By default, the package make processes use the main jobserver, in which case this option only takes effect when you add -jX to the make command. If you are unsure, select N. config PKG_BUILD_USE_JOBSERVER bool prompt "Use top-level make jobserver for packages" depends on PKG_BUILD_PARALLEL default y help This passes the main make process jobserver fds to package builds, enabling full parallelization across different packages. Note that disabling this may overcommit CPU resources depending on the -j level of the main make process, the number of package submake jobs selected below and the number of actual CPUs present. Example: If the main make is passed a -j4 and the submake -j is also set to 4, we may end up with 16 parallel make processes in the worst case. config PKG_BUILD_JOBS int prompt "Number of package submake jobs (2-512)" range 2 512 default 2 depends on PKG_BUILD_PARALLEL && !PKG_BUILD_USE_JOBSERVER help The number of jobs (-jX) to pass to packages submake. config PKG_DEFAULT_PARALLEL bool prompt "Parallelize the default package build rule (May break build)" depends on PKG_BUILD_PARALLEL depends on BROKEN default n help Always set the default package build rules to parallel build. WARNING: This may break build or kill your cat, as it builds packages with multiple jobs that are probably not tested in a parallel build environment. Only say Y if you don't mind fixing broken packages. Before reporting build bugs, set this to N and re-run the build. comment "Stripping options" choice prompt "Binary stripping method" default USE_STRIP if EXTERNAL_TOOLCHAIN default USE_STRIP if USE_GLIBC default USE_SSTRIP help Select the binary stripping method you wish to use. config NO_STRIP bool "none" help This will install unstripped binaries (useful for native compiling/debugging). config USE_STRIP bool "strip" help This will install binaries stripped using strip from binutils. config USE_SSTRIP bool "sstrip" depends on !USE_GLIBC help This will install binaries stripped using sstrip. endchoice config STRIP_ARGS string prompt "Strip arguments" depends on USE_STRIP default "--strip-unneeded --remove-section=.comment --remove-section=.note" if DEBUG default "--strip-all" help Specifies arguments passed to the strip command when stripping binaries. config STRIP_KERNEL_EXPORTS bool "Strip unnecessary exports from the kernel image" help Reduces kernel size by stripping unused kernel exports from the kernel image. Note that this might make the kernel incompatible with any kernel modules that were not selected at the time the kernel image was created. config USE_MKLIBS bool "Strip unnecessary functions from libraries" help Reduces libraries to only those functions that are necessary for using all selected packages (including those selected as <M>). Note that this will make the system libraries incompatible with most of the packages that are not selected during the build process. choice prompt "Preferred standard C++ library" default USE_LIBSTDCXX if USE_GLIBC default USE_UCLIBCXX help Select the preferred standard C++ library for all packages that support this. config USE_UCLIBCXX bool "uClibc++" config USE_LIBSTDCXX bool "libstdc++" endchoice comment "Hardening build options" config PKG_CHECK_FORMAT_SECURITY bool prompt "Enable gcc format-security" default y help Add -Wformat -Werror=format-security to the CFLAGS. You can disable this per package by adding PKG_CHECK_FORMAT_SECURITY:=0 in the package Makefile. choice prompt "User space Stack-Smashing Protection" depends on USE_MUSL default PKG_CC_STACKPROTECTOR_REGULAR help Enable GCC Stack Smashing Protection (SSP) for userspace applications config PKG_CC_STACKPROTECTOR_NONE bool "None" config PKG_CC_STACKPROTECTOR_REGULAR bool "Regular" select SSP_SUPPORT if !USE_MUSL depends on KERNEL_CC_STACKPROTECTOR_REGULAR config PKG_CC_STACKPROTECTOR_STRONG bool "Strong" select SSP_SUPPORT if !USE_MUSL depends on GCC_VERSION_5 depends on KERNEL_CC_STACKPROTECTOR_STRONG endchoice choice prompt "Kernel space Stack-Smashing Protection" default KERNEL_CC_STACKPROTECTOR_REGULAR depends on USE_MUSL || !(x86_64 || i386) help Enable GCC Stack-Smashing Protection (SSP) for the kernel config KERNEL_CC_STACKPROTECTOR_NONE bool "None" config KERNEL_CC_STACKPROTECTOR_REGULAR bool "Regular" config KERNEL_CC_STACKPROTECTOR_STRONG depends on GCC_VERSION_5 bool "Strong" endchoice choice prompt "Enable buffer-overflows detection (FORTIFY_SOURCE)" default PKG_FORTIFY_SOURCE_1 help Enable the _FORTIFY_SOURCE macro which introduces additional checks to detect buffer-overflows in the following standard library functions: memcpy, mempcpy, memmove, memset, strcpy, stpcpy, strncpy, strcat, strncat, sprintf, vsprintf, snprintf, vsnprintf, gets. "Conservative" (_FORTIFY_SOURCE set to 1) only introduces checks that shouldn't change the behavior of conforming programs, while "aggressive" (_FORTIFY_SOURCES set to 2) some more checking is added, but some conforming programs might fail. config PKG_FORTIFY_SOURCE_NONE bool "None" config PKG_FORTIFY_SOURCE_1 bool "Conservative" config PKG_FORTIFY_SOURCE_2 bool "Aggressive" endchoice choice prompt "Enable RELRO protection" default PKG_RELRO_FULL help Enable a link-time protection known as RELRO (Relocation Read Only) which helps to protect from certain type of exploitation techniques altering the content of some ELF sections. "Partial" RELRO makes the .dynamic section not writeable after initialization, introducing almost no performance penalty, while "full" RELRO also marks the GOT as read-only at the cost of initializing all of it at startup. config PKG_RELRO_NONE bool "None" config PKG_RELRO_PARTIAL bool "Partial" config PKG_RELRO_FULL bool "Full" endchoice endmenu
{ "pile_set_name": "Github" }
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { AuthService } from '../modules/auth/auth.service'; import { UserEntity } from '../modules/user/user.entity'; @Injectable() export class AuthUserInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const request = context.switchToHttp().getRequest(); const user = <UserEntity>request.user; AuthService.setAuthUser(user); return next.handle(); } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Text; namespace System.Web.WebPages.Administration.PackageManager { internal static class PageUtils { private const string WebPagesPreferredTag = " aspnetwebpages "; internal static string GetPackagesHome() { return SiteAdmin.GetVirtualPath("~/packages"); } internal static string GetPageVirtualPath(string page) { return SiteAdmin.GetVirtualPath("~/packages/" + page); } internal static WebPackageSource GetPackageSource(string name) { if (String.IsNullOrEmpty(name)) { return PackageManagerModule.ActiveSource; } // If no source is found for the specified name, default to the ActiveSource return PackageManagerModule.GetSource(name) ?? PackageManagerModule.ActiveSource; } internal static string GetFilterValue(HttpRequestBase request, string cookieName, string key) { var value = request.QueryString[key]; if (String.IsNullOrEmpty(value)) { var cookie = request.Cookies[cookieName]; if (cookie != null) { value = cookie[key]; } } return value; } internal static void PersistFilter(HttpResponseBase response, string cookieName, IDictionary<string, string> filterItems) { var cookie = response.Cookies[cookieName]; if (cookie == null) { cookie = new HttpCookie(cookieName); response.Cookies.Add(cookie); } foreach (var item in filterItems) { cookie[item.Key] = item.Value; } } internal static bool IsValidLicenseUrl(Uri licenseUri) { return Uri.UriSchemeHttp.Equals(licenseUri.Scheme, StringComparison.OrdinalIgnoreCase) || Uri.UriSchemeHttps.Equals(licenseUri.Scheme, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Constructs a query string from an IDictionary /// </summary> internal static string BuildQueryString(IDictionary<string, string> parameters) { StringBuilder stringBuilder = new StringBuilder(); foreach (var param in parameters) { stringBuilder.Append(stringBuilder.Length == 0 ? '?' : '&') .Append(HttpUtility.UrlEncode(param.Key)) .Append('=') .Append(HttpUtility.UrlEncode(param.Value)); } return stringBuilder.ToString(); } } }
{ "pile_set_name": "Github" }
# Copyright (c) 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Pickle collected data for later comparisons. persistent=yes # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= [MESSAGES CONTROL] # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). # CHANGED: # C0103: Invalid name "" # C0111: Missing docstring # C0301: Line too long # C0302: Too many lines in module (N) # I0010: Unable to consider inline option '' # I0011: Locally disabling WNNNN # # R0201: Method could be a function # R0801: Similar lines in N files # R0901: Too many ancestors (8/7) # R0902: Too many instance attributes (N/7) # R0903: Too few public methods (N/2) # R0904: Too many public methods (N/20) # R0911: Too many return statements (N/6) # R0912: Too many branches (N/12) # R0913: Too many arguments (N/5) # R0914: Too many local variables (N/15) # R0915: Too many statements (N/50) # R0921: Abstract class not referenced # R0922: Abstract class is only referenced 1 times # W0122: Use of the exec statement # W0141: Used builtin function '' # W0212: Access to a protected member X of a client class # W0142: Used * or ** magic # W0401: Wildcard import X # W0402: Uses of a deprecated module 'string' # W0404: 41: Reimport 'XX' (imported line NN) # W0511: TODO # W0603: Using the global statement # W0614: Unused import X from wildcard import # W0703: Catch "Exception" # W1201: Specify string format arguments as logging function parameters disable=C0103,C0111,C0301,C0302,I0010,I0011,R0201,R0801,R0901,R0902,R0903,R0904,R0911,R0912,R0913,R0914,R0915,R0921,R0922,W0122,W0141,W0142,W0212,W0401,W0402,W0404,W0511,W0603,W0614,W0703,W1201 [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html output-format=text # Include message's id in output include-ids=yes # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages # CHANGED: reports=no # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the beginning of the name of dummy variables # (i.e. not used). dummy-variables-rgx=_|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject,twisted.internet.reactor,hashlib,google.appengine.api.memcache # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members=REQUEST,acl_users,aq_parent [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes [FORMAT] # Maximum number of characters on a single line. max-line-length=200 # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). # CHANGED: indent-string=' ' [BASIC] # Required attributes for module, separated by a comma required-attributes= # List of builtins function names that should not be used, separated by a comma bad-functions=map,filter,apply,input # Regular expression which should only match correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression which should only match correct module level names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression which should only match correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Regular expression which should only match correct function names function-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct method names method-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct instance attribute names attr-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct argument names argument-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct variable names variable-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct list comprehension / # generator expression variable names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_ # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Regular expression which should only match functions or classes name which do # not require a docstring no-docstring-rgx=__.*__ [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branchs=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=regsub,string,TERMIOS,Bastion,rexec # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception
{ "pile_set_name": "Github" }
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!29 &1 OcclusionCullingSettings: m_ObjectHideFlags: 0 serializedVersion: 2 m_OcclusionBakeSettings: smallestOccluder: 5 smallestHole: 0.25 backfaceThreshold: 100 m_SceneGUID: 00000000000000000000000000000000 m_OcclusionCullingData: {fileID: 0} --- !u!104 &2 RenderSettings: m_ObjectHideFlags: 0 serializedVersion: 9 m_Fog: 0 m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} m_FogMode: 3 m_FogDensity: 0.01 m_LinearFogStart: 0 m_LinearFogEnd: 300 m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} m_AmbientIntensity: 1 m_AmbientMode: 0 m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} m_HaloStrength: 0.5 m_FlareStrength: 1 m_FlareFadeSpeed: 3 m_HaloTexture: {fileID: 0} m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} m_DefaultReflectionMode: 0 m_DefaultReflectionResolution: 128 m_ReflectionBounces: 1 m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 170076734} m_IndirectSpecularColor: {r: 0.18028355, g: 0.22571374, b: 0.30692255, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: m_ObjectHideFlags: 0 serializedVersion: 11 m_GIWorkflowMode: 0 m_GISettings: serializedVersion: 2 m_BounceScale: 1 m_IndirectOutputScale: 1 m_AlbedoBoost: 1 m_EnvironmentLightingMode: 0 m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 0 m_LightmapEditorSettings: serializedVersion: 10 m_Resolution: 2 m_BakeResolution: 10 m_AtlasSize: 512 m_AO: 0 m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 m_TextureCompression: 1 m_FinalGather: 0 m_FinalGatherFiltering: 1 m_FinalGatherRayCount: 256 m_ReflectionCompression: 2 m_MixedBakeMode: 2 m_BakeBackend: 1 m_PVRSampling: 1 m_PVRDirectSampleCount: 32 m_PVRSampleCount: 256 m_PVRBounces: 2 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 m_PVRFilteringMode: 1 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 m_PVRFilteringGaussRadiusAO: 2 m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 m_ShowResolutionOverlay: 1 m_LightingDataAsset: {fileID: 0} m_UseShadowmask: 1 --- !u!196 &4 NavMeshSettings: serializedVersion: 2 m_ObjectHideFlags: 0 m_BuildSettings: serializedVersion: 2 agentTypeID: 0 agentRadius: 0.5 agentHeight: 2 agentSlope: 45 agentClimb: 0.4 ledgeDropHeight: 0 maxJumpAcrossDistance: 0 minRegionArea: 2 manualCellSize: 0 cellSize: 0.16666667 manualTileSize: 0 tileSize: 256 accuratePlacement: 0 debug: m_Flags: 0 m_NavMeshData: {fileID: 0} --- !u!1 &170076733 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 170076735} - component: {fileID: 170076734} m_Layer: 0 m_Name: Directional Light m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!108 &170076734 Light: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 170076733} m_Enabled: 1 serializedVersion: 8 m_Type: 1 m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} m_Intensity: 1 m_Range: 10 m_SpotAngle: 30 m_CookieSize: 10 m_Shadows: m_Type: 2 m_Resolution: -1 m_CustomResolution: -1 m_Strength: 1 m_Bias: 0.05 m_NormalBias: 0.4 m_NearPlane: 0.2 m_Cookie: {fileID: 0} m_DrawHalo: 0 m_Flare: {fileID: 0} m_RenderMode: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294967295 m_Lightmapping: 1 m_LightShadowCasterMode: 0 m_AreaSize: {x: 1, y: 1} m_BounceIntensity: 1 m_ColorTemperature: 6570 m_UseColorTemperature: 0 m_ShadowRadius: 0 m_ShadowAngle: 0 --- !u!4 &170076735 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 170076733} m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261} m_LocalPosition: {x: 0, y: 3, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0} --- !u!1 &534669902 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 534669905} - component: {fileID: 534669904} - component: {fileID: 534669903} - component: {fileID: 534669908} - component: {fileID: 534669906} - component: {fileID: 534669907} m_Layer: 0 m_Name: Main Camera m_TagString: MainCamera m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!81 &534669903 AudioListener: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 --- !u!20 &534669904 Camera: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_projectionMatrixMode: 1 m_SensorSize: {x: 36, y: 24} m_LensShift: {x: 0, y: 0} m_GateFitMode: 2 m_FocalLength: 50 m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: -1 m_CullingMask: serializedVersion: 2 m_Bits: 4294967295 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 1 m_AllowMSAA: 1 m_AllowDynamicResolution: 0 m_ForceIntoRT: 1 m_OcclusionCulling: 1 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!4 &534669905 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 1, z: -10} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &534669906 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 3e24ef00b2c654bb98b41804c985fe55, type: 3} m_Name: m_EditorClassIdentifier: material: {fileID: 2100000, guid: 25435d20b534145198b6504ed75ea06f, type: 2} --- !u!114 &534669907 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1742a5216af1a441d9b5e8b6f3de6c96, type: 3} m_Name: m_EditorClassIdentifier: material: {fileID: 2100000, guid: b94234e7349dc4e5bbd5575b9377d263, type: 2} speed: 1 --- !u!114 &534669908 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 621596ad687ad4eca991108f26e9673a, type: 3} m_Name: m_EditorClassIdentifier: cycleInterval: 2 materials: - {fileID: 2100000, guid: 25435d20b534145198b6504ed75ea06f, type: 2} - {fileID: 2100000, guid: b94234e7349dc4e5bbd5575b9377d263, type: 2} - {fileID: 2100000, guid: 4dd0daa9715c0ba4bb16018308ce9000, type: 2} - {fileID: 2100000, guid: b41ba31a89ccb4d8fa96e9ec09253174, type: 2} - {fileID: 2100000, guid: e43b144c336254275838ae41faea7954, type: 2} - {fileID: 2100000, guid: a3ada1b7a85244e51b2f69766a8cd669, type: 2} - {fileID: 2100000, guid: 1c6e4499c090e434cbdd22314f4daf82, type: 2} - {fileID: 2100000, guid: d61a9fb14d8ab492e98445f0729db5ca, type: 2} - {fileID: 2100000, guid: 8aa06232ec54c4303a216328e6938a97, type: 2} - {fileID: 2100000, guid: ab546805727fd4c04b014d0575d440dc, type: 2} - {fileID: 2100000, guid: a0b5d09605efa4932a029f45121f9706, type: 2} --- !u!1 &1140052746 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 1140052750} - component: {fileID: 1140052749} - component: {fileID: 1140052748} - component: {fileID: 1140052747} m_Layer: 0 m_Name: Cube m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!65 &1140052747 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1140052746} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!23 &1140052748 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1140052746} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &1140052749 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1140052746} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!4 &1140052750 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1140052746} m_LocalRotation: {x: 0.04004227, y: -0.39548567, z: 0.33010873, w: 0.8561635} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1.9977, y: 1.9977, z: 1.9977} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 19.249, y: -43.575, z: 34.415} --- !u!1 &1235551315 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 1235551317} - component: {fileID: 1235551316} m_Layer: 0 m_Name: Second Camera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!20 &1235551316 Camera: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1235551315} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 2 m_BackGroundColor: {r: 0.735849, g: 0.21173012, b: 0.21173012, a: 0} m_projectionMatrixMode: 1 m_SensorSize: {x: 36, y: 24} m_LensShift: {x: 0, y: 0} m_GateFitMode: 2 m_FocalLength: 50 m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294967295 m_RenderingPath: -1 m_TargetTexture: {fileID: 8400000, guid: b4cbb265595964cf5905ef434583d399, type: 2} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 1 m_AllowMSAA: 1 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 1 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!4 &1235551317 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1235551315} m_LocalRotation: {x: 0.33686924, y: -0, z: -0, w: 0.94155145} m_LocalPosition: {x: 0.4, y: 8.5, z: -7.5} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 39.372, y: 0, z: 0}
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file contains implementations of the divisions * WebRtcSpl_DivU32U16() * WebRtcSpl_DivW32W16() * WebRtcSpl_DivW32W16ResW16() * WebRtcSpl_DivResultInQ31() * WebRtcSpl_DivW32HiLow() * * The description header can be found in signal_processing_library.h * */ #include "webrtc/common_audio/signal_processing/include/signal_processing_library.h" #include "webrtc/rtc_base/sanitizer.h" uint32_t WebRtcSpl_DivU32U16(uint32_t num, uint16_t den) { // Guard against division with 0 if (den != 0) { return (uint32_t)(num / den); } else { return (uint32_t)0xFFFFFFFF; } } int32_t WebRtcSpl_DivW32W16(int32_t num, int16_t den) { // Guard against division with 0 if (den != 0) { return (int32_t)(num / den); } else { return (int32_t)0x7FFFFFFF; } } int16_t WebRtcSpl_DivW32W16ResW16(int32_t num, int16_t den) { // Guard against division with 0 if (den != 0) { return (int16_t)(num / den); } else { return (int16_t)0x7FFF; } } int32_t WebRtcSpl_DivResultInQ31(int32_t num, int32_t den) { int32_t L_num = num; int32_t L_den = den; int32_t div = 0; int k = 31; int change_sign = 0; if (num == 0) return 0; if (num < 0) { change_sign++; L_num = -num; } if (den < 0) { change_sign++; L_den = -den; } while (k--) { div <<= 1; L_num <<= 1; if (L_num >= L_den) { L_num -= L_den; div++; } } if (change_sign == 1) { div = -div; } return div; } int32_t RTC_NO_SANITIZE("signed-integer-overflow") // bugs.webrtc.org/5486 WebRtcSpl_DivW32HiLow(int32_t num, int16_t den_hi, int16_t den_low) { int16_t approx, tmp_hi, tmp_low, num_hi, num_low; int32_t tmpW32; approx = (int16_t)WebRtcSpl_DivW32W16((int32_t)0x1FFFFFFF, den_hi); // result in Q14 (Note: 3FFFFFFF = 0.5 in Q30) // tmpW32 = 1/den = approx * (2.0 - den * approx) (in Q30) tmpW32 = (den_hi * approx << 1) + ((den_low * approx >> 15) << 1); // tmpW32 = den * approx tmpW32 = (int32_t)0x7fffffffL - tmpW32; // result in Q30 (tmpW32 = 2.0-(den*approx)) // UBSan: 2147483647 - -2 cannot be represented in type 'int' // Store tmpW32 in hi and low format tmp_hi = (int16_t)(tmpW32 >> 16); tmp_low = (int16_t)((tmpW32 - ((int32_t)tmp_hi << 16)) >> 1); // tmpW32 = 1/den in Q29 tmpW32 = (tmp_hi * approx + (tmp_low * approx >> 15)) << 1; // 1/den in hi and low format tmp_hi = (int16_t)(tmpW32 >> 16); tmp_low = (int16_t)((tmpW32 - ((int32_t)tmp_hi << 16)) >> 1); // Store num in hi and low format num_hi = (int16_t)(num >> 16); num_low = (int16_t)((num - ((int32_t)num_hi << 16)) >> 1); // num * (1/den) by 32 bit multiplication (result in Q28) tmpW32 = num_hi * tmp_hi + (num_hi * tmp_low >> 15) + (num_low * tmp_hi >> 15); // Put result in Q31 (convert from Q28) tmpW32 = WEBRTC_SPL_LSHIFT_W32(tmpW32, 3); return tmpW32; }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dx.cf.code; import com.android.dx.rop.cst.Constant; import com.android.dx.rop.cst.ConstantPool; import com.android.dx.rop.cst.CstDouble; import com.android.dx.rop.cst.CstFloat; import com.android.dx.rop.cst.CstInteger; import com.android.dx.rop.cst.CstKnownNull; import com.android.dx.rop.cst.CstLiteralBits; import com.android.dx.rop.cst.CstLong; import com.android.dx.rop.cst.CstType; import com.android.dx.rop.type.Type; import com.android.dx.util.Bits; import com.android.dx.util.ByteArray; import com.android.dx.util.Hex; import java.util.ArrayList; /** * Bytecode array, which is part of a standard {@code Code} attribute. */ public final class BytecodeArray { /** convenient no-op implementation of {@link Visitor} */ public static final Visitor EMPTY_VISITOR = new BaseVisitor(); /** {@code non-null;} underlying bytes */ private final ByteArray bytes; /** * {@code non-null;} constant pool to use when resolving constant * pool indices */ private final ConstantPool pool; /** * Constructs an instance. * * @param bytes {@code non-null;} underlying bytes * @param pool {@code non-null;} constant pool to use when * resolving constant pool indices */ public BytecodeArray(ByteArray bytes, ConstantPool pool) { if (bytes == null) { throw new NullPointerException("bytes == null"); } if (pool == null) { throw new NullPointerException("pool == null"); } this.bytes = bytes; this.pool = pool; } /** * Gets the underlying byte array. * * @return {@code non-null;} the byte array */ public ByteArray getBytes() { return bytes; } /** * Gets the size of the bytecode array, per se. * * @return {@code >= 0;} the length of the bytecode array */ public int size() { return bytes.size(); } /** * Gets the total length of this structure in bytes, when included in * a {@code Code} attribute. The returned value includes the * array size plus four bytes for {@code code_length}. * * @return {@code >= 4;} the total length, in bytes */ public int byteLength() { return 4 + bytes.size(); } /** * Parses each instruction in the array, in order. * * @param visitor {@code null-ok;} visitor to call back to for * each instruction */ public void forEach(Visitor visitor) { int sz = bytes.size(); int at = 0; while (at < sz) { /* * Don't record the previous offset here, so that we get to see the * raw code that initializes the array */ at += parseInstruction(at, visitor); } } /** * Finds the offset to each instruction in the bytecode array. The * result is a bit set with the offset of each opcode-per-se flipped on. * * @see Bits * @return {@code non-null;} appropriately constructed bit set */ public int[] getInstructionOffsets() { int sz = bytes.size(); int[] result = Bits.makeBitSet(sz); int at = 0; while (at < sz) { Bits.set(result, at, true); int length = parseInstruction(at, null); at += length; } return result; } /** * Processes the given "work set" by repeatedly finding the lowest bit * in the set, clearing it, and parsing and visiting the instruction at * the indicated offset (that is, the bit index), repeating until the * work set is empty. It is expected that the visitor will regularly * set new bits in the work set during the process. * * @param workSet {@code non-null;} the work set to process * @param visitor {@code non-null;} visitor to call back to for * each instruction */ public void processWorkSet(int[] workSet, Visitor visitor) { if (visitor == null) { throw new NullPointerException("visitor == null"); } for (;;) { int offset = Bits.findFirst(workSet, 0); if (offset < 0) { break; } Bits.clear(workSet, offset); parseInstruction(offset, visitor); visitor.setPreviousOffset(offset); } } /** * Parses the instruction at the indicated offset. Indicate the * result by calling the visitor if supplied and by returning the * number of bytes consumed by the instruction. * * <p>In order to simplify further processing, the opcodes passed * to the visitor are canonicalized, altering the opcode to a more * universal one and making formerly implicit arguments * explicit. In particular:</p> * * <ul> * <li>The opcodes to push literal constants of primitive types all become * {@code ldc}. * E.g., {@code fconst_0}, {@code sipush}, and * {@code lconst_0} qualify for this treatment.</li> * <li>{@code aconst_null} becomes {@code ldc} of a * "known null."</li> * <li>Shorthand local variable accessors become the corresponding * longhand. E.g. {@code aload_2} becomes {@code aload}.</li> * <li>{@code goto_w} and {@code jsr_w} become {@code goto} * and {@code jsr} (respectively).</li> * <li>{@code ldc_w} becomes {@code ldc}.</li> * <li>{@code tableswitch} becomes {@code lookupswitch}. * <li>Arithmetic, array, and value-returning ops are collapsed * to the {@code int} variant opcode, with the {@code type} * argument set to indicate the actual type. E.g., * {@code fadd} becomes {@code iadd}, but * {@code type} is passed as {@code Type.FLOAT} in that * case. Similarly, {@code areturn} becomes * {@code ireturn}. (However, {@code return} remains * unchanged.</li> * <li>Local variable access ops are collapsed to the {@code int} * variant opcode, with the {@code type} argument set to indicate * the actual type. E.g., {@code aload} becomes {@code iload}, * but {@code type} is passed as {@code Type.OBJECT} in * that case.</li> * <li>Numeric conversion ops ({@code i2l}, etc.) are left alone * to avoid too much confustion, but their {@code type} is * the pushed type. E.g., {@code i2b} gets type * {@code Type.INT}, and {@code f2d} gets type * {@code Type.DOUBLE}. Other unaltered opcodes also get * their pushed type. E.g., {@code arraylength} gets type * {@code Type.INT}.</li> * </ul> * * @param offset {@code >= 0, < bytes.size();} offset to the start of the * instruction * @param visitor {@code null-ok;} visitor to call back to * @return the length of the instruction, in bytes */ public int parseInstruction(int offset, Visitor visitor) { if (visitor == null) { visitor = EMPTY_VISITOR; } try { int opcode = bytes.getUnsignedByte(offset); int info = ByteOps.opInfo(opcode); int fmt = info & ByteOps.FMT_MASK; switch (opcode) { case ByteOps.NOP: { visitor.visitNoArgs(opcode, offset, 1, Type.VOID); return 1; } case ByteOps.ACONST_NULL: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstKnownNull.THE_ONE, 0); return 1; } case ByteOps.ICONST_M1: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstInteger.VALUE_M1, -1); return 1; } case ByteOps.ICONST_0: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstInteger.VALUE_0, 0); return 1; } case ByteOps.ICONST_1: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstInteger.VALUE_1, 1); return 1; } case ByteOps.ICONST_2: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstInteger.VALUE_2, 2); return 1; } case ByteOps.ICONST_3: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstInteger.VALUE_3, 3); return 1; } case ByteOps.ICONST_4: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstInteger.VALUE_4, 4); return 1; } case ByteOps.ICONST_5: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstInteger.VALUE_5, 5); return 1; } case ByteOps.LCONST_0: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstLong.VALUE_0, 0); return 1; } case ByteOps.LCONST_1: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstLong.VALUE_1, 0); return 1; } case ByteOps.FCONST_0: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstFloat.VALUE_0, 0); return 1; } case ByteOps.FCONST_1: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstFloat.VALUE_1, 0); return 1; } case ByteOps.FCONST_2: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstFloat.VALUE_2, 0); return 1; } case ByteOps.DCONST_0: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstDouble.VALUE_0, 0); return 1; } case ByteOps.DCONST_1: { visitor.visitConstant(ByteOps.LDC, offset, 1, CstDouble.VALUE_1, 0); return 1; } case ByteOps.BIPUSH: { int value = bytes.getByte(offset + 1); visitor.visitConstant(ByteOps.LDC, offset, 2, CstInteger.make(value), value); return 2; } case ByteOps.SIPUSH: { int value = bytes.getShort(offset + 1); visitor.visitConstant(ByteOps.LDC, offset, 3, CstInteger.make(value), value); return 3; } case ByteOps.LDC: { int idx = bytes.getUnsignedByte(offset + 1); Constant cst = pool.get(idx); int value = (cst instanceof CstInteger) ? ((CstInteger) cst).getValue() : 0; visitor.visitConstant(ByteOps.LDC, offset, 2, cst, value); return 2; } case ByteOps.LDC_W: { int idx = bytes.getUnsignedShort(offset + 1); Constant cst = pool.get(idx); int value = (cst instanceof CstInteger) ? ((CstInteger) cst).getValue() : 0; visitor.visitConstant(ByteOps.LDC, offset, 3, cst, value); return 3; } case ByteOps.LDC2_W: { int idx = bytes.getUnsignedShort(offset + 1); Constant cst = pool.get(idx); visitor.visitConstant(ByteOps.LDC2_W, offset, 3, cst, 0); return 3; } case ByteOps.ILOAD: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ILOAD, offset, 2, idx, Type.INT, 0); return 2; } case ByteOps.LLOAD: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ILOAD, offset, 2, idx, Type.LONG, 0); return 2; } case ByteOps.FLOAD: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ILOAD, offset, 2, idx, Type.FLOAT, 0); return 2; } case ByteOps.DLOAD: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ILOAD, offset, 2, idx, Type.DOUBLE, 0); return 2; } case ByteOps.ALOAD: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ILOAD, offset, 2, idx, Type.OBJECT, 0); return 2; } case ByteOps.ILOAD_0: case ByteOps.ILOAD_1: case ByteOps.ILOAD_2: case ByteOps.ILOAD_3: { int idx = opcode - ByteOps.ILOAD_0; visitor.visitLocal(ByteOps.ILOAD, offset, 1, idx, Type.INT, 0); return 1; } case ByteOps.LLOAD_0: case ByteOps.LLOAD_1: case ByteOps.LLOAD_2: case ByteOps.LLOAD_3: { int idx = opcode - ByteOps.LLOAD_0; visitor.visitLocal(ByteOps.ILOAD, offset, 1, idx, Type.LONG, 0); return 1; } case ByteOps.FLOAD_0: case ByteOps.FLOAD_1: case ByteOps.FLOAD_2: case ByteOps.FLOAD_3: { int idx = opcode - ByteOps.FLOAD_0; visitor.visitLocal(ByteOps.ILOAD, offset, 1, idx, Type.FLOAT, 0); return 1; } case ByteOps.DLOAD_0: case ByteOps.DLOAD_1: case ByteOps.DLOAD_2: case ByteOps.DLOAD_3: { int idx = opcode - ByteOps.DLOAD_0; visitor.visitLocal(ByteOps.ILOAD, offset, 1, idx, Type.DOUBLE, 0); return 1; } case ByteOps.ALOAD_0: case ByteOps.ALOAD_1: case ByteOps.ALOAD_2: case ByteOps.ALOAD_3: { int idx = opcode - ByteOps.ALOAD_0; visitor.visitLocal(ByteOps.ILOAD, offset, 1, idx, Type.OBJECT, 0); return 1; } case ByteOps.IALOAD: { visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.INT); return 1; } case ByteOps.LALOAD: { visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.LONG); return 1; } case ByteOps.FALOAD: { visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.FLOAT); return 1; } case ByteOps.DALOAD: { visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.DOUBLE); return 1; } case ByteOps.AALOAD: { visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.OBJECT); return 1; } case ByteOps.BALOAD: { /* * Note: This is a load from either a byte[] or a * boolean[]. */ visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.BYTE); return 1; } case ByteOps.CALOAD: { visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.CHAR); return 1; } case ByteOps.SALOAD: { visitor.visitNoArgs(ByteOps.IALOAD, offset, 1, Type.SHORT); return 1; } case ByteOps.ISTORE: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ISTORE, offset, 2, idx, Type.INT, 0); return 2; } case ByteOps.LSTORE: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ISTORE, offset, 2, idx, Type.LONG, 0); return 2; } case ByteOps.FSTORE: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ISTORE, offset, 2, idx, Type.FLOAT, 0); return 2; } case ByteOps.DSTORE: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ISTORE, offset, 2, idx, Type.DOUBLE, 0); return 2; } case ByteOps.ASTORE: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(ByteOps.ISTORE, offset, 2, idx, Type.OBJECT, 0); return 2; } case ByteOps.ISTORE_0: case ByteOps.ISTORE_1: case ByteOps.ISTORE_2: case ByteOps.ISTORE_3: { int idx = opcode - ByteOps.ISTORE_0; visitor.visitLocal(ByteOps.ISTORE, offset, 1, idx, Type.INT, 0); return 1; } case ByteOps.LSTORE_0: case ByteOps.LSTORE_1: case ByteOps.LSTORE_2: case ByteOps.LSTORE_3: { int idx = opcode - ByteOps.LSTORE_0; visitor.visitLocal(ByteOps.ISTORE, offset, 1, idx, Type.LONG, 0); return 1; } case ByteOps.FSTORE_0: case ByteOps.FSTORE_1: case ByteOps.FSTORE_2: case ByteOps.FSTORE_3: { int idx = opcode - ByteOps.FSTORE_0; visitor.visitLocal(ByteOps.ISTORE, offset, 1, idx, Type.FLOAT, 0); return 1; } case ByteOps.DSTORE_0: case ByteOps.DSTORE_1: case ByteOps.DSTORE_2: case ByteOps.DSTORE_3: { int idx = opcode - ByteOps.DSTORE_0; visitor.visitLocal(ByteOps.ISTORE, offset, 1, idx, Type.DOUBLE, 0); return 1; } case ByteOps.ASTORE_0: case ByteOps.ASTORE_1: case ByteOps.ASTORE_2: case ByteOps.ASTORE_3: { int idx = opcode - ByteOps.ASTORE_0; visitor.visitLocal(ByteOps.ISTORE, offset, 1, idx, Type.OBJECT, 0); return 1; } case ByteOps.IASTORE: { visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.INT); return 1; } case ByteOps.LASTORE: { visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.LONG); return 1; } case ByteOps.FASTORE: { visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.FLOAT); return 1; } case ByteOps.DASTORE: { visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.DOUBLE); return 1; } case ByteOps.AASTORE: { visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.OBJECT); return 1; } case ByteOps.BASTORE: { /* * Note: This is a load from either a byte[] or a * boolean[]. */ visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.BYTE); return 1; } case ByteOps.CASTORE: { visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.CHAR); return 1; } case ByteOps.SASTORE: { visitor.visitNoArgs(ByteOps.IASTORE, offset, 1, Type.SHORT); return 1; } case ByteOps.POP: case ByteOps.POP2: case ByteOps.DUP: case ByteOps.DUP_X1: case ByteOps.DUP_X2: case ByteOps.DUP2: case ByteOps.DUP2_X1: case ByteOps.DUP2_X2: case ByteOps.SWAP: { visitor.visitNoArgs(opcode, offset, 1, Type.VOID); return 1; } case ByteOps.IADD: case ByteOps.ISUB: case ByteOps.IMUL: case ByteOps.IDIV: case ByteOps.IREM: case ByteOps.INEG: case ByteOps.ISHL: case ByteOps.ISHR: case ByteOps.IUSHR: case ByteOps.IAND: case ByteOps.IOR: case ByteOps.IXOR: { visitor.visitNoArgs(opcode, offset, 1, Type.INT); return 1; } case ByteOps.LADD: case ByteOps.LSUB: case ByteOps.LMUL: case ByteOps.LDIV: case ByteOps.LREM: case ByteOps.LNEG: case ByteOps.LSHL: case ByteOps.LSHR: case ByteOps.LUSHR: case ByteOps.LAND: case ByteOps.LOR: case ByteOps.LXOR: { /* * It's "opcode - 1" because, conveniently enough, all * these long ops are one past the int variants. */ visitor.visitNoArgs(opcode - 1, offset, 1, Type.LONG); return 1; } case ByteOps.FADD: case ByteOps.FSUB: case ByteOps.FMUL: case ByteOps.FDIV: case ByteOps.FREM: case ByteOps.FNEG: { /* * It's "opcode - 2" because, conveniently enough, all * these float ops are two past the int variants. */ visitor.visitNoArgs(opcode - 2, offset, 1, Type.FLOAT); return 1; } case ByteOps.DADD: case ByteOps.DSUB: case ByteOps.DMUL: case ByteOps.DDIV: case ByteOps.DREM: case ByteOps.DNEG: { /* * It's "opcode - 3" because, conveniently enough, all * these double ops are three past the int variants. */ visitor.visitNoArgs(opcode - 3, offset, 1, Type.DOUBLE); return 1; } case ByteOps.IINC: { int idx = bytes.getUnsignedByte(offset + 1); int value = bytes.getByte(offset + 2); visitor.visitLocal(opcode, offset, 3, idx, Type.INT, value); return 3; } case ByteOps.I2L: case ByteOps.F2L: case ByteOps.D2L: { visitor.visitNoArgs(opcode, offset, 1, Type.LONG); return 1; } case ByteOps.I2F: case ByteOps.L2F: case ByteOps.D2F: { visitor.visitNoArgs(opcode, offset, 1, Type.FLOAT); return 1; } case ByteOps.I2D: case ByteOps.L2D: case ByteOps.F2D: { visitor.visitNoArgs(opcode, offset, 1, Type.DOUBLE); return 1; } case ByteOps.L2I: case ByteOps.F2I: case ByteOps.D2I: case ByteOps.I2B: case ByteOps.I2C: case ByteOps.I2S: case ByteOps.LCMP: case ByteOps.FCMPL: case ByteOps.FCMPG: case ByteOps.DCMPL: case ByteOps.DCMPG: case ByteOps.ARRAYLENGTH: { visitor.visitNoArgs(opcode, offset, 1, Type.INT); return 1; } case ByteOps.IFEQ: case ByteOps.IFNE: case ByteOps.IFLT: case ByteOps.IFGE: case ByteOps.IFGT: case ByteOps.IFLE: case ByteOps.IF_ICMPEQ: case ByteOps.IF_ICMPNE: case ByteOps.IF_ICMPLT: case ByteOps.IF_ICMPGE: case ByteOps.IF_ICMPGT: case ByteOps.IF_ICMPLE: case ByteOps.IF_ACMPEQ: case ByteOps.IF_ACMPNE: case ByteOps.GOTO: case ByteOps.JSR: case ByteOps.IFNULL: case ByteOps.IFNONNULL: { int target = offset + bytes.getShort(offset + 1); visitor.visitBranch(opcode, offset, 3, target); return 3; } case ByteOps.RET: { int idx = bytes.getUnsignedByte(offset + 1); visitor.visitLocal(opcode, offset, 2, idx, Type.RETURN_ADDRESS, 0); return 2; } case ByteOps.TABLESWITCH: { return parseTableswitch(offset, visitor); } case ByteOps.LOOKUPSWITCH: { return parseLookupswitch(offset, visitor); } case ByteOps.IRETURN: { visitor.visitNoArgs(ByteOps.IRETURN, offset, 1, Type.INT); return 1; } case ByteOps.LRETURN: { visitor.visitNoArgs(ByteOps.IRETURN, offset, 1, Type.LONG); return 1; } case ByteOps.FRETURN: { visitor.visitNoArgs(ByteOps.IRETURN, offset, 1, Type.FLOAT); return 1; } case ByteOps.DRETURN: { visitor.visitNoArgs(ByteOps.IRETURN, offset, 1, Type.DOUBLE); return 1; } case ByteOps.ARETURN: { visitor.visitNoArgs(ByteOps.IRETURN, offset, 1, Type.OBJECT); return 1; } case ByteOps.RETURN: case ByteOps.ATHROW: case ByteOps.MONITORENTER: case ByteOps.MONITOREXIT: { visitor.visitNoArgs(opcode, offset, 1, Type.VOID); return 1; } case ByteOps.GETSTATIC: case ByteOps.PUTSTATIC: case ByteOps.GETFIELD: case ByteOps.PUTFIELD: case ByteOps.INVOKEVIRTUAL: case ByteOps.INVOKESPECIAL: case ByteOps.INVOKESTATIC: case ByteOps.NEW: case ByteOps.ANEWARRAY: case ByteOps.CHECKCAST: case ByteOps.INSTANCEOF: { int idx = bytes.getUnsignedShort(offset + 1); Constant cst = pool.get(idx); visitor.visitConstant(opcode, offset, 3, cst, 0); return 3; } case ByteOps.INVOKEINTERFACE: { int idx = bytes.getUnsignedShort(offset + 1); int count = bytes.getUnsignedByte(offset + 3); int expectZero = bytes.getUnsignedByte(offset + 4); Constant cst = pool.get(idx); visitor.visitConstant(opcode, offset, 5, cst, count | (expectZero << 8)); return 5; } case ByteOps.NEWARRAY: { return parseNewarray(offset, visitor); } case ByteOps.WIDE: { return parseWide(offset, visitor); } case ByteOps.MULTIANEWARRAY: { int idx = bytes.getUnsignedShort(offset + 1); int dimensions = bytes.getUnsignedByte(offset + 3); Constant cst = pool.get(idx); visitor.visitConstant(opcode, offset, 4, cst, dimensions); return 4; } case ByteOps.GOTO_W: case ByteOps.JSR_W: { int target = offset + bytes.getInt(offset + 1); int newop = (opcode == ByteOps.GOTO_W) ? ByteOps.GOTO : ByteOps.JSR; visitor.visitBranch(newop, offset, 5, target); return 5; } default: { visitor.visitInvalid(opcode, offset, 1); return 1; } } } catch (SimException ex) { ex.addContext("...at bytecode offset " + Hex.u4(offset)); throw ex; } catch (RuntimeException ex) { SimException se = new SimException(ex); se.addContext("...at bytecode offset " + Hex.u4(offset)); throw se; } } /** * Helper to deal with {@code tableswitch}. * * @param offset the offset to the {@code tableswitch} opcode itself * @param visitor {@code non-null;} visitor to use * @return instruction length, in bytes */ private int parseTableswitch(int offset, Visitor visitor) { int at = (offset + 4) & ~3; // "at" skips the padding. // Collect the padding. int padding = 0; for (int i = offset + 1; i < at; i++) { padding = (padding << 8) | bytes.getUnsignedByte(i); } int defaultTarget = offset + bytes.getInt(at); int low = bytes.getInt(at + 4); int high = bytes.getInt(at + 8); int count = high - low + 1; at += 12; if (low > high) { throw new SimException("low / high inversion"); } SwitchList cases = new SwitchList(count); for (int i = 0; i < count; i++) { int target = offset + bytes.getInt(at); at += 4; cases.add(low + i, target); } cases.setDefaultTarget(defaultTarget); cases.removeSuperfluousDefaults(); cases.setImmutable(); int length = at - offset; visitor.visitSwitch(ByteOps.LOOKUPSWITCH, offset, length, cases, padding); return length; } /** * Helper to deal with {@code lookupswitch}. * * @param offset the offset to the {@code lookupswitch} opcode itself * @param visitor {@code non-null;} visitor to use * @return instruction length, in bytes */ private int parseLookupswitch(int offset, Visitor visitor) { int at = (offset + 4) & ~3; // "at" skips the padding. // Collect the padding. int padding = 0; for (int i = offset + 1; i < at; i++) { padding = (padding << 8) | bytes.getUnsignedByte(i); } int defaultTarget = offset + bytes.getInt(at); int npairs = bytes.getInt(at + 4); at += 8; SwitchList cases = new SwitchList(npairs); for (int i = 0; i < npairs; i++) { int match = bytes.getInt(at); int target = offset + bytes.getInt(at + 4); at += 8; cases.add(match, target); } cases.setDefaultTarget(defaultTarget); cases.removeSuperfluousDefaults(); cases.setImmutable(); int length = at - offset; visitor.visitSwitch(ByteOps.LOOKUPSWITCH, offset, length, cases, padding); return length; } /** * Helper to deal with {@code newarray}. * * @param offset the offset to the {@code newarray} opcode itself * @param visitor {@code non-null;} visitor to use * @return instruction length, in bytes */ private int parseNewarray(int offset, Visitor visitor) { int value = bytes.getUnsignedByte(offset + 1); CstType type; switch (value) { case ByteOps.NEWARRAY_BOOLEAN: { type = CstType.BOOLEAN_ARRAY; break; } case ByteOps.NEWARRAY_CHAR: { type = CstType.CHAR_ARRAY; break; } case ByteOps.NEWARRAY_DOUBLE: { type = CstType.DOUBLE_ARRAY; break; } case ByteOps.NEWARRAY_FLOAT: { type = CstType.FLOAT_ARRAY; break; } case ByteOps.NEWARRAY_BYTE: { type = CstType.BYTE_ARRAY; break; } case ByteOps.NEWARRAY_SHORT: { type = CstType.SHORT_ARRAY; break; } case ByteOps.NEWARRAY_INT: { type = CstType.INT_ARRAY; break; } case ByteOps.NEWARRAY_LONG: { type = CstType.LONG_ARRAY; break; } default: { throw new SimException("bad newarray code " + Hex.u1(value)); } } // Revisit the previous bytecode to find out the length of the array int previousOffset = visitor.getPreviousOffset(); ConstantParserVisitor constantVisitor = new ConstantParserVisitor(); int arrayLength = 0; /* * For visitors that don't record the previous offset, -1 will be * seen here */ if (previousOffset >= 0) { parseInstruction(previousOffset, constantVisitor); if (constantVisitor.cst instanceof CstInteger && constantVisitor.length + previousOffset == offset) { arrayLength = constantVisitor.value; } } /* * Try to match the array initialization idiom. For example, if the * subsequent code is initializing an int array, we are expecting the * following pattern repeatedly: * dup * push index * push value * *astore * * where the index value will be incrimented sequentially from 0 up. */ int nInit = 0; int curOffset = offset+2; int lastOffset = curOffset; ArrayList<Constant> initVals = new ArrayList<Constant>(); if (arrayLength != 0) { while (true) { boolean punt = false; // First, check if the next bytecode is dup. int nextByte = bytes.getUnsignedByte(curOffset++); if (nextByte != ByteOps.DUP) break; /* * Next, check if the expected array index is pushed to * the stack. */ parseInstruction(curOffset, constantVisitor); if (constantVisitor.length == 0 || !(constantVisitor.cst instanceof CstInteger) || constantVisitor.value != nInit) break; // Next, fetch the init value and record it. curOffset += constantVisitor.length; /* * Next, find out what kind of constant is pushed onto * the stack. */ parseInstruction(curOffset, constantVisitor); if (constantVisitor.length == 0 || !(constantVisitor.cst instanceof CstLiteralBits)) break; curOffset += constantVisitor.length; initVals.add(constantVisitor.cst); nextByte = bytes.getUnsignedByte(curOffset++); // Now, check if the value is stored to the array properly. switch (value) { case ByteOps.NEWARRAY_BYTE: case ByteOps.NEWARRAY_BOOLEAN: { if (nextByte != ByteOps.BASTORE) { punt = true; } break; } case ByteOps.NEWARRAY_CHAR: { if (nextByte != ByteOps.CASTORE) { punt = true; } break; } case ByteOps.NEWARRAY_DOUBLE: { if (nextByte != ByteOps.DASTORE) { punt = true; } break; } case ByteOps.NEWARRAY_FLOAT: { if (nextByte != ByteOps.FASTORE) { punt = true; } break; } case ByteOps.NEWARRAY_SHORT: { if (nextByte != ByteOps.SASTORE) { punt = true; } break; } case ByteOps.NEWARRAY_INT: { if (nextByte != ByteOps.IASTORE) { punt = true; } break; } case ByteOps.NEWARRAY_LONG: { if (nextByte != ByteOps.LASTORE) { punt = true; } break; } default: punt = true; break; } if (punt) { break; } lastOffset = curOffset; nInit++; } } /* * For singleton arrays it is still more economical to * generate the aput. */ if (nInit < 2 || nInit != arrayLength) { visitor.visitNewarray(offset, 2, type, null); return 2; } else { visitor.visitNewarray(offset, lastOffset - offset, type, initVals); return lastOffset - offset; } } /** * Helper to deal with {@code wide}. * * @param offset the offset to the {@code wide} opcode itself * @param visitor {@code non-null;} visitor to use * @return instruction length, in bytes */ private int parseWide(int offset, Visitor visitor) { int opcode = bytes.getUnsignedByte(offset + 1); int idx = bytes.getUnsignedShort(offset + 2); switch (opcode) { case ByteOps.ILOAD: { visitor.visitLocal(ByteOps.ILOAD, offset, 4, idx, Type.INT, 0); return 4; } case ByteOps.LLOAD: { visitor.visitLocal(ByteOps.ILOAD, offset, 4, idx, Type.LONG, 0); return 4; } case ByteOps.FLOAD: { visitor.visitLocal(ByteOps.ILOAD, offset, 4, idx, Type.FLOAT, 0); return 4; } case ByteOps.DLOAD: { visitor.visitLocal(ByteOps.ILOAD, offset, 4, idx, Type.DOUBLE, 0); return 4; } case ByteOps.ALOAD: { visitor.visitLocal(ByteOps.ILOAD, offset, 4, idx, Type.OBJECT, 0); return 4; } case ByteOps.ISTORE: { visitor.visitLocal(ByteOps.ISTORE, offset, 4, idx, Type.INT, 0); return 4; } case ByteOps.LSTORE: { visitor.visitLocal(ByteOps.ISTORE, offset, 4, idx, Type.LONG, 0); return 4; } case ByteOps.FSTORE: { visitor.visitLocal(ByteOps.ISTORE, offset, 4, idx, Type.FLOAT, 0); return 4; } case ByteOps.DSTORE: { visitor.visitLocal(ByteOps.ISTORE, offset, 4, idx, Type.DOUBLE, 0); return 4; } case ByteOps.ASTORE: { visitor.visitLocal(ByteOps.ISTORE, offset, 4, idx, Type.OBJECT, 0); return 4; } case ByteOps.RET: { visitor.visitLocal(opcode, offset, 4, idx, Type.RETURN_ADDRESS, 0); return 4; } case ByteOps.IINC: { int value = bytes.getShort(offset + 4); visitor.visitLocal(opcode, offset, 6, idx, Type.INT, value); return 6; } default: { visitor.visitInvalid(ByteOps.WIDE, offset, 1); return 1; } } } /** * Instruction visitor interface. */ public interface Visitor { /** * Visits an invalid instruction. * * @param opcode the opcode * @param offset offset to the instruction * @param length length of the instruction, in bytes */ public void visitInvalid(int opcode, int offset, int length); /** * Visits an instruction which has no inline arguments * (implicit or explicit). * * @param opcode the opcode * @param offset offset to the instruction * @param length length of the instruction, in bytes * @param type {@code non-null;} type the instruction operates on */ public void visitNoArgs(int opcode, int offset, int length, Type type); /** * Visits an instruction which has a local variable index argument. * * @param opcode the opcode * @param offset offset to the instruction * @param length length of the instruction, in bytes * @param idx the local variable index * @param type {@code non-null;} the type of the accessed value * @param value additional literal integer argument, if salient (i.e., * for {@code iinc}) */ public void visitLocal(int opcode, int offset, int length, int idx, Type type, int value); /** * Visits an instruction which has a (possibly synthetic) * constant argument, and possibly also an * additional literal integer argument. In the case of * {@code multianewarray}, the argument is the count of * dimensions. In the case of {@code invokeinterface}, * the argument is the parameter count or'ed with the * should-be-zero value left-shifted by 8. In the case of entries * of type {@code int}, the {@code value} field always * holds the raw value (for convenience of clients). * * <p><b>Note:</b> In order to avoid giving it a barely-useful * visitor all its own, {@code newarray} also uses this * form, passing {@code value} as the array type code and * {@code cst} as a {@link CstType} instance * corresponding to the array type.</p> * * @param opcode the opcode * @param offset offset to the instruction * @param length length of the instruction, in bytes * @param cst {@code non-null;} the constant * @param value additional literal integer argument, if salient * (ignore if not) */ public void visitConstant(int opcode, int offset, int length, Constant cst, int value); /** * Visits an instruction which has a branch target argument. * * @param opcode the opcode * @param offset offset to the instruction * @param length length of the instruction, in bytes * @param target the absolute (not relative) branch target */ public void visitBranch(int opcode, int offset, int length, int target); /** * Visits a switch instruction. * * @param opcode the opcode * @param offset offset to the instruction * @param length length of the instruction, in bytes * @param cases {@code non-null;} list of (value, target) * pairs, plus the default target * @param padding the bytes found in the padding area (if any), * packed */ public void visitSwitch(int opcode, int offset, int length, SwitchList cases, int padding); /** * Visits a newarray instruction. * * @param offset offset to the instruction * @param length length of the instruction, in bytes * @param type {@code non-null;} the type of the array * @param initVals {@code non-null;} list of bytecode offsets * for init values */ public void visitNewarray(int offset, int length, CstType type, ArrayList<Constant> initVals); /** * Set previous bytecode offset * @param offset offset of the previous fully parsed bytecode */ public void setPreviousOffset(int offset); /** * Get previous bytecode offset * @return return the recored offset of the previous bytecode */ public int getPreviousOffset(); } /** * Base implementation of {@link Visitor}, which has empty method * bodies for all methods. */ public static class BaseVisitor implements Visitor { /** offset of the previously parsed bytecode */ private int previousOffset; BaseVisitor() { previousOffset = -1; } /** {@inheritDoc} */ public void visitInvalid(int opcode, int offset, int length) { // This space intentionally left blank. } /** {@inheritDoc} */ public void visitNoArgs(int opcode, int offset, int length, Type type) { // This space intentionally left blank. } /** {@inheritDoc} */ public void visitLocal(int opcode, int offset, int length, int idx, Type type, int value) { // This space intentionally left blank. } /** {@inheritDoc} */ public void visitConstant(int opcode, int offset, int length, Constant cst, int value) { // This space intentionally left blank. } /** {@inheritDoc} */ public void visitBranch(int opcode, int offset, int length, int target) { // This space intentionally left blank. } /** {@inheritDoc} */ public void visitSwitch(int opcode, int offset, int length, SwitchList cases, int padding) { // This space intentionally left blank. } /** {@inheritDoc} */ public void visitNewarray(int offset, int length, CstType type, ArrayList<Constant> initValues) { // This space intentionally left blank. } /** {@inheritDoc} */ public void setPreviousOffset(int offset) { previousOffset = offset; } /** {@inheritDoc} */ public int getPreviousOffset() { return previousOffset; } } /** * Implementation of {@link Visitor}, which just pays attention * to constant values. */ class ConstantParserVisitor extends BaseVisitor { Constant cst; int length; int value; /** Empty constructor */ ConstantParserVisitor() { } private void clear() { length = 0; } /** {@inheritDoc} */ @Override public void visitInvalid(int opcode, int offset, int length) { clear(); } /** {@inheritDoc} */ @Override public void visitNoArgs(int opcode, int offset, int length, Type type) { clear(); } /** {@inheritDoc} */ @Override public void visitLocal(int opcode, int offset, int length, int idx, Type type, int value) { clear(); } /** {@inheritDoc} */ @Override public void visitConstant(int opcode, int offset, int length, Constant cst, int value) { this.cst = cst; this.length = length; this.value = value; } /** {@inheritDoc} */ @Override public void visitBranch(int opcode, int offset, int length, int target) { clear(); } /** {@inheritDoc} */ @Override public void visitSwitch(int opcode, int offset, int length, SwitchList cases, int padding) { clear(); } /** {@inheritDoc} */ @Override public void visitNewarray(int offset, int length, CstType type, ArrayList<Constant> initVals) { clear(); } /** {@inheritDoc} */ @Override public void setPreviousOffset(int offset) { // Intentionally left empty } /** {@inheritDoc} */ @Override public int getPreviousOffset() { // Intentionally left empty return -1; } } }
{ "pile_set_name": "Github" }
/* ==================================================================== * Copyright (c) 2001 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). * */ #ifndef HEADER_CSWIFT_ERR_H # define HEADER_CSWIFT_ERR_H #ifdef __cplusplus extern "C" { #endif /* BEGIN ERROR CODES */ /* * The following lines are auto generated by the script mkerr.pl. Any changes * made after this point may be overwritten when the script is next run. */ static void ERR_load_CSWIFT_strings(void); static void ERR_unload_CSWIFT_strings(void); static void ERR_CSWIFT_error(int function, int reason, char *file, int line); # define CSWIFTerr(f,r) ERR_CSWIFT_error((f),(r),__FILE__,__LINE__) /* Error codes for the CSWIFT functions. */ /* Function codes. */ # define CSWIFT_F_CSWIFT_CTRL 100 # define CSWIFT_F_CSWIFT_DSA_SIGN 101 # define CSWIFT_F_CSWIFT_DSA_VERIFY 102 # define CSWIFT_F_CSWIFT_FINISH 103 # define CSWIFT_F_CSWIFT_INIT 104 # define CSWIFT_F_CSWIFT_MOD_EXP 105 # define CSWIFT_F_CSWIFT_MOD_EXP_CRT 106 # define CSWIFT_F_CSWIFT_RAND_BYTES 108 # define CSWIFT_F_CSWIFT_RSA_MOD_EXP 107 /* Reason codes. */ # define CSWIFT_R_ALREADY_LOADED 100 # define CSWIFT_R_BAD_KEY_SIZE 101 # define CSWIFT_R_BN_CTX_FULL 102 # define CSWIFT_R_BN_EXPAND_FAIL 103 # define CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED 104 # define CSWIFT_R_MISSING_KEY_COMPONENTS 105 # define CSWIFT_R_NOT_LOADED 106 # define CSWIFT_R_REQUEST_FAILED 107 # define CSWIFT_R_UNIT_FAILURE 108 #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
// Copyright 2016 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "io" ) // randomBits completely fills slice b with random data. func randomBits(b []byte) { if _, err := io.ReadFull(rander, b); err != nil { panic(err.Error()) // rand should never fail } } // xvalues returns the value of a byte as a hexadecimal digit or 255. var xvalues = [256]byte{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, } // xtob converts hex characters x1 and x2 into a byte. func xtob(x1, x2 byte) (byte, bool) { b1 := xvalues[x1] b2 := xvalues[x2] return (b1 << 4) | b2, b1 != 255 && b2 != 255 }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: ab90c5d984b4d4e9e935ae8760fd47ef
{ "pile_set_name": "Github" }
export enum KeyboardModifier { NoModifier = 0x00000000, ShiftModifier = 0x02000000, ControlModifier = 0x04000000, AltModifier = 0x08000000, MetaModifier = 0x10000000, KeypadModifier = 0x20000000, GroupSwitchModifier = 0x40000000, }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DO_NO_IMPORTS import "oaidl.idl"; import "ocidl.idl"; #endif [ object, oleautomation, uuid(93598207-3E34-49ec-97EC-EFA9A1E16335), pointer_default(unique) ] interface IWebNotification : IUnknown { /* + (id)notificationWithName:(NSString *)aName object:(id)anObject + (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)userInfo */ HRESULT notificationWithName([in] BSTR aName, [in] IUnknown* anObject, [in] IPropertyBag* userInfo); /* - (NSString *)name */ HRESULT name([out, retval] BSTR* result); /* - (id)object */ HRESULT getObject([out, retval] IUnknown** result); /* - (NSDictionary *)userInfo */ HRESULT userInfo([out, retval] IPropertyBag** result); }
{ "pile_set_name": "Github" }
@echo off git submodule update --init --recursive
{ "pile_set_name": "Github" }
////////////////////////////////////////////////////////// // GENERATED BY FLUTTIFY. DO NOT EDIT IT. ////////////////////////////////////////////////////////// #import <Foundation/Foundation.h> #import <Flutter/Flutter.h> #import <MAMapKit/MAMapKit.h> @interface MACustomCalloutViewFactory : NSObject <FlutterPlatformViewFactory> - (instancetype)initWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar; @property(nonatomic) NSObject<FlutterPluginRegistrar>* registrar; @end @interface MACustomCalloutViewPlatformView : NSObject <MATraceDelegate, MAMultiPointOverlayRendererDelegate, MAMapViewDelegate, FlutterPlatformView> - (instancetype)initWithViewId:(int64_t)viewId frame:(CGRect)frame registrar:(NSObject <FlutterPluginRegistrar> *)registrar arguments:(id _Nullable)args; @property(nonatomic) NSObject<FlutterPluginRegistrar>* registrar; @end
{ "pile_set_name": "Github" }
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package openpgp import ( "bytes" _ "crypto/sha512" "encoding/hex" "io" "io/ioutil" "strings" "testing" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" ) func readerFromHex(s string) io.Reader { data, err := hex.DecodeString(s) if err != nil { panic("readerFromHex: bad input") } return bytes.NewBuffer(data) } func TestReadKeyRing(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(testKeys1And2Hex)) if err != nil { t.Error(err) return } if len(kring) != 2 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB || uint32(kring[1].PrimaryKey.KeyId) != 0x1E35246B { t.Errorf("bad keyring: %#v", kring) } } func TestRereadKeyRing(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(testKeys1And2Hex)) if err != nil { t.Errorf("error in initial parse: %s", err) return } out := new(bytes.Buffer) err = kring[0].Serialize(out) if err != nil { t.Errorf("error in serialization: %s", err) return } kring, err = ReadKeyRing(out) if err != nil { t.Errorf("error in second parse: %s", err) return } if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB { t.Errorf("bad keyring: %#v", kring) } } func TestReadPrivateKeyRing(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) if err != nil { t.Error(err) return } if len(kring) != 2 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB || uint32(kring[1].PrimaryKey.KeyId) != 0x1E35246B || kring[0].PrimaryKey == nil { t.Errorf("bad keyring: %#v", kring) } } func TestReadDSAKey(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(dsaTestKeyHex)) if err != nil { t.Error(err) return } if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0x0CCC0360 { t.Errorf("bad parse: %#v", kring) } } func TestReadP256Key(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(p256TestKeyHex)) if err != nil { t.Error(err) return } if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0x5918513E { t.Errorf("bad parse: %#v", kring) } } func TestDSAHashTruncatation(t *testing.T) { // dsaKeyWithSHA512 was generated with GnuPG and --cert-digest-algo // SHA512 in order to require DSA hash truncation to verify correctly. _, err := ReadKeyRing(readerFromHex(dsaKeyWithSHA512)) if err != nil { t.Error(err) } } func TestGetKeyById(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) keys := kring.KeysById(0xa34d7e18c20c31bb) if len(keys) != 1 || keys[0].Entity != kring[0] { t.Errorf("bad result for 0xa34d7e18c20c31bb: %#v", keys) } keys = kring.KeysById(0xfd94408d4543314f) if len(keys) != 1 || keys[0].Entity != kring[0] { t.Errorf("bad result for 0xa34d7e18c20c31bb: %#v", keys) } } func checkSignedMessage(t *testing.T, signedHex, expected string) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) md, err := ReadMessage(readerFromHex(signedHex), kring, nil, nil) if err != nil { t.Error(err) return } if !md.IsSigned || md.SignedByKeyId != 0xa34d7e18c20c31bb || md.SignedBy == nil || md.IsEncrypted || md.IsSymmetricallyEncrypted || len(md.EncryptedToKeyIds) != 0 || md.IsSymmetricallyEncrypted { t.Errorf("bad MessageDetails: %#v", md) } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("error reading UnverifiedBody: %s", err) } if string(contents) != expected { t.Errorf("bad UnverifiedBody got:%s want:%s", string(contents), expected) } if md.SignatureError != nil || md.Signature == nil { t.Errorf("failed to validate: %s", md.SignatureError) } } func TestSignedMessage(t *testing.T) { checkSignedMessage(t, signedMessageHex, signedInput) } func TestTextSignedMessage(t *testing.T) { checkSignedMessage(t, signedTextMessageHex, signedTextInput) } // The reader should detect "compressed quines", which are compressed // packets that expand into themselves and cause an infinite recursive // parsing loop. // The packet in this test case comes from Taylor R. Campbell at // http://mumble.net/~campbell/misc/pgp-quine/ func TestCampbellQuine(t *testing.T) { md, err := ReadMessage(readerFromHex(campbellQuine), nil, nil, nil) if md != nil { t.Errorf("Reading a compressed quine should not return any data: %#v", md) } structural, ok := err.(errors.StructuralError) if !ok { t.Fatalf("Unexpected class of error: %T", err) } if !strings.Contains(string(structural), "too many layers of packets") { t.Fatalf("Unexpected error: %s", err) } } var signedEncryptedMessageTests = []struct { keyRingHex string messageHex string signedByKeyId uint64 encryptedToKeyId uint64 }{ { testKeys1And2PrivateHex, signedEncryptedMessageHex, 0xa34d7e18c20c31bb, 0x2a67d68660df41c7, }, { dsaElGamalTestKeysHex, signedEncryptedMessage2Hex, 0x33af447ccd759b09, 0xcf6a7abcd43e3673, }, } func TestSignedEncryptedMessage(t *testing.T) { for i, test := range signedEncryptedMessageTests { expected := "Signed and encrypted message\n" kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex)) prompt := func(keys []Key, symmetric bool) ([]byte, error) { if symmetric { t.Errorf("prompt: message was marked as symmetrically encrypted") return nil, errors.ErrKeyIncorrect } if len(keys) == 0 { t.Error("prompt: no keys requested") return nil, errors.ErrKeyIncorrect } err := keys[0].PrivateKey.Decrypt([]byte("passphrase")) if err != nil { t.Errorf("prompt: error decrypting key: %s", err) return nil, errors.ErrKeyIncorrect } return nil, nil } md, err := ReadMessage(readerFromHex(test.messageHex), kring, prompt, nil) if err != nil { t.Errorf("#%d: error reading message: %s", i, err) return } if !md.IsSigned || md.SignedByKeyId != test.signedByKeyId || md.SignedBy == nil || !md.IsEncrypted || md.IsSymmetricallyEncrypted || len(md.EncryptedToKeyIds) == 0 || md.EncryptedToKeyIds[0] != test.encryptedToKeyId { t.Errorf("#%d: bad MessageDetails: %#v", i, md) } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("#%d: error reading UnverifiedBody: %s", i, err) } if string(contents) != expected { t.Errorf("#%d: bad UnverifiedBody got:%s want:%s", i, string(contents), expected) } if md.SignatureError != nil || md.Signature == nil { t.Errorf("#%d: failed to validate: %s", i, md.SignatureError) } } } func TestUnspecifiedRecipient(t *testing.T) { expected := "Recipient unspecified\n" kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) md, err := ReadMessage(readerFromHex(recipientUnspecifiedHex), kring, nil, nil) if err != nil { t.Errorf("error reading message: %s", err) return } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("error reading UnverifiedBody: %s", err) } if string(contents) != expected { t.Errorf("bad UnverifiedBody got:%s want:%s", string(contents), expected) } } func TestSymmetricallyEncrypted(t *testing.T) { firstTimeCalled := true prompt := func(keys []Key, symmetric bool) ([]byte, error) { if len(keys) != 0 { t.Errorf("prompt: len(keys) = %d (want 0)", len(keys)) } if !symmetric { t.Errorf("symmetric is not set") } if firstTimeCalled { firstTimeCalled = false return []byte("wrongpassword"), nil } return []byte("password"), nil } md, err := ReadMessage(readerFromHex(symmetricallyEncryptedCompressedHex), nil, prompt, nil) if err != nil { t.Errorf("ReadMessage: %s", err) return } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("ReadAll: %s", err) } expectedCreationTime := uint32(1295992998) if md.LiteralData.Time != expectedCreationTime { t.Errorf("LiteralData.Time is %d, want %d", md.LiteralData.Time, expectedCreationTime) } const expected = "Symmetrically encrypted.\n" if string(contents) != expected { t.Errorf("contents got: %s want: %s", string(contents), expected) } } func testDetachedSignature(t *testing.T, kring KeyRing, signature io.Reader, sigInput, tag string, expectedSignerKeyId uint64) { signed := bytes.NewBufferString(sigInput) signer, err := CheckDetachedSignature(kring, signed, signature) if err != nil { t.Errorf("%s: signature error: %s", tag, err) return } if signer == nil { t.Errorf("%s: signer is nil", tag) return } if signer.PrimaryKey.KeyId != expectedSignerKeyId { t.Errorf("%s: wrong signer got:%x want:%x", tag, signer.PrimaryKey.KeyId, expectedSignerKeyId) } } func TestDetachedSignature(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) testDetachedSignature(t, kring, readerFromHex(detachedSignatureHex), signedInput, "binary", testKey1KeyId) testDetachedSignature(t, kring, readerFromHex(detachedSignatureTextHex), signedInput, "text", testKey1KeyId) testDetachedSignature(t, kring, readerFromHex(detachedSignatureV3TextHex), signedInput, "v3", testKey1KeyId) incorrectSignedInput := signedInput + "X" _, err := CheckDetachedSignature(kring, bytes.NewBufferString(incorrectSignedInput), readerFromHex(detachedSignatureHex)) if err == nil { t.Fatal("CheckDetachedSignature returned without error for bad signature") } if err == errors.ErrUnknownIssuer { t.Fatal("CheckDetachedSignature returned ErrUnknownIssuer when the signer was known, but the signature invalid") } } func TestDetachedSignatureDSA(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyHex)) testDetachedSignature(t, kring, readerFromHex(detachedSignatureDSAHex), signedInput, "binary", testKey3KeyId) } func TestMultipleSignaturePacketsDSA(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyHex)) testDetachedSignature(t, kring, readerFromHex(missingHashFunctionHex+detachedSignatureDSAHex), signedInput, "binary", testKey3KeyId) } func TestDetachedSignatureP256(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(p256TestKeyHex)) testDetachedSignature(t, kring, readerFromHex(detachedSignatureP256Hex), signedInput, "binary", testKeyP256KeyId) } func testHashFunctionError(t *testing.T, signatureHex string) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) _, err := CheckDetachedSignature(kring, nil, readerFromHex(signatureHex)) if err == nil { t.Fatal("Packet with bad hash type was correctly parsed") } unsupported, ok := err.(errors.UnsupportedError) if !ok { t.Fatalf("Unexpected class of error: %s", err) } if !strings.Contains(string(unsupported), "hash ") { t.Fatalf("Unexpected error: %s", err) } } func TestUnknownHashFunction(t *testing.T) { // unknownHashFunctionHex contains a signature packet with hash // function type 153 (which isn't a real hash function id). testHashFunctionError(t, unknownHashFunctionHex) } func TestMissingHashFunction(t *testing.T) { // missingHashFunctionHex contains a signature packet that uses // RIPEMD160, which isn't compiled in. Since that's the only signature // packet we don't find any suitable packets and end up with ErrUnknownIssuer kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) _, err := CheckDetachedSignature(kring, nil, readerFromHex(missingHashFunctionHex)) if err == nil { t.Fatal("Packet with missing hash type was correctly parsed") } if err != errors.ErrUnknownIssuer { t.Fatalf("Unexpected class of error: %s", err) } } func TestReadingArmoredPrivateKey(t *testing.T) { el, err := ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKeyBlock)) if err != nil { t.Error(err) } if len(el) != 1 { t.Errorf("got %d entities, wanted 1\n", len(el)) } } func TestReadingArmoredPublicKey(t *testing.T) { el, err := ReadArmoredKeyRing(bytes.NewBufferString(e2ePublicKey)) if err != nil { t.Error(err) } if len(el) != 1 { t.Errorf("didn't get a valid entity") } } func TestNoArmoredData(t *testing.T) { _, err := ReadArmoredKeyRing(bytes.NewBufferString("foo")) if _, ok := err.(errors.InvalidArgumentError); !ok { t.Errorf("error was not an InvalidArgumentError: %s", err) } } func testReadMessageError(t *testing.T, messageHex string) { buf, err := hex.DecodeString(messageHex) if err != nil { t.Errorf("hex.DecodeString(): %v", err) } kr, err := ReadKeyRing(new(bytes.Buffer)) if err != nil { t.Errorf("ReadKeyring(): %v", err) } _, err = ReadMessage(bytes.NewBuffer(buf), kr, func([]Key, bool) ([]byte, error) { return []byte("insecure"), nil }, nil) if err == nil { t.Errorf("ReadMessage(): Unexpected nil error") } } func TestIssue11503(t *testing.T) { testReadMessageError(t, "8c040402000aa430aa8228b9248b01fc899a91197130303030") } func TestIssue11504(t *testing.T) { testReadMessageError(t, "9303000130303030303030303030983002303030303030030000000130") } // TestSignatureV3Message tests the verification of V3 signature, generated // with a modern V4-style key. Some people have their clients set to generate // V3 signatures, so it's useful to be able to verify them. func TestSignatureV3Message(t *testing.T) { sig, err := armor.Decode(strings.NewReader(signedMessageV3)) if err != nil { t.Error(err) return } key, err := ReadArmoredKeyRing(strings.NewReader(keyV4forVerifyingSignedMessageV3)) if err != nil { t.Error(err) return } md, err := ReadMessage(sig.Body, key, nil, nil) if err != nil { t.Error(err) return } _, err = ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Error(err) return } // We'll see a sig error here after reading in the UnverifiedBody above, // if there was one to see. if err = md.SignatureError; err != nil { t.Error(err) return } if md.SignatureV3 == nil { t.Errorf("No available signature after checking signature") return } if md.Signature != nil { t.Errorf("Did not expect a signature V4 back") return } return } const testKey1KeyId = 0xA34D7E18C20C31BB const testKey3KeyId = 0x338934250CCC0360 const testKeyP256KeyId = 0xd44a2c495918513e const signedInput = "Signed message\nline 2\nline 3\n" const signedTextInput = "Signed message\r\nline 2\r\nline 3\r\n" const recipientUnspecifiedHex = "848c0300000000000000000103ff62d4d578d03cf40c3da998dfe216c074fa6ddec5e31c197c9666ba292830d91d18716a80f699f9d897389a90e6d62d0238f5f07a5248073c0f24920e4bc4a30c2d17ee4e0cae7c3d4aaa4e8dced50e3010a80ee692175fa0385f62ecca4b56ee6e9980aa3ec51b61b077096ac9e800edaf161268593eedb6cc7027ff5cb32745d250010d407a6221ae22ef18469b444f2822478c4d190b24d36371a95cb40087cdd42d9399c3d06a53c0673349bfb607927f20d1e122bde1e2bf3aa6cae6edf489629bcaa0689539ae3b718914d88ededc3b" const detachedSignatureHex = "889c04000102000605024d449cd1000a0910a34d7e18c20c31bb167603ff57718d09f28a519fdc7b5a68b6a3336da04df85e38c5cd5d5bd2092fa4629848a33d85b1729402a2aab39c3ac19f9d573f773cc62c264dc924c067a79dfd8a863ae06c7c8686120760749f5fd9b1e03a64d20a7df3446ddc8f0aeadeaeba7cbaee5c1e366d65b6a0c6cc749bcb912d2f15013f812795c2e29eb7f7b77f39ce77" const detachedSignatureTextHex = "889c04010102000605024d449d21000a0910a34d7e18c20c31bbc8c60400a24fbef7342603a41cb1165767bd18985d015fb72fe05db42db36cfb2f1d455967f1e491194fbf6cf88146222b23bf6ffbd50d17598d976a0417d3192ff9cc0034fd00f287b02e90418bbefe609484b09231e4e7a5f3562e199bf39909ab5276c4d37382fe088f6b5c3426fc1052865da8b3ab158672d58b6264b10823dc4b39" const detachedSignatureV3TextHex = "8900950305005255c25ca34d7e18c20c31bb0102bb3f04009f6589ef8a028d6e54f6eaf25432e590d31c3a41f4710897585e10c31e5e332c7f9f409af8512adceaff24d0da1474ab07aa7bce4f674610b010fccc5b579ae5eb00a127f272fb799f988ab8e4574c141da6dbfecfef7e6b2c478d9a3d2551ba741f260ee22bec762812f0053e05380bfdd55ad0f22d8cdf71b233fe51ae8a24" const detachedSignatureDSAHex = "884604001102000605024d6c4eac000a0910338934250ccc0360f18d00a087d743d6405ed7b87755476629600b8b694a39e900a0abff8126f46faf1547c1743c37b21b4ea15b8f83" const detachedSignatureP256Hex = "885e0400130a0006050256e5bb00000a0910d44a2c495918513edef001009841a4f792beb0befccb35c8838a6a87d9b936beaa86db6745ddc7b045eee0cf00fd1ac1f78306b17e965935dd3f8bae4587a76587e4af231efe19cc4011a8434817" const testKeys1And2Hex = "988d044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd0011010001b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b0020003b88d044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f0011010001889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab0020003988d044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b0020003b88d044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020003" const testKeys1And2PrivateHex = "9501d8044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd00110100010003ff4d91393b9a8e3430b14d6209df42f98dc927425b881f1209f319220841273a802a97c7bdb8b3a7740b3ab5866c4d1d308ad0d3a79bd1e883aacf1ac92dfe720285d10d08752a7efe3c609b1d00f17f2805b217be53999a7da7e493bfc3e9618fd17018991b8128aea70a05dbce30e4fbe626aa45775fa255dd9177aabf4df7cf0200c1ded12566e4bc2bb590455e5becfb2e2c9796482270a943343a7835de41080582c2be3caf5981aa838140e97afa40ad652a0b544f83eb1833b0957dce26e47b0200eacd6046741e9ce2ec5beb6fb5e6335457844fb09477f83b050a96be7da043e17f3a9523567ed40e7a521f818813a8b8a72209f1442844843ccc7eb9805442570200bdafe0438d97ac36e773c7162028d65844c4d463e2420aa2228c6e50dc2743c3d6c72d0d782a5173fe7be2169c8a9f4ef8a7cf3e37165e8c61b89c346cdc6c1799d2b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b00200009d01d8044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f00110100010003fd17a7490c22a79c59281fb7b20f5e6553ec0c1637ae382e8adaea295f50241037f8997cf42c1ce26417e015091451b15424b2c59eb8d4161b0975630408e394d3b00f88d4b4e18e2cc85e8251d4753a27c639c83f5ad4a571c4f19d7cd460b9b73c25ade730c99df09637bd173d8e3e981ac64432078263bb6dc30d3e974150dd0200d0ee05be3d4604d2146fb0457f31ba17c057560785aa804e8ca5530a7cd81d3440d0f4ba6851efcfd3954b7e68908fc0ba47f7ac37bf559c6c168b70d3a7c8cd0200da1c677c4bce06a068070f2b3733b0a714e88d62aa3f9a26c6f5216d48d5c2b5624144f3807c0df30be66b3268eeeca4df1fbded58faf49fc95dc3c35f134f8b01fd1396b6c0fc1b6c4f0eb8f5e44b8eace1e6073e20d0b8bc5385f86f1cf3f050f66af789f3ef1fc107b7f4421e19e0349c730c68f0a226981f4e889054fdb4dc149e8e889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab00200009501fe044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001fe030302e9030f3c783e14856063f16938530e148bc57a7aa3f3e4f90df9dceccdc779bc0835e1ad3d006e4a8d7b36d08b8e0de5a0d947254ecfbd22037e6572b426bcfdc517796b224b0036ff90bc574b5509bede85512f2eefb520fb4b02aa523ba739bff424a6fe81c5041f253f8d757e69a503d3563a104d0d49e9e890b9d0c26f96b55b743883b472caa7050c4acfd4a21f875bdf1258d88bd61224d303dc9df77f743137d51e6d5246b88c406780528fd9a3e15bab5452e5b93970d9dcc79f48b38651b9f15bfbcf6da452837e9cc70683d1bdca94507870f743e4ad902005812488dd342f836e72869afd00ce1850eea4cfa53ce10e3608e13d3c149394ee3cbd0e23d018fcbcb6e2ec5a1a22972d1d462ca05355d0d290dd2751e550d5efb38c6c89686344df64852bf4ff86638708f644e8ec6bd4af9b50d8541cb91891a431326ab2e332faa7ae86cfb6e0540aa63160c1e5cdd5a4add518b303fff0a20117c6bc77f7cfbaf36b04c865c6c2b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b00200009d01fe044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001fe030302e9030f3c783e148560f936097339ae381d63116efcf802ff8b1c9360767db5219cc987375702a4123fd8657d3e22700f23f95020d1b261eda5257e9a72f9a918e8ef22dd5b3323ae03bbc1923dd224db988cadc16acc04b120a9f8b7e84da9716c53e0334d7b66586ddb9014df604b41be1e960dcfcbc96f4ed150a1a0dd070b9eb14276b9b6be413a769a75b519a53d3ecc0c220e85cd91ca354d57e7344517e64b43b6e29823cbd87eae26e2b2e78e6dedfbb76e3e9f77bcb844f9a8932eb3db2c3f9e44316e6f5d60e9e2a56e46b72abe6b06dc9a31cc63f10023d1f5e12d2a3ee93b675c96f504af0001220991c88db759e231b3320dcedf814dcf723fd9857e3d72d66a0f2af26950b915abdf56c1596f46a325bf17ad4810d3535fb02a259b247ac3dbd4cc3ecf9c51b6c07cebb009c1506fba0a89321ec8683e3fd009a6e551d50243e2d5092fefb3321083a4bad91320dc624bd6b5dddf93553e3d53924c05bfebec1fb4bd47e89a1a889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020000" const dsaElGamalTestKeysHex = "9501e1044dfcb16a110400aa3e5c1a1f43dd28c2ffae8abf5cfce555ee874134d8ba0a0f7b868ce2214beddc74e5e1e21ded354a95d18acdaf69e5e342371a71fbb9093162e0c5f3427de413a7f2c157d83f5cd2f9d791256dc4f6f0e13f13c3302af27f2384075ab3021dff7a050e14854bbde0a1094174855fc02f0bae8e00a340d94a1f22b32e48485700a0cec672ac21258fb95f61de2ce1af74b2c4fa3e6703ff698edc9be22c02ae4d916e4fa223f819d46582c0516235848a77b577ea49018dcd5e9e15cff9dbb4663a1ae6dd7580fa40946d40c05f72814b0f88481207e6c0832c3bded4853ebba0a7e3bd8e8c66df33d5a537cd4acf946d1080e7a3dcea679cb2b11a72a33a2b6a9dc85f466ad2ddf4c3db6283fa645343286971e3dd700703fc0c4e290d45767f370831a90187e74e9972aae5bff488eeff7d620af0362bfb95c1a6c3413ab5d15a2e4139e5d07a54d72583914661ed6a87cce810be28a0aa8879a2dd39e52fb6fe800f4f181ac7e328f740cde3d09a05cecf9483e4cca4253e60d4429ffd679d9996a520012aad119878c941e3cf151459873bdfc2a9563472fe0303027a728f9feb3b864260a1babe83925ce794710cfd642ee4ae0e5b9d74cee49e9c67b6cd0ea5dfbb582132195a121356a1513e1bca73e5b80c58c7ccb4164453412f456c47616d616c2054657374204b65792031886204131102002205024dfcb16a021b03060b090807030206150802090a0b0416020301021e01021780000a091033af447ccd759b09fadd00a0b8fd6f5a790bad7e9f2dbb7632046dc4493588db009c087c6a9ba9f7f49fab221587a74788c00db4889ab00200009d0157044dfcb16a1004008dec3f9291205255ccff8c532318133a6840739dd68b03ba942676f9038612071447bf07d00d559c5c0875724ea16a4c774f80d8338b55fca691a0522e530e604215b467bbc9ccfd483a1da99d7bc2648b4318fdbd27766fc8bfad3fddb37c62b8ae7ccfe9577e9b8d1e77c1d417ed2c2ef02d52f4da11600d85d3229607943700030503ff506c94c87c8cab778e963b76cf63770f0a79bf48fb49d3b4e52234620fc9f7657f9f8d56c96a2b7c7826ae6b57ebb2221a3fe154b03b6637cea7e6d98e3e45d87cf8dc432f723d3d71f89c5192ac8d7290684d2c25ce55846a80c9a7823f6acd9bb29fa6cd71f20bc90eccfca20451d0c976e460e672b000df49466408d527affe0303027a728f9feb3b864260abd761730327bca2aaa4ea0525c175e92bf240682a0e83b226f97ecb2e935b62c9a133858ce31b271fa8eb41f6a1b3cd72a63025ce1a75ee4180dcc284884904181102000905024dfcb16a021b0c000a091033af447ccd759b09dd0b009e3c3e7296092c81bee5a19929462caaf2fff3ae26009e218c437a2340e7ea628149af1ec98ec091a43992b00200009501e1044dfcb1be1104009f61faa61aa43df75d128cbe53de528c4aec49ce9360c992e70c77072ad5623de0a3a6212771b66b39a30dad6781799e92608316900518ec01184a85d872365b7d2ba4bacfb5882ea3c2473d3750dc6178cc1cf82147fb58caa28b28e9f12f6d1efcb0534abed644156c91cca4ab78834268495160b2400bc422beb37d237c2300a0cac94911b6d493bda1e1fbc6feeca7cb7421d34b03fe22cec6ccb39675bb7b94a335c2b7be888fd3906a1125f33301d8aa6ec6ee6878f46f73961c8d57a3e9544d8ef2a2cbfd4d52da665b1266928cfe4cb347a58c412815f3b2d2369dec04b41ac9a71cc9547426d5ab941cccf3b18575637ccfb42df1a802df3cfe0a999f9e7109331170e3a221991bf868543960f8c816c28097e503fe319db10fb98049f3a57d7c80c420da66d56f3644371631fad3f0ff4040a19a4fedc2d07727a1b27576f75a4d28c47d8246f27071e12d7a8de62aad216ddbae6aa02efd6b8a3e2818cda48526549791ab277e447b3a36c57cefe9b592f5eab73959743fcc8e83cbefec03a329b55018b53eec196765ae40ef9e20521a603c551efe0303020950d53a146bf9c66034d00c23130cce95576a2ff78016ca471276e8227fb30b1ffbd92e61804fb0c3eff9e30b1a826ee8f3e4730b4d86273ca977b4164453412f456c47616d616c2054657374204b65792032886204131102002205024dfcb1be021b03060b090807030206150802090a0b0416020301021e01021780000a0910a86bf526325b21b22bd9009e34511620415c974750a20df5cb56b182f3b48e6600a0a9466cb1a1305a84953445f77d461593f1d42bc1b00200009d0157044dfcb1be1004009565a951da1ee87119d600c077198f1c1bceb0f7aa54552489298e41ff788fa8f0d43a69871f0f6f77ebdfb14a4260cf9fbeb65d5844b4272a1904dd95136d06c3da745dc46327dd44a0f16f60135914368c8039a34033862261806bb2c5ce1152e2840254697872c85441ccb7321431d75a747a4bfb1d2c66362b51ce76311700030503fc0ea76601c196768070b7365a200e6ddb09307f262d5f39eec467b5f5784e22abdf1aa49226f59ab37cb49969d8f5230ea65caf56015abda62604544ed526c5c522bf92bed178a078789f6c807b6d34885688024a5bed9e9f8c58d11d4b82487b44c5f470c5606806a0443b79cadb45e0f897a561a53f724e5349b9267c75ca17fe0303020950d53a146bf9c660bc5f4ce8f072465e2d2466434320c1e712272fafc20e342fe7608101580fa1a1a367e60486a7cd1246b7ef5586cf5e10b32762b710a30144f12dd17dd4884904181102000905024dfcb1be021b0c000a0910a86bf526325b21b2904c00a0b2b66b4b39ccffda1d10f3ea8d58f827e30a8b8e009f4255b2d8112a184e40cde43a34e8655ca7809370b0020000" const signedMessageHex = "a3019bc0cbccc0c4b8d8b74ee2108fe16ec6d3ca490cbe362d3f8333d3f352531472538b8b13d353b97232f352158c20943157c71c16064626063656269052062e4e01987e9b6fccff4b7df3a34c534b23e679cbec3bc0f8f6e64dfb4b55fe3f8efa9ce110ddb5cd79faf1d753c51aecfa669f7e7aa043436596cccc3359cb7dd6bbe9ecaa69e5989d9e57209571edc0b2fa7f57b9b79a64ee6e99ce1371395fee92fec2796f7b15a77c386ff668ee27f6d38f0baa6c438b561657377bf6acff3c5947befd7bf4c196252f1d6e5c524d0300" const signedTextMessageHex = "a3019bc0cbccc8c4b8d8b74ee2108fe16ec6d36a250cbece0c178233d3f352531472538b8b13d35379b97232f352158ca0b4312f57c71c1646462606365626906a062e4e019811591798ff99bf8afee860b0d8a8c2a85c3387e3bcf0bb3b17987f2bbcfab2aa526d930cbfd3d98757184df3995c9f3e7790e36e3e9779f06089d4c64e9e47dd6202cb6e9bc73c5d11bb59fbaf89d22d8dc7cf199ddf17af96e77c5f65f9bbed56f427bd8db7af37f6c9984bf9385efaf5f184f986fb3e6adb0ecfe35bbf92d16a7aa2a344fb0bc52fb7624f0200" const signedEncryptedMessageHex = "848c032a67d68660df41c70103ff5789d0de26b6a50c985a02a13131ca829c413a35d0e6fa8d6842599252162808ac7439c72151c8c6183e76923fe3299301414d0c25a2f06a2257db3839e7df0ec964773f6e4c4ac7ff3b48c444237166dd46ba8ff443a5410dc670cb486672fdbe7c9dfafb75b4fea83af3a204fe2a7dfa86bd20122b4f3d2646cbeecb8f7be8d2c03b018bd210b1d3791e1aba74b0f1034e122ab72e760492c192383cf5e20b5628bd043272d63df9b923f147eb6091cd897553204832aba48fec54aa447547bb16305a1024713b90e77fd0065f1918271947549205af3c74891af22ee0b56cd29bfec6d6e351901cd4ab3ece7c486f1e32a792d4e474aed98ee84b3f591c7dff37b64e0ecd68fd036d517e412dcadf85840ce184ad7921ad446c4ee28db80447aea1ca8d4f574db4d4e37688158ddd19e14ee2eab4873d46947d65d14a23e788d912cf9a19624ca7352469b72a83866b7c23cb5ace3deab3c7018061b0ba0f39ed2befe27163e5083cf9b8271e3e3d52cc7ad6e2a3bd81d4c3d7022f8d" const signedEncryptedMessage2Hex = "85010e03cf6a7abcd43e36731003fb057f5495b79db367e277cdbe4ab90d924ddee0c0381494112ff8c1238fb0184af35d1731573b01bc4c55ecacd2aafbe2003d36310487d1ecc9ac994f3fada7f9f7f5c3a64248ab7782906c82c6ff1303b69a84d9a9529c31ecafbcdb9ba87e05439897d87e8a2a3dec55e14df19bba7f7bd316291c002ae2efd24f83f9e3441203fc081c0c23dc3092a454ca8a082b27f631abf73aca341686982e8fbda7e0e7d863941d68f3de4a755c2964407f4b5e0477b3196b8c93d551dd23c8beef7d0f03fbb1b6066f78907faf4bf1677d8fcec72651124080e0b7feae6b476e72ab207d38d90b958759fdedfc3c6c35717c9dbfc979b3cfbbff0a76d24a5e57056bb88acbd2a901ef64bc6e4db02adc05b6250ff378de81dca18c1910ab257dff1b9771b85bb9bbe0a69f5989e6d1710a35e6dfcceb7d8fb5ccea8db3932b3d9ff3fe0d327597c68b3622aec8e3716c83a6c93f497543b459b58ba504ed6bcaa747d37d2ca746fe49ae0a6ce4a8b694234e941b5159ff8bd34b9023da2814076163b86f40eed7c9472f81b551452d5ab87004a373c0172ec87ea6ce42ccfa7dbdad66b745496c4873d8019e8c28d6b3" const symmetricallyEncryptedCompressedHex = "8c0d04030302eb4a03808145d0d260c92f714339e13de5a79881216431925bf67ee2898ea61815f07894cd0703c50d0a76ef64d482196f47a8bc729af9b80bb6" const dsaTestKeyHex = "9901a2044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" const dsaTestKeyPrivateHex = "9501bb044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4d00009f592e0619d823953577d4503061706843317e4fee083db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" const p256TestKeyHex = "98520456e5b83813082a8648ce3d030107020304a2072cd6d21321266c758cc5b83fab0510f751cb8d91897cddb7047d8d6f185546e2107111b0a95cb8ef063c33245502af7a65f004d5919d93ee74eb71a66253b424502d3235362054657374204b6579203c696e76616c6964406578616d706c652e636f6d3e8879041313080021050256e5b838021b03050b09080702061508090a0b020416020301021e01021780000a0910d44a2c495918513e54e50100dfa64f97d9b47766fc1943c6314ba3f2b2a103d71ad286dc5b1efb96a345b0c80100dbc8150b54241f559da6ef4baacea6d31902b4f4b1bdc09b34bf0502334b7754b8560456e5b83812082a8648ce3d030107020304bfe3cea9cee13486f8d518aa487fecab451f25467d2bf08e58f63e5fa525d5482133e6a79299c274b068ef0be448152ad65cf11cf764348588ca4f6a0bcf22b6030108078861041813080009050256e5b838021b0c000a0910d44a2c495918513e4a4800ff49d589fa64024ad30be363a032e3a0e0e6f5db56ba4c73db850518bf0121b8f20100fd78e065f4c70ea5be9df319ea67e493b936fc78da834a71828043d3154af56e" const p256TestKeyPrivateHex = "94a50456e5b83813082a8648ce3d030107020304a2072cd6d21321266c758cc5b83fab0510f751cb8d91897cddb7047d8d6f185546e2107111b0a95cb8ef063c33245502af7a65f004d5919d93ee74eb71a66253fe070302f0c2bfb0b6c30f87ee1599472b8636477eab23ced13b271886a4b50ed34c9d8436af5af5b8f88921f0efba6ef8c37c459bbb88bc1c6a13bbd25c4ce9b1e97679569ee77645d469bf4b43de637f5561b424502d3235362054657374204b6579203c696e76616c6964406578616d706c652e636f6d3e8879041313080021050256e5b838021b03050b09080702061508090a0b020416020301021e01021780000a0910d44a2c495918513e54e50100dfa64f97d9b47766fc1943c6314ba3f2b2a103d71ad286dc5b1efb96a345b0c80100dbc8150b54241f559da6ef4baacea6d31902b4f4b1bdc09b34bf0502334b77549ca90456e5b83812082a8648ce3d030107020304bfe3cea9cee13486f8d518aa487fecab451f25467d2bf08e58f63e5fa525d5482133e6a79299c274b068ef0be448152ad65cf11cf764348588ca4f6a0bcf22b603010807fe0703027510012471a603cfee2968dce19f732721ddf03e966fd133b4e3c7a685b788705cbc46fb026dc94724b830c9edbaecd2fb2c662f23169516cacd1fe423f0475c364ecc10abcabcfd4bbbda1a36a1bd8861041813080009050256e5b838021b0c000a0910d44a2c495918513e4a4800ff49d589fa64024ad30be363a032e3a0e0e6f5db56ba4c73db850518bf0121b8f20100fd78e065f4c70ea5be9df319ea67e493b936fc78da834a71828043d3154af56e" const armoredPrivateKeyBlock = `-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1.4.10 (GNU/Linux) lQHYBE2rFNoBBADFwqWQIW/DSqcB4yCQqnAFTJ27qS5AnB46ccAdw3u4Greeu3Bp idpoHdjULy7zSKlwR1EA873dO/k/e11Ml3dlAFUinWeejWaK2ugFP6JjiieSsrKn vWNicdCS4HTWn0X4sjl0ZiAygw6GNhqEQ3cpLeL0g8E9hnYzJKQ0LWJa0QARAQAB AAP/TB81EIo2VYNmTq0pK1ZXwUpxCrvAAIG3hwKjEzHcbQznsjNvPUihZ+NZQ6+X 0HCfPAdPkGDCLCb6NavcSW+iNnLTrdDnSI6+3BbIONqWWdRDYJhqZCkqmG6zqSfL IdkJgCw94taUg5BWP/AAeQrhzjChvpMQTVKQL5mnuZbUCeMCAN5qrYMP2S9iKdnk VANIFj7656ARKt/nf4CBzxcpHTyB8+d2CtPDKCmlJP6vL8t58Jmih+kHJMvC0dzn gr5f5+sCAOOe5gt9e0am7AvQWhdbHVfJU0TQJx+m2OiCJAqGTB1nvtBLHdJnfdC9 TnXXQ6ZXibqLyBies/xeY2sCKL5qtTMCAKnX9+9d/5yQxRyrQUHt1NYhaXZnJbHx q4ytu0eWz+5i68IYUSK69jJ1NWPM0T6SkqpB3KCAIv68VFm9PxqG1KmhSrQIVGVz dCBLZXmIuAQTAQIAIgUCTasU2gIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA CgkQO9o98PRieSoLhgQAkLEZex02Qt7vGhZzMwuN0R22w3VwyYyjBx+fM3JFETy1 ut4xcLJoJfIaF5ZS38UplgakHG0FQ+b49i8dMij0aZmDqGxrew1m4kBfjXw9B/v+ eIqpODryb6cOSwyQFH0lQkXC040pjq9YqDsO5w0WYNXYKDnzRV0p4H1pweo2VDid AdgETasU2gEEAN46UPeWRqKHvA99arOxee38fBt2CI08iiWyI8T3J6ivtFGixSqV bRcPxYO/qLpVe5l84Nb3X71GfVXlc9hyv7CD6tcowL59hg1E/DC5ydI8K8iEpUmK /UnHdIY5h8/kqgGxkY/T/hgp5fRQgW1ZoZxLajVlMRZ8W4tFtT0DeA+JABEBAAEA A/0bE1jaaZKj6ndqcw86jd+QtD1SF+Cf21CWRNeLKnUds4FRRvclzTyUMuWPkUeX TaNNsUOFqBsf6QQ2oHUBBK4VCHffHCW4ZEX2cd6umz7mpHW6XzN4DECEzOVksXtc lUC1j4UB91DC/RNQqwX1IV2QLSwssVotPMPqhOi0ZLNY7wIA3n7DWKInxYZZ4K+6 rQ+POsz6brEoRHwr8x6XlHenq1Oki855pSa1yXIARoTrSJkBtn5oI+f8AzrnN0BN oyeQAwIA/7E++3HDi5aweWrViiul9cd3rcsS0dEnksPhvS0ozCJiHsq/6GFmy7J8 QSHZPteedBnZyNp5jR+H7cIfVN3KgwH/Skq4PsuPhDq5TKK6i8Pc1WW8MA6DXTdU nLkX7RGmMwjC0DBf7KWAlPjFaONAX3a8ndnz//fy1q7u2l9AZwrj1qa1iJ8EGAEC AAkFAk2rFNoCGwwACgkQO9o98PRieSo2/QP/WTzr4ioINVsvN1akKuekmEMI3LAp BfHwatufxxP1U+3Si/6YIk7kuPB9Hs+pRqCXzbvPRrI8NHZBmc8qIGthishdCYad AHcVnXjtxrULkQFGbGvhKURLvS9WnzD/m1K2zzwxzkPTzT9/Yf06O6Mal5AdugPL VrM0m72/jnpKo04= =zNCn -----END PGP PRIVATE KEY BLOCK-----` const e2ePublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- Charset: UTF-8 xv8AAABSBAAAAAATCCqGSM49AwEHAgME1LRoXSpOxtHXDUdmuvzchyg6005qIBJ4 sfaSxX7QgH9RV2ONUhC+WiayCNADq+UMzuR/vunSr4aQffXvuGnR383/AAAAFDxk Z2lsQHlhaG9vLWluYy5jb20+wv8AAACGBBATCAA4/wAAAAWCVGvAG/8AAAACiwn/ AAAACZC2VkQCOjdvYf8AAAAFlQgJCgv/AAAAA5YBAv8AAAACngEAAE1BAP0X8veD 24IjmI5/C6ZAfVNXxgZZFhTAACFX75jUA3oD6AEAzoSwKf1aqH6oq62qhCN/pekX +WAsVMBhNwzLpqtCRjLO/wAAAFYEAAAAABIIKoZIzj0DAQcCAwT50ain7vXiIRv8 B1DO3x3cE/aattZ5sHNixJzRCXi2vQIA5QmOxZ6b5jjUekNbdHG3SZi1a2Ak5mfX fRxC/5VGAwEIB8L/AAAAZQQYEwgAGP8AAAAFglRrwBz/AAAACZC2VkQCOjdvYQAA FJAA9isX3xtGyMLYwp2F3nXm7QEdY5bq5VUcD/RJlj792VwA/1wH0pCzVLl4Q9F9 ex7En5r7rHR5xwX82Msc+Rq9dSyO =7MrZ -----END PGP PUBLIC KEY BLOCK-----` const dsaKeyWithSHA512 = `9901a2044f04b07f110400db244efecc7316553ee08d179972aab87bb1214de7692593fcf5b6feb1c80fba268722dd464748539b85b81d574cd2d7ad0ca2444de4d849b8756bad7768c486c83a824f9bba4af773d11742bdfb4ac3b89ef8cc9452d4aad31a37e4b630d33927bff68e879284a1672659b8b298222fc68f370f3e24dccacc4a862442b9438b00a0ea444a24088dc23e26df7daf8f43cba3bffc4fe703fe3d6cd7fdca199d54ed8ae501c30e3ec7871ea9cdd4cf63cfe6fc82281d70a5b8bb493f922cd99fba5f088935596af087c8d818d5ec4d0b9afa7f070b3d7c1dd32a84fca08d8280b4890c8da1dde334de8e3cad8450eed2a4a4fcc2db7b8e5528b869a74a7f0189e11ef097ef1253582348de072bb07a9fa8ab838e993cef0ee203ff49298723e2d1f549b00559f886cd417a41692ce58d0ac1307dc71d85a8af21b0cf6eaa14baf2922d3a70389bedf17cc514ba0febbd107675a372fe84b90162a9e88b14d4b1c6be855b96b33fb198c46f058568817780435b6936167ebb3724b680f32bf27382ada2e37a879b3d9de2abe0c3f399350afd1ad438883f4791e2e3b4184453412068617368207472756e636174696f6e207465737488620413110a002205024f04b07f021b03060b090807030206150802090a0b0416020301021e01021780000a0910ef20e0cefca131581318009e2bf3bf047a44d75a9bacd00161ee04d435522397009a03a60d51bd8a568c6c021c8d7cf1be8d990d6417b0020003` const unknownHashFunctionHex = `8a00000040040001990006050253863c24000a09103b4fe6acc0b21f32ffff01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101` const missingHashFunctionHex = `8a00000040040001030006050253863c24000a09103b4fe6acc0b21f32ffff0101010101010101010101010101010101010101010101010101010101010101010101010101` const campbellQuine = `a0b001000300fcffa0b001000d00f2ff000300fcffa0b001000d00f2ff8270a01c00000500faff8270a01c00000500faff000500faff001400ebff8270a01c00000500faff000500faff001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400000000ffff000000ffff000b00f4ff428821c400000000ffff000000ffff000b00f4ff0233214c40000100feff000233214c40000100feff0000` const keyV4forVerifyingSignedMessageV3 = `-----BEGIN PGP PUBLIC KEY BLOCK----- Comment: GPGTools - https://gpgtools.org mI0EVfxoFQEEAMBIqmbDfYygcvP6Phr1wr1XI41IF7Qixqybs/foBF8qqblD9gIY BKpXjnBOtbkcVOJ0nljd3/sQIfH4E0vQwK5/4YRQSI59eKOqd6Fx+fWQOLG+uu6z tewpeCj9LLHvibx/Sc7VWRnrznia6ftrXxJ/wHMezSab3tnGC0YPVdGNABEBAAG0 JEdvY3J5cHRvIFRlc3QgS2V5IDx0aGVtYXhAZ21haWwuY29tPoi5BBMBCgAjBQJV /GgVAhsDBwsJCAcDAgEGFQgCCQoLBBYCAwECHgECF4AACgkQeXnQmhdGW9PFVAP+ K7TU0qX5ArvIONIxh/WAweyOk884c5cE8f+3NOPOOCRGyVy0FId5A7MmD5GOQh4H JseOZVEVCqlmngEvtHZb3U1VYtVGE5WZ+6rQhGsMcWP5qaT4soYwMBlSYxgYwQcx YhN9qOr292f9j2Y//TTIJmZT4Oa+lMxhWdqTfX+qMgG4jQRV/GgVAQQArhFSiij1 b+hT3dnapbEU+23Z1yTu1DfF6zsxQ4XQWEV3eR8v+8mEDDNcz8oyyF56k6UQ3rXi UMTIwRDg4V6SbZmaFbZYCOwp/EmXJ3rfhm7z7yzXj2OFN22luuqbyVhuL7LRdB0M pxgmjXb4tTvfgKd26x34S+QqUJ7W6uprY4sAEQEAAYifBBgBCgAJBQJV/GgVAhsM AAoJEHl50JoXRlvT7y8D/02ckx4OMkKBZo7viyrBw0MLG92i+DC2bs35PooHR6zz 786mitjOp5z2QWNLBvxC70S0qVfCIz8jKupO1J6rq6Z8CcbLF3qjm6h1omUBf8Nd EfXKD2/2HV6zMKVknnKzIEzauh+eCKS2CeJUSSSryap/QLVAjRnckaES/OsEWhNB =RZia -----END PGP PUBLIC KEY BLOCK----- ` const signedMessageV3 = `-----BEGIN PGP MESSAGE----- Comment: GPGTools - https://gpgtools.org owGbwMvMwMVYWXlhlrhb9GXG03JJDKF/MtxDMjKLFYAoUaEktbhEITe1uDgxPVWP q5NhKjMrWAVcC9evD8z/bF/uWNjqtk/X3y5/38XGRQHm/57rrDRYuGnTw597Xqka uM3137/hH3Os+Jf2dc0fXOITKwJvXJvecPVs0ta+Vg7ZO1MLn8w58Xx+6L58mbka DGHyU9yTueZE8D+QF/Tz28Y78dqtF56R1VPn9Xw4uJqrWYdd7b3vIZ1V6R4Nh05d iT57d/OhWwA= =hG7R -----END PGP MESSAGE----- `
{ "pile_set_name": "Github" }
#!/usr/bin/env python # # euclid graphics maths module # # Copyright (c) 2006 Alex Holkner # [email protected] # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 2.1 of the License, or (at your # option) any later version. # # This library is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA '''euclid graphics maths module Documentation and tests are included in the file "euclid.txt", or online at http://code.google.com/p/pyeuclid ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' __revision__ = '$Revision$' import math import operator import types try: import itertools.imap as map # XXX Python3 has changed map behavior except ImportError: pass # Some magic here. If _use_slots is True, the classes will derive from # object and will define a __slots__ class variable. If _use_slots is # False, classes will be old-style and will not define __slots__. # # _use_slots = True: Memory efficient, probably faster in future versions # of Python, "better". # _use_slots = False: Ordinary classes, much faster than slots in current # versions of Python (2.4 and 2.5). _use_slots = True # If True, allows components of Vector2 and Vector3 to be set via swizzling; # e.g. v.xyz = (1, 2, 3). This is much, much slower than the more verbose # v.x = 1; v.y = 2; v.z = 3, and slows down ordinary element setting as # well. Recommended setting is False. _enable_swizzle_set = False # Requires class to derive from object. if _enable_swizzle_set: _use_slots = True # Implement _use_slots magic. class _EuclidMetaclass(type): def __new__(cls, name, bases, dct): if '__slots__' in dct: dct['__getstate__'] = cls._create_getstate(dct['__slots__']) dct['__setstate__'] = cls._create_setstate(dct['__slots__']) if _use_slots: return type.__new__(cls, name, bases + (object,), dct) else: if '__slots__' in dct: del dct['__slots__'] return types.ClassType.__new__(type, name, bases, dct) @classmethod def _create_getstate(cls, slots): def __getstate__(self): d = {} for slot in slots: d[slot] = getattr(self, slot) return d return __getstate__ @classmethod def _create_setstate(cls, slots): def __setstate__(self, state): for name, value in list(state.items()): setattr(self, name, value) return __setstate__ __metaclass__ = _EuclidMetaclass class Vector2: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y def __copy__(self): return self.__class__(self.x, self.y) copy = __copy__ def __repr__(self): return 'Vector2(%.2f, %.2f)' % (self.x, self.y) def __eq__(self, other): if isinstance(other, Vector2): return self.x == other.x and \ self.y == other.y else: assert hasattr(other, '__len__') and len(other) == 2 return self.x == other[0] and \ self.y == other[1] def __ne__(self, other): return not self.__eq__(other) def __bool__(self): return self.x != 0 or self.y != 0 def __len__(self): return 2 def __getitem__(self, key): return (self.x, self.y)[key] def __setitem__(self, key, value): l = [self.x, self.y] l[key] = value self.x, self.y = l def __iter__(self): return iter((self.x, self.y)) def __getattr__(self, name): try: return tuple([(self.x, self.y)['xy'.index(c)] \ for c in name]) except ValueError: raise AttributeError(name) if _enable_swizzle_set: # This has detrimental performance on ordinary setattr as well # if enabled def __setattr__(self, name, value): if len(name) == 1: object.__setattr__(self, name, value) else: try: l = [self.x, self.y] for c, v in map(None, name, value): l['xy'.index(c)] = v self.x, self.y = l except ValueError: raise AttributeError(name) def __add__(self, other): if isinstance(other, Vector2): return Vector2(self.x + other.x, self.y + other.y) else: assert hasattr(other, '__len__') and len(other) == 2 return Vector2(self.x + other[0], self.y + other[1]) __radd__ = __add__ def __iadd__(self, other): if isinstance(other, Vector2): self.x += other.x self.y += other.y else: self.x += other[0] self.y += other[1] return self def __sub__(self, other): if isinstance(other, Vector2): return Vector2(self.x - other.x, self.y - other.y) else: assert hasattr(other, '__len__') and len(other) == 2 return Vector2(self.x - other[0], self.y - other[1]) def __rsub__(self, other): if isinstance(other, Vector2): return Vector2(other.x - self.x, other.y - self.y) else: assert hasattr(other, '__len__') and len(other) == 2 return Vector2(other.x - self[0], other.y - self[1]) def __mul__(self, other): assert type(other) in (int, int, float) return Vector2(self.x * other, self.y * other) __rmul__ = __mul__ def __imul__(self, other): assert type(other) in (int, int, float) self.x *= other self.y *= other return self def __div__(self, other): assert type(other) in (int, int, float) return Vector2(operator.div(self.x, other), operator.div(self.y, other)) def __rdiv__(self, other): assert type(other) in (int, int, float) return Vector2(operator.div(other, self.x), operator.div(other, self.y)) def __floordiv__(self, other): assert type(other) in (int, int, float) return Vector2(operator.floordiv(self.x, other), operator.floordiv(self.y, other)) def __rfloordiv__(self, other): assert type(other) in (int, int, float) return Vector2(operator.floordiv(other, self.x), operator.floordiv(other, self.y)) def __truediv__(self, other): assert type(other) in (int, int, float) return Vector2(operator.truediv(self.x, other), operator.truediv(self.y, other)) def __rtruediv__(self, other): assert type(other) in (int, int, float) return Vector2(operator.truediv(other, self.x), operator.truediv(other, self.y)) def __neg__(self): return Vector2(-self.x, -self.y) __pos__ = __copy__ def __abs__(self): return math.sqrt(self.x ** 2 + \ self.y ** 2) magnitude = __abs__ def magnitude_squared(self): return self.x ** 2 + \ self.y ** 2 def normalize(self): d = self.magnitude() if d: self.x /= d self.y /= d return self def normalized(self): d = self.magnitude() if d: return Vector2(self.x / d, self.y / d) return self.copy() def dot(self, other): assert isinstance(other, Vector2) return self.x * other.x + \ self.y * other.y def cross(self): return Vector2(self.y, -self.x) def reflect(self, normal): # assume normal is normalized assert isinstance(normal, Vector2) d = 2 * (self.x * normal.x + self.y * normal.y) return Vector2(self.x - d * normal.x, self.y - d * normal.y) class Vector3: __slots__ = ['x', 'y', 'z'] def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __copy__(self): return self.__class__(self.x, self.y, self.z) copy = __copy__ def __repr__(self): return 'Vector3(%.2f, %.2f, %.2f)' % (self.x, self.y, self.z) def __eq__(self, other): if isinstance(other, Vector3): return self.x == other.x and \ self.y == other.y and \ self.z == other.z else: assert hasattr(other, '__len__') and len(other) == 3 return self.x == other[0] and \ self.y == other[1] and \ self.z == other[2] def __ne__(self, other): return not self.__eq__(other) def __bool__(self): return self.x != 0 or self.y != 0 or self.z != 0 def __len__(self): return 3 def __getitem__(self, key): return (self.x, self.y, self.z)[key] def __setitem__(self, key, value): l = [self.x, self.y, self.z] l[key] = value self.x, self.y, self.z = l def __iter__(self): return iter((self.x, self.y, self.z)) def __getattr__(self, name): try: return tuple([(self.x, self.y, self.z)['xyz'.index(c)] \ for c in name]) except ValueError: raise AttributeError(name) if _enable_swizzle_set: # This has detrimental performance on ordinary setattr as well # if enabled def __setattr__(self, name, value): if len(name) == 1: object.__setattr__(self, name, value) else: try: l = [self.x, self.y, self.z] for c, v in map(None, name, value): l['xyz'.index(c)] = v self.x, self.y, self.z = l except ValueError: raise AttributeError(name) def __add__(self, other): if isinstance(other, Vector3): # Vector + Vector -> Vector # Vector + Point -> Point # Point + Point -> Vector if self.__class__ is other.__class__: _class = Vector3 else: _class = Point3 return _class(self.x + other.x, self.y + other.y, self.z + other.z) else: assert hasattr(other, '__len__') and len(other) == 3 return Vector3(self.x + other[0], self.y + other[1], self.z + other[2]) __radd__ = __add__ def __iadd__(self, other): if isinstance(other, Vector3): self.x += other.x self.y += other.y self.z += other.z else: self.x += other[0] self.y += other[1] self.z += other[2] return self def __sub__(self, other): if isinstance(other, Vector3): # Vector - Vector -> Vector # Vector - Point -> Point # Point - Point -> Vector if self.__class__ is other.__class__: _class = Vector3 else: _class = Point3 return Vector3(self.x - other.x, self.y - other.y, self.z - other.z) else: assert hasattr(other, '__len__') and len(other) == 3 return Vector3(self.x - other[0], self.y - other[1], self.z - other[2]) def __rsub__(self, other): if isinstance(other, Vector3): return Vector3(other.x - self.x, other.y - self.y, other.z - self.z) else: assert hasattr(other, '__len__') and len(other) == 3 return Vector3(other.x - self[0], other.y - self[1], other.z - self[2]) def __mul__(self, other): if isinstance(other, Vector3): # TODO component-wise mul/div in-place and on Vector2; docs. if self.__class__ is Point3 or other.__class__ is Point3: _class = Point3 else: _class = Vector3 return _class(self.x * other.x, self.y * other.y, self.z * other.z) else: assert type(other) in (int, int, float) return Vector3(self.x * other, self.y * other, self.z * other) __rmul__ = __mul__ def __imul__(self, other): assert type(other) in (int, int, float) self.x *= other self.y *= other self.z *= other return self def __div__(self, other): assert type(other) in (int, int, float) return Vector3(operator.div(self.x, other), operator.div(self.y, other), operator.div(self.z, other)) def __rdiv__(self, other): assert type(other) in (int, int, float) return Vector3(operator.div(other, self.x), operator.div(other, self.y), operator.div(other, self.z)) def __floordiv__(self, other): assert type(other) in (int, int, float) return Vector3(operator.floordiv(self.x, other), operator.floordiv(self.y, other), operator.floordiv(self.z, other)) def __rfloordiv__(self, other): assert type(other) in (int, int, float) return Vector3(operator.floordiv(other, self.x), operator.floordiv(other, self.y), operator.floordiv(other, self.z)) def __truediv__(self, other): assert type(other) in (int, int, float) return Vector3(operator.truediv(self.x, other), operator.truediv(self.y, other), operator.truediv(self.z, other)) def __rtruediv__(self, other): assert type(other) in (int, int, float) return Vector3(operator.truediv(other, self.x), operator.truediv(other, self.y), operator.truediv(other, self.z)) def __neg__(self): return Vector3(-self.x, -self.y, -self.z) __pos__ = __copy__ def __abs__(self): return math.sqrt(self.x ** 2 + \ self.y ** 2 + \ self.z ** 2) magnitude = __abs__ def magnitude_squared(self): return self.x ** 2 + \ self.y ** 2 + \ self.z ** 2 def normalize(self): d = self.magnitude() if d: self.x /= d self.y /= d self.z /= d return self def normalized(self): d = self.magnitude() if d: return Vector3(self.x / d, self.y / d, self.z / d) return self.copy() def dot(self, other): assert isinstance(other, Vector3) return self.x * other.x + \ self.y * other.y + \ self.z * other.z def cross(self, other): assert isinstance(other, Vector3) return Vector3(self.y * other.z - self.z * other.y, -self.x * other.z + self.z * other.x, self.x * other.y - self.y * other.x) def reflect(self, normal): # assume normal is normalized assert isinstance(normal, Vector3) d = 2 * (self.x * normal.x + self.y * normal.y + self.z * normal.z) return Vector3(self.x - d * normal.x, self.y - d * normal.y, self.z - d * normal.z) class AffineVector3(Vector3): w = 1 def __repr__(self): return 'Vector3(%.2f, %.2f, %.2f, 1.00)' % (self.x, self.y, self.z) def __len__(self): return 4 def __getitem__(self, key): return (self.x, self.y, self.z, 1)[key] def __iter__(self): return iter((self.x, self.y, self.z, 1)) # a b c # e f g # i j k class Matrix3: __slots__ = list('abcefgijk') def __init__(self): self.identity() def __copy__(self): M = Matrix3() M.a = self.a M.b = self.b M.c = self.c M.e = self.e M.f = self.f M.g = self.g M.i = self.i M.j = self.j M.k = self.k return M copy = __copy__ def __repr__(self): return ('Matrix3([% 8.2f % 8.2f % 8.2f\n' \ ' % 8.2f % 8.2f % 8.2f\n' \ ' % 8.2f % 8.2f % 8.2f])') \ % (self.a, self.b, self.c, self.e, self.f, self.g, self.i, self.j, self.k) def __getitem__(self, key): return [self.a, self.e, self.i, self.b, self.f, self.j, self.c, self.g, self.k][key] def __setitem__(self, key, value): L = self[:] L[key] = value (self.a, self.e, self.i, self.b, self.f, self.j, self.c, self.g, self.k) = L def __mul__(self, other): if isinstance(other, Matrix3): # Caching repeatedly accessed attributes in local variables # apparently increases performance by 20%. Attrib: Will McGugan. Aa = self.a Ab = self.b Ac = self.c Ae = self.e Af = self.f Ag = self.g Ai = self.i Aj = self.j Ak = self.k Ba = other.a Bb = other.b Bc = other.c Be = other.e Bf = other.f Bg = other.g Bi = other.i Bj = other.j Bk = other.k C = Matrix3() C.a = Aa * Ba + Ab * Be + Ac * Bi C.b = Aa * Bb + Ab * Bf + Ac * Bj C.c = Aa * Bc + Ab * Bg + Ac * Bk C.e = Ae * Ba + Af * Be + Ag * Bi C.f = Ae * Bb + Af * Bf + Ag * Bj C.g = Ae * Bc + Af * Bg + Ag * Bk C.i = Ai * Ba + Aj * Be + Ak * Bi C.j = Ai * Bb + Aj * Bf + Ak * Bj C.k = Ai * Bc + Aj * Bg + Ak * Bk return C elif isinstance(other, Point2): A = self B = other P = Point2(0, 0) P.x = A.a * B.x + A.b * B.y + A.c P.y = A.e * B.x + A.f * B.y + A.g return P elif isinstance(other, Vector2): A = self B = other V = Vector2(0, 0) V.x = A.a * B.x + A.b * B.y V.y = A.e * B.x + A.f * B.y return V else: other = other.copy() other._apply_transform(self) return other def __imul__(self, other): assert isinstance(other, Matrix3) # Cache attributes in local vars (see Matrix3.__mul__). Aa = self.a Ab = self.b Ac = self.c Ae = self.e Af = self.f Ag = self.g Ai = self.i Aj = self.j Ak = self.k Ba = other.a Bb = other.b Bc = other.c Be = other.e Bf = other.f Bg = other.g Bi = other.i Bj = other.j Bk = other.k self.a = Aa * Ba + Ab * Be + Ac * Bi self.b = Aa * Bb + Ab * Bf + Ac * Bj self.c = Aa * Bc + Ab * Bg + Ac * Bk self.e = Ae * Ba + Af * Be + Ag * Bi self.f = Ae * Bb + Af * Bf + Ag * Bj self.g = Ae * Bc + Af * Bg + Ag * Bk self.i = Ai * Ba + Aj * Be + Ak * Bi self.j = Ai * Bb + Aj * Bf + Ak * Bj self.k = Ai * Bc + Aj * Bg + Ak * Bk return self def identity(self): self.a = self.f = self.k = 1. self.b = self.c = self.e = self.g = self.i = self.j = 0 return self def scale(self, x, y): self *= Matrix3.new_scale(x, y) return self def translate(self, x, y): self *= Matrix3.new_translate(x, y) return self def rotate(self, angle): self *= Matrix3.new_rotate(angle) return self # Static constructors def new_identity(cls): self = cls() return self new_identity = classmethod(new_identity) def new_scale(cls, x, y): self = cls() self.a = x self.f = y return self new_scale = classmethod(new_scale) def new_translate(cls, x, y): self = cls() self.c = x self.g = y return self new_translate = classmethod(new_translate) def new_rotate(cls, angle): self = cls() s = math.sin(angle) c = math.cos(angle) self.a = self.f = c self.b = -s self.e = s return self new_rotate = classmethod(new_rotate) # a b c d # e f g h # i j k l # m n o p class Matrix4: __slots__ = list('abcdefghijklmnop') def __init__(self): self.identity() def __copy__(self): M = Matrix4() M.a = self.a M.b = self.b M.c = self.c M.d = self.d M.e = self.e M.f = self.f M.g = self.g M.h = self.h M.i = self.i M.j = self.j M.k = self.k M.l = self.l M.m = self.m M.n = self.n M.o = self.o M.p = self.p return M copy = __copy__ def __repr__(self): return ('Matrix4([% 8.2f % 8.2f % 8.2f % 8.2f\n' \ ' % 8.2f % 8.2f % 8.2f % 8.2f\n' \ ' % 8.2f % 8.2f % 8.2f % 8.2f\n' \ ' % 8.2f % 8.2f % 8.2f % 8.2f])') \ % (self.a, self.b, self.c, self.d, self.e, self.f, self.g, self.h, self.i, self.j, self.k, self.l, self.m, self.n, self.o, self.p) def __getitem__(self, key): return [self.a, self.e, self.i, self.m, self.b, self.f, self.j, self.n, self.c, self.g, self.k, self.o, self.d, self.h, self.l, self.p][key] def __setitem__(self, key, value): assert not isinstance(key, slice) or \ key.stop - key.start == len(value), 'key length != value length' L = self[:] L[key] = value (self.a, self.e, self.i, self.m, self.b, self.f, self.j, self.n, self.c, self.g, self.k, self.o, self.d, self.h, self.l, self.p) = L def __mul__(self, other): if isinstance(other, Matrix4): # Cache attributes in local vars (see Matrix3.__mul__). Aa = self.a Ab = self.b Ac = self.c Ad = self.d Ae = self.e Af = self.f Ag = self.g Ah = self.h Ai = self.i Aj = self.j Ak = self.k Al = self.l Am = self.m An = self.n Ao = self.o Ap = self.p Ba = other.a Bb = other.b Bc = other.c Bd = other.d Be = other.e Bf = other.f Bg = other.g Bh = other.h Bi = other.i Bj = other.j Bk = other.k Bl = other.l Bm = other.m Bn = other.n Bo = other.o Bp = other.p C = Matrix4() C.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm C.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn C.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo C.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp C.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm C.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn C.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo C.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp C.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm C.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn C.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo C.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp C.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm C.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn C.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo C.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp return C elif isinstance(other, Point3): A = self B = other P = Point3(0, 0, 0) P.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d P.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h P.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l return P elif isinstance(other, AffineVector3): A = self B = other V = AffineVector3(0, 0, 0) V.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d * B.w V.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h * B.w V.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l * B.w return V elif isinstance(other, Vector3): A = self B = other V = Vector3(0, 0, 0) V.x = A.a * B.x + A.b * B.y + A.c * B.z V.y = A.e * B.x + A.f * B.y + A.g * B.z V.z = A.i * B.x + A.j * B.y + A.k * B.z return V else: other = other.copy() other._apply_transform(self) return other def __imul__(self, other): assert isinstance(other, Matrix4) # Cache attributes in local vars (see Matrix3.__mul__). Aa = self.a Ab = self.b Ac = self.c Ad = self.d Ae = self.e Af = self.f Ag = self.g Ah = self.h Ai = self.i Aj = self.j Ak = self.k Al = self.l Am = self.m An = self.n Ao = self.o Ap = self.p Ba = other.a Bb = other.b Bc = other.c Bd = other.d Be = other.e Bf = other.f Bg = other.g Bh = other.h Bi = other.i Bj = other.j Bk = other.k Bl = other.l Bm = other.m Bn = other.n Bo = other.o Bp = other.p self.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm self.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn self.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo self.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp self.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm self.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn self.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo self.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp self.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm self.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn self.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo self.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp self.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm self.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn self.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo self.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp return self def identity(self): self.a = self.f = self.k = self.p = 1. self.b = self.c = self.d = self.e = self.g = self.h = \ self.i = self.j = self.l = self.m = self.n = self.o = 0 return self def scale(self, x, y, z): self *= Matrix4.new_scale(x, y, z) return self def translate(self, x, y, z): self *= Matrix4.new_translate(x, y, z) return self def rotatex(self, angle): self *= Matrix4.new_rotatex(angle) return self def rotatey(self, angle): self *= Matrix4.new_rotatey(angle) return self def rotatez(self, angle): self *= Matrix4.new_rotatez(angle) return self def rotate_axis(self, angle, axis): self *= Matrix4.new_rotate_axis(angle, axis) return self def rotate_euler(self, heading, attitude, bank): self *= Matrix4.new_rotate_euler(heading, attitude, bank) return self # Static constructors def new_identity(cls): self = cls() return self new_identity = classmethod(new_identity) def new_scale(cls, x, y, z): self = cls() self.a = x self.f = y self.k = z return self new_scale = classmethod(new_scale) def new_translate(cls, x, y, z): self = cls() self.d = x self.h = y self.l = z return self new_translate = classmethod(new_translate) def new_rotatex(cls, angle): self = cls() s = math.sin(angle) c = math.cos(angle) self.f = self.k = c self.g = -s self.j = s return self new_rotatex = classmethod(new_rotatex) def new_rotatey(cls, angle): self = cls() s = math.sin(angle) c = math.cos(angle) self.a = self.k = c self.c = s self.i = -s return self new_rotatey = classmethod(new_rotatey) def new_rotatez(cls, angle): self = cls() s = math.sin(angle) c = math.cos(angle) self.a = self.f = c self.b = -s self.e = s return self new_rotatez = classmethod(new_rotatez) def new_rotate_axis(cls, angle, axis): assert (isinstance(axis, Vector3)) vector = axis.normalized() x = vector.x y = vector.y z = vector.z self = cls() s = math.sin(angle) c = math.cos(angle) c1 = 1. - c # from the glRotate man page self.a = x * x * c1 + c self.b = x * y * c1 - z * s self.c = x * z * c1 + y * s self.e = y * x * c1 + z * s self.f = y * y * c1 + c self.g = y * z * c1 - x * s self.i = x * z * c1 - y * s self.j = y * z * c1 + x * s self.k = z * z * c1 + c return self new_rotate_axis = classmethod(new_rotate_axis) def new_rotate_euler(cls, heading, attitude, bank): # from http://www.euclideanspace.com/ ch = math.cos(heading) sh = math.sin(heading) ca = math.cos(attitude) sa = math.sin(attitude) cb = math.cos(bank) sb = math.sin(bank) self = cls() self.a = ch * ca self.b = sh * sb - ch * sa * cb self.c = ch * sa * sb + sh * cb self.e = sa self.f = ca * cb self.g = -ca * sb self.i = -sh * ca self.j = sh * sa * cb + ch * sb self.k = -sh * sa * sb + ch * cb return self new_rotate_euler = classmethod(new_rotate_euler) def new_perspective(cls, fov_y, aspect, near, far): # from the gluPerspective man page f = 1 / math.tan(fov_y / 2) self = cls() assert near != 0.0 and near != far self.a = f / aspect self.f = f self.k = (far + near) / (near - far) self.l = 2 * far * near / (near - far) self.o = -1 self.p = 0 return self new_perspective = classmethod(new_perspective) class Quaternion: # All methods and naming conventions based off # http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions # w is the real part, (x, y, z) are the imaginary parts __slots__ = ['w', 'x', 'y', 'z'] def __init__(self): self.identity() def __copy__(self): Q = Quaternion() Q.w = self.w Q.x = self.x Q.y = self.y Q.z = self.z copy = __copy__ def __repr__(self): return 'Quaternion(real=%.2f, imag=<%.2f, %.2f, %.2f>)' % \ (self.w, self.x, self.y, self.z) def __mul__(self, other): if isinstance(other, Quaternion): Ax = self.x Ay = self.y Az = self.z Aw = self.w Bx = other.x By = other.y Bz = other.z Bw = other.w Q = Quaternion() Q.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx Q.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By Q.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz Q.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw return Q elif isinstance(other, Vector3): w = self.w x = self.x y = self.y z = self.z Vx = other.x Vy = other.y Vz = other.z return other.__class__( \ w * w * Vx + 2 * y * w * Vz - 2 * z * w * Vy + \ x * x * Vx + 2 * y * x * Vy + 2 * z * x * Vz - \ z * z * Vx - y * y * Vx, 2 * x * y * Vx + y * y * Vy + 2 * z * y * Vz + \ 2 * w * z * Vx - z * z * Vy + w * w * Vy - \ 2 * x * w * Vz - x * x * Vy, 2 * x * z * Vx + 2 * y * z * Vy + \ z * z * Vz - 2 * w * y * Vx - y * y * Vz + \ 2 * w * x * Vy - x * x * Vz + w * w * Vz) else: other = other.copy() other._apply_transform(self) return other def __imul__(self, other): assert isinstance(other, Quaternion) Ax = self.x Ay = self.y Az = self.z Aw = self.w Bx = other.x By = other.y Bz = other.z Bw = other.w self.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx self.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By self.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz self.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw return self def __abs__(self): return math.sqrt(self.w ** 2 + \ self.x ** 2 + \ self.y ** 2 + \ self.z ** 2) magnitude = __abs__ def magnitude_squared(self): return self.w ** 2 + \ self.x ** 2 + \ self.y ** 2 + \ self.z ** 2 def identity(self): self.w = 1 self.x = 0 self.y = 0 self.z = 0 return self def rotate_axis(self, angle, axis): self *= Quaternion.new_rotate_axis(angle, axis) return self def rotate_euler(self, heading, attitude, bank): self *= Quaternion.new_rotate_euler(heading, attitude, bank) return self def conjugated(self): Q = Quaternion() Q.w = self.w Q.x = -self.x Q.y = -self.y Q.z = -self.z return Q def normalize(self): d = self.magnitude() if d != 0: self.w /= d self.x /= d self.y /= d self.z /= d return self def normalized(self): d = self.magnitude() if d != 0: Q = Quaternion() Q.w /= d Q.x /= d Q.y /= d Q.z /= d return Q else: return self.copy() def get_angle_axis(self): if self.w > 1: self = self.normalized() angle = 2 * math.acos(self.w) s = math.sqrt(1 - self.w ** 2) if s < 0.001: return angle, Vector3(1, 0, 0) else: return angle, Vector3(self.x / s, self.y / s, self.z / s) def get_euler(self): t = self.x * self.y + self.z * self.w if t > 0.4999: heading = 2 * math.atan2(self.x, self.w) attitude = math.pi / 2 bank = 0 elif t < -0.4999: heading = -2 * math.atan2(self.x, self.w) attitude = -math.pi / 2 bank = 0 else: sqx = self.x ** 2 sqy = self.y ** 2 sqz = self.z ** 2 heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z, 1 - 2 * sqy - 2 * sqz) attitude = math.asin(2 * t) bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z, 1 - 2 * sqx - 2 * sqz) return heading, attitude, bank def get_matrix(self): xx = self.x ** 2 xy = self.x * self.y xz = self.x * self.z xw = self.x * self.w yy = self.y ** 2 yz = self.y * self.z yw = self.y * self.w zz = self.z ** 2 zw = self.z * self.w M = Matrix4() M.a = 1 - 2 * (yy + zz) M.b = 2 * (xy - zw) M.c = 2 * (xz + yw) M.e = 2 * (xy + zw) M.f = 1 - 2 * (xx + zz) M.g = 2 * (yz - xw) M.i = 2 * (xz - yw) M.j = 2 * (yz + xw) M.k = 1 - 2 * (xx + yy) return M # Static constructors def new_identity(cls): return cls() new_identity = classmethod(new_identity) def new_rotate_axis(cls, angle, axis): assert (isinstance(axis, Vector3)) axis = axis.normalized() s = math.sin(angle / 2) Q = cls() Q.w = math.cos(angle / 2) Q.x = axis.x * s Q.y = axis.y * s Q.z = axis.z * s return Q new_rotate_axis = classmethod(new_rotate_axis) def new_rotate_euler(cls, heading, attitude, bank): Q = cls() c1 = math.cos(heading / 2) s1 = math.sin(heading / 2) c2 = math.cos(attitude / 2) s2 = math.sin(attitude / 2) c3 = math.cos(bank / 2) s3 = math.sin(bank / 2) Q.w = c1 * c2 * c3 - s1 * s2 * s3 Q.x = s1 * s2 * c3 + c1 * c2 * s3 Q.y = s1 * c2 * c3 + c1 * s2 * s3 Q.z = c1 * s2 * c3 - s1 * c2 * s3 return Q new_rotate_euler = classmethod(new_rotate_euler) def new_interpolate(cls, q1, q2, t): assert isinstance(q1, Quaternion) and isinstance(q2, Quaternion) Q = cls() costheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z theta = math.acos(costheta) if abs(theta) < 0.01: Q.w = q2.w Q.x = q2.x Q.y = q2.y Q.z = q2.z return Q sintheta = math.sqrt(1.0 - costheta * costheta) if abs(sintheta) < 0.01: Q.w = (q1.w + q2.w) * 0.5 Q.x = (q1.x + q2.x) * 0.5 Q.y = (q1.y + q2.y) * 0.5 Q.z = (q1.z + q2.z) * 0.5 return Q ratio1 = math.sin((1 - t) * theta) / sintheta ratio2 = math.sin(t * theta) / sintheta Q.w = q1.w * ratio1 + q2.w * ratio2 Q.x = q1.x * ratio1 + q2.x * ratio2 Q.y = q1.y * ratio1 + q2.y * ratio2 Q.z = q1.z * ratio1 + q2.z * ratio2 return Q new_interpolate = classmethod(new_interpolate) # Geometry # Much maths thanks to Paul Bourke, http://astronomy.swin.edu.au/~pbourke # --------------------------------------------------------------------------- class Geometry: def _connect_unimplemented(self, other): raise AttributeError('Cannot connect %s to %s' % \ (self.__class__, other.__class__)) def _intersect_unimplemented(self, other): raise AttributeError('Cannot intersect %s and %s' % \ (self.__class__, other.__class__)) _intersect_point2 = _intersect_unimplemented _intersect_line2 = _intersect_unimplemented _intersect_circle = _intersect_unimplemented _connect_point2 = _connect_unimplemented _connect_line2 = _connect_unimplemented _connect_circle = _connect_unimplemented _intersect_point3 = _intersect_unimplemented _intersect_line3 = _intersect_unimplemented _intersect_sphere = _intersect_unimplemented _intersect_plane = _intersect_unimplemented _connect_point3 = _connect_unimplemented _connect_line3 = _connect_unimplemented _connect_sphere = _connect_unimplemented _connect_plane = _connect_unimplemented def intersect(self, other): raise NotImplementedError def connect(self, other): raise NotImplementedError def distance(self, other): c = self.connect(other) if c: return c.length return 0.0 def _intersect_point2_circle(P, C): return abs(P - C.c) <= C.r def _intersect_line2_line2(A, B): d = B.v.y * A.v.x - B.v.x * A.v.y if d == 0: return None dy = A.p.y - B.p.y dx = A.p.x - B.p.x ua = (B.v.x * dy - B.v.y * dx) / d if not A._u_in(ua): return None ub = (A.v.x * dy - A.v.y * dx) / d if not B._u_in(ub): return None return Point2(A.p.x + ua * A.v.x, A.p.y + ua * A.v.y) def _intersect_line2_circle(L, C): a = L.v.magnitude_squared() b = 2 * (L.v.x * (L.p.x - C.c.x) + \ L.v.y * (L.p.y - C.c.y)) c = C.c.magnitude_squared() + \ L.p.magnitude_squared() - \ 2 * C.c.dot(L.p) - \ C.r ** 2 det = b ** 2 - 4 * a * c if det < 0: return None sq = math.sqrt(det) u1 = (-b + sq) / (2 * a) u2 = (-b - sq) / (2 * a) if not L._u_in(u1): u1 = max(min(u1, 1.0), 0.0) if not L._u_in(u2): u2 = max(min(u2, 1.0), 0.0) return LineSegment2(Point2(L.p.x + u1 * L.v.x, L.p.y + u1 * L.v.y), Point2(L.p.x + u2 * L.v.x, L.p.y + u2 * L.v.y)) def _connect_point2_line2(P, L): d = L.v.magnitude_squared() assert d != 0 u = ((P.x - L.p.x) * L.v.x + \ (P.y - L.p.y) * L.v.y) / d if not L._u_in(u): u = max(min(u, 1.0), 0.0) return LineSegment2(P, Point2(L.p.x + u * L.v.x, L.p.y + u * L.v.y)) def _connect_point2_circle(P, C): v = P - C.c v.normalize() v *= C.r return LineSegment2(P, Point2(C.c.x + v.x, C.c.y + v.y)) def _connect_line2_line2(A, B): d = B.v.y * A.v.x - B.v.x * A.v.y if d == 0: # Parallel, connect an endpoint with a line if isinstance(B, Ray2) or isinstance(B, LineSegment2): p1, p2 = _connect_point2_line2(B.p, A) return p2, p1 # No endpoint (or endpoint is on A), possibly choose arbitrary point # on line. return _connect_point2_line2(A.p, B) dy = A.p.y - B.p.y dx = A.p.x - B.p.x ua = (B.v.x * dy - B.v.y * dx) / d if not A._u_in(ua): ua = max(min(ua, 1.0), 0.0) ub = (A.v.x * dy - A.v.y * dx) / d if not B._u_in(ub): ub = max(min(ub, 1.0), 0.0) return LineSegment2(Point2(A.p.x + ua * A.v.x, A.p.y + ua * A.v.y), Point2(B.p.x + ub * B.v.x, B.p.y + ub * B.v.y)) def _connect_circle_line2(C, L): d = L.v.magnitude_squared() assert d != 0 u = ((C.c.x - L.p.x) * L.v.x + (C.c.y - L.p.y) * L.v.y) / d if not L._u_in(u): u = max(min(u, 1.0), 0.0) point = Point2(L.p.x + u * L.v.x, L.p.y + u * L.v.y) v = (point - C.c) v.normalize() v *= C.r return LineSegment2(Point2(C.c.x + v.x, C.c.y + v.y), point) def _connect_circle_circle(A, B): v = B.c - A.c v.normalize() return LineSegment2(Point2(A.c.x + v.x * A.r, A.c.y + v.y * A.r), Point2(B.c.x - v.x * B.r, B.c.y - v.y * B.r)) class Point2(Vector2, Geometry): def __repr__(self): return 'Point2(%.2f, %.2f)' % (self.x, self.y) def intersect(self, other): return other._intersect_point2(self) def _intersect_circle(self, other): return _intersect_point2_circle(self, other) def connect(self, other): return other._connect_point2(self) def _connect_point2(self, other): return LineSegment2(other, self) def _connect_line2(self, other): c = _connect_point2_line2(self, other) if c: return c._swap() def _connect_circle(self, other): c = _connect_point2_circle(self, other) if c: return c._swap() class Line2(Geometry): __slots__ = ['p', 'v'] def __init__(self, *args): if len(args) == 3: assert isinstance(args[0], Point2) and \ isinstance(args[1], Vector2) and \ type(args[2]) == float self.p = args[0].copy() self.v = args[1] * args[2] / abs(args[1]) elif len(args) == 2: if isinstance(args[0], Point2) and isinstance(args[1], Point2): self.p = args[0].copy() self.v = args[1] - args[0] elif isinstance(args[0], Point2) and isinstance(args[1], Vector2): self.p = args[0].copy() self.v = args[1].copy() else: raise AttributeError('%r' % (args,)) elif len(args) == 1: if isinstance(args[0], Line2): self.p = args[0].p.copy() self.v = args[0].v.copy() else: raise AttributeError('%r' % (args,)) else: raise AttributeError('%r' % (args,)) if not self.v: raise AttributeError('Line has zero-length vector') def __copy__(self): return self.__class__(self.p, self.v) copy = __copy__ def __repr__(self): return 'Line2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \ (self.p.x, self.p.y, self.v.x, self.v.y) p1 = property(lambda self: self.p) p2 = property(lambda self: Point2(self.p.x + self.v.x, self.p.y + self.v.y)) def _apply_transform(self, t): self.p = t * self.p self.v = t * self.v def _u_in(self, u): return True def intersect(self, other): return other._intersect_line2(self) def _intersect_line2(self, other): return _intersect_line2_line2(self, other) def _intersect_circle(self, other): return _intersect_line2_circle(self, other) def connect(self, other): return other._connect_line2(self) def _connect_point2(self, other): return _connect_point2_line2(other, self) def _connect_line2(self, other): return _connect_line2_line2(other, self) def _connect_circle(self, other): return _connect_circle_line2(other, self) class Ray2(Line2): def __repr__(self): return 'Ray2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \ (self.p.x, self.p.y, self.v.x, self.v.y) def _u_in(self, u): return u >= 0.0 class LineSegment2(Line2): def __repr__(self): return 'LineSegment2(<%.2f, %.2f> to <%.2f, %.2f>)' % \ (self.p.x, self.p.y, self.p.x + self.v.x, self.p.y + self.v.y) def _u_in(self, u): return u >= 0.0 and u <= 1.0 def __abs__(self): return abs(self.v) def magnitude_squared(self): return self.v.magnitude_squared() def _swap(self): # used by connect methods to switch order of points self.p = self.p2 self.v *= -1 return self length = property(lambda self: abs(self.v)) class Circle(Geometry): __slots__ = ['c', 'r'] def __init__(self, center, radius): assert isinstance(center, Vector2) and type(radius) == float self.c = center.copy() self.r = radius def __copy__(self): return self.__class__(self.c, self.r) copy = __copy__ def __repr__(self): return 'Circle(<%.2f, %.2f>, radius=%.2f)' % \ (self.c.x, self.c.y, self.r) def _apply_transform(self, t): self.c = t * self.c def intersect(self, other): return other._intersect_circle(self) def _intersect_point2(self, other): return _intersect_point2_circle(other, self) def _intersect_line2(self, other): return _intersect_line2_circle(other, self) def connect(self, other): return other._connect_circle(self) def _connect_point2(self, other): return _connect_point2_circle(other, self) def _connect_line2(self, other): c = _connect_circle_line2(self, other) if c: return c._swap() def _connect_circle(self, other): return _connect_circle_circle(other, self) # 3D Geometry # ------------------------------------------------------------------------- def _connect_point3_line3(P, L): d = L.v.magnitude_squared() assert d != 0 u = ((P.x - L.p.x) * L.v.x + \ (P.y - L.p.y) * L.v.y + \ (P.z - L.p.z) * L.v.z) / d if not L._u_in(u): u = max(min(u, 1.0), 0.0) return LineSegment3(P, Point3(L.p.x + u * L.v.x, L.p.y + u * L.v.y, L.p.z + u * L.v.z)) def _connect_point3_sphere(P, S): v = P - S.c v.normalize() v *= S.r return LineSegment3(P, Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z)) def _connect_point3_plane(p, plane): n = plane.n.normalized() d = p.dot(plane.n) - plane.k return LineSegment3(p, Point3(p.x - n.x * d, p.y - n.y * d, p.z - n.z * d)) def _connect_line3_line3(A, B): assert A.v and B.v p13 = A.p - B.p d1343 = p13.dot(B.v) d4321 = B.v.dot(A.v) d1321 = p13.dot(A.v) d4343 = B.v.magnitude_squared() denom = A.v.magnitude_squared() * d4343 - d4321 ** 2 if denom == 0: # Parallel, connect an endpoint with a line if isinstance(B, Ray3) or isinstance(B, LineSegment3): return _connect_point3_line3(B.p, A)._swap() # No endpoint (or endpoint is on A), possibly choose arbitrary # point on line. return _connect_point3_line3(A.p, B) ua = (d1343 * d4321 - d1321 * d4343) / denom if not A._u_in(ua): ua = max(min(ua, 1.0), 0.0) ub = (d1343 + d4321 * ua) / d4343 if not B._u_in(ub): ub = max(min(ub, 1.0), 0.0) return LineSegment3(Point3(A.p.x + ua * A.v.x, A.p.y + ua * A.v.y, A.p.z + ua * A.v.z), Point3(B.p.x + ub * B.v.x, B.p.y + ub * B.v.y, B.p.z + ub * B.v.z)) def _connect_line3_plane(L, P): d = P.n.dot(L.v) if not d: # Parallel, choose an endpoint return _connect_point3_plane(L.p, P) u = (P.k - P.n.dot(L.p)) / d if not L._u_in(u): # intersects out of range, choose nearest endpoint u = max(min(u, 1.0), 0.0) return _connect_point3_plane(Point3(L.p.x + u * L.v.x, L.p.y + u * L.v.y, L.p.z + u * L.v.z), P) # Intersection return None def _connect_sphere_line3(S, L): d = L.v.magnitude_squared() assert d != 0 u = ((S.c.x - L.p.x) * L.v.x + \ (S.c.y - L.p.y) * L.v.y + \ (S.c.z - L.p.z) * L.v.z) / d if not L._u_in(u): u = max(min(u, 1.0), 0.0) point = Point3(L.p.x + u * L.v.x, L.p.y + u * L.v.y, L.p.z + u * L.v.z) v = (point - S.c) v.normalize() v *= S.r return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z), point) def _connect_sphere_sphere(A, B): v = B.c - A.c v.normalize() return LineSegment3(Point3(A.c.x + v.x * A.r, A.c.y + v.y * A.r, A.c.x + v.z * A.r), Point3(B.c.x + v.x * B.r, B.c.y + v.y * B.r, B.c.x + v.z * B.r)) def _connect_sphere_plane(S, P): c = _connect_point3_plane(S.c, P) if not c: return None p2 = c.p2 v = p2 - S.c v.normalize() v *= S.r return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z), p2) def _connect_plane_plane(A, B): if A.n.cross(B.n): # Planes intersect return None else: # Planes are parallel, connect to arbitrary point return _connect_point3_plane(A._get_point(), B) def _intersect_point3_sphere(P, S): return abs(P - S.c) <= S.r def _intersect_line3_sphere(L, S): a = L.v.magnitude_squared() b = 2 * (L.v.x * (L.p.x - S.c.x) + \ L.v.y * (L.p.y - S.c.y) + \ L.v.z * (L.p.z - S.c.z)) c = S.c.magnitude_squared() + \ L.p.magnitude_squared() - \ 2 * S.c.dot(L.p) - \ S.r ** 2 det = b ** 2 - 4 * a * c if det < 0: return None sq = math.sqrt(det) u1 = (-b + sq) / (2 * a) u2 = (-b - sq) / (2 * a) if not L._u_in(u1): u1 = max(min(u1, 1.0), 0.0) if not L._u_in(u2): u2 = max(min(u2, 1.0), 0.0) return LineSegment3(Point3(L.p.x + u1 * L.v.x, L.p.y + u1 * L.v.y, L.p.z + u1 * L.v.z), Point3(L.p.x + u2 * L.v.x, L.p.y + u2 * L.v.y, L.p.z + u2 * L.v.z)) def _intersect_line3_plane(L, P): d = P.n.dot(L.v) if not d: # Parallel return None u = (P.k - P.n.dot(L.p)) / d if not L._u_in(u): return None return Point3(L.p.x + u * L.v.x, L.p.y + u * L.v.y, L.p.z + u * L.v.z) def _intersect_plane_plane(A, B): n1_m = A.n.magnitude_squared() n2_m = B.n.magnitude_squared() n1d2 = A.n.dot(B.n) det = n1_m * n2_m - n1d2 ** 2 if det == 0: # Parallel return None c1 = (A.k * n2_m - B.k * n1d2) / det c2 = (B.k * n1_m - A.k * n1d2) / det return Line3(Point3(c1 * A.n.x + c2 * B.n.x, c1 * A.n.y + c2 * B.n.y, c1 * A.n.z + c2 * B.n.z), A.n.cross(B.n)) class Point3(Vector3, Geometry): def __repr__(self): return 'Point3(%.2f, %.2f, %.2f)' % (self.x, self.y, self.z) def intersect(self, other): return other._intersect_point3(self) def _intersect_sphere(self, other): return _intersect_point3_sphere(self, other) def connect(self, other): return other._connect_point3(self) def _connect_point3(self, other): if self != other: return LineSegment3(other, self) return None def _connect_line3(self, other): c = _connect_point3_line3(self, other) if c: return c._swap() def _connect_sphere(self, other): c = _connect_point3_sphere(self, other) if c: return c._swap() def _connect_plane(self, other): c = _connect_point3_plane(self, other) if c: return c._swap() class Line3: __slots__ = ['p', 'v'] def __init__(self, *args): if len(args) == 3: assert isinstance(args[0], Point3) and \ isinstance(args[1], Vector3) and \ type(args[2]) == float self.p = args[0].copy() self.v = args[1] * args[2] / abs(args[1]) elif len(args) == 2: if isinstance(args[0], Point3) and isinstance(args[1], Point3): self.p = args[0].copy() self.v = args[1] - args[0] elif isinstance(args[0], Point3) and isinstance(args[1], Vector3): self.p = args[0].copy() self.v = args[1].copy() else: raise AttributeError('%r' % (args,)) elif len(args) == 1: if isinstance(args[0], Line3): self.p = args[0].p.copy() self.v = args[0].v.copy() else: raise AttributeError('%r' % (args,)) else: raise AttributeError('%r' % (args,)) # XXX This is annoying. # if not self.v: # raise AttributeError, 'Line has zero-length vector' def __copy__(self): return self.__class__(self.p, self.v) copy = __copy__ def __repr__(self): return 'Line3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \ (self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z) p1 = property(lambda self: self.p) p2 = property(lambda self: Point3(self.p.x + self.v.x, self.p.y + self.v.y, self.p.z + self.v.z)) def _apply_transform(self, t): self.p = t * self.p self.v = t * self.v def _u_in(self, u): return True def intersect(self, other): return other._intersect_line3(self) def _intersect_sphere(self, other): return _intersect_line3_sphere(self, other) def _intersect_plane(self, other): return _intersect_line3_plane(self, other) def connect(self, other): return other._connect_line3(self) def _connect_point3(self, other): return _connect_point3_line3(other, self) def _connect_line3(self, other): return _connect_line3_line3(other, self) def _connect_sphere(self, other): return _connect_sphere_line3(other, self) def _connect_plane(self, other): c = _connect_line3_plane(self, other) if c: return c class Ray3(Line3): def __repr__(self): return 'Ray3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \ (self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z) def _u_in(self, u): return u >= 0.0 class LineSegment3(Line3): def __repr__(self): return 'LineSegment3(<%.2f, %.2f, %.2f> to <%.2f, %.2f, %.2f>)' % \ (self.p.x, self.p.y, self.p.z, self.p.x + self.v.x, self.p.y + self.v.y, self.p.z + self.v.z) def _u_in(self, u): return u >= 0.0 and u <= 1.0 def __abs__(self): return abs(self.v) def magnitude_squared(self): return self.v.magnitude_squared() def _swap(self): # used by connect methods to switch order of points self.p = self.p2 self.v *= -1 return self length = property(lambda self: abs(self.v)) class Sphere: __slots__ = ['c', 'r'] def __init__(self, center, radius): assert isinstance(center, Vector3) and type(radius) == float self.c = center.copy() self.r = radius def __copy__(self): return self.__class__(self.c, self.r) copy = __copy__ def __repr__(self): return 'Sphere(<%.2f, %.2f, %.2f>, radius=%.2f)' % \ (self.c.x, self.c.y, self.c.z, self.r) def _apply_transform(self, t): self.c = t * self.c def intersect(self, other): return other._intersect_sphere(self) def _intersect_point3(self, other): return _intersect_point3_sphere(other, self) def _intersect_line3(self, other): return _intersect_line3_sphere(other, self) def connect(self, other): return other._connect_sphere(self) def _connect_point3(self, other): return _connect_point3_sphere(other, self) def _connect_line3(self, other): c = _connect_sphere_line3(self, other) if c: return c._swap() def _connect_sphere(self, other): return _connect_sphere_sphere(other, self) def _connect_plane(self, other): c = _connect_sphere_plane(self, other) if c: return c class Plane: # n.p = k, where n is normal, p is point on plane, k is constant scalar __slots__ = ['n', 'k'] def __init__(self, *args): if len(args) == 3: assert isinstance(args[0], Point3) and \ isinstance(args[1], Point3) and \ isinstance(args[2], Point3) self.n = (args[1] - args[0]).cross(args[2] - args[0]) self.n.normalize() self.k = self.n.dot(args[0]) elif len(args) == 2: if isinstance(args[0], Point3) and isinstance(args[1], Vector3): self.n = args[1].normalized() self.k = self.n.dot(args[0]) elif isinstance(args[0], Vector3) and type(args[1]) == float: self.n = args[0].normalized() self.k = args[1] else: raise AttributeError('%r' % (args,)) else: raise AttributeError('%r' % (args,)) if not self.n: raise AttributeError('Points on plane are colinear') def __copy__(self): return self.__class__(self.n, self.k) copy = __copy__ def __repr__(self): return 'Plane(<%.2f, %.2f, %.2f>.p = %.2f)' % \ (self.n.x, self.n.y, self.n.z, self.k) def _get_point(self): # Return an arbitrary point on the plane if self.n.z: return Point3(0., 0., self.k / self.n.z) elif self.n.y: return Point3(0., self.k / self.n.y, 0.) else: return Point3(self.k / self.n.x, 0., 0.) def _apply_transform(self, t): p = t * self._get_point() self.n = t * self.n self.k = self.n.dot(p) def intersect(self, other): return other._intersect_plane(self) def _intersect_line3(self, other): return _intersect_line3_plane(other, self) def _intersect_plane(self, other): return _intersect_plane_plane(self, other) def connect(self, other): return other._connect_plane(self) def _connect_point3(self, other): return _connect_point3_plane(other, self) def _connect_line3(self, other): return _connect_line3_plane(other, self) def _connect_sphere(self, other): return _connect_sphere_plane(other, self) def _connect_plane(self, other): return _connect_plane_plane(other, self)
{ "pile_set_name": "Github" }
/* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. */ /****************************************************************************** * * You may not use the identified files except in compliance with the Apache * License, Version 2.0 (the "License.") * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * * NAME * insert2.js * * DESCRIPTION * Show the auto commit behavior. * * By default, node-oracledb does not commit on execute. * The driver also has commit() and rollback() methods to explicitly control transactions. * * Note: regardless of the auto commit mode, any open transaction * will be rolled back when a connection is closed. * * This example uses Node 8's async/await syntax. * *****************************************************************************/ const oracledb = require('oracledb'); const dbConfig = require('./dbconfig.js'); async function run() { let connection1, connection2; try { connection1 = await oracledb.getConnection(dbConfig); connection2 = await oracledb.getConnection(dbConfig); let result; // // Create a table // const stmts = [ `DROP TABLE no_tab2`, `CREATE TABLE no_tab2 (id NUMBER, name VARCHAR2(20))` ]; for (const s of stmts) { try { await connection1.execute(s); } catch(e) { if (e.errorNum != 942) console.error(e); } } // // Show several examples of inserting // // Insert with autoCommit enabled result = await connection1.execute( `INSERT INTO no_tab2 VALUES (:id, :nm)`, [1, 'Chris'], // Bind values { autoCommit: true} // Override the default, non-autocommit behavior ); console.log("Rows inserted: " + result.rowsAffected); // 1 // Insert without committing result = await connection1.execute( `INSERT INTO no_tab2 VALUES (:id, :nm)`, [2, 'Alison'], // Bind values // { autoCommit: true}, // Since this isn't set, operations using a second connection won't see this row ); console.log("Rows inserted: " + result.rowsAffected); // 1 // A query on the second connection will only show 'Chris' because // inserting 'Alison' is not commited by default. Uncomment the // autoCommit option above and you will see both rows result = await connection2.execute( `SELECT * FROM no_tab2` ); console.log(result.rows); } catch (err) { console.error(err); } finally { try { if (connection1) await connection1.close(); if (connection2) await connection2.close(); } catch (err) { console.error(err); } } } run();
{ "pile_set_name": "Github" }
/** * @file AutoLabelImageProvider.h * * Provider for LabelImage based on simulated data. * Randomly places other robots of the field to random location. * This can be logged in the simulator and used for further processing. * * @author Jan Blumenkamp */ #pragma once #include "Tools/Module/Module.h" #include "Representations/Modeling/LabelImage.h" #include "Representations/Infrastructure/CameraInfo.h" #include "Representations/Perception/ImagePreprocessing/CameraMatrix.h" #include "Representations/Infrastructure/GroundTruthWorldState.h" MODULE(AutoLabelImageProvider, {, REQUIRES(GroundTruthWorldState), REQUIRES(CameraInfo), REQUIRES(CameraMatrix), PROVIDES(LabelImage), DEFINES_PARAMETERS( {, (float)(573.f) robotHeight, ///< Bounding box robot height (float)(220.f) robotHandsHeight, ///< Bounding box height of the hands (float)(200.f) robotWidthBody, ///< Bounding box robot width for the body (float)(150.f) robotWidthHead, ///< Bounding box robot width for the head (float)(350.f) robotWidthHands, ///< Bounding box robot width for the hands (float)(140.f) robotDepthFeet, ///< Bounding box robot depth of feet (float)(110.f) robotDepthHead, ///< Bounding box robot depth of head (float)(60.f) robotCenter, ///< Bounding Box center of depth (offset) of bounding box (int)(20) marginBoundingBox, ///< Only if an object is at least this many pixels inside a frame a bounding box will be created (int)(370) minDistanceToRobots, ///< Minimum distance the teleported robot should keep to other robots (float)(4800.f) robotPlacementAreaLength, ///< Range (-n to n) along the field length where robots will be placed randomly (float)(3000.f) robotPlacementAreaWidth, ///< Range (-n to n) along the field width where robots will be placed randomly (int)(8) minRobotPlacementId, ///< Minimum ID of robot whose position will be manipulated randomly (int)(12) maxRobotPlacementId, ///< Maximum ID of robot whose position will be manipulated randomly }), }); class AutoLabelImageProvider : public AutoLabelImageProviderBase { private: void update(LabelImage& labelImage) override; /** * Populates the given vector with points representing a 3D bounding box for a robot * @param box vector to be populated. Will be overwritten. */ std::vector<Vector3f> getPlainRobot3DBoundingBox(); /** * Translates and rotates the given vector of 3D points (representing a polygone) by the given pose in place * @param box vector of 3D points to be moved (will not be changed) * @param moved * @param pose */ void move3DBoundingBox(std::vector<Vector3f>& box, const Pose2f& pose); /** * Draws a 3D bounding box in robot relative coordinates to the field * @param relative3DBoundingBox 3D bounding box in robot relative coordinates */ void drawRelative3DBoundingBox(const std::vector<Vector3f>& relative3DBoundingBox); /** * Projects a robot relative 3D Bounding box to an 2D annotation bounding box * @param box vector of 3D bounding box points to be projected * @param annotation annotation object to write the bounding box data in. * Only manipulates correct, upperLeft, lowerRight * @return true on success, otherwise false */ bool projectRelative3DBoundingBoxToAnnotation(const std::vector<Vector3f>& box, LabelImage::Annotation& annotation); /** * Teleport the robot to the given absolute field coordinate * @param robotId robot with the given id to move * @param pos absolute field coordinate */ void teleportRobot(int robotId, const Pose2f& pose); /** * Calculates the distance to the closest robot from the given position * @param position distance to consider * @return distance to the closes robot in mm. infinity if there are no robots. */ float calculateDistanceToClosestRobot(const Vector2f& position); };
{ "pile_set_name": "Github" }
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO. // You may push code into the target .java compilation unit if you wish to edit any member(s). package org.springframework.roo.petclinic.web; import io.springlets.data.domain.GlobalSearch; import io.springlets.data.web.datatables.ConvertedDatatablesData; import io.springlets.data.web.datatables.Datatables; import io.springlets.data.web.datatables.DatatablesColumns; import io.springlets.data.web.datatables.DatatablesPageable; import io.springlets.web.NotFoundException; import io.springlets.web.mvc.util.ControllerMethodLinkBuilderFactory; import io.springlets.web.mvc.util.MethodLinkBuilderFactory; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.joda.time.format.DateTimeFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.roo.petclinic.domain.Vet; import org.springframework.roo.petclinic.domain.Visit; import org.springframework.roo.petclinic.service.api.VetService; import org.springframework.roo.petclinic.service.api.VisitService; import org.springframework.roo.petclinic.web.VetsCollectionThymeleafController; import org.springframework.roo.petclinic.web.VetsCollectionThymeleafLinkFactory; import org.springframework.roo.petclinic.web.VetsItemVisitsThymeleafController; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; privileged aspect VetsItemVisitsThymeleafController_Roo_Thymeleaf { declare @type: VetsItemVisitsThymeleafController: @Controller; declare @type: VetsItemVisitsThymeleafController: @RequestMapping(value = "/vets/{vet}/visits", name = "VetsItemVisitsThymeleafController", produces = MediaType.TEXT_HTML_VALUE); /** * TODO Auto-generated attribute documentation * */ private MessageSource VetsItemVisitsThymeleafController.messageSource; /** * TODO Auto-generated attribute documentation * */ private MethodLinkBuilderFactory<VetsCollectionThymeleafController> VetsItemVisitsThymeleafController.collectionLink; /** * TODO Auto-generated attribute documentation * */ private ConversionService VetsItemVisitsThymeleafController.conversionService; /** * TODO Auto-generated constructor documentation * * @param vetService * @param visitService * @param conversionService * @param messageSource * @param linkBuilder */ @Autowired public VetsItemVisitsThymeleafController.new(VetService vetService, VisitService visitService, ConversionService conversionService, MessageSource messageSource, ControllerMethodLinkBuilderFactory linkBuilder) { setVetService(vetService); setVisitService(visitService); setConversionService(conversionService); setMessageSource(messageSource); setCollectionLink(linkBuilder.of(VetsCollectionThymeleafController.class)); } /** * TODO Auto-generated method documentation * * @return MessageSource */ public MessageSource VetsItemVisitsThymeleafController.getMessageSource() { return messageSource; } /** * TODO Auto-generated method documentation * * @param messageSource */ public void VetsItemVisitsThymeleafController.setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } /** * TODO Auto-generated method documentation * * @return MethodLinkBuilderFactory */ public MethodLinkBuilderFactory<VetsCollectionThymeleafController> VetsItemVisitsThymeleafController.getCollectionLink() { return collectionLink; } /** * TODO Auto-generated method documentation * * @param collectionLink */ public void VetsItemVisitsThymeleafController.setCollectionLink(MethodLinkBuilderFactory<VetsCollectionThymeleafController> collectionLink) { this.collectionLink = collectionLink; } /** * TODO Auto-generated method documentation * * @return ConversionService */ public ConversionService VetsItemVisitsThymeleafController.getConversionService() { return conversionService; } /** * TODO Auto-generated method documentation * * @param conversionService */ public void VetsItemVisitsThymeleafController.setConversionService(ConversionService conversionService) { this.conversionService = conversionService; } /** * TODO Auto-generated method documentation * * @param id * @param locale * @param method * @return Vet */ @ModelAttribute public Vet VetsItemVisitsThymeleafController.getVet(@PathVariable("vet") Long id, Locale locale, HttpMethod method) { Vet vet = null; if (HttpMethod.PUT.equals(method)) { vet = vetService.findOneForUpdate(id); } else { vet = vetService.findOne(id); } if (vet == null) { String message = messageSource.getMessage("error_NotFound", new Object[] {"Vet", id}, "The record couldn't be found", locale); throw new NotFoundException(message); } return vet; } /** * TODO Auto-generated method documentation * * @param model */ public void VetsItemVisitsThymeleafController.populateFormats(Model model) { model.addAttribute("application_locale", LocaleContextHolder.getLocale().getLanguage()); model.addAttribute("visitDate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale())); model.addAttribute("createdDate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale())); model.addAttribute("modifiedDate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale())); } /** * TODO Auto-generated method documentation * * @param model */ public void VetsItemVisitsThymeleafController.populateForm(Model model) { populateFormats(model); } /** * TODO Auto-generated method documentation * * @param vet * @param datatablesColumns * @param search * @param pageable * @param draw * @return ResponseEntity */ @GetMapping(name = "datatables", produces = Datatables.MEDIA_TYPE, value = "/dt") @ResponseBody public ResponseEntity<ConvertedDatatablesData<Visit>> VetsItemVisitsThymeleafController.datatables(@ModelAttribute Vet vet, DatatablesColumns datatablesColumns, GlobalSearch search, DatatablesPageable pageable, @RequestParam("draw") Integer draw) { Page<Visit> visits = getVisitService().findByVet(vet, search, pageable); long totalVisitsCount = getVisitService().countByVet(vet); ConvertedDatatablesData<Visit> data = new ConvertedDatatablesData<Visit>(visits, totalVisitsCount, draw, getConversionService(), datatablesColumns); return ResponseEntity.ok(data); } /** * TODO Auto-generated method documentation * * @param vet * @param model * @return ModelAndView */ @GetMapping(value = "/create-form", name = "createForm") public ModelAndView VetsItemVisitsThymeleafController.createForm(@ModelAttribute Vet vet, Model model) { populateForm(model); model.addAttribute(new Visit()); return new ModelAndView("vets/visits/create"); } /** * TODO Auto-generated method documentation * * @param vet * @param visitsToRemove * @return ResponseEntity */ @DeleteMapping(name = "removeFromVisits", value = "/{visitsToRemove}") @ResponseBody public ResponseEntity<?> VetsItemVisitsThymeleafController.removeFromVisits(@ModelAttribute Vet vet, @PathVariable("visitsToRemove") Long visitsToRemove) { getVetService().removeFromVisits(vet,Collections.singleton(visitsToRemove)); return ResponseEntity.ok().build(); } /** * TODO Auto-generated method documentation * * @param vet * @param visitsToRemove * @return ResponseEntity */ @DeleteMapping(name = "removeFromVisitsBatch", value = "/batch/{visitsToRemove}") @ResponseBody public ResponseEntity<?> VetsItemVisitsThymeleafController.removeFromVisitsBatch(@ModelAttribute Vet vet, @PathVariable("visitsToRemove") Collection<Long> visitsToRemove) { getVetService().removeFromVisits(vet, visitsToRemove); return ResponseEntity.ok().build(); } /** * TODO Auto-generated method documentation * * @param vet * @param visits * @param model * @return ModelAndView */ @PostMapping(name = "create") public ModelAndView VetsItemVisitsThymeleafController.create(@ModelAttribute Vet vet, @RequestParam("visitsIds") List<Long> visits, Model model) { // Remove empty values for (Iterator<Long> iterator = visits.iterator(); iterator.hasNext();) { if (iterator.next() == null) { iterator.remove(); } } getVetService().setVisits(vet,visits); return new ModelAndView("redirect:" + getCollectionLink().to(VetsCollectionThymeleafLinkFactory.LIST).toUriString()); } }
{ "pile_set_name": "Github" }
/* * Copyright 2008-2010 Cisco Systems, Inc. All rights reserved. * Copyright 2007 Nuova Systems, Inc. All rights reserved. * * This program is free software; you may redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef _VNIC_RQ_H_ #define _VNIC_RQ_H_ #include <linux/pci.h> #include "vnic_dev.h" #include "vnic_cq.h" /* Receive queue control */ struct vnic_rq_ctrl { u64 ring_base; /* 0x00 */ u32 ring_size; /* 0x08 */ u32 pad0; u32 posted_index; /* 0x10 */ u32 pad1; u32 cq_index; /* 0x18 */ u32 pad2; u32 enable; /* 0x20 */ u32 pad3; u32 running; /* 0x28 */ u32 pad4; u32 fetch_index; /* 0x30 */ u32 pad5; u32 error_interrupt_enable; /* 0x38 */ u32 pad6; u32 error_interrupt_offset; /* 0x40 */ u32 pad7; u32 error_status; /* 0x48 */ u32 pad8; u32 dropped_packet_count; /* 0x50 */ u32 pad9; u32 dropped_packet_count_rc; /* 0x58 */ u32 pad10; }; /* Break the vnic_rq_buf allocations into blocks of 32/64 entries */ #define VNIC_RQ_BUF_MIN_BLK_ENTRIES 32 #define VNIC_RQ_BUF_DFLT_BLK_ENTRIES 64 #define VNIC_RQ_BUF_BLK_ENTRIES(entries) \ ((unsigned int)((entries < VNIC_RQ_BUF_DFLT_BLK_ENTRIES) ? \ VNIC_RQ_BUF_MIN_BLK_ENTRIES : VNIC_RQ_BUF_DFLT_BLK_ENTRIES)) #define VNIC_RQ_BUF_BLK_SZ(entries) \ (VNIC_RQ_BUF_BLK_ENTRIES(entries) * sizeof(struct vnic_rq_buf)) #define VNIC_RQ_BUF_BLKS_NEEDED(entries) \ DIV_ROUND_UP(entries, VNIC_RQ_BUF_BLK_ENTRIES(entries)) #define VNIC_RQ_BUF_BLKS_MAX VNIC_RQ_BUF_BLKS_NEEDED(4096) struct vnic_rq_buf { struct vnic_rq_buf *next; dma_addr_t dma_addr; void *os_buf; unsigned int os_buf_index; unsigned int len; unsigned int index; void *desc; uint64_t wr_id; }; struct vnic_rq { unsigned int index; struct vnic_dev *vdev; struct vnic_rq_ctrl __iomem *ctrl; /* memory-mapped */ struct vnic_dev_ring ring; struct vnic_rq_buf *bufs[VNIC_RQ_BUF_BLKS_MAX]; struct vnic_rq_buf *to_use; struct vnic_rq_buf *to_clean; void *os_buf_head; unsigned int pkts_outstanding; #ifdef CONFIG_NET_RX_BUSY_POLL #define ENIC_POLL_STATE_IDLE 0 #define ENIC_POLL_STATE_NAPI (1 << 0) /* NAPI owns this poll */ #define ENIC_POLL_STATE_POLL (1 << 1) /* poll owns this poll */ #define ENIC_POLL_STATE_NAPI_YIELD (1 << 2) /* NAPI yielded this poll */ #define ENIC_POLL_STATE_POLL_YIELD (1 << 3) /* poll yielded this poll */ #define ENIC_POLL_YIELD (ENIC_POLL_STATE_NAPI_YIELD | \ ENIC_POLL_STATE_POLL_YIELD) #define ENIC_POLL_LOCKED (ENIC_POLL_STATE_NAPI | \ ENIC_POLL_STATE_POLL) #define ENIC_POLL_USER_PEND (ENIC_POLL_STATE_POLL | \ ENIC_POLL_STATE_POLL_YIELD) unsigned int bpoll_state; spinlock_t bpoll_lock; #endif /* CONFIG_NET_RX_BUSY_POLL */ }; static inline unsigned int vnic_rq_desc_avail(struct vnic_rq *rq) { /* how many does SW own? */ return rq->ring.desc_avail; } static inline unsigned int vnic_rq_desc_used(struct vnic_rq *rq) { /* how many does HW own? */ return rq->ring.desc_count - rq->ring.desc_avail - 1; } static inline void *vnic_rq_next_desc(struct vnic_rq *rq) { return rq->to_use->desc; } static inline unsigned int vnic_rq_next_index(struct vnic_rq *rq) { return rq->to_use->index; } static inline void vnic_rq_post(struct vnic_rq *rq, void *os_buf, unsigned int os_buf_index, dma_addr_t dma_addr, unsigned int len, uint64_t wrid) { struct vnic_rq_buf *buf = rq->to_use; buf->os_buf = os_buf; buf->os_buf_index = os_buf_index; buf->dma_addr = dma_addr; buf->len = len; buf->wr_id = wrid; buf = buf->next; rq->to_use = buf; rq->ring.desc_avail--; /* Move the posted_index every nth descriptor */ #ifndef VNIC_RQ_RETURN_RATE #define VNIC_RQ_RETURN_RATE 0xf /* keep 2^n - 1 */ #endif if ((buf->index & VNIC_RQ_RETURN_RATE) == 0) { /* Adding write memory barrier prevents compiler and/or CPU * reordering, thus avoiding descriptor posting before * descriptor is initialized. Otherwise, hardware can read * stale descriptor fields. */ wmb(); iowrite32(buf->index, &rq->ctrl->posted_index); } } static inline void vnic_rq_return_descs(struct vnic_rq *rq, unsigned int count) { rq->ring.desc_avail += count; } enum desc_return_options { VNIC_RQ_RETURN_DESC, VNIC_RQ_DEFER_RETURN_DESC, }; static inline void vnic_rq_service(struct vnic_rq *rq, struct cq_desc *cq_desc, u16 completed_index, int desc_return, void (*buf_service)(struct vnic_rq *rq, struct cq_desc *cq_desc, struct vnic_rq_buf *buf, int skipped, void *opaque), void *opaque) { struct vnic_rq_buf *buf; int skipped; buf = rq->to_clean; while (1) { skipped = (buf->index != completed_index); (*buf_service)(rq, cq_desc, buf, skipped, opaque); if (desc_return == VNIC_RQ_RETURN_DESC) rq->ring.desc_avail++; rq->to_clean = buf->next; if (!skipped) break; buf = rq->to_clean; } } static inline int vnic_rq_fill(struct vnic_rq *rq, int (*buf_fill)(struct vnic_rq *rq)) { int err; while (vnic_rq_desc_avail(rq) > 0) { err = (*buf_fill)(rq); if (err) return err; } return 0; } #ifdef CONFIG_NET_RX_BUSY_POLL static inline void enic_busy_poll_init_lock(struct vnic_rq *rq) { spin_lock_init(&rq->bpoll_lock); rq->bpoll_state = ENIC_POLL_STATE_IDLE; } static inline bool enic_poll_lock_napi(struct vnic_rq *rq) { bool rc = true; spin_lock(&rq->bpoll_lock); if (rq->bpoll_state & ENIC_POLL_LOCKED) { WARN_ON(rq->bpoll_state & ENIC_POLL_STATE_NAPI); rq->bpoll_state |= ENIC_POLL_STATE_NAPI_YIELD; rc = false; } else { rq->bpoll_state = ENIC_POLL_STATE_NAPI; } spin_unlock(&rq->bpoll_lock); return rc; } static inline bool enic_poll_unlock_napi(struct vnic_rq *rq) { bool rc = false; spin_lock(&rq->bpoll_lock); WARN_ON(rq->bpoll_state & (ENIC_POLL_STATE_POLL | ENIC_POLL_STATE_NAPI_YIELD)); if (rq->bpoll_state & ENIC_POLL_STATE_POLL_YIELD) rc = true; rq->bpoll_state = ENIC_POLL_STATE_IDLE; spin_unlock(&rq->bpoll_lock); return rc; } static inline bool enic_poll_lock_poll(struct vnic_rq *rq) { bool rc = true; spin_lock_bh(&rq->bpoll_lock); if (rq->bpoll_state & ENIC_POLL_LOCKED) { rq->bpoll_state |= ENIC_POLL_STATE_POLL_YIELD; rc = false; } else { rq->bpoll_state |= ENIC_POLL_STATE_POLL; } spin_unlock_bh(&rq->bpoll_lock); return rc; } static inline bool enic_poll_unlock_poll(struct vnic_rq *rq) { bool rc = false; spin_lock_bh(&rq->bpoll_lock); WARN_ON(rq->bpoll_state & ENIC_POLL_STATE_NAPI); if (rq->bpoll_state & ENIC_POLL_STATE_POLL_YIELD) rc = true; rq->bpoll_state = ENIC_POLL_STATE_IDLE; spin_unlock_bh(&rq->bpoll_lock); return rc; } static inline bool enic_poll_busy_polling(struct vnic_rq *rq) { WARN_ON(!(rq->bpoll_state & ENIC_POLL_LOCKED)); return rq->bpoll_state & ENIC_POLL_USER_PEND; } #else static inline void enic_busy_poll_init_lock(struct vnic_rq *rq) { } static inline bool enic_poll_lock_napi(struct vnic_rq *rq) { return true; } static inline bool enic_poll_unlock_napi(struct vnic_rq *rq) { return false; } static inline bool enic_poll_lock_poll(struct vnic_rq *rq) { return false; } static inline bool enic_poll_unlock_poll(struct vnic_rq *rq) { return false; } static inline bool enic_poll_ll_polling(struct vnic_rq *rq) { return false; } #endif /* CONFIG_NET_RX_BUSY_POLL */ void vnic_rq_free(struct vnic_rq *rq); int vnic_rq_alloc(struct vnic_dev *vdev, struct vnic_rq *rq, unsigned int index, unsigned int desc_count, unsigned int desc_size); void vnic_rq_init(struct vnic_rq *rq, unsigned int cq_index, unsigned int error_interrupt_enable, unsigned int error_interrupt_offset); unsigned int vnic_rq_error_status(struct vnic_rq *rq); void vnic_rq_enable(struct vnic_rq *rq); int vnic_rq_disable(struct vnic_rq *rq); void vnic_rq_clean(struct vnic_rq *rq, void (*buf_clean)(struct vnic_rq *rq, struct vnic_rq_buf *buf)); #endif /* _VNIC_RQ_H_ */
{ "pile_set_name": "Github" }
/** Bits that can appear on any page. */ .path-mod-quiz .statedetails { display: block; font-size: 0.7em; } /** Attempt and review pages **/ #page-mod-quiz-attempt #page .controls, #page-mod-quiz-summary #page .controls, #page-mod-quiz-review #page .controls { text-align: center; margin: 8px auto; } #page-mod-quiz-attempt .submitbtns, #page-mod-quiz-review .submitbtns { clear: left; text-align: left; padding-top: 1.5em; } #page-mod-quiz-attempt .submitbtns .mod_quiz-next-nav, #page-mod-quiz-review .submitbtns .mod_quiz-next-nav { float: right; } .path-mod-quiz .mod_quiz-redo_question_button { margin: 0; } .path-mod-quiz input[type="submit"].mod_quiz-redo_question_button { padding: 2px 0.8em; font-size: 1em; } #page-mod-quiz-attempt .mod_quiz-blocked_question_warning .que .formulation, #page-mod-quiz-review .mod_quiz-blocked_question_warning .que .formulation { background: #eee; border: 1px solid #dcdcdc; } #page-mod-quiz-attempt #connection-ok, #page-mod-quiz-attempt #connection-error { position: fixed; top: 0; width: 80%; left: 10%; color: #555; border-radius: 0 0 10px 10px; box-shadow: 5px 5px 20px 0 #666; padding: 1em 1em 0; z-index: 10000; } #page-mod-quiz-attempt #connection-error { background-color: #fcc; } #page-mod-quiz-attempt #connection-ok { background-color: #cfb; width: 60%; left: 20%; } /** Mod quiz attempt **/ .generalbox#passwordbox { /* Should probably match .generalbox#intro above */ width: 70%; margin-left: auto; margin-right: auto; } #passwordform { margin: 1em 0; } /* Question navigation block. */ #quiznojswarning { color: red; } #quiznojswarning { font-size: 0.7em; line-height: 1.1; } .jsenabled #quiznojswarning { display: none; } .path-mod-quiz #user-picture { margin: 0.5em 0; } .path-mod-quiz #user-picture img { width: auto; height: auto; vertical-align: bottom; } .path-mod-quiz #mod_quiz_navblock h3.mod_quiz-section-heading { padding: 0.7em 0 0; margin: 0; clear: both; } .path-mod-quiz #mod_quiz_navblock h3.mod_quiz-section-heading:first-child { padding-top: 0; } .path-mod-quiz .qnbutton { display: block; position: relative; float: left; width: 1.5em; height: 1.5em; overflow: hidden; margin: 0.3em 0.3em 0.3em 0; padding: 0; border: 1px solid #bbb; background: #ddd; text-align: center; line-height: 1.5em; font-weight: bold; text-decoration: none; } .path-mod-quiz .qnbutton:visited:hover, .path-mod-quiz .qnbutton:link:hover { text-decoration: underline; } .path-mod-quiz .qnbutton .trafficlight, .path-mod-quiz .qnbutton .thispageholder { display: block; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .path-mod-quiz .qnbutton.thispage { border-color: #666; } .path-mod-quiz .qnbutton.thispage .thispageholder { border: 1px solid #666; } .path-mod-quiz .qnbutton.flagged .trafficlight { background: url([[pix:quiz|navflagged]]) no-repeat top right; } .path-mod-quiz .qnbutton.blocked, .path-mod-quiz .qnbutton.notyetanswered, .path-mod-quiz .qnbutton.requiresgrading, .path-mod-quiz .qnbutton.invalidanswer { background-color: white; } .path-mod-quiz .qnbutton.correct { background-color: #cfc; } .path-mod-quiz .qnbutton.correct .trafficlight { border-bottom: 3px solid #080; } .path-mod-quiz .qnbutton.partiallycorrect { background-color: #ffa; } .path-mod-quiz .qnbutton.notanswered, .path-mod-quiz .qnbutton.incorrect { background-color: #fcc; } .path-mod-quiz .qnbutton.blocked { color: #999; } .path-mod-quiz .qnbutton.notanswered .trafficlight, .path-mod-quiz .qnbutton.incorrect .trafficlight { border-top: 3px solid #800; } .path-mod-quiz .othernav { clear: both; margin: 0.5em 0; } .path-mod-quiz .othernav a, .path-mod-quiz .othernav input { display: block; margin: 0.5em 0; } /** mod quiz mod **/ #page-mod-quiz-mod #id_reviewoptionshdr .fitem { width: 23%; margin-left: 10px; } #page-mod-quiz-mod #id_reviewoptionshdr fieldset.fgroup { width: 100%; text-align: left; margin-left: 0; } #page-mod-quiz-mod #id_reviewoptionshdr .fitem { float: left; width: 23%; clear: none; } #page-mod-quiz-mod #id_reviewoptionshdr .fitemtitle { width: 100%; font-weight: bold; text-align: left; height: 2.5em; margin-left: 0; } #page-mod-quiz-mod #id_reviewoptionshdr fieldset.fgroup { clear: left; margin: 0 0 1em; } #page-mod-quiz-mod #id_reviewoptionshdr fieldset.fgroup > span { float: left; clear: left; line-height: 1.7; } #page-mod-quiz-mod #id_reviewoptionshdr fieldset.fgroup span label { margin-left: 0.4em; } /** Mod quiz view **/ #page-mod-quiz-view .quizinfo, #page-mod-quiz-view #page .quizgradefeedback, #page-mod-quiz-view #page .quizattempt { text-align: center; } #page-mod-quiz-view #page .quizattemptsummary td p { margin-top: 0; } #page-mod-quiz-view table.quizattemptsummary tr.bestrow td { border-color: #bce8f1; background-color: #d9edf7; } table.quizattemptsummary .noreviewmessage { color: gray; } #page-mod-quiz-view .generaltable.quizattemptsummary { margin-left: auto; margin-right: auto; } #page-mod-quiz-view .generalbox#feedback { width: 70%; margin-left: auto; margin-right: auto; padding-bottom: 15px; } #page-mod-quiz-view .generalbox#feedback h2 { margin: 0; } #page-mod-quiz-view .generalbox#feedback h3 { text-align: left; } #page-mod-quiz-view .generalbox#feedback .overriddennotice { text-align: center; font-size: 0.7em; } .quizstartbuttondiv.quizsecuremoderequired input, .quizstartbuttondiv.quizsecuremoderequired button { display: none; } .jsenabled .quizstartbuttondiv.quizsecuremoderequired input, .jsenabled .quizstartbuttondiv.quizsecuremoderequired button { display: inline; } .quizattempt #mod_quiz_preflight_form { display: none; } #mod_quiz_preflight_form .femptylabel .fitemtitle { display: none; } .moodle-dialogue-base .moodle-dialogue.mod_quiz_preflight_popup { width: 600px; } .moodle-dialogue-base .moodle-dialogue.mod_quiz_preflight_popup .moodle-dialogue-wrap { overflow: hidden; } .moodle-dialogue-base .moodle-dialogue.mod_quiz_preflight_popup .moodle-dialogue-bd { padding: 0; } .moodle-dialogue-base .moodle-dialogue.mod_quiz_preflight_popup .moodle-dialogue-bd #mod_quiz_preflight_form legend { padding: 0 10px; margin: 0; border: 0 none; } .moodle-dialogue-base .moodle-dialogue.mod_quiz_preflight_popup .moodle-dialogue-bd #mod_quiz_preflight_form .fitem { margin-left: 10px; } .moodle-dialogue-base .moodle-dialogue.mod_quiz_preflight_popup .moodle-dialogue-bd #mod_quiz_preflight_form #fgroup_id_buttonar { padding: 10px 0 0; margin: 0; } .moodle-dialogue-base .moodle-dialogue.mod_quiz_preflight_popup .moodle-dialogue-content .moodle-dialogue-ft { margin: 0; } /* Standard Moodle rule that needs to be more specific here. */ .moodle-dialogue-bd #mod_quiz_preflight_form fieldset.hidden { display: inherit; visibility: inherit; } body.path-mod-quiz .gradedattempt, body.path-mod-quiz table tbody tr.gradedattempt > td { border-color: #bce8f1; background-color: #d9edf7; } .quizattemptcounts { clear: left; text-align: center; display: inline; margin-left: 20%; } #page-mod-quiz-view .quizattemptcounts { display: block; margin-left: 0; margin-right: 0; } /** Mod quiz summary **/ #page-mod-quiz-summary #content { text-align: center; } #page-mod-quiz-summary .questionflag { vertical-align: text-bottom; } #page-mod-quiz-summary #quiz-timer { text-align: center; margin-top: 1em; } #page-mod-quiz-summary .submitbtns { margin-top: 1.5em; } @media print { .quiz-secure-window * { display: none; } } /** Mod quiz review **/ table.quizreviewsummary { width: 100%; } table.quizreviewsummary th.cell { padding: 1px 0.5em 1px 1em; font-weight: bold; text-align: right; width: 10em; background: #f0f0f0; } table.quizreviewsummary td.cell { padding: 1px 1em 1px 0.5em; text-align: left; background: #fafafa; } /** Mod quiz make comment or override grade popup. **/ #page-mod-quiz-comment .mform { width: 100%; } #page-mod-quiz-comment .mform fieldset { margin: 0; } #page-mod-quiz-comment .que { margin: 0; } /** Mod quiz report **/ #page-mod-quiz-report h2.main { clear: both; } #page-mod-quiz-report div#commands, #page-mod-quiz-report .controls { text-align: center; } #page-mod-quiz-report .dubious { background-color: #fcc; } #page-mod-quiz-report .highlight { border: 1px solid #bce8f1; background-color: #d9edf7; } #page-mod-quiz-report .negcovar { border: medium solid pink; } #page-mod-quiz-report .toggleincludeauto { text-align: center; } #page-mod-quiz-report .gradetheselink { font-size: 0.8em; } #page-mod-quiz-report .mform fieldset.fgroup span label { margin-right: 14px; } #page-mod-quiz-report table th { white-space: normal; } #page-mod-quiz-report table#attempts td, #page-mod-quiz-report table.quizresponseanalysis td { word-wrap: break-word; max-width: 20em; } #page-mod-quiz-report table.titlesleft td.c0 { font-weight: bold; } #page-mod-quiz-report table .numcol { text-align: center; vertical-align: middle; } #page-mod-quiz-report table#attempts { clear: both; width: 80%; margin: 0.2em auto; } #page-mod-quiz-report table#attempts .header, #page-mod-quiz-report table#attempts .cell { padding: 4px; } #page-mod-quiz-report table#attempts .header .commands { display: inline; } #page-mod-quiz-report table#attempts .picture { width: 40px; } #page-mod-quiz-report table#attempts td { border-left-width: 1px; border-right-width: 1px; border-left-style: solid; border-right-style: solid; vertical-align: middle; } #page-mod-quiz-report table#attempts .header { text-align: left; } #page-mod-quiz-report table#attempts .picture { text-align: center; } #page-mod-quiz-report table#attempts.grades span.que, #page-mod-quiz-report table#attempts span.avgcell { white-space: nowrap; } #page-mod-quiz-report table#attempts span.que .requiresgrading { white-space: normal; } #page-mod-quiz-report table#attempts .questionflag { vertical-align: text-bottom; padding-left: 6px; } #page-mod-quiz-report .graph.flexible-wrap { text-align: center; overflow: auto; } #page-mod-quiz-report #cachingnotice { margin-bottom: 1em; padding: 0.2em; } #page-mod-quiz-report #cachingnotice .singlebutton { margin: 0.5em 0 0; } #page-mod-quiz-report .bold .reviewlink { font-weight: normal; } #page-mod-quiz-report tr.lastrowforattempt { border-bottom: lightgrey solid 0.2em; } #page-mod-quiz-report tr.quiz_statistics-summaryrow td.cell { padding-top: 1px; padding-bottom: 1px; border-top: none; } /** Mod quiz edit **/ #page-mod-quiz-edit .statusdisplay { background-color: #ffc; clear: both; margin: 0.3em 0; padding: 1px 10px; } #page-mod-quiz-edit .statusdisplay p { margin: 4px 0; } #page-mod-quiz-edit .mod_quiz-edit-top-controls { position: relative; } #page-mod-quiz-edit .mod_quiz-edit-action-buttons { display: block; min-height: 2.85em; } @media (max-width: 576px) { #page-mod-quiz-edit .maxgrade { margin-bottom: 0.6em; } #page-mod-quiz-edit .maxgrade .form-control { display: inline-block; vertical-align: middle; } } #page-mod-quiz-edit .maxgrade label { display: inline; } #page-mod-quiz-edit .maxgrade input[type="submit"] { margin: 0; } #page-mod-quiz-edit li.activity > div, #page-mod-quiz-edit li.pagenumber { position: relative; } #page-mod-quiz-edit ul.section li.pagenumber:first-child .add-menu-outer .menu > :last-child, #page-mod-quiz-edit .last-add-menu .add-menu-outer .menu > :last-child { display: none; } #page-mod-quiz-edit .last-add-menu { position: relative; height: 1.5em; margin: 0 20px; } #page-mod-quiz-edit .add-menu-outer { position: absolute; right: 0; } #page-mod-quiz-edit .slotnumber { background-color: #d3d3d3; text-align: center; margin: 0.1em 0.5em; min-width: 2em; display: inline-block; } #page-mod-quiz-edit .section-heading { margin-left: 20px; margin-bottom: 0; height: 40px; } #page-mod-quiz-edit .section-heading .instancesectioncontainer { font-size: 24px; display: inline; } #page-mod-quiz-edit .section-heading .instancesectioncontainer h3 { display: inline; color: #999; } #page-mod-quiz-edit .section-heading .editing_section, #page-mod-quiz-edit .section-heading .editing_delete { margin-left: 10px; } #page-mod-quiz-edit .section-heading .sectioninstance { position: relative; } #page-mod-quiz-edit .section-heading .instancesection { white-space: nowrap; max-width: 72%; display: inline-block; text-overflow: ellipsis; overflow: hidden; vertical-align: bottom; } #page-mod-quiz-edit .section-heading form { display: inline; position: relative; top: 3px; left: -7px; } #page-mod-quiz-edit .section-heading form input { font-size: 24px; font-weight: bold; width: 50%; } #page-mod-quiz-edit .section-heading .instanceshufflequestions { float: right; margin: 0.3em 20px 0 0; } .instanceshufflequestions [type="checkbox"] { vertical-align: middle; margin-right: .5rem; } #page-mod-quiz-edit ul.section { margin: 0; padding: 0 20px; } #page-mod-quiz-edit ul.slots { margin: 0; padding: 0; } #page-mod-quiz-edit ul.slots li.section { border: 0; } #page-mod-quiz-edit ul.slots li.section .content { background-color: #fafafa; padding: 1px 0; } #page-mod-quiz-edit ul.slots li.section { list-style: none; margin: 0; padding: 0; } #page-mod-quiz-edit ul.slots li.section li.activity { background: #e6e6e6; margin: 3px 0; padding: 0.2em; position: relative; } #page-mod-quiz-edit ul.slots li.section li.activity.page { background: transparent; } #page-mod-quiz-edit ul.slots li.section li.activity.page h4 { display: inline; font-weight: normal; font-size: 1em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmarkcontainer { background: white; padding: 0.2em; margin: 0.4em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmarkcontainer .editicon { width: 13px; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmarkcontainer.infoitem { background: transparent; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmarkcontainer form { display: inline; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark { display: inline-block; text-align: right; } #page-mod-quiz-edit ul.slots li.section li.activity .page_split_join_wrapper { position: absolute; left: -20px; bottom: -11px; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_0 { min-width: 1.3em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_1 { min-width: 2em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_2 { min-width: 2.6em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_3 { min-width: 3.2em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_4 { min-width: 3.7em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_5 { min-width: 4.3em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_6 { min-width: 4.8em; } #page-mod-quiz-edit ul.slots li.section li.activity .instancemaxmark.decimalplaces_7 { min-width: 5.45em; } #page-mod-quiz-edit ul.slots li.section li.activity .edit_icon, #page-mod-quiz-edit ul.slots li.section li.activity a.preview, #page-mod-quiz-edit ul.slots li.section li.activity .editing_delete, #page-mod-quiz-edit ul.slots li.section li.activity .editing_maxmark { margin: 0 2px; } #page-mod-quiz-edit ul.slots li.section.only-has-one-slot li.activity .editing_move, #page-mod-quiz-edit ul.slots li.section.only-has-one-slot li.activity .editing_delete { visibility: hidden; } #page-mod-quiz-edit ul.slots.only-one-section li.section.only-has-one-slot li.activity .editing_delete { visibility: visible; } #page-mod-quiz-edit ul.slots li.section li.activity .question_dependency_wrapper { position: absolute; top: 0; right: 0; } #page-mod-quiz-edit ul.slots li.section li.activity .question_dependency_wrapper.question_dependency_cannot_depend { display: none; } #page-mod-quiz-edit ul.slots li.section li.activity .question_dependency_wrapper .currentlink, #page-mod-quiz-edit ul.slots li.section li.activity .question_dependency_wrapper .cm-edit-action { position: relative; left: 20px; top: -1em; } #page-mod-quiz-edit ul.slots li.section li.activity .activityinstance { display: flex; flex: 1 1 auto; min-height: 1.7em; } #page-mod-quiz-edit ul.slots li.section li.activity .mod-indent-outer { display: flex; padding-left: 22px; } #page-mod-quiz-edit ul.slots .activityinstance form { display: inline; } #page-mod-quiz-edit span.editinstructions { right: 0; } #page-mod-quiz-edit ul.slots .activityinstance span.instancename { overflow-x: hidden; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; display: inline-block; height: 20px; } #page-mod-quiz-edit ul.slots .activityinstance span.instancename img { margin: 0 0.2em; } #page-mod-quiz-edit #categoryquestions .questionname, #page-mod-quiz-edit ul.slots li.activity div.activityinstance .questionname { font-weight: bold; color: #555; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } #page-mod-quiz-edit ul.slots li.activity div.activityinstance .questiontext { color: #555; } #page-mod-quiz-edit .section .activity .editing_move { position: absolute; left: 0; top: 0; } #page-mod-quiz-edit ul.slots li.activity div.activityinstance .mod_quiz_random_qbank_link { font-size: 0.8em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-left: 0.25rem; } #page-mod-quiz-edit ul.slots .activityinstance img.activityicon { float: inherit; margin: .2em 0 0; padding: 0; } #page-mod-quiz-edit .section .activity .actions { position: inherit; white-space: nowrap; background: #e6e6e6; padding: 0.1em 0; } #page-mod-quiz-edit .mod_quiz_edit_forms { display: none; } #categoryquestions > tbody > tr:nth-of-type(even) { background: #e4e4e4; } #categoryquestions > tbody > tr.highlight { background-color: #afa; } #categoryquestions .header { text-align: center; padding: 0 2px; border: 0 none; vertical-align: top; } #categoryquestions .header.checkbox { vertical-align: bottom; } #categoryquestions .header.qtype { white-space: nowrap; } #categoryquestions th .sorters { font-weight: normal; font-size: 0.8em; } #categoryquestions td.modifiername, #categoryquestions td.creatorname { line-height: 1em; } #categoryquestions td.modifiername span.date, #categoryquestions td.creatorname span.date { font-weight: normal; font-size: 0.8em; } table#categoryquestions { width: 100%; table-layout: fixed; } #categoryquestions .iconcol { width: 15px; text-align: center; padding: 0; } #categoryquestions .checkbox { width: 19px; text-align: center; padding: 0; } #categoryquestions .editmenu { width: 5em; } #categoryquestions .qtype { text-align: center; } #categoryquestions .qtype { width: 28px; padding: 0; } #categoryquestions .questiontext { position: relative; zoom: 1; padding-left: 0.3em; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } #categoryquestions .questionname { white-space: nowrap; overflow: hidden; zoom: 1; position: relative; } #categoryquestions .questiontext p { margin: 0; } #page-mod-quiz-edit table#categoryquestions td, #page-mod-quiz-edit table#categoryquestions th { overflow: hidden; white-space: nowrap; } .mod_quiz_qbank_dialogue { width: 80%; min-height: 200px; } .mod_quiz_qbank_dialogue.moodle-dialogue-fullscreen { width: 100%; } .mod_quiz_qbank_dialogue .questionbankloading { position: absolute; top: 30px; bottom: 0; left: 0; right: 0; background: #fff; text-align: center; opacity: 0.5; padding-top: 50px; } .mod_quiz_qbank_dialogue #advancedsearch label { font-size: 100%; } .modulespecificbuttonscontainer { padding-left: 0.3em; padding-right: 0.3em; } .questionbankformforpopup .modulespecificbuttonscontainer { padding-top: 10px; padding-left: 0; } .quizquestionlistcontrols { text-align: center; } .categoryinfo { padding: 0.3em; } .path-mod-quiz .gradingdetails { font-size: small; } #page-mod-quiz-edit div#repaginatedialog .mform { margin-left: auto; margin-right: auto; } #page-mod-quiz-edit div.container div.generalbox { position: relative; display: block; border: 0 none; margin: 0; padding: 0; } #page-mod-quiz-edit .paging { margin-top: 0; margin-bottom: 0; padding: 0.1em 0.3em; display: block; background-color: #ddd; } #page-mod-quiz-edit #page-footer { clear: both; padding-top: 1em; } #page-mod-quiz-edit .categoryinfofield { font-style: italic; } #page-mod-quiz-edit .categorynamefield { font-weight: bold; } #page-mod-quiz-edit .questionsortoptions { background-color: #ddd; } #page-mod-quiz-edit div.questionbank .categorysortopotionscontainer { padding-top: 0.5em; margin-top: 0.3em; } #page-mod-quiz-edit div.questionbank .categoryquestionscontainer, .questionbank .categorysortopotionscontainer, .questionbank .categorypagingbarcontainer, .questionbank .categoryselectallcontainer { background-color: #fff; } /* Bulk edit actions */ #page-mod-quiz-edit .btn-group.selectmultiplecommand, #page-mod-quiz-edit .selectmultiplecommandbuttons, #page-mod-quiz-edit .select-multiple-checkbox { display: none; } #page-mod-quiz-edit.select-multiple .selectmultiplecommand, #page-mod-quiz-edit.select-multiple .selectmultiplecommandbuttons, #page-mod-quiz-edit.select-multiple .select-multiple-checkbox { display: inline-block; } #page-mod-quiz-edit.select-multiple input.select-multiple-checkbox[type="checkbox"] { display: inline; } #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section .activity .editing_move, #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section .activity .commands { display: none; } #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section .page_split_join_wrapper { display: none; } #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section .activity .actions .editing_delete, #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section .activity .actions .editing_maxmark { display: none; } #page-mod-quiz-edit.select-multiple#page-mod-quiz-edit .maxgrade, #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .last-add-menu { display: none; } #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section-heading a, #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section-heading form, #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .section-heading .instanceshufflequestions { display: none; } #page-mod-quiz-edit.select-multiple .mod-quiz-edit-content .edit-toolbar .mb-1 { display: none; } #page-mod-quiz-edit.select-multiple#page-mod-quiz-edit ul.slots li.section li.activity .mod-indent-outer { padding-left: 3px; } #page-mod-quiz-edit .section .summary .iconsmall, #page-mod-quiz-edit .section .activity .iconsmall { float: left; } /* Base theme needs extra support. */ #page-mod-quiz-edit ul.slots li.section ul.section { list-style: none; } @media (max-width: 576px) { #page-mod-quiz-edit ul.slots li.section li.activity { padding-top: 30px; } #page-mod-quiz-edit ul.slots li.section li.activity .activityinstance { top: -30px; left: 0; padding-right: 0; overflow: hidden; align-items: center; position: absolute; width: 100%; } } /** Print formatting for attempt and review pages **/ @media print { #page-mod-quiz-attempt header.navbar, #page-mod-quiz-review header.navbar { display: none; } #page-mod-quiz-attempt #dock, #page-mod-quiz-review #dock { display: none; } #page-mod-quiz-attempt #page #page-header h1, #page-mod-quiz-review #page #page-header h1 { display: none; } #page-mod-quiz-attempt #region-main, #page-mod-quiz-review #region-main { width: 100%; } #page-mod-quiz-attempt #block-region-side-pre, #page-mod-quiz-attempt #block-region-side-post, #page-mod-quiz-review #block-region-side-pre, #page-mod-quiz-review #block-region-side-post { display: none; } #page-mod-quiz-attempt #page-footer, #page-mod-quiz-review #page-footer { display: none; } #page-mod-quiz-attempt .editquestion, #page-mod-quiz-review .editquestion, #page-mod-quiz-attempt .questionflag, #page-mod-quiz-review .questionflag { display: none; } #page-mod-quiz-attempt .submitbtns, #page-mod-quiz-review .submitbtns { display: none; } #page-mod-quiz-review .que .commentlink { display: none; } #page-mod-quiz-attempt .que, #page-mod-quiz-review .que { page-break-inside: avoid; } }
{ "pile_set_name": "Github" }
// cmcstl2 - A concept-enabled C++ standard library // // Copyright Casey Carter 2015 // Copyright Eric Niebler 2015 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/caseycarter/cmcstl2 // #ifndef STL2_DETAIL_CONCEPTS_REGULAR_HPP #define STL2_DETAIL_CONCEPTS_REGULAR_HPP #include <stl2/detail/fwd.hpp> #include <stl2/detail/concepts/compare.hpp> #include <stl2/detail/concepts/object/semiregular.hpp> STL2_OPEN_NAMESPACE { /////////////////////////////////////////////////////////////////////////// // regular [concepts.lib.object.regular] // template<class T> META_CONCEPT regular = semiregular<T> && equality_comparable<T>; } STL2_CLOSE_NAMESPACE #endif
{ "pile_set_name": "Github" }
package org.horaapps.leafpic.data; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.ThumbnailUtils; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.widget.Toast; import com.orhanobut.hawk.Hawk; import org.horaapps.leafpic.R; import org.horaapps.leafpic.activities.SplashScreen; import org.horaapps.leafpic.data.sort.SortingMode; import org.horaapps.leafpic.data.sort.SortingOrder; import org.horaapps.leafpic.util.preferences.Prefs; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import static org.horaapps.leafpic.data.MediaHelper.scanFile; import static org.horaapps.leafpic.util.BitmapUtils.addWhiteBorder; import static org.horaapps.leafpic.util.BitmapUtils.getCroppedBitmap; /** * Created by dnld on 3/25/17. */ public class AlbumsHelper { public static void createShortcuts(Context context, List<Album> albums) { for (Album selectedAlbum : albums) { Intent shortcutIntent; shortcutIntent = new Intent(context, SplashScreen.class); shortcutIntent.setAction(SplashScreen.ACTION_OPEN_ALBUM); shortcutIntent.putExtra("albumPath", selectedAlbum.getPath()); shortcutIntent.putExtra("albumId", selectedAlbum.getId()); shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Intent addIntent = new Intent(); addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, selectedAlbum.getName()); Media coverAlbum = selectedAlbum.getCover(); File image = new File(coverAlbum.getPath()); Bitmap bitmap = coverAlbum.isVideo() ? ThumbnailUtils.createVideoThumbnail(coverAlbum.getPath(), MediaStore.Images.Thumbnails.MINI_KIND) : BitmapFactory.decodeFile(image.getAbsolutePath(), new BitmapFactory.Options()); if (bitmap == null) { Toast.makeText(context, R.string.error_thumbnail, Toast.LENGTH_SHORT).show(); // TODO: 12/31/16 return; } bitmap = Bitmap.createScaledBitmap(getCroppedBitmap(bitmap), 128, 128, false); addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, addWhiteBorder(bitmap, 5)); addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); context.sendBroadcast(addIntent); } } @NonNull public static SortingMode getSortingMode() { return Prefs.getAlbumSortingMode(); } @NonNull public static SortingOrder getSortingOrder() { return Prefs.getAlbumSortingOrder(); } public static void setSortingMode(@NonNull SortingMode sortingMode) { Prefs.setAlbumSortingMode(sortingMode); } public static void setSortingOrder(@NonNull SortingOrder sortingOrder) { Prefs.setAlbumSortingOrder(sortingOrder); } public static void hideAlbum(String path, Context context) { File dirName = new File(path); File file = new File(dirName, ".nomedia"); if (!file.exists()) { try { FileOutputStream out = new FileOutputStream(file); out.flush(); out.close(); scanFile(context, new String[]{ file.getAbsolutePath() }); } catch (Exception e) { e.printStackTrace(); } } } public static void unHideAlbum(String path, Context context) { File dirName = new File(path); File file = new File(dirName, ".nomedia"); if (file.exists()) { if (file.delete()) scanFile(context, new String[]{ file.getAbsolutePath() }); } } public static boolean deleteAlbum(Album album, Context context) { return StorageHelper.deleteFilesInFolder(context, new File(album.getPath())); } public static void saveLastHiddenPaths(ArrayList<String> list) { Hawk.put("h", list); } public static ArrayList<String> getLastHiddenPaths() { return Hawk.get("h", new ArrayList<>()); } }
{ "pile_set_name": "Github" }
Function moveMPEGFilters() Dim CommonFolder, LegacyFolder, InstallFolder, DestinationFolder, SourceTestFile, DestinationLegacy InstallFolder = Session.TargetPath("INSTALLFOLDER") 'InstallFolder = "C:\Program Files (x86)\SageTV" CommonFolder = InstallFolder + "\Common\" LegacyFolder = InstallFolder + "\Common\Legacy\" 'Use this test file to see if the Decoders are available for copy SourceTestFile = "stvmpgadec.dll" 'DestinationFolder = "C:\BackupMPEG\" DestinationFolder = InstallFolder + "\MPEGDecoder\" DestinationLegacy = DestinationFolder + "Legacy\" Set fso = CreateObject("Scripting.FileSystemObject") 'Check to see if the Source Files Exist use the test file If Not fso.FileExists(CommonFolder + SourceTestFile) Then 'the source does not exist so just exit 'msgbox "Decoders do not exist on this system" moveMPEGFilters = 1 Set fso = Nothing Exit Function End If 'Check to see if the file already exists in the destination folder If fso.FileExists(DestinationFolder + SourceTestFile) Then 'the file exists so just exit 'msgbox "File already in the destination location" moveMPEGFilters = 1 Else 'The file does not exist in the destination folder 'Create the destination folder if needed If Not fso.FolderExists(DestinationFolder) Then fso.CreateFolder(DestinationFolder) 'msgbox "Created folder " + DestinationFolder 'create the legacy destination folder if needed If Not fso.FolderExists(DestinationLegacy) Then fso.CreateFolder(DestinationLegacy) 'msgbox "Created folder " + DestinationLegacy End If End If 'copy all the Common Files fso.CopyFile CommonFolder + "stv*.*", DestinationFolder, True fso.CopyFile CommonFolder + "msvcp71.dll", DestinationFolder, True fso.CopyFile CommonFolder + "msvcr71.dll", DestinationFolder, True 'msgbox "Copying complete to " + DestinationFolder 'copy all the Legacy Files fso.CopyFile LegacyFolder + "stv*.*", DestinationLegacy, True 'msgbox "Copying complete to " + DestinationLegacy Session.Property("MPEGDecoderMoved") = "1" moveMPEGFilters = 1 End If Set fso = Nothing moveMPEGFilters = 1 Exit Function End Function Function registerMPEGFilters() Dim CommonFolder, LegacyFolder, InstallFolder, DestinationFolder, SourceTestFile, DestinationLegacy Dim intRegister InstallFolder = Session.Property("CustomActionData") 'InstallFolder = "C:\Program Files (x86)\SageTV" CommonFolder = InstallFolder + "\Common\" LegacyFolder = InstallFolder + "\Common\Legacy\" 'Use this test file to see if the Decoders are available for copy SourceTestFile = "stvmpgadec.dll" 'DestinationFolder = "C:\BackupMPEG\" DestinationFolder = InstallFolder + "\MPEGDecoder\" DestinationLegacy = DestinationFolder + "Legacy\" Set fso = CreateObject("Scripting.FileSystemObject") 'Check to see if the file exists in the destination folder If fso.FileExists(DestinationFolder + SourceTestFile) Then 'the file exists so we will register the filters Set objShell = CreateObject("WScript.Shell") objShell.CurrentDirectory = DestinationFolder 'msgbox "Changing folder to " + objShell.CurrentDirectory intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationFolder + "stvl2ad.ax" + Chr(34)) intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationFolder + "stvl2ae.ax" + Chr(34)) intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationFolder + "stvm2vd.ax" + Chr(34)) intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationFolder + "stvm2ve.ax" + Chr(34)) intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationFolder + "stvmpeg2mux.ax" + Chr(34)) intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationFolder + "stvmpgdmx.ax" + Chr(34)) intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationFolder + "stvmuxmpeg.ax" + Chr(34)) objShell.CurrentDirectory = DestinationLegacy 'msgbox "Changing folder to " + objShell.CurrentDirectory intRegister = objShell.Run("regsvr32 /s " + Chr(34) + DestinationLegacy + "stvmcdsmpeg.ax" + Chr(34)) Else 'The file does not exist so just exit End If Set fso = Nothing registerMPEGFilters = 1 Exit Function End Function
{ "pile_set_name": "Github" }
#ifndef _ORA_SCHEMA_H_ #define _ORA_SCHEMA_H_ /* * Use internal * * Location: * src/backend/oraschema/oraschema.h */ #include "postgres.h" #include "catalog/catversion.h" #include "nodes/pg_list.h" #include <sys/time.h> #include "utils/datetime.h" #include "utils/datum.h" #define TextPCopy(t) \ DatumGetTextP(datumCopy(PointerGetDatum(t), false, -1)) #define PG_GETARG_IF_EXISTS(n, type, defval) \ ((PG_NARGS() > (n) && !PG_ARGISNULL(n)) ? PG_GETARG_##type(n) : (defval)) extern int ora_instr(text *txt, text *pattern, int start, int nth); extern int ora_mb_strlen(text *str, char **sizes, int **positions); extern int ora_mb_strlen1(text *str); extern int ora_seq_search(const char *name, char * array[], int max); #if PG_VERSION_NUM >= 80400 extern Oid equality_oper_funcid(Oid argtype); #endif #endif /* _ORA_SCHEMA_H_ */
{ "pile_set_name": "Github" }
hello world
{ "pile_set_name": "Github" }
import { IconDefinition } from '../types'; declare const WechatOutlined: IconDefinition; export default WechatOutlined;
{ "pile_set_name": "Github" }
#region Copyright Syncfusion Inc. 2001-2020. // Copyright Syncfusion Inc. 2001-2020. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // [email protected]. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfChat { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoadMoreView : RelativeLayout { public LoadMoreView () { InitializeComponent (); } } }
{ "pile_set_name": "Github" }
// // ATMessageCenterCell.h // ApptentiveConnect // // Created by Andrew Wooster on 1/29/13. // Copyright (c) 2013 Apptentive, Inc. All rights reserved. // #import <Foundation/Foundation.h> @protocol ATMessageCenterCell <NSObject> - (CGFloat)cellHeightForWidth:(CGFloat)width; @end
{ "pile_set_name": "Github" }
// // YFCategoryTableInteractor.m // BigShow1949 // // Created by big show on 2018/12/8. // Copyright © 2018年 BigShowCompany. All rights reserved. // #import "YFCategoryTableInteractor.h" #import "YFCategoryDisplayItem.h" @implementation YFCategoryTableInteractor -(NSMutableArray*)getAllCategories { YFCategoryDisplayItem *item0 = [YFCategoryDisplayItem itemWithTitle:@"0"]; YFCategoryDisplayItem *item1 = [YFCategoryDisplayItem itemWithTitle:@"1"]; YFCategoryDisplayItem *item2 = [YFCategoryDisplayItem itemWithTitle:@"2"]; YFCategoryDisplayItem *item3 = [YFCategoryDisplayItem itemWithTitle:@"3"]; YFCategoryDisplayItem *item4 = [YFCategoryDisplayItem itemWithTitle:@"4"]; return @[item0,item1,item2,item3,item4]; } @end
{ "pile_set_name": "Github" }
--- name: Bug Report about: Report a Cirrus CI bug labels: bug assignees: '' --- # Expected Behavior What should have happened is ... # Real Behavior What ended up happening was ... # Related Info - [ ] Website issue - Link to page: - [ ] Task issue - OS: (DockerLinux, macOS, Windows, FreeBSD) - Task name: - Script/cache name (if applies):
{ "pile_set_name": "Github" }
-------------------------------------------------- Name -------------------------------------------------- Mango Salsa Chicken -------------------------------------------------- Ingredients -------------------------------------------------- 1 fresh, ripe mango 1/2 red onion, finely diced 1 bunch cilantro, finely chopped 1/2 green bell pepper, minced 1 fresh red chile pepper, seeded and chopped 4 skinless, boneless chicken breasts 1 egg 1/4 cup milk 1 cup dried bread crumbs 1/4 cup olive oil 1 sprig fresh cilantro, for garnish -------------------------------------------------- Directions -------------------------------------------------- TO MAKE SALSA: In a small bowl, combine the mango, onion, cilantro, green bell pepper and red chile pepper. Put aside until serving time Lightly pound the chicken breasts with a mallet to flatten. Beat the egg and milk together. Then coat them in the egg/milk mixture then the breadcrumbs. Chill for 1/2 hour Saute the chicken in olive oil until cooked through and juices run clear. Drain and serve with the mango salsa. Garnish with cilantro leaves --------------------------------------------------
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic extern int a1[]; void f0(); void f1(int [*]); void f2(int [const *]); void f3(int [volatile const*]); int f4(*XX)(void); /* expected-error {{cannot return}} expected-warning {{type specifier missing, defaults to 'int'}} */ char ((((*X)))); void (*signal(int, void (*)(int)))(int); int aaaa, ***C, * const D, B(int); int *A; struct str; void test2(int *P, int A) { struct str; // Hard case for array decl, not Array[*]. int Array[*(int*)P+A]; } typedef int atype; void test3(x, atype /* expected-error {{unexpected type name 'atype': expected identifier}} */ ) int x, atype; {} void test4(x, x) int x; {} /* expected-error {{redefinition of parameter 'x'}} */ // PR3031 int (test5), ; // expected-error {{expected identifier or '('}} // PR3963 & rdar://6759604 - test error recovery for mistyped "typenames". foo_t *d; // expected-error {{unknown type name 'foo_t'}} foo_t a; // expected-error {{unknown type name 'foo_t'}} int test6() { return a; } // a should be declared. // Use of tagged type without tag. rdar://6783347 struct xyz { int y; }; enum myenum { ASDFAS }; xyz b; // expected-error {{must use 'struct' tag to refer to type 'xyz'}} myenum c; // expected-error {{must use 'enum' tag to refer to type 'myenum'}} float *test7() { // We should recover 'b' by parsing it with a valid type of "struct xyz", which // allows us to diagnose other bad things done with y, such as this. return &b.y; // expected-warning {{incompatible pointer types returning 'int *' from a function with result type 'float *'}} } struct xyz test8() { return a; } // a should be be marked invalid, no diag. // Verify that implicit int still works. static f; // expected-warning {{type specifier missing, defaults to 'int'}} static g = 4; // expected-warning {{type specifier missing, defaults to 'int'}} static h // expected-warning {{type specifier missing, defaults to 'int'}} __asm__("foo"); struct test9 { int x // expected-error {{expected ';' at end of declaration list}} int y; int z // expected-warning {{expected ';' at end of declaration list}} }; // PR6208 struct test10 { int a; } static test10x; struct test11 { int a; } const test11x; // PR6216 void test12() { (void)__builtin_offsetof(struct { char c; int i; }, i); } // rdar://7608537 struct test13 { int a; } (test13x); // <rdar://problem/8044088> struct X<foo::int> { }; // expected-error{{expected identifier or '('}} // PR7617 - error recovery on missing ;. void test14() // expected-error {{expected ';' after top level declarator}} void test14a(); void *test14b = (void*)test14a; // Make sure test14a didn't get skipped. // rdar://problem/8358508 long struct X { int x; } test15(); // expected-error {{'long struct' is invalid}} void test16(i) int i j; { } // expected-error {{expected ';' at end of declaration}} void test17(i, j) int i, j k; { } // expected-error {{expected ';' at end of declaration}}
{ "pile_set_name": "Github" }
// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_BLUETOOTH = 0x20 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_ENCAP = 0x1c AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_KEY = 0x1e AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x1d AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ALTWERASE = 0x200 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRFILT = 0x4004427c BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc010427b BIOCGETIF = 0x4020426b BIOCGFILDROP = 0x40044278 BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044273 BIOCGRTIMEOUT = 0x4010426e BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x20004276 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDIRFILT = 0x8004427d BIOCSDLT = 0x8004427a BIOCSETF = 0x80104267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x80104277 BIOCSFILDROP = 0x80044279 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044272 BIOCSRTIMEOUT = 0x8010426d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIRECTION_IN = 0x1 BPF_DIRECTION_OUT = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x200000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_BOOTTIME = 0x6 CLOCK_MONOTONIC = 0x3 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_THREAD_CPUTIME_ID = 0x4 CLOCK_UPTIME = 0x5 CREAD = 0x800 CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0xff CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_HW = 0x6 CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e DLT_ARCNET = 0x7 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0xd DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_LOOP = 0xc DLT_MPLS = 0xdb DLT_NULL = 0x0 DLT_OPENFLOW = 0x10b DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xe DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_USBPCAP = 0xf9 DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMT_TAGOVF = 0x1 EMUL_ENABLED = 0x1 EMUL_NATIVE = 0x2 ENDRUNDISC = 0x9 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_AOE = 0x88a2 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LLDP = 0x88cc ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_QINQ = 0x88a8 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOW = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_ALIGN = 0x2 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_DIX_LEN = 0x600 ETHER_MAX_HARDMTU_LEN = 0xff9b ETHER_MAX_LEN = 0x5ee ETHER_MIN_LEN = 0x40 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = -0x3 EVFILT_DEVICE = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x8 EVFILT_TIMER = -0x7 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EVL_ENCAPLEN = 0x4 EVL_PRIO_BITS = 0xd EVL_PRIO_MAX = 0x7 EVL_VLID_MASK = 0xfff EVL_VLID_MAX = 0xffe EVL_VLID_MIN = 0x1 EVL_VLID_NULL = 0x0 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xa F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_ISATTY = 0xb F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8e52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_STATICARP = 0x20 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BLUETOOTH = 0xf8 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf7 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DUMMY = 0xf1 IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf3 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MBIM = 0xfa IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFLOW = 0xf9 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf2 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_HOST = 0x1 IN_RFC3021_NET = 0xfffffffe IN_RFC3021_NSHIFT = 0x1f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DIVERT = 0x102 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x103 IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPV6_AUTH_LEVEL = 0x35 IPV6_AUTOFLOWLABEL = 0x3b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_ESP_NETWORK_LEVEL = 0x37 IPV6_ESP_TRANS_LEVEL = 0x36 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPCOMP_LEVEL = 0x3c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MINHOPCOUNT = 0x41 IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_OPTIONS = 0x1 IPV6_PATHMTU = 0x2c IPV6_PIPEX = 0x3f IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVDSTPORT = 0x40 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTABLE = 0x1021 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_AUTH_LEVEL = 0x14 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_ESP_NETWORK_LEVEL = 0x16 IP_ESP_TRANS_LEVEL = 0x15 IP_HDRINCL = 0x2 IP_IPCOMP_LEVEL = 0x1d IP_IPDEFTTL = 0x25 IP_IPSECFLOWINFO = 0x24 IP_IPSEC_LOCAL_AUTH = 0x1b IP_IPSEC_LOCAL_CRED = 0x19 IP_IPSEC_LOCAL_ID = 0x17 IP_IPSEC_REMOTE_AUTH = 0x1c IP_IPSEC_REMOTE_CRED = 0x1a IP_IPSEC_REMOTE_ID = 0x18 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0xfff IP_MF = 0x2000 IP_MINTTL = 0x20 IP_MIN_MEMBERSHIPS = 0xf IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PIPEX = 0x22 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVDSTPORT = 0x21 IP_RECVIF = 0x1e IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRTABLE = 0x23 IP_RECVTTL = 0x1f IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RTABLE = 0x1021 IP_SENDSRCADDR = 0x7 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IUCLC = 0x1000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 KERN_HOSTNAME = 0xa KERN_OSRELEASE = 0x2 KERN_OSTYPE = 0x1 KERN_VERSION = 0x4 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_CONCEAL = 0x8000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FLAGMASK = 0xfff7 MAP_HASSEMAPHORE = 0x0 MAP_INHERIT = 0x0 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_INHERIT_ZERO = 0x3 MAP_NOEXTEND = 0x0 MAP_NORESERVE = 0x0 MAP_PRIVATE = 0x2 MAP_RENAME = 0x0 MAP_SHARED = 0x1 MAP_STACK = 0x4000 MAP_TRYFIXED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ASYNC = 0x40 MNT_DEFEXPORTED = 0x200 MNT_DELEXPORT = 0x20000 MNT_DOOMED = 0x8000000 MNT_EXPORTANON = 0x400 MNT_EXPORTED = 0x100 MNT_EXRDONLY = 0x80 MNT_FORCE = 0x80000 MNT_LAZY = 0x3 MNT_LOCAL = 0x1000 MNT_NOATIME = 0x8000 MNT_NODEV = 0x10 MNT_NOEXEC = 0x4 MNT_NOPERM = 0x20 MNT_NOSUID = 0x8 MNT_NOWAIT = 0x2 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SOFTDEP = 0x4000000 MNT_STALLED = 0x100000 MNT_SYNCHRONOUS = 0x2 MNT_UPDATE = 0x10000 MNT_VISFLAGMASK = 0x400ffff MNT_WAIT = 0x1 MNT_WANTRDWR = 0x2000000 MNT_WXALLOWED = 0x800 MSG_BCAST = 0x100 MSG_CMSG_CLOEXEC = 0x800 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_MCAST = 0x200 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x4 MS_SYNC = 0x2 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFNAMES = 0x6 NET_RT_MAXID = 0x7 NET_RT_STATS = 0x4 NET_RT_TABLE = 0x5 NFDBITS = 0x20 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 NOTE_CHANGE = 0x1 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EOF = 0x2 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRUNCATE = 0x80 NOTE_WRITE = 0x2 OCRNL = 0x10 OLCUC = 0x20 ONLCR = 0x2 ONLRET = 0x80 ONOCR = 0x40 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x10000 O_CREAT = 0x200 O_DIRECTORY = 0x20000 O_DSYNC = 0x80 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x80 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PF_FLUSH = 0x1 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BFD = 0xb RTAX_BRD = 0x7 RTAX_DNS = 0xc RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_LABEL = 0xa RTAX_MAX = 0xf RTAX_NETMASK = 0x2 RTAX_SEARCH = 0xe RTAX_SRC = 0x8 RTAX_SRCMASK = 0x9 RTAX_STATIC = 0xd RTA_AUTHOR = 0x40 RTA_BFD = 0x800 RTA_BRD = 0x80 RTA_DNS = 0x1000 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_LABEL = 0x400 RTA_NETMASK = 0x4 RTA_SEARCH = 0x4000 RTA_SRC = 0x100 RTA_SRCMASK = 0x200 RTA_STATIC = 0x2000 RTF_ANNOUNCE = 0x4000 RTF_BFD = 0x1000000 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CACHED = 0x20000 RTF_CLONED = 0x10000 RTF_CLONING = 0x100 RTF_CONNECTED = 0x800000 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FMASK = 0x110fc08 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MPATH = 0x40000 RTF_MPLS = 0x100000 RTF_MULTICAST = 0x200 RTF_PERMANENT_ARP = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x2000 RTF_REJECT = 0x8 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_USETRAILERS = 0x8000 RTM_ADD = 0x1 RTM_BFD = 0x12 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DESYNC = 0x10 RTM_GET = 0x4 RTM_IFANNOUNCE = 0xf RTM_IFINFO = 0xe RTM_INVALIDATE = 0x11 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MAXSIZE = 0x800 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_PROPOSAL = 0x13 RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_TABLEID_BITS = 0x8 RT_TABLEID_MASK = 0xff RT_TABLEID_MAX = 0xff RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80286987 SIOCATMARK = 0x40047307 SIOCBRDGADD = 0x8060693c SIOCBRDGADDL = 0x80606949 SIOCBRDGADDS = 0x80606941 SIOCBRDGARL = 0x808c694d SIOCBRDGDADDR = 0x81286947 SIOCBRDGDEL = 0x8060693d SIOCBRDGDELS = 0x80606942 SIOCBRDGFLUSH = 0x80606948 SIOCBRDGFRL = 0x808c694e SIOCBRDGGCACHE = 0xc0186941 SIOCBRDGGFD = 0xc0186952 SIOCBRDGGHT = 0xc0186951 SIOCBRDGGIFFLGS = 0xc060693e SIOCBRDGGMA = 0xc0186953 SIOCBRDGGPARAM = 0xc0406958 SIOCBRDGGPRI = 0xc0186950 SIOCBRDGGRL = 0xc030694f SIOCBRDGGTO = 0xc0186946 SIOCBRDGIFS = 0xc0606942 SIOCBRDGRTS = 0xc0206943 SIOCBRDGSADDR = 0xc1286944 SIOCBRDGSCACHE = 0x80186940 SIOCBRDGSFD = 0x80186952 SIOCBRDGSHT = 0x80186951 SIOCBRDGSIFCOST = 0x80606955 SIOCBRDGSIFFLGS = 0x8060693f SIOCBRDGSIFPRIO = 0x80606954 SIOCBRDGSIFPROT = 0x8060694a SIOCBRDGSMA = 0x80186953 SIOCBRDGSPRI = 0x80186950 SIOCBRDGSPROTO = 0x8018695a SIOCBRDGSTO = 0x80186945 SIOCBRDGSTXHC = 0x80186959 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80286989 SIOCDIFPARENT = 0x802069b4 SIOCDIFPHYADDR = 0x80206949 SIOCDVNETID = 0x802069af SIOCGETKALIVE = 0xc01869a4 SIOCGETLABEL = 0x8020699a SIOCGETMPWCFG = 0xc02069ae SIOCGETPFLOW = 0xc02069fe SIOCGETPFSYNC = 0xc02069f8 SIOCGETSGCNT = 0xc0207534 SIOCGETVIFCNT = 0xc0287533 SIOCGETVLAN = 0xc0206990 SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCONF = 0xc0106924 SIOCGIFDATA = 0xc020691b SIOCGIFDESCR = 0xc0206981 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGATTR = 0xc028698b SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc028698a SIOCGIFGROUP = 0xc0286988 SIOCGIFHARDMTU = 0xc02069a5 SIOCGIFLLPRIO = 0xc02069b6 SIOCGIFMEDIA = 0xc0406938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc020697e SIOCGIFNETMASK = 0xc0206925 SIOCGIFPAIR = 0xc02069b1 SIOCGIFPARENT = 0xc02069b3 SIOCGIFPRIORITY = 0xc020699c SIOCGIFRDOMAIN = 0xc02069a0 SIOCGIFRTLABEL = 0xc0206983 SIOCGIFRXR = 0x802069aa SIOCGIFXFLAGS = 0xc020699e SIOCGLIFPHYADDR = 0xc218694b SIOCGLIFPHYDF = 0xc02069c2 SIOCGLIFPHYRTABLE = 0xc02069a2 SIOCGLIFPHYTTL = 0xc02069a9 SIOCGPGRP = 0x40047309 SIOCGSPPPPARAMS = 0xc0206994 SIOCGUMBINFO = 0xc02069be SIOCGUMBPARAM = 0xc02069c0 SIOCGVH = 0xc02069f6 SIOCGVNETFLOWID = 0xc02069c4 SIOCGVNETID = 0xc02069a7 SIOCIFAFATTACH = 0x801169ab SIOCIFAFDETACH = 0x801169ac SIOCIFCREATE = 0x8020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106978 SIOCSETKALIVE = 0x801869a3 SIOCSETLABEL = 0x80206999 SIOCSETMPWCFG = 0x802069ad SIOCSETPFLOW = 0x802069fd SIOCSETPFSYNC = 0x802069f7 SIOCSETVLAN = 0x8020698f SIOCSIFADDR = 0x8020690c SIOCSIFBRDADDR = 0x80206913 SIOCSIFDESCR = 0x80206980 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGATTR = 0x8028698c SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020691f SIOCSIFLLPRIO = 0x802069b5 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x8020697f SIOCSIFNETMASK = 0x80206916 SIOCSIFPAIR = 0x802069b0 SIOCSIFPARENT = 0x802069b2 SIOCSIFPRIORITY = 0x8020699b SIOCSIFRDOMAIN = 0x8020699f SIOCSIFRTLABEL = 0x80206982 SIOCSIFXFLAGS = 0x8020699d SIOCSLIFPHYADDR = 0x8218694a SIOCSLIFPHYDF = 0x802069c1 SIOCSLIFPHYRTABLE = 0x802069a1 SIOCSLIFPHYTTL = 0x802069a8 SIOCSPGRP = 0x80047308 SIOCSSPPPPARAMS = 0x80206993 SIOCSUMBPARAM = 0x802069bf SIOCSVH = 0xc02069f5 SIOCSVNETFLOWID = 0x802069c3 SIOCSVNETID = 0x802069a6 SIOCSWGDPID = 0xc018695b SIOCSWGMAXFLOW = 0xc0186960 SIOCSWGMAXGROUP = 0xc018695d SIOCSWSDPID = 0x8018695c SIOCSWSPORTNO = 0xc060695f SOCK_CLOEXEC = 0x8000 SOCK_DGRAM = 0x2 SOCK_DNS = 0x1000 SOCK_NONBLOCK = 0x4000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BINDANY = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NETPROC = 0x1020 SO_OOBINLINE = 0x100 SO_PEERCRED = 0x1022 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RTABLE = 0x1021 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_SPLICE = 0x1023 SO_TIMESTAMP = 0x800 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_ZEROIZE = 0x2000 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x3 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x4 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOPUSH = 0x10 TCP_SACK_ENABLE = 0x8 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCHKVERAUTH = 0x2000741e TIOCCLRVERAUTH = 0x2000741d TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_PPS = 0x10 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGTSTAMP = 0x4010745b TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMODG = 0x4004746a TIOCMODS = 0x8004746d TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSETVERAUTH = 0x8004741c TIOCSFLAGS = 0x8004745c TIOCSIG = 0x8004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSTSTAMP = 0x8008745a TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TIOCUCNTL_CBRK = 0x7a TIOCUCNTL_SBRK = 0x7b TOSTOP = 0x400000 UTIME_NOW = -0x2 UTIME_OMIT = -0x1 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_ANONMIN = 0x7 VM_LOADAVG = 0x2 VM_MAXID = 0xc VM_MAXSLP = 0xa VM_METER = 0x1 VM_NKMEMPAGES = 0x6 VM_PSSTRINGS = 0x3 VM_SWAPENCRYPT = 0x5 VM_USPACE = 0xb VM_UVMEXP = 0x4 VM_VNODEMIN = 0x9 VM_VTEXTMIN = 0x8 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALTSIG = 0x4 WCONTINUED = 0x8 WCOREFLAG = 0x80 WNOHANG = 0x1 WUNTRACED = 0x2 XCASE = 0x1000000 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x5c) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x58) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x59) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EIPSEC = syscall.Errno(0x52) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x5f) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x56) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x53) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOMEDIUM = syscall.Errno(0x55) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5a) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x5d) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x5b) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x57) EOWNERDEAD = syscall.Errno(0x5e) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x5f) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errorList = [...]struct { num syscall.Errno name string desc string }{ {1, "EPERM", "operation not permitted"}, {2, "ENOENT", "no such file or directory"}, {3, "ESRCH", "no such process"}, {4, "EINTR", "interrupted system call"}, {5, "EIO", "input/output error"}, {6, "ENXIO", "device not configured"}, {7, "E2BIG", "argument list too long"}, {8, "ENOEXEC", "exec format error"}, {9, "EBADF", "bad file descriptor"}, {10, "ECHILD", "no child processes"}, {11, "EDEADLK", "resource deadlock avoided"}, {12, "ENOMEM", "cannot allocate memory"}, {13, "EACCES", "permission denied"}, {14, "EFAULT", "bad address"}, {15, "ENOTBLK", "block device required"}, {16, "EBUSY", "device busy"}, {17, "EEXIST", "file exists"}, {18, "EXDEV", "cross-device link"}, {19, "ENODEV", "operation not supported by device"}, {20, "ENOTDIR", "not a directory"}, {21, "EISDIR", "is a directory"}, {22, "EINVAL", "invalid argument"}, {23, "ENFILE", "too many open files in system"}, {24, "EMFILE", "too many open files"}, {25, "ENOTTY", "inappropriate ioctl for device"}, {26, "ETXTBSY", "text file busy"}, {27, "EFBIG", "file too large"}, {28, "ENOSPC", "no space left on device"}, {29, "ESPIPE", "illegal seek"}, {30, "EROFS", "read-only file system"}, {31, "EMLINK", "too many links"}, {32, "EPIPE", "broken pipe"}, {33, "EDOM", "numerical argument out of domain"}, {34, "ERANGE", "result too large"}, {35, "EAGAIN", "resource temporarily unavailable"}, {36, "EINPROGRESS", "operation now in progress"}, {37, "EALREADY", "operation already in progress"}, {38, "ENOTSOCK", "socket operation on non-socket"}, {39, "EDESTADDRREQ", "destination address required"}, {40, "EMSGSIZE", "message too long"}, {41, "EPROTOTYPE", "protocol wrong type for socket"}, {42, "ENOPROTOOPT", "protocol not available"}, {43, "EPROTONOSUPPORT", "protocol not supported"}, {44, "ESOCKTNOSUPPORT", "socket type not supported"}, {45, "EOPNOTSUPP", "operation not supported"}, {46, "EPFNOSUPPORT", "protocol family not supported"}, {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, {48, "EADDRINUSE", "address already in use"}, {49, "EADDRNOTAVAIL", "can't assign requested address"}, {50, "ENETDOWN", "network is down"}, {51, "ENETUNREACH", "network is unreachable"}, {52, "ENETRESET", "network dropped connection on reset"}, {53, "ECONNABORTED", "software caused connection abort"}, {54, "ECONNRESET", "connection reset by peer"}, {55, "ENOBUFS", "no buffer space available"}, {56, "EISCONN", "socket is already connected"}, {57, "ENOTCONN", "socket is not connected"}, {58, "ESHUTDOWN", "can't send after socket shutdown"}, {59, "ETOOMANYREFS", "too many references: can't splice"}, {60, "ETIMEDOUT", "operation timed out"}, {61, "ECONNREFUSED", "connection refused"}, {62, "ELOOP", "too many levels of symbolic links"}, {63, "ENAMETOOLONG", "file name too long"}, {64, "EHOSTDOWN", "host is down"}, {65, "EHOSTUNREACH", "no route to host"}, {66, "ENOTEMPTY", "directory not empty"}, {67, "EPROCLIM", "too many processes"}, {68, "EUSERS", "too many users"}, {69, "EDQUOT", "disk quota exceeded"}, {70, "ESTALE", "stale NFS file handle"}, {71, "EREMOTE", "too many levels of remote in path"}, {72, "EBADRPC", "RPC struct is bad"}, {73, "ERPCMISMATCH", "RPC version wrong"}, {74, "EPROGUNAVAIL", "RPC program not available"}, {75, "EPROGMISMATCH", "program version wrong"}, {76, "EPROCUNAVAIL", "bad procedure for program"}, {77, "ENOLCK", "no locks available"}, {78, "ENOSYS", "function not implemented"}, {79, "EFTYPE", "inappropriate file type or format"}, {80, "EAUTH", "authentication error"}, {81, "ENEEDAUTH", "need authenticator"}, {82, "EIPSEC", "IPsec processing failure"}, {83, "ENOATTR", "attribute not found"}, {84, "EILSEQ", "illegal byte sequence"}, {85, "ENOMEDIUM", "no medium found"}, {86, "EMEDIUMTYPE", "wrong medium type"}, {87, "EOVERFLOW", "value too large to be stored in data type"}, {88, "ECANCELED", "operation canceled"}, {89, "EIDRM", "identifier removed"}, {90, "ENOMSG", "no message of desired type"}, {91, "ENOTSUP", "not supported"}, {92, "EBADMSG", "bad message"}, {93, "ENOTRECOVERABLE", "state not recoverable"}, {94, "EOWNERDEAD", "previous owner died"}, {95, "ELAST", "protocol error"}, } // Signal table var signalList = [...]struct { num syscall.Signal name string desc string }{ {1, "SIGHUP", "hangup"}, {2, "SIGINT", "interrupt"}, {3, "SIGQUIT", "quit"}, {4, "SIGILL", "illegal instruction"}, {5, "SIGTRAP", "trace/BPT trap"}, {6, "SIGABRT", "abort trap"}, {7, "SIGEMT", "EMT trap"}, {8, "SIGFPE", "floating point exception"}, {9, "SIGKILL", "killed"}, {10, "SIGBUS", "bus error"}, {11, "SIGSEGV", "segmentation fault"}, {12, "SIGSYS", "bad system call"}, {13, "SIGPIPE", "broken pipe"}, {14, "SIGALRM", "alarm clock"}, {15, "SIGTERM", "terminated"}, {16, "SIGURG", "urgent I/O condition"}, {17, "SIGSTOP", "suspended (signal)"}, {18, "SIGTSTP", "suspended"}, {19, "SIGCONT", "continued"}, {20, "SIGCHLD", "child exited"}, {21, "SIGTTIN", "stopped (tty input)"}, {22, "SIGTTOU", "stopped (tty output)"}, {23, "SIGIO", "I/O possible"}, {24, "SIGXCPU", "cputime limit exceeded"}, {25, "SIGXFSZ", "filesize limit exceeded"}, {26, "SIGVTALRM", "virtual timer expired"}, {27, "SIGPROF", "profiling timer expired"}, {28, "SIGWINCH", "window size changes"}, {29, "SIGINFO", "information request"}, {30, "SIGUSR1", "user defined signal 1"}, {31, "SIGUSR2", "user defined signal 2"}, {32, "SIGTHR", "thread AST"}, }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dianping.cat.report; import java.io.IOException; import java.util.Collection; import java.util.Date; public interface ReportBucket { /** * Close bucket and release component instance * * @throws IOException */ public void close() throws IOException; /** * Find data by given id in the bucket. return null if not found. * * @param id * @return data for given id, null if not found * @throws IOException */ public String findById(String id) throws IOException; /** * Flush the buffered data in the bucket if have. * * @throws IOException */ public void flush() throws IOException; /** * Return all ids in the bucket. * * @return */ public Collection<String> getIds(); /** * Initialize the bucket after its creation. * * @param name * @param timestamp * @param index * @throws IOException */ public void initialize(String name, Date timestamp, int index) throws IOException; /** * store the data by id into the bucket. * * @param id * @param data * @return true means the data was stored in the bucket, otherwise false. * @throws IOException */ public boolean storeById(String id, String data) throws IOException; }
{ "pile_set_name": "Github" }
// // UIEdgeInsets.swift // FBSnapshotTestCase // // Created by Daniel Huri on 4/21/18. // import UIKit extension UIEdgeInsets { var hasVerticalInsets: Bool { return top > 0 || bottom > 0 } }
{ "pile_set_name": "Github" }
/* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ #ifndef __SGI_STL_MAP #define __SGI_STL_MAP #ifndef __SGI_STL_INTERNAL_TREE_H #include <stl_tree.h> #endif #include <stl_map.h> #include <stl_multimap.h> #endif /* __SGI_STL_MAP */ // Local Variables: // mode:C++ // End:
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-only /****************************************************************************** AudioScience HPI driver Copyright (C) 1997-2014 AudioScience Inc. <[email protected]> \file hpicmn.c Common functions used by hpixxxx.c modules (C) Copyright AudioScience Inc. 1998-2003 *******************************************************************************/ #define SOURCEFILE_NAME "hpicmn.c" #include "hpi_internal.h" #include "hpidebug.h" #include "hpimsginit.h" #include "hpicmn.h" struct hpi_adapters_list { struct hpios_spinlock list_lock; struct hpi_adapter_obj adapter[HPI_MAX_ADAPTERS]; u16 gw_num_adapters; }; static struct hpi_adapters_list adapters; /** * hpi_validate_response - Given an HPI Message that was sent out and * a response that was received, validate that the response has the * correct fields filled in, i.e ObjectType, Function etc * @phm: message * @phr: response */ u16 hpi_validate_response(struct hpi_message *phm, struct hpi_response *phr) { if (phr->type != HPI_TYPE_RESPONSE) { HPI_DEBUG_LOG(ERROR, "header type %d invalid\n", phr->type); return HPI_ERROR_INVALID_RESPONSE; } if (phr->object != phm->object) { HPI_DEBUG_LOG(ERROR, "header object %d invalid\n", phr->object); return HPI_ERROR_INVALID_RESPONSE; } if (phr->function != phm->function) { HPI_DEBUG_LOG(ERROR, "header function %d invalid\n", phr->function); return HPI_ERROR_INVALID_RESPONSE; } return 0; } u16 hpi_add_adapter(struct hpi_adapter_obj *pao) { u16 retval = 0; /*HPI_ASSERT(pao->type); */ hpios_alistlock_lock(&adapters); if (pao->index >= HPI_MAX_ADAPTERS) { retval = HPI_ERROR_BAD_ADAPTER_NUMBER; goto unlock; } if (adapters.adapter[pao->index].type) { int a; for (a = HPI_MAX_ADAPTERS - 1; a >= 0; a--) { if (!adapters.adapter[a].type) { HPI_DEBUG_LOG(WARNING, "ASI%X duplicate index %d moved to %d\n", pao->type, pao->index, a); pao->index = a; break; } } if (a < 0) { retval = HPI_ERROR_DUPLICATE_ADAPTER_NUMBER; goto unlock; } } adapters.adapter[pao->index] = *pao; hpios_dsplock_init(&adapters.adapter[pao->index]); adapters.gw_num_adapters++; unlock: hpios_alistlock_unlock(&adapters); return retval; } void hpi_delete_adapter(struct hpi_adapter_obj *pao) { if (!pao->type) { HPI_DEBUG_LOG(ERROR, "removing null adapter?\n"); return; } hpios_alistlock_lock(&adapters); if (adapters.adapter[pao->index].type) adapters.gw_num_adapters--; memset(&adapters.adapter[pao->index], 0, sizeof(adapters.adapter[0])); hpios_alistlock_unlock(&adapters); } /** * hpi_find_adapter - FindAdapter returns a pointer to the struct * hpi_adapter_obj with index wAdapterIndex in an HPI_ADAPTERS_LIST * structure. * @adapter_index: value in [0, HPI_MAX_ADAPTERS[ */ struct hpi_adapter_obj *hpi_find_adapter(u16 adapter_index) { struct hpi_adapter_obj *pao = NULL; if (adapter_index >= HPI_MAX_ADAPTERS) { HPI_DEBUG_LOG(VERBOSE, "find_adapter invalid index %d\n", adapter_index); return NULL; } pao = &adapters.adapter[adapter_index]; if (pao->type != 0) { /* HPI_DEBUG_LOG(VERBOSE, "Found adapter index %d\n", wAdapterIndex); */ return pao; } else { /* HPI_DEBUG_LOG(VERBOSE, "No adapter index %d\n", wAdapterIndex); */ return NULL; } } /** * wipe_adapter_list - wipe an HPI_ADAPTERS_LIST structure. * */ static void wipe_adapter_list(void) { memset(&adapters, 0, sizeof(adapters)); } static void subsys_get_adapter(struct hpi_message *phm, struct hpi_response *phr) { int count = phm->obj_index; u16 index = 0; /* find the nCount'th nonzero adapter in array */ for (index = 0; index < HPI_MAX_ADAPTERS; index++) { if (adapters.adapter[index].type) { if (!count) break; count--; } } if (index < HPI_MAX_ADAPTERS) { phr->u.s.adapter_index = adapters.adapter[index].index; phr->u.s.adapter_type = adapters.adapter[index].type; } else { phr->u.s.adapter_index = 0; phr->u.s.adapter_type = 0; phr->error = HPI_ERROR_INVALID_OBJ_INDEX; } } static unsigned int control_cache_alloc_check(struct hpi_control_cache *pC) { unsigned int i; int cached = 0; if (!pC) return 0; if (pC->init) return pC->init; if (!pC->p_cache) return 0; if (pC->control_count && pC->cache_size_in_bytes) { char *p_master_cache; unsigned int byte_count = 0; p_master_cache = (char *)pC->p_cache; HPI_DEBUG_LOG(DEBUG, "check %d controls\n", pC->control_count); for (i = 0; i < pC->control_count; i++) { struct hpi_control_cache_info *info = (struct hpi_control_cache_info *) &p_master_cache[byte_count]; u16 control_index = info->control_index; if (control_index >= pC->control_count) { HPI_DEBUG_LOG(INFO, "adap %d control index %d out of range, cache not ready?\n", pC->adap_idx, control_index); return 0; } if (!info->size_in32bit_words) { if (!i) { HPI_DEBUG_LOG(INFO, "adap %d cache not ready?\n", pC->adap_idx); return 0; } /* The cache is invalid. * Minimum valid entry size is * sizeof(struct hpi_control_cache_info) */ HPI_DEBUG_LOG(ERROR, "adap %d zero size cache entry %d\n", pC->adap_idx, i); break; } if (info->control_type) { pC->p_info[control_index] = info; cached++; } else { /* dummy cache entry */ pC->p_info[control_index] = NULL; } byte_count += info->size_in32bit_words * 4; HPI_DEBUG_LOG(VERBOSE, "cached %d, pinfo %p index %d type %d size %d\n", cached, pC->p_info[info->control_index], info->control_index, info->control_type, info->size_in32bit_words); /* quit loop early if whole cache has been scanned. * dwControlCount is the maximum possible entries * but some may be absent from the cache */ if (byte_count >= pC->cache_size_in_bytes) break; /* have seen last control index */ if (info->control_index == pC->control_count - 1) break; } if (byte_count != pC->cache_size_in_bytes) HPI_DEBUG_LOG(WARNING, "adap %d bytecount %d != cache size %d\n", pC->adap_idx, byte_count, pC->cache_size_in_bytes); else HPI_DEBUG_LOG(DEBUG, "adap %d cache good, bytecount == cache size = %d\n", pC->adap_idx, byte_count); pC->init = (u16)cached; } return pC->init; } /** Find a control. */ static short find_control(u16 control_index, struct hpi_control_cache *p_cache, struct hpi_control_cache_info **pI) { if (!control_cache_alloc_check(p_cache)) { HPI_DEBUG_LOG(VERBOSE, "control_cache_alloc_check() failed %d\n", control_index); return 0; } *pI = p_cache->p_info[control_index]; if (!*pI) { HPI_DEBUG_LOG(VERBOSE, "Uncached Control %d\n", control_index); return 0; } else { HPI_DEBUG_LOG(VERBOSE, "find_control() type %d\n", (*pI)->control_type); } return 1; } /* allow unified treatment of several string fields within struct */ #define HPICMN_PAD_OFS_AND_SIZE(m) {\ offsetof(struct hpi_control_cache_pad, m), \ sizeof(((struct hpi_control_cache_pad *)(NULL))->m) } struct pad_ofs_size { unsigned int offset; unsigned int field_size; }; static const struct pad_ofs_size pad_desc[] = { HPICMN_PAD_OFS_AND_SIZE(c_channel), /* HPI_PAD_CHANNEL_NAME */ HPICMN_PAD_OFS_AND_SIZE(c_artist), /* HPI_PAD_ARTIST */ HPICMN_PAD_OFS_AND_SIZE(c_title), /* HPI_PAD_TITLE */ HPICMN_PAD_OFS_AND_SIZE(c_comment), /* HPI_PAD_COMMENT */ }; /** CheckControlCache checks the cache and fills the struct hpi_response * accordingly. It returns one if a cache hit occurred, zero otherwise. */ short hpi_check_control_cache_single(struct hpi_control_cache_single *pC, struct hpi_message *phm, struct hpi_response *phr) { size_t response_size; short found = 1; /* set the default response size */ response_size = sizeof(struct hpi_response_header) + sizeof(struct hpi_control_res); switch (pC->u.i.control_type) { case HPI_CONTROL_METER: if (phm->u.c.attribute == HPI_METER_PEAK) { phr->u.c.an_log_value[0] = pC->u.meter.an_log_peak[0]; phr->u.c.an_log_value[1] = pC->u.meter.an_log_peak[1]; } else if (phm->u.c.attribute == HPI_METER_RMS) { if (pC->u.meter.an_logRMS[0] == HPI_CACHE_INVALID_SHORT) { phr->error = HPI_ERROR_INVALID_CONTROL_ATTRIBUTE; phr->u.c.an_log_value[0] = HPI_METER_MINIMUM; phr->u.c.an_log_value[1] = HPI_METER_MINIMUM; } else { phr->u.c.an_log_value[0] = pC->u.meter.an_logRMS[0]; phr->u.c.an_log_value[1] = pC->u.meter.an_logRMS[1]; } } else found = 0; break; case HPI_CONTROL_VOLUME: if (phm->u.c.attribute == HPI_VOLUME_GAIN) { phr->u.c.an_log_value[0] = pC->u.vol.an_log[0]; phr->u.c.an_log_value[1] = pC->u.vol.an_log[1]; } else if (phm->u.c.attribute == HPI_VOLUME_MUTE) { if (pC->u.vol.flags & HPI_VOLUME_FLAG_HAS_MUTE) { if (pC->u.vol.flags & HPI_VOLUME_FLAG_MUTED) phr->u.c.param1 = HPI_BITMASK_ALL_CHANNELS; else phr->u.c.param1 = 0; } else { phr->error = HPI_ERROR_INVALID_CONTROL_ATTRIBUTE; phr->u.c.param1 = 0; } } else { found = 0; } break; case HPI_CONTROL_MULTIPLEXER: if (phm->u.c.attribute == HPI_MULTIPLEXER_SOURCE) { phr->u.c.param1 = pC->u.mux.source_node_type; phr->u.c.param2 = pC->u.mux.source_node_index; } else { found = 0; } break; case HPI_CONTROL_CHANNEL_MODE: if (phm->u.c.attribute == HPI_CHANNEL_MODE_MODE) phr->u.c.param1 = pC->u.mode.mode; else found = 0; break; case HPI_CONTROL_LEVEL: if (phm->u.c.attribute == HPI_LEVEL_GAIN) { phr->u.c.an_log_value[0] = pC->u.level.an_log[0]; phr->u.c.an_log_value[1] = pC->u.level.an_log[1]; } else found = 0; break; case HPI_CONTROL_TUNER: if (phm->u.c.attribute == HPI_TUNER_FREQ) phr->u.c.param1 = pC->u.tuner.freq_ink_hz; else if (phm->u.c.attribute == HPI_TUNER_BAND) phr->u.c.param1 = pC->u.tuner.band; else if (phm->u.c.attribute == HPI_TUNER_LEVEL_AVG) if (pC->u.tuner.s_level_avg == HPI_CACHE_INVALID_SHORT) { phr->u.cu.tuner.s_level = 0; phr->error = HPI_ERROR_INVALID_CONTROL_ATTRIBUTE; } else phr->u.cu.tuner.s_level = pC->u.tuner.s_level_avg; else found = 0; break; case HPI_CONTROL_AESEBU_RECEIVER: if (phm->u.c.attribute == HPI_AESEBURX_ERRORSTATUS) phr->u.c.param1 = pC->u.aes3rx.error_status; else if (phm->u.c.attribute == HPI_AESEBURX_FORMAT) phr->u.c.param1 = pC->u.aes3rx.format; else found = 0; break; case HPI_CONTROL_AESEBU_TRANSMITTER: if (phm->u.c.attribute == HPI_AESEBUTX_FORMAT) phr->u.c.param1 = pC->u.aes3tx.format; else found = 0; break; case HPI_CONTROL_TONEDETECTOR: if (phm->u.c.attribute == HPI_TONEDETECTOR_STATE) phr->u.c.param1 = pC->u.tone.state; else found = 0; break; case HPI_CONTROL_SILENCEDETECTOR: if (phm->u.c.attribute == HPI_SILENCEDETECTOR_STATE) { phr->u.c.param1 = pC->u.silence.state; } else found = 0; break; case HPI_CONTROL_MICROPHONE: if (phm->u.c.attribute == HPI_MICROPHONE_PHANTOM_POWER) phr->u.c.param1 = pC->u.microphone.phantom_state; else found = 0; break; case HPI_CONTROL_SAMPLECLOCK: if (phm->u.c.attribute == HPI_SAMPLECLOCK_SOURCE) phr->u.c.param1 = pC->u.clk.source; else if (phm->u.c.attribute == HPI_SAMPLECLOCK_SOURCE_INDEX) { if (pC->u.clk.source_index == HPI_CACHE_INVALID_UINT16) { phr->u.c.param1 = 0; phr->error = HPI_ERROR_INVALID_CONTROL_ATTRIBUTE; } else phr->u.c.param1 = pC->u.clk.source_index; } else if (phm->u.c.attribute == HPI_SAMPLECLOCK_SAMPLERATE) phr->u.c.param1 = pC->u.clk.sample_rate; else found = 0; break; case HPI_CONTROL_PAD:{ struct hpi_control_cache_pad *p_pad; p_pad = (struct hpi_control_cache_pad *)pC; if (!(p_pad->field_valid_flags & (1 << HPI_CTL_ATTR_INDEX(phm->u.c. attribute)))) { phr->error = HPI_ERROR_INVALID_CONTROL_ATTRIBUTE; break; } if (phm->u.c.attribute == HPI_PAD_PROGRAM_ID) phr->u.c.param1 = p_pad->pI; else if (phm->u.c.attribute == HPI_PAD_PROGRAM_TYPE) phr->u.c.param1 = p_pad->pTY; else { unsigned int index = HPI_CTL_ATTR_INDEX(phm->u.c. attribute) - 1; unsigned int offset = phm->u.c.param1; unsigned int pad_string_len, field_size; char *pad_string; unsigned int tocopy; if (index > ARRAY_SIZE(pad_desc) - 1) { phr->error = HPI_ERROR_INVALID_CONTROL_ATTRIBUTE; break; } pad_string = ((char *)p_pad) + pad_desc[index].offset; field_size = pad_desc[index].field_size; /* Ensure null terminator */ pad_string[field_size - 1] = 0; pad_string_len = strlen(pad_string) + 1; if (offset > pad_string_len) { phr->error = HPI_ERROR_INVALID_CONTROL_VALUE; break; } tocopy = pad_string_len - offset; if (tocopy > sizeof(phr->u.cu.chars8.sz_data)) tocopy = sizeof(phr->u.cu.chars8. sz_data); memcpy(phr->u.cu.chars8.sz_data, &pad_string[offset], tocopy); phr->u.cu.chars8.remaining_chars = pad_string_len - offset - tocopy; } } break; default: found = 0; break; } HPI_DEBUG_LOG(VERBOSE, "%s Adap %d, Ctl %d, Type %d, Attr %d\n", found ? "Cached" : "Uncached", phm->adapter_index, pC->u.i.control_index, pC->u.i.control_type, phm->u.c.attribute); if (found) { phr->size = (u16)response_size; phr->type = HPI_TYPE_RESPONSE; phr->object = phm->object; phr->function = phm->function; } return found; } short hpi_check_control_cache(struct hpi_control_cache *p_cache, struct hpi_message *phm, struct hpi_response *phr) { struct hpi_control_cache_info *pI; if (!find_control(phm->obj_index, p_cache, &pI)) { HPI_DEBUG_LOG(VERBOSE, "HPICMN find_control() failed for adap %d\n", phm->adapter_index); return 0; } phr->error = 0; phr->specific_error = 0; phr->version = 0; return hpi_check_control_cache_single((struct hpi_control_cache_single *)pI, phm, phr); } /** Updates the cache with Set values. Only update if no error. Volume and Level return the limited values in the response, so use these Multiplexer does so use sent values */ void hpi_cmn_control_cache_sync_to_msg_single(struct hpi_control_cache_single *pC, struct hpi_message *phm, struct hpi_response *phr) { switch (pC->u.i.control_type) { case HPI_CONTROL_VOLUME: if (phm->u.c.attribute == HPI_VOLUME_GAIN) { pC->u.vol.an_log[0] = phr->u.c.an_log_value[0]; pC->u.vol.an_log[1] = phr->u.c.an_log_value[1]; } else if (phm->u.c.attribute == HPI_VOLUME_MUTE) { if (phm->u.c.param1) pC->u.vol.flags |= HPI_VOLUME_FLAG_MUTED; else pC->u.vol.flags &= ~HPI_VOLUME_FLAG_MUTED; } break; case HPI_CONTROL_MULTIPLEXER: /* mux does not return its setting on Set command. */ if (phm->u.c.attribute == HPI_MULTIPLEXER_SOURCE) { pC->u.mux.source_node_type = (u16)phm->u.c.param1; pC->u.mux.source_node_index = (u16)phm->u.c.param2; } break; case HPI_CONTROL_CHANNEL_MODE: /* mode does not return its setting on Set command. */ if (phm->u.c.attribute == HPI_CHANNEL_MODE_MODE) pC->u.mode.mode = (u16)phm->u.c.param1; break; case HPI_CONTROL_LEVEL: if (phm->u.c.attribute == HPI_LEVEL_GAIN) { pC->u.vol.an_log[0] = phr->u.c.an_log_value[0]; pC->u.vol.an_log[1] = phr->u.c.an_log_value[1]; } break; case HPI_CONTROL_MICROPHONE: if (phm->u.c.attribute == HPI_MICROPHONE_PHANTOM_POWER) pC->u.microphone.phantom_state = (u16)phm->u.c.param1; break; case HPI_CONTROL_AESEBU_TRANSMITTER: if (phm->u.c.attribute == HPI_AESEBUTX_FORMAT) pC->u.aes3tx.format = phm->u.c.param1; break; case HPI_CONTROL_AESEBU_RECEIVER: if (phm->u.c.attribute == HPI_AESEBURX_FORMAT) pC->u.aes3rx.format = phm->u.c.param1; break; case HPI_CONTROL_SAMPLECLOCK: if (phm->u.c.attribute == HPI_SAMPLECLOCK_SOURCE) pC->u.clk.source = (u16)phm->u.c.param1; else if (phm->u.c.attribute == HPI_SAMPLECLOCK_SOURCE_INDEX) pC->u.clk.source_index = (u16)phm->u.c.param1; else if (phm->u.c.attribute == HPI_SAMPLECLOCK_SAMPLERATE) pC->u.clk.sample_rate = phm->u.c.param1; break; default: break; } } void hpi_cmn_control_cache_sync_to_msg(struct hpi_control_cache *p_cache, struct hpi_message *phm, struct hpi_response *phr) { struct hpi_control_cache_single *pC; struct hpi_control_cache_info *pI; if (phr->error) return; if (!find_control(phm->obj_index, p_cache, &pI)) { HPI_DEBUG_LOG(VERBOSE, "HPICMN find_control() failed for adap %d\n", phm->adapter_index); return; } /* pC is the default cached control strucure. May be cast to something else in the following switch statement. */ pC = (struct hpi_control_cache_single *)pI; hpi_cmn_control_cache_sync_to_msg_single(pC, phm, phr); } /** Allocate control cache. \return Cache pointer, or NULL if allocation fails. */ struct hpi_control_cache *hpi_alloc_control_cache(const u32 control_count, const u32 size_in_bytes, u8 *p_dsp_control_buffer) { struct hpi_control_cache *p_cache = kmalloc(sizeof(*p_cache), GFP_KERNEL); if (!p_cache) return NULL; p_cache->p_info = kcalloc(control_count, sizeof(*p_cache->p_info), GFP_KERNEL); if (!p_cache->p_info) { kfree(p_cache); return NULL; } p_cache->cache_size_in_bytes = size_in_bytes; p_cache->control_count = control_count; p_cache->p_cache = p_dsp_control_buffer; p_cache->init = 0; return p_cache; } void hpi_free_control_cache(struct hpi_control_cache *p_cache) { if (p_cache) { kfree(p_cache->p_info); kfree(p_cache); } } static void subsys_message(struct hpi_message *phm, struct hpi_response *phr) { hpi_init_response(phr, HPI_OBJ_SUBSYSTEM, phm->function, 0); switch (phm->function) { case HPI_SUBSYS_OPEN: case HPI_SUBSYS_CLOSE: case HPI_SUBSYS_DRIVER_UNLOAD: break; case HPI_SUBSYS_DRIVER_LOAD: wipe_adapter_list(); hpios_alistlock_init(&adapters); break; case HPI_SUBSYS_GET_ADAPTER: subsys_get_adapter(phm, phr); break; case HPI_SUBSYS_GET_NUM_ADAPTERS: phr->u.s.num_adapters = adapters.gw_num_adapters; break; case HPI_SUBSYS_CREATE_ADAPTER: break; default: phr->error = HPI_ERROR_INVALID_FUNC; break; } } void HPI_COMMON(struct hpi_message *phm, struct hpi_response *phr) { switch (phm->type) { case HPI_TYPE_REQUEST: switch (phm->object) { case HPI_OBJ_SUBSYSTEM: subsys_message(phm, phr); break; } break; default: phr->error = HPI_ERROR_INVALID_TYPE; break; } }
{ "pile_set_name": "Github" }
--- layout: base title: 'Statistics of amod in UD_Dutch-Alpino' udver: '2' --- ## Treebank Statistics: UD_Dutch-Alpino: Relations: `amod` This relation is universal. 10242 nodes (5%) are attached to their parents as `amod`. 9820 instances of `amod` (96%) are right-to-left (child precedes parent). Average distance between parent and child is 1.2775825034173. The following 61 pairs of parts of speech are connected with `amod`: <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (7366; 72% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (860; 8% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (746; 7% instances), <tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (260; 3% instances), <tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (96; 1% instances), <tt><a href="nl_alpino-pos-PRON.html">PRON</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (95; 1% instances), <tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (93; 1% instances), <tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (61; 1% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt> (59; 1% instances), <tt><a href="nl_alpino-pos-PRON.html">PRON</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (55; 1% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (53; 1% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (49; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-DET.html">DET</a></tt> (46; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (40; 0% instances), <tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (38; 0% instances), <tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (33; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-PRON.html">PRON</a></tt> (29; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (28; 0% instances), <tt><a href="nl_alpino-pos-X.html">X</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (27; 0% instances), <tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (23; 0% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (19; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-DET.html">DET</a></tt> (18; 0% instances), <tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (14; 0% instances), <tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (14; 0% instances), <tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (11; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt> (11; 0% instances), <tt><a href="nl_alpino-pos-SYM.html">SYM</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (8; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (7; 0% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt> (7; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (7; 0% instances), <tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt>-<tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt> (7; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (6; 0% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-X.html">X</a></tt> (5; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt> (5; 0% instances), <tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (5; 0% instances), <tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt>-<tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt> (3; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt> (3; 0% instances), <tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (3; 0% instances), <tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt>-<tt><a href="nl_alpino-pos-X.html">X</a></tt> (3; 0% instances), <tt><a href="nl_alpino-pos-X.html">X</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (3; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt> (2; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt> (2; 0% instances), <tt><a href="nl_alpino-pos-INTJ.html">INTJ</a></tt>-<tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt> (2; 0% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-DET.html">DET</a></tt> (2; 0% instances), <tt><a href="nl_alpino-pos-SYM.html">SYM</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (2; 0% instances), <tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt>-<tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-ADJ.html">ADJ</a></tt>-<tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt>-<tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-ADV.html">ADV</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-PRON.html">PRON</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-DET.html">DET</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-PRON.html">PRON</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-NOUN.html">NOUN</a></tt>-<tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-NUM.html">NUM</a></tt>-<tt><a href="nl_alpino-pos-X.html">X</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-PRON.html">PRON</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt>-<tt><a href="nl_alpino-pos-PROPN.html">PROPN</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt>-<tt><a href="nl_alpino-pos-ADP.html">ADP</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt>-<tt><a href="nl_alpino-pos-DET.html">DET</a></tt> (1; 0% instances), <tt><a href="nl_alpino-pos-X.html">X</a></tt>-<tt><a href="nl_alpino-pos-VERB.html">VERB</a></tt> (1; 0% instances). ~~~ conllu # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 5 bgColor:blue # visual-style 5 fgColor:white # visual-style 5 4 amod color:blue 1 Gravelbijters gravelbijter NOUN N|soort|mv|basis Number=Plur 2 nsubj 2:nsubj _ 2 kennen kennen VERB WW|pv|tgw|mv Number=Plur|Tense=Pres|VerbForm=Fin 0 root 0:root _ 3 hun hun PRON VNW|bez|det|stan|vol|3|mv|prenom|zonder|agr Person=3|Poss=Yes|PronType=Prs 5 nmod:poss 5:nmod:poss _ 4 eigen eigen ADJ ADJ|prenom|basis|zonder Degree=Pos 5 amod 5:amod _ 5 logica logica NOUN N|soort|ev|basis|zijd|stan Gender=Com|Number=Sing 2 obj 2:obj SpaceAfter=No 6 . . PUNCT LET _ 2 punct 2:punct _ ~~~ ~~~ conllu # visual-style 3 bgColor:blue # visual-style 3 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 3 amod color:blue 1 Maar maar CCONJ VG|neven _ 5 mark 5:mark _ 2 de de DET LID|bep|stan|rest Definite=Def 4 det 4:det _ 3 meeste veel ADV VNW|onbep|grad|stan|prenom|met-e|agr|sup _ 4 amod 4:amod _ 4 pijn pijn NOUN N|soort|ev|basis|zijd|stan Gender=Com|Number=Sing 5 obj 5:obj _ 5 deed doen VERB WW|pv|verl|ev Number=Sing|Tense=Past|VerbForm=Fin 0 root 0:root _ 6 het het DET LID|bep|stan|evon Definite=Def 8 det 8:det _ 7 gedesillusioneerde desillusioneren VERB WW|vd|prenom|met-e VerbForm=Part 8 amod 8:amod _ 8 Oranje Oranje PROPN N|eigen|ev|basis|onz|stan Gender=Neut|Number=Sing 5 nsubj 5:nsubj _ 9 zichzelf zichzelf PRON VNW|refl|pron|obl|nadr|3|getal Case=Acc|Person=3|PronType=Prs|Reflex=Yes 5 iobj 5:iobj SpaceAfter=No 10 . . PUNCT LET _ 5 punct 5:punct _ ~~~ ~~~ conllu # visual-style 6 bgColor:blue # visual-style 6 fgColor:white # visual-style 7 bgColor:blue # visual-style 7 fgColor:white # visual-style 7 6 amod color:blue 1 Nederland Nederland PROPN N|eigen|ev|basis|onz|stan Gender=Neut|Number=Sing 9 nsubj 9:nsubj _ 2 kon kunnen AUX WW|pv|verl|ev Number=Sing|Tense=Past|VerbForm=Fin 9 aux 9:aux _ 3 er er ADV VNW|aanw|adv-pron|stan|red|3|getal _ 9 obl 9:obl:tegenover _ 4 zelden zelden ADV BW _ 9 advmod 9:advmod _ 5 een een DET LID|onbep|stan|agr Definite=Ind 7 det 7:det _ 6 vloeiende vloeien VERB WW|od|prenom|met-e VerbForm=Part 7 amod 7:amod _ 7 aanval aanval NOUN N|soort|ev|basis|zijd|stan Gender=Com|Number=Sing 9 obj 9:obj _ 8 tegenover tegenover ADP VZ|fin _ 3 case 3:case _ 9 stellen stellen VERB WW|inf|vrij|zonder VerbForm=Inf 0 root 0:root SpaceAfter=No 10 . . PUNCT LET _ 9 punct 9:punct _ ~~~
{ "pile_set_name": "Github" }
/* * The RSA public-key cryptosystem * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: GPL-2.0 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This file is part of mbed TLS (https://tls.mbed.org) */ /* * The following sources were referenced in the design of this implementation * of the RSA algorithm: * * [1] A method for obtaining digital signatures and public-key cryptosystems * R Rivest, A Shamir, and L Adleman * http://people.csail.mit.edu/rivest/pubs.html#RSA78 * * [2] Handbook of Applied Cryptography - 1997, Chapter 8 * Menezes, van Oorschot and Vanstone * * [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks * Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and * Stefan Mangard * https://arxiv.org/abs/1702.08719v2 * */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_RSA_C) #include "mbedtls/rsa.h" #include "mbedtls/rsa_internal.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_PKCS1_V21) #include "mbedtls/md.h" #endif #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) #include <stdlib.h> #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #define mbedtls_calloc calloc #define mbedtls_free free #endif #if !defined(MBEDTLS_RSA_ALT) #if defined(MBEDTLS_PKCS1_V15) /* constant-time buffer comparison */ static inline int mbedtls_safer_memcmp(const void *a, const void *b, size_t n) { size_t i; const unsigned char *A = (const unsigned char *) a; const unsigned char *B = (const unsigned char *) b; unsigned char diff = 0; for (i = 0; i < n; i++) diff |= A[i] ^ B[i]; return (diff); } #endif /* MBEDTLS_PKCS1_V15 */ int mbedtls_rsa_import(mbedtls_rsa_context *ctx, const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E) { int ret; if ((N != NULL && (ret = mbedtls_mpi_copy(&ctx->N, N)) != 0) || (P != NULL && (ret = mbedtls_mpi_copy(&ctx->P, P)) != 0) || (Q != NULL && (ret = mbedtls_mpi_copy(&ctx->Q, Q)) != 0) || (D != NULL && (ret = mbedtls_mpi_copy(&ctx->D, D)) != 0) || (E != NULL && (ret = mbedtls_mpi_copy(&ctx->E, E)) != 0)) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); } if (N != NULL) ctx->len = mbedtls_mpi_size(&ctx->N); return (0); } int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx, unsigned char const *N, size_t N_len, unsigned char const *P, size_t P_len, unsigned char const *Q, size_t Q_len, unsigned char const *D, size_t D_len, unsigned char const *E, size_t E_len) { int ret = 0; if (N != NULL) { MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->N, N, N_len)); ctx->len = mbedtls_mpi_size(&ctx->N); } if (P != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->P, P, P_len)); if (Q != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->Q, Q, Q_len)); if (D != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->D, D, D_len)); if (E != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->E, E, E_len)); cleanup: if (ret != 0) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); return (0); } /* * Checks whether the context fields are set in such a way * that the RSA primitives will be able to execute without error. * It does *not* make guarantees for consistency of the parameters. */ static int rsa_check_context(mbedtls_rsa_context const *ctx, int is_priv, int blinding_needed) { #if !defined(MBEDTLS_RSA_NO_CRT) /* blinding_needed is only used for NO_CRT to decide whether * P,Q need to be present or not. */ ((void) blinding_needed); #endif if (ctx->len != mbedtls_mpi_size(&ctx->N) || ctx->len > MBEDTLS_MPI_MAX_SIZE) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } /* * 1. Modular exponentiation needs positive, odd moduli. */ /* Modular exponentiation wrt. N is always used for * RSA public key operations. */ if (mbedtls_mpi_cmp_int(&ctx->N, 0) <= 0 || mbedtls_mpi_get_bit(&ctx->N, 0) == 0) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } #if !defined(MBEDTLS_RSA_NO_CRT) /* Modular exponentiation for P and Q is only * used for private key operations and if CRT * is used. */ if (is_priv && (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 || mbedtls_mpi_get_bit(&ctx->P, 0) == 0 || mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0 || mbedtls_mpi_get_bit(&ctx->Q, 0) == 0)) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } #endif /* !MBEDTLS_RSA_NO_CRT */ /* * 2. Exponents must be positive */ /* Always need E for public key operations */ if (mbedtls_mpi_cmp_int(&ctx->E, 0) <= 0) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); #if defined(MBEDTLS_RSA_NO_CRT) /* For private key operations, use D or DP & DQ * as (unblinded) exponents. */ if (is_priv && mbedtls_mpi_cmp_int(&ctx->D, 0) <= 0) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); #else if (is_priv && (mbedtls_mpi_cmp_int(&ctx->DP, 0) <= 0 || mbedtls_mpi_cmp_int(&ctx->DQ, 0) <= 0)) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } #endif /* MBEDTLS_RSA_NO_CRT */ /* Blinding shouldn't make exponents negative either, * so check that P, Q >= 1 if that hasn't yet been * done as part of 1. */ #if defined(MBEDTLS_RSA_NO_CRT) if (is_priv && blinding_needed && (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 || mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0)) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } #endif /* It wouldn't lead to an error if it wasn't satisfied, * but check for QP >= 1 nonetheless. */ #if !defined(MBEDTLS_RSA_NO_CRT) if (is_priv && mbedtls_mpi_cmp_int(&ctx->QP, 0) <= 0) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } #endif return (0); } int mbedtls_rsa_complete(mbedtls_rsa_context *ctx) { int ret = 0; const int have_N = (mbedtls_mpi_cmp_int(&ctx->N, 0) != 0); const int have_P = (mbedtls_mpi_cmp_int(&ctx->P, 0) != 0); const int have_Q = (mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0); const int have_D = (mbedtls_mpi_cmp_int(&ctx->D, 0) != 0); const int have_E = (mbedtls_mpi_cmp_int(&ctx->E, 0) != 0); /* * Check whether provided parameters are enough * to deduce all others. The following incomplete * parameter sets for private keys are supported: * * (1) P, Q missing. * (2) D and potentially N missing. * */ const int n_missing = have_P && have_Q && have_D && have_E; const int pq_missing = have_N && !have_P && !have_Q && have_D && have_E; const int d_missing = have_P && have_Q && !have_D && have_E; const int is_pub = have_N && !have_P && !have_Q && !have_D && have_E; /* These three alternatives are mutually exclusive */ const int is_priv = n_missing || pq_missing || d_missing; if (!is_priv && !is_pub) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); /* * Step 1: Deduce N if P, Q are provided. */ if (!have_N && have_P && have_Q) { if ((ret = mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q)) != 0) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); } ctx->len = mbedtls_mpi_size(&ctx->N); } /* * Step 2: Deduce and verify all remaining core parameters. */ if (pq_missing) { ret = mbedtls_rsa_deduce_primes(&ctx->N, &ctx->E, &ctx->D, &ctx->P, &ctx->Q); if (ret != 0) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); } else if (d_missing) { if ((ret = mbedtls_rsa_deduce_private_exponent(&ctx->P, &ctx->Q, &ctx->E, &ctx->D)) != 0) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); } } /* * Step 3: Deduce all additional parameters specific * to our current RSA implementation. */ #if !defined(MBEDTLS_RSA_NO_CRT) if (is_priv) { ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP); if (ret != 0) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); } #endif /* MBEDTLS_RSA_NO_CRT */ /* * Step 3: Basic sanity checks */ return (rsa_check_context(ctx, is_priv, 1)); } int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx, unsigned char *N, size_t N_len, unsigned char *P, size_t P_len, unsigned char *Q, size_t Q_len, unsigned char *D, size_t D_len, unsigned char *E, size_t E_len) { int ret = 0; /* Check if key is private or public */ const int is_priv = mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->E, 0) != 0; if (!is_priv) { /* If we're trying to export private parameters for a public key, * something must be wrong. */ if (P != NULL || Q != NULL || D != NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } if (N != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->N, N, N_len)); if (P != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->P, P, P_len)); if (Q != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->Q, Q, Q_len)); if (D != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->D, D, D_len)); if (E != NULL) MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->E, E, E_len)); cleanup: return (ret); } int mbedtls_rsa_export(const mbedtls_rsa_context *ctx, mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q, mbedtls_mpi *D, mbedtls_mpi *E) { int ret; /* Check if key is private or public */ int is_priv = mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->E, 0) != 0; if (!is_priv) { /* If we're trying to export private parameters for a public key, * something must be wrong. */ if (P != NULL || Q != NULL || D != NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } /* Export all requested core parameters. */ if ((N != NULL && (ret = mbedtls_mpi_copy(N, &ctx->N)) != 0) || (P != NULL && (ret = mbedtls_mpi_copy(P, &ctx->P)) != 0) || (Q != NULL && (ret = mbedtls_mpi_copy(Q, &ctx->Q)) != 0) || (D != NULL && (ret = mbedtls_mpi_copy(D, &ctx->D)) != 0) || (E != NULL && (ret = mbedtls_mpi_copy(E, &ctx->E)) != 0)) { return (ret); } return (0); } /* * Export CRT parameters * This must also be implemented if CRT is not used, for being able to * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt * can be used in this case. */ int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP) { int ret; /* Check if key is private or public */ int is_priv = mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 && mbedtls_mpi_cmp_int(&ctx->E, 0) != 0; if (!is_priv) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); #if !defined(MBEDTLS_RSA_NO_CRT) /* Export all requested blinding parameters. */ if ((DP != NULL && (ret = mbedtls_mpi_copy(DP, &ctx->DP)) != 0) || (DQ != NULL && (ret = mbedtls_mpi_copy(DQ, &ctx->DQ)) != 0) || (QP != NULL && (ret = mbedtls_mpi_copy(QP, &ctx->QP)) != 0)) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); } #else if ((ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D, DP, DQ, QP)) != 0) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret); } #endif return (0); } /* * Initialize an RSA context */ void mbedtls_rsa_init(mbedtls_rsa_context *ctx, int padding, int hash_id) { memset(ctx, 0, sizeof(mbedtls_rsa_context)); mbedtls_rsa_set_padding(ctx, padding, hash_id); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_init(&ctx->mutex); #endif } /* * Set padding for an existing RSA context */ void mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding, int hash_id) { ctx->padding = padding; ctx->hash_id = hash_id; } /* * Get length in bytes of RSA modulus */ size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx) { return (ctx->len); } #if defined(MBEDTLS_GENPRIME) /* * Generate an RSA keypair * * This generation method follows the RSA key pair generation procedure of * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072. */ int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, unsigned int nbits, int exponent) { int ret; mbedtls_mpi H, G, L; if (f_rng == NULL || nbits < 128 || exponent < 3) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); if (nbits % 2) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); mbedtls_mpi_init(&H); mbedtls_mpi_init(&G); mbedtls_mpi_init(&L); /* * find primes P and Q with Q < P so that: * 1. |P-Q| > 2^( nbits / 2 - 100 ) * 2. GCD( E, (P-1)*(Q-1) ) == 1 * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 ) */ MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent)); do { MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1, 0, f_rng, p_rng)); MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1, 0, f_rng, p_rng)); /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */ MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q)); if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) continue; /* not required by any standards, but some users rely on the fact that P > Q */ if (H.s < 0) mbedtls_mpi_swap(&ctx->P, &ctx->Q); /* Temporarily replace P,Q by P-1, Q-1 */ MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->P, &ctx->P, 1)); MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->Q, &ctx->Q, 1)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&H, &ctx->P, &ctx->Q)); /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */ MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->E, &H)); if (mbedtls_mpi_cmp_int(&G, 1) != 0) continue; /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */ MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->P, &ctx->Q)); MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&L, NULL, &H, &G)); MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->D, &ctx->E, &L)); if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) // (FIPS 186-4 §B.3.1 criterion 3(a)) continue; break; } while (1); /* Restore P,Q */ MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->P, &ctx->P, 1)); MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->Q, &ctx->Q, 1)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q)); ctx->len = mbedtls_mpi_size(&ctx->N); #if !defined(MBEDTLS_RSA_NO_CRT) /* * DP = D mod (P - 1) * DQ = D mod (Q - 1) * QP = Q^-1 mod P */ MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP)); #endif /* MBEDTLS_RSA_NO_CRT */ /* Double-check */ MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx)); cleanup: mbedtls_mpi_free(&H); mbedtls_mpi_free(&G); mbedtls_mpi_free(&L); if (ret != 0) { mbedtls_rsa_free(ctx); return (MBEDTLS_ERR_RSA_KEY_GEN_FAILED + ret); } return (0); } #endif /* MBEDTLS_GENPRIME */ /* * Check a public RSA key */ int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx) { if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); if (mbedtls_mpi_bitlen(&ctx->N) < 128) { return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); } if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 || mbedtls_mpi_bitlen(&ctx->E) < 2 || mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) { return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); } return (0); } /* * Check for the consistency of all fields in an RSA private key context */ int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx) { if (mbedtls_rsa_check_pubkey(ctx) != 0 || rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) { return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); } if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q, &ctx->D, &ctx->E, NULL, NULL) != 0) { return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); } #if !defined(MBEDTLS_RSA_NO_CRT) else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP) != 0) { return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); } #endif return (0); } /* * Check if contexts holding a public and private key match */ int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv) { if (mbedtls_rsa_check_pubkey(pub) != 0 || mbedtls_rsa_check_privkey(prv) != 0) { return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); } if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 || mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) { return (MBEDTLS_ERR_RSA_KEY_CHECK_FAILED); } return (0); } /* * Do an RSA public key operation */ int mbedtls_rsa_public(mbedtls_rsa_context *ctx, const unsigned char *input, unsigned char *output) { int ret; size_t olen; mbedtls_mpi T; if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); mbedtls_mpi_init(&T); #if defined(MBEDTLS_THREADING_C) if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) return (ret); #endif MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len)); if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } olen = ctx->len; MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &ctx->E, &ctx->N, &ctx->RN)); MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen)); cleanup: #if defined(MBEDTLS_THREADING_C) if (mbedtls_mutex_unlock(&ctx->mutex) != 0) return (MBEDTLS_ERR_THREADING_MUTEX_ERROR); #endif mbedtls_mpi_free(&T); if (ret != 0) return (MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret); return (0); } /* * Generate or update blinding values, see section 10 of: * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA, * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer * Berlin Heidelberg, 1996. p. 104-113. */ static int rsa_prepare_blinding(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) { int ret, count = 0; if (ctx->Vf.p != NULL) { /* We already have blinding values, just update them by squaring */ MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi)); MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf)); MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N)); goto cleanup; } /* Unblinding value: Vf = random number, invertible mod N */ do { if (count++ > 10) return (MBEDTLS_ERR_RSA_RNG_FAILED); MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->Vf, ctx->len - 1, f_rng, p_rng)); MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&ctx->Vi, &ctx->Vf, &ctx->N)); } while (mbedtls_mpi_cmp_int(&ctx->Vi, 1) != 0); /* Blinding value: Vi = Vf^(-e) mod N */ MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->Vi, &ctx->Vf, &ctx->N)); MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN)); cleanup: return (ret); } /* * Exponent blinding supposed to prevent side-channel attacks using multiple * traces of measurements to recover the RSA key. The more collisions are there, * the more bits of the key can be recovered. See [3]. * * Collecting n collisions with m bit long blinding value requires 2^(m-m/n) * observations on avarage. * * For example with 28 byte blinding to achieve 2 collisions the adversary has * to make 2^112 observations on avarage. * * (With the currently (as of 2017 April) known best algorithms breaking 2048 * bit RSA requires approximately as much time as trying out 2^112 random keys. * Thus in this sense with 28 byte blinding the security is not reduced by * side-channel attacks like the one in [3]) * * This countermeasure does not help if the key recovery is possible with a * single trace. */ #define RSA_EXPONENT_BLINDING 28 /* * Do an RSA private key operation */ int mbedtls_rsa_private(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, const unsigned char *input, unsigned char *output) { int ret; size_t olen; /* Temporary holding the result */ mbedtls_mpi T; /* Temporaries holding P-1, Q-1 and the * exponent blinding factor, respectively. */ mbedtls_mpi P1, Q1, R; #if !defined(MBEDTLS_RSA_NO_CRT) /* Temporaries holding the results mod p resp. mod q. */ mbedtls_mpi TP, TQ; /* Temporaries holding the blinded exponents for * the mod p resp. mod q computation (if used). */ mbedtls_mpi DP_blind, DQ_blind; /* Pointers to actual exponents to be used - either the unblinded * or the blinded ones, depending on the presence of a PRNG. */ mbedtls_mpi *DP = &ctx->DP; mbedtls_mpi *DQ = &ctx->DQ; #else /* Temporary holding the blinded exponent (if used). */ mbedtls_mpi D_blind; /* Pointer to actual exponent to be used - either the unblinded * or the blinded one, depending on the presence of a PRNG. */ mbedtls_mpi *D = &ctx->D; #endif /* MBEDTLS_RSA_NO_CRT */ /* Temporaries holding the initial input and the double * checked result; should be the same in the end. */ mbedtls_mpi I, C; if (rsa_check_context(ctx, 1 /* private key checks */, f_rng != NULL /* blinding y/n */) != 0) { return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } #if defined(MBEDTLS_THREADING_C) if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) return (ret); #endif /* MPI Initialization */ mbedtls_mpi_init(&T); mbedtls_mpi_init(&P1); mbedtls_mpi_init(&Q1); mbedtls_mpi_init(&R); if (f_rng != NULL) { #if defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_init(&D_blind); #else mbedtls_mpi_init(&DP_blind); mbedtls_mpi_init(&DQ_blind); #endif } #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ); #endif mbedtls_mpi_init(&I); mbedtls_mpi_init(&C); /* End of MPI initialization */ MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len)); if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&I, &T)); if (f_rng != NULL) { /* * Blinding * T = T * Vi mod N */ MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi)); MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N)); /* * Exponent blinding */ MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1)); MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1)); #if defined(MBEDTLS_RSA_NO_CRT) /* * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D */ MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING, f_rng, p_rng)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R)); MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D)); D = &D_blind; #else /* * DP_blind = ( P - 1 ) * R + DP */ MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING, f_rng, p_rng)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R)); MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind, &ctx->DP)); DP = &DP_blind; /* * DQ_blind = ( Q - 1 ) * R + DQ */ MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING, f_rng, p_rng)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R)); MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind, &ctx->DQ)); DQ = &DQ_blind; #endif /* MBEDTLS_RSA_NO_CRT */ } #if defined(MBEDTLS_RSA_NO_CRT) MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, D, &ctx->N, &ctx->RN)); #else /* * Faster decryption using the CRT * * TP = input ^ dP mod P * TQ = input ^ dQ mod Q */ MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, DP, &ctx->P, &ctx->RP)); MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, DQ, &ctx->Q, &ctx->RQ)); /* * T = (TP - TQ) * (Q^-1 mod P) mod P */ MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ)); MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP)); MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P)); /* * T = TQ + T * Q */ MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q)); MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP)); #endif /* MBEDTLS_RSA_NO_CRT */ if (f_rng != NULL) { /* * Unblind * T = T * Vf mod N */ MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vf)); MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N)); } /* Verify the result to prevent glitching attacks. */ MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&C, &T, &ctx->E, &ctx->N, &ctx->RN)); if (mbedtls_mpi_cmp_mpi(&C, &I) != 0) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto cleanup; } olen = ctx->len; MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen)); cleanup: #if defined(MBEDTLS_THREADING_C) if (mbedtls_mutex_unlock(&ctx->mutex) != 0) return (MBEDTLS_ERR_THREADING_MUTEX_ERROR); #endif mbedtls_mpi_free(&P1); mbedtls_mpi_free(&Q1); mbedtls_mpi_free(&R); if (f_rng != NULL) { #if defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free(&D_blind); #else mbedtls_mpi_free(&DP_blind); mbedtls_mpi_free(&DQ_blind); #endif } mbedtls_mpi_free(&T); #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ); #endif mbedtls_mpi_free(&C); mbedtls_mpi_free(&I); if (ret != 0) return (MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret); return (0); } #if defined(MBEDTLS_PKCS1_V21) /** * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer. * * \param dst buffer to mask * \param dlen length of destination buffer * \param src source of the mask generation * \param slen length of the source buffer * \param md_ctx message digest context to use */ static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src, size_t slen, mbedtls_md_context_t *md_ctx) { unsigned char mask[MBEDTLS_MD_MAX_SIZE]; unsigned char counter[4]; unsigned char *p; unsigned int hlen; size_t i, use_len; int ret = 0; memset(mask, 0, MBEDTLS_MD_MAX_SIZE); memset(counter, 0, 4); hlen = mbedtls_md_get_size(md_ctx->md_info); /* Generate and apply dbMask */ p = dst; while (dlen > 0) { use_len = hlen; if (dlen < hlen) use_len = dlen; if ((ret = mbedtls_md_starts(md_ctx)) != 0) goto exit; if ((ret = mbedtls_md_update(md_ctx, src, slen)) != 0) goto exit; if ((ret = mbedtls_md_update(md_ctx, counter, 4)) != 0) goto exit; if ((ret = mbedtls_md_finish(md_ctx, mask)) != 0) goto exit; for (i = 0; i < use_len; ++i) *p++ ^= mask[i]; counter[3]++; dlen -= use_len; } exit: mbedtls_platform_zeroize(mask, sizeof(mask)); return (ret); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function */ int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t ilen, const unsigned char *input, unsigned char *output) { size_t olen; int ret; unsigned char *p = output; unsigned int hlen; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); if (f_rng == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); md_info = mbedtls_md_info_from_type((mbedtls_md_type_t) ctx->hash_id); if (md_info == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); olen = ctx->len; hlen = mbedtls_md_get_size(md_info); /* first comparison checks for overflow */ if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); memset(output, 0, olen); *p++ = 0; /* Generate a random octet string seed */ if ((ret = f_rng(p_rng, p, hlen)) != 0) return (MBEDTLS_ERR_RSA_RNG_FAILED + ret); p += hlen; /* Construct DB */ if ((ret = mbedtls_md(md_info, label, label_len, p)) != 0) return (ret); p += hlen; p += olen - 2 * hlen - 2 - ilen; *p++ = 1; memcpy(p, input, ilen); mbedtls_md_init(&md_ctx); if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) goto exit; /* maskedDB: Apply dbMask to DB */ if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen, &md_ctx)) != 0) goto exit; /* maskedSeed: Apply seedMask to seed */ if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1, &md_ctx)) != 0) goto exit; exit: mbedtls_md_free(&md_ctx); if (ret != 0) return (ret); return ((mode == MBEDTLS_RSA_PUBLIC) ? mbedtls_rsa_public(ctx, output, output) : mbedtls_rsa_private(ctx, f_rng, p_rng, output, output)); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function */ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output) { size_t nb_pad, olen; int ret; unsigned char *p = output; if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); // We don't check p_rng because it won't be dereferenced here if (f_rng == NULL || input == NULL || output == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); olen = ctx->len; /* first comparison checks for overflow */ if (ilen + 11 < ilen || olen < ilen + 11) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); nb_pad = olen - 3 - ilen; *p++ = 0; if (mode == MBEDTLS_RSA_PUBLIC) { *p++ = MBEDTLS_RSA_CRYPT; while (nb_pad-- > 0) { int rng_dl = 100; do { ret = f_rng(p_rng, p, 1); } while (*p == 0 && --rng_dl && ret == 0); /* Check if RNG failed to generate data */ if (rng_dl == 0 || ret != 0) return (MBEDTLS_ERR_RSA_RNG_FAILED + ret); p++; } } else { *p++ = MBEDTLS_RSA_SIGN; while (nb_pad-- > 0) *p++ = 0xFF; } *p++ = 0; memcpy(p, input, ilen); return ((mode == MBEDTLS_RSA_PUBLIC) ? mbedtls_rsa_public(ctx, output, output) : mbedtls_rsa_private(ctx, f_rng, p_rng, output, output)); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Add the message padding, then do an RSA operation */ int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output) { switch (ctx->padding) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng, mode, ilen, input, output); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, mode, NULL, 0, ilen, input, output); #endif default: return (MBEDTLS_ERR_RSA_INVALID_PADDING); } } #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function */ int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len) { int ret; size_t ilen, i, pad_len; unsigned char *p, bad, pad_done; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; unsigned char lhash[MBEDTLS_MD_MAX_SIZE]; unsigned int hlen; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; /* * Parameters sanity checks */ if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); ilen = ctx->len; if (ilen < 16 || ilen > sizeof(buf)) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); md_info = mbedtls_md_info_from_type((mbedtls_md_type_t) ctx->hash_id); if (md_info == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); hlen = mbedtls_md_get_size(md_info); // checking for integer underflow if (2 * hlen + 2 > ilen) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); /* * RSA operation */ ret = (mode == MBEDTLS_RSA_PUBLIC) ? mbedtls_rsa_public(ctx, input, buf) : mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf); if (ret != 0) goto cleanup; /* * Unmask data and generate lHash */ mbedtls_md_init(&md_ctx); if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) { mbedtls_md_free(&md_ctx); goto cleanup; } /* seed: Apply seedMask to maskedSeed */ if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1, &md_ctx)) != 0 || /* DB: Apply dbMask to maskedDB */ (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen, &md_ctx)) != 0) { mbedtls_md_free(&md_ctx); goto cleanup; } mbedtls_md_free(&md_ctx); /* Generate lHash */ if ((ret = mbedtls_md(md_info, label, label_len, lhash)) != 0) goto cleanup; /* * Check contents, in "constant-time" */ p = buf; bad = 0; bad |= *p++; /* First byte must be 0 */ p += hlen; /* Skip seed */ /* Check lHash */ for (i = 0; i < hlen; i++) bad |= lhash[i] ^ *p++; /* Get zero-padding len, but always read till end of buffer * (minus one, for the 01 byte) */ pad_len = 0; pad_done = 0; for (i = 0; i < ilen - 2 * hlen - 2; i++) { pad_done |= p[i]; pad_len += ((pad_done | (unsigned char) - pad_done) >> 7) ^ 1; } p += pad_len; bad |= *p++ ^ 0x01; /* * The only information "leaked" is whether the padding was correct or not * (eg, no data is copied if it was not correct). This meets the * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between * the different error conditions. */ if (bad != 0) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto cleanup; } if (ilen - (p - buf) > output_max_len) { ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE; goto cleanup; } *olen = ilen - (p - buf); memcpy(output, p, *olen); ret = 0; cleanup: mbedtls_platform_zeroize(buf, sizeof(buf)); mbedtls_platform_zeroize(lhash, sizeof(lhash)); return (ret); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function */ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len) { int ret; size_t ilen, pad_count = 0, i; unsigned char *p, bad, pad_done = 0; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); ilen = ctx->len; if (ilen < 16 || ilen > sizeof(buf)) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); ret = (mode == MBEDTLS_RSA_PUBLIC) ? mbedtls_rsa_public(ctx, input, buf) : mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf); if (ret != 0) goto cleanup; p = buf; bad = 0; /* * Check and get padding len in "constant-time" */ bad |= *p++; /* First byte must be 0 */ /* This test does not depend on secret data */ if (mode == MBEDTLS_RSA_PRIVATE) { bad |= *p++ ^ MBEDTLS_RSA_CRYPT; /* Get padding len, but always read till end of buffer * (minus one, for the 00 byte) */ for (i = 0; i < ilen - 3; i++) { pad_done |= ((p[i] | (unsigned char) - p[i]) >> 7) ^ 1; pad_count += ((pad_done | (unsigned char) - pad_done) >> 7) ^ 1; } p += pad_count; bad |= *p++; /* Must be zero */ } else { bad |= *p++ ^ MBEDTLS_RSA_SIGN; /* Get padding len, but always read till end of buffer * (minus one, for the 00 byte) */ for (i = 0; i < ilen - 3; i++) { pad_done |= (p[i] != 0xFF); pad_count += (pad_done == 0); } p += pad_count; bad |= *p++; /* Must be zero */ } bad |= (pad_count < 8); if (bad) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto cleanup; } if (ilen - (p - buf) > output_max_len) { ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE; goto cleanup; } *olen = ilen - (p - buf); memcpy(output, p, *olen); ret = 0; cleanup: mbedtls_platform_zeroize(buf, sizeof(buf)); return (ret); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation, then remove the message padding */ int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len) { switch (ctx->padding) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, mode, olen, input, output, output_max_len); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, mode, NULL, 0, olen, input, output, output_max_len); #endif default: return (MBEDTLS_ERR_RSA_INVALID_PADDING); } } #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function */ int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig) { size_t olen; unsigned char *p = sig; unsigned char salt[MBEDTLS_MD_MAX_SIZE]; unsigned int slen, hlen, offset = 0; int ret; size_t msb; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); if (f_rng == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); olen = ctx->len; if (md_alg != MBEDTLS_MD_NONE) { /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type(md_alg); if (md_info == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); hashlen = mbedtls_md_get_size(md_info); } md_info = mbedtls_md_info_from_type((mbedtls_md_type_t) ctx->hash_id); if (md_info == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); hlen = mbedtls_md_get_size(md_info); slen = hlen; if (olen < hlen + slen + 2) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); memset(sig, 0, olen); /* Generate salt of length slen */ if ((ret = f_rng(p_rng, salt, slen)) != 0) return (MBEDTLS_ERR_RSA_RNG_FAILED + ret); /* Note: EMSA-PSS encoding is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen(&ctx->N) - 1; p += olen - hlen * 2 - 2; *p++ = 0x01; memcpy(p, salt, slen); p += slen; mbedtls_md_init(&md_ctx); if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) goto exit; /* Generate H = Hash( M' ) */ if ((ret = mbedtls_md_starts(&md_ctx)) != 0) goto exit; if ((ret = mbedtls_md_update(&md_ctx, p, 8)) != 0) goto exit; if ((ret = mbedtls_md_update(&md_ctx, hash, hashlen)) != 0) goto exit; if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) goto exit; if ((ret = mbedtls_md_finish(&md_ctx, p)) != 0) goto exit; /* Compensate for boundary condition when applying mask */ if (msb % 8 == 0) offset = 1; /* maskedDB: Apply dbMask to DB */ if ((ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx)) != 0) goto exit; msb = mbedtls_mpi_bitlen(&ctx->N) - 1; sig[0] &= 0xFF >> (olen * 8 - msb); p += hlen; *p++ = 0xBC; mbedtls_platform_zeroize(salt, sizeof(salt)); exit: mbedtls_md_free(&md_ctx); if (ret != 0) return (ret); return ((mode == MBEDTLS_RSA_PUBLIC) ? mbedtls_rsa_public(ctx, sig, sig) : mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig)); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function */ /* Construct a PKCS v1.5 encoding of a hashed message * * This is used both for signature generation and verification. * * Parameters: * - md_alg: Identifies the hash algorithm used to generate the given hash; * MBEDTLS_MD_NONE if raw data is signed. * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE. * - hash: Buffer containing the hashed message or the raw data. * - dst_len: Length of the encoded message. * - dst: Buffer to hold the encoded message. * * Assumptions: * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE. * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE. * - dst points to a buffer of size at least dst_len. * */ static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, size_t dst_len, unsigned char *dst) { size_t oid_size = 0; size_t nb_pad = dst_len; unsigned char *p = dst; const char *oid = NULL; /* Are we signing hashed or raw data? */ if (md_alg != MBEDTLS_MD_NONE) { const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg); if (md_info == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); hashlen = mbedtls_md_get_size(md_info); /* Double-check that 8 + hashlen + oid_size can be used as a * 1-byte ASN.1 length encoding and that there's no overflow. */ if (8 + hashlen + oid_size >= 0x80 || 10 + hashlen < hashlen || 10 + hashlen + oid_size < 10 + hashlen) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); /* * Static bounds check: * - Need 10 bytes for five tag-length pairs. * (Insist on 1-byte length encodings to protect against variants of * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification) * - Need hashlen bytes for hash * - Need oid_size bytes for hash alg OID. */ if (nb_pad < 10 + hashlen + oid_size) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); nb_pad -= 10 + hashlen + oid_size; } else { if (nb_pad < hashlen) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); nb_pad -= hashlen; } /* Need space for signature header and padding delimiter (3 bytes), * and 8 bytes for the minimal padding */ if (nb_pad < 3 + 8) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); nb_pad -= 3; /* Now nb_pad is the amount of memory to be filled * with padding, and at least 8 bytes long. */ /* Write signature header and padding */ *p++ = 0; *p++ = MBEDTLS_RSA_SIGN; memset(p, 0xFF, nb_pad); p += nb_pad; *p++ = 0; /* Are we signing raw data? */ if (md_alg == MBEDTLS_MD_NONE) { memcpy(p, hash, hashlen); return (0); } /* Signing hashed data, add corresponding ASN.1 structure * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest } * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * Schematic: * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ] * TAG-NULL + LEN [ NULL ] ] * TAG-OCTET + LEN [ HASH ] ] */ *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; *p++ = (unsigned char)(0x08 + oid_size + hashlen); *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; *p++ = (unsigned char)(0x04 + oid_size); *p++ = MBEDTLS_ASN1_OID; *p++ = (unsigned char) oid_size; memcpy(p, oid, oid_size); p += oid_size; *p++ = MBEDTLS_ASN1_NULL; *p++ = 0x00; *p++ = MBEDTLS_ASN1_OCTET_STRING; *p++ = (unsigned char) hashlen; memcpy(p, hash, hashlen); p += hashlen; /* Just a sanity-check, should be automatic * after the initial bounds check. */ if (p != dst + dst_len) { mbedtls_platform_zeroize(dst, dst_len); return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); } return (0); } /* * Do an RSA operation to sign the message digest */ int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig) { int ret; unsigned char *sig_try = NULL, *verif = NULL; if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); /* * Prepare PKCS1-v1.5 encoding (padding and hash identifier) */ if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, ctx->len, sig)) != 0) return (ret); /* * Call respective RSA primitive */ if (mode == MBEDTLS_RSA_PUBLIC) { /* Skip verification on a public key operation */ return (mbedtls_rsa_public(ctx, sig, sig)); } /* Private key operation * * In order to prevent Lenstra's attack, make the signature in a * temporary buffer and check it before returning it. */ sig_try = mbedtls_calloc(1, ctx->len); if (sig_try == NULL) return (MBEDTLS_ERR_MPI_ALLOC_FAILED); verif = mbedtls_calloc(1, ctx->len); if (verif == NULL) { mbedtls_free(sig_try); return (MBEDTLS_ERR_MPI_ALLOC_FAILED); } MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try)); MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif)); if (mbedtls_safer_memcmp(verif, sig, ctx->len) != 0) { ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED; goto cleanup; } memcpy(sig, sig_try, ctx->len); cleanup: mbedtls_free(sig_try); mbedtls_free(verif); return (ret); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation to sign the message digest */ int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig) { switch (ctx->padding) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig); #endif default: return (MBEDTLS_ERR_RSA_INVALID_PADDING); } } #if defined(MBEDTLS_PKCS1_V21) /* * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function */ int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, mbedtls_md_type_t mgf1_hash_id, int expected_salt_len, const unsigned char *sig) { int ret; size_t siglen; unsigned char *p; unsigned char *hash_start; unsigned char result[MBEDTLS_MD_MAX_SIZE]; unsigned char zeros[8]; unsigned int hlen; size_t observed_salt_len, msb; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); siglen = ctx->len; if (siglen < 16 || siglen > sizeof(buf)) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); ret = (mode == MBEDTLS_RSA_PUBLIC) ? mbedtls_rsa_public(ctx, sig, buf) : mbedtls_rsa_private(ctx, f_rng, p_rng, sig, buf); if (ret != 0) return (ret); p = buf; if (buf[siglen - 1] != 0xBC) return (MBEDTLS_ERR_RSA_INVALID_PADDING); if (md_alg != MBEDTLS_MD_NONE) { /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type(md_alg); if (md_info == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); hashlen = mbedtls_md_get_size(md_info); } md_info = mbedtls_md_info_from_type(mgf1_hash_id); if (md_info == NULL) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); hlen = mbedtls_md_get_size(md_info); memset(zeros, 0, 8); /* * Note: EMSA-PSS verification is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen(&ctx->N) - 1; if (buf[0] >> (8 - siglen * 8 + msb)) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); /* Compensate for boundary condition when applying mask */ if (msb % 8 == 0) { p++; siglen -= 1; } if (siglen < hlen + 2) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); hash_start = p + siglen - hlen - 1; mbedtls_md_init(&md_ctx); if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) goto exit; ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, &md_ctx); if (ret != 0) goto exit; buf[0] &= 0xFF >> (siglen * 8 - msb); while (p < hash_start - 1 && *p == 0) p++; if (*p++ != 0x01) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto exit; } observed_salt_len = hash_start - p; if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY && observed_salt_len != (size_t) expected_salt_len) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto exit; } /* * Generate H = Hash( M' ) */ ret = mbedtls_md_starts(&md_ctx); if (ret != 0) goto exit; ret = mbedtls_md_update(&md_ctx, zeros, 8); if (ret != 0) goto exit; ret = mbedtls_md_update(&md_ctx, hash, hashlen); if (ret != 0) goto exit; ret = mbedtls_md_update(&md_ctx, p, observed_salt_len); if (ret != 0) goto exit; ret = mbedtls_md_finish(&md_ctx, result); if (ret != 0) goto exit; if (memcmp(hash_start, result, hlen) != 0) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto exit; } exit: mbedtls_md_free(&md_ctx); return (ret); } /* * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function */ int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig) { mbedtls_md_type_t mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE) ? (mbedtls_md_type_t) ctx->hash_id : md_alg; return (mbedtls_rsa_rsassa_pss_verify_ext(ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY, sig)); } #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function */ int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig) { int ret = 0; const size_t sig_len = ctx->len; unsigned char *encoded = NULL, *encoded_expected = NULL; if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA); /* * Prepare expected PKCS1 v1.5 encoding of hash. */ if ((encoded = mbedtls_calloc(1, sig_len)) == NULL || (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) { ret = MBEDTLS_ERR_MPI_ALLOC_FAILED; goto cleanup; } if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len, encoded_expected)) != 0) goto cleanup; /* * Apply RSA primitive to get what should be PKCS1 encoded hash. */ ret = (mode == MBEDTLS_RSA_PUBLIC) ? mbedtls_rsa_public(ctx, sig, encoded) : mbedtls_rsa_private(ctx, f_rng, p_rng, sig, encoded); if (ret != 0) goto cleanup; /* * Compare */ if ((ret = mbedtls_safer_memcmp(encoded, encoded_expected, sig_len)) != 0) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto cleanup; } cleanup: if (encoded != NULL) { mbedtls_platform_zeroize(encoded, sig_len); mbedtls_free(encoded); } if (encoded_expected != NULL) { mbedtls_platform_zeroize(encoded_expected, sig_len); mbedtls_free(encoded_expected); } return (ret); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation and check the message digest */ int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig) { switch (ctx->padding) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsassa_pss_verify(ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig); #endif default: return (MBEDTLS_ERR_RSA_INVALID_PADDING); } } /* * Copy the components of an RSA key */ int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src) { int ret; dst->ver = src->ver; dst->len = src->len; MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q)); #if !defined(MBEDTLS_RSA_NO_CRT) MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ)); #endif MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi)); MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf)); dst->padding = src->padding; dst->hash_id = src->hash_id; cleanup: if (ret != 0) mbedtls_rsa_free(dst); return (ret); } /* * Free the components of an RSA key */ void mbedtls_rsa_free(mbedtls_rsa_context *ctx) { mbedtls_mpi_free(&ctx->Vi); mbedtls_mpi_free(&ctx->Vf); mbedtls_mpi_free(&ctx->RN); mbedtls_mpi_free(&ctx->D); mbedtls_mpi_free(&ctx->Q); mbedtls_mpi_free(&ctx->P); mbedtls_mpi_free(&ctx->E); mbedtls_mpi_free(&ctx->N); #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free(&ctx->RQ); mbedtls_mpi_free(&ctx->RP); mbedtls_mpi_free(&ctx->QP); mbedtls_mpi_free(&ctx->DQ); mbedtls_mpi_free(&ctx->DP); #endif /* MBEDTLS_RSA_NO_CRT */ #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free(&ctx->mutex); #endif } #endif /* !MBEDTLS_RSA_ALT */ #if defined(MBEDTLS_SELF_TEST) #include "mbedtls/sha1.h" /* * Example RSA-1024 keypair, for test purposes */ #define KEY_LEN 128 #define RSA_N "9292758453063D803DD603D5E777D788" \ "8ED1D5BF35786190FA2F23EBC0848AEA" \ "DDA92CA6C3D80B32C4D109BE0F36D6AE" \ "7130B9CED7ACDF54CFC7555AC14EEBAB" \ "93A89813FBF3C4F8066D2D800F7C38A8" \ "1AE31942917403FF4946B0A83D3D3E05" \ "EE57C6F5F5606FB5D4BC6CD34EE0801A" \ "5E94BB77B07507233A0BC7BAC8F90F79" #define RSA_E "10001" #define RSA_D "24BF6185468786FDD303083D25E64EFC" \ "66CA472BC44D253102F8B4A9D3BFA750" \ "91386C0077937FE33FA3252D28855837" \ "AE1B484A8A9A45F7EE8C0C634F99E8CD" \ "DF79C5CE07EE72C7F123142198164234" \ "CABB724CF78B8173B9F880FC86322407" \ "AF1FEDFDDE2BEB674CA15F3E81A1521E" \ "071513A1E85B5DFA031F21ECAE91A34D" #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \ "2C01CAD19EA484A87EA4377637E75500" \ "FCB2005C5C7DD6EC4AC023CDA285D796" \ "C3D9E75E1EFC42488BB4F1D13AC30A57" #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \ "E211C2B9E5DB1ED0BF61D0D9899620F4" \ "910E4168387E3C30AA1E00C339A79508" \ "8452DD96A9A5EA5D9DCA68DA636032AF" #define PT_LEN 24 #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \ "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD" #if defined(MBEDTLS_PKCS1_V15) static int myrand(void *rng_state, unsigned char *output, size_t len) { #if !defined(__OpenBSD__) size_t i; if (rng_state != NULL) rng_state = NULL; for (i = 0; i < len; ++i) output[i] = rand(); #else if (rng_state != NULL) rng_state = NULL; arc4random_buf(output, len); #endif /* !OpenBSD */ return (0); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Checkup routine */ int mbedtls_rsa_self_test(int verbose) { int ret = 0; #if defined(MBEDTLS_PKCS1_V15) size_t len; mbedtls_rsa_context rsa; unsigned char rsa_plaintext[PT_LEN]; unsigned char rsa_decrypted[PT_LEN]; unsigned char rsa_ciphertext[KEY_LEN]; #if defined(MBEDTLS_SHA1_C) unsigned char sha1sum[20]; #endif mbedtls_mpi K; mbedtls_mpi_init(&K); mbedtls_rsa_init(&rsa, MBEDTLS_RSA_PKCS_V15, 0); MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N)); MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL)); MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P)); MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL)); MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q)); MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL)); MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D)); MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL)); MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E)); MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K)); MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa)); if (verbose != 0) mbedtls_printf(" RSA key validation: "); if (mbedtls_rsa_check_pubkey(&rsa) != 0 || mbedtls_rsa_check_privkey(&rsa) != 0) { if (verbose != 0) mbedtls_printf("failed\n"); ret = 1; goto cleanup; } if (verbose != 0) mbedtls_printf("passed\n PKCS#1 encryption : "); memcpy(rsa_plaintext, RSA_PT, PT_LEN); if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC, PT_LEN, rsa_plaintext, rsa_ciphertext) != 0) { if (verbose != 0) mbedtls_printf("failed\n"); ret = 1; goto cleanup; } if (verbose != 0) mbedtls_printf("passed\n PKCS#1 decryption : "); if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, &len, rsa_ciphertext, rsa_decrypted, sizeof(rsa_decrypted)) != 0) { if (verbose != 0) mbedtls_printf("failed\n"); ret = 1; goto cleanup; } if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) { if (verbose != 0) mbedtls_printf("failed\n"); ret = 1; goto cleanup; } if (verbose != 0) mbedtls_printf("passed\n"); #if defined(MBEDTLS_SHA1_C) if (verbose != 0) mbedtls_printf(" PKCS#1 data sign : "); if (mbedtls_sha1_ret(rsa_plaintext, PT_LEN, sha1sum) != 0) { if (verbose != 0) mbedtls_printf("failed\n"); return (1); } if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0, sha1sum, rsa_ciphertext) != 0) { if (verbose != 0) mbedtls_printf("failed\n"); ret = 1; goto cleanup; } if (verbose != 0) mbedtls_printf("passed\n PKCS#1 sig. verify: "); if (mbedtls_rsa_pkcs1_verify(&rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0, sha1sum, rsa_ciphertext) != 0) { if (verbose != 0) mbedtls_printf("failed\n"); ret = 1; goto cleanup; } if (verbose != 0) mbedtls_printf("passed\n"); #endif /* MBEDTLS_SHA1_C */ if (verbose != 0) mbedtls_printf("\n"); cleanup: mbedtls_mpi_free(&K); mbedtls_rsa_free(&rsa); #else /* MBEDTLS_PKCS1_V15 */ ((void) verbose); #endif /* MBEDTLS_PKCS1_V15 */ return (ret); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_RSA_C */
{ "pile_set_name": "Github" }
FROM php:7.0-apache # Install composer RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer # Necessary to run composer RUN apt-get update RUN apt-get install -y git COPY composer.json /var/www WORKDIR /var/www RUN composer install COPY public/ /var/www/html/ COPY src /var/www/src RUN cp /var/www/src/diskover/Constants.php.sample /var/www/src/diskover/Constants.php RUN cp /var/www/html/smartsearches.txt.sample /var/www/html/smartsearches.txt RUN cp /var/www/html/customtags.txt.sample /var/www/html/customtags.txt RUN cp /var/www/html/extrafields.txt.sample /var/www/html/extrafields.txt ARG ES_HOST=elasticsearch RUN sed -i "s!const ES_HOST = 'localhost';!const ES_HOST = '$ES_HOST';!g" /var/www/src/diskover/Constants.php RUN ln -s /var/www/html/dashboard.php /var/www/html/index.php
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- generated on Wed Sep 11 13:21:56 2019 by Eclipse SUMO duarouter Version v1_3_1+0234-c526b02 This data file and the accompanying materials are made available under the terms of the Eclipse Public License v2.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v20.html SPDX-License-Identifier: EPL-2.0 <configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/duarouterConfiguration.xsd"> <input> <net-file value="input_net.net.xml"/> <additional-files value="input_additional.add.xml"/> <route-files value="input_routes.rou.xml"/> </input> <output> <write-license value="true"/> <output-file value="routes.rou.xml"/> <alternatives-output value="routes.rou.alt.xml"/> <intermodal-network-output value="additional.xml"/> <intermodal-weight-output value="weights.xml"/> </output> <processing> <persontrip.transfer.car-walk value="ptStops"/> </processing> <report> <xml-validation value="never"/> <no-step-log value="true"/> </report> </configuration> --> <weights xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/meandata_file.xsd"> <interval id="intermodalweights" begin="0" end="9223372036854775807"> <edge id=":absBeg_w0-1.00" traveltime="0.07" effort="0.00"/> <edge id=":absEnd_0_fwd-1.00" traveltime="0.07" effort="0.00"/> <edge id=":absEnd_0_bwd-1.00" traveltime="0.07" effort="0.00"/> <edge id=":absEnd_0_depart_connector" traveltime="0.00" effort="0.00"/> <edge id=":absEnd_0_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id=":absEnd_w0-1.00" traveltime="0.07" effort="0.00"/> <edge id=":beg_0_fwd-1.00" traveltime="5.23" effort="0.00"/> <edge id=":beg_0_bwd-1.00" traveltime="5.23" effort="0.00"/> <edge id=":beg_0_depart_connector" traveltime="0.00" effort="0.00"/> <edge id=":beg_0_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id=":beg_1_fwd-1.00" traveltime="3.60" effort="0.00"/> <edge id=":beg_1_bwd-1.00" traveltime="3.60" effort="0.00"/> <edge id=":beg_1_depart_connector" traveltime="0.00" effort="0.00"/> <edge id=":beg_1_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id=":beg_w0-1.00" traveltime="4.44" effort="0.00"/> <edge id=":begleft_0_fwd-1.00" traveltime="1.86" effort="0.00"/> <edge id=":begleft_0_bwd-1.00" traveltime="1.86" effort="0.00"/> <edge id=":begleft_0_depart_connector" traveltime="0.00" effort="0.00"/> <edge id=":begleft_0_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id=":end_0_fwd-1.00" traveltime="7.37" effort="0.00"/> <edge id=":end_0_bwd-1.00" traveltime="7.37" effort="0.00"/> <edge id=":end_0_depart_connector" traveltime="0.00" effort="0.00"/> <edge id=":end_0_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id=":end_w0-1.00" traveltime="5.64" effort="0.00"/> <edge id=":endleft_0_fwd-1.00" traveltime="3.60" effort="0.00"/> <edge id=":endleft_0_bwd-1.00" traveltime="3.60" effort="0.00"/> <edge id=":endleft_0_depart_connector" traveltime="0.00" effort="0.00"/> <edge id=":endleft_0_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id=":endleft_w0-1.00" traveltime="3.15" effort="0.00"/> <edge id=":rabsEnd_w0-1.00" traveltime="0.07" effort="0.00"/> <edge id="beg_fwd-1.00" traveltime="358.96" effort="0.00"/> <edge id="beg_bwd-1.00" traveltime="358.96" effort="0.00"/> <edge id="beg_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="beg_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="beg2left_fwd-1.00" traveltime="180.00" effort="0.00"/> <edge id="beg2left_bwd250.00" traveltime="176.62" effort="0.00"/> <edge id="beg2left_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="beg2left_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="end_fwd-1.00" traveltime="358.96" effort="0.00"/> <edge id="end_bwd-1.00" traveltime="358.96" effort="0.00"/> <edge id="end_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="end_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="gneE0_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="gneE0_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="left_fwd-1.00" traveltime="711.86" effort="0.00"/> <edge id="left_bwd-1.00" traveltime="711.86" effort="0.00"/> <edge id="left_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="left_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="left2end_fwd-1.00" traveltime="180.00" effort="0.00"/> <edge id="left2end_bwd250.00" traveltime="175.54" effort="0.00"/> <edge id="left2end_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="left2end_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="middle_fwd-1.00" traveltime="710.78" effort="0.00"/> <edge id="middle_bwd-1.00" traveltime="710.78" effort="0.00"/> <edge id="middle_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="middle_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="rend_fwd-1.00" traveltime="360.00" effort="0.00"/> <edge id="rend_bwd-1.00" traveltime="360.00" effort="0.00"/> <edge id="rend_depart_connector" traveltime="0.00" effort="0.00"/> <edge id="rend_arrival_connector" traveltime="0.00" effort="0.00"/> <edge id="gneJ1_walking_connector" traveltime="0.00" effort="0.00"/> <edge id=":absEnd_0_car-1.00" traveltime="0.00" effort="0.00"/> <edge id=":beg_0_car-1.00" traveltime="0.35" effort="0.00"/> <edge id=":beg_1_car-1.00" traveltime="0.18" effort="0.00"/> <edge id=":begleft_0_car-1.00" traveltime="0.09" effort="0.00"/> <edge id=":end_0_car-1.00" traveltime="0.49" effort="0.00"/> <edge id=":endleft_0_car-1.00" traveltime="0.18" effort="0.00"/> <edge id="beg_car-1.00" traveltime="17.93" effort="0.00"/> <edge id="beg2left_car-1.00" traveltime="8.99" effort="0.00"/> <edge id="end_car-1.00" traveltime="17.93" effort="0.00"/> <edge id="gneE0_car-1.00" traveltime="110.08" effort="0.00"/> <edge id="left_car-1.00" traveltime="35.56" effort="0.00"/> <edge id="left2end_car-1.00" traveltime="8.99" effort="0.00"/> <edge id="middle_car-1.00" traveltime="71.02" effort="0.00"/> <edge id="rend_car-1.00" traveltime="17.99" effort="0.00"/> <edge id="beg2left" traveltime="0.00" effort="0.00"/> <edge id="beg2left_fwd250.00" traveltime="176.62" effort="0.00"/> <edge id="beg2left_fwd-1.00:beg2left" traveltime="0.00" effort="0.00"/> <edge id="beg2left:beg2left_fwd250.00" traveltime="0.00" effort="0.00"/> <edge id="beg2left_bwd-1.00" traveltime="180.00" effort="0.00"/> <edge id="beg2left_bwd250.00:beg2left" traveltime="0.00" effort="0.00"/> <edge id="beg2left:beg2left_bwd-1.00" traveltime="0.00" effort="0.00"/> <edge id="beg2left_car250.00" traveltime="8.82" effort="0.00"/> <edge id="beg2left_car-1.00:beg2left" traveltime="0.00" effort="0.00"/> <edge id="beg2left_car-1.00:beg2left_fwd250.00" traveltime="0.00" effort="0.00"/> <edge id="beg2left_car-1.00:beg2left_bwd-1.00" traveltime="0.00" effort="0.00"/> <edge id="beg2left_depart_connector250.00" traveltime="0.00" effort="0.00"/> <edge id="beg2left_arrival_connector250.00" traveltime="0.00" effort="0.00"/> <edge id="left2end" traveltime="0.00" effort="0.00"/> <edge id="left2end_fwd250.00" traveltime="175.54" effort="0.00"/> <edge id="left2end_fwd-1.00:left2end" traveltime="0.00" effort="0.00"/> <edge id="left2end:left2end_fwd250.00" traveltime="0.00" effort="0.00"/> <edge id="left2end_bwd-1.00" traveltime="180.00" effort="0.00"/> <edge id="left2end_bwd250.00:left2end" traveltime="0.00" effort="0.00"/> <edge id="left2end:left2end_bwd-1.00" traveltime="0.00" effort="0.00"/> <edge id="left2end_car250.00" traveltime="8.77" effort="0.00"/> <edge id="left2end_car-1.00:left2end" traveltime="0.00" effort="0.00"/> <edge id="left2end_car-1.00:left2end_fwd250.00" traveltime="0.00" effort="0.00"/> <edge id="left2end_car-1.00:left2end_bwd-1.00" traveltime="0.00" effort="0.00"/> <edge id="left2end_depart_connector250.00" traveltime="0.00" effort="0.00"/> <edge id="left2end_arrival_connector250.00" traveltime="0.00" effort="0.00"/> <edge id="train:left2end" traveltime="60.00" effort="0.00"/> </interval> </weights>
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="referencedata.xsl"?> <ReferenceData> <InitializedPositions> <Positions> <Int Name="Count">1</Int> <String Name="Type">single</String> <Sequence Name="Block"> <Int Name="Length">2</Int> <Int>0</Int> <Int>9</Int> </Sequence> <Position> <Sequence Name="Atoms"> <Int Name="Length">9</Int> <Int>0</Int> <Int>1</Int> <Int>2</Int> <Int>3</Int> <Int>4</Int> <Int>5</Int> <Int>6</Int> <Int>7</Int> <Int>8</Int> </Sequence> <Int Name="RefId">0</Int> </Position> </Positions> </InitializedPositions> <EvaluatedPositions Name="Frame0"> <Positions> <Int Name="Count">1</Int> <String Name="Type">single</String> <Sequence Name="Block"> <Int Name="Length">2</Int> <Int>0</Int> <Int>9</Int> </Sequence> <Position> <Sequence Name="Atoms"> <Int Name="Length">9</Int> <Int>0</Int> <Int>1</Int> <Int>2</Int> <Int>3</Int> <Int>4</Int> <Int>5</Int> <Int>6</Int> <Int>7</Int> <Int>8</Int> </Sequence> <Int Name="RefId">0</Int> <Vector Name="Coordinates"> <Real Name="X">4</Real> <Real Name="Y">0</Real> <Real Name="Z">0</Real> </Vector> <Vector Name="Velocity"> <Real Name="X">4</Real> <Real Name="Y">0</Real> <Real Name="Z">1</Real> </Vector> <Vector Name="Force"> <Real Name="X">42</Real> <Real Name="Y">0</Real> <Real Name="Z">-10</Real> </Vector> </Position> </Positions> </EvaluatedPositions> </ReferenceData>
{ "pile_set_name": "Github" }
label { width: 4em; float: left; text-align: right; margin-right: 0.5em; display: block } .submit input { margin-left: 4.5em; } input { color: #781351; background: #fee3ad; border: 1px solid #781351 } .submit input { color: #000; background: #ffa20f; border: 2px outset #d7b9c9 } fieldset { border: 1px solid #781351; width: 20em } legend { color: #fff; background: #ffa20c; border: 1px solid #781351; padding: 2px 6px }
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 // This file contains a collection of methods that can be used from go-restful to // generate Swagger API documentation for its models. Please read this PR for more // information on the implementation: https://github.com/emicklei/go-restful/pull/215 // // TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if // they are on one line! For multiple line or blocks that you want to ignore use ---. // Any context after a --- is ignored. // // Those methods can be generated by using hack/update-generated-swagger-docs.sh // AUTO-GENERATED FUNCTIONS START HERE var map_StorageClass = map[string]string{ "": "StorageClass describes the parameters for a class of storage for which PersistentVolumes can be dynamically provisioned.\n\nStorageClasses are non-namespaced; the name of the storage class according to etcd is in ObjectMeta.Name.", "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata", "provisioner": "Provisioner indicates the type of the provisioner.", "parameters": "Parameters holds the parameters for the provisioner that should create volumes of this storage class.", "reclaimPolicy": "Dynamically provisioned PersistentVolumes of this storage class are created with this reclaimPolicy. Defaults to Delete.", "mountOptions": "Dynamically provisioned PersistentVolumes of this storage class are created with these mountOptions, e.g. [\"ro\", \"soft\"]. Not validated - mount of the PVs will simply fail if one is invalid.", "allowVolumeExpansion": "AllowVolumeExpansion shows whether the storage class allow volume expand", "volumeBindingMode": "VolumeBindingMode indicates how PersistentVolumeClaims should be provisioned and bound. When unset, VolumeBindingImmediate is used. This field is alpha-level and is only honored by servers that enable the VolumeScheduling feature.", } func (StorageClass) SwaggerDoc() map[string]string { return map_StorageClass } var map_StorageClassList = map[string]string{ "": "StorageClassList is a collection of storage classes.", "metadata": "Standard list metadata More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata", "items": "Items is the list of StorageClasses", } func (StorageClassList) SwaggerDoc() map[string]string { return map_StorageClassList } // AUTO-GENERATED FUNCTIONS END HERE
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _SELFTESTS_POWERPC_BASIC_ASM_H #define _SELFTESTS_POWERPC_BASIC_ASM_H #include <ppc-asm.h> #include <asm/unistd.h> #define LOAD_REG_IMMEDIATE(reg, expr) \ lis reg, (expr)@highest; \ ori reg, reg, (expr)@higher; \ rldicr reg, reg, 32, 31; \ oris reg, reg, (expr)@high; \ ori reg, reg, (expr)@l; /* * Note: These macros assume that variables being stored on the stack are * doublewords, while this is usually the case it may not always be the * case for each use case. */ #if defined(_CALL_ELF) && _CALL_ELF == 2 #define STACK_FRAME_MIN_SIZE 32 #define STACK_FRAME_TOC_POS 24 #define __STACK_FRAME_PARAM(_param) (32 + ((_param)*8)) #define __STACK_FRAME_LOCAL(_num_params, _var_num) \ ((STACK_FRAME_PARAM(_num_params)) + ((_var_num)*8)) #else #define STACK_FRAME_MIN_SIZE 112 #define STACK_FRAME_TOC_POS 40 #define __STACK_FRAME_PARAM(i) (48 + ((i)*8)) /* * Caveat: if a function passed more than 8 doublewords, the caller will have * made more space... which would render the 112 incorrect. */ #define __STACK_FRAME_LOCAL(_num_params, _var_num) \ (112 + ((_var_num)*8)) #endif /* Parameter x saved to the stack */ #define STACK_FRAME_PARAM(var) __STACK_FRAME_PARAM(var) /* Local variable x saved to the stack after x parameters */ #define STACK_FRAME_LOCAL(num_params, var) \ __STACK_FRAME_LOCAL(num_params, var) #define STACK_FRAME_LR_POS 16 #define STACK_FRAME_CR_POS 8 /* * It is very important to note here that _extra is the extra amount of * stack space needed. This space can be accessed using STACK_FRAME_PARAM() * or STACK_FRAME_LOCAL() macros. * * r1 and r2 are not defined in ppc-asm.h (instead they are defined as sp * and toc). Kernel programmers tend to prefer rX even for r1 and r2, hence * %1 and %r2. r0 is defined in ppc-asm.h and therefore %r0 gets * preprocessed incorrectly, hence r0. */ #define PUSH_BASIC_STACK(_extra) \ mflr r0; \ std r0, STACK_FRAME_LR_POS(%r1); \ stdu %r1, -(_extra + STACK_FRAME_MIN_SIZE)(%r1); \ mfcr r0; \ stw r0, STACK_FRAME_CR_POS(%r1); \ std %r2, STACK_FRAME_TOC_POS(%r1); #define POP_BASIC_STACK(_extra) \ ld %r2, STACK_FRAME_TOC_POS(%r1); \ lwz r0, STACK_FRAME_CR_POS(%r1); \ mtcr r0; \ addi %r1, %r1, (_extra + STACK_FRAME_MIN_SIZE); \ ld r0, STACK_FRAME_LR_POS(%r1); \ mtlr r0; #endif /* _SELFTESTS_POWERPC_BASIC_ASM_H */
{ "pile_set_name": "Github" }
amiga/launch.c amiga/expat_68k.c amiga/expat_68k.h amiga/expat_68k_handler_stubs.c amiga/expat_base.h amiga/expat_vectors.c amiga/expat_lib.c amiga/expat.xml amiga/README.txt amiga/Makefile amiga/include/proto/expat.h amiga/include/libraries/expat.h amiga/include/interfaces/expat.h amiga/include/inline4/expat.h bcb5/README.txt bcb5/all_projects.bpg bcb5/elements.bpf bcb5/elements.bpr bcb5/elements.mak bcb5/expat.bpf bcb5/expat.bpr bcb5/expat.mak bcb5/expat_static.bpf bcb5/expat_static.bpr bcb5/expat_static.mak bcb5/expatw.bpf bcb5/expatw.bpr bcb5/expatw.mak bcb5/expatw_static.bpf bcb5/expatw_static.bpr bcb5/expatw_static.mak bcb5/libexpat_mtd.def bcb5/libexpatw_mtd.def bcb5/makefile.mak bcb5/outline.bpf bcb5/outline.bpr bcb5/outline.mak bcb5/setup.bat bcb5/xmlwf.bpf bcb5/xmlwf.bpr bcb5/xmlwf.mak doc/expat.png doc/reference.html doc/style.css doc/valid-xhtml10.png doc/xmlwf.1 doc/xmlwf.sgml CMakeLists.txt CMake.README COPYING Changes ConfigureChecks.cmake MANIFEST Makefile.in README configure configure.in expat_config.h.in expat_config.h.cmake expat.pc.in expat.dsw aclocal.m4 conftools/PrintPath conftools/ac_c_bigendian_cross.m4 conftools/expat.m4 conftools/get-version.sh conftools/mkinstalldirs conftools/config.guess conftools/config.sub conftools/install-sh conftools/ltmain.sh m4/libtool.m4 m4/ltversion.m4 m4/ltoptions.m4 m4/ltsugar.m4 m4/lt~obsolete.m4 examples/elements.c examples/elements.dsp examples/outline.c examples/outline.dsp lib/Makefile.MPW lib/amigaconfig.h lib/ascii.h lib/asciitab.h lib/expat.dsp lib/expat.h lib/expat_external.h lib/expat_static.dsp lib/expatw.dsp lib/expatw_static.dsp lib/iasciitab.h lib/internal.h lib/latin1tab.h lib/libexpat.def lib/libexpatw.def lib/macconfig.h lib/nametab.h lib/utf8tab.h lib/winconfig.h lib/xmlparse.c lib/xmlrole.c lib/xmlrole.h lib/xmltok.c lib/xmltok.h lib/xmltok_impl.c lib/xmltok_impl.h lib/xmltok_ns.c tests/benchmark/README.txt tests/benchmark/benchmark.c tests/benchmark/benchmark.dsp tests/benchmark/benchmark.dsw tests/README.txt tests/chardata.c tests/chardata.h tests/minicheck.c tests/minicheck.h tests/runtests.c tests/runtestspp.cpp tests/xmltest.sh vms/README.vms vms/descrip.mms vms/expat_config.h win32/MANIFEST.txt win32/README.txt win32/expat.iss xmlwf/codepage.c xmlwf/codepage.h xmlwf/ct.c xmlwf/filemap.h xmlwf/readfilemap.c xmlwf/unixfilemap.c xmlwf/win32filemap.c xmlwf/xmlfile.c xmlwf/xmlfile.h xmlwf/xmlmime.c xmlwf/xmlmime.h xmlwf/xmltchar.h xmlwf/xmlurl.h xmlwf/xmlwf.c xmlwf/xmlwf.dsp xmlwf/xmlwin32url.cxx
{ "pile_set_name": "Github" }
westinghouse says it expects at least pct ings shr growth through
{ "pile_set_name": "Github" }
# Événement Événement is a very simple event dispatching library for PHP. It has the same design goals as [Silex](http://silex-project.org) and [Pimple](http://pimple-project.org), to empower the user while staying concise and simple. It is very strongly inspired by the EventEmitter API found in [node.js](http://nodejs.org). [![Build Status](https://secure.travis-ci.org/igorw/evenement.png?branch=master)](http://travis-ci.org/igorw/evenement) ## Fetch The recommended way to install Événement is [through composer](http://getcomposer.org). Just create a composer.json file for your project: ```JSON { "require": { "evenement/evenement": "2.0.*" } } ``` **Note:** The `2.0.*` version of Événement requires PHP 5.4. If you are using PHP 5.3, please use the `1.0.*` version: ```JSON { "require": { "evenement/evenement": "1.0.*" } } ``` And run these two commands to install it: $ curl -s http://getcomposer.org/installer | php $ php composer.phar install Now you can add the autoloader, and you will have access to the library: ```php <?php require 'vendor/autoload.php'; ``` ## Usage ### Creating an Emitter ```php <?php $emitter = new Evenement\EventEmitter(); ``` ### Adding Listeners ```php <?php $emitter->on('user.created', function (User $user) use ($logger) { $logger->log(sprintf("User '%s' was created.", $user->getLogin())); }); ``` ### Emitting Events ```php <?php $emitter->emit('user.created', array($user)); ``` Tests ----- $ phpunit License ------- MIT, see LICENSE.
{ "pile_set_name": "Github" }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.plugin; /** * A Simple Test Extension Interface. * * @author joa23 * */ public interface ITestExtension { public String testGetExtension(String hello); }
{ "pile_set_name": "Github" }
/* * Copyright (c) [2015] - [2017] Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ 'use strict'; /** * Test */ describe('Codenvy', function(){ /** * Account Factory for the test */ var factory; /** * setup module */ beforeEach(angular.mock.module('codenvyDashboard')); /** * Check that we're able to fetch project types */ it('Empty', function() { console.log('first test'); } ); });
{ "pile_set_name": "Github" }
from __future__ import print_function, division # import sys,os os.environ['KMP_DUPLICATE_LIB_OK']='True' # uncomment this line if omp error occurs on OSX for python 3 os.environ['OMP_NUM_THREADS']='1' # set number of OpenMP threads to run in parallel os.environ['MKL_NUM_THREADS']='1' # set number of MKL threads to run in parallel # quspin_path = os.path.join(os.getcwd(),"../../") sys.path.insert(0,quspin_path) ########################################################################### # example 13 # # In this script we demonstrate how to construct a spinful fermion basis # # with no doubly occupancid sites in the Fermi-Hubbard model, # # using the spinful_fermion_ basis_general class. # ########################################################################### from quspin.basis import spinful_fermion_basis_general from quspin.operators import hamiltonian import numpy as np # ###### define model parameters ###### Lx, Ly = 3, 3 # linear dimension of spin 1 2d lattice N_2d = Lx*Ly # number of sites for spin 1 # J=1.0 # hopping matrix element U=2.0 # onsite interaction mu=0.5 # chemical potential # ###### setting up user-defined BASIC symmetry transformations for 2d lattice ###### s = np.arange(N_2d) # sites [0,1,2,...,N_2d-1] in simple notation x = s%Lx # x positions for sites y = s//Lx # y positions for sites T_x = (x+1)%Lx + Lx*y # translation along x-direction T_y = x + Lx*((y+1)%Ly) # translation along y-direction P_x = x + Lx*(Ly-y-1) # reflection about x-axis P_y = (Lx-x-1) + Lx*y # reflection about y-axis S = -(s+1) # fermion spin inversion in the simple case # ###### setting up bases ###### basis_2d=spinful_fermion_basis_general(N_2d,Nf=(3,3),double_occupancy=False, kxblock=(T_x,0),kyblock=(T_y,0), pxblock=(P_x,1),pyblock=(P_y,0), # contains GS sblock=(S,0)) print(basis_2d) # ###### setting up hamiltonian ###### # setting up site-coupling lists for simple case hopping_left =[[-J,i,T_x[i]] for i in range(N_2d)] + [[-J,i,T_y[i]] for i in range(N_2d)] hopping_right=[[+J,i,T_x[i]] for i in range(N_2d)] + [[+J,i,T_y[i]] for i in range(N_2d)] potential=[[-mu,i] for i in range(N_2d)] interaction=[[U,i,i] for i in range(N_2d)] # static=[["+-|",hopping_left], # spin up hops to left ["-+|",hopping_right], # spin up hops to right ["|+-",hopping_left], # spin down hopes to left ["|-+",hopping_right], # spin up hops to right ["n|",potential], # onsite potenial, spin up ["|n",potential], # onsite potential, spin down ["n|n",interaction]] # spin up-spin down interaction # build hamiltonian H=hamiltonian(static,[],basis=basis_2d,dtype=np.float64) # compute GS of H E_GS, psi_GS=H.eigsh(k=1,which='SA')
{ "pile_set_name": "Github" }
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright 2011, Blender Foundation. */ #include "COM_ChromaMatteOperation.h" #include "BLI_math.h" ChromaMatteOperation::ChromaMatteOperation() : NodeOperation() { addInputSocket(COM_DT_COLOR); addInputSocket(COM_DT_COLOR); addOutputSocket(COM_DT_VALUE); this->m_inputImageProgram = NULL; this->m_inputKeyProgram = NULL; } void ChromaMatteOperation::initExecution() { this->m_inputImageProgram = this->getInputSocketReader(0); this->m_inputKeyProgram = this->getInputSocketReader(1); } void ChromaMatteOperation::deinitExecution() { this->m_inputImageProgram = NULL; this->m_inputKeyProgram = NULL; } void ChromaMatteOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) { float inKey[4]; float inImage[4]; const float acceptance = this->m_settings->t1; /* in radians */ const float cutoff = this->m_settings->t2; /* in radians */ const float gain = this->m_settings->fstrength; float x_angle, z_angle, alpha; float theta, beta; float kfg; this->m_inputKeyProgram->readSampled(inKey, x, y, sampler); this->m_inputImageProgram->readSampled(inImage, x, y, sampler); /* store matte(alpha) value in [0] to go with * COM_SetAlphaOperation and the Value output */ /* Algorithm from book "Video Demistified," does not include the spill reduction part */ /* find theta, the angle that the color space should be rotated based on key */ /* rescale to -1.0..1.0 */ // inImage[0] = (inImage[0] * 2.0f) - 1.0f; // UNUSED inImage[1] = (inImage[1] * 2.0f) - 1.0f; inImage[2] = (inImage[2] * 2.0f) - 1.0f; // inKey[0] = (inKey[0] * 2.0f) - 1.0f; // UNUSED inKey[1] = (inKey[1] * 2.0f) - 1.0f; inKey[2] = (inKey[2] * 2.0f) - 1.0f; theta = atan2(inKey[2], inKey[1]); /*rotate the cb and cr into x/z space */ x_angle = inImage[1] * cosf(theta) + inImage[2] * sinf(theta); z_angle = inImage[2] * cosf(theta) - inImage[1] * sinf(theta); /*if within the acceptance angle */ /* if kfg is <0 then the pixel is outside of the key color */ kfg = x_angle - (fabsf(z_angle) / tanf(acceptance / 2.0f)); if (kfg > 0.0f) { /* found a pixel that is within key color */ alpha = 1.0f - (kfg / gain); beta = atan2(z_angle, x_angle); /* if beta is within the cutoff angle */ if (fabsf(beta) < (cutoff / 2.0f)) { alpha = 0.0f; } /* don't make something that was more transparent less transparent */ if (alpha < inImage[3]) { output[0] = alpha; } else { output[0] = inImage[3]; } } else { /*pixel is outside key color */ output[0] = inImage[3]; /* make pixel just as transparent as it was before */ } }
{ "pile_set_name": "Github" }
// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3 with static-linking exception. // See LICENCE file for details. package ratelimit import ( "math" "testing" "time" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } type rateLimitSuite struct{} var _ = gc.Suite(rateLimitSuite{}) type takeReq struct { time time.Duration count int64 expectWait time.Duration } var takeTests = []struct { about string fillInterval time.Duration capacity int64 reqs []takeReq }{{ about: "serial requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 0, expectWait: 0, }, { time: 0, count: 10, expectWait: 0, }, { time: 0, count: 1, expectWait: 250 * time.Millisecond, }, { time: 250 * time.Millisecond, count: 1, expectWait: 250 * time.Millisecond, }}, }, { about: "concurrent requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 10, expectWait: 0, }, { time: 0, count: 2, expectWait: 500 * time.Millisecond, }, { time: 0, count: 2, expectWait: 1000 * time.Millisecond, }, { time: 0, count: 1, expectWait: 1250 * time.Millisecond, }}, }, { about: "more than capacity", fillInterval: 1 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 10, expectWait: 0, }, { time: 20 * time.Millisecond, count: 15, expectWait: 5 * time.Millisecond, }}, }, { about: "sub-quantum time", fillInterval: 10 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 10, expectWait: 0, }, { time: 7 * time.Millisecond, count: 1, expectWait: 3 * time.Millisecond, }, { time: 8 * time.Millisecond, count: 1, expectWait: 12 * time.Millisecond, }}, }, { about: "within capacity", fillInterval: 10 * time.Millisecond, capacity: 5, reqs: []takeReq{{ time: 0, count: 5, expectWait: 0, }, { time: 60 * time.Millisecond, count: 5, expectWait: 0, }, { time: 60 * time.Millisecond, count: 1, expectWait: 10 * time.Millisecond, }, { time: 80 * time.Millisecond, count: 2, expectWait: 10 * time.Millisecond, }}, }} var availTests = []struct { about string capacity int64 fillInterval time.Duration take int64 sleep time.Duration expectCountAfterTake int64 expectCountAfterSleep int64 }{{ about: "should fill tokens after interval", capacity: 5, fillInterval: time.Second, take: 5, sleep: time.Second, expectCountAfterTake: 0, expectCountAfterSleep: 1, }, { about: "should fill tokens plus existing count", capacity: 2, fillInterval: time.Second, take: 1, sleep: time.Second, expectCountAfterTake: 1, expectCountAfterSleep: 2, }, { about: "shouldn't fill before interval", capacity: 2, fillInterval: 2 * time.Second, take: 1, sleep: time.Second, expectCountAfterTake: 1, expectCountAfterSleep: 1, }, { about: "should fill only once after 1*interval before 2*interval", capacity: 2, fillInterval: 2 * time.Second, take: 1, sleep: 3 * time.Second, expectCountAfterTake: 1, expectCountAfterSleep: 2, }} func (rateLimitSuite) TestTake(c *gc.C) { for i, test := range takeTests { tb := NewBucket(test.fillInterval, test.capacity) for j, req := range test.reqs { d, ok := tb.take(tb.startTime.Add(req.time), req.count, infinityDuration) c.Assert(ok, gc.Equals, true) if d != req.expectWait { c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) } } } } func (rateLimitSuite) TestTakeMaxDuration(c *gc.C) { for i, test := range takeTests { tb := NewBucket(test.fillInterval, test.capacity) for j, req := range test.reqs { if req.expectWait > 0 { d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait-1) c.Assert(ok, gc.Equals, false) c.Assert(d, gc.Equals, time.Duration(0)) } d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait) c.Assert(ok, gc.Equals, true) if d != req.expectWait { c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) } } } } type takeAvailableReq struct { time time.Duration count int64 expect int64 } var takeAvailableTests = []struct { about string fillInterval time.Duration capacity int64 reqs []takeAvailableReq }{{ about: "serial requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeAvailableReq{{ time: 0, count: 0, expect: 0, }, { time: 0, count: 10, expect: 10, }, { time: 0, count: 1, expect: 0, }, { time: 250 * time.Millisecond, count: 1, expect: 1, }}, }, { about: "concurrent requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeAvailableReq{{ time: 0, count: 5, expect: 5, }, { time: 0, count: 2, expect: 2, }, { time: 0, count: 5, expect: 3, }, { time: 0, count: 1, expect: 0, }}, }, { about: "more than capacity", fillInterval: 1 * time.Millisecond, capacity: 10, reqs: []takeAvailableReq{{ time: 0, count: 10, expect: 10, }, { time: 20 * time.Millisecond, count: 15, expect: 10, }}, }, { about: "within capacity", fillInterval: 10 * time.Millisecond, capacity: 5, reqs: []takeAvailableReq{{ time: 0, count: 5, expect: 5, }, { time: 60 * time.Millisecond, count: 5, expect: 5, }, { time: 70 * time.Millisecond, count: 1, expect: 1, }}, }} func (rateLimitSuite) TestTakeAvailable(c *gc.C) { for i, test := range takeAvailableTests { tb := NewBucket(test.fillInterval, test.capacity) for j, req := range test.reqs { d := tb.takeAvailable(tb.startTime.Add(req.time), req.count) if d != req.expect { c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expect) } } } } func (rateLimitSuite) TestPanics(c *gc.C) { c.Assert(func() { NewBucket(0, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") c.Assert(func() { NewBucket(-2, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") c.Assert(func() { NewBucket(1, 0) }, gc.PanicMatches, "token bucket capacity is not > 0") c.Assert(func() { NewBucket(1, -2) }, gc.PanicMatches, "token bucket capacity is not > 0") } func isCloseTo(x, y, tolerance float64) bool { return math.Abs(x-y)/y < tolerance } func (rateLimitSuite) TestRate(c *gc.C) { tb := NewBucket(1, 1) if !isCloseTo(tb.Rate(), 1e9, 0.00001) { c.Fatalf("got %v want 1e9", tb.Rate()) } tb = NewBucket(2*time.Second, 1) if !isCloseTo(tb.Rate(), 0.5, 0.00001) { c.Fatalf("got %v want 0.5", tb.Rate()) } tb = NewBucketWithQuantum(100*time.Millisecond, 1, 5) if !isCloseTo(tb.Rate(), 50, 0.00001) { c.Fatalf("got %v want 50", tb.Rate()) } } func checkRate(c *gc.C, rate float64) { tb := NewBucketWithRate(rate, 1<<62) if !isCloseTo(tb.Rate(), rate, rateMargin) { c.Fatalf("got %g want %v", tb.Rate(), rate) } d, ok := tb.take(tb.startTime, 1<<62, infinityDuration) c.Assert(ok, gc.Equals, true) c.Assert(d, gc.Equals, time.Duration(0)) // Check that the actual rate is as expected by // asking for a not-quite multiple of the bucket's // quantum and checking that the wait time // correct. d, ok = tb.take(tb.startTime, tb.quantum*2-tb.quantum/2, infinityDuration) c.Assert(ok, gc.Equals, true) expectTime := 1e9 * float64(tb.quantum) * 2 / rate if !isCloseTo(float64(d), expectTime, rateMargin) { c.Fatalf("rate %g: got %g want %v", rate, float64(d), expectTime) } } func (rateLimitSuite) TestNewWithRate(c *gc.C) { for rate := float64(1); rate < 1e6; rate += 7 { checkRate(c, rate) } for _, rate := range []float64{ 1024 * 1024 * 1024, 1e-5, 0.9e-5, 0.5, 0.9, 0.9e8, 3e12, 4e18, } { checkRate(c, rate) checkRate(c, rate/3) checkRate(c, rate*1.3) } } func TestAvailable(t *testing.T) { for i, tt := range availTests { tb := NewBucket(tt.fillInterval, tt.capacity) if c := tb.takeAvailable(tb.startTime, tt.take); c != tt.take { t.Fatalf("#%d: %s, take = %d, want = %d", i, tt.about, c, tt.take) } if c := tb.available(tb.startTime); c != tt.expectCountAfterTake { t.Fatalf("#%d: %s, after take, available = %d, want = %d", i, tt.about, c, tt.expectCountAfterTake) } if c := tb.available(tb.startTime.Add(tt.sleep)); c != tt.expectCountAfterSleep { t.Fatalf("#%d: %s, after some time it should fill in new tokens, available = %d, want = %d", i, tt.about, c, tt.expectCountAfterSleep) } } } func BenchmarkWait(b *testing.B) { tb := NewBucket(1, 16*1024) for i := b.N - 1; i >= 0; i-- { tb.Wait(1) } }
{ "pile_set_name": "Github" }
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/KVOController GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/KVOController PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES
{ "pile_set_name": "Github" }
// DIE's signature file init("packer","nPack"); function detect(bShowType,bShowVersion,bShowOptions) { if(PE.compareEP("833D..........7505E901000000C3E841000000B8........2B05........A3........E85E000000E8")) { switch(PE.getEPSignature(42,7)) { case "E0010000E8EC06": sVersion="1.1.150.2006.Beta"; break; case "EC010000E8F806": sVersion="1.1.200.2006.Beta"; break; default: sVersion="1.1.xxx"; } bDetected=1; } else if(PE.compareEP("833D..........7505E901000000C3E846000000E873000000B8........2B05........A3........E89C000000E8")) { switch(PE.readDword(PE.nEP+47)) { case 0x204: sVersion="1.1.250.2006.Beta"; break; case 0x22D: sVersion="1.1.300.2006.Beta"; break; case 0x248: sVersion="1.1.800.2008.Beta"; break; default: sVersion="1.1.xxx"; } bDetected=1; } return result(bShowType,bShowVersion,bShowOptions); }
{ "pile_set_name": "Github" }
.. _pvenc: ============================ PVENC: video encoding engine ============================ .. contents:: .. todo:: write me Introduction ============ .. todo:: write me .. _pvenc-falcon: falcon parameters ================= Present on: v0: GK104:GM107 v1: GM107+ BAR0 address: v0: 0x1c2000 v1: 0x1c8000 PMC interrupt line: 16 PMC enable bit: 18 Version: v0: 4 v1: 5 Code segment size: 0x4000 Data segment size: v0: 0x1800 v1: 0x2c00 Fifo size: 0x10 Xfer slots: 8 Secretful: no Code TLB index bits: 8 Code ports: 1 Data ports: 1 Version 4 unknown caps: 27 Unified address space: no IO addressing type: simple Core clock: ??? Fermi VM engine: 0x19 Fermi VM client: HUB 0x1b Interrupts: ===== ===== ================== =============== Line Type Name Description ===== ===== ================== =============== 9 edge MEMIF_BREAK :ref:`MEMIF breakpoint <falcon-memif-intr-break>` ===== ===== ================== =============== Status bits: ===== ========== ============ Bit Name Description ===== ========== ============ 0 FALCON :ref:`Falcon unit <falcon-status>` 1 MEMIF :ref:`Memory interface <falcon-memif-status>` 2 ??? ??? 3 ??? ??? 4 ??? ??? 5 ??? ??? 6 ??? ??? 7 ??? ??? 8 ??? ??? 9 ??? ??? 10 ??? ??? 11 ??? ??? 12 ??? ??? ===== ========== ============ IO registers: :ref:`pvenc-io` .. todo:: status bits .. todo:: interrupts .. todo:: MEMIF ports .. todo:: core clock .. _pvenc-io: IO registers ============ .. space:: 8 gk104-pvenc 0x1000 H.264 video encoding engine .. todo:: write me .. space:: 8 gm107-pvenc 0x2000 H.264 video encoding engine .. todo:: write me .. todo:: write me
{ "pile_set_name": "Github" }
"use strict"; const derivable = require("../dist/derivable"); const { atom, derive, lens } = derivable; describe("the `is*` fns", () => { it("just work, don't worry about it", () => { const a = atom(0); const d = derive(() => a.get() * 2); const p = lens({ get: () => a.get() * 2, set: x => a.set(x / 2) }); expect(derivable.isAtom(a)).toBeTruthy(); expect(derivable.isAtom(d)).toBeFalsy(); expect(derivable.isAtom(p)).toBeTruthy(); expect(derivable.isDerivation(a)).toBeFalsy(); expect(derivable.isDerivation(d)).toBeTruthy(); expect(derivable.isDerivation(p)).toBeTruthy(); expect(derivable.isLens(a)).toBeFalsy(); expect(derivable.isLens(p)).toBeTruthy(); expect(derivable.isLens(d)).toBeFalsy(); expect(derivable.isDerivable(a)).toBeTruthy(); expect(derivable.isDerivable(d)).toBeTruthy(); expect(derivable.isDerivable(p)).toBeTruthy(); }); }); describe("the `transact` function", () => { it("executes a function in the context of a transaction", () => { const a = derivable.atom("a"); const b = derivable.atom("b"); let timesChanged = 0; derivable.struct({ a, b }).react( () => { timesChanged++; }, { skipFirst: true } ); expect(timesChanged).toBe(0); const setAAndB = (a_val, b_val) => { a.set(a_val); b.set(b_val); }; setAAndB("aye", "bee"); expect(timesChanged).toBe(2); expect(a.get()).toBe("aye"); expect(b.get()).toBe("bee"); derivable.transact(() => { setAAndB("a", "b"); }); expect(timesChanged).toBe(3); expect(a.get()).toBe("a"); expect(b.get()).toBe("b"); derivable.transact(() => { setAAndB(5, 6); }); expect(timesChanged).toBe(4); expect(a.get()).toBe(5); expect(b.get()).toBe(6); }); }); describe("the `transaction` function", () => { it("wraps a function such that its body is executed in a txn", () => { const a = derivable.atom("a"); const b = derivable.atom("b"); let timesChanged = 0; derivable.struct({ a, b }).react( () => { timesChanged++; }, { skipFirst: true } ); expect(timesChanged).toBe(0); const setAAndB = (a_val, b_val) => { a.set(a_val); b.set(b_val); return a_val + b_val; }; expect(setAAndB("aye", "bee")).toBe("ayebee"); expect(timesChanged).toBe(2); expect(a.get()).toBe("aye"); expect(b.get()).toBe("bee"); const tSetAAndB = derivable.transaction(setAAndB); expect(tSetAAndB("a", "b")).toBe("ab"); expect(timesChanged).toBe(3); expect(a.get()).toBe("a"); expect(b.get()).toBe("b"); expect(tSetAAndB(2, 3)).toBe(5); expect(timesChanged).toBe(4); expect(a.get()).toBe(2); expect(b.get()).toBe(3); }); }); describe("debug mode", () => { it( "causes derivations and reactors to store the stacktraces of their" + " instantiation points", () => { const d = derivable.derive(() => 0); expect(!d.stack).toBeTruthy(); derivable.setDebugMode(true); const e = derivable.derive(() => { throw Error(); }); expect(e.stack).toBeTruthy(); derivable.setDebugMode(false); } ); it("causes stack traces to be printed when things derivations and reactors throw errors", () => { const d = derivable.derive(() => 0); expect(!d.stack).toBeTruthy(); derivable.setDebugMode(true); const error = derivable.derive(() => { throw "cheese"; }); try { const err = console.error; let stack = void 0; console.error = _stack => { stack = _stack; }; error.get(); expect(stack).toBe(error.stack); console.error = err; } catch (e) { expect(e).toBe("cheese"); } derivable.setDebugMode(false); }); }); describe("the atomically function", () => { it("creates a transaction if not already in a transaction", () => { const $A = derivable.atom("a"); let numReactions = 0; $A.react( () => { numReactions++; }, { skipFirst: true } ); expect(numReactions).toBe(0); derivable.atomically(() => { $A.set("b"); expect(numReactions).toBe(0); }); expect(numReactions).toBe(1); }); it("doesn't create new transactions if already in a transaction", () => { const $A = derivable.atom("a"); derivable.transact(() => { try { derivable.atomically(() => { $A.set("b"); expect($A.get()).toBe("b"); throw new Error(); }); } catch (ignored) {} // no transaction created so change to $A persists expect($A.get()).toBe("b"); }); expect($A.get()).toBe("b"); }); }); describe("the atomic function", () => { it("creates a transaction if not already in a transaction", () => { const $A = derivable.atom("a"); let numReactions = 0; $A.react( () => { return numReactions++; }, { skipFirst: true } ); expect(numReactions).toBe(0); const res = derivable.atomic(() => { $A.set("b"); expect(numReactions).toBe(0); return 3; })(); expect(numReactions).toBe(1); expect(res).toBe(3); }); it("doesn't create new transactions if already in a transaction", () => { const $A = derivable.atom("a"); derivable.transact(() => { try { derivable.atomic(() => { $A.set("b"); expect($A.get()).toBe("b"); throw new Error(); })(); } catch (ignored) {} // no transaction created so change to $A persists expect($A.get()).toBe("b"); }); expect($A.get()).toBe("b"); }); });
{ "pile_set_name": "Github" }
13. 分页 =========
{ "pile_set_name": "Github" }
0.0.1 ----- - Initial version 0.0.2 ----- - routes « threads » renamed to « discussions »
{ "pile_set_name": "Github" }
import React from 'react'; import { DndProvider } from 'react-dnd'; import { Flipper, Flipped } from 'react-flip-toolkit'; import HTML5Backend from 'react-dnd-html5-backend'; import Sortly, { ContextProvider, useDrag, useDrop } from 'react-sortly'; // Components import Block from './block'; // Services import { findBetterImageAndText } from '../../../services/blocks_service'; const buildItems = props => { return (props.sectionContent.blocks || []).map(block => { const definition = props.sectionDefinition.blocks.find(def => def.type === block.type) if (definition === null || definition === undefined) return null; var { image, text } = findBetterImageAndText(block, definition) // we don't want the blocks to all have the same text if (text === null && block.index) text = `${definition.name} #${block.index}` return { block, text, image, id: block.id, depth: block.depth || 0, blockDefinition: definition, editPath: props.editBlockPath(props.section, block.type, block.id) } }); } const ItemRenderer = (props) => { const { data } = props; const [, drop] = useDrop(); const [{ isDragging }, drag, preview] = useDrag({ collect: (monitor) => ({ isDragging: monitor.isDragging(), }), }); return ( <Flipped flipId={data.id}> <div ref={ref => drop(preview(ref))}> <div style={{ marginLeft: data.depth * 20 }}> <Block isDragging={isDragging} drag={drag} {...data} /> </div> </div> </Flipped> ); }; const SortableTree = props => { const items = buildItems(props); const onChange = sortedItems => { props.moveBlock( sortedItems.map(item => ({ ...item.block, depth: item.depth })) ); }; return ( <Flipper flipKey={items.map(({ id }) => id).join('.')} spring="stiff"> <Sortly items={items} onChange={onChange} maxDepth={props.maxDepth}> {(props) => <ItemRenderer {...props} />} </Sortly> </Flipper> ); }; const BlockList = props => ( <DndProvider backend={HTML5Backend}> <ContextProvider> <SortableTree {...props} /> </ContextProvider> </DndProvider> ); export default BlockList;
{ "pile_set_name": "Github" }
{ "version": "eosio::abi/1.1", "structs": [ { "name": "abi_hash", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "hash", "type": "checksum256" } ] }, { "name": "activate", "base": "", "fields": [ { "name": "feature_digest", "type": "checksum256" } ] }, { "name": "authority", "base": "", "fields": [ { "name": "threshold", "type": "uint32" }, { "name": "keys", "type": "key_weight[]" }, { "name": "accounts", "type": "permission_level_weight[]" }, { "name": "waits", "type": "wait_weight[]" } ] }, { "name": "bid_refund", "base": "", "fields": [ { "name": "bidder", "type": "name" }, { "name": "amount", "type": "asset" } ] }, { "name": "bidname", "base": "", "fields": [ { "name": "bidder", "type": "name" }, { "name": "newname", "type": "name" }, { "name": "bid", "type": "asset" } ] }, { "name": "bidrefund", "base": "", "fields": [ { "name": "bidder", "type": "name" }, { "name": "newname", "type": "name" } ] }, { "name": "block_header", "base": "", "fields": [ { "name": "timestamp", "type": "uint32" }, { "name": "producer", "type": "name" }, { "name": "confirmed", "type": "uint16" }, { "name": "previous", "type": "checksum256" }, { "name": "transaction_mroot", "type": "checksum256" }, { "name": "action_mroot", "type": "checksum256" }, { "name": "schedule_version", "type": "uint32" }, { "name": "new_producers", "type": "producer_schedule?" } ] }, { "name": "blockchain_parameters", "base": "", "fields": [ { "name": "max_block_net_usage", "type": "uint64" }, { "name": "target_block_net_usage_pct", "type": "uint32" }, { "name": "max_transaction_net_usage", "type": "uint32" }, { "name": "base_per_transaction_net_usage", "type": "uint32" }, { "name": "net_usage_leeway", "type": "uint32" }, { "name": "context_free_discount_net_usage_num", "type": "uint32" }, { "name": "context_free_discount_net_usage_den", "type": "uint32" }, { "name": "max_block_cpu_usage", "type": "uint32" }, { "name": "target_block_cpu_usage_pct", "type": "uint32" }, { "name": "max_transaction_cpu_usage", "type": "uint32" }, { "name": "min_transaction_cpu_usage", "type": "uint32" }, { "name": "max_transaction_lifetime", "type": "uint32" }, { "name": "deferred_trx_expiration_window", "type": "uint32" }, { "name": "max_transaction_delay", "type": "uint32" }, { "name": "max_inline_action_size", "type": "uint32" }, { "name": "max_inline_action_depth", "type": "uint16" }, { "name": "max_authority_depth", "type": "uint16" } ] }, { "name": "buyram", "base": "", "fields": [ { "name": "payer", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "quant", "type": "asset" } ] }, { "name": "buyrambytes", "base": "", "fields": [ { "name": "payer", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "bytes", "type": "uint32" } ] }, { "name": "buyrex", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "amount", "type": "asset" } ] }, { "name": "canceldelay", "base": "", "fields": [ { "name": "canceling_auth", "type": "permission_level" }, { "name": "trx_id", "type": "checksum256" } ] }, { "name": "claimrewards", "base": "", "fields": [ { "name": "owner", "type": "name" } ] }, { "name": "closerex", "base": "", "fields": [ { "name": "owner", "type": "name" } ] }, { "name": "cnclrexorder", "base": "", "fields": [ { "name": "owner", "type": "name" } ] }, { "name": "connector", "base": "", "fields": [ { "name": "balance", "type": "asset" }, { "name": "weight", "type": "float64" } ] }, { "name": "consolidate", "base": "", "fields": [ { "name": "owner", "type": "name" } ] }, { "name": "defcpuloan", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "loan_num", "type": "uint64" }, { "name": "amount", "type": "asset" } ] }, { "name": "defnetloan", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "loan_num", "type": "uint64" }, { "name": "amount", "type": "asset" } ] }, { "name": "delegatebw", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "stake_net_quantity", "type": "asset" }, { "name": "stake_cpu_quantity", "type": "asset" }, { "name": "transfer", "type": "bool" } ] }, { "name": "delegated_bandwidth", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "to", "type": "name" }, { "name": "net_weight", "type": "asset" }, { "name": "cpu_weight", "type": "asset" } ] }, { "name": "deleteauth", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "permission", "type": "name" } ] }, { "name": "deposit", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "amount", "type": "asset" } ] }, { "name": "eosio_global_state", "base": "blockchain_parameters", "fields": [ { "name": "max_ram_size", "type": "uint64" }, { "name": "total_ram_bytes_reserved", "type": "uint64" }, { "name": "total_ram_stake", "type": "int64" }, { "name": "last_producer_schedule_update", "type": "block_timestamp_type" }, { "name": "last_pervote_bucket_fill", "type": "time_point" }, { "name": "pervote_bucket", "type": "int64" }, { "name": "perblock_bucket", "type": "int64" }, { "name": "total_unpaid_blocks", "type": "uint32" }, { "name": "total_activated_stake", "type": "int64" }, { "name": "thresh_activated_stake_time", "type": "time_point" }, { "name": "last_producer_schedule_size", "type": "uint16" }, { "name": "total_producer_vote_weight", "type": "float64" }, { "name": "last_name_close", "type": "block_timestamp_type" } ] }, { "name": "eosio_global_state2", "base": "", "fields": [ { "name": "new_ram_per_block", "type": "uint16" }, { "name": "last_ram_increase", "type": "block_timestamp_type" }, { "name": "last_block_num", "type": "block_timestamp_type" }, { "name": "total_producer_votepay_share", "type": "float64" }, { "name": "revision", "type": "uint8" } ] }, { "name": "eosio_global_state3", "base": "", "fields": [ { "name": "last_vpay_state_update", "type": "time_point" }, { "name": "total_vpay_share_change_rate", "type": "float64" } ] }, { "name": "exchange_state", "base": "", "fields": [ { "name": "supply", "type": "asset" }, { "name": "base", "type": "connector" }, { "name": "quote", "type": "connector" } ] }, { "name": "fundcpuloan", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "loan_num", "type": "uint64" }, { "name": "payment", "type": "asset" } ] }, { "name": "fundnetloan", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "loan_num", "type": "uint64" }, { "name": "payment", "type": "asset" } ] }, { "name": "init", "base": "", "fields": [ { "name": "version", "type": "varuint32" }, { "name": "core", "type": "symbol" } ] }, { "name": "key_weight", "base": "", "fields": [ { "name": "key", "type": "public_key" }, { "name": "weight", "type": "uint16" } ] }, { "name": "linkauth", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "code", "type": "name" }, { "name": "type", "type": "name" }, { "name": "requirement", "type": "name" } ] }, { "name": "mvfrsavings", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "rex", "type": "asset" } ] }, { "name": "mvtosavings", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "rex", "type": "asset" } ] }, { "name": "name_bid", "base": "", "fields": [ { "name": "newname", "type": "name" }, { "name": "high_bidder", "type": "name" }, { "name": "high_bid", "type": "int64" }, { "name": "last_bid_time", "type": "time_point" } ] }, { "name": "newaccount", "base": "", "fields": [ { "name": "creator", "type": "name" }, { "name": "name", "type": "name" }, { "name": "owner", "type": "authority" }, { "name": "active", "type": "authority" } ] }, { "name": "onblock", "base": "", "fields": [ { "name": "header", "type": "block_header" } ] }, { "name": "onerror", "base": "", "fields": [ { "name": "sender_id", "type": "uint128" }, { "name": "sent_trx", "type": "bytes" } ] }, { "name": "pair_time_point_sec_int64", "base": "", "fields": [ { "name": "first", "type": "time_point_sec" }, { "name": "second", "type": "int64" } ] }, { "name": "permission_level", "base": "", "fields": [ { "name": "actor", "type": "name" }, { "name": "permission", "type": "name" } ] }, { "name": "permission_level_weight", "base": "", "fields": [ { "name": "permission", "type": "permission_level" }, { "name": "weight", "type": "uint16" } ] }, { "name": "producer_info", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "total_votes", "type": "float64" }, { "name": "producer_key", "type": "public_key" }, { "name": "is_active", "type": "bool" }, { "name": "url", "type": "string" }, { "name": "unpaid_blocks", "type": "uint32" }, { "name": "last_claim_time", "type": "time_point" }, { "name": "location", "type": "uint16" } ] }, { "name": "producer_info2", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "votepay_share", "type": "float64" }, { "name": "last_votepay_share_update", "type": "time_point" } ] }, { "name": "producer_key", "base": "", "fields": [ { "name": "producer_name", "type": "name" }, { "name": "block_signing_key", "type": "public_key" } ] }, { "name": "producer_schedule", "base": "", "fields": [ { "name": "version", "type": "uint32" }, { "name": "producers", "type": "producer_key[]" } ] }, { "name": "refund", "base": "", "fields": [ { "name": "owner", "type": "name" } ] }, { "name": "refund_request", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "request_time", "type": "time_point_sec" }, { "name": "net_amount", "type": "asset" }, { "name": "cpu_amount", "type": "asset" } ] }, { "name": "regproducer", "base": "", "fields": [ { "name": "producer", "type": "name" }, { "name": "producer_key", "type": "public_key" }, { "name": "url", "type": "string" }, { "name": "location", "type": "uint16" } ] }, { "name": "regproxy", "base": "", "fields": [ { "name": "proxy", "type": "name" }, { "name": "isproxy", "type": "bool" } ] }, { "name": "rentcpu", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "loan_payment", "type": "asset" }, { "name": "loan_fund", "type": "asset" } ] }, { "name": "rentnet", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "loan_payment", "type": "asset" }, { "name": "loan_fund", "type": "asset" } ] }, { "name": "rex_balance", "base": "", "fields": [ { "name": "version", "type": "uint8" }, { "name": "owner", "type": "name" }, { "name": "vote_stake", "type": "asset" }, { "name": "rex_balance", "type": "asset" }, { "name": "matured_rex", "type": "int64" }, { "name": "rex_maturities", "type": "pair_time_point_sec_int64[]" } ] }, { "name": "rex_fund", "base": "", "fields": [ { "name": "version", "type": "uint8" }, { "name": "owner", "type": "name" }, { "name": "balance", "type": "asset" } ] }, { "name": "rex_loan", "base": "", "fields": [ { "name": "version", "type": "uint8" }, { "name": "from", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "payment", "type": "asset" }, { "name": "balance", "type": "asset" }, { "name": "total_staked", "type": "asset" }, { "name": "loan_num", "type": "uint64" }, { "name": "expiration", "type": "time_point" } ] }, { "name": "rex_order", "base": "", "fields": [ { "name": "version", "type": "uint8" }, { "name": "owner", "type": "name" }, { "name": "rex_requested", "type": "asset" }, { "name": "proceeds", "type": "asset" }, { "name": "stake_change", "type": "asset" }, { "name": "order_time", "type": "time_point" }, { "name": "is_open", "type": "bool" } ] }, { "name": "rex_pool", "base": "", "fields": [ { "name": "version", "type": "uint8" }, { "name": "total_lent", "type": "asset" }, { "name": "total_unlent", "type": "asset" }, { "name": "total_rent", "type": "asset" }, { "name": "total_lendable", "type": "asset" }, { "name": "total_rex", "type": "asset" }, { "name": "namebid_proceeds", "type": "asset" }, { "name": "loan_num", "type": "uint64" } ] }, { "name": "rexexec", "base": "", "fields": [ { "name": "user", "type": "name" }, { "name": "max", "type": "uint16" } ] }, { "name": "rmvproducer", "base": "", "fields": [ { "name": "producer", "type": "name" } ] }, { "name": "sellram", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "bytes", "type": "int64" } ] }, { "name": "sellrex", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "rex", "type": "asset" } ] }, { "name": "setabi", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "abi", "type": "bytes" } ] }, { "name": "setacctcpu", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "cpu_weight", "type": "int64?" } ] }, { "name": "setacctnet", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "net_weight", "type": "int64?" } ] }, { "name": "setacctram", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "ram_bytes", "type": "int64?" } ] }, { "name": "setalimits", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "ram_bytes", "type": "int64" }, { "name": "net_weight", "type": "int64" }, { "name": "cpu_weight", "type": "int64" } ] }, { "name": "setcode", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "vmtype", "type": "uint8" }, { "name": "vmversion", "type": "uint8" }, { "name": "code", "type": "bytes" } ] }, { "name": "setparams", "base": "", "fields": [ { "name": "params", "type": "blockchain_parameters" } ] }, { "name": "setpriv", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "is_priv", "type": "uint8" } ] }, { "name": "setram", "base": "", "fields": [ { "name": "max_ram_size", "type": "uint64" } ] }, { "name": "setramrate", "base": "", "fields": [ { "name": "bytes_per_block", "type": "uint16" } ] }, { "name": "setrex", "base": "", "fields": [ { "name": "balance", "type": "asset" } ] }, { "name": "undelegatebw", "base": "", "fields": [ { "name": "from", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "unstake_net_quantity", "type": "asset" }, { "name": "unstake_cpu_quantity", "type": "asset" } ] }, { "name": "unlinkauth", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "code", "type": "name" }, { "name": "type", "type": "name" } ] }, { "name": "unregprod", "base": "", "fields": [ { "name": "producer", "type": "name" } ] }, { "name": "unstaketorex", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "receiver", "type": "name" }, { "name": "from_net", "type": "asset" }, { "name": "from_cpu", "type": "asset" } ] }, { "name": "updateauth", "base": "", "fields": [ { "name": "account", "type": "name" }, { "name": "permission", "type": "name" }, { "name": "parent", "type": "name" }, { "name": "auth", "type": "authority" } ] }, { "name": "updaterex", "base": "", "fields": [ { "name": "owner", "type": "name" } ] }, { "name": "updtrevision", "base": "", "fields": [ { "name": "revision", "type": "uint8" } ] }, { "name": "user_resources", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "net_weight", "type": "asset" }, { "name": "cpu_weight", "type": "asset" }, { "name": "ram_bytes", "type": "int64" } ] }, { "name": "voteproducer", "base": "", "fields": [ { "name": "voter", "type": "name" }, { "name": "proxy", "type": "name" }, { "name": "producers", "type": "name[]" } ] }, { "name": "voter_info", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "proxy", "type": "name" }, { "name": "producers", "type": "name[]" }, { "name": "staked", "type": "int64" }, { "name": "last_vote_weight", "type": "float64" }, { "name": "proxied_vote_weight", "type": "float64" }, { "name": "is_proxy", "type": "bool" }, { "name": "flags1", "type": "uint32" }, { "name": "reserved2", "type": "uint32" }, { "name": "reserved3", "type": "asset" } ] }, { "name": "wait_weight", "base": "", "fields": [ { "name": "wait_sec", "type": "uint32" }, { "name": "weight", "type": "uint16" } ] }, { "name": "withdraw", "base": "", "fields": [ { "name": "owner", "type": "name" }, { "name": "amount", "type": "asset" } ] } ], "actions": [ { "name": "activate", "type": "activate", "ricardian_contract": "" }, { "name": "bidname", "type": "bidname", "ricardian_contract": "" }, { "name": "bidrefund", "type": "bidrefund", "ricardian_contract": "" }, { "name": "buyram", "type": "buyram", "ricardian_contract": "" }, { "name": "buyrambytes", "type": "buyrambytes", "ricardian_contract": "" }, { "name": "buyrex", "type": "buyrex", "ricardian_contract": "" }, { "name": "canceldelay", "type": "canceldelay", "ricardian_contract": "" }, { "name": "claimrewards", "type": "claimrewards", "ricardian_contract": "" }, { "name": "closerex", "type": "closerex", "ricardian_contract": "" }, { "name": "cnclrexorder", "type": "cnclrexorder", "ricardian_contract": "" }, { "name": "consolidate", "type": "consolidate", "ricardian_contract": "" }, { "name": "defcpuloan", "type": "defcpuloan", "ricardian_contract": "" }, { "name": "defnetloan", "type": "defnetloan", "ricardian_contract": "" }, { "name": "delegatebw", "type": "delegatebw", "ricardian_contract": "" }, { "name": "deleteauth", "type": "deleteauth", "ricardian_contract": "" }, { "name": "deposit", "type": "deposit", "ricardian_contract": "" }, { "name": "fundcpuloan", "type": "fundcpuloan", "ricardian_contract": "" }, { "name": "fundnetloan", "type": "fundnetloan", "ricardian_contract": "" }, { "name": "init", "type": "init", "ricardian_contract": "" }, { "name": "linkauth", "type": "linkauth", "ricardian_contract": "" }, { "name": "mvfrsavings", "type": "mvfrsavings", "ricardian_contract": "" }, { "name": "mvtosavings", "type": "mvtosavings", "ricardian_contract": "" }, { "name": "newaccount", "type": "newaccount", "ricardian_contract": "" }, { "name": "onblock", "type": "onblock", "ricardian_contract": "" }, { "name": "onerror", "type": "onerror", "ricardian_contract": "" }, { "name": "refund", "type": "refund", "ricardian_contract": "" }, { "name": "regproducer", "type": "regproducer", "ricardian_contract": "" }, { "name": "regproxy", "type": "regproxy", "ricardian_contract": "" }, { "name": "rentcpu", "type": "rentcpu", "ricardian_contract": "" }, { "name": "rentnet", "type": "rentnet", "ricardian_contract": "" }, { "name": "rexexec", "type": "rexexec", "ricardian_contract": "" }, { "name": "rmvproducer", "type": "rmvproducer", "ricardian_contract": "" }, { "name": "sellram", "type": "sellram", "ricardian_contract": "" }, { "name": "sellrex", "type": "sellrex", "ricardian_contract": "" }, { "name": "setabi", "type": "setabi", "ricardian_contract": "" }, { "name": "setacctcpu", "type": "setacctcpu", "ricardian_contract": "" }, { "name": "setacctnet", "type": "setacctnet", "ricardian_contract": "" }, { "name": "setacctram", "type": "setacctram", "ricardian_contract": "" }, { "name": "setalimits", "type": "setalimits", "ricardian_contract": "" }, { "name": "setcode", "type": "setcode", "ricardian_contract": "" }, { "name": "setparams", "type": "setparams", "ricardian_contract": "" }, { "name": "setpriv", "type": "setpriv", "ricardian_contract": "" }, { "name": "setram", "type": "setram", "ricardian_contract": "" }, { "name": "setramrate", "type": "setramrate", "ricardian_contract": "" }, { "name": "setrex", "type": "setrex", "ricardian_contract": "" }, { "name": "undelegatebw", "type": "undelegatebw", "ricardian_contract": "" }, { "name": "unlinkauth", "type": "unlinkauth", "ricardian_contract": "" }, { "name": "unregprod", "type": "unregprod", "ricardian_contract": "" }, { "name": "unstaketorex", "type": "unstaketorex", "ricardian_contract": "" }, { "name": "updateauth", "type": "updateauth", "ricardian_contract": "" }, { "name": "updaterex", "type": "updaterex", "ricardian_contract": "" }, { "name": "updtrevision", "type": "updtrevision", "ricardian_contract": "" }, { "name": "voteproducer", "type": "voteproducer", "ricardian_contract": "" }, { "name": "withdraw", "type": "withdraw", "ricardian_contract": "" } ], "tables": [ { "name": "abihash", "index_type": "i64", "type": "abi_hash" }, { "name": "bidrefunds", "index_type": "i64", "type": "bid_refund" }, { "name": "cpuloan", "index_type": "i64", "type": "rex_loan" }, { "name": "delband", "index_type": "i64", "type": "delegated_bandwidth" }, { "name": "global", "index_type": "i64", "type": "eosio_global_state" }, { "name": "global2", "index_type": "i64", "type": "eosio_global_state2" }, { "name": "global3", "index_type": "i64", "type": "eosio_global_state3" }, { "name": "namebids", "index_type": "i64", "type": "name_bid" }, { "name": "netloan", "index_type": "i64", "type": "rex_loan" }, { "name": "producers", "index_type": "i64", "type": "producer_info" }, { "name": "producers2", "index_type": "i64", "type": "producer_info2" }, { "name": "rammarket", "index_type": "i64", "type": "exchange_state" }, { "name": "refunds", "index_type": "i64", "type": "refund_request" }, { "name": "rexbal", "index_type": "i64", "type": "rex_balance" }, { "name": "rexfund", "index_type": "i64", "type": "rex_fund" }, { "name": "rexpool", "index_type": "i64", "type": "rex_pool" }, { "name": "rexqueue", "index_type": "i64", "type": "rex_order" }, { "name": "userres", "index_type": "i64", "type": "user_resources" }, { "name": "voters", "index_type": "i64", "type": "voter_info" } ] }
{ "pile_set_name": "Github" }
// cgo -godefs types_aix.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc,aix package unix const ( SizeofPtr = 0x4 SizeofShort = 0x2 SizeofInt = 0x4 SizeofLong = 0x4 SizeofLongLong = 0x8 PathMax = 0x3ff ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type off64 int64 type off int32 type Mode_t uint32 type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timeval32 struct { Sec int32 Usec int32 } type Timex struct{} type Time_t int32 type Tms struct{} type Utimbuf struct { Actime int32 Modtime int32 } type Timezone struct { Minuteswest int32 Dsttime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type Pid_t int32 type _Gid_t uint32 type dev_t uint32 type Stat_t struct { Dev uint32 Ino uint32 Mode uint32 Nlink int16 Flag uint16 Uid uint32 Gid uint32 Rdev uint32 Size int32 Atim Timespec Mtim Timespec Ctim Timespec Blksize int32 Blocks int32 Vfstype int32 Vfs uint32 Type uint32 Gen uint32 Reserved [9]uint32 } type StatxTimestamp struct{} type Statx_t struct{} type Dirent struct { Offset uint32 Ino uint32 Reclen uint16 Namlen uint16 Name [256]uint8 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [1023]uint8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [120]uint8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]uint8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [1012]uint8 } type _Socklen uint32 type Cmsghdr struct { Len uint32 Level int32 Type int32 } type ICMPv6Filter struct { Filt [8]uint32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type Linger struct { Onoff int32 Linger int32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x404 SizeofSockaddrUnix = 0x401 SizeofSockaddrDatalink = 0x80 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofICMPv6Filter = 0x20 ) const ( SizeofIfMsghdr = 0x10 ) type IfMsgHdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Addrlen uint8 _ [1]byte } type FdSet struct { Bits [2048]int32 } type Utsname struct { Sysname [32]byte Nodename [32]byte Release [32]byte Version [32]byte Machine [32]byte } type Ustat_t struct{} type Sigset_t struct { Losigs uint32 Hisigs uint32 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x1 AT_SYMLINK_NOFOLLOW = 0x1 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [16]uint8 } type Termio struct { Iflag uint16 Oflag uint16 Cflag uint16 Lflag uint16 Line uint8 Cc [8]uint8 _ [1]byte } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type PollFd struct { Fd int32 Events uint16 Revents uint16 } const ( POLLERR = 0x4000 POLLHUP = 0x2000 POLLIN = 0x1 POLLNVAL = 0x8000 POLLOUT = 0x2 POLLPRI = 0x4 POLLRDBAND = 0x20 POLLRDNORM = 0x10 POLLWRBAND = 0x40 POLLWRNORM = 0x2 ) type Flock_t struct { Type int16 Whence int16 Sysid uint32 Pid int32 Vfs int32 Start int64 Len int64 } type Fsid_t struct { Val [2]uint32 } type Fsid64_t struct { Val [2]uint64 } type Statfs_t struct { Version int32 Type int32 Bsize uint32 Blocks uint32 Bfree uint32 Bavail uint32 Files uint32 Ffree uint32 Fsid Fsid_t Vfstype int32 Fsize uint32 Vfsnumber int32 Vfsoff int32 Vfslen int32 Vfsvers int32 Fname [32]uint8 Fpack [32]uint8 Name_max int32 } const RNDGETENTCNT = 0x80045200
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011 Broadcom Corporation * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef BRCMFMAC_USB_H #define BRCMFMAC_USB_H enum brcmf_usb_state { BRCMFMAC_USB_STATE_DOWN, BRCMFMAC_USB_STATE_DL_FAIL, BRCMFMAC_USB_STATE_DL_DONE, BRCMFMAC_USB_STATE_UP, BRCMFMAC_USB_STATE_SLEEP }; struct brcmf_stats { u32 tx_ctlpkts; u32 tx_ctlerrs; u32 rx_ctlpkts; u32 rx_ctlerrs; }; struct brcmf_usbdev { struct brcmf_bus *bus; struct brcmf_usbdev_info *devinfo; enum brcmf_usb_state state; struct brcmf_stats stats; int ntxq, nrxq, rxsize; u32 bus_mtu; int devid; int chiprev; /* chip revsion number */ }; /* IO Request Block (IRB) */ struct brcmf_usbreq { struct list_head list; struct brcmf_usbdev_info *devinfo; struct urb *urb; struct sk_buff *skb; }; #endif /* BRCMFMAC_USB_H */
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>模拟迁徙</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hmap-js/dist/hmap.css"> <style> html, body, #map { height: 100%; padding: 0; margin: 0; } </style> </head> <body> <div id="map"></div> <script src="https://cdn.jsdelivr.net/npm/hmap-js/dist/hmap.js"></script> <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.js"></script> <script src="https://cdn.jsdelivr.net/npm/ol3-echarts/dist/ol3Echarts.js"></script> <!--<script src="../../../dist/ol3Echarts.js"></script>--> <script> var map = new HMap('map', { controls: { loading: true, zoomSlider: true, fullScreen: false }, view: { center: [113.48639681199214, 23.31897543042969], projection: 'EPSG:4326', zoom: 10, // resolution }, baseLayers: [ { layerName: 'vector', isDefault: true, layerType: 'TileXYZ', projection: 'EPSG:3857', tileGrid: { tileSize: 256, extent: [-2.0037507067161843E7, -3.0240971958386254E7, 2.0037507067161843E7, 3.0240971958386205E7], origin: [-2.0037508342787E7, 2.0037508342787E7], resolutions: [ 156543.03392800014, 78271.51696399994, 39135.75848200009, 19567.87924099992, 9783.93962049996, 4891.96981024998, 2445.98490512499, 1222.992452562495, 611.4962262813797, 305.74811314055756, 152.87405657041106, 76.43702828507324, 38.21851414253662, 19.10925707126831, 9.554628535634155, 4.77731426794937, 2.388657133974685 ] }, layerUrl: 'http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}' } ] }); var echartslayer = new ol3Echarts(getOption()); echartslayer.appendTo(map.getMap()); function getOption () { var geoCoordMap = { '上海': [121.4648, 31.2891], '东莞': [113.8953, 22.901], '东营': [118.7073, 37.5513], '中山': [113.4229, 22.478], '临汾': [111.4783, 36.1615], '临沂': [118.3118, 35.2936], '丹东': [124.541, 40.4242], '丽水': [119.5642, 28.1854], '乌鲁木齐': [87.9236, 43.5883], '佛山': [112.8955, 23.1097], '保定': [115.0488, 39.0948], '兰州': [103.5901, 36.3043], '包头': [110.3467, 41.4899], '北京': [116.4551, 40.2539], '北海': [109.314, 21.6211], '南京': [118.8062, 31.9208], '南宁': [108.479, 23.1152], '南昌': [116.0046, 28.6633], '南通': [121.1023, 32.1625], '厦门': [118.1689, 24.6478], '台州': [121.1353, 28.6688], '合肥': [117.29, 32.0581], '呼和浩特': [111.4124, 40.4901], '咸阳': [108.4131, 34.8706], '哈尔滨': [127.9688, 45.368], '唐山': [118.4766, 39.6826], '嘉兴': [120.9155, 30.6354], '大同': [113.7854, 39.8035], '大连': [122.2229, 39.4409], '天津': [117.4219, 39.4189], '太原': [112.3352, 37.9413], '威海': [121.9482, 37.1393], '宁波': [121.5967, 29.6466], '宝鸡': [107.1826, 34.3433], '宿迁': [118.5535, 33.7775], '常州': [119.4543, 31.5582], '广州': [113.5107, 23.2196], '廊坊': [116.521, 39.0509], '延安': [109.1052, 36.4252], '张家口': [115.1477, 40.8527], '徐州': [117.5208, 34.3268], '德州': [116.6858, 37.2107], '惠州': [114.6204, 23.1647], '成都': [103.9526, 30.7617], '扬州': [119.4653, 32.8162], '承德': [117.5757, 41.4075], '拉萨': [91.1865, 30.1465], '无锡': [120.3442, 31.5527], '日照': [119.2786, 35.5023], '昆明': [102.9199, 25.4663], '杭州': [119.5313, 29.8773], '枣庄': [117.323, 34.8926], '柳州': [109.3799, 24.9774], '株洲': [113.5327, 27.0319], '武汉': [114.3896, 30.6628], '汕头': [117.1692, 23.3405], '江门': [112.6318, 22.1484], '沈阳': [123.1238, 42.1216], '沧州': [116.8286, 38.2104], '河源': [114.917, 23.9722], '泉州': [118.3228, 25.1147], '泰安': [117.0264, 36.0516], '泰州': [120.0586, 32.5525], '济南': [117.1582, 36.8701], '济宁': [116.8286, 35.3375], '海口': [110.3893, 19.8516], '淄博': [118.0371, 36.6064], '淮安': [118.927, 33.4039], '深圳': [114.5435, 22.5439], '清远': [112.9175, 24.3292], '温州': [120.498, 27.8119], '渭南': [109.7864, 35.0299], '湖州': [119.8608, 30.7782], '湘潭': [112.5439, 27.7075], '滨州': [117.8174, 37.4963], '潍坊': [119.0918, 36.524], '烟台': [120.7397, 37.5128], '玉溪': [101.9312, 23.8898], '珠海': [113.7305, 22.1155], '盐城': [120.2234, 33.5577], '盘锦': [121.9482, 41.0449], '石家庄': [114.4995, 38.1006], '福州': [119.4543, 25.9222], '秦皇岛': [119.2126, 40.0232], '绍兴': [120.564, 29.7565], '聊城': [115.9167, 36.4032], '肇庆': [112.1265, 23.5822], '舟山': [122.2559, 30.2234], '苏州': [120.6519, 31.3989], '莱芜': [117.6526, 36.2714], '菏泽': [115.6201, 35.2057], '营口': [122.4316, 40.4297], '葫芦岛': [120.1575, 40.578], '衡水': [115.8838, 37.7161], '衢州': [118.6853, 28.8666], '西宁': [101.4038, 36.8207], '西安': [109.1162, 34.2004], '贵阳': [106.6992, 26.7682], '连云港': [119.1248, 34.552], '邢台': [114.8071, 37.2821], '邯郸': [114.4775, 36.535], '郑州': [113.4668, 34.6234], '鄂尔多斯': [108.9734, 39.2487], '重庆': [107.7539, 30.1904], '金华': [120.0037, 29.1028], '铜川': [109.0393, 35.1947], '银川': [106.3586, 38.1775], '镇江': [119.4763, 31.9702], '长春': [125.8154, 44.2584], '长沙': [113.0823, 28.2568], '长治': [112.8625, 36.4746], '阳泉': [113.4778, 38.0951], '青岛': [120.4651, 36.3373], '韶关': [113.7964, 24.7028] }; var BJData = [ [{name: '北京'}, {name: '上海', value: 95}], [{name: '北京'}, {name: '广州', value: 90}], [{name: '北京'}, {name: '大连', value: 80}], [{name: '北京'}, {name: '南宁', value: 70}], [{name: '北京'}, {name: '南昌', value: 60}], [{name: '北京'}, {name: '拉萨', value: 50}], [{name: '北京'}, {name: '长春', value: 40}], [{name: '北京'}, {name: '包头', value: 30}], [{name: '北京'}, {name: '重庆', value: 20}], [{name: '北京'}, {name: '常州', value: 10}] ]; var SHData = [ [{name: '上海'}, {name: '包头', value: 95}], [{name: '上海'}, {name: '昆明', value: 90}], [{name: '上海'}, {name: '广州', value: 80}], [{name: '上海'}, {name: '郑州', value: 70}], [{name: '上海'}, {name: '长春', value: 60}], [{name: '上海'}, {name: '重庆', value: 50}], [{name: '上海'}, {name: '长沙', value: 40}], [{name: '上海'}, {name: '北京', value: 30}], [{name: '上海'}, {name: '丹东', value: 20}], [{name: '上海'}, {name: '大连', value: 10}] ]; var GZData = [ [{name: '广州'}, {name: '福州', value: 95}], [{name: '广州'}, {name: '太原', value: 90}], [{name: '广州'}, {name: '长春', value: 80}], [{name: '广州'}, {name: '重庆', value: 70}], [{name: '广州'}, {name: '西安', value: 60}], [{name: '广州'}, {name: '成都', value: 50}], [{name: '广州'}, {name: '常州', value: 40}], [{name: '广州'}, {name: '北京', value: 30}], [{name: '广州'}, {name: '北海', value: 20}], [{name: '广州'}, {name: '海口', value: 10}] ]; var planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'; var convertData = function (data) { var res = []; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; var fromCoord = geoCoordMap[dataItem[0].name]; var toCoord = geoCoordMap[dataItem[1].name]; if (fromCoord && toCoord) { res.push({ fromName: dataItem[0].name, toName: dataItem[1].name, coords: [fromCoord, toCoord] }); } } return res; }; var color = ['#a6c84c', '#ffa022', '#46bee9']; var series = []; [ ['北京', BJData], ['上海', SHData], ['广州', GZData]].forEach( function (item, i) { series.push({ name: item[0] + ' Top10', type: 'lines', zlevel: 1, effect: { show: true, period: 6, trailLength: 0.7, color: '#fff', symbolSize: 3 }, lineStyle: { normal: { color: color[i], width: 0, curveness: 0.2 } }, data: convertData(item[1]) }, { name: item[0] + ' Top10', type: 'lines', zlevel: 2, effect: { show: true, period: 6, trailLength: 0, symbol: planePath, symbolSize: 15 }, lineStyle: { normal: { color: color[i], width: 1, opacity: 0.4, curveness: 0.2 } }, data: convertData(item[1]) }, { name: item[0] + ' Top10', type: 'effectScatter', coordinateSystem: 'geo', zlevel: 2, rippleEffect: { brushType: 'stroke' }, label: { normal: { show: true, position: 'right', formatter: '{b}' } }, symbolSize: function (val) { return val[2] / 8; }, itemStyle: { normal: { color: color[i] } }, data: item[1].map(function (dataItem) { return { name: dataItem[1].name, value: geoCoordMap[dataItem[1].name].concat([dataItem[1].value]) }; }) }); }); return { tooltip: { trigger: 'item' }, series: series }; } </script> </body> </html>
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 1991, 2020 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ /** * @file * @ingroup GC_Base_Core */ #if !defined(MARKMAP_HPP_) #define MARKMAP_HPP_ #include "omrcfg.h" #include "omr.h" #include "omrmodroncore.h" #include "HeapMap.hpp" #define J9MODRON_HEAP_SLOTS_PER_MARK_BIT J9MODRON_HEAP_SLOTS_PER_HEAPMAP_BIT #define J9MODRON_HEAP_SLOTS_PER_MARK_SLOT J9MODRON_HEAP_SLOTS_PER_HEAPMAP_SLOT #define J9MODRON_HEAP_BYTES_PER_MARK_BYTE J9MODRON_HEAP_BYTES_PER_HEAPMAP_BYTE #define BITS_PER_BYTE 8 class MM_EnvironmentBase; class MM_MarkMap : public MM_HeapMap { private: bool _isMarkMapValid; /** < Is this mark map valid */ public: MMINLINE bool isMarkMapValid() const { return _isMarkMapValid; } MMINLINE void setMarkMapValid(bool isMarkMapValid) { _isMarkMapValid = isMarkMapValid; } static MM_MarkMap *newInstance(MM_EnvironmentBase *env, uintptr_t maxHeapSize); void initializeMarkMap(MM_EnvironmentBase *env); MMINLINE void *getMarkBits() { return _heapMapBits; }; MMINLINE uintptr_t getHeapMapBaseRegionRounded() { return _heapMapBaseDelta; } MMINLINE void getSlotIndexAndBlockMask(omrobjectptr_t objectPtr, uintptr_t *slotIndex, uintptr_t *bitMask, bool lowBlock) { uintptr_t slot = ((uintptr_t)objectPtr) - _heapMapBaseDelta; uintptr_t bitIndex = (slot & _heapMapBitMask) >> _heapMapBitShift; if (lowBlock) { *bitMask = (((uintptr_t)-1) >> (J9BITS_BITS_IN_SLOT - 1 - bitIndex)); } else { *bitMask = (((uintptr_t)-1) << bitIndex); } *slotIndex = slot >> _heapMapIndexShift; } MMINLINE void setMarkBlock(uintptr_t slotIndexLow, uintptr_t slotIndexHigh, uintptr_t value) { uintptr_t slotIndex; for (slotIndex = slotIndexLow; slotIndex <= slotIndexHigh; slotIndex++) { _heapMapBits[slotIndex] = value; } } MMINLINE void markBlockAtomic(uintptr_t slotIndex, uintptr_t bitMask) { volatile uintptr_t *slotAddress; uintptr_t oldValue; slotAddress = &(_heapMapBits[slotIndex]); do { oldValue = *slotAddress; } while(oldValue != MM_AtomicOperations::lockCompareExchange(slotAddress, oldValue, oldValue | bitMask)); } MMINLINE uintptr_t getFirstCellByMarkSlotIndex(uintptr_t slotIndex) { return _heapMapBaseDelta + (slotIndex << _heapMapIndexShift); } /** * check MarkMap if there is any liveObjects in the Card * this function assumes that card covers exactly 512 bytes. * @param heapAddress has to be card size aligned */ MMINLINE bool areAnyLiveObjectsInCard(void* heapAddress) const { #if (8 != BITS_PER_BYTE) || (9 != CARD_SIZE_SHIFT) #error Card size has to be exactly 512 bytes #endif return 0 != *(uint64_t*)getSlotPtrForAddress((omrobjectptr_t) heapAddress); } /** * Create a MarkMap object. */ MM_MarkMap(MM_EnvironmentBase *env, uintptr_t maxHeapSize) : MM_HeapMap(env, maxHeapSize, env->getExtensions()->isSegregatedHeap()) , _isMarkMapValid(false) { _typeId = __FUNCTION__; }; }; #endif /* MARKMAP_HPP_ */
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-only /* * AMD Cryptographic Coprocessor (CCP) AES CMAC crypto API support * * Copyright (C) 2013,2018 Advanced Micro Devices, Inc. * * Author: Tom Lendacky <[email protected]> */ #include <linux/module.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/scatterlist.h> #include <linux/crypto.h> #include <crypto/algapi.h> #include <crypto/aes.h> #include <crypto/hash.h> #include <crypto/internal/hash.h> #include <crypto/scatterwalk.h> #include "ccp-crypto.h" static int ccp_aes_cmac_complete(struct crypto_async_request *async_req, int ret) { struct ahash_request *req = ahash_request_cast(async_req); struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); struct ccp_aes_cmac_req_ctx *rctx = ahash_request_ctx(req); unsigned int digest_size = crypto_ahash_digestsize(tfm); if (ret) goto e_free; if (rctx->hash_rem) { /* Save remaining data to buffer */ unsigned int offset = rctx->nbytes - rctx->hash_rem; scatterwalk_map_and_copy(rctx->buf, rctx->src, offset, rctx->hash_rem, 0); rctx->buf_count = rctx->hash_rem; } else { rctx->buf_count = 0; } /* Update result area if supplied */ if (req->result && rctx->final) memcpy(req->result, rctx->iv, digest_size); e_free: sg_free_table(&rctx->data_sg); return ret; } static int ccp_do_cmac_update(struct ahash_request *req, unsigned int nbytes, unsigned int final) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); struct ccp_ctx *ctx = crypto_ahash_ctx(tfm); struct ccp_aes_cmac_req_ctx *rctx = ahash_request_ctx(req); struct scatterlist *sg, *cmac_key_sg = NULL; unsigned int block_size = crypto_tfm_alg_blocksize(crypto_ahash_tfm(tfm)); unsigned int need_pad, sg_count; gfp_t gfp; u64 len; int ret; if (!ctx->u.aes.key_len) return -EINVAL; if (nbytes) rctx->null_msg = 0; len = (u64)rctx->buf_count + (u64)nbytes; if (!final && (len <= block_size)) { scatterwalk_map_and_copy(rctx->buf + rctx->buf_count, req->src, 0, nbytes, 0); rctx->buf_count += nbytes; return 0; } rctx->src = req->src; rctx->nbytes = nbytes; rctx->final = final; rctx->hash_rem = final ? 0 : len & (block_size - 1); rctx->hash_cnt = len - rctx->hash_rem; if (!final && !rctx->hash_rem) { /* CCP can't do zero length final, so keep some data around */ rctx->hash_cnt -= block_size; rctx->hash_rem = block_size; } if (final && (rctx->null_msg || (len & (block_size - 1)))) need_pad = 1; else need_pad = 0; sg_init_one(&rctx->iv_sg, rctx->iv, sizeof(rctx->iv)); /* Build the data scatterlist table - allocate enough entries for all * possible data pieces (buffer, input data, padding) */ sg_count = (nbytes) ? sg_nents(req->src) + 2 : 2; gfp = req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP ? GFP_KERNEL : GFP_ATOMIC; ret = sg_alloc_table(&rctx->data_sg, sg_count, gfp); if (ret) return ret; sg = NULL; if (rctx->buf_count) { sg_init_one(&rctx->buf_sg, rctx->buf, rctx->buf_count); sg = ccp_crypto_sg_table_add(&rctx->data_sg, &rctx->buf_sg); if (!sg) { ret = -EINVAL; goto e_free; } } if (nbytes) { sg = ccp_crypto_sg_table_add(&rctx->data_sg, req->src); if (!sg) { ret = -EINVAL; goto e_free; } } if (need_pad) { int pad_length = block_size - (len & (block_size - 1)); rctx->hash_cnt += pad_length; memset(rctx->pad, 0, sizeof(rctx->pad)); rctx->pad[0] = 0x80; sg_init_one(&rctx->pad_sg, rctx->pad, pad_length); sg = ccp_crypto_sg_table_add(&rctx->data_sg, &rctx->pad_sg); if (!sg) { ret = -EINVAL; goto e_free; } } if (sg) { sg_mark_end(sg); sg = rctx->data_sg.sgl; } /* Initialize the K1/K2 scatterlist */ if (final) cmac_key_sg = (need_pad) ? &ctx->u.aes.k2_sg : &ctx->u.aes.k1_sg; memset(&rctx->cmd, 0, sizeof(rctx->cmd)); INIT_LIST_HEAD(&rctx->cmd.entry); rctx->cmd.engine = CCP_ENGINE_AES; rctx->cmd.u.aes.type = ctx->u.aes.type; rctx->cmd.u.aes.mode = ctx->u.aes.mode; rctx->cmd.u.aes.action = CCP_AES_ACTION_ENCRYPT; rctx->cmd.u.aes.key = &ctx->u.aes.key_sg; rctx->cmd.u.aes.key_len = ctx->u.aes.key_len; rctx->cmd.u.aes.iv = &rctx->iv_sg; rctx->cmd.u.aes.iv_len = AES_BLOCK_SIZE; rctx->cmd.u.aes.src = sg; rctx->cmd.u.aes.src_len = rctx->hash_cnt; rctx->cmd.u.aes.dst = NULL; rctx->cmd.u.aes.cmac_key = cmac_key_sg; rctx->cmd.u.aes.cmac_key_len = ctx->u.aes.kn_len; rctx->cmd.u.aes.cmac_final = final; ret = ccp_crypto_enqueue_request(&req->base, &rctx->cmd); return ret; e_free: sg_free_table(&rctx->data_sg); return ret; } static int ccp_aes_cmac_init(struct ahash_request *req) { struct ccp_aes_cmac_req_ctx *rctx = ahash_request_ctx(req); memset(rctx, 0, sizeof(*rctx)); rctx->null_msg = 1; return 0; } static int ccp_aes_cmac_update(struct ahash_request *req) { return ccp_do_cmac_update(req, req->nbytes, 0); } static int ccp_aes_cmac_final(struct ahash_request *req) { return ccp_do_cmac_update(req, 0, 1); } static int ccp_aes_cmac_finup(struct ahash_request *req) { return ccp_do_cmac_update(req, req->nbytes, 1); } static int ccp_aes_cmac_digest(struct ahash_request *req) { int ret; ret = ccp_aes_cmac_init(req); if (ret) return ret; return ccp_aes_cmac_finup(req); } static int ccp_aes_cmac_export(struct ahash_request *req, void *out) { struct ccp_aes_cmac_req_ctx *rctx = ahash_request_ctx(req); struct ccp_aes_cmac_exp_ctx state; /* Don't let anything leak to 'out' */ memset(&state, 0, sizeof(state)); state.null_msg = rctx->null_msg; memcpy(state.iv, rctx->iv, sizeof(state.iv)); state.buf_count = rctx->buf_count; memcpy(state.buf, rctx->buf, sizeof(state.buf)); /* 'out' may not be aligned so memcpy from local variable */ memcpy(out, &state, sizeof(state)); return 0; } static int ccp_aes_cmac_import(struct ahash_request *req, const void *in) { struct ccp_aes_cmac_req_ctx *rctx = ahash_request_ctx(req); struct ccp_aes_cmac_exp_ctx state; /* 'in' may not be aligned so memcpy to local variable */ memcpy(&state, in, sizeof(state)); memset(rctx, 0, sizeof(*rctx)); rctx->null_msg = state.null_msg; memcpy(rctx->iv, state.iv, sizeof(rctx->iv)); rctx->buf_count = state.buf_count; memcpy(rctx->buf, state.buf, sizeof(rctx->buf)); return 0; } static int ccp_aes_cmac_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int key_len) { struct ccp_ctx *ctx = crypto_tfm_ctx(crypto_ahash_tfm(tfm)); struct ccp_crypto_ahash_alg *alg = ccp_crypto_ahash_alg(crypto_ahash_tfm(tfm)); u64 k0_hi, k0_lo, k1_hi, k1_lo, k2_hi, k2_lo; u64 rb_hi = 0x00, rb_lo = 0x87; struct crypto_aes_ctx aes; __be64 *gk; int ret; switch (key_len) { case AES_KEYSIZE_128: ctx->u.aes.type = CCP_AES_TYPE_128; break; case AES_KEYSIZE_192: ctx->u.aes.type = CCP_AES_TYPE_192; break; case AES_KEYSIZE_256: ctx->u.aes.type = CCP_AES_TYPE_256; break; default: return -EINVAL; } ctx->u.aes.mode = alg->mode; /* Set to zero until complete */ ctx->u.aes.key_len = 0; /* Set the key for the AES cipher used to generate the keys */ ret = aes_expandkey(&aes, key, key_len); if (ret) return ret; /* Encrypt a block of zeroes - use key area in context */ memset(ctx->u.aes.key, 0, sizeof(ctx->u.aes.key)); aes_encrypt(&aes, ctx->u.aes.key, ctx->u.aes.key); memzero_explicit(&aes, sizeof(aes)); /* Generate K1 and K2 */ k0_hi = be64_to_cpu(*((__be64 *)ctx->u.aes.key)); k0_lo = be64_to_cpu(*((__be64 *)ctx->u.aes.key + 1)); k1_hi = (k0_hi << 1) | (k0_lo >> 63); k1_lo = k0_lo << 1; if (ctx->u.aes.key[0] & 0x80) { k1_hi ^= rb_hi; k1_lo ^= rb_lo; } gk = (__be64 *)ctx->u.aes.k1; *gk = cpu_to_be64(k1_hi); gk++; *gk = cpu_to_be64(k1_lo); k2_hi = (k1_hi << 1) | (k1_lo >> 63); k2_lo = k1_lo << 1; if (ctx->u.aes.k1[0] & 0x80) { k2_hi ^= rb_hi; k2_lo ^= rb_lo; } gk = (__be64 *)ctx->u.aes.k2; *gk = cpu_to_be64(k2_hi); gk++; *gk = cpu_to_be64(k2_lo); ctx->u.aes.kn_len = sizeof(ctx->u.aes.k1); sg_init_one(&ctx->u.aes.k1_sg, ctx->u.aes.k1, sizeof(ctx->u.aes.k1)); sg_init_one(&ctx->u.aes.k2_sg, ctx->u.aes.k2, sizeof(ctx->u.aes.k2)); /* Save the supplied key */ memset(ctx->u.aes.key, 0, sizeof(ctx->u.aes.key)); memcpy(ctx->u.aes.key, key, key_len); ctx->u.aes.key_len = key_len; sg_init_one(&ctx->u.aes.key_sg, ctx->u.aes.key, key_len); return ret; } static int ccp_aes_cmac_cra_init(struct crypto_tfm *tfm) { struct ccp_ctx *ctx = crypto_tfm_ctx(tfm); struct crypto_ahash *ahash = __crypto_ahash_cast(tfm); ctx->complete = ccp_aes_cmac_complete; ctx->u.aes.key_len = 0; crypto_ahash_set_reqsize(ahash, sizeof(struct ccp_aes_cmac_req_ctx)); return 0; } int ccp_register_aes_cmac_algs(struct list_head *head) { struct ccp_crypto_ahash_alg *ccp_alg; struct ahash_alg *alg; struct hash_alg_common *halg; struct crypto_alg *base; int ret; ccp_alg = kzalloc(sizeof(*ccp_alg), GFP_KERNEL); if (!ccp_alg) return -ENOMEM; INIT_LIST_HEAD(&ccp_alg->entry); ccp_alg->mode = CCP_AES_MODE_CMAC; alg = &ccp_alg->alg; alg->init = ccp_aes_cmac_init; alg->update = ccp_aes_cmac_update; alg->final = ccp_aes_cmac_final; alg->finup = ccp_aes_cmac_finup; alg->digest = ccp_aes_cmac_digest; alg->export = ccp_aes_cmac_export; alg->import = ccp_aes_cmac_import; alg->setkey = ccp_aes_cmac_setkey; halg = &alg->halg; halg->digestsize = AES_BLOCK_SIZE; halg->statesize = sizeof(struct ccp_aes_cmac_exp_ctx); base = &halg->base; snprintf(base->cra_name, CRYPTO_MAX_ALG_NAME, "cmac(aes)"); snprintf(base->cra_driver_name, CRYPTO_MAX_ALG_NAME, "cmac-aes-ccp"); base->cra_flags = CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_NEED_FALLBACK; base->cra_blocksize = AES_BLOCK_SIZE; base->cra_ctxsize = sizeof(struct ccp_ctx); base->cra_priority = CCP_CRA_PRIORITY; base->cra_init = ccp_aes_cmac_cra_init; base->cra_module = THIS_MODULE; ret = crypto_register_ahash(alg); if (ret) { pr_err("%s ahash algorithm registration error (%d)\n", base->cra_name, ret); kfree(ccp_alg); return ret; } list_add(&ccp_alg->entry, head); return 0; }
{ "pile_set_name": "Github" }
{ "defaultPolicy": "allow", "blockedServers": [] }
{ "pile_set_name": "Github" }
/* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * * -*- mode: c, c-basic-offset: 4 -*- */ /* * Copyright © BeyondTrust Software 2004 - 2019 * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Copyright (C) BeyondTrust Software. All rights reserved. * * Module Name: * * lm.h * * Abstract: * * BeyondTrust Net API * * Public API * */ #ifndef __LM_H__ #define __LM_H__ #ifndef NET_API_STATUS_DEFINED typedef WINERROR NET_API_STATUS; #define NET_API_STATUS_DEFINED #endif NET_API_STATUS NetApiInitialize( VOID ); NET_API_STATUS NetApiBufferAllocate( DWORD dwCount, PVOID* ppBuffer ); NET_API_STATUS NetApiBufferFree( PVOID pBuffer ); NET_API_STATUS NetServerGetInfoA( PSTR pszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetServerGetInfoW( PWSTR pwszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetServerSetInfoA( PSTR pszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE pBuffer, /* IN */ PDWORD pdwParmError /* OUT OPTIONAL */ ); NET_API_STATUS NetServerSetInfoW( PWSTR pwszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE pBuffer, /* IN */ PDWORD pdwParmError /* OUT OPTIONAL */ ); NET_API_STATUS NetShareEnumA( PSTR pszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxLen, /* IN */ PDWORD pdwEntriesRead, /* OUT */ PDWORD pdwTotalEntries,/* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetShareEnumW( PWSTR pwszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxLen, /* IN */ PDWORD pdwEntriesRead, /* OUT */ PDWORD pdwTotalEntries,/* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetShareGetInfoA( PSTR pszServername, /* IN OPTIONAL */ PSTR pszNetname, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetShareGetInfoW( PWSTR pwszServername, /* IN OPTIONAL */ PWSTR pwszNetname, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetShareSetInfoA( PSTR pszServername, /* IN OPTIONAL */ PSTR pszNetname, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE pBuffer, /* IN */ PDWORD pdwParmError /* OUT */ ); NET_API_STATUS NetShareSetInfoW( PWSTR pwszServername, /* IN OPTIONAL */ PWSTR pwszNetname, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE pBuffer, /* IN */ PDWORD pdwParmError /* OUT */ ); NET_API_STATUS NetShareAddA( PSTR pszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE pBuffer, /* IN */ PDWORD pdwParmError /* OUT */ ); NET_API_STATUS NetShareAddW( PWSTR pwszServername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE pBuffer, /* IN */ PDWORD pdwParmError /* OUT */ ); NET_API_STATUS NetShareDelA( PSTR pszServername, /* IN OPTIONAL */ PSTR pszNetname, /* IN */ DWORD dwReserved /* IN */ ); NET_API_STATUS NetShareDelW( PWSTR pwszServername, /* IN OPTIONAL */ PWSTR pwszNetname, /* IN */ DWORD dwReserved /* IN */ ); NET_API_STATUS NetSessionEnumA( PSTR pszServername, /* IN OPTIONAL */ PSTR pszUncClientname, /* IN OPTIONAL */ PSTR pszUsername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxLen, /* IN */ PDWORD pdwEntriesRead, /* OUT */ PDWORD pdwTotalEntries, /* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetSessionEnumW( PWSTR pwszServername, /* IN OPTIONAL */ PWSTR pwszUncClientname, /* IN OPTIONAL */ PWSTR pwszUsername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxLen, /* IN */ PDWORD pdwEntriesRead, /* OUT */ PDWORD pdwTotalEntries, /* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetSessionDelA( PSTR pszServername, /* IN OPTIONAL */ PSTR pszUncClientname, /* IN OPTIONAL */ PSTR pszUsername /* IN OPTIONAL */ ); NET_API_STATUS NetSessionDelW( PWSTR pwszServername, /* IN OPTIONAL */ PWSTR pwszUncClientname, /* IN OPTIONAL */ PWSTR pwszUsername /* IN OPTIONAL */ ); NET_API_STATUS NetConnectionEnumA( PSTR pszServername, /* IN OPTIONAL */ PSTR pszQualifier, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxlen, /* IN */ PDWORD pdwEntriesRead, /* OUT */ PDWORD pdwTotalEntries, /* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetConnectionEnumW( PWSTR pwszServername, /* IN OPTIONAL */ PWSTR pwszQualifier, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxlen, /* IN */ PDWORD pdwEntriesRead, /* OUT */ PDWORD pdwTotalEntries, /* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetFileEnumA( PSTR pszServername, /* IN OPTIONAL */ PSTR pszBasepath, /* IN OPTIONAL */ PSTR pszUsername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxlen, /* IN */ PDWORD pwdEntriesRead, /* OUT */ PDWORD pdwTotalEntries, /* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetFileEnumW( PCWSTR pwszServername, /* IN OPTIONAL */ PCWSTR pwszBasepath, /* IN OPTIONAL */ PCWSTR pwszUsername, /* IN OPTIONAL */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer, /* OUT */ DWORD dwPrefmaxlen, /* IN */ PDWORD pwdEntriesRead, /* OUT */ PDWORD pdwTotalEntries, /* OUT */ PDWORD pdwResumeHandle /* IN OUT OPTIONAL */ ); NET_API_STATUS NetFileGetInfoA( PSTR pszServername, /* IN OPTIONAL */ DWORD dwFileId, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetFileGetInfoW( PCWSTR pwszServername, /* IN OPTIONAL */ DWORD dwFileId, /* IN */ DWORD dwInfoLevel, /* IN */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetFileCloseA( PSTR pszServername, /* IN OPTIONAL */ DWORD dwFileId /* IN */ ); NET_API_STATUS NetFileCloseW( PCWSTR pwszServername, /* IN OPTIONAL */ DWORD dwFileId /* IN */ ); NET_API_STATUS NetRemoteTODA( PSTR pszServername, /* IN OPTIONAL */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetRemoteTODW( PWSTR pwszServername, /* IN OPTIONAL */ PBYTE* ppBuffer /* OUT */ ); NET_API_STATUS NetApiShutdown( VOID ); #if defined(UNICODE) #define NetServerGetInfo NetServerGetInfoW #define NetServerSetInfo NetServerSetInfoW #define NetShareEnum NetShareEnumW #define NetShareGetInfo NetShareGetInfoW #define NetShareSetInfo NetShareSetInfoW #define NetShareAdd NetShareAddW #define NetServerDel NetServerDelW #define NetSessionEnum NetSessionEnumW #define NetSessionDel NetSessionDelW #define NetConnectionEnum NetConnectionEnumW #define NetFileEnum NetFileEnumW #define NetFileGetInfo NetFileGetInfoW #define NetFileClose NetFileCloseW #define NetRemoteTOD NetRemoteTODW #else #define NetServerGetInfo NetServerGetInfoA #define NetServerSetInfo NetServerSetInfoA #define NetShareEnum NetShareEnumA #define NetShareGetInfo NetShareGetInfoA #define NetShareSetInfo NetShareSetInfoA #define NetShareAdd NetShareAddA #define NetServerDel NetServerDelA #define NetSessionEnum NetSessionEnumA #define NetSessionDel NetSessionDelA #define NetConnectionEnum NetConnectionEnumA #define NetFileEnum NetFileEnumA #define NetFileGetInfo NetFileGetInfoA #define NetFileClose NetFileCloseA #define NetRemoteTOD NetRemoteTODA #endif /* UNICODE */ #endif /* __LM_H__ */
{ "pile_set_name": "Github" }
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #pragma once #include <variant> #include <QObject> #include <QStringList> #include "common.h" namespace LC { namespace DBusManager { class General : public QObject { Q_OBJECT public: using QObject::QObject; QStringList GetLoadedPlugins (); using Description_t = Util::Either<std::variant<IdentifierNotFound>, QString>; Description_t GetDescription (const QString&); using Icon_t = Util::Either<std::variant<IdentifierNotFound, SerializationError>, QByteArray>; Icon_t GetIcon (const QString&, int); }; } }
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11 // <chrono> #include <chrono> #include <type_traits> #include <cassert> #include "test_macros.h" int main(int, char**) { using namespace std::literals; std::chrono::hours h = 4h; assert ( h == std::chrono::hours(4)); auto h2 = 4.0h; assert ( h == h2 ); std::chrono::minutes min = 36min; assert ( min == std::chrono::minutes(36)); auto min2 = 36.0min; assert ( min == min2 ); std::chrono::seconds s = 24s; assert ( s == std::chrono::seconds(24)); auto s2 = 24.0s; assert ( s == s2 ); std::chrono::milliseconds ms = 247ms; assert ( ms == std::chrono::milliseconds(247)); auto ms2 = 247.0ms; assert ( ms == ms2 ); std::chrono::microseconds us = 867us; assert ( us == std::chrono::microseconds(867)); auto us2 = 867.0us; assert ( us == us2 ); std::chrono::nanoseconds ns = 645ns; assert ( ns == std::chrono::nanoseconds(645)); auto ns2 = 645.ns; assert ( ns == ns2 ); return 0; }
{ "pile_set_name": "Github" }
/***************************************************************************** * fsm.c - Network Control Protocol Finite State Machine program file. * * Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. * portions Copyright (c) 1997 by Global Election Systems Inc. * * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this * notice and the following disclaimer are included verbatim in any * distributions. No written agreement, license, or royalty fee is required * for any of the authorized uses. * * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** * REVISION HISTORY * * 03-01-01 Marc Boucher <[email protected]> * Ported to lwIP. * 97-12-01 Guy Lancaster <[email protected]>, Global Election Systems Inc. * Original based on BSD fsm.c. *****************************************************************************/ /* * fsm.c - {Link, IP} Control Protocol Finite State Machine. * * Copyright (c) 1989 Carnegie Mellon University. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by Carnegie Mellon University. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* * TODO: * Randomize fsm id on link/init. * Deal with variable outgoing MTU. */ #include "lwip/opt.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #include "ppp.h" #include "pppdebug.h" #include "fsm.h" #include <string.h> #if PPP_DEBUG static const char *ppperr_strerr[] = { "LS_INITIAL", /* LS_INITIAL 0 */ "LS_STARTING", /* LS_STARTING 1 */ "LS_CLOSED", /* LS_CLOSED 2 */ "LS_STOPPED", /* LS_STOPPED 3 */ "LS_CLOSING", /* LS_CLOSING 4 */ "LS_STOPPING", /* LS_STOPPING 5 */ "LS_REQSENT", /* LS_REQSENT 6 */ "LS_ACKRCVD", /* LS_ACKRCVD 7 */ "LS_ACKSENT", /* LS_ACKSENT 8 */ "LS_OPENED" /* LS_OPENED 9 */ }; #endif /* PPP_DEBUG */ static void fsm_timeout (void *); static void fsm_rconfreq (fsm *, u_char, u_char *, int); static void fsm_rconfack (fsm *, int, u_char *, int); static void fsm_rconfnakrej (fsm *, int, int, u_char *, int); static void fsm_rtermreq (fsm *, int, u_char *, int); static void fsm_rtermack (fsm *); static void fsm_rcoderej (fsm *, u_char *, int); static void fsm_sconfreq (fsm *, int); #define PROTO_NAME(f) ((f)->callbacks->proto_name) int peer_mru[NUM_PPP]; /* * fsm_init - Initialize fsm. * * Initialize fsm state. */ void fsm_init(fsm *f) { f->state = LS_INITIAL; f->flags = 0; f->id = 0; /* XXX Start with random id? */ f->timeouttime = FSM_DEFTIMEOUT; f->maxconfreqtransmits = FSM_DEFMAXCONFREQS; f->maxtermtransmits = FSM_DEFMAXTERMREQS; f->maxnakloops = FSM_DEFMAXNAKLOOPS; f->term_reason_len = 0; } /* * fsm_lowerup - The lower layer is up. */ void fsm_lowerup(fsm *f) { int oldState = f->state; LWIP_UNUSED_ARG(oldState); switch( f->state ) { case LS_INITIAL: f->state = LS_CLOSED; break; case LS_STARTING: if( f->flags & OPT_SILENT ) { f->state = LS_STOPPED; } else { /* Send an initial configure-request */ fsm_sconfreq(f, 0); f->state = LS_REQSENT; } break; default: FSMDEBUG(LOG_INFO, ("%s: Up event in state %d (%s)!\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); } FSMDEBUG(LOG_INFO, ("%s: lowerup state %d (%s) -> %d (%s)\n", PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); } /* * fsm_lowerdown - The lower layer is down. * * Cancel all timeouts and inform upper layers. */ void fsm_lowerdown(fsm *f) { int oldState = f->state; LWIP_UNUSED_ARG(oldState); switch( f->state ) { case LS_CLOSED: f->state = LS_INITIAL; break; case LS_STOPPED: f->state = LS_STARTING; if( f->callbacks->starting ) { (*f->callbacks->starting)(f); } break; case LS_CLOSING: f->state = LS_INITIAL; UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ break; case LS_STOPPING: case LS_REQSENT: case LS_ACKRCVD: case LS_ACKSENT: f->state = LS_STARTING; UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ break; case LS_OPENED: if( f->callbacks->down ) { (*f->callbacks->down)(f); } f->state = LS_STARTING; break; default: FSMDEBUG(LOG_INFO, ("%s: Down event in state %d (%s)!\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); } FSMDEBUG(LOG_INFO, ("%s: lowerdown state %d (%s) -> %d (%s)\n", PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); } /* * fsm_open - Link is allowed to come up. */ void fsm_open(fsm *f) { int oldState = f->state; LWIP_UNUSED_ARG(oldState); switch( f->state ) { case LS_INITIAL: f->state = LS_STARTING; if( f->callbacks->starting ) { (*f->callbacks->starting)(f); } break; case LS_CLOSED: if( f->flags & OPT_SILENT ) { f->state = LS_STOPPED; } else { /* Send an initial configure-request */ fsm_sconfreq(f, 0); f->state = LS_REQSENT; } break; case LS_CLOSING: f->state = LS_STOPPING; /* fall through */ case LS_STOPPED: case LS_OPENED: if( f->flags & OPT_RESTART ) { fsm_lowerdown(f); fsm_lowerup(f); } break; } FSMDEBUG(LOG_INFO, ("%s: open state %d (%s) -> %d (%s)\n", PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); } #if 0 /* backport pppd 2.4.4b1; */ /* * terminate_layer - Start process of shutting down the FSM * * Cancel any timeout running, notify upper layers we're done, and * send a terminate-request message as configured. */ static void terminate_layer(fsm *f, int nextstate) { /* @todo */ } #endif /* * fsm_close - Start closing connection. * * Cancel timeouts and either initiate close or possibly go directly to * the LS_CLOSED state. */ void fsm_close(fsm *f, char *reason) { int oldState = f->state; LWIP_UNUSED_ARG(oldState); f->term_reason = reason; f->term_reason_len = (reason == NULL ? 0 : (int)strlen(reason)); switch( f->state ) { case LS_STARTING: f->state = LS_INITIAL; break; case LS_STOPPED: f->state = LS_CLOSED; break; case LS_STOPPING: f->state = LS_CLOSING; break; case LS_REQSENT: case LS_ACKRCVD: case LS_ACKSENT: case LS_OPENED: if( f->state != LS_OPENED ) { UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ } else if( f->callbacks->down ) { (*f->callbacks->down)(f); /* Inform upper layers we're down */ } /* Init restart counter, send Terminate-Request */ f->retransmits = f->maxtermtransmits; fsm_sdata(f, TERMREQ, f->reqid = ++f->id, (u_char *) f->term_reason, f->term_reason_len); TIMEOUT(fsm_timeout, f, f->timeouttime); --f->retransmits; f->state = LS_CLOSING; break; } FSMDEBUG(LOG_INFO, ("%s: close reason=%s state %d (%s) -> %d (%s)\n", PROTO_NAME(f), reason, oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); } /* * fsm_timeout - Timeout expired. */ static void fsm_timeout(void *arg) { fsm *f = (fsm *) arg; switch (f->state) { case LS_CLOSING: case LS_STOPPING: if( f->retransmits <= 0 ) { FSMDEBUG(LOG_WARNING, ("%s: timeout sending Terminate-Request state=%d (%s)\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); /* * We've waited for an ack long enough. Peer probably heard us. */ f->state = (f->state == LS_CLOSING)? LS_CLOSED: LS_STOPPED; if( f->callbacks->finished ) { (*f->callbacks->finished)(f); } } else { FSMDEBUG(LOG_WARNING, ("%s: timeout resending Terminate-Requests state=%d (%s)\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); /* Send Terminate-Request */ fsm_sdata(f, TERMREQ, f->reqid = ++f->id, (u_char *) f->term_reason, f->term_reason_len); TIMEOUT(fsm_timeout, f, f->timeouttime); --f->retransmits; } break; case LS_REQSENT: case LS_ACKRCVD: case LS_ACKSENT: if (f->retransmits <= 0) { FSMDEBUG(LOG_WARNING, ("%s: timeout sending Config-Requests state=%d (%s)\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); f->state = LS_STOPPED; if( (f->flags & OPT_PASSIVE) == 0 && f->callbacks->finished ) { (*f->callbacks->finished)(f); } } else { FSMDEBUG(LOG_WARNING, ("%s: timeout resending Config-Request state=%d (%s)\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); /* Retransmit the configure-request */ if (f->callbacks->retransmit) { (*f->callbacks->retransmit)(f); } fsm_sconfreq(f, 1); /* Re-send Configure-Request */ if( f->state == LS_ACKRCVD ) { f->state = LS_REQSENT; } } break; default: FSMDEBUG(LOG_INFO, ("%s: UNHANDLED timeout event in state %d (%s)!\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); } } /* * fsm_input - Input packet. */ void fsm_input(fsm *f, u_char *inpacket, int l) { u_char *inp = inpacket; u_char code, id; int len; /* * Parse header (code, id and length). * If packet too short, drop it. */ if (l < HEADERLEN) { FSMDEBUG(LOG_WARNING, ("fsm_input(%x): Rcvd short header.\n", f->protocol)); return; } GETCHAR(code, inp); GETCHAR(id, inp); GETSHORT(len, inp); if (len < HEADERLEN) { FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd illegal length.\n", f->protocol)); return; } if (len > l) { FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd short packet.\n", f->protocol)); return; } len -= HEADERLEN; /* subtract header length */ if( f->state == LS_INITIAL || f->state == LS_STARTING ) { FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd packet in state %d (%s).\n", f->protocol, f->state, ppperr_strerr[f->state])); return; } FSMDEBUG(LOG_INFO, ("fsm_input(%s):%d,%d,%d\n", PROTO_NAME(f), code, id, l)); /* * Action depends on code. */ switch (code) { case CONFREQ: fsm_rconfreq(f, id, inp, len); break; case CONFACK: fsm_rconfack(f, id, inp, len); break; case CONFNAK: case CONFREJ: fsm_rconfnakrej(f, code, id, inp, len); break; case TERMREQ: fsm_rtermreq(f, id, inp, len); break; case TERMACK: fsm_rtermack(f); break; case CODEREJ: fsm_rcoderej(f, inp, len); break; default: FSMDEBUG(LOG_INFO, ("fsm_input(%s): default: \n", PROTO_NAME(f))); if( !f->callbacks->extcode || !(*f->callbacks->extcode)(f, code, id, inp, len) ) { fsm_sdata(f, CODEREJ, ++f->id, inpacket, len + HEADERLEN); } break; } } /* * fsm_rconfreq - Receive Configure-Request. */ static void fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len) { int code, reject_if_disagree; FSMDEBUG(LOG_INFO, ("fsm_rconfreq(%s): Rcvd id %d state=%d (%s)\n", PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); switch( f->state ) { case LS_CLOSED: /* Go away, we're closed */ fsm_sdata(f, TERMACK, id, NULL, 0); return; case LS_CLOSING: case LS_STOPPING: return; case LS_OPENED: /* Go down and restart negotiation */ if( f->callbacks->down ) { (*f->callbacks->down)(f); /* Inform upper layers */ } fsm_sconfreq(f, 0); /* Send initial Configure-Request */ break; case LS_STOPPED: /* Negotiation started by our peer */ fsm_sconfreq(f, 0); /* Send initial Configure-Request */ f->state = LS_REQSENT; break; } /* * Pass the requested configuration options * to protocol-specific code for checking. */ if (f->callbacks->reqci) { /* Check CI */ reject_if_disagree = (f->nakloops >= f->maxnakloops); code = (*f->callbacks->reqci)(f, inp, &len, reject_if_disagree); } else if (len) { code = CONFREJ; /* Reject all CI */ } else { code = CONFACK; } /* send the Ack, Nak or Rej to the peer */ fsm_sdata(f, (u_char)code, id, inp, len); if (code == CONFACK) { if (f->state == LS_ACKRCVD) { UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ f->state = LS_OPENED; if (f->callbacks->up) { (*f->callbacks->up)(f); /* Inform upper layers */ } } else { f->state = LS_ACKSENT; } f->nakloops = 0; } else { /* we sent CONFACK or CONFREJ */ if (f->state != LS_ACKRCVD) { f->state = LS_REQSENT; } if( code == CONFNAK ) { ++f->nakloops; } } } /* * fsm_rconfack - Receive Configure-Ack. */ static void fsm_rconfack(fsm *f, int id, u_char *inp, int len) { FSMDEBUG(LOG_INFO, ("fsm_rconfack(%s): Rcvd id %d state=%d (%s)\n", PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); if (id != f->reqid || f->seen_ack) { /* Expected id? */ return; /* Nope, toss... */ } if( !(f->callbacks->ackci? (*f->callbacks->ackci)(f, inp, len): (len == 0)) ) { /* Ack is bad - ignore it */ FSMDEBUG(LOG_INFO, ("%s: received bad Ack (length %d)\n", PROTO_NAME(f), len)); return; } f->seen_ack = 1; switch (f->state) { case LS_CLOSED: case LS_STOPPED: fsm_sdata(f, TERMACK, (u_char)id, NULL, 0); break; case LS_REQSENT: f->state = LS_ACKRCVD; f->retransmits = f->maxconfreqtransmits; break; case LS_ACKRCVD: /* Huh? an extra valid Ack? oh well... */ UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ fsm_sconfreq(f, 0); f->state = LS_REQSENT; break; case LS_ACKSENT: UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ f->state = LS_OPENED; f->retransmits = f->maxconfreqtransmits; if (f->callbacks->up) { (*f->callbacks->up)(f); /* Inform upper layers */ } break; case LS_OPENED: /* Go down and restart negotiation */ if (f->callbacks->down) { (*f->callbacks->down)(f); /* Inform upper layers */ } fsm_sconfreq(f, 0); /* Send initial Configure-Request */ f->state = LS_REQSENT; break; } } /* * fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject. */ static void fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len) { int (*proc) (fsm *, u_char *, int); int ret; FSMDEBUG(LOG_INFO, ("fsm_rconfnakrej(%s): Rcvd id %d state=%d (%s)\n", PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); if (id != f->reqid || f->seen_ack) { /* Expected id? */ return; /* Nope, toss... */ } proc = (code == CONFNAK)? f->callbacks->nakci: f->callbacks->rejci; if (!proc || !((ret = proc(f, inp, len)))) { /* Nak/reject is bad - ignore it */ FSMDEBUG(LOG_INFO, ("%s: received bad %s (length %d)\n", PROTO_NAME(f), (code==CONFNAK? "Nak": "reject"), len)); return; } f->seen_ack = 1; switch (f->state) { case LS_CLOSED: case LS_STOPPED: fsm_sdata(f, TERMACK, (u_char)id, NULL, 0); break; case LS_REQSENT: case LS_ACKSENT: /* They didn't agree to what we wanted - try another request */ UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ if (ret < 0) { f->state = LS_STOPPED; /* kludge for stopping CCP */ } else { fsm_sconfreq(f, 0); /* Send Configure-Request */ } break; case LS_ACKRCVD: /* Got a Nak/reject when we had already had an Ack?? oh well... */ UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ fsm_sconfreq(f, 0); f->state = LS_REQSENT; break; case LS_OPENED: /* Go down and restart negotiation */ if (f->callbacks->down) { (*f->callbacks->down)(f); /* Inform upper layers */ } fsm_sconfreq(f, 0); /* Send initial Configure-Request */ f->state = LS_REQSENT; break; } } /* * fsm_rtermreq - Receive Terminate-Req. */ static void fsm_rtermreq(fsm *f, int id, u_char *p, int len) { LWIP_UNUSED_ARG(p); FSMDEBUG(LOG_INFO, ("fsm_rtermreq(%s): Rcvd id %d state=%d (%s)\n", PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); switch (f->state) { case LS_ACKRCVD: case LS_ACKSENT: f->state = LS_REQSENT; /* Start over but keep trying */ break; case LS_OPENED: if (len > 0) { FSMDEBUG(LOG_INFO, ("%s terminated by peer (%p)\n", PROTO_NAME(f), p)); } else { FSMDEBUG(LOG_INFO, ("%s terminated by peer\n", PROTO_NAME(f))); } if (f->callbacks->down) { (*f->callbacks->down)(f); /* Inform upper layers */ } f->retransmits = 0; f->state = LS_STOPPING; TIMEOUT(fsm_timeout, f, f->timeouttime); break; } fsm_sdata(f, TERMACK, (u_char)id, NULL, 0); } /* * fsm_rtermack - Receive Terminate-Ack. */ static void fsm_rtermack(fsm *f) { FSMDEBUG(LOG_INFO, ("fsm_rtermack(%s): state=%d (%s)\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); switch (f->state) { case LS_CLOSING: UNTIMEOUT(fsm_timeout, f); f->state = LS_CLOSED; if( f->callbacks->finished ) { (*f->callbacks->finished)(f); } break; case LS_STOPPING: UNTIMEOUT(fsm_timeout, f); f->state = LS_STOPPED; if( f->callbacks->finished ) { (*f->callbacks->finished)(f); } break; case LS_ACKRCVD: f->state = LS_REQSENT; break; case LS_OPENED: if (f->callbacks->down) { (*f->callbacks->down)(f); /* Inform upper layers */ } fsm_sconfreq(f, 0); break; default: FSMDEBUG(LOG_INFO, ("fsm_rtermack(%s): UNHANDLED state=%d (%s)!!!\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); } } /* * fsm_rcoderej - Receive an Code-Reject. */ static void fsm_rcoderej(fsm *f, u_char *inp, int len) { u_char code, id; FSMDEBUG(LOG_INFO, ("fsm_rcoderej(%s): state=%d (%s)\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); if (len < HEADERLEN) { FSMDEBUG(LOG_INFO, ("fsm_rcoderej: Rcvd short Code-Reject packet!\n")); return; } GETCHAR(code, inp); GETCHAR(id, inp); FSMDEBUG(LOG_WARNING, ("%s: Rcvd Code-Reject for code %d, id %d\n", PROTO_NAME(f), code, id)); if( f->state == LS_ACKRCVD ) { f->state = LS_REQSENT; } } /* * fsm_protreject - Peer doesn't speak this protocol. * * Treat this as a catastrophic error (RXJ-). */ void fsm_protreject(fsm *f) { switch( f->state ) { case LS_CLOSING: UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ /* fall through */ case LS_CLOSED: f->state = LS_CLOSED; if( f->callbacks->finished ) { (*f->callbacks->finished)(f); } break; case LS_STOPPING: case LS_REQSENT: case LS_ACKRCVD: case LS_ACKSENT: UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ /* fall through */ case LS_STOPPED: f->state = LS_STOPPED; if( f->callbacks->finished ) { (*f->callbacks->finished)(f); } break; case LS_OPENED: if( f->callbacks->down ) { (*f->callbacks->down)(f); } /* Init restart counter, send Terminate-Request */ f->retransmits = f->maxtermtransmits; fsm_sdata(f, TERMREQ, f->reqid = ++f->id, (u_char *) f->term_reason, f->term_reason_len); TIMEOUT(fsm_timeout, f, f->timeouttime); --f->retransmits; f->state = LS_STOPPING; break; default: FSMDEBUG(LOG_INFO, ("%s: Protocol-reject event in state %d (%s)!\n", PROTO_NAME(f), f->state, ppperr_strerr[f->state])); } } /* * fsm_sconfreq - Send a Configure-Request. */ static void fsm_sconfreq(fsm *f, int retransmit) { u_char *outp; int cilen; if( f->state != LS_REQSENT && f->state != LS_ACKRCVD && f->state != LS_ACKSENT ) { /* Not currently negotiating - reset options */ if( f->callbacks->resetci ) { (*f->callbacks->resetci)(f); } f->nakloops = 0; } if( !retransmit ) { /* New request - reset retransmission counter, use new ID */ f->retransmits = f->maxconfreqtransmits; f->reqid = ++f->id; } f->seen_ack = 0; /* * Make up the request packet */ outp = outpacket_buf[f->unit] + PPP_HDRLEN + HEADERLEN; if( f->callbacks->cilen && f->callbacks->addci ) { cilen = (*f->callbacks->cilen)(f); if( cilen > peer_mru[f->unit] - (int)HEADERLEN ) { cilen = peer_mru[f->unit] - HEADERLEN; } if (f->callbacks->addci) { (*f->callbacks->addci)(f, outp, &cilen); } } else { cilen = 0; } /* send the request to our peer */ fsm_sdata(f, CONFREQ, f->reqid, outp, cilen); /* start the retransmit timer */ --f->retransmits; TIMEOUT(fsm_timeout, f, f->timeouttime); FSMDEBUG(LOG_INFO, ("%s: sending Configure-Request, id %d\n", PROTO_NAME(f), f->reqid)); } /* * fsm_sdata - Send some data. * * Used for all packets sent to our peer by this module. */ void fsm_sdata( fsm *f, u_char code, u_char id, u_char *data, int datalen) { u_char *outp; int outlen; /* Adjust length to be smaller than MTU */ outp = outpacket_buf[f->unit]; if (datalen > peer_mru[f->unit] - (int)HEADERLEN) { datalen = peer_mru[f->unit] - HEADERLEN; } if (datalen && data != outp + PPP_HDRLEN + HEADERLEN) { BCOPY(data, outp + PPP_HDRLEN + HEADERLEN, datalen); } outlen = datalen + HEADERLEN; MAKEHEADER(outp, f->protocol); PUTCHAR(code, outp); PUTCHAR(id, outp); PUTSHORT(outlen, outp); pppWrite(f->unit, outpacket_buf[f->unit], outlen + PPP_HDRLEN); FSMDEBUG(LOG_INFO, ("fsm_sdata(%s): Sent code %d,%d,%d.\n", PROTO_NAME(f), code, id, outlen)); } #endif /* PPP_SUPPORT */
{ "pile_set_name": "Github" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_MULTI_COLUMN_SET_PAINTER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_MULTI_COLUMN_SET_PAINTER_H_ #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink { class LayoutMultiColumnSet; struct PaintInfo; struct PhysicalOffset; class MultiColumnSetPainter { STACK_ALLOCATED(); public: MultiColumnSetPainter(const LayoutMultiColumnSet& layout_multi_column_set) : layout_multi_column_set_(layout_multi_column_set) {} void PaintObject(const PaintInfo&, const PhysicalOffset& paint_offset); private: void PaintColumnRules(const PaintInfo&, const PhysicalOffset& paint_offset); const LayoutMultiColumnSet& layout_multi_column_set_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_MULTI_COLUMN_SET_PAINTER_H_
{ "pile_set_name": "Github" }
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/abap', ['require', 'exports', 'module' , 'ace/mode/abap_highlight_rules', 'ace/mode/folding/coffee', 'ace/range', 'ace/mode/text', 'ace/lib/oop'], function(require, exports, module) { var Rules = require("./abap_highlight_rules").AbapHighlightRules; var FoldMode = require("./folding/coffee").FoldMode; var Range = require("../range").Range; var TextMode = require("./text").Mode; var oop = require("../lib/oop"); function Mode() { this.HighlightRules = Rules; this.foldingRules = new FoldMode(); } oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); return indent; }; this.toggleCommentLines = function(state, doc, startRow, endRow){ var range = new Range(0, 0, 0, 0); for (var i = startRow; i <= endRow; ++i) { var line = doc.getLine(i); if (hereComment.test(line)) continue; if (commentLine.test(line)) line = line.replace(commentLine, '$1'); else line = line.replace(indentation, '$&#'); range.end.row = range.start.row = i; range.end.column = line.length + 1; doc.replace(range, line); } }; this.$id = "ace/mode/abap"; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/abap_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var AbapHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "variable.language": "this", "keyword": "ADD ALIAS ALIASES ASSERT ASSIGN ASSIGNING AT BACK" + " CALL CASE CATCH CHECK CLASS CLEAR CLOSE CNT COLLECT COMMIT COMMUNICATION COMPUTE CONCATENATE CONDENSE CONSTANTS CONTINUE CONTROLS CONVERT CREATE CURRENCY" + " DATA DEFINE DEFINITION DEFERRED DELETE DESCRIBE DETAIL DIVIDE DO" + " ELSE ELSEIF ENDAT ENDCASE ENDCLASS ENDDO ENDEXEC ENDFORM ENDFUNCTION ENDIF ENDIFEND ENDINTERFACE ENDLOOP ENDMETHOD ENDMODULE ENDON ENDPROVIDE ENDSELECT ENDTRY ENDWHILE EVENT EVENTS EXEC EXIT EXPORT EXPORTING EXTRACT" + " FETCH FIELDS FORM FORMAT FREE FROM FUNCTION" + " GENERATE GET" + " HIDE" + " IF IMPORT IMPORTING INDEX INFOTYPES INITIALIZATION INTERFACE INTERFACES INPUT INSERT IMPLEMENTATION" + " LEAVE LIKE LINE LOAD LOCAL LOOP" + " MESSAGE METHOD METHODS MODIFY MODULE MOVE MULTIPLY" + " ON OVERLAY OPTIONAL OTHERS" + " PACK PARAMETERS PERFORM POSITION PROGRAM PROVIDE PUT" + " RAISE RANGES READ RECEIVE RECEIVING REDEFINITION REFERENCE REFRESH REJECT REPLACE REPORT RESERVE RESTORE RETURNING ROLLBACK" + " SCAN SCROLL SEARCH SELECT SET SHIFT SKIP SORT SORTED SPLIT STANDARD STATICS STEP STOP SUBMIT SUBTRACT SUM SUMMARY SUPPRESS" + " TABLES TIMES TRANSFER TRANSLATE TRY TYPE TYPES" + " UNASSIGN ULINE UNPACK UPDATE" + " WHEN WHILE WINDOW WRITE" + " OCCURS STRUCTURE OBJECT PROPERTY" + " CASTING APPEND RAISING VALUE COLOR" + " CHANGING EXCEPTION EXCEPTIONS DEFAULT CHECKBOX COMMENT" + " ID NUMBER FOR TITLE OUTPUT" + " WITH EXIT USING" + " INTO WHERE GROUP BY HAVING ORDER BY SINGLE" + " APPENDING CORRESPONDING FIELDS OF TABLE" + " LEFT RIGHT OUTER INNER JOIN AS CLIENT SPECIFIED BYPASSING BUFFER UP TO ROWS CONNECTING" + " EQ NE LT LE GT GE NOT AND OR XOR IN LIKE BETWEEN", "constant.language": "TRUE FALSE NULL SPACE", "support.type": "c n i p f d t x string xstring decfloat16 decfloat34", "keyword.operator": "abs sign ceil floor trunc frac acos asin atan cos sin tan" + " abapOperator cosh sinh tanh exp log log10 sqrt" + " strlen xstrlen charlen numofchar dbmaxlen lines" }, "text", true, " "); var compoundKeywords = "WITH\\W+(?:HEADER\\W+LINE|FRAME|KEY)|NO\\W+STANDARD\\W+PAGE\\W+HEADING|"+ "EXIT\\W+FROM\\W+STEP\\W+LOOP|BEGIN\\W+OF\\W+(?:BLOCK|LINE)|BEGIN\\W+OF|"+ "END\\W+OF\\W+(?:BLOCK|LINE)|END\\W+OF|NO\\W+INTERVALS|"+ "RESPECTING\\W+BLANKS|SEPARATED\\W+BY|USING\\W+(?:EDIT\\W+MASK)|"+ "WHERE\\W+(?:LINE)|RADIOBUTTON\\W+GROUP|REF\\W+TO|"+ "(?:PUBLIC|PRIVATE|PROTECTED)(?:\\W+SECTION)?|DELETING\\W+(?:TRAILING|LEADING)"+ "(?:ALL\\W+OCCURRENCES)|(?:FIRST|LAST)\\W+OCCURRENCE|INHERITING\\W+FROM|"+ "LINE-COUNT|ADD-CORRESPONDING|AUTHORITY-CHECK|BREAK-POINT|CLASS-DATA|CLASS-METHODS|"+ "CLASS-METHOD|DIVIDE-CORRESPONDING|EDITOR-CALL|END-OF-DEFINITION|END-OF-PAGE|END-OF-SELECTION|"+ "FIELD-GROUPS|FIELD-SYMBOLS|FUNCTION-POOL|MOVE-CORRESPONDING|MULTIPLY-CORRESPONDING|NEW-LINE|"+ "NEW-PAGE|NEW-SECTION|PRINT-CONTROL|RP-PROVIDE-FROM-LAST|SELECT-OPTIONS|SELECTION-SCREEN|"+ "START-OF-SELECTION|SUBTRACT-CORRESPONDING|SYNTAX-CHECK|SYNTAX-TRACE|TOP-OF-PAGE|TYPE-POOL|"+ "TYPE-POOLS|LINE-SIZE|LINE-COUNT|MESSAGE-ID|DISPLAY-MODE|READ(?:-ONLY)?|"+ "IS\\W+(?:NOT\\W+)?(?:ASSIGNED|BOUND|INITIAL|SUPPLIED)"; this.$rules = { "start" : [ {token : "string", regex : "`", next : "string"}, {token : "string", regex : "'", next : "qstring"}, {token : "doc.comment", regex : /^\*.+/}, {token : "comment", regex : /".+$/}, {token : "invalid", regex: "\\.{2,}"}, {token : "keyword.operator", regex: /\W[\-+\%=<>*]\W|\*\*|[~:,\.&$]|->*?|=>/}, {token : "paren.lparen", regex : "[\\[({]"}, {token : "paren.rparen", regex : "[\\])}]"}, {token : "constant.numeric", regex: "[+-]?\\d+\\b"}, {token : "variable.parameter", regex : /sy|pa?\d\d\d\d\|t\d\d\d\.|innnn/}, {token : "keyword", regex : compoundKeywords}, {token : "variable.parameter", regex : /\w+-\w+(?:-\w+)*/}, {token : keywordMapper, regex : "\\b\\w+\\b"}, {caseInsensitive: true} ], "qstring" : [ {token : "constant.language.escape", regex : "''"}, {token : "string", regex : "'", next : "start"}, {defaultToken : "string"} ], "string" : [ {token : "constant.language.escape", regex : "``"}, {token : "string", regex : "`", next : "start"}, {defaultToken : "string"} ] } }; oop.inherits(AbapHighlightRules, TextHighlightRules); exports.AbapHighlightRules = AbapHighlightRules; }); define('ace/mode/folding/coffee', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != "#") return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != "#") break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); });
{ "pile_set_name": "Github" }
--- http_interactions: - request: method: get uri: https://auth0-sdk-tests.auth0.com/api/v2/connections?fields=name&include_fields=true&strategy=auth0 body: encoding: US-ASCII string: '' headers: Accept: - "*/*" Accept-Encoding: - gzip, deflate User-Agent: - Ruby/2.5.1 Content-Type: - application/json Auth0-Client: - eyJuYW1lIjoicnVieS1hdXRoMCIsInZlcnNpb24iOiI0LjUuMCJ9 Authorization: - Bearer API_TOKEN Host: - auth0-sdk-tests.auth0.com response: status: code: 200 message: OK headers: Date: - Thu, 04 Oct 2018 15:41:06 GMT Content-Type: - application/json; charset=utf-8 Transfer-Encoding: - chunked Connection: - keep-alive X-Ratelimit-Limit: - '10' X-Ratelimit-Remaining: - '4' X-Ratelimit-Reset: - '1538667670' Vary: - origin,accept-encoding Cache-Control: - private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Content-Encoding: - gzip Strict-Transport-Security: - max-age=15724800 X-Robots-Tag: - noindex, nofollow, nosnippet, noarchive body: encoding: ASCII-8BIT string: !binary |- H4sIAAAAAAAAA4uuVspMUbJSSs7Pi4+oMPEuKs1PTDIwKS/LiYxQ0lHKS8xNBcqGFqcWgZi6AYnFxeX5RSm6jqUlGal5JZnJiSWZ+XlAlZnF8Sn5uYmZefFAo/JSk8HCVmmJOcWptTpIlngb+Lq7GmdGhKSkJvp6F5ggLAlJLS5xhuvVLSpNqiwBChEwOxYAA7Uw2cIAAAA= http_version: recorded_at: Thu, 04 Oct 2018 15:41:06 GMT recorded_with: VCR 3.0.3
{ "pile_set_name": "Github" }
################################################################################ # # openjdk jni test # ################################################################################ OPENJDK_JNI_TEST_DEPENDENCIES = openjdk JNI_INCLUDE_PATH = $(BUILD_DIR)/openjdk-$(OPENJDK_VERSION)/build/linux-aarch64-server-release/jdk/include define OPENJDK_JNI_TEST_BUILD_CMDS # Compile Java classes and generate native headers $(JAVAC) -d $(@D) -h $(@D) \ $(OPENJDK_JNI_TEST_PKGDIR)/JniTest.java \ $(OPENJDK_JNI_TEST_PKGDIR)/JniWrapper.java \ $(OPENJDK_JNI_TEST_PKGDIR)/JniHelper.java # Compile shared library $(TARGET_MAKE_ENV) $(TARGET_CC) -shared -fPIC \ -I$(JNI_INCLUDE_PATH) -I$(JNI_INCLUDE_PATH)/linux -I$(@D) \ -o $(@D)/libjni_native.so \ $(OPENJDK_JNI_TEST_PKGDIR)/JniWrapper.c \ $(OPENJDK_JNI_TEST_PKGDIR)/jni_helper.c \ $(OPENJDK_JNI_TEST_PKGDIR)/native.c endef define OPENJDK_JNI_TEST_INSTALL_TARGET_CMDS $(INSTALL) -D -m 755 $(@D)/JniTest.class $(TARGET_DIR)/usr/bin/JniTest.class $(INSTALL) -D -m 755 $(@D)/JniWrapper.class $(TARGET_DIR)/usr/bin/JniWrapper.class $(INSTALL) -D -m 755 $(@D)/JniHelper.class $(TARGET_DIR)/usr/bin/JniHelper.class $(INSTALL) -D -m 755 $(@D)/libjni_native.so $(TARGET_DIR)/usr/lib/libjni_native.so endef $(eval $(generic-package))
{ "pile_set_name": "Github" }
'use strict'; var React = require('react'); var FluxibleApp = require('fluxible'); var routrPlugin = require('fluxible-plugin-routr'); var fetchrPlugin = require('fluxible-plugin-fetchr'); var routes = require('../client/client-routes'); var config = require('./config'); var appComponent = React.createFactory(require('../content/themes/' + config.theme + '/App')); var context = new FluxibleApp({ appComponent: appComponent }); context.plug(routrPlugin({ routes: routes })); context.plug(fetchrPlugin({ xhrPath: '/api' })); function configPlugin(options) { var config = options.config; return { name: 'configPlugin', plugContext: function() { return { plugActionContext: function(actionContext) { actionContext.config = config; }, dehydrate: function() { return { config: config }; }, rehydrate: function(state) { config = state.config; } }; } }; } context.plug(configPlugin({ config: config })); context.registerStore(require('./stores/ContentStore')); context.registerStore(require('./stores/ContentListStore')); context.registerStore(require('./stores/ApplicationStore')); context.registerStore(require('./stores/MetaStore')); module.exports = context;
{ "pile_set_name": "Github" }
<?php namespace Faker\Provider\kk_KZ; class Text extends \Faker\Provider\Text { /** * From kk.wikipedia.org * * Мәтін Creative Commons Attribution-ShareAlike лицензиясы аясында қолжетімді * кейбір жағдайларда қосымша шарттардың талаптары атқарылады. * Толығырақ қ. Қолдану шарттары. * * * Title: Арыстан баб кесенесі * * Posting Date: 22:55, 2015 ж. сәуірдің 12. * * Language: Kazakh * * @licence Creative Commons Attribution-ShareAlike http://creativecommons.org/licenses/by-sa/3.0/deed.ru * @see https://wikimediafoundation.org/wiki/Terms_of_Use/ * @link http://ru.wikipedia.org/wiki/%D0%92%D0%B8%D0%BA%D0%B8%D0%BF%D0%B5%D0%B4%D0%B8%D1%8F:%D0%A2%D0%B5%D0%BA%D1%81%D1%82_%D0%BB%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D0%B8_Creative_Commons_Attribution-ShareAlike_3.0_Unported * @var string */ protected static $baseText = <<<'EOT' Арыстан баб кесенесі - көне Отырар жеріндегі сәулет өнері ескерткіші. Түркістан халқының арасында мұсылман дінін таратушы Қожа Ахмет Иасауидің ұстазы болған Арыстан баб ата қабірінің басына салынған. Кесене дәлізхана, мешіт, құжырахана, азан шақыратын мұнара сияқты жеке бөлмелерден құралған. Кесененің ең көне бөлігі қабірхана болуы тиіс. Қазір де оның едені басқа бөлмелермен салыстырғанда едәуір биік. Қабір үстіне алғашқы белгі 12 ғ. шамасында салынған. Мазар 14 ғасырда қайта жөнделген. Арыстан баб кесенесі 20 ғасырдың басында жергілікті халықтың қаражатымен күйдірілген кірпіштен ауданы 35x12 м, биіктігі 12 м, бұрынғы Меккеге қараған есігі Түркістанға, Әзірет Сұлтанға бағытталып, Солтүстік жағы кесене, Оңтүстік жағы мешіт есебінде қайта жәнделді. Дәліз-қақпа маңдайшасына мәрмәр тақта қаланып, бетіне һижра бойынша 1327 жыл, яғни соңғы құрылыс жүрген уақыт деп көрсетілген. Қысқаша мәлімет Бұл кесене XII ғасырда өмір сүрген діни көріпкел Арыстан баб мазарының үстіне салынған. Кесененің бірінші құрылысы XIV-XV ғасырға жатады. Сол құрылыстан кесілген айван тізбектері қалған. XVIII ғасырда көне мазардың орнында жер сілкінісінен кейін екі кесілген ағаш тізбекке тірелген айванмен салынған екі күмбезді құрылыс орнатылды. XVIII ғасырда құрылыс қиратылып, фриз жазбалары бойынша 1909 жылы қайта салынды. 1971 жылы жоғары деңгейдегі грунт сулары салдарынан мешіт құлатылып, қайта орнатылды. Құрылыс алебастр ерітіндісінде күйдірілген кірпіштен қабырғаның сырт жағына салынды. Қазіргі кезде бұл кесене Орталық Азиядағы қажылық міндетті өтейтін мұсылман киелі жерлерінің бірі болып саналады Аңыз бойынша Арыстан баб Мұхаммед пайғамбардың елшісі болған. Бір күні Мұхаммед пайғамбар өзінің шәкірттерімен құрма жеп отырған еді. Бір құрма қайта-қайта ыдыстан құлай беріп, пайғамбар ішкі дауысты естіді: «Бұл құрма Сізден кейін 400 жыл алдағы уақытта туылатын мұсылман бала Ахметке арналған». Сонда пайғамбар шәкірттері ішінен бұл құрманы кім иесіне жеткізетінін сұрайды. Ешкім сұранған жоқ. Пайғамбар сұрақты қайта қойғаннан кейін, Арыстан баб былай деді: «Егер Сіз Алла Тағаладан 400 жыл сұрап берсеңіз мен бұл құрманы иесіне жеткіземін». Халық аңыздарынан және жазба деректеріне қарағанда («Рисолаи Сарем-Исфижоб» және Куприлозада кітабы) Арыстан баб Ахмет Яссауидің ұстазы болып құрманы жеткізеді. Қазіргі кезде Арыстан баб мазары үстінде 30*13 метр аумағы бар кесене тұр. Тарихи деректер бойынша XII-XVIII ғасырларда кесене бірнеше рет қайта салынып, қайта жаңартылды. Қожа Ахмет Яссауи ұлы әулие мен діни көріпкел 1103 жылы туылып 1166 жылы қайтыс болған. Арыстанбаб туралы аңыздар Арыстанбабтың дүние салуы Қожа Ахмет Иасауи хикметінде былайша суреттеледі: «Бабам айтты: Ей балам, қасымда тұр өлейін, Жаназамды оқып көм, жан тәсілім қалайын. Медет берсе Мұстафа, ғарыш биігіне шығайын. Арыслан бабам сөздерін есітіңіз - тәбәрік. Жылап айттым: ей бала, жас көдекпін білмеймін. Көріңізді қазармын, көтеріп сала алмаспын. Хақ Мұстафа сүндетін, балапанмын, білмеймін. Бабам айтты: Ей балам, періштелер жиылады. Жебірейіл имам болып, өзгелер оған ұйиды. Макаил мен Исрафил көтеріп көрге қояды».Отырар өңірінде біз естіген аңыз байынша Арыстанбаб дүние салған соң, оның денесін ақ бураға артып, еркіне жіберіп, соңынан ілесіп отырған. Ақ бура жүре-жүре осы жерге шөккен екен. Сол шөккен жерге Арыстанбаб қойылыпты. «Алпамыс жырының» бір үлгісінде Байбөрі мен Аналық «Самарқанда сансыз баб», Бұқарадағы «Баһауәдин Нақишбент» молаларына зират қылады, және "Түнейді үш күн Байбөрі Әзіретті сұлтанға. Түркістанда түмен бап, Сайрамда бар сансыз бап, Отырарда отыз бап, Бабалардың бабын сұрасаң, Ең үлкені Арыстан бап. Әулие қоймай қыдырып, Бабалардың бәрін қылды сап» Әзірет Сұлтан қорық-музейінің сақтаулы тұрған Баян ауылдан бір зияратшылдың қолжазбасында мынадай қызық мағұлмат бар: Арыстанбаб дүние салған соң, оның моласының басына екі құс – бірі лашын, бірі қарға ұшып келеді. Бұл әңгіме бізді ежелгі түркі шаманизміне жетелейді. Көне түркілер бұл аталған құстарды киелі деп санаған. Мысалы, ескі жылнамаларда жазылған аңыз бойынша көне түркілердің Ашина тайпасына жау шауып, жаппай қырып кетеді. Сонда жалғыз қалған бала ғана аман қалады. Баланы қасқыр емізіп, аспан әлемінің елшісі – қарға ет әкеліп асыраған. Осы баладан түркілердің ұрпағы деседі. Қазақтардың қарғаны киелі құс санағаны жөнінде дерек ер аз емес. Қарға сөзімен байланысты мынадай мақал-мәтелдер бар: «Біздің де қолымызға қарға тышар», «Қарға тамырлы қазақ», «Қарғам-ау» деген сөз қарағым, қалқам деген мағынада қолданылады. «Қарғам, қарғашым, қарғатайым" деп қарттар немере-шөберелерін еркелеткен. Қанша балаң бар деп жауап қайтарған. Құрылымы Арыстанбаб кесенесі ғасырлар бойы түрлі өндеу-жөндеуді басынан кешірген құрылыс. Кейде Арыстанбабтың ХІ-ХІІ ғасырларда өмір сүргенін тілге тиек ете отырып, оның кесенесі Арыстанбаб дүние салған соң іле-шала тұрғызылған деген жорамал айтылады. Алайда бізге жеткен қазіргі кесенеде ХІІ ғасырдың белгілері жоқ. Бұл арада біз ислам дінінің алғашқы кезде қабыр үстіне төбесі жабық құрылыс тұрғызуға тыйым салғанын есте ұстағанымыз жөн. Осы тұрғыдан қарағанда, ХІІ ғасырда Арыстанбаб ғимаратының болмауы да мүмкін. А.Черкасовтың жазбаларында Арыстанбаб кесенесі әулие және шәкірттері жатқан екі бөлмеден, сондай-ақ алдындағы бастырмадан тұрғанын жоғарыда айтқан болатынбыз. Бұлардың жобасы ХІV ғасырдың құрылысына сай келеді. Осымен қатар бастырмадағы ұстындар да ХІҮ ғасырдың аяғы мен ХV ғасырдың басында жасалған деген тұжырымды мамандар айтқан болатын. Яғни қазіргі Арыстанбаб құрылыс кешеніндегі қабырғаналар бөлігі ең көнесі, әуелгісі болып табылады. Бұған қоса халық арасында кең тараған мынадай аңыз бар: «Қожа Ахмет кесенесінің қабырғалары қаланып болған түні алып жасыл өгіз көтерілген дуалдарды мүйізімен соғып, құлатады. Ғимарат қабырғалары қайта тұрғызылып, күмбездері қалана бастағанда бұл оқиға тағы да қайталанып, бәрі үйелген төбеге айналады. Бұл жай Әмір Темірді көп ойландырады. Түсінде бір шал келіп, аян береді, ол Қожа Ахметтің ең алғашқы ұстазы, Арыстанбаб моласының үстіне мазар көтеруге әмір ететінін жеткізеді. Бұл талап орындалған соң ғана Әмір Темір Түркістандағы құрылысын ойдағыдай аяқтайды». Арыстанбаб қабірханасының едені басқа бөлмелермен салыстырғанда едәуір биік. Тігінен көтерілген қабырғалары бір биіктікте сәулет өнерінде «желкен» деп аталатын өріммен иіліп барым күмбезге ұласады. Күмбез ауқымы кең, һәм биік етіп тұрғызылған. Қабірхананың есігі күнбатысқа, дәлірек айтсақ, Меккеге бағышталған. Бұл қасиетті қабірлерге тағзым етудің мұсылмандық ережелерінен туындайды: зиярат етушінің беті сағанаға, арқасы құбылаға қарауға тиіс болған. Оның ұзындығы 3 м. 90 см., ені 1 м. 30 см., биіктігі 1 м. 20 см. Қабаттас, көлемі 5,4м х 5,4 м. Бөлмеде үш қабір бар. Ол да биік күмбезбен жабылған. Алайда күмбездің іші алебастрмен сыланып, геометриялық үлгідегі өрнектермен нақышталған. Әулиеге кірер есіктің екі жағында екі қабір орналасқан. Шырақшылар бұларды Лашынбаб пен Қарғабаб дейді. Олар әулие қабірімен салыстырғанда аса шағын болып келген. Лашын баб қабырының көлемі 1,63м х 0,92м., Қарғабабтікі 1,70 м х 0,90 м. Осы қабарханаларға оңтүстік-батыс жақтан бірнеше бөлмелер қосылған. Екі қанаттағы бөлмелерді біріктіріп, байланыстырып тұрған дәліз-бастырма бар. Ол әдеттегі бастырма-айвандардан өзгеше, тұтасымен қыштан өріліп, төбесі иіліп жабылған. Оның көлемі 7,60м х 4,35м. Қабырханалар, дәліз қышпен қаланып күмбезделсе, мешіт бөлігі негізінен қам кесектен тұрғызылып, төбесін жабуда ағаш кең пайдаланылған. Мешіттің ортасында В.В.Константинова жасаған жоба бойынша алты ағаш тіреу болған. Олардың үстіне қары қойылып, ағаштан қырлы күмбез қиыстырылған. Мешіт қабырғасында Мекке бағытын көрсететін ойық-михраб бар Зерттелуі Арыстан баб ескерткіші деп аталатын мазарлар басқа аймақтардың бірі – Қырғызстандағы Ош өңірінде. Бірақ қырғыздардың діни-нанымдарын зерттеген ғалым С.М.Абрамзонның пікірінше, жергілікті халық бұл жерде жерленген Арыстанбабты қалмақтарға қарсы соғысқан батыр деп таниды. Яғни Оштағы Арыстанбаб XYII-XVII ғасырларда болған адам. Арыстанбаб қабірінің басына тұрғызылған ғимарат алғаш ғылыми әдебиетте 1898 ж.ж. И.Т.Пославскийдің «Развалины города Отрара» атты мақаласында аталады. 1903 жылы кесене түркістандық археология әуесқойлар үйірмесінің мүшесі А.Черкасовтың Отырар төбені көріп айтқаны жөніндегі есебінде аталып өтіледі. А.Черкасовты түкпір бөлмедегі Арсытанбабтың қабірі таң қалдырады: «Надгробие Арстан – Баба такой же формы, как и остальные, покрыто куском белого коленкора и поражает своими размерами. Такого роста, по ловам шейха, достигал и сам святой...». А.Черкасовтың деректері кеінірек орыс-француз тілдерінде жарық көрген. И.А.Кастеньенің «Древности Киргизской степи и Оренбургского края» деген еңбегінде де қайталанады. Көп үзілістен кейін Арыстанбаб кесенесі жөніндегі ғылыми сипаттама 1950 ж. В.В.Константинованың «Некоторые архитектурные памятники по среднему течению р.Сырдарьи» деген мақаласында жарияланды. 1987 жылы «Білім мен Еңбекте» М.Сембиннің кесене жайлы мақаласы жарияланды. М.Сембин Арыстанбаб туралы мақаласында О.Дастановтың «Әулиелі жерлер туралы шындық» атты кітабындағы келтірілген мәліметтерге сүйене отырып, Арыстанбаб кесенесінің сәулетшісі ташкенттік Ескендір қажы болған деген болатын. «Ол өзінше бір қайта жырау, тыңнан толғау, немесе ақындық шабыт-шалым сынасып, жырмен жарысу есепті...»,- деген М.Әуезов сөздері Арыстанбаб сәулетшісіне толығымен тән. XXI ғасырдағы Арыстан баб кесенесі Әлемге танымал “Арыстан баб” мавзолейінің құрылысы екі жыл бұрын жаңа архитектуралық кешен тұрғысында басталған. Идея авторы – белгілі мемлекет және қоғам қайраткері, инженер-ғалым, танымал меценат Асқар Құлыбаев болып табылады. Бір кездері Асқар Алтынбекұлы халық игілігі үшін рухани құндылық орнатуды армандаған. Бүгінде Асқар Құлыбаевтың және оның ұлдарының Қазақстанның жан азығы байлығын еселей түсу мақсатындағы сіңірген үлесі зор екендігін айту қажет. Елбасымыз Н.Ә.Назарбаев өзі бастама көтеріп, бүкіл мемлекеттік деңгейде жүзеге “Мәдени мұра” бағдарламасы асырылып жатыр. EOT; /* *** START: FULL LICENSE *** Creative Commons Legal Code Attribution-ShareAlike 3.0 Unported CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM ITS USE. License THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 1. Definitions "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License. "Creative Commons Compatible License" means a license that is listed at http://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership. "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. 2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; to Distribute and Publicly Perform the Work including as incorporated in Collections; and, to Distribute and Publicly Perform Adaptations. For the avoidance of doubt: Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and, Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License. The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved. 4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested. You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. 5. Representations, Warranties and Disclaimer UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Termination This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. Creative Commons Notice Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor. Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, Creative Commons does not authorize the use by either party of the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time. For the avoidance of doubt, this trademark restriction does not form part of the License. Creative Commons may be contacted at http://creativecommons.org/. */ }
{ "pile_set_name": "Github" }
namespace ClassLib063 { public class Class020 { public static string Property => "ClassLib063"; } }
{ "pile_set_name": "Github" }
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "atom_vec_charge.h" #include "atom.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ AtomVecCharge::AtomVecCharge(LAMMPS *lmp) : AtomVec(lmp) { molecular = Atom::ATOMIC; mass_type = PER_TYPE; atom->q_flag = 1; // strings with peratom variables to include in each AtomVec method // strings cannot contain fields in corresponding AtomVec default strings // order of fields in a string does not matter // except: fields_data_atom & fields_data_vel must match data file fields_grow = (char *) "q"; fields_copy = (char *) "q"; fields_comm = (char *) ""; fields_comm_vel = (char *) ""; fields_reverse = (char *) ""; fields_border = (char *) "q"; fields_border_vel = (char *) "q"; fields_exchange = (char *) "q"; fields_restart = (char *) "q"; fields_create = (char *) "q"; fields_data_atom = (char *) "id type q x"; fields_data_vel = (char *) "id v"; setup_fields(); }
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define __DARWIN_UNIX03 0 #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include <dirent.h> #include <fcntl.h> #include <poll.h> #include <signal.h> #include <termios.h> #include <unistd.h> #include <mach/mach.h> #include <mach/message.h> #include <sys/event.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/param.h> #include <sys/ptrace.h> #include <sys/resource.h> #include <sys/select.h> #include <sys/signal.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/un.h> #include <sys/utsname.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_dl.h> #include <net/if_var.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/icmp6.h> #include <netinet/tcp.h> enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat64 type Statfs_t C.struct_statfs64 type Flock_t C.struct_flock type Fstore_t C.struct_fstore type Radvisory_t C.struct_radvisory type Fbootstraptransfer_t C.struct_fbootstraptransfer type Log2phys_t C.struct_log2phys type Fsid C.struct_fsid type Dirent C.struct_dirent // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet4Pktinfo C.struct_in_pktinfo type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2 SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfmaMsghdr2 C.struct_ifma_msghdr2 type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios type Winsize C.struct_winsize // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_REMOVEDIR = C.AT_REMOVEDIR AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) // poll type PollFd C.struct_pollfd const ( POLLERR = C.POLLERR POLLHUP = C.POLLHUP POLLIN = C.POLLIN POLLNVAL = C.POLLNVAL POLLOUT = C.POLLOUT POLLPRI = C.POLLPRI POLLRDBAND = C.POLLRDBAND POLLRDNORM = C.POLLRDNORM POLLWRBAND = C.POLLWRBAND POLLWRNORM = C.POLLWRNORM ) // uname type Utsname C.struct_utsname
{ "pile_set_name": "Github" }
/* * Copyright (c) 2002, Intel Corporation. All rights reserved. * This file is licensed under the GPL license. For the full content * of this license, see the COPYING file at the top level of this * source tree. * Test that pthread_rwlock_rdlock(pthread_rwlock_t *rwlock) * * If the Thread Execution Scheduling option is supported, * and the threads involved in the lock are executing with the * scheduling policies SCHED_FIFO or SCHED_RR, the calling thread shall not * acquire the lock if a writer holds the lock or if writers of * higher or equal priority are blocked on the lock; * otherwise, the calling thread shall acquire the lock. * * In this case, we test "higher priority writer block" * Steps: * We have three threads, main(also a reader), writer, reader * * 1. Main thread set its shcedule policy as "SCHED_FIFO", with highest priority * the three: sched_get_priority_min()+2. * 2. Main thread read lock 'rwlock' * 3. Create a writer thread, with schedule policy as "SCHED_FIFO", and priority * using sched_get_priority_min()+1. * 4. The thread write lock 'rwlock', should block. * 5. Main thread create a reader thread, with schedule policy as "SCHED_FIFO", and * priority sched_get_priority_min() * 6. Reader thread read lock 'rwlock', should block, since there is a higher priority * writer blocked on 'rwlock' * 7. Main thread release the 'rwlock', the writer should get the lock first */ /* NOTE: The test result is UNSUPPORTED if Thread Execution Scheduling option * is not supported. */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sched.h> #include "posixtest.h" #define TRD_POLICY SCHED_FIFO static pthread_rwlock_t rwlock; static int rd_thread_state; static int wr_thread_state; /* thread states: 1: not in child thread yet; 2: just enter child thread ; 3: just before child thread exit; */ #define NOT_CREATED_THREAD 1 #define ENTERED_THREAD 2 #define EXITING_THREAD 3 static int set_priority(pthread_t pid, unsigned policy, unsigned prio) { struct sched_param sched_param; memset(&sched_param, 0, sizeof(sched_param)); sched_param.sched_priority = prio; if (pthread_setschedparam(pid, policy, &sched_param) == -1) { printf("Can't set policy to %d and prio to %d\n", policy, prio); exit(PTS_UNRESOLVED); } return 0; } static void *fn_rd(void *arg) { int rc = 0; int priority; rd_thread_state = ENTERED_THREAD; priority = (long)arg; set_priority(pthread_self(), TRD_POLICY, priority); printf("rd_thread: attempt read lock\n"); rc = pthread_rwlock_rdlock(&rwlock); if (rc != 0) { printf ("Test FAILED: rd_thread failed to get read lock, Error code:%d\n", rc); exit(PTS_FAIL); } else printf("rd_thread: acquired read lock\n"); sleep(1); printf("rd_thread: unlock read lock\n"); if (pthread_rwlock_unlock(&rwlock) != 0) { printf("rd_thread: Error at pthread_rwlock_unlock()\n"); exit(PTS_UNRESOLVED); } rd_thread_state = EXITING_THREAD; pthread_exit(0); return NULL; } static void *fn_wr(void *arg) { int rc = 0; int priority; wr_thread_state = ENTERED_THREAD; priority = (long)arg; set_priority(pthread_self(), TRD_POLICY, priority); printf("wr_thread: attempt write lock\n"); rc = pthread_rwlock_wrlock(&rwlock); if (rc != 0) { printf ("Error: wr_thread failed to get write lock, Error code:%d\n", rc); exit(PTS_UNRESOLVED); } else printf("wr_thread: acquired write lock\n"); sleep(1); printf("wr_thread: unlock write lock\n"); if (pthread_rwlock_unlock(&rwlock) != 0) { printf("wr_thread: Error at pthread_rwlock_unlock()\n"); exit(PTS_UNRESOLVED); } wr_thread_state = EXITING_THREAD; pthread_exit(0); return NULL; } int main(void) { #ifndef _POSIX_THREAD_PRIORITY_SCHEDULING printf("Posix Thread Execution Scheduling not supported\n"); return PTS_UNSUPPORTED; #endif int cnt = 0; pthread_t rd_thread, wr_thread; int priority; /* main thread needs to have the highest priority */ priority = sched_get_priority_min(TRD_POLICY) + 2; set_priority(pthread_self(), TRD_POLICY, priority); printf("main: has priority: %d\n", priority); if (pthread_rwlock_init(&rwlock, NULL) != 0) { printf("main: Error at pthread_rwlock_init()\n"); return PTS_UNRESOLVED; } printf("main: attempt read lock\n"); /* This read lock should succeed */ if (pthread_rwlock_rdlock(&rwlock) != 0) { printf ("Test FAILED: main cannot get read lock when no one owns the lock\n"); return PTS_FAIL; } else printf("main: acquired read lock\n"); wr_thread_state = NOT_CREATED_THREAD; priority = sched_get_priority_min(TRD_POLICY) + 1; printf("main: create wr_thread, with priority: %d\n", priority); if (pthread_create(&wr_thread, NULL, fn_wr, (void *)(long)priority) != 0) { printf("main: Error at 1st pthread_create()\n"); return PTS_UNRESOLVED; } /* If the shared data is not altered by child after 3 seconds, we regard it as blocked */ /* We expect the wr_thread to block */ cnt = 0; do { sleep(1); } while (wr_thread_state != EXITING_THREAD && cnt++ < 3); if (wr_thread_state == EXITING_THREAD) { printf ("wr_thread did not block on write lock, when a reader owns the lock\n"); exit(PTS_UNRESOLVED); } else if (wr_thread_state != ENTERED_THREAD) { printf("Unexpected wr_thread state: %d\n", wr_thread_state); exit(PTS_UNRESOLVED); } rd_thread_state = 1; priority = sched_get_priority_min(TRD_POLICY); printf("main: create rd_thread, with priority: %d\n", priority); if (pthread_create(&rd_thread, NULL, fn_rd, (void *)(long)priority) != 0) { printf("main: failed at creating rd_thread\n"); return PTS_UNRESOLVED; } /* We expect the rd_thread to block */ cnt = 0; do { sleep(1); } while (rd_thread_state != EXITING_THREAD && cnt++ < 3); if (rd_thread_state == EXITING_THREAD) { printf ("Test FAILED: rd_thread did not block on read lock, when a reader owns the lock, and a higher priority writer is waiting for the lock\n"); exit(PTS_FAIL); } else if (rd_thread_state != ENTERED_THREAD) { printf("Unexpected rd_thread state: %d\n", rd_thread_state); exit(PTS_UNRESOLVED); } printf("main: unlock read lock\n"); if (pthread_rwlock_unlock(&rwlock) != 0) { printf("main: failed to unlock read lock\n"); exit(PTS_UNRESOLVED); } /* we expect the writer get the lock */ cnt = 0; do { sleep(1); } while (wr_thread_state != EXITING_THREAD && cnt++ < 3); if (wr_thread_state == ENTERED_THREAD) { printf ("Test FAILED: higher priority wr_thread still blocked on write lock, when a reader release the lock\n"); exit(PTS_FAIL); } else if (wr_thread_state != EXITING_THREAD) { printf("Unexpected wr_thread state: %d\n", wr_thread_state); exit(PTS_UNRESOLVED); } if (pthread_join(wr_thread, NULL) != 0) { printf("main: Error at 1st pthread_join()\n"); exit(PTS_UNRESOLVED); } /* we expect the reader get the lock when writer has unlocked the lock */ cnt = 0; do { sleep(1); } while (rd_thread_state != EXITING_THREAD && cnt++ < 3); if (rd_thread_state == ENTERED_THREAD) { printf ("Test FAILED: rd_thread still block on read lock when the lock has no owner\n"); exit(PTS_FAIL); } else if (rd_thread_state != EXITING_THREAD) { printf("Unexpected rd_thread state\n"); exit(PTS_UNRESOLVED); } if (pthread_join(rd_thread, NULL) != 0) { printf("main: Error at 2nd pthread_join()\n"); exit(PTS_UNRESOLVED); } if (pthread_rwlock_destroy(&rwlock) != 0) { printf("Error at pthread_rwlockattr_destroy()"); return PTS_UNRESOLVED; } printf("Test PASSED\n"); return PTS_PASS; }
{ "pile_set_name": "Github" }
{ "homebrew_version": "1.1.6", "used_options": [ "--with-foo", "--without-bar" ], "unused_options": [ "--with-baz", "--without-qux" ], "built_as_bottle": false, "poured_from_bottle": true, "changed_files": [ "INSTALL_RECEIPT.json", "bin/foo" ], "time": 1403827774, "HEAD": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", "alias_path": "/usr/local/Library/Taps/homebrew/homebrew-core/Aliases/test-formula", "stdlib": "libcxx", "compiler": "clang", "runtime_dependencies": [ { "full_name": "foo", "version": "1.0" } ], "source": { "path": "/usr/local/Library/Taps/homebrew/homebrew-core/Formula/foo.rb", "tap": "homebrew/core", "spec": "stable", "versions": { "stable": "2.14", "devel": "2.15", "head": "HEAD-0000000" } } }
{ "pile_set_name": "Github" }
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_ChattoApp : NSObject @end @implementation PodsDummy_Pods_ChattoApp @end
{ "pile_set_name": "Github" }
/* * Common SPI flash Interface * * Copyright (C) 2008 Atmel Corporation * Copyright (C) 2013 Jagannadha Sutradharudu Teki, Xilinx Inc. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ #ifndef _SPI_FLASH_H_ #define _SPI_FLASH_H_ #include <spi.h> #include <linux/types.h> #include <linux/compiler.h> /* sf param flags */ #define SECT_4K 1 << 1 #define SECT_32K 1 << 2 #define E_FSR 1 << 3 #define WR_QPP 1 << 4 /* Enum list - Full read commands */ enum spi_read_cmds { ARRAY_SLOW = 1 << 0, DUAL_OUTPUT_FAST = 1 << 1, DUAL_IO_FAST = 1 << 2, QUAD_OUTPUT_FAST = 1 << 3, QUAD_IO_FAST = 1 << 4, }; #define RD_EXTN ARRAY_SLOW | DUAL_OUTPUT_FAST | DUAL_IO_FAST #define RD_FULL RD_EXTN | QUAD_OUTPUT_FAST | QUAD_IO_FAST /* Dual SPI flash memories */ enum spi_dual_flash { SF_SINGLE_FLASH = 0, SF_DUAL_STACKED_FLASH = 1 << 0, SF_DUAL_PARALLEL_FLASH = 1 << 1, }; /** * struct spi_flash_params - SPI/QSPI flash device params structure * * @name: Device name ([MANUFLETTER][DEVTYPE][DENSITY][EXTRAINFO]) * @jedec: Device jedec ID (0x[1byte_manuf_id][2byte_dev_id]) * @ext_jedec: Device ext_jedec ID * @sector_size: Sector size of this device * @nr_sectors: No.of sectors on this device * @e_rd_cmd: Enum list for read commands * @flags: Importent param, for flash specific behaviour */ struct spi_flash_params { const char *name; u32 jedec; u16 ext_jedec; u32 sector_size; u32 nr_sectors; u8 e_rd_cmd; u16 flags; }; extern const struct spi_flash_params spi_flash_params_table[]; /** * struct spi_flash - SPI flash structure * * @spi: SPI slave * @name: Name of SPI flash * @dual_flash: Indicates dual flash memories - dual stacked, parallel * @shift: Flash shift useful in dual parallel * @size: Total flash size * @page_size: Write (page) size * @sector_size: Sector size * @erase_size: Erase size * @bank_read_cmd: Bank read cmd * @bank_write_cmd: Bank write cmd * @bank_curr: Current flash bank * @poll_cmd: Poll cmd - for flash erase/program * @erase_cmd: Erase cmd 4K, 32K, 64K * @read_cmd: Read cmd - Array Fast, Extn read and quad read. * @write_cmd: Write cmd - page and quad program. * @dummy_byte: Dummy cycles for read operation. * @memory_map: Address of read-only SPI flash access * @read: Flash read ops: Read len bytes at offset into buf * Supported cmds: Fast Array Read * @write: Flash write ops: Write len bytes from buf into offeset * Supported cmds: Page Program * @erase: Flash erase ops: Erase len bytes from offset * Supported cmds: Sector erase 4K, 32K, 64K * return 0 - Sucess, 1 - Failure */ struct spi_flash { struct spi_slave *spi; const char *name; u8 dual_flash; u8 shift; u32 size; u32 page_size; u32 sector_size; u32 erase_size; #ifdef CONFIG_SPI_FLASH_BAR u8 bank_read_cmd; u8 bank_write_cmd; u8 bank_curr; #endif u8 poll_cmd; u8 erase_cmd; u8 read_cmd; u8 write_cmd; u8 dummy_byte; void *memory_map; int (*read)(struct spi_flash *flash, u32 offset, size_t len, void *buf); int (*write)(struct spi_flash *flash, u32 offset, size_t len, const void *buf); int (*erase)(struct spi_flash *flash, u32 offset, size_t len); }; struct spi_flash *spi_flash_probe(unsigned int bus, unsigned int cs, unsigned int max_hz, unsigned int spi_mode); /** * Set up a new SPI flash from an fdt node * * @param blob Device tree blob * @param slave_node Pointer to this SPI slave node in the device tree * @param spi_node Cached pointer to the SPI interface this node belongs * to * @return 0 if ok, -1 on error */ struct spi_flash *spi_flash_probe_fdt(const void *blob, int slave_node, int spi_node); void spi_flash_free(struct spi_flash *flash); static inline int spi_flash_read(struct spi_flash *flash, u32 offset, size_t len, void *buf) { return flash->read(flash, offset, len, buf); } static inline int spi_flash_write(struct spi_flash *flash, u32 offset, size_t len, const void *buf) { return flash->write(flash, offset, len, buf); } static inline int spi_flash_erase(struct spi_flash *flash, u32 offset, size_t len) { return flash->erase(flash, offset, len); } void spi_boot(void) __noreturn; #endif /* _SPI_FLASH_H_ */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectName>libvorbisfile</ProjectName> <ProjectGuid>{CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}</ProjectGuid> <RootNamespace>libvorbisfile</RootNamespace> <Keyword>Win32Proj</Keyword> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" /> <Import Project="..\libogg.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" /> <Import Project="..\libogg.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" /> <Import Project="..\libogg.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" /> <Import Project="..\libogg.props" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup> <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion> <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Platform)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental> <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Platform)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental> <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Platform)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental> <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Platform)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>..\..\..\include;..\..\..\..\libogg\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBVORBISFILE_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <MinimalRebuild>true</MinimalRebuild> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>EditAndContinue</DebugInformationFormat> <CallingConvention>Cdecl</CallingConvention> </ClCompile> <Link> <AdditionalDependencies>libogg.lib;libvorbis.lib;%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)libvorbisfile.dll</OutputFile> <AdditionalLibraryDirectories>..\..\..\..\libogg\win32\VS2010\$(Platform)\$(Configuration);..\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>..\..\vorbisfile.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <ProgramDatabaseFile>$(OutDir)libvorbisfile.pdb</ProgramDatabaseFile> <SubSystem>Windows</SubSystem> <ImportLibrary>$(OutDir)libvorbisfile.lib</ImportLibrary> <TargetMachine>MachineX86</TargetMachine> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <Midl> <TargetEnvironment>X64</TargetEnvironment> </Midl> <ClCompile> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>..\..\..\include;..\..\..\..\libogg\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBVORBISFILE_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <MinimalRebuild>true</MinimalRebuild> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <CallingConvention>Cdecl</CallingConvention> </ClCompile> <Link> <AdditionalDependencies>libogg.lib;libvorbis.lib;%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)libvorbisfile.dll</OutputFile> <AdditionalLibraryDirectories>..\..\..\..\libogg\win32\VS2010\$(Platform)\$(Configuration);..\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>..\..\vorbisfile.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <ProgramDatabaseFile>$(OutDir)libvorbisfile.pdb</ProgramDatabaseFile> <SubSystem>Windows</SubSystem> <ImportLibrary>$(OutDir)libvorbisfile.lib</ImportLibrary> <TargetMachine>MachineX64</TargetMachine> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <AdditionalIncludeDirectories>..\..\..\include;..\..\..\..\libogg\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBVORBISFILE_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <CallingConvention>Cdecl</CallingConvention> </ClCompile> <Link> <AdditionalDependencies>libogg.lib;libvorbis.lib;%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)libvorbisfile.dll</OutputFile> <AdditionalLibraryDirectories>..\..\..\..\libogg\win32\VS2010\$(Platform)\$(Configuration);..\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>..\..\vorbisfile.def</ModuleDefinitionFile> <GenerateDebugInformation>false</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <OptimizeReferences>true</OptimizeReferences> <EnableCOMDATFolding>true</EnableCOMDATFolding> <ImportLibrary>$(OutDir)libvorbisfile.lib</ImportLibrary> <TargetMachine>MachineX86</TargetMachine> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <Midl> <TargetEnvironment>X64</TargetEnvironment> </Midl> <ClCompile> <AdditionalIncludeDirectories>..\..\..\include;..\..\..\..\libogg\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBVORBISFILE_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <CallingConvention>Cdecl</CallingConvention> </ClCompile> <Link> <AdditionalDependencies>libogg.lib;libvorbis.lib;%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)libvorbisfile.dll</OutputFile> <AdditionalLibraryDirectories>..\..\..\..\libogg\win32\VS2010\$(Platform)\$(Configuration);..\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>..\..\vorbisfile.def</ModuleDefinitionFile> <GenerateDebugInformation>false</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <OptimizeReferences>true</OptimizeReferences> <EnableCOMDATFolding>true</EnableCOMDATFolding> <ImportLibrary>$(OutDir)libvorbisfile.lib</ImportLibrary> <TargetMachine>MachineX64</TargetMachine> </Link> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="..\..\..\lib\vorbisfile.c" /> </ItemGroup> <ItemGroup> <ClInclude Include="..\..\..\include\vorbis\vorbisfile.h" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\libvorbis\libvorbis_dynamic.vcxproj"> <Project>{3a214e06-b95e-4d61-a291-1f8df2ec10fd}</Project> </ProjectReference> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
{ "pile_set_name": "Github" }
#ifndef K3DSDK_IBOUNDED_H #define K3DSDK_IBOUNDED_H // K-3D // Copyright (c) 1995-2004, Timothy M. Shead // // Contact: [email protected] // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** \file \author Tim Shead ([email protected]) */ #include <k3dsdk/bounding_box3.h> #include <k3dsdk/iunknown.h> namespace k3d { /// Abstract interface for quickly determining the bounding box of objects that fill a 3D volume class ibounded : public virtual iunknown { public: /// Returns the bounding box of an object (within its local coordinate system) virtual const bounding_box3 extents() = 0; protected: ibounded() {} ibounded(const ibounded&) {} ibounded& operator=(const ibounded&) { return *this; } virtual ~ibounded() {} }; } // namespace k3d #endif // !K3DSDK_IBOUNDED_H
{ "pile_set_name": "Github" }
// PLAIN_PARAM(name) // ANY_PARAM(name) // WORD(name) // GROUP(options) module.exports = { name: 'AST', init: function(){ var AST = basis.require('basis.router.ast'); var parsePath = AST.parsePath; var stringify = AST.stringify; function plain(name) { return { type: AST.TYPE.PLAIN_PARAM, name: name }; } function any(name) { return { type: AST.TYPE.ANY_PARAM, name: name }; } function word(name) { return { type: AST.TYPE.WORD, name: name }; } function group() { return { type: AST.TYPE.GROUP, options: basis.array.from(arguments) }; } function option() { return { type: AST.TYPE.GROUP_OPTION, children: basis.array.from(arguments) }; } function ast(path) { return JSON.stringify(parsePath(path).ast); } function str(obj) { return JSON.stringify(obj); } }, test: [ { name: 'parsePath', test: [ { name: 'simple case', test: function(){ var actual = ast('foo/:bar/*baz'); var expected = str([ word('foo/'), plain('bar'), word('/'), any('baz') ]); assert(actual == expected); } }, { name: 'word with extra chars', test: function(){ var actual = ast('/[]?{}/:bar/|+-.^'); var expected = str([ word('/[]?{}/'), plain('bar'), word('/|+-.^') ]); assert(actual == expected); } }, { name: 'group with one child', test: function(){ var actual = ast('page/sub(/)(:rest)(complex/*sub)'); var expected = str([ word('page/sub'), group( option( word('/') ) ), group( option( plain('rest') ) ), group( option( word('complex/'), any('sub') ) ) ]); assert(actual == expected); } }, { name: 'word with non-closing bracket', test: function(){ var actual = ast('page/sub)('); var expected = str([ word('page/sub)(') ]); assert(actual == expected); } }, { name: 'group with multiple options', test: function(){ var actual = ast('page/(:foo|bar|*baz)/end'); var expected = str([ word('page/'), group( option( plain('foo') ), option( word('bar') ), option( any('baz') ) ), word('/end') ]); assert(actual == expected); } }, { name: 'recursive group', test: function(){ var actual = ast('page/(:foo|(bar|:spam(/))|*baz)/end'); var expected = str([ word('page/'), group( option( plain('foo') ), option( group( option( word('bar') ), option( plain('spam'), group( option( word('/') ) ) ) ) ), option( any('baz') ) ), word('/end') ]); assert(actual == expected); } }, { name: 'escaping', test: function(){ var actual = ast('page\\/\\(\\:foo\\|bar\\|\\*baz\\)\\/\\end\\\\'); var expected = str([ word('page/(:foo|bar|*baz)/end\\') ]); assert(actual == expected); } }, { name: 'regexp - groups and params', test: function(){ var actual = parsePath('page/(:foo|(bar|:spam(/))|*baz)/end').regexp.toString(); var expected = new RegExp('^page\/(?:([^/]+)|(?:bar|([^/]+)(?:\/)?)?|(.*?))?\/end$', 'i').toString(); assert(actual == expected); } }, { name: 'regexp - escaping', test: function(){ // page\/\(\:foo\|bar\|\*baz\)\/\end\\ var actual = parsePath('page\\/\\(\\:foo\\|bar\\|\\*baz\\)\\/\\end\\\\').regexp.toString(); var expected = new RegExp('^page\\/\\(\\:foo\\|bar\\|\\*baz\\)\\/\\end\\\\$', 'i').toString(); assert(actual == expected); } }, { name: 'regexp - symbols', test: function(){ var actual = parsePath('/[]?{}/:bar/|+-.^').regexp.toString(); var expected = new RegExp('^\\/\\[\\]\\?\\{\\}\\/([^/]+)\\/\\|\\+\\-\\.\\^$', 'i').toString(); assert(actual == expected); } } ] }, { name: 'stringify', test: [ { name: 'word', test: function(){ var actual = stringify([ word('myword') ], {}, {}); var expected = 'myword'; assert(actual == expected); } }, { name: 'plain param', test: function(){ var actual = stringify([ plain('plainParam') ], { plainParam: 'plainParam value' }, { plainParam: true // plainParam has modified value }); var expected = 'plainParam%20value'; assert(actual == expected); } }, { name: 'any param', test: function(){ var actual = stringify([ any('anyParam') ], { anyParam: 'anyParam/value' }, { anyParam: true // anyParam has modified value }); var expected = 'anyParam%2Fvalue'; assert(actual == expected); } }, { name: 'omits optional group without params', test: function(){ var actual = stringify([ word('begin'), group( option( word('/end') ) ) ], {}, {}); var expected = 'begin'; assert(actual == expected); } }, { name: 'writes optional group with any param', test: function(){ var actual = stringify([ word('begin'), group( option( word('/'), any('id') ) ) ], { id: 42 }, { id: true // id has modified value }); var expected = 'begin/42'; assert(actual == expected); } }, { name: 'omits optional group with plain param with default value', test: function(){ var actual = stringify([ word('begin'), group( option( word('/'), plain('id') ) ) ], { id: -1 }, { id: false // id has default value }); var expected = 'begin'; assert(actual == expected); } }, { name: 'omits optional group with any param with default value - recursive', test: function(){ var actual = stringify([ word('begin'), group( option( word('/'), plain('id') ) ) ], { id: 1 }, { id: false // id has default value }); var expected = 'begin'; assert(actual == expected); } }, { name: 'omits optional group with multiple options if there is no params between them', test: function(){ var actual = stringify([ word('page/'), group( option( word('foo') ), option( word('bar') ), option( word('baz') ) ) ], {}, {}); var expected = 'page/'; assert(actual == expected); } }, { name: 'omits optional group with multiple options if there is no nondefault params', test: function(){ var actual = stringify([ word('page/'), group( option( word('foo') ), option( plain('plainParam') ), option( any('anyParam') ) ) ], { plainParam: 'plain', anyParam: 'any' }, { plainParam: false, // plainParam has default value anyParam: false // anyParam has default value }); var expected = 'page/'; assert(actual == expected); } }, { name: 'writes optional group with specified param only', test: function(){ var actual = stringify([ word('page/'), group( option( word('foo') ), option( plain('plainParam') ), option( any('anyParam') ) ) ], { plainParam: 'plain', anyParam: 'any' }, { plainParam: false, // plainParam has default value anyParam: true // anyParam has modified value }); var expected = 'page/any'; assert(actual == expected); } }, { name: 'writes optional group with specified param only - recursive', test: function(){ var actual = stringify([ word('page/'), group( option( word('foo') ), option( group( option( word('bar') ), option( plain('plainParam') ) ) ), option( any('anyParam') ) ) ], { plainParam: 'plain', anyParam: 'any param' }, { plainParam: true, // plainParam has modified value anyParam: true // anyParam has modified value }); var expected = 'page/plain?anyParam=any%20param'; assert(actual == expected); } }, { name: 'writes multiple optional params to query', test: function(){ var actual = stringify([ word('page/') ], { plainParam: 'plain', anyParam: 'any param' }, { plainParam: true, // plainParam has modified value anyParam: true // anyParam has modified value }); var expected = 'page/?plainParam=plain&anyParam=any%20param'; assert(actual == expected); } }, { name: 'writes multiple optional params to query', test: function(){ var actual = stringify([ word('page/') ], { 'basis js': 'framework' }, { 'basis js': true // 'basis js' has modified value }); var expected = 'page/?basis%20js=framework'; assert(actual == expected); } }, { name: 'writes optional groups with default params in case they precedes a nondefault param', test: function(){ var actual = stringify([ word('page/'), group( option( plain('first'), word('/') ) ), group( option( plain('second'), word('/') ) ), group( option( plain('third'), word('/') ) ), group( option( plain('fourth'), word('/') ) ) ], { first: 1, second: 2, third: 3, fourth: 4 }, { first: false, // first has default value second: false, // second has default value third: true, // third has modified value fourth: false // fourth has default value }); var expected = 'page/1/2/3/'; assert(actual == expected); } }, { name: 'writes optional group with default params in case they precedes a required plain param', test: function(){ var actual = stringify([ word('page/'), group( option( plain('first'), word('/') ) ), plain('second') ], { first: 1, second: 2 }, { first: false, // first has default value second: false // second has default value }); var expected = 'page/1/2'; assert(actual == expected); } }, { name: 'writes optional group with default params in case they precedes a word', test: function(){ var actual = stringify([ word('page/'), group( option( plain('first'), word('/') ) ), word('second') ], { first: 1 }, { first: false // first has default value }); var expected = 'page/1/second'; assert(actual == expected); } } ] } ] };
{ "pile_set_name": "Github" }
class Re2 < Formula desc "Alternative to backtracking PCRE-style regular expression engines" homepage "https://github.com/google/re2" head "https://github.com/google/re2.git" stable do url "https://github.com/google/re2/archive/2016-03-01.tar.gz" version "20160301" sha256 "2dc6188270fe83660ccb379ef2d5ce38e0e38ca0e1c0b3af4b2b7cf0d8c9c11a" end bottle do cellar :any sha256 "e1042bd0951be2c2651327269ffdf605c6cddff01162c266dac9663ee846940a" => :el_capitan sha256 "00abdcbad108a5dee607a6b34ccb97d970f6dc6fd53dd9680e0549945ef2fb9e" => :yosemite sha256 "941571b08e34921134c2fc15b5e855f7c2da5a882fd262766fa01dac988990f3" => :mavericks end needs :cxx11 unless OS.mac? def install ENV.cxx11 unless OS.mac? system "make", "install", "prefix=#{prefix}" system "install_name_tool", "-id", "#{lib}/libre2.0.dylib", "#{lib}/libre2.0.0.0.dylib" if OS.mac? ext = OS.mac? ? "dylib" : "so" lib.install_symlink "libre2.0.0.0.#{ext}" => "libre2.0.#{ext}" lib.install_symlink "libre2.0.0.0.#{ext}" => "libre2.#{ext}" end test do (testpath/"test.cpp").write <<-EOS.undent #include <re2/re2.h> #include <assert.h> int main() { assert(!RE2::FullMatch("hello", "e")); assert(RE2::PartialMatch("hello", "e")); return 0; } EOS system ENV.cxx, "-I#{include}", "-L#{lib}", "-lre2", testpath/"test.cpp", "-o", "test" system "./test" end end
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1 import ( "time" v1 "k8s.io/api/storage/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // StorageClassesGetter has a method to return a StorageClassInterface. // A group's client should implement this interface. type StorageClassesGetter interface { StorageClasses() StorageClassInterface } // StorageClassInterface has methods to work with StorageClass resources. type StorageClassInterface interface { Create(*v1.StorageClass) (*v1.StorageClass, error) Update(*v1.StorageClass) (*v1.StorageClass, error) Delete(name string, options *metav1.DeleteOptions) error DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error Get(name string, options metav1.GetOptions) (*v1.StorageClass, error) List(opts metav1.ListOptions) (*v1.StorageClassList, error) Watch(opts metav1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.StorageClass, err error) StorageClassExpansion } // storageClasses implements StorageClassInterface type storageClasses struct { client rest.Interface } // newStorageClasses returns a StorageClasses func newStorageClasses(c *StorageV1Client) *storageClasses { return &storageClasses{ client: c.RESTClient(), } } // Get takes name of the storageClass, and returns the corresponding storageClass object, and an error if there is any. func (c *storageClasses) Get(name string, options metav1.GetOptions) (result *v1.StorageClass, err error) { result = &v1.StorageClass{} err = c.client.Get(). Resource("storageclasses"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(). Into(result) return } // List takes label and field selectors, and returns the list of StorageClasses that match those selectors. func (c *storageClasses) List(opts metav1.ListOptions) (result *v1.StorageClassList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.StorageClassList{} err = c.client.Get(). Resource("storageclasses"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested storageClasses. func (c *storageClasses) Watch(opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Resource("storageclasses"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch() } // Create takes the representation of a storageClass and creates it. Returns the server's representation of the storageClass, and an error, if there is any. func (c *storageClasses) Create(storageClass *v1.StorageClass) (result *v1.StorageClass, err error) { result = &v1.StorageClass{} err = c.client.Post(). Resource("storageclasses"). Body(storageClass). Do(). Into(result) return } // Update takes the representation of a storageClass and updates it. Returns the server's representation of the storageClass, and an error, if there is any. func (c *storageClasses) Update(storageClass *v1.StorageClass) (result *v1.StorageClass, err error) { result = &v1.StorageClass{} err = c.client.Put(). Resource("storageclasses"). Name(storageClass.Name). Body(storageClass). Do(). Into(result) return } // Delete takes name of the storageClass and deletes it. Returns an error if one occurs. func (c *storageClasses) Delete(name string, options *metav1.DeleteOptions) error { return c.client.Delete(). Resource("storageclasses"). Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *storageClasses) DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error { var timeout time.Duration if listOptions.TimeoutSeconds != nil { timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second } return c.client.Delete(). Resource("storageclasses"). VersionedParams(&listOptions, scheme.ParameterCodec). Timeout(timeout). Body(options). Do(). Error() } // Patch applies the patch and returns the patched storageClass. func (c *storageClasses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.StorageClass, err error) { result = &v1.StorageClass{} err = c.client.Patch(pt). Resource("storageclasses"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }
{ "pile_set_name": "Github" }
module.exports = { // doc for f1 f1: function() { return 7; } }; // doc for f2 module.exports.f2 = function() { return 7; };
{ "pile_set_name": "Github" }
_ 33494 e 8992 n 7900 t 7859 a 7781 r 7251 s 6435 i 5649 l 4541 d 4079 o 3724 m 3203 k 3058 g 2478 en 2403 n_ 2389 t_ 2073 de 1939 r_ 1910 v 1890 h 1789 u 1782 _s 1768 ä 1724 er 1709 f 1597 en_ 1537 a_ 1526 an 1357 p 1320 et 1317 ö 1278 å 1261 st 1236 ar 1226 c 1191 _d 1158 e_ 1116 in 1045 _f 1027 te 1000 b 997 _a 978 s_ 974 ra 958 . 956 tt 935 _i 898 _m 890 ._ 886 ll 870 ta 844 _o 842 _e 839 nd 820 ti 804 sk 798 re 779 at 769 _de 754 om 743 m_ 739 ör 720 , 697 ,_ 695 ng 686 li 673 ka 666 oc 662 _h 654 on 652 et_ 647 ch 645 ns 643 is 642 er_ 630 är 625 _v 614 _t 614 ni 611 i_ 609 _oc 592 tt_ 587 na 586 y 586 la 579 _b 579 h_ 577 kt 575 ch_ 568 ig 564 fö 563 och 555 or 555 _och 554 och_ 554 _och_ 553 me 548 den 548 om_ 535 _i_ 531 d_ 530 j 529 ik 520 de_ 520 för 518 ge 498 ad 497 _k 491 _fö 487 ri 484 el 482 il 481 so 480 al 474 g_ 469 le 464 an_ 461 _för 447 si 437 ar_ 437 att 435 _p 434 es 420 ing 413 se 407 to 404 _u 403 _en 403 and 398 den_ 395 nde 393 nn 393 _l 391 å_ 391 D 385 än 383 nt 382 l_ 381 tr 378 _D 372 va 370 am 369 sa 367 _so 365 ga 364 _en_ 361 är_ 358 ck 357 av 354 v_ 351 ed 347 ma 346 da 346 som 346 rs 344 som_ 344 ve 342 ter 341 att_ 341 ha 338 ne 337 ut 335 as 332 ska 329 _at 327 _att 326 _som 324 _att_ 324 _som_ 323 vi 322 ikt 317 _av 316 det 316 _den 315 he 315 ss 314 un 307 ke 304 _g 303 us 302 di 302 _st 300 rn 297 _me 296 _ä 295 ade 294 " 290 _ha 290 av_ 289 ill 288 _n 286 _in 279 io 275 _r 275 der 275 it 274 _av_ 274 sta 274 gen 272 isk 270 _ti 269 id 265 na_ 265 ns_ 264 ko 262 _den_ 261 ag 258 det_ 257 lig 257 era 256 ll_ 255 _det 252 _är 251 be 249 _är_ 248 ra_ 247 ion 244 - 241 pr 240 oni 233 til 231 ten 228 _si 225 k_ 222 på 222 fr 221 ro 219 till 219 iv 216 ls 216 ande 215 ör_ 214 _det_ 213 äl 212 _på 211 ts 210 ens 209 med 209 mm 208 rt 208 _till 208 _til 208 _va 207 _fr 205 _sk 205 var 205 nin 204 ning 203 ol 201 ka_ 200 lle 198 ett 198 rd 197 em 196 på_ 195 x 195 rk 194 _ut 194 ste 194 ds 193 _vi 192 år 192 S 192 nde_ 191 are 191 ver 190 _på_ 190 nis 189 kr 189 _med 188 all 188 ån 187 nge 185 mo 184 os 183 ld 182 ade_ 181 _S 181 ed_ 180 rä 176 De 175 _- 175 kan 174 ta_ 173 ng_ 172 vä 171 för_ 170 ill_ 170 han 170 _De 170 pp 169 lt 169 sam 168 nte 167 ans 167 ton 166 ur 165 mi 165 ess 165 kl 164 ig_ 164 ks 164 as_ 163 und 163 men 162 med_ 161 _med_ 161 ak 161 Di 160 ot 159 rna 159 ul 159 _var 159 te_ 158 gen_ 158 het 157 kto 157 str 156 _Di 155 tad 155 lan 154 ga_ 154 iska 154 fa 154 fi 154 så 154 Dikt 153 Dik 153 pe 153 ska_ 152 ja 152 H 151 res 151 ku 151 iu 150 ande_ 150 till_ 150 t. 150 ern 150 rm 149 _Dikt 149 _Dik 149 ie 149 bl 148 -_ 147 od 147 _H 147 n. 147 ist 147 _di 146 ius 146 _" 145 la_ 145 sl 145 man 145 ren 145 _för_ 145 toni 144 kton 144 n._ 144 ktoni 144 ikton 144 I 144 ikto 144 nius 143 ten_ 143 onius 143 oniu 143 toniu 143 ing_ 143 Dikto 143 niu 143 _ko 143 ic 142 _sa 142 _han 142 ett_ 142 sm 141 ba 141 M 141 gr 140 lä 140 ex 138 t._ 138 sp 137 lla 137 _et 137 _M 137 dr 137 rö 136 rad 136 ek 136 _be 135 tar 135 _-_ 135 _om 134 rl 134 E 134 mä 133
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="anyType" nillable="true" type="xs:anyType" /> <xs:element name="anyURI" nillable="true" type="xs:anyURI" /> <xs:element name="base64Binary" nillable="true" type="xs:base64Binary" /> <xs:element name="boolean" nillable="true" type="xs:boolean" /> <xs:element name="byte" nillable="true" type="xs:byte" /> <xs:element name="dateTime" nillable="true" type="xs:dateTime" /> <xs:element name="decimal" nillable="true" type="xs:decimal" /> <xs:element name="double" nillable="true" type="xs:double" /> <xs:element name="float" nillable="true" type="xs:float" /> <xs:element name="int" nillable="true" type="xs:int" /> <xs:element name="long" nillable="true" type="xs:long" /> <xs:element name="QName" nillable="true" type="xs:QName" /> <xs:element name="short" nillable="true" type="xs:short" /> <xs:element name="string" nillable="true" type="xs:string" /> <xs:element name="unsignedByte" nillable="true" type="xs:unsignedByte" /> <xs:element name="unsignedInt" nillable="true" type="xs:unsignedInt" /> <xs:element name="unsignedLong" nillable="true" type="xs:unsignedLong" /> <xs:element name="unsignedShort" nillable="true" type="xs:unsignedShort" /> <xs:element name="char" nillable="true" type="tns:char" /> <xs:simpleType name="char"> <xs:restriction base="xs:int" /> </xs:simpleType> <xs:element name="duration" nillable="true" type="tns:duration" /> <xs:simpleType name="duration"> <xs:restriction base="xs:duration"> <xs:pattern value="\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?" /> <xs:minInclusive value="-P10675199DT2H48M5.4775808S" /> <xs:maxInclusive value="P10675199DT2H48M5.4775807S" /> </xs:restriction> </xs:simpleType> <xs:element name="guid" nillable="true" type="tns:guid" /> <xs:simpleType name="guid"> <xs:restriction base="xs:string"> <xs:pattern value="[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}" /> </xs:restriction> </xs:simpleType> <xs:attribute name="FactoryType" type="xs:QName" /> <xs:attribute name="Id" type="xs:ID" /> <xs:attribute name="Ref" type="xs:IDREF" /> </xs:schema>
{ "pile_set_name": "Github" }
import pandas as pd import re from .constants import PARSING_SCHEME from ..decorators import float_property_decorator, int_property_decorator from .. import utils from .conferences import Conferences from .ncaaf_utils import _retrieve_all_teams from .roster import Roster from .schedule import Schedule class Team: """ An object containing all of a team's season information. Finds and parses all team stat information and identifiers, such as full and short names, and sets them as properties which can be directly read from for easy reference. If calling directly, the team's abbreviation needs to be passed. Otherwise, the Teams class will handle all arguments. Parameters ---------- team_name : string (optional) The name of the team to pull if being called directly. team_data : string (optional) A string containing all of the rows of stats for a given team. If multiple tables are being referenced, this will be comprised of multiple rows in a single string. team_conference : string (optional) A string of the team's conference abbreviation, such as 'big-12'. year : string (optional) The requested year to pull stats from. """ def __init__(self, team_name=None, team_data=None, team_conference=None, year=None): self._team_conference = team_conference self._year = year self._abbreviation = None self._name = None self._games = None self._wins = None self._losses = None self._win_percentage = None self._conference_wins = None self._conference_losses = None self._conference_win_percentage = None self._points_per_game = None self._points_against_per_game = None self._strength_of_schedule = None self._simple_rating_system = None self._pass_completions = None self._pass_attempts = None self._pass_completion_percentage = None self._pass_yards = None self._interceptions = None self._pass_touchdowns = None self._rush_attempts = None self._rush_yards = None self._rush_yards_per_attempt = None self._rush_touchdowns = None self._plays = None self._yards = None self._turnovers = None self._fumbles_lost = None self._yards_per_play = None self._pass_first_downs = None self._rush_first_downs = None self._first_downs_from_penalties = None self._first_downs = None self._penalties = None self._yards_from_penalties = None self._opponents_pass_completions = None self._opponents_pass_attempts = None self._opponents_pass_completion_percentage = None self._opponents_pass_yards = None self._opponents_interceptions = None self._opponents_pass_touchdowns = None self._opponents_rush_attempts = None self._opponents_rush_yards = None self._opponents_rush_yards_per_attempt = None self._opponents_rush_touchdowns = None self._opponents_plays = None self._opponents_yards = None self._opponents_turnovers = None self._opponents_fumbles_lost = None self._opponents_yards_per_play = None self._opponents_pass_first_downs = None self._opponents_rush_first_downs = None self._opponents_first_downs_from_penalties = None self._opponents_first_downs = None self._opponents_penalties = None self._opponents_yards_from_penalties = None if team_name: team_data = self._retrieve_team_data(year, team_name) conferences_dict = Conferences(year).team_conference self._team_conference = conferences_dict[team_name.lower()] self._parse_team_data(team_data) def __str__(self): """ Return the string representation of the class. """ return f'{self.name} ({self.abbreviation}) - {self._year}' def __repr__(self): """ Return the string representation of the class. """ return self.__str__() def _retrieve_team_data(self, year, team_name): """ Pull all stats for a specific team. By first retrieving a dictionary containing all information for all teams in the league, only select the desired team for a specific year and return only their relevant results. Parameters ---------- year : string A ``string`` of the requested year to pull stats from. team_name : string A ``string`` of the team's abbreviation, such as 'PURDUE' for the Purdue Boilermakers. Returns ------- PyQuery object Returns a PyQuery object containing all stats and information for the specified team. """ team_data_dict, year = _retrieve_all_teams(year) self._year = year team_data = team_data_dict[team_name]['data'] return team_data def _parse_team_data(self, team_data): """ Parses a value for every attribute. This function looks through every attribute and retrieves the value according to the parsing scheme and index of the attribute from the passed HTML data. Once the value is retrieved, the attribute's value is updated with the returned result. Note that this method is called directly once Team is invoked and does not need to be called manually. Parameters ---------- team_data : string A string containing all of the rows of stats for a given team. If multiple tables are being referenced, this will be comprised of multiple rows in a single string. """ for field in self.__dict__: if field == '_year' or \ field == '_team_conference': continue value = utils._parse_field(PARSING_SCHEME, team_data, str(field)[1:]) setattr(self, field, value) @property def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string abbreviation of the team, such as 'PURDUE'. """ fields_to_include = { 'abbreviation': self.abbreviation, 'conference': self.conference, 'conference_losses': self.conference_losses, 'conference_win_percentage': self.conference_win_percentage, 'conference_wins': self.conference_wins, 'first_downs': self.first_downs, 'opponents_first_downs': self.opponents_first_downs, 'first_downs_from_penalties': self.first_downs_from_penalties, 'opponents_first_downs_from_penalties': self.opponents_first_downs_from_penalties, 'fumbles_lost': self.fumbles_lost, 'opponents_fumbles_lost': self.opponents_fumbles_lost, 'games': self.games, 'interceptions': self.interceptions, 'opponents_interceptions': self.opponents_interceptions, 'losses': self.losses, 'name': self.name, 'pass_attempts': self.pass_attempts, 'opponents_pass_attempts': self.opponents_pass_attempts, 'pass_completion_percentage': self.pass_completion_percentage, 'opponents_pass_completion_percentage': self.opponents_pass_completion_percentage, 'pass_completions': self.pass_completions, 'opponents_pass_completions': self.opponents_pass_completions, 'pass_first_downs': self.pass_first_downs, 'opponents_pass_first_downs': self.opponents_pass_first_downs, 'pass_touchdowns': self.pass_touchdowns, 'opponents_pass_touchdowns': self.opponents_pass_touchdowns, 'pass_yards': self.pass_yards, 'opponents_pass_yards': self.opponents_pass_yards, 'penalties': self.penalties, 'opponents_penalties': self.opponents_penalties, 'plays': self.plays, 'opponents_plays': self.opponents_plays, 'points_against_per_game': self.points_against_per_game, 'points_per_game': self.points_per_game, 'rush_attempts': self.rush_attempts, 'opponents_rush_attempts': self.opponents_rush_attempts, 'rush_first_downs': self.rush_first_downs, 'opponents_rush_first_downs': self.opponents_rush_first_downs, 'rush_touchdowns': self.rush_touchdowns, 'opponents_rush_touchdowns': self.opponents_rush_touchdowns, 'rush_yards': self.rush_yards, 'opponents_rush_yards': self.opponents_rush_yards, 'rush_yards_per_attempt': self.rush_yards_per_attempt, 'opponents_rush_yards_per_attempt': self.opponents_rush_yards_per_attempt, 'simple_rating_system': self.simple_rating_system, 'strength_of_schedule': self.strength_of_schedule, 'turnovers': self.turnovers, 'opponents_turnovers': self.opponents_turnovers, 'win_percentage': self.win_percentage, 'wins': self.wins, 'yards': self.yards, 'opponents_yards': self.opponents_yards, 'yards_from_penalties': self.yards_from_penalties, 'opponents_yards_from_penalties': self.opponents_yards_from_penalties, 'yards_per_play': self.yards_per_play, 'opponents_yards_per_play': self.opponents_yards_per_play } return pd.DataFrame([fields_to_include], index=[self._abbreviation]) @property def conference(self): """ Returns a ``string`` of the team's conference abbreviation, such as 'big-12' for the Big 12 Conference. """ return self._team_conference @property def abbreviation(self): """ Returns a ``string`` of the team's short name, such as 'PURDUE' for the Purdue Boilermakers. """ return self._abbreviation @property def schedule(self): """ Returns an instance of the Schedule class containing the team's complete schedule for the season. """ return Schedule(self._abbreviation, self._year) @property def roster(self): """ Returns an instance of the Roster class containing all players for the team during the season with all career stats. """ return Roster(self._abbreviation, self._year) @property def name(self): """ Returns a ``string`` of the team's full name, such as 'Purdue Boilermakers'. """ return self._name @int_property_decorator def games(self): """ Returns an ``int`` of the total number of games the team has played during the season. """ return self._games @int_property_decorator def wins(self): """ Returns an ``int`` of the total number of games the team won during the season. """ return self._wins @int_property_decorator def losses(self): """ Returns an ``int`` of the total number of games the team lost during the season. """ return self._losses @float_property_decorator def win_percentage(self): """ Returns a ``float`` of the percentage of wins divided by the number of games played during the season. Percentage ranges from 0-1. """ return self._win_percentage @int_property_decorator def conference_wins(self): """ Returns an ``int`` of the total number of conference games the team won during the season. """ return self._conference_wins @int_property_decorator def conference_losses(self): """ Returns an ``int`` of the total number of conference games the team lost during the season. """ return self._conference_losses @float_property_decorator def conference_win_percentage(self): """ Returns a ``float`` of the percentage of conference wins divided by the number of conference games played during the season. Percentage ranges from 0-1. """ return self._conference_win_percentage @float_property_decorator def points_per_game(self): """ Returns a ``float`` of the average number of points scored by the team per game. """ return self._points_per_game @float_property_decorator def points_against_per_game(self): """ Returns a ``float`` of the average number of points conceded per game. """ return self._points_against_per_game @float_property_decorator def strength_of_schedule(self): """ Returns a ``float`` of the team's strength of schedule based on the number of points above or below average. An average difficulty schedule is denoted with 0.0 while a negative score indicates a comparatively easy schedule. """ return self._strength_of_schedule @float_property_decorator def simple_rating_system(self): """ Returns a ``float`` of the team's relative strength based on the average margin of victory and the strength of schedule. An average team is denoted with 0.0 while a negative score indicates a comparatively weak team. """ return self._simple_rating_system @float_property_decorator def pass_completions(self): """ Returns a ``float`` of the average number of completed passes per game. """ return self._pass_completions @float_property_decorator def opponents_pass_completions(self): """ Returns a ``float`` of the opponents' average number of completed passes per game. """ return self._opponents_pass_completions @float_property_decorator def pass_attempts(self): """ Returns a ``float`` of the average number of passes that are attempted per game. """ return self._pass_attempts @float_property_decorator def opponents_pass_attempts(self): """ Returns a ``float`` of the opponents' average number of passes that are attempted per game. """ return self._opponents_pass_attempts @float_property_decorator def pass_completion_percentage(self): """ Returns a ``float`` of the percentage of completed passes per game. Percentage ranges from 0-100. """ return self._pass_completion_percentage @float_property_decorator def opponents_pass_completion_percentage(self): """ Returns a ``float`` of the opponents' percentage of completed passes per game. Percentage ranges from 0-100. """ return self._opponents_pass_completion_percentage @float_property_decorator def pass_yards(self): """ Returns a ``float`` of the average number of yards gained from passing per game. """ return self._pass_yards @float_property_decorator def opponents_pass_yards(self): """ Returns a ``float`` of the opponents' average number of yards gained from passing per game. """ return self._opponents_pass_yards @float_property_decorator def interceptions(self): """ Returns a ``float`` of the average number of interceptions thrown per game. """ return self._interceptions @float_property_decorator def opponents_interceptions(self): """ Returns a ``float`` of the opponents' average number of interceptions thrown per game. """ return self._opponents_interceptions @float_property_decorator def pass_touchdowns(self): """ Returns a ``float`` of the average number of passing touchdowns scored per game. """ return self._pass_touchdowns @float_property_decorator def opponents_pass_touchdowns(self): """ Returns a ``float`` of the opponents' average number of passing touchdowns scored per game. """ return self._opponents_pass_touchdowns @float_property_decorator def rush_attempts(self): """ Returns a ``float`` of the average number of rushing plays per game. """ return self._rush_attempts @float_property_decorator def opponents_rush_attempts(self): """ Returns a ``float`` of the opponents' average number of rushing plays per game. """ return self._opponents_rush_attempts @float_property_decorator def rush_yards(self): """ Returns a ``float`` of the average number of yards gained from rushing per game. """ return self._rush_yards @float_property_decorator def opponents_rush_yards(self): """ Returns a ``float`` of the opponents' average number of yards gained from rushing per game. """ return self._opponents_rush_yards @float_property_decorator def rush_yards_per_attempt(self): """ Returns a ``float`` of the average number of yards gained per rushing attempt per game. """ return self._rush_yards_per_attempt @float_property_decorator def opponents_rush_yards_per_attempt(self): """ Returns a ``float`` of the opponents' average number of yards gained per rushing attempt per game. """ return self._opponents_rush_yards_per_attempt @float_property_decorator def rush_touchdowns(self): """ Returns a ``float`` of the average number of rushing touchdowns scored per game. """ return self._rush_touchdowns @float_property_decorator def opponents_rush_touchdowns(self): """ Returns a ``float`` of the opponents' average number of rushing touchdowns scored per game. """ return self._opponents_rush_touchdowns @float_property_decorator def plays(self): """ Returns a ``float`` of the average number of offensive plays per game. """ return self._plays @float_property_decorator def opponents_plays(self): """ Returns a ``float`` of the opponents' average number of offensive plays per game. """ return self._opponents_plays @float_property_decorator def yards(self): """ Returns a ``float`` of the average number of yards gained per game. """ return self._yards @float_property_decorator def opponents_yards(self): """ Returns a ``float`` of the opponents' average number of yards gained per game. """ return self._opponents_yards @float_property_decorator def turnovers(self): """ Returns a ``float`` of the average number of turnovers per game. """ return self._turnovers @float_property_decorator def opponents_turnovers(self): """ Returns a ``float`` of the opponents' average number of turnovers per game. """ return self._opponents_turnovers @float_property_decorator def fumbles_lost(self): """ Returns a ``float`` of the average number of fumbles per game. """ return self._fumbles_lost @float_property_decorator def opponents_fumbles_lost(self): """ Returns a ``float`` of the opponents' average number of fumbles per game. """ return self._opponents_fumbles_lost @float_property_decorator def yards_per_play(self): """ Returns a ``float`` of the average number of yards gained per play. """ return self._yards_per_play @float_property_decorator def opponents_yards_per_play(self): """ Returns a ``float`` of the opponents' average number of yards gained per play. """ return self._opponents_yards_per_play @float_property_decorator def pass_first_downs(self): """ Returns a ``float`` of the average number of first downs from passing plays per game. """ return self._pass_first_downs @float_property_decorator def opponents_pass_first_downs(self): """ Returns a ``float`` of the opponents' average number of first downs from passing plays per game. """ return self._opponents_pass_first_downs @float_property_decorator def rush_first_downs(self): """ Returns a ``float`` of the average number of first downs from rushing plays per game. """ return self._rush_first_downs @float_property_decorator def opponents_rush_first_downs(self): """ Returns a ``float`` of the opponents' average number of first downs from rushing plays per game. """ return self._opponents_rush_first_downs @float_property_decorator def first_downs_from_penalties(self): """ Returns a ``float`` of the average number of first downs from an opponent's penalties per game. """ return self._first_downs_from_penalties @float_property_decorator def opponents_first_downs_from_penalties(self): """ Returns a ``float`` of the opponents' average number of first downs from an opponent's penalties per game. """ return self._opponents_first_downs_from_penalties @float_property_decorator def first_downs(self): """ Returns a ``float`` of the total number of first downs achieved per game. """ return self._first_downs @float_property_decorator def opponents_first_downs(self): """ Returns a ``float`` of the opponents' total number of first downs achieved per game. """ return self._opponents_first_downs @float_property_decorator def penalties(self): """ Returns a ``float`` of the average number of penalties conceded per game. """ return self._penalties @float_property_decorator def opponents_penalties(self): """ Returns a ``float`` of the opponents' average number of penalties conceded per game. """ return self._opponents_penalties @float_property_decorator def yards_from_penalties(self): """ Returns a ``float`` of the average number of yards gained from an opponent's penalties per game. """ return self._yards_from_penalties @float_property_decorator def opponents_yards_from_penalties(self): """ Returns a ``float`` of the opponents' average number of yards gained from an opponent's penalties per game. """ return self._opponents_yards_from_penalties class Teams: """ A list of all NCAA Men's Football teams and their stats in a given year. Finds and retrieves a list of all NCAA Men's Football teams from www.sports-reference.com and creates a Team instance for every team that participated in the league in a given year. The Team class comprises a list of all major stats and a few identifiers for the requested season. Parameters ---------- year : string (optional) The requested year to pull stats from. """ def __init__(self, year=None): self._teams = [] self._conferences_dict = Conferences(year, True).team_conference team_data_dict, year = _retrieve_all_teams(year) self._instantiate_teams(team_data_dict, year) def __getitem__(self, abbreviation): """ Return a specified team. Returns a team's instance in the Teams class as specified by the team's short name. Parameters ---------- abbreviation : string An NCAAF team's short name (ie. 'PURDUE' for the Purdue Boilermakers). Returns ------- Team instance If the requested team can be found, its Team instance is returned. Raises ------ ValueError If the requested team is not present within the Teams list. """ for team in self._teams: if team.abbreviation.upper() == abbreviation.upper(): return team raise ValueError('Team abbreviation %s not found' % abbreviation) def __call__(self, abbreviation): """ Return a specified team. Returns a team's instance in the Teams class as specified by the team's abbreviation. This method is a wrapper for __getitem__. Parameters ---------- abbreviation : string An NCAAF team's short name (ie. 'PURDUE' for the Purdue Boilermakers). Returns ------- Team instance If the requested team can be found, its Team instance is returned. """ return self.__getitem__(abbreviation) def __str__(self): """ Return the string representation of the class. """ teams = [f'{team.name} ({team.abbreviation})'.strip() for team in self._teams] return '\n'.join(teams) def __repr__(self): """ Return the string representation of the class. """ return self.__str__() def __iter__(self): """Returns an iterator of all of the NCAAF teams for a given season.""" return iter(self._teams) def __len__(self): """Returns the number of NCAAF teams for a given season.""" return len(self._teams) def _instantiate_teams(self, team_data_dict, year): """ Create a Team instance for all teams. Once all team information has been pulled from the various webpages, create a Team instance for each team and append it to a larger list of team instances for later use. Parameters ---------- team_data_dict : dictionary A ``dictionary`` containing all stats information in HTML format as well as team rankings, indexed by team abbreviation. year : string A ``string`` of the requested year to pull stats from. """ if not team_data_dict: return for team_name, team_data in team_data_dict.items(): if team_name.lower() not in self._conferences_dict: conference = None else: conference = self._conferences_dict[team_name.lower()] team = Team(team_data=team_data['data'], team_conference=conference, year=year) self._teams.append(team) @property def dataframes(self): """ Returns a pandas DataFrame where each row is a representation of the Team class. Rows are indexed by the team abbreviation. """ frames = [] for team in self.__iter__(): frames.append(team.dataframe) return pd.concat(frames)
{ "pile_set_name": "Github" }
;(function(exports) { if (exports.F2 && !exports.F2_TESTING_MODE) { return; }
{ "pile_set_name": "Github" }
.class public Landroid/support/v7/widget/LinearLayoutManager$SavedState; .super Ljava/lang/Object; # interfaces .implements Landroid/os/Parcelable; # annotations .annotation build Landroid/support/annotation/RestrictTo; value = { .enum Landroid/support/annotation/RestrictTo$Scope;->LIBRARY_GROUP:Landroid/support/annotation/RestrictTo$Scope; } .end annotation # static fields .field public static final CREATOR:Landroid/os/Parcelable$Creator; .annotation system Ldalvik/annotation/Signature; value = { "Landroid/os/Parcelable$Creator", "<", "Landroid/support/v7/widget/LinearLayoutManager$SavedState;", ">;" } .end annotation .end field # instance fields .field mAnchorLayoutFromEnd:Z .field mAnchorOffset:I .field mAnchorPosition:I # direct methods .method static constructor <clinit>()V .locals 1 new-instance v0, Landroid/support/v7/widget/LinearLayoutManager$SavedState$1; invoke-direct {v0}, Landroid/support/v7/widget/LinearLayoutManager$SavedState$1;-><init>()V sput-object v0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->CREATOR:Landroid/os/Parcelable$Creator; return-void .end method .method public constructor <init>()V .locals 0 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method .method constructor <init>(Landroid/os/Parcel;)V .locals 2 const/4 v0, 0x1 invoke-direct {p0}, Ljava/lang/Object;-><init>()V invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I move-result v1 iput v1, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorPosition:I invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I move-result v1 iput v1, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorOffset:I invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I move-result v1 if-ne v1, v0, :cond_0 :goto_0 iput-boolean v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorLayoutFromEnd:Z return-void :cond_0 const/4 v0, 0x0 goto :goto_0 .end method .method public constructor <init>(Landroid/support/v7/widget/LinearLayoutManager$SavedState;)V .locals 1 invoke-direct {p0}, Ljava/lang/Object;-><init>()V iget v0, p1, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorPosition:I iput v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorPosition:I iget v0, p1, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorOffset:I iput v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorOffset:I iget-boolean v0, p1, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorLayoutFromEnd:Z iput-boolean v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorLayoutFromEnd:Z return-void .end method # virtual methods .method public describeContents()I .locals 1 const/4 v0, 0x0 return v0 .end method .method hasValidAnchor()Z .locals 1 iget v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorPosition:I if-ltz v0, :cond_0 const/4 v0, 0x1 :goto_0 return v0 :cond_0 const/4 v0, 0x0 goto :goto_0 .end method .method invalidateAnchor()V .locals 1 const/4 v0, -0x1 iput v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorPosition:I return-void .end method .method public writeToParcel(Landroid/os/Parcel;I)V .locals 1 iget v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorPosition:I invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V iget v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorOffset:I invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V iget-boolean v0, p0, Landroid/support/v7/widget/LinearLayoutManager$SavedState;->mAnchorLayoutFromEnd:Z if-eqz v0, :cond_0 const/4 v0, 0x1 :goto_0 invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V return-void :cond_0 const/4 v0, 0x0 goto :goto_0 .end method
{ "pile_set_name": "Github" }