text
stringlengths
2
97.5k
meta
dict
<component name="libraryTable"> <library name="Maven: org.springframework.boot:spring-boot-starter-logging:1.5.3.RELEASE"> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/org/springframework/boot/spring-boot-starter-logging/1.5.3.RELEASE/spring-boot-starter-logging-1.5.3.RELEASE.jar!/" /> </CLASSES> <JAVADOC> <root url="jar://$MAVEN_REPOSITORY$/org/springframework/boot/spring-boot-starter-logging/1.5.3.RELEASE/spring-boot-starter-logging-1.5.3.RELEASE-javadoc.jar!/" /> </JAVADOC> <SOURCES> <root url="jar://$MAVEN_REPOSITORY$/org/springframework/boot/spring-boot-starter-logging/1.5.3.RELEASE/spring-boot-starter-logging-1.5.3.RELEASE-sources.jar!/" /> </SOURCES> </library> </component>
{ "pile_set_name": "Github" }
define({ name: "cPrime" });
{ "pile_set_name": "Github" }
using Xunit; using LanguageExt; using LanguageExt.Common; using static LanguageExt.Prelude; namespace LanguageExt.Tests.Transformer.Traverse.EitherT.Sync { public class OptionUnsafeEither { [Fact] public void NoneLeftIsRightNone() { var ma = OptionUnsafe<Either<Error, int>>.None; var mb = ma.Sequence(); var mc = Right<Error, OptionUnsafe<int>>(None); var mr = mb == mc; Assert.True(mr); } [Fact] public void SomeLeftIsLeft() { var ma = SomeUnsafe<Either<Error, int>>(Left(Error.New("alt"))); var mb = ma.Sequence(); var mc = Left<Error, OptionUnsafe<int>>(Error.New("alt")); var mr = mb == mc; Assert.True(mr); } [Fact] public void SomeRightIsRight() { var ma = SomeUnsafe<Either<Error, int>>(Right(1234)); var mb = ma.Sequence(); var mc = Right<Error, OptionUnsafe<int>>(SomeUnsafe(1234)); var mr = mb == mc; Assert.True(mr); } } }
{ "pile_set_name": "Github" }
/** * *************************************************************************** * Copyright (c) 2014-2019, TigerGraph Inc. * All rights reserved * Unauthorized copying of this file, via any medium is * strictly prohibited * Proprietary and confidential * Author: Mingxi Wu * **************************************************************************** */ package com.tigergraph.v2_5_0.common; import java.util.List; import java.util.ArrayList; /** * Options for syntax version setting at global or query level. * <p> * Currently, the default sytnax version is v1. */ public enum SyntaxVersion { /** * syntax up until v2.3, where <code>-(E)-</code> is equivalent * to <code>-(E)-></code> */ V1("v1"), /** syntax after v2.4, i.e. pattern match syntax */ V2("v2"), /** * syntax after v2.4 that shows transformed query in GSQL log, * internal use only */ _V2("_v2"), /** unknown syntax version used for error reporting */ UNKNOWN("unknown"); private String version; // Note: In 3.0, we should change below to V2. /** Default syntax version in 2.4 is V1 */ static public SyntaxVersion defaultVersion = V1; private SyntaxVersion(String version) { this.version = version; } public String getVersion() { return version; } /** * Returns the <code>SyntaxVersion</code> object corresponding to the * given version string. * <p> * Accepted inputs are "v1", "v2", "V1", "V2", "_v2", "_V2" to allow * for case-insensitive setting. * * @param version the version string provided by user * @return corresponding <code>SyntaxVersion</code> object for valid input * or <code>SyntaxVersion.UNKNOWN<code> for invalid input */ public static SyntaxVersion getInstance(String version) { for (SyntaxVersion obj: SyntaxVersion.values()) { // check for each valid input and return the corresponding object if match if (obj.version.equalsIgnoreCase(version)) { return obj; } } // return unknown syntax version for invalid input return SyntaxVersion.UNKNOWN; } /** * Resets default sytnax version to the one corresponding to the provided * version string. * * @param version the version string provided by user * @return true if user input is valid and false otherwise */ public static boolean setDefaultSyntaxVersion(String version) { defaultVersion = getInstance(version); return defaultVersion != UNKNOWN; } /** Returns the default syntax version in current session. */ public static SyntaxVersion defaultSyntax() { return defaultVersion; } /** Returns the version string of the current default syntax version */ public static String defaultVersion() { return defaultSyntax().getVersion(); } /** * Checks whether a version string is valid or not. * @param version the user-provided version string to check * @return true if the user input is valid and false otherwise */ public static boolean isValidVersion(String version) { return getInstance(version) != SyntaxVersion.UNKNOWN; } /** Returns a list of supported syntax version string */ public static List<String> supportVersions() { List<String> vNames = new ArrayList<>(); // filter out invalid string in SyntaxVersion.values() (e.g. "unknown") // also filter out version string for internal usage (e.g. "_v2") for (SyntaxVersion obj: SyntaxVersion.values()) { if (isValidVersion(obj.version) && obj != SyntaxVersion._V2) { vNames.add(obj.version); } } return vNames; } /** Returns a string representation of all supported syntax version string */ public static String allSupportVersions() { List<String> vNames = supportVersions(); // will return [v1,v2] String res = "[" + String.join(",", vNames) + "]"; return res; } /** Returns the syntax version string */ public String toString(){ return version; } }
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace Symplify\CodingStandard\CognitiveComplexity\Rules; use PhpParser\Node; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\Trait_; use PHPStan\Analyser\Scope; use Symplify\CodingStandard\CognitiveComplexity\AstCognitiveComplexityAnalyzer; use Symplify\CodingStandard\Rules\AbstractManyNodeTypeRule; /** * @see \Symplify\CodingStandard\CognitiveComplexity\Tests\Rules\ClassLikeCognitiveComplexityRule\ClassLikeCognitiveComplexityRuleTest */ final class ClassLikeCognitiveComplexityRule extends AbstractManyNodeTypeRule { /** * @var string */ public const ERROR_MESSAGE = '%s cognitive complexity for "%s" is %d, keep it under %d'; /** * @var int */ private $maxClassCognitiveComplexity; /** * @var AstCognitiveComplexityAnalyzer */ private $astCognitiveComplexityAnalyzer; public function __construct( AstCognitiveComplexityAnalyzer $astCognitiveComplexityAnalyzer, int $maxClassCognitiveComplexity = 50 ) { $this->maxClassCognitiveComplexity = $maxClassCognitiveComplexity; $this->astCognitiveComplexityAnalyzer = $astCognitiveComplexityAnalyzer; } /** * @return string[] */ public function getNodeTypes(): array { return [Class_::class, Trait_::class]; } /** * @param Class_|Trait_ $node * @return string[] */ public function process(Node $node, Scope $scope): array { $classLikeCognitiveComplexity = 0; foreach ($node->getMethods() as $classMethod) { $classLikeCognitiveComplexity += $this->astCognitiveComplexityAnalyzer->analyzeFunctionLike($classMethod); } if ($classLikeCognitiveComplexity <= $this->maxClassCognitiveComplexity) { return []; } $classLikeName = (string) $node->name; $type = $node instanceof Class_ ? 'Class' : 'Trait'; $message = sprintf( self::ERROR_MESSAGE, $type, $classLikeName, $classLikeCognitiveComplexity, $this->maxClassCognitiveComplexity ); return [$message]; } }
{ "pile_set_name": "Github" }
/** ****************************************************************************** * @file startup_stm32f042.s * @author MCD Application Team * @version V1.3.2 * @date 27-March-2014 * @brief STM32F042 Devices vector table for Atollic toolchain. * This module performs: * - Set the initial SP * - Set the initial PC == Reset_Handler, * - Set the vector table entries with the exceptions ISR address * - Configure the system clock * - Branches to main in the C library (which eventually * calls main()). * After Reset the Cortex-M0 processor is in Thread mode, * priority is Privileged, and the Stack is set to Main. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ .syntax unified .cpu cortex-m0 .fpu softvfp .thumb .global g_pfnVectors .global Default_Handler /* start address for the initialization values of the .data section. defined in linker script */ .word _sidata /* start address for the .data section. defined in linker script */ .word _sdata /* end address for the .data section. defined in linker script */ .word _edata /* start address for the .bss section. defined in linker script */ .word _sbss /* end address for the .bss section. defined in linker script */ .word _ebss .equ BootRAM, 0xF108F85F /** * @brief This is the code that gets called when the processor first * starts execution following a reset event. Only the absolutely * necessary set is performed, after which the application * supplied main() routine is called. * @param None * @retval : None */ .section .text.Reset_Handler .weak Reset_Handler .type Reset_Handler, %function Reset_Handler: ldr r0, =_estack mov sp, r0 /* set stack pointer */ /*Check if boot space corresponds to test memory*/ LDR R0,=0x00000004 LDR R1, [R0] LSRS R1, R1, #24 LDR R2,=0x1F CMP R1, R2 BNE ApplicationStart /*SYSCFG clock enable*/ LDR R0,=0x40021018 LDR R1,=0x00000001 STR R1, [R0] /*Set CFGR1 register with flash memory remap at address 0*/ LDR R0,=0x40010000 LDR R1,=0x00000000 STR R1, [R0] ApplicationStart: /* Copy the data segment initializers from flash to SRAM */ movs r1, #0 b LoopCopyDataInit CopyDataInit: ldr r3, =_sidata ldr r3, [r3, r1] str r3, [r0, r1] adds r1, r1, #4 LoopCopyDataInit: ldr r0, =_sdata ldr r3, =_edata adds r2, r0, r1 cmp r2, r3 bcc CopyDataInit ldr r2, =_sbss b LoopFillZerobss /* Zero fill the bss segment. */ FillZerobss: movs r3, #0 str r3, [r2] adds r2, r2, #4 LoopFillZerobss: ldr r3, = _ebss cmp r2, r3 bcc FillZerobss /* Call the clock system intitialization function.*/ bl SystemInit /* Call static constructors */ bl __libc_init_array /* Call the application's entry point.*/ bl main LoopForever: b LoopForever .size Reset_Handler, .-Reset_Handler /** * @brief This is the code that gets called when the processor receives an * unexpected interrupt. This simply enters an infinite loop, preserving * the system state for examination by a debugger. * * @param None * @retval : None */ .section .text.Default_Handler,"ax",%progbits Default_Handler: Infinite_Loop: b Infinite_Loop .size Default_Handler, .-Default_Handler /****************************************************************************** * * The minimal vector table for a Cortex M0. Note that the proper constructs * must be placed on this to ensure that it ends up at physical address * 0x0000.0000. * ******************************************************************************/ .section .isr_vector,"a",%progbits .type g_pfnVectors, %object .size g_pfnVectors, .-g_pfnVectors g_pfnVectors: .word _estack .word Reset_Handler .word NMI_Handler .word HardFault_Handler .word 0 .word 0 .word 0 .word 0 .word 0 .word 0 .word 0 .word SVC_Handler .word 0 .word 0 .word PendSV_Handler .word SysTick_Handler .word WWDG_IRQHandler .word PVD_VDDIO2_IRQHandler .word RTC_IRQHandler .word FLASH_IRQHandler .word RCC_CRS_IRQHandler .word EXTI0_1_IRQHandler .word EXTI2_3_IRQHandler .word EXTI4_15_IRQHandler .word TSC_IRQHandler .word DMA1_Channel1_IRQHandler .word DMA1_Channel2_3_IRQHandler .word DMA1_Channel4_5_IRQHandler .word ADC1_IRQHandler .word TIM1_BRK_UP_TRG_COM_IRQHandler .word TIM1_CC_IRQHandler .word TIM2_IRQHandler .word TIM3_IRQHandler .word 0 .word 0 .word TIM14_IRQHandler .word 0 .word TIM16_IRQHandler .word TIM17_IRQHandler .word I2C1_IRQHandler .word 0 .word SPI1_IRQHandler .word SPI2_IRQHandler .word USART1_IRQHandler .word USART2_IRQHandler .word 0 .word CEC_CAN_IRQHandler .word USB_IRQHandler .word BootRAM /* @0x108. This is for boot in RAM mode for STM32F0xx devices. */ /******************************************************************************* * * Provide weak aliases for each Exception handler to the Default_Handler. * As they are weak aliases, any function with the same name will override * this definition. * *******************************************************************************/ .weak NMI_Handler .thumb_set NMI_Handler,Default_Handler .weak HardFault_Handler .thumb_set HardFault_Handler,Default_Handler .weak SVC_Handler .thumb_set SVC_Handler,Default_Handler .weak PendSV_Handler .thumb_set PendSV_Handler,Default_Handler /* * The weak SysTick_Handler symbol is in the stm32plus MillisecondTimer class * .weak SysTick_Handler .thumb_set SysTick_Handler,Default_Handler */ .weak WWDG_IRQHandler .thumb_set WWDG_IRQHandler,Default_Handler .weak PVD_VDDIO2_IRQHandler .thumb_set PVD_VDDIO2_IRQHandler,Default_Handler .weak RTC_IRQHandler .thumb_set RTC_IRQHandler,Default_Handler .weak FLASH_IRQHandler .thumb_set FLASH_IRQHandler,Default_Handler .weak RCC_CRS_IRQHandler .thumb_set RCC_CRS_IRQHandler,Default_Handler .weak EXTI0_1_IRQHandler .thumb_set EXTI0_1_IRQHandler,Default_Handler .weak EXTI2_3_IRQHandler .thumb_set EXTI2_3_IRQHandler,Default_Handler .weak EXTI4_15_IRQHandler .thumb_set EXTI4_15_IRQHandler,Default_Handler .weak TSC_IRQHandler .thumb_set TSC_IRQHandler,Default_Handler .weak DMA1_Channel1_IRQHandler .thumb_set DMA1_Channel1_IRQHandler,Default_Handler .weak DMA1_Channel2_3_IRQHandler .thumb_set DMA1_Channel2_3_IRQHandler,Default_Handler .weak DMA1_Channel4_5_IRQHandler .thumb_set DMA1_Channel4_5_IRQHandler,Default_Handler .weak ADC1_IRQHandler .thumb_set ADC1_IRQHandler,Default_Handler .weak TIM1_BRK_UP_TRG_COM_IRQHandler .thumb_set TIM1_BRK_UP_TRG_COM_IRQHandler,Default_Handler .weak TIM1_CC_IRQHandler .thumb_set TIM1_CC_IRQHandler,Default_Handler .weak TIM2_IRQHandler .thumb_set TIM2_IRQHandler,Default_Handler .weak TIM3_IRQHandler .thumb_set TIM3_IRQHandler,Default_Handler .weak TIM14_IRQHandler .thumb_set TIM14_IRQHandler,Default_Handler .weak TIM16_IRQHandler .thumb_set TIM16_IRQHandler,Default_Handler .weak TIM17_IRQHandler .thumb_set TIM17_IRQHandler,Default_Handler .weak I2C1_IRQHandler .thumb_set I2C1_IRQHandler,Default_Handler .weak SPI1_IRQHandler .thumb_set SPI1_IRQHandler,Default_Handler .weak SPI2_IRQHandler .thumb_set SPI2_IRQHandler,Default_Handler .weak USART1_IRQHandler .thumb_set USART1_IRQHandler,Default_Handler .weak USART2_IRQHandler .thumb_set USART2_IRQHandler,Default_Handler .weak CEC_CAN_IRQHandler .thumb_set CEC_CAN_IRQHandler,Default_Handler .weak USB_IRQHandler .thumb_set USB_IRQHandler,Default_Handler /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "pile_set_name": "Github" }
/*++ Copyright (c) 2015 Microsoft Corporation --*/ #include "ast/ast_pp.h" #include "ast/arith_decl_plugin.h" #include "ast/reg_decl_plugins.h" #include "muz/fp/datalog_parser.h" #include "muz/base/dl_context.h" #include "smt/params/smt_params.h" #include "muz/fp/dl_register_engine.h" using namespace datalog; void tst_dl_context() { return; #if 0 symbol relations[] = { symbol("tr_skip"), symbol("tr_sparse"), symbol("tr_hashtable"), symbol("smt_relation2") }; const unsigned rel_cnt = sizeof(relations)/sizeof(symbol); const char * test_file = "c:\\tvm\\src\\benchmarks\\datalog\\t0.datalog"; params_ref params; for(unsigned rel_index=0; rel_index<rel_cnt; rel_index++) { params.set_sym("default_relation", relations[rel_index]); for(int eager_checking=1; eager_checking>=0; eager_checking--) { params.set_bool("eager_emptiness_checking", eager_checking!=0); std::cerr << "Testing " << relations[rel_index] << "\n"; std::cerr << "Eager emptiness checking " << (eager_checking!=0 ? "on" : "off") << "\n"; dl_context_simple_query_test(params); dl_context_saturate_file(params, test_file); } } #endif } #if 0 static lbool dl_context_eval_unary_predicate(ast_manager & m, context & ctx, char const* problem_text, const char * pred_name) { parser* p = parser::create(ctx,m); TRUSTME( p->parse_string(problem_text) ); dealloc(p); func_decl * pred = ctx.try_get_predicate_decl(symbol(pred_name)); ENSURE(pred); ENSURE(pred->get_arity()==1); app_ref query_app(m.mk_app(pred, m.mk_var(0, pred->get_domain()[0])), m); lbool status = ctx.query(query_app); ENSURE(status != l_undef); return status; } static void dl_context_simple_query_test(params_ref & params) { ast_manager m; reg_decl_plugins(m); dl_decl_util decl_util(m); register_engine re; smt_params fparams; context ctx(m, re, fparams); ctx.updt_params(params); /* lbool status = */ dl_context_eval_unary_predicate(m, ctx, "Z 64\n\nP(x:Z)\nP(\"a\").", "P"); #if 0 // TBD: //zero corresponds to the first constant the datalog parser encountered, in our case "a" app_ref c_0(decl_util.mk_constant(0, res1->get_signature()[0]), m); app_ref c_1(decl_util.mk_constant(1, res1->get_signature()[0]), m); relation_fact f(m); f.push_back(c_0); ENSURE(res1->contains_fact(f)); f[0]=c_1; ENSURE(!res1->contains_fact(f)); #endif } void dl_context_saturate_file(params_ref & params, const char * f) { ast_manager m; dl_decl_util decl_util(m); smt_params fparams; register_engine re; context ctx(m, re, fparams); ctx.updt_params(params); datalog::parser * parser = datalog::parser::create(ctx, m); if (!parser || !parser->parse_file(f)) { warning_msg("ERROR: failed to parse file"); dealloc(parser); return; } dealloc(parser); std::cerr << "Saturating...\n"; ctx.get_rel_context()->saturate(); std::cerr << "Done\n"; } #endif
{ "pile_set_name": "Github" }
# elli - Erlang web server for HTTP APIs [![Hex.pm][hex badge]][hex package] [![Documentation][doc badge]][docs] [![Erlang][erlang badge]][erlang downloads] [![Travis CI][travis badge]][travis builds] [![Coverage Status][coveralls badge]][coveralls link] [![MIT License][license badge]](LICENSE) [travis builds]: https://travis-ci.org/elli-lib/elli [travis badge]: https://travis-ci.org/elli-lib/elli.svg [hex badge]: https://img.shields.io/hexpm/v/elli.svg [hex package]: https://hex.pm/packages/elli [latest release]: https://github.com/elli-lib/elli/releases/latest [erlang badge]: https://img.shields.io/badge/erlang-%E2%89%A518.0-red.svg [erlang downloads]: http://www.erlang.org/downloads [doc badge]: https://img.shields.io/badge/docs-edown-green.svg [docs]: doc/README.md [coveralls badge]: https://coveralls.io/repos/github/elli-lib/elli/badge.svg?branch=develop [coveralls link]: https://coveralls.io/github/elli-lib/elli?branch=develop [license badge]: https://img.shields.io/badge/license-MIT-blue.svg Elli is a webserver you can run inside your Erlang application to expose an HTTP API. Elli is a aimed exclusively at building high-throughput, low-latency HTTP APIs. If robustness and performance is more important than general purpose features, then `elli` might be for you. If you find yourself digging into the implementation of a webserver, `elli` might be for you. If you're building web services, not web sites, then `elli` might be for you. Elli is used in production at Wooga and Game Analytics. Elli requires OTP 18.0 or newer. ## Installation To use `elli` you will need a working installation of Erlang 18.0 (or later). Add `elli` to your application by adding it as a dependency to your [`rebar.config`](http://www.rebar3.org/docs/configuration): ```erlang {deps, [elli]}. ``` Afterwards you can run: ```sh $ rebar3 compile ``` ## Usage ```sh $ rebar3 shell ``` ```erlang %% starting elli 1> {ok, Pid} = elli:start_link([{callback, elli_example_callback}, {port, 3000}]). ``` ## Examples ### Callback Module The best source to learn how to write a callback module is [src/elli_example_callback.erl](src/elli_example_callback.erl) and its [generated documentation](doc/elli_example_callback.md). There are a bunch of examples used in the tests as well as descriptions of all the events. A minimal callback module could look like this: ```erlang -module(elli_minimal_callback). -export([handle/2, handle_event/3]). -include_lib("elli/include/elli.hrl"). -behaviour(elli_handler). handle(Req, _Args) -> %% Delegate to our handler function handle(Req#req.method, elli_request:path(Req), Req). handle('GET',[<<"hello">>, <<"world">>], _Req) -> %% Reply with a normal response. `ok' can be used instead of `200' %% to signal success. {ok, [], <<"Hello World!">>}; handle(_, _, _Req) -> {404, [], <<"Not Found">>}. %% @doc Handle request events, like request completed, exception %% thrown, client timeout, etc. Must return `ok'. handle_event(_Event, _Data, _Args) -> ok. ``` ### Supervisor Childspec To add `elli` to a supervisor you can use the following example and adapt it to your needs. ```erlang -module(fancyapi_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> ElliOpts = [{callback, fancyapi_callback}, {port, 3000}], ElliSpec = { fancy_http, {elli, start_link, [ElliOpts]}, permanent, 5000, worker, [elli]}, {ok, { {one_for_one, 5, 10}, [ElliSpec]} }. ``` ## Features Here's the features Elli _does_ have: * [Rack][]-style request-response. Your handler function gets a complete request and returns a complete response. There's no messaging, no receiving data directly from the socket, no writing responses directly to the socket. It's a very simple and straightforward API. Have a look at [`elli_example_callback`](elli_example_callback.md) for examples. * Middlewares allow you to add useful features like compression, encoding, stats, but only have it used when needed. No features you don't use on the critical path. * Short-circuiting of responses using exceptions, allows you to use "assertions" that return for example 403 permission denied. `is_allowed(Req) orelse throw({403, [], <<"Permission denied">>})`. * Every client connection gets its own process, isolating the failure of a request from another. For the duration of the connection, only one process is involved, resulting in very robust and efficient code. * Binaries everywhere for strings. * Instrumentation inside the core of the webserver, triggering user callbacks. For example when a request completes, the user callback gets the `request_complete` event which contains timings of all the different parts of handling a request. There's also events for clients unexpectedly closing a connection, crashes in the user callback, etc. * Keep alive, using one Erlang process per connection only active when there is a request from the client. Number of connections is only limited by RAM and CPU. * Chunked transfer in responses for real-time push to clients * Basic pipelining. HTTP verbs that does not have side-effects(`GET` and `HEAD`) can be pipelined, ie. a client supporting pipelining can send multiple requests down the line and expect the responses to appear in the same order as requests. Elli processes the requests one at a time in order, future work could make it possible to process them in parallel. * SSL using built-in Erlang/OTP ssl, nice for low volume admin interfaces, etc. For high volume, you should probably go with nginx, stunnel or ELB if you're on AWS. * Implement your own connection handling, for WebSockets, streaming uploads, etc. See [`elli_example_callback_handover`](elli_example_callback_handover.md). ## Extensions * [elli_access_log](https://github.com/elli-lib/elli_access_log): Access log * [elli_basicauth](https://github.com/elli-lib/elli_basicauth): Basic auth * [elli_chatterbox](https://github.com/elli-lib/elli_chatterbox): HTTP/2 support * [elli_cloudfront](https://github.com/elli-lib/elli_cloudfront): CloudFront signed URLs * [elli_cookie](https://github.com/elli-lib/elli_cookie): Cookies * [elli_date](https://github.com/elli-lib/elli_date): "Date" header * [elli_fileserve](https://github.com/elli-lib/elli_fileserve): Static content * [elli_prometheus](https://github.com/elli-lib/elli_prometheus): Prometheus * [elli_stats](https://github.com/elli-lib/elli_stats): Real-time statistics dashboard * [elli_websockets](https://github.com/elli-lib/elli_websocket): WebSockets * [elli_xpblfe](https://github.com/elli-lib/elli_xpblfe): X-Powered-By LFE ## About From operating and debugging high-volume, low-latency apps we have gained some valuable insight into what we want from a webserver. We want simplicity, robustness, performance, ease of debugging, visibility into strange client behaviour, really good instrumentation and good tests. We are willing to sacrifice almost everything, even basic features to achieve this. With this in mind we looked at the big names in the Erlang community: [Yaws][], [Mochiweb][], [Misultin][] and [Cowboy][]. We found [Mochiweb][] to be the best match. However, we also wanted to see if we could take the architecture of [Mochiweb][] and improve on it. `elli` takes the acceptor-turns-into-request-handler idea found in [Mochiweb][], the binaries-only idea from [Cowboy][] and the request-response idea from [WSGI][]/[Rack][] (with chunked transfer being an exception). On top of this we built a handler that allows us to write HTTP middleware modules to add practical features, like compression of responses, HTTP access log with timings, a real-time statistics dashboard and chaining multiple request handlers. ## Aren't there enough webservers in the Erlang community already? There are a few very mature and robust projects with steady development, one recently ceased development and one new kid on the block with lots of interest. As `elli` is not a general purpose webserver, but more of a specialized tool, we believe it has a very different target audience and would not attract effort or users away from the big names. ## Why another webserver? Isn't this just the NIH syndrome? [Yaws][], [Mochiweb][], [Misultin][], and [Cowboy][] are great projects, hardened over time and full of very useful features for web development. If you value developer productivity, [Yaws][] is an excellent choice. If you want a fast and lightweight server, [Mochiweb][] and [Cowboy][] are excellent choices. Having used and studied all of these projects, we believed that if we merged some of the existing ideas and added some ideas from other communities, we could create a core that was better for our use cases. It started out as an experiment to see if it is at all possible to significantly improve and it turns out that for our particular use cases, there is enough improvement to warrant a new project. ## What makes Elli different? Elli has a very simple architecture. It avoids using more processes and messages than absolutely necessary. It uses binaries for strings. The request-response programming model allows middlewares to do much heavy lifting, so the core can stay very simple. It has been instrumented so as a user you can understand where time is spent. When things go wrong, like the client closed the connection before you could send a response, you are notified about these things so you can better understand your client behaviour. ## Performance "Hello World!" micro-benchmarks are really useful when measuring the performance of the webserver itself, but the numbers usually do more harm than good when released. I encourage you to run your own benchmarks, on your own hardware. Mark Nottingham has some [very good pointers](http://www.mnot.net/blog/2011/05/18/http_benchmark_rules) about benchmarking HTTP servers. [Yaws]: https://github.com/klacke/yaws [Mochiweb]: https://github.com/mochi/mochiweb [Misultin]: https://github.com/ostinelli/misultin [Cowboy]: https://github.com/ninenines/cowboy [WSGI]: https://www.python.org/dev/peps/pep-3333/ [Rack]: https://github.com/rack/rack ## Modules ## <table width="100%" border="0" summary="list of modules"> <tr><td><a href="elli.md" class="module">elli</a></td></tr> <tr><td><a href="elli_example_callback.md" class="module">elli_example_callback</a></td></tr> <tr><td><a href="elli_example_callback_handover.md" class="module">elli_example_callback_handover</a></td></tr> <tr><td><a href="elli_handler.md" class="module">elli_handler</a></td></tr> <tr><td><a href="elli_http.md" class="module">elli_http</a></td></tr> <tr><td><a href="elli_middleware.md" class="module">elli_middleware</a></td></tr> <tr><td><a href="elli_middleware_compress.md" class="module">elli_middleware_compress</a></td></tr> <tr><td><a href="elli_request.md" class="module">elli_request</a></td></tr> <tr><td><a href="elli_sendfile.md" class="module">elli_sendfile</a></td></tr> <tr><td><a href="elli_tcp.md" class="module">elli_tcp</a></td></tr> <tr><td><a href="elli_test.md" class="module">elli_test</a></td></tr> <tr><td><a href="elli_util.md" class="module">elli_util</a></td></tr></table> ## License Elli is licensed under [The MIT License](LICENSE). Copyright (c) 2012-2016 Knut Nesheim, 2016-2018 elli-lib team
{ "pile_set_name": "Github" }
<?php /*// HRCLOUD2-PLUGIN-START App Name: Pell for HRC2 App Version: v3.4 (7-7-2018 00:00) App License: GPLv3 App Author: jaredreich & zelon88 App Description: A simple HRCloud2 document writer. App Integration: 0 (False) App Permission: 1 (Everyone) HRCLOUD2-PLUGIN-END //*/ // / The following code loads required HRCloud2 corefiles and resources. $noStyles = 1; if (!file_exists('../../sanitizeCore.php')) { echo nl2br('</head><body>ERROR!!! HRC2PellApp33, Cannot process the HRCloud2 Sanitization Core file (sanitizeCore.php)!'."\n".'</body></html>'); die (); } else { require_once ('../../sanitizeCore.php'); } if (!file_exists('../../securityCore.php')) { echo nl2br('ERROR!!! HRC2PellApp47, Cannot process the HRCloud2 Security Core file (securityCore.php).'."\n"); die (); } else { require ('../../securityCore.php'); } if (!file_exists('../../commonCore.php')) { echo nl2br('ERROR!!! HRC2PellApp35, Cannot process the HRCloud2 Common Core file (commonCore.php).'."\n"); die (); } else { require_once ('../../commonCore.php'); } if (!file_exists('../../Applications/Pell/dist/PellHRC2Lib.php')) { echo nl2br('ERROR!!! HRC2PellApp35, Cannot process the HRC2 library for Pell file (PellHRC2Lib.php).'."\n"); die (); } else { require ('../../Applications/Pell/dist/PellHRC2Lib.php'); } ?> <!DOCTYPE html> <html> <head> <meta name="viewport" content="user-scalable=1.0,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0"> <title>Pell for HRC2</title> <link rel="stylesheet" type="text/css" href="dist/pell.css"> <style> body { margin: 0; padding: 0; } .content { box-sizing: border-box; margin: 0 auto; max-width: 600px; padding: 20px; } #html-output { white-space: pre-wrap; } </style> </head> <body> <a id="header" name="header" align="center"><h1>Pell Editor for HRC2</h1></a> <hr /> <div id="hrc2Toolbar" name="hrc2Toolbar" style="float:left;"> <a href="Pell.php"><img src="resources\new.png" title="New File" alt="New File" onclick="toggle_visibility('loading');"></a> <img src="resources/save.png" title="Save File" alt="Save File" onclick="toggle_visibility('saveOptions');"> <img src="resources/load.png" title="Open File" alt="Open File" onclick="toggle_visibility('openOptions');"> </div> <div align="center"><h3><?php if ($_GET['saved'] ==1) echo 'Saved '; echo ($fileEcho1); ?></h3></div> <img id="loading" name="loading" src="resources/loading.gif" style="display:none;"> <br> <div id="saveOptions" name="saveOptions" align="center" style="display:none;"> <form action="Pell.php" id="saveForm" name="saveForm" method="post" enctype="multipart/form-data"> <a style="float:left;">Save File: </a> <br> Filename: <input type="text" name="filename" id="filename" value="<?php echo $fileEcho; ?>"> | Extension: <select name="extension" id="extension"> <option value="txt">Txt</option> <option value="doc">Doc</option> <option value="docx">Docx</option> <option value="rtf">Rtf</option> <option value="odt">Odt</option> </select> <input type="hidden" name="htmlOutput" id="htmlOutput" value=""> <input type="hidden" name="fileOutput" id="fileOutput" value=""> <br> <button href="#" onclick="setValue();">Save</button> </form> </div> <div id="openOptions" name="openOptions" align="center" style="display:none;"> <a style="float:left;">Open File: </a> <br> <form action="Pell.php" id="deleteForm" name="deleteForm" method="post" enctype="multipart/form-data"> <table id="openFiles" name="openFiles" class="sortable"> <tr> <th>Filename</th> <th>Delete</th> <th>Last Modified</th> </tr> <?php // / The following code builds the table of files from the CloudUsrDir. foreach ($pellFiles as $file) { if (in_array($file, $pellDangerArr)) continue; $fileExtension = pathinfo($CloudUsrDir.$file, PATHINFO_EXTENSION); if (!in_array($fileExtension, $pellDocArray)) continue; if (!file_exists($CloudUsrDir.$file)) continue; $lastmodified = date("M j Y g:i A", filemtime($CloudUsrDir.$file)); $timekey=date("YmdHis", filemtime($CloudUsrDir.$file)); echo('<tr><td><a href="Pell.php?pellOpen='.$file.'">'.$file.'</a></td> <td><input type="image" id="deleteFile" name="deleteFile" value="'.$file.'" src="'.$URL.'/HRProprietary/HRCloud2/Applications/Pell/resources/deletesmall.png" alt="Delete '.$file.'" title="Delete '.$file.'"></td> <td sorttable_customkey=\''.$timekey.'\'><a href="Pell.php?pellOpen='.$file.'">'.$lastmodified.'</a></td></tr>'); } ?> </table> </form> </div> <div class="content"> <div id="pell" class="pell"></div> <div style="margin-top:20px;"> <h3>Text output:</h3> <div id="textoutput"></div> </div> <div style="margin-top:20px;"> <h3>HTML output:</h3> <pre id="htmloutput"></pre> </div> </div> <script src="dist/pell.js"></script> <script> function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } function ensureHTTP (str) { return /^https?:\/\//.test(str) && str || `http://${str}` } var editor = window.pell.init({ element: document.getElementById('pell'), styleWithCSS: false, actions: [ 'bold', 'underline', 'italic', { name: 'zitalic', icon: 'Z', title: 'Zitalic', result: () => window.pell.exec('italic') }, { name: 'heading1', result: () => window.pell.exec('formatBlock', '<H1>') }, { name: 'heading2', result: () => window.pell.exec('formatBlock', '<H2>') }, { name: 'paragraph', result: () => window.pell.exec('formatBlock', '<P>') }, { name: 'quote', result: () => window.pell.exec('formatBlock', '<BLOCKQUOTE>') }, { name: 'olist', result: () => window.pell.exec('insertOrderedList') }, { name: 'ulist', result: () => window.pell.exec('insertUnorderedList') }, { name: 'line', result: () => window.pell.exec('insertHorizontalRule') }, { name: 'undo', result: () => window.pell.exec('undo') }, { name: 'redo', result: () => window.pell.exec('redo') }, { name: 'image', result: () => { const url = window.prompt('Enter the image URL') if (url) window.pell.exec('insertImage', ensureHTTP(url)) } }, { name: 'link', result: () => { const url = window.prompt('Enter the link URL') if (url) window.pell.exec('createLink', ensureHTTP(url)) } } ], onChange: function (html) { document.getElementById('textoutput').innerHTML = html; document.getElementById('htmloutput').textContent = html; } }) document.getElementById('htmloutput').textContent = '<?php echo str_replace('\'', '\\\'', str_replace("\n", '', preg_replace('/\s\s+/', ' ', htmlspecialchars_decode(trim($pellOpenFileData))))); ?>'; <?php if (isset($_POST['pellOpen']) && $pellOpen !== '') { echo(' var pellc = document.getElementsByClassName(\'pell-content\'), i = pellc.length; while(i--) { pellc[i].innerHTML = \''.str_replace('\'', '\\\'', str_replace("\n", '', preg_replace('/\s\s+/', ' ', htmlspecialchars_decode(trim($pellOpenFileData))))).'\'; }'); } ?> </script> </body> </html>
{ "pile_set_name": "Github" }
// // docopt_util.h // docopt // // Created by Jared Grubb on 2013-11-04. // Copyright (c) 2013 Jared Grubb. All rights reserved. // #ifndef docopt_docopt_util_h #define docopt_docopt_util_h #pragma mark - #pragma mark General utility namespace { bool starts_with(std::string const& str, std::string const& prefix) { if (str.length() < prefix.length()) return false; return std::equal(prefix.begin(), prefix.end(), str.begin()); } std::string trim(std::string&& str, const std::string& whitespace = " \t\n") { const auto strEnd = str.find_last_not_of(whitespace); if (strEnd==std::string::npos) return {}; // no content str.erase(strEnd+1); const auto strBegin = str.find_first_not_of(whitespace); str.erase(0, strBegin); return std::move(str); } std::vector<std::string> split(std::string const& str, size_t pos = 0) { const char* const anySpace = " \t\r\n\v\f"; std::vector<std::string> ret; while (pos != std::string::npos) { auto start = str.find_first_not_of(anySpace, pos); if (start == std::string::npos) break; auto end = str.find_first_of(anySpace, start); auto size = end==std::string::npos ? end : end-start; ret.emplace_back(str.substr(start, size)); pos = end; } return ret; } std::tuple<std::string, std::string, std::string> partition(std::string str, std::string const& point) { std::tuple<std::string, std::string, std::string> ret; auto i = str.find(point); if (i == std::string::npos) { // no match: string goes in 0th spot only } else { std::get<2>(ret) = str.substr(i + point.size()); std::get<1>(ret) = point; str.resize(i); } std::get<0>(ret) = std::move(str); return ret; } template <typename I> std::string join(I iter, I end, std::string const& delim) { if (iter==end) return {}; std::string ret = *iter; for(++iter; iter!=end; ++iter) { ret.append(delim); ret.append(*iter); } return ret; } } namespace docopt { template <class T> inline void hash_combine(std::size_t& seed, T const& v) { // stolen from boost::hash_combine std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); } } #endif
{ "pile_set_name": "Github" }
/* dP dP dP */ /* 88 88 88 */ /* d8888P 88d888b. .d8888b. 88d8b.d8b. .d8888b. 88d888b. .d8888b. 88d888b. 88 .dP */ /* 88 88' `88 88ooood8 88'`88'`88 88ooood8 88' `88 88' `88 88' `88 88888" */ /* 88 88 88 88. ... 88 88 88 88. ... 88. .88 88. .88 88 88 `8b. */ /* dP dP dP `88888P' dP dP dP `88888P' 88 88Y888P' `88888P8 dP dP `YP */ /* 88 */ /* dP */ /* Made by @gilbN */ /* https://github.com/gilbN/theme.park */ /* GUACAMOLE ORGANIZR-DARK THEME */ @import url(https://gilbn.github.io/theme.park/CSS/themes/guacamole/guacamole-base.css); :root { --main-bg-color: #1f1f1f; --modal-bg-color: #1b1b1b; --button-color: #2cabe3; --button-color-hover: rgb(44 171 227 / .8); }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: cd2721292fc859a46843372293c8c3d7 folderAsset: yes timeCreated: 1504268317 licenseType: Free DefaultImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
1 dutch; flemish x-vnd.Haiku-Fortune 52757361 Fortune file: ConfigView Geluksbestand: Fortune FortuneFilter Geluk Tag line: ConfigView Tagregel: Fortune cookie says:\n\n ConfigView Gelukskoekje zegt:\n\n
{ "pile_set_name": "Github" }
var parse = require('shell-quote').parse; var exec = require('child_process').exec; var path = require('path'); var echo = process.execPath + ' ' + path.join(__dirname, 'bin/echo'); var fs = require('fs'); module.exports = function (str, opts) { var parts = parse(str); for (var i = 0; i < parts.length; i++) { if (parts[i].op) break; } if (i === parts.length) { // no ops var w = fs.createWriteStream(str); w.once('finish', function () { w.emit('exit', 0) }); w.once('error', function (err) { w.emit('exit', 1) }); return w; } else { if (parts[parts.length-1].op === '|') { str += echo; } if (parts[0].op === '|') { str = echo + str; } if (parts[0].op === '>') { str = echo + str; } } var p = exec(str, opts); p.stderr.pipe(process.stderr, { end: false }); p.stdout.pipe(process.stdout, { end: false }); p.once('exit', function (code) { p.stdin.emit('exit', code) }); return p.stdin; };
{ "pile_set_name": "Github" }
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class SztvHuIE(InfoExtractor): _VALID_URL = r'https?://(?:(?:www\.)?sztv\.hu|www\.tvszombathely\.hu)/(?:[^/]+)/.+-(?P<id>[0-9]+)' _TEST = { 'url': 'http://sztv.hu/hirek/cserkeszek-nepszerusitettek-a-kornyezettudatos-eletmodot-a-savaria-teren-20130909', 'md5': 'a6df607b11fb07d0e9f2ad94613375cb', 'info_dict': { 'id': '20130909', 'ext': 'mp4', 'title': 'Cserkészek népszerűsítették a környezettudatos életmódot a Savaria téren', 'description': 'A zöld nap játékos ismeretterjesztő programjait a Magyar Cserkész Szövetség szervezte, akik az ország nyolc városában adják át tudásukat az érdeklődőknek. A PET...', }, } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) video_file = self._search_regex( r'file: "...:(.*?)",', webpage, 'video file') title = self._html_search_regex( r'<meta name="title" content="([^"]*?) - [^-]*? - [^-]*?"', webpage, 'video title') description = self._html_search_regex( r'<meta name="description" content="([^"]*)"/>', webpage, 'video description', fatal=False) thumbnail = self._og_search_thumbnail(webpage) video_url = 'http://media.sztv.hu/vod/' + video_file return { 'id': video_id, 'url': video_url, 'title': title, 'description': description, 'thumbnail': thumbnail, }
{ "pile_set_name": "Github" }
#!/bin/bash # Copyright 2012 Johns Hopkins University (Author: Daniel Povey) # Apache 2.0 # To be run from .. (one directory up from here) # see ../run.sh for example # Compute cepstral mean and variance statistics per speaker. # We do this in just one job; it's fast. # This script takes no options. # # Note: there is no option to do CMVN per utterance. The idea is # that if you did it per utterance it would not make sense to do # per-speaker fMLLR on top of that (since you'd be doing fMLLR on # top of different offsets). Therefore what would be the use # of the speaker information? In this case you should probably # make the speaker-ids identical to the utterance-ids. The # speaker information does not have to correspond to actual # speakers, it's just the level you want to adapt at. echo "$0 $@" # Print the command line for logging fake=false fake_dims= # If specified, can generate 'fake' stats (that won't normalize) # from a specified dimension. two_channel=false tag= if [ "$1" == "--tag" ]; then tag=$2 shift shift else echo "tag not specified" exit 1 fi if [ "$1" == "--fake" ]; then fake=true shift fi if [ "$1" == "--fake-dims" ]; then fake_dims=$2 shift shift fi if [ "$1" == "--two-channel" ]; then two_channel=true shift fi if [ $# != 3 ]; then echo "Usage: $0 [options] <data-dir> <log-dir> <path-to-cmvn-dir>"; echo "e.g.: $0 data/train exp/make_mfcc/train mfcc" echo "Options:" echo " --tag <tag> uses tag as suffix to feats file" echo " --fake gives you fake cmvn stats that do no normalization." echo " --two-channel is for two-channel telephone data, there must be no segments " echo " file and reco2file_and_channel must be present. It will take" echo " only frames that are louder than the other channel." echo " --fake-dims <n1:n2> Generate stats that won't cause normalization for these" echo " dimensions (e.g. 13:14:15)" exit 1; fi if [ -f path.sh ]; then . ./path.sh; fi data=$1 logdir=$2 cmvndir=$3 # make $cmvndir an absolute pathname. cmvndir=`perl -e '($dir,$pwd)= @ARGV; if($dir!~m:^/:) { $dir = "$pwd/$dir"; } print $dir; ' $cmvndir ${PWD}` # use "name" as part of name of the archive. name=`basename $data` mkdir -p $cmvndir || exit 1; mkdir -p $logdir || exit 1; required="$data/feats_${tag}.scp $data/spk2utt" for f in $required; do if [ ! -f $f ]; then echo "make_cmvn.sh: no such file $f" exit 1; fi done if $fake; then dim=`feat-to-dim scp:$data/feats_${tag}.scp -` ! cat $data/spk2utt | awk -v dim=$dim '{print $1, "["; for (n=0; n < dim; n++) { printf("0 "); } print "1"; for (n=0; n < dim; n++) { printf("1 "); } print "0 ]";}' | \ copy-matrix ark:- ark,scp:$cmvndir/cmvn_$name.ark,$cmvndir/cmvn_$name.scp && \ echo "Error creating fake CMVN stats" && exit 1; elif $two_channel; then ! compute-cmvn-stats-two-channel $data/reco2file_and_channel scp:$data/feats_${tag}.scp \ ark,scp:$cmvndir/cmvn_$name.ark,$cmvndir/cmvn_$name.scp \ 2> $logdir/cmvn_$name.log && echo "Error computing CMVN stats (using two-channel method)" && exit 1; elif [ ! -z "$fake_dims" ]; then ! compute-cmvn-stats --spk2utt=ark:$data/spk2utt scp:$data/feats_${tag}.scp ark:- | \ modify-cmvn-stats "$fake_dims" ark:- ark,scp:$cmvndir/cmvn_$name.ark,$cmvndir/cmvn_$name.scp && \ echo "Error computing (partially fake) CMVN stats" && exit 1; else ! compute-cmvn-stats --spk2utt=ark:$data/spk2utt scp:$data/feats_${tag}.scp ark,scp:$cmvndir/cmvn_$name.ark,$cmvndir/cmvn_$name.scp \ 2> $logdir/cmvn_$name.log && echo "Error computing CMVN stats" && exit 1; fi cp $cmvndir/cmvn_$name.scp $data/cmvn.scp || exit 1; nc=`cat $data/cmvn.scp | wc -l` nu=`cat $data/spk2utt | wc -l` if [ $nc -ne $nu ]; then echo "$0: warning: it seems not all of the speakers got cmvn stats ($nc != $nu);" [ $nc -eq 0 ] && exit 1; fi echo "Succeeded creating CMVN stats for $name"
{ "pile_set_name": "Github" }
# SOME DESCRIPTIVE TITLE. # Copyright (C) 2019-2020 The Zrythm contributors # This file is distributed under the same license as the Zrythm package. # FIRST AUTHOR <EMAIL@ADDRESS>, 2020. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Zrythm 1.0.0-alpha.0\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2020-09-24 00:47+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.8.0\n" #: ../../control-surfaces/intro.rst:6 msgid "Control Surfaces" msgstr ""
{ "pile_set_name": "Github" }
/********************************************************************** * * Copyright (c) 2004 Olaf Willuhn * All rights reserved. * * This software is copyrighted work licensed under the terms of the * Jameica License. Please consult the file "LICENSE" for details. * **********************************************************************/ package de.willuhn.jameica.hbci.io.print; import java.rmi.RemoteException; import java.util.Date; import net.sf.paperclips.GridPrint; import net.sf.paperclips.TextPrint; import de.willuhn.jameica.hbci.HBCI; import de.willuhn.jameica.hbci.rmi.SepaSammelLastschrift; import de.willuhn.util.ApplicationException; /** * Druck-Support fuer SEPA-Sammel-Lastschriften. */ public class PrintSupportSepaSammelLastschrift extends AbstractPrintSupportSepaSammelTransfer<SepaSammelLastschrift> { /** * ct. * @param ctx die zu druckenden Daten. */ public PrintSupportSepaSammelLastschrift(Object ctx) { super(ctx); } /** * @see de.willuhn.jameica.hbci.io.print.AbstractPrintSupport#getTitle() */ String getTitle() throws ApplicationException { return i18n.tr("SEPA-Sammellastschrift"); } /** * @see de.willuhn.jameica.hbci.io.print.AbstractPrintSupportSepaSammelTransfer#createTransferTable(de.willuhn.jameica.hbci.rmi.SepaSammelTransfer) */ GridPrint createTransferTable(SepaSammelLastschrift a) throws RemoteException, ApplicationException { GridPrint table = super.createTransferTable(a); // Wir fuegen noch ein paar SEPA-spezifische Sachen hinzu. table.add(new TextPrint(i18n.tr("Sequenz-Typ"),fontNormal)); table.add(new TextPrint(a.getSequenceType().getDescription(),fontNormal)); table.add(new TextPrint(i18n.tr("Lastschrift-Art"),fontNormal)); table.add(new TextPrint(a.getType().getDescription(),fontNormal)); Date faellig = a.getTargetDate(); table.add(new TextPrint(i18n.tr("Zieltermin"),fontNormal)); table.add(new TextPrint(faellig == null ? "-" : HBCI.DATEFORMAT.format(faellig),fontNormal)); return table; } }
{ "pile_set_name": "Github" }
<Type Name="ComponentEnabledChangedEventArgs" FullName="Urho.ComponentEnabledChangedEventArgs"> <TypeSignature Language="C#" Value="public struct ComponentEnabledChangedEventArgs" /> <TypeSignature Language="ILAsm" Value=".class public sequential ansi sealed beforefieldinit ComponentEnabledChangedEventArgs extends System.ValueType" /> <AssemblyInfo> <AssemblyName>Urho</AssemblyName> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <Base> <BaseTypeName>System.ValueType</BaseTypeName> </Base> <Interfaces /> <Docs> <summary>Event arguments for the Scene's ComponentEnabledChanged event</summary> <remarks>To be added.</remarks> </Docs> <Members> <Member MemberName="Component"> <MemberSignature Language="C#" Value="public Urho.Component Component { get; }" /> <MemberSignature Language="ILAsm" Value=".property instance class Urho.Component Component" /> <MemberType>Property</MemberType> <AssemblyInfo> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>Urho.Component</ReturnType> </ReturnValue> <Docs> <summary>To be added.</summary> <value>To be added.</value> <remarks>To be added.</remarks> </Docs> </Member> <Member MemberName="EventData"> <MemberSignature Language="C#" Value="public Urho.EventDataContainer EventData;" /> <MemberSignature Language="ILAsm" Value=".field public class Urho.EventDataContainer EventData" /> <MemberType>Field</MemberType> <AssemblyInfo> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>Urho.EventDataContainer</ReturnType> </ReturnValue> <Docs> <summary>To be added.</summary> <remarks>To be added.</remarks> </Docs> </Member> <Member MemberName="Node"> <MemberSignature Language="C#" Value="public Urho.Node Node { get; }" /> <MemberSignature Language="ILAsm" Value=".property instance class Urho.Node Node" /> <MemberType>Property</MemberType> <AssemblyInfo> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>Urho.Node</ReturnType> </ReturnValue> <Docs> <summary>To be added.</summary> <value>To be added.</value> <remarks>To be added.</remarks> </Docs> </Member> <Member MemberName="Scene"> <MemberSignature Language="C#" Value="public Urho.Scene Scene { get; }" /> <MemberSignature Language="ILAsm" Value=".property instance class Urho.Scene Scene" /> <MemberType>Property</MemberType> <AssemblyInfo> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>Urho.Scene</ReturnType> </ReturnValue> <Docs> <summary>To be added.</summary> <value>To be added.</value> <remarks>To be added.</remarks> </Docs> </Member> </Members> </Type>
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ssm/SSM_EXPORTS.h> #include <aws/ssm/model/AutomationExecution.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace SSM { namespace Model { class AWS_SSM_API GetAutomationExecutionResult { public: GetAutomationExecutionResult(); GetAutomationExecutionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); GetAutomationExecutionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>Detailed information about the current state of an automation execution.</p> */ inline const AutomationExecution& GetAutomationExecution() const{ return m_automationExecution; } /** * <p>Detailed information about the current state of an automation execution.</p> */ inline void SetAutomationExecution(const AutomationExecution& value) { m_automationExecution = value; } /** * <p>Detailed information about the current state of an automation execution.</p> */ inline void SetAutomationExecution(AutomationExecution&& value) { m_automationExecution = std::move(value); } /** * <p>Detailed information about the current state of an automation execution.</p> */ inline GetAutomationExecutionResult& WithAutomationExecution(const AutomationExecution& value) { SetAutomationExecution(value); return *this;} /** * <p>Detailed information about the current state of an automation execution.</p> */ inline GetAutomationExecutionResult& WithAutomationExecution(AutomationExecution&& value) { SetAutomationExecution(std::move(value)); return *this;} private: AutomationExecution m_automationExecution; }; } // namespace Model } // namespace SSM } // namespace Aws
{ "pile_set_name": "Github" }
{ "method": "PROPFIND", "url": "http://mockbin.com/har" }
{ "pile_set_name": "Github" }
RevTilt::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure static asset server for tests with Cache-Control for performance config.serve_static_files = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Don't actually send emails config.action_mailer.perform_deliveries = false # ActionMailer config.action_mailer.default_url_options = { :host => 'test.host' } # Print deprecation notices to the stderr config.active_support.deprecation = :stderr end
{ "pile_set_name": "Github" }
auto a_func( const char a[] ) -> decltype(a) { return a+1; } char b_func() { return 'b'; } auto c_func( char c() ) -> decltype(c) { return b_func; } auto d_func( const char d ) -> decltype(d)* { return "d"; } void foobar() { const char* a = a_func("xabc"); char c = c_func(b_func)(); const char* d = d_func('x'); }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=../../../libc/struct.ifaddrs.html"> </head> <body> <p>Redirecting to <a href="../../../libc/struct.ifaddrs.html">../../../libc/struct.ifaddrs.html</a>...</p> <script>location.replace("../../../libc/struct.ifaddrs.html" + location.search + location.hash);</script> </body> </html>
{ "pile_set_name": "Github" }
// AFURLSessionManager.h // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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. #import <Foundation/Foundation.h> #import "AFURLResponseSerialization.h" #import "AFURLRequestSerialization.h" #import "AFSecurityPolicy.h" #if !TARGET_OS_WATCH #import "AFNetworkReachabilityManager.h" #endif /** `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`. ## Subclassing Notes This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. ## NSURLSession & NSURLSessionTask Delegate Methods `AFURLSessionManager` implements the following delegate methods: ### `NSURLSessionDelegate` - `URLSession:didBecomeInvalidWithError:` - `URLSession:didReceiveChallenge:completionHandler:` - `URLSessionDidFinishEventsForBackgroundURLSession:` ### `NSURLSessionTaskDelegate` - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` - `URLSession:task:didReceiveChallenge:completionHandler:` - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` - `URLSession:task:needNewBodyStream:` - `URLSession:task:didCompleteWithError:` ### `NSURLSessionDataDelegate` - `URLSession:dataTask:didReceiveResponse:completionHandler:` - `URLSession:dataTask:didBecomeDownloadTask:` - `URLSession:dataTask:didReceiveData:` - `URLSession:dataTask:willCacheResponse:completionHandler:` ### `NSURLSessionDownloadDelegate` - `URLSession:downloadTask:didFinishDownloadingToURL:` - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. ## Network Reachability Monitoring Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. ## NSCoding Caveats - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. ## NSCopying Caveats - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. */ NS_ASSUME_NONNULL_BEGIN @interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying> /** The managed session. */ @property (readonly, nonatomic, strong) NSURLSession *session; /** The operation queue on which delegate callbacks are run. */ @property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; /** Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. @warning `responseSerializer` must not be `nil`. */ @property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer; ///------------------------------- /// @name Managing Security Policy ///------------------------------- /** The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. */ @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; #if !TARGET_OS_WATCH ///-------------------------------------- /// @name Monitoring Network Reachability ///-------------------------------------- /** The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. */ @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; #endif ///---------------------------- /// @name Getting Session Tasks ///---------------------------- /** The data, upload, and download tasks currently run by the managed session. */ @property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks; /** The data tasks currently run by the managed session. */ @property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks; /** The upload tasks currently run by the managed session. */ @property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks; /** The download tasks currently run by the managed session. */ @property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks; ///------------------------------- /// @name Managing Callback Queues ///------------------------------- /** The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. */ @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; /** The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. */ @property (nonatomic, strong, nullable) dispatch_group_t completionGroup; ///--------------------------------- /// @name Working Around System Bugs ///--------------------------------- /** Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again. @see https://github.com/AFNetworking/AFNetworking/issues/1675 */ @property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; ///--------------------- /// @name Initialization ///--------------------- /** Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. @param configuration The configuration used to create the managed session. @return A manager for a newly-created session. */ - (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; /** Invalidates the managed session, optionally canceling pending tasks. @param cancelPendingTasks Whether or not to cancel pending tasks. */ - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; ///------------------------- /// @name Running Data Tasks ///------------------------- /** Creates an `NSURLSessionDataTask` with the specified request. @param request The HTTP request for the request. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. */ - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionDataTask` with the specified request. @param request The HTTP request for the request. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. */ - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; ///--------------------------- /// @name Running Upload Tasks ///--------------------------- /** Creates an `NSURLSessionUploadTask` with the specified request for a local file. @param request The HTTP request for the request. @param fileURL A URL to the local file to be uploaded. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. @see `attemptsToRecreateUploadTasksForBackgroundSessions` */ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. @param request The HTTP request for the request. @param bodyData A data object containing the HTTP body to be uploaded. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. */ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(nullable NSData *)bodyData progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionUploadTask` with the specified streaming request. @param request The HTTP request for the request. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. */ - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; ///----------------------------- /// @name Running Download Tasks ///----------------------------- /** Creates an `NSURLSessionDownloadTask` with the specified request. @param request The HTTP request for the request. @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. */ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionDownloadTask` with the specified resume data. @param resumeData The data used to resume downloading. @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. */ - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; ///--------------------------------- /// @name Getting Progress for Tasks ///--------------------------------- /** Returns the upload progress of the specified task. @param task The session task. Must not be `nil`. @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. */ - (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; /** Returns the download progress of the specified task. @param task The session task. Must not be `nil`. @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. */ - (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; ///----------------------------------------- /// @name Setting Session Delegate Callbacks ///----------------------------------------- /** Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. */ - (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; /** Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. */ - (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; ///-------------------------------------- /// @name Setting Task Delegate Callbacks ///-------------------------------------- /** Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. @param block A block object to be executed when a task requires a new request body stream. */ - (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; /** Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. */ - (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; /** Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. */ - (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; /** Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. */ - (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; /** Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. */ - (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; ///------------------------------------------- /// @name Setting Data Task Delegate Callbacks ///------------------------------------------- /** Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. */ - (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; /** Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. */ - (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; /** Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. */ - (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; /** Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. */ - (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; /** Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. */ - (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; ///----------------------------------------------- /// @name Setting Download Task Delegate Callbacks ///----------------------------------------------- /** Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. */ - (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; /** Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. */ - (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; /** Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. */ - (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; @end ///-------------------- /// @name Notifications ///-------------------- /** Posted when a task resumes. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; /** Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; /** Posted when a task suspends its execution. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; /** Posted when a session is invalidated. */ FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; /** Posted when a session download task encountered an error when moving the temporary download file to a specified destination. */ FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; /** The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; /** The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; /** The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; /** The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; /** Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. */ FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
var overload_copy = require("overload_copy"); f = new overload_copy.Foo(); g = new overload_copy.Foo(f);
{ "pile_set_name": "Github" }
# fuzzy grep open via ag local file file="$(ag --nobreak --noheading $@ | fzf -0 -1 | awk -F: '{print $1}')" if [[ -n $file ]] then vim $file fi
{ "pile_set_name": "Github" }
<?php namespace Orchestra\Testbench\Tests\Stubs\Providers; class DeferredChildServiceProvider extends ServiceProvider { protected $defer = true; public function register() { $this->app['child.deferred.loaded'] = true; } }
{ "pile_set_name": "Github" }
# # really simple gluster setup for physical provisioning. # (yeah, that's it-- for iron!) # node /^annex\d+$/ { # annex{1,2,..N} class { '::gluster::simple': replica => 2, vip => '192.168.1.42', vrrp => true, # NOTE: _each_ host will have four bricks with these devices... brick_params_defaults => [ # note the spelling and type... {'dev' => '/dev/sdb'}, {'dev' => '/dev/sdc'}, {'dev' => '/dev/sdd'}, {'dev' => '/dev/sde'}, ], brick_param_defaults => { # every brick will use these... lvm => false, xfs_inode64 => true, force => true, }, #brick_params => {}, # NOTE: you can also use this option to # override a particular fqdn with the options that you need to! } }
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2011 Bryce Lelbach Distributed under 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) =============================================================================*/ #if !defined(BOOST_SPIRIT_UTREE_DETAIL1) #define BOOST_SPIRIT_UTREE_DETAIL1 #include <boost/type_traits/alignment_of.hpp> namespace boost { namespace spirit { namespace detail { template <typename UTreeX, typename UTreeY> struct visit_impl; struct index_impl; /////////////////////////////////////////////////////////////////////////// // Our POD double linked list. Straightforward implementation. // This implementation is very primitive and is not meant to be // used stand-alone. This is the internal data representation // of lists in our utree. /////////////////////////////////////////////////////////////////////////// struct list // keep this a POD! { struct node; template <typename Value> class node_iterator; void free(); void copy(list const& other); void default_construct(); template <typename T, typename Iterator> void insert(T const& val, Iterator pos); template <typename T> void push_front(T const& val); template <typename T> void push_back(T const& val); void pop_front(); void pop_back(); node* erase(node* pos); node* first; node* last; std::size_t size; }; /////////////////////////////////////////////////////////////////////////// // A range of utree(s) using an iterator range (begin/end) of node(s) /////////////////////////////////////////////////////////////////////////// struct range { list::node* first; list::node* last; }; /////////////////////////////////////////////////////////////////////////// // A range of char*s /////////////////////////////////////////////////////////////////////////// struct string_range { char const* first; char const* last; }; /////////////////////////////////////////////////////////////////////////// // A void* plus type_info /////////////////////////////////////////////////////////////////////////// struct void_ptr { void* p; std::type_info const* i; }; /////////////////////////////////////////////////////////////////////////// // Our POD fast string. This implementation is very primitive and is not // meant to be used stand-alone. This is the internal data representation // of strings in our utree. This is deliberately a POD to allow it to be // placed in a union. This POD fast string specifically utilizes // (sizeof(list) * alignment_of(list)) - (2 * sizeof(char)). In a 32 bit // system, this is 14 bytes. The two extra bytes are used by utree to store // management info. // // It is a const string (i.e. immutable). It stores the characters directly // if possible and only uses the heap if the string does not fit. Null // characters are allowed, making it suitable to encode raw binary. The // string length is encoded in the first byte if the string is placed in-situ, // else, the length plus a pointer to the string in the heap are stored. /////////////////////////////////////////////////////////////////////////// struct fast_string // Keep this a POD! { static std::size_t const buff_size = (sizeof(list) + boost::alignment_of<list>::value) / sizeof(char); static std::size_t const small_string_size = buff_size-sizeof(char); static std::size_t const max_string_len = small_string_size - 3; struct heap_store { char* str; std::size_t size; }; union { char buff[buff_size]; long lbuff[buff_size / (sizeof(long)/sizeof(char))]; // for initialize heap_store heap; }; int get_type() const; void set_type(int t); bool is_heap_allocated() const; std::size_t size() const; char const* str() const; template <typename Iterator> void construct(Iterator f, Iterator l); void swap(fast_string& other); void free(); void copy(fast_string const& other); void initialize(); char& info(); char info() const; short tag() const; void tag(short tag); }; }}} #endif
{ "pile_set_name": "Github" }
config BR2_PACKAGE_HOST_PYTHON_SIX bool "host python-six" help Six is a Python 2 and 3 compatibility library. It provides utility functions for smoothing over the differences between the Python versions with the goal of writing Python code that is compatible on both Python versions. http://pythonhosted.org/six
{ "pile_set_name": "Github" }
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // 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. #ifndef RAPIDJSON_FILEREADSTREAM_H_ #define RAPIDJSON_FILEREADSTREAM_H_ #include "stream.h" #include <cstdio> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(unreachable-code) RAPIDJSON_DIAG_OFF(missing-noreturn) #endif RAPIDJSON_NAMESPACE_BEGIN //! File byte stream for input using fread(). /*! \note implements Stream concept */ class FileReadStream { public: typedef char Ch; //!< Character type (byte). //! Constructor. /*! \param fp File pointer opened for read. \param buffer user-supplied buffer. \param bufferSize size of buffer in bytes. Must >=4 bytes. */ FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { RAPIDJSON_ASSERT(fp_ != 0); RAPIDJSON_ASSERT(bufferSize >= 4); Read(); } Ch Peek() const { return *current_; } Ch Take() { Ch c = *current_; Read(); return c; } size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); } // Not implemented void Put(Ch) { RAPIDJSON_ASSERT(false); } void Flush() { RAPIDJSON_ASSERT(false); } Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } // For encoding detection only. const Ch* Peek4() const { return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; } private: void Read() { if (current_ < bufferLast_) ++current_; else if (!eof_) { count_ += readCount_; readCount_ = std::fread(buffer_, 1, bufferSize_, fp_); bufferLast_ = buffer_ + readCount_ - 1; current_ = buffer_; if (readCount_ < bufferSize_) { buffer_[readCount_] = '\0'; ++bufferLast_; eof_ = true; } } } std::FILE* fp_; Ch *buffer_; size_t bufferSize_; Ch *bufferLast_; Ch *current_; size_t readCount_; size_t count_; //!< Number of characters read bool eof_; }; RAPIDJSON_NAMESPACE_END #ifdef __clang__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_FILESTREAM_H_
{ "pile_set_name": "Github" }
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under 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) */ /*! * \file locking_ptr.hpp * \author Andrey Semashev * \date 15.07.2009 * * This header is the Boost.Log library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html. */ #ifndef BOOST_LOG_DETAIL_LOCKING_PTR_HPP_INCLUDED_ #define BOOST_LOG_DETAIL_LOCKING_PTR_HPP_INCLUDED_ #include <cstddef> #include <boost/move/core.hpp> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/thread/lock_options.hpp> #include <boost/log/detail/config.hpp> #include <boost/utility/explicit_operator_bool.hpp> #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace aux { //! A pointer type that locks the backend until it's destroyed template< typename T, typename LockableT > class locking_ptr { typedef locking_ptr this_type; BOOST_COPYABLE_AND_MOVABLE_ALT(this_type) public: //! Pointed type typedef T element_type; private: //! Lockable type typedef LockableT lockable_type; private: //! The pointer to the backend shared_ptr< element_type > m_pElement; //! Reference to the shared lock control object lockable_type* m_pLock; public: //! Default constructor locking_ptr() BOOST_NOEXCEPT : m_pLock(NULL) { } //! Constructor locking_ptr(shared_ptr< element_type > const& p, lockable_type& l) : m_pElement(p), m_pLock(&l) { m_pLock->lock(); } //! Constructor locking_ptr(shared_ptr< element_type > const& p, lockable_type& l, try_to_lock_t const&) : m_pElement(p), m_pLock(&l) { if (!m_pLock->try_lock()) { m_pElement.reset(); m_pLock = NULL; } } //! Copy constructor locking_ptr(locking_ptr const& that) : m_pElement(that.m_pElement), m_pLock(that.m_pLock) { if (m_pLock) m_pLock->lock(); } //! Move constructor locking_ptr(BOOST_RV_REF(this_type) that) BOOST_NOEXCEPT : m_pLock(that.m_pLock) { m_pElement.swap(that.m_pElement); that.m_pLock = NULL; } //! Destructor ~locking_ptr() { if (m_pLock) m_pLock->unlock(); } //! Assignment locking_ptr& operator= (locking_ptr that) BOOST_NOEXCEPT { this->swap(that); return *this; } //! Indirection element_type* operator-> () const BOOST_NOEXCEPT { return m_pElement.get(); } //! Dereferencing element_type& operator* () const BOOST_NOEXCEPT { return *m_pElement; } //! Accessor to the raw pointer element_type* get() const BOOST_NOEXCEPT { return m_pElement.get(); } //! Checks for null pointer BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT() //! Checks for null pointer bool operator! () const BOOST_NOEXCEPT { return !m_pElement; } //! Swaps two pointers void swap(locking_ptr& that) BOOST_NOEXCEPT { m_pElement.swap(that.m_pElement); lockable_type* p = m_pLock; m_pLock = that.m_pLock; that.m_pLock = p; } }; //! Free raw pointer getter to assist generic programming template< typename T, typename LockableT > inline T* get_pointer(locking_ptr< T, LockableT > const& p) BOOST_NOEXCEPT { return p.get(); } //! Free swap operation template< typename T, typename LockableT > inline void swap(locking_ptr< T, LockableT >& left, locking_ptr< T, LockableT >& right) BOOST_NOEXCEPT { left.swap(right); } } // namespace aux BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_DETAIL_LOCKING_PTR_HPP_INCLUDED_
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="ISO-8859-1" ?> <!-- - - $Id$ - - This file is part of the OpenLink Software Virtuoso Open-Source (VOS) - project. - - Copyright (C) 1998-2020 OpenLink Software - - This project 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; only version 2 of the License, dated June 1991. - - 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 St, Fifth Floor, Boston, MA 02110-1301 USA - - --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:v="http://www.openlinksw.com/vspx/" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:vm="http://www.openlinksw.com/vspx/macro"> <!--=========================================================================--> <xsl:template name="make_href"> <xsl:param name="url"></xsl:param> <xsl:param name="params"/> <xsl:param name="class"></xsl:param> <xsl:param name="target"/> <xsl:param name="onclick"/> <xsl:param name="onmousedown"/> <xsl:param name="label"/> <xsl:param name="deflabel"><font color="FF0000"><b>Error !!!</b></font></xsl:param> <xsl:param name="title"/> <xsl:param name="id"/> <xsl:param name="no_sid">0</xsl:param> <xsl:param name="img"/> <xsl:param name="img_width"/> <xsl:param name="img_height"/> <xsl:param name="img_hspace"/> <xsl:param name="img_vspace"/> <xsl:param name="img_align"/> <xsl:param name="img_class"/> <xsl:param name="img_with_sid">0</xsl:param> <xsl:param name="img_params"/> <xsl:param name="ovr_mount_point"/> <xsl:choose> <xsl:when test="$url = ''"> <xsl:variable name="url">/</xsl:variable> <xsl:variable name="label">Home</xsl:variable> </xsl:when> </xsl:choose> <xsl:choose> <xsl:when test="starts-with($url,'javascript')"> <xsl:variable name="pparams"></xsl:variable> </xsl:when> <xsl:when test="$no_sid = 1 and $params != ''"> <xsl:variable name="pparams">?<xsl:value-of select="$params"/></xsl:variable> </xsl:when> <xsl:when test="$no_sid = 1 and $params = ''"> <xsl:variable name="pparams"></xsl:variable> </xsl:when> <xsl:when test="$no_sid = 0 and $params = ''"> <xsl:variable name="pparams">?sid=<xsl:value-of select="$sid"/>&amp;realm=<xsl:value-of select="$realm"/></xsl:variable> </xsl:when> <xsl:when test="$no_sid = 0 and $params != ''"> <xsl:variable name="pparams">?sid=<xsl:value-of select="$sid"/>&amp;realm=<xsl:value-of select="$realm"/>&amp;<xsl:value-of select="$params"/></xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="pparams">buuuuuuuuug</xsl:variable> </xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="$img != ''"> <xsl:variable name="label"> <xsl:call-template name="make_img"> <xsl:with-param name="src" select="$img"/> <xsl:with-param name="width" select="$img_width"/> <xsl:with-param name="height" select="$img_height"/> <xsl:with-param name="alt" select="$label"/> <xsl:with-param name="hspace" select="$img_hspace"/> <xsl:with-param name="vspace" select="$img_vspace"/> <xsl:with-param name="align" select="$img_align"/> <xsl:with-param name="class" select="$img_class"/> <xsl:with-param name="with_sid" select="$img_with_sid"/> <xsl:with-param name="params" select="$img_params"/> </xsl:call-template> </xsl:variable> </xsl:when> <xsl:when test="$label != ''"> <xsl:variable name="label"><xsl:value-of select="$label"/></xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="label"><xsl:value-of select="$deflabel"/></xsl:variable> </xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="$target = 'help-popup'"> <xsl:variable name="onclick">javascript:window.open('<xsl:value-of select="$url"/><xsl:value-of select="$pparams"/>','help','width=300, height=300, left=100,top=100')</xsl:variable> <xsl:variable name="href">#</xsl:variable> <xsl:variable name="target"></xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="href"><xsl:value-of select="$url"/><xsl:value-of select="$pparams"/></xsl:variable> </xsl:otherwise> </xsl:choose> <a> <xsl:attribute name="href"><xsl:value-of select="$href"/></xsl:attribute> <xsl:if test="$class != ''"><xsl:attribute name="class"><xsl:value-of select="$class"/></xsl:attribute></xsl:if> <xsl:if test="$onclick != ''"><xsl:attribute name="OnClick"><xsl:value-of select="$onclick"/></xsl:attribute></xsl:if> <xsl:if test="$onmousedown != ''"><xsl:attribute name="OnMouseDown"><xsl:value-of select="$onmousedown"/></xsl:attribute></xsl:if> <xsl:if test="$target != ''"><xsl:attribute name="target"><xsl:value-of select="$target"/></xsl:attribute></xsl:if> <xsl:if test="$title != ''"><xsl:attribute name="title"><xsl:value-of select="$title"/></xsl:attribute></xsl:if> <xsl:if test="$id != ''"><xsl:attribute name="id"><xsl:value-of select="$id"/></xsl:attribute></xsl:if> <xsl:copy-of select="$label" /> </a> </xsl:template> <!--========================================================================--> <xsl:template name="html_script"> <script language="JavaScript"><![CDATA[ function showtab(did,tabs_count){ for (var i = 1; i <= tabs_count; i++) { var div = document.getElementById(i); var ahref = document.getElementById('ahref_'+i); if (i == did) { div.style.visibility = 'visible'; ahref.className = "tab activeTab"; ahref.blur(); } else { div.style.visibility = 'hidden'; ahref.className = "tab"; }; }; }; function disable_all (cnt) { for ( var i = 1; i <= cnt; i++) { eval ("document.form_" + i + ".new_endp.disabled = true"); document.form_def.endpoint.disabled = true; }; }; function deleteConfirm() { return confirm('Are you sure you want to delete this process?'); }; function ch_msg() { for (var i=0; i<document.F1.elements.length; i++) { var e = document.F1.elements[i]; if (e.name != 'ch_all') e.checked = document.F1.ch_all.checked; }; }; ]]></script> </xsl:template> <!--========================================================================--> <xsl:template name="nbsp"> <xsl:param name="count" select="1"/> <xsl:if test="$count != 0"> <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:call-template name="nbsp"> <xsl:with-param name="count" select="$count - 1"/> </xsl:call-template> </xsl:if> </xsl:template> <!-- ===================================================================================================================================== --> <xsl:template match="report"> <xsl:choose> <xsl:when test="@type = 'result'"> <th class="tr_title"><xsl:value-of select="res"/></th> <th colspan="3"><xsl:value-of select="desc"/></th> </xsl:when> <xsl:when test="@type = 'error'"> <th class="tr_ms" colspan="4"><xsl:value-of select="res"/>&nbsp;<xsl:value-of select="desc"/></th> </xsl:when> </xsl:choose> </xsl:template> <!--========================================================================--> <xsl:template name="make_submit"> <xsl:param name="name"></xsl:param> <xsl:param name="value"></xsl:param> <xsl:param name="id"></xsl:param> <xsl:param name="src">-1</xsl:param> <xsl:param name="button">-1</xsl:param> <xsl:param name="hspace">-1</xsl:param> <xsl:param name="vspace">-1</xsl:param> <xsl:param name="border">-1</xsl:param> <xsl:param name="class">-1</xsl:param> <xsl:param name="onclick">-1</xsl:param> <xsl:param name="disabled">-1</xsl:param> <xsl:param name="tabindex">-1</xsl:param> <xsl:param name="alt">-1</xsl:param> <xsl:choose> <xsl:when test="$src != '-1' and $src != ''"> <xsl:variable name="type">image</xsl:variable> <xsl:variable name="pname"><xsl:value-of select="$name"/></xsl:variable> </xsl:when> <xsl:when test="$button != '-1'"> <xsl:variable name="type">button</xsl:variable> <xsl:variable name="pname"><xsl:value-of select="$name"/></xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="type">submit</xsl:variable> <xsl:variable name="pname"><xsl:value-of select="$name"/>.x</xsl:variable> </xsl:otherwise> </xsl:choose> <input> <xsl:attribute name="type"><xsl:value-of select="$type"/></xsl:attribute> <xsl:attribute name="name"><xsl:value-of select="$pname"/></xsl:attribute> <xsl:attribute name="value"><xsl:value-of select="$value"/></xsl:attribute> <xsl:attribute name="alt"><xsl:value-of select="$value"/></xsl:attribute> <xsl:attribute name="border">0</xsl:attribute> <xsl:if test="$id != ''"> <xsl:attribute name="id"><xsl:value-of select="$id"/></xsl:attribute> </xsl:if> <xsl:if test="$src != '-1'"> <xsl:attribute name="src"><xsl:value-of select="$src"/></xsl:attribute> </xsl:if> <xsl:if test="$class != '-1'"> <xsl:attribute name="class"><xsl:value-of select="$class"/></xsl:attribute> </xsl:if> <xsl:if test="$alt != '-1'"> <xsl:attribute name="alt"><xsl:value-of select="$alt"/></xsl:attribute><xsl:attribute name="title"><xsl:value-of select="$alt"/></xsl:attribute> </xsl:if> <xsl:if test="$onclick != '-1'"> <xsl:attribute name="onClick"><xsl:value-of select="$onclick"/></xsl:attribute> </xsl:if> <xsl:if test="$border != '-1'"> <xsl:attribute name="border"><xsl:value-of select="$border"/></xsl:attribute> </xsl:if> <xsl:if test="$vspace != '-1'"> <xsl:attribute name="vspace"><xsl:value-of select="$vspace"/></xsl:attribute> </xsl:if> <xsl:if test="$hspace != '-1'"> <xsl:attribute name="hspace"><xsl:value-of select="$hspace"/></xsl:attribute> </xsl:if> <xsl:if test="$disabled != '-1'"> <xsl:attribute name="disabled">disabled</xsl:attribute> </xsl:if> </input> </xsl:template> <!--========================================================================--> <xsl:template name="make_img"> <xsl:param name="src">/not_found.gif</xsl:param> <xsl:param name="width"/> <xsl:param name="height"/> <xsl:param name="alt"/> <xsl:param name="hspace"/> <xsl:param name="vspace"/> <xsl:param name="align"/> <xsl:param name="border">0</xsl:param> <xsl:param name="with_sid">0</xsl:param> <xsl:param name="params"/> <xsl:param name="class"/> <xsl:choose> <xsl:when test="$with_sid = 0 and $params != ''"> <xsl:variable name="pparams">?<xsl:value-of select="$params"/></xsl:variable> </xsl:when> <xsl:when test="$with_sid = 0 and $params = ''"> <xsl:variable name="pparams"></xsl:variable> </xsl:when> <xsl:when test="$with_sid = 1 and $params = ''"> <xsl:variable name="pparams">?sid=<xsl:value-of select="$sid"/></xsl:variable> </xsl:when> <xsl:when test="$with_sid = 1 and $params != ''"> <xsl:variable name="pparams">?sid=<xsl:value-of select="$sid"/>&amp;realm=<xsl:value-of select="$realm"/>&amp;<xsl:value-of select="$params"/></xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="pparams">buuuuuuuuug</xsl:variable> </xsl:otherwise> </xsl:choose> <img> <xsl:attribute name="src"><xsl:value-of select="$src"/><xsl:value-of select="$pparams"/></xsl:attribute> <xsl:if test="$width"><xsl:attribute name="width"><xsl:value-of select="$width"/></xsl:attribute></xsl:if> <xsl:if test="$height"><xsl:attribute name="height"><xsl:value-of select="$height"/></xsl:attribute></xsl:if> <xsl:if test="$alt"><xsl:attribute name="alt"><xsl:value-of select="$alt"/></xsl:attribute><xsl:attribute name="title"><xsl:value-of select="$alt"/></xsl:attribute></xsl:if> <xsl:if test="$hspace"><xsl:attribute name="hspace"><xsl:value-of select="$hspace"/></xsl:attribute></xsl:if> <xsl:if test="$vspace"><xsl:attribute name="vspace"><xsl:value-of select="$vspace"/></xsl:attribute></xsl:if> <xsl:if test="$align"><xsl:attribute name="align"><xsl:value-of select="$align"/></xsl:attribute></xsl:if> <xsl:if test="$border"><xsl:attribute name="border"><xsl:value-of select="$border"/></xsl:attribute></xsl:if> <xsl:if test="$class"><xsl:attribute name="class"><xsl:value-of select="$class"/></xsl:attribute></xsl:if> </img> </xsl:template> <!--=========================================================================--> <xsl:variable name="pid" select="$id"/> <xsl:variable name="nam" select="$name"/> <!--=========================================================================--> <xsl:template match="HelpTopic"> <div class="help"> <xsl:call-template name="Title"/> <xsl:choose> <xsl:when test="sect1[@id=$pid]"> <xsl:apply-templates select="sect1[@id=$pid]"/> </xsl:when> <xsl:otherwise><xsl:call-template name="topic-not-found"/></xsl:otherwise> </xsl:choose> </div> </xsl:template> <!--=========================================================================--> <xsl:template match="sect1"> <xsl:choose> <xsl:when test="$nam != ''"> <table id="subcontent" width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td width="15%">Page name</td> <td><b><xsl:value-of select="title"/></b></td> </tr> <tr> <td width="15%">Form field</td> <td><xsl:apply-templates select="/HelpTopic/sect1/sect2/sect3[@id=$nam]" mode="nam"/></td> </tr> </table> </xsl:when> <xsl:otherwise> <table width="100%" id="subcontent" cellpadding="0" cellspacing="0" border="0"> <tr> <td width="15%"></td> <td> <xsl:call-template name="sect1-all"/> </td> </tr> <tr> <td width="15%"><xsl:value-of select="sect2/title"/></td> <td><xsl:apply-templates select="sect2"/></td> </tr> </table> </xsl:otherwise> </xsl:choose> </xsl:template> <!--=========================================================================--> <xsl:template name="sect1-all"> <table width="100%" id="subcontent" cellpadding="0" cellspacing="0" border="0"> <tr> <td><b><xsl:value-of select="title"/></b> <xsl:apply-templates select="para|simplelist"/> </td> </tr> </table> </xsl:template> <!--=========================================================================--> <xsl:template match="sect2"> <table width="100%" id="subcontent" cellpadding="0" cellspacing="0" border="0"> <xsl:apply-templates select="sect3"/> </table> </xsl:template> <!--=========================================================================--> <xsl:template match="sect3"> <tr> <td> <xsl:apply-templates select="title"/> <xsl:apply-templates select="para|simplelist"/> </td> </tr> </xsl:template> <!--=========================================================================--> <xsl:template match="simplelist"> <br/><div><xsl:apply-templates/></div> </xsl:template> <!--=========================================================================--> <xsl:template match="member"> <li><xsl:apply-templates select="ulink"/><xsl:value-of select="."/></li> </xsl:template> <!--=========================================================================--> <xsl:template match="ulink"> <xsl:call-template name="make_img"> <xsl:with-param name="src" select="@url"/> <xsl:with-param name="height" select="16"/> <xsl:with-param name="alt" select="@alt"/> </xsl:call-template>&nbsp; </xsl:template> <!--=========================================================================--> <xsl:template match="sect3" mode="nam"> <table width="100%" id="subcontent" cellpadding="0" cellspacing="0" border="0"> <tr> <td> <xsl:apply-templates/> </td> </tr> </table> </xsl:template> <!--=========================================================================--> <xsl:template match="title"> <b><xsl:value-of select="."/></b> </xsl:template> <!--=========================================================================--> <xsl:template match="para"> <br/><xsl:apply-templates/><br/> </xsl:template> <!--=========================================================================--> <xsl:template name="topic-not-found"> <h3>Help Topic Not Found</h3> </xsl:template> <!--=========================================================================--> <xsl:template name="Title"> <h1 class="page_title">Virtuoso Conductor Help</h1> </xsl:template> <!--=========================================================================--> </xsl:stylesheet>
{ "pile_set_name": "Github" }
``` npm install node index.js ``` and open another terminal window ``` npm run generate ``` this command with generate static file store in `./publci`, then you can go to `locahost:8000` to see the result
{ "pile_set_name": "Github" }
#ifndef MIPS3_INTF #define MIPS3_INTF #include "mips3/mips3_common.h" typedef UINT8 (*pMips3ReadByteHandler)(UINT32 a); typedef void (*pMips3WriteByteHandler)(UINT32 a, UINT8 d); typedef UINT16 (*pMips3ReadHalfHandler)(UINT32 a); typedef void (*pMips3WriteHalfHandler)(UINT32 a, UINT16 d); typedef UINT32 (*pMips3ReadWordHandler)(UINT32 a); typedef void (*pMips3WriteWordHandler)(UINT32 a, UINT32 d); typedef UINT64 (*pMips3ReadDoubleHandler)(UINT32 a); typedef void (*pMips3WriteDoubleHandler)(UINT32 a, UINT64 d); int Mips3Init(); int Mips3UseRecompiler(bool use); int Mips3Exit(); void Mips3Reset(); int Mips3Run(int cycles); unsigned int Mips3GetPC(); int Mips3MapMemory(unsigned char* pMemory, unsigned int nStart, unsigned int nEnd, int nType); int Mips3MapHandler(uintptr_t nHandler, unsigned int nStart, unsigned int nEnd, int nType); int Mips3SetReadByteHandler(int i, pMips3ReadByteHandler pHandler); int Mips3SetWriteByteHandler(int i, pMips3WriteByteHandler pHandler); int Mips3SetReadHalfHandler(int i, pMips3ReadHalfHandler pHandler); int Mips3SetWriteHalfHandler(int i, pMips3WriteHalfHandler pHandler); int Mips3SetReadWordHandler(int i, pMips3ReadWordHandler pHandler); int Mips3SetWriteWordHandler(int i, pMips3WriteWordHandler pHandler); int Mips3SetReadDoubleHandler(int i, pMips3ReadDoubleHandler pHandler); int Mips3SetWriteDoubleHandler(int i, pMips3WriteDoubleHandler pHandler); void Mips3SetIRQLine(const int line, const int state); #endif // MIPS3_INTF
{ "pile_set_name": "Github" }
<?php /** * The 'touch' command. * * The "touch" command allows a worker to request more time to work on a job. * This is useful for jobs that potentially take a long time, but you still want * the benefits of a TTR pulling a job away from an unresponsive worker. A worker * may periodically tell the server that it's still alive and processing a job * (e.g. it may do this on DEADLINE_SOON). * * @author Paul Annesley * @package Pheanstalk * @licence http://www.opensource.org/licenses/mit-license.php */ class Pheanstalk_Command_TouchCommand extends Pheanstalk_Command_AbstractCommand implements Pheanstalk_ResponseParser { private $_job; /** * @param Pheanstalk_Job $job */ public function __construct($job) { $this->_job = $job; } /* (non-phpdoc) * @see Pheanstalk_Command::getCommandLine() */ public function getCommandLine() { return sprintf('touch %d', $this->_job->getId()); } /* (non-phpdoc) * @see Pheanstalk_ResponseParser::parseRespose() */ public function parseResponse($responseLine, $responseData) { if ($responseLine == Pheanstalk_Response::RESPONSE_NOT_FOUND) { throw new Pheanstalk_Exception_ServerException(sprintf( 'Job %d %s: does not exist or is not reserved by client', $this->_job->getId(), $responseLine )); } return $this->_createResponse($responseLine); } }
{ "pile_set_name": "Github" }
#include <stdio.h> #include "Status.h" //**▲01 绪论**// /* 宏定义 */ #define N 100 //栈的容量 /* 双向栈元素类型定义 */ typedef int SElemType; /* 双向栈中包含的两个栈的栈名 */ typedef enum { Left, Right } StackName; /* 双向栈结构 */ typedef struct { SElemType stack[N]; // 用一个容量足够大的数组做栈 int top[2]; // 存放栈顶指针 } TWS; // 初始化栈 Status Inistack_3_15(TWS* tws); // 入栈,name指示向哪个栈中添加元素 Status Push_3_15(TWS* tws, StackName name, SElemType x); // 出栈,name指示从哪个栈中移除元素 Status Pop_3_15(TWS* tws, StackName name, SElemType* x); // 输出栈中元素,name指示输出哪个栈中的元素 void OutputStack(TWS tws, StackName name); int main(int argc, char* argv[]) { TWS S; int i, x; printf("████████ 初始化栈...\n"); Inistack_3_15(&S); printf("████████ 向两个栈中压入元素...\n"); for(i = 1; i <= 5; i++) { Push_3_15(&S, Left, i); Push_3_15(&S, Right, 2 * i); } printf("█ 左栈中的元素(从栈底到栈顶):"); OutputStack(S, Left); printf("█ 右栈中的元素(从栈底到栈顶):"); OutputStack(S, Right); printf("████████ 分别弹出两个栈的栈顶元素...\n"); Pop_3_15(&S, Left, &x); printf("█ 弹出左栈的栈顶元素为:%d\n", x); printf("█ 左栈中的元素(从栈底到栈顶):"); OutputStack(S, Left); Pop_3_15(&S, Right, &x); printf("█ 弹出右栈的栈顶元素为:%d\n", x); printf("█ 右栈中的元素(从栈底到栈顶):"); OutputStack(S, Right); return 0; } // 初始化栈 Status Inistack_3_15(TWS* tws) { if(tws == NULL) { return ERROR; } (*tws).top[Left] = -1; // 栈0的栈顶指针,注意不是0 (*tws).top[Right] = N; // 栈1的栈顶指针,注意不是N-1 return OK; } // 入栈,name指示向哪个栈中添加元素 Status Push_3_15(TWS* tws, StackName name, SElemType x) { if(tws == NULL) { return ERROR; } // 注意栈满条件,数组全被填充完才算栈满,不浪费空间 if((*tws).top[Left] + 1 == (*tws).top[Right]) { return ERROR; } // 先移动栈顶游标,再存入元素 switch(name) { case Left: (*tws).top[name]++; // 左边栈的游标向右移动 break; case Right: (*tws).top[name]--; // 右边栈的游标向左移动 break; default: break; } // 存入元素 (*tws).stack[(*tws).top[name]] = x; return OK; } // 出栈,name指示从哪个栈中移除元素 Status Pop_3_15(TWS* tws, StackName name, SElemType* x) { if(tws == NULL) { return ERROR; } // 先移除元素,再移动游标 switch(name) { case Left: // 判断左边的栈是否为空 if((*tws).top[name] == -1) { return ERROR; } *x = (*tws).stack[(*tws).top[name]]; (*tws).top[name]--; break; case Right: // 判断右边的栈是否为空 if((*tws).top[name] == N) { return ERROR; } *x = (*tws).stack[(*tws).top[name]]; (*tws).top[name]++; break; default: break; } return OK; } // 输出栈中元素,name指示输出哪个栈中的元素 void OutputStack(TWS tws, StackName name) { int i; switch(name) { case Left: for(i = 0; i <= tws.top[name]; i++) { printf("%d ", tws.stack[i]); } break; case Right: for(i = N - 1; i >= tws.top[name]; i--) { printf("%d ", tws.stack[i]); } break; default: break; } printf("\n"); }
{ "pile_set_name": "Github" }
ArrayList<Task> tasks; PFont roboto16, roboto20; PShape icon_menu, icon_search; void setup() { size(320, 720); loadResources(); tasks = new ArrayList<Task>(); tasks.add(new Task("asdasd")); tasks.add(new Task("asdasd")); tasks.add(new Task("asdasd")); tasks.add(new Task("asdasd")); tasks.add(new Task("asdasd")); } void draw() { background(#303030); noStroke(); fill(#FF4081); rect(0, 0, width, 56); shape(icon_menu, 16, 16); //shape(icon_search, width-icon_search.width-16, 16); fill(255); textSize(20); textFont(roboto20); textAlign(LEFT, TOP); text("Title", 72, 16); for (int i = 0; i < tasks.size(); i++) { Task t = tasks.get(i); t.y = 56*(i+1); t.update(); t.show(); } } void loadJson() { } void saveJson() { } void loadResources() { roboto16 = createFont("fonts/Roboto-Regular.ttf", 16, true); roboto20 = createFont("fonts/Roboto-Medium.ttf", 20, true); icon_menu = loadShape("icons/ic_menu_black_48px.svg"); icon_menu.scale(0.5); /* icon_search = loadShape("icons/ic_search_black_48px.svg"); icon_search.scale(0.5); */ }
{ "pile_set_name": "Github" }
// Copyright 2013 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 ssa defines a representation of the elements of Go programs // (packages, types, functions, variables and constants) using a // static single-assignment (SSA) form intermediate representation // (IR) for the bodies of functions. // // THIS INTERFACE IS EXPERIMENTAL AND IS LIKELY TO CHANGE. // // For an introduction to SSA form, see // http://en.wikipedia.org/wiki/Static_single_assignment_form. // This page provides a broader reading list: // http://www.dcs.gla.ac.uk/~jsinger/ssa.html. // // The level of abstraction of the SSA form is intentionally close to // the source language to facilitate construction of source analysis // tools. It is not intended for machine code generation. // // All looping, branching and switching constructs are replaced with // unstructured control flow. Higher-level control flow constructs // such as multi-way branch can be reconstructed as needed; see // ssautil.Switches() for an example. // // To construct an SSA-form program, call ssautil.CreateProgram on a // loader.Program, a set of type-checked packages created from // parsed Go source files. The resulting ssa.Program contains all the // packages and their members, but SSA code is not created for // function bodies until a subsequent call to (*Package).Build. // // The builder initially builds a naive SSA form in which all local // variables are addresses of stack locations with explicit loads and // stores. Registerisation of eligible locals and φ-node insertion // using dominance and dataflow are then performed as a second pass // called "lifting" to improve the accuracy and performance of // subsequent analyses; this pass can be skipped by setting the // NaiveForm builder flag. // // The primary interfaces of this package are: // // - Member: a named member of a Go package. // - Value: an expression that yields a value. // - Instruction: a statement that consumes values and performs computation. // - Node: a Value or Instruction (emphasizing its membership in the SSA value graph) // // A computation that yields a result implements both the Value and // Instruction interfaces. The following table shows for each // concrete type which of these interfaces it implements. // // Value? Instruction? Member? // *Alloc ✔ ✔ // *BinOp ✔ ✔ // *Builtin ✔ // *Call ✔ ✔ // *ChangeInterface ✔ ✔ // *ChangeType ✔ ✔ // *Const ✔ // *Convert ✔ ✔ // *DebugRef ✔ // *Defer ✔ // *Extract ✔ ✔ // *Field ✔ ✔ // *FieldAddr ✔ ✔ // *FreeVar ✔ // *Function ✔ ✔ (func) // *Global ✔ ✔ (var) // *Go ✔ // *If ✔ // *Index ✔ ✔ // *IndexAddr ✔ ✔ // *Jump ✔ // *Lookup ✔ ✔ // *MakeChan ✔ ✔ // *MakeClosure ✔ ✔ // *MakeInterface ✔ ✔ // *MakeMap ✔ ✔ // *MakeSlice ✔ ✔ // *MapUpdate ✔ // *NamedConst ✔ (const) // *Next ✔ ✔ // *Panic ✔ // *Parameter ✔ // *Phi ✔ ✔ // *Range ✔ ✔ // *Return ✔ // *RunDefers ✔ // *Select ✔ ✔ // *Send ✔ // *Slice ✔ ✔ // *Store ✔ // *Type ✔ (type) // *TypeAssert ✔ ✔ // *UnOp ✔ ✔ // // Other key types in this package include: Program, Package, Function // and BasicBlock. // // The program representation constructed by this package is fully // resolved internally, i.e. it does not rely on the names of Values, // Packages, Functions, Types or BasicBlocks for the correct // interpretation of the program. Only the identities of objects and // the topology of the SSA and type graphs are semantically // significant. (There is one exception: Ids, used to identify field // and method names, contain strings.) Avoidance of name-based // operations simplifies the implementation of subsequent passes and // can make them very efficient. Many objects are nonetheless named // to aid in debugging, but it is not essential that the names be // either accurate or unambiguous. The public API exposes a number of // name-based maps for client convenience. // // The ssa/ssautil package provides various utilities that depend only // on the public API of this package. // // TODO(adonovan): Consider the exceptional control-flow implications // of defer and recover(). // // TODO(adonovan): write a how-to document for all the various cases // of trying to determine corresponding elements across the four // domains of source locations, ast.Nodes, types.Objects, // ssa.Values/Instructions. // package ssa // import "golang.org/x/tools/go/ssa"
{ "pile_set_name": "Github" }
import * as Canvas from './modules/canvas.js'; import * as Square from './modules/square.js'; import * as Circle from './modules/circle.js'; import * as Triangle from './modules/triangle.js'; // create the canvas and reporting list let myCanvas = Canvas.create('myCanvas', document.body, 480, 320); let reportList = Canvas.createReportList(myCanvas.id); // draw a square let square1 = Square.draw(myCanvas.ctx, 50, 50, 100, 'blue'); Square.reportArea(square1.length, reportList); Square.reportPerimeter(square1.length, reportList); // draw a circle let circle1 = Circle.draw(myCanvas.ctx, 75, 200, 100, 'green'); Circle.reportArea(circle1.radius, reportList); Circle.reportPerimeter(circle1.radius, reportList); // draw a triangle let triangle1 = Triangle.draw(myCanvas.ctx, 100, 75, 190, 'yellow'); Triangle.reportArea(triangle1.length, reportList); Triangle.reportPerimeter(triangle1.length, reportList);
{ "pile_set_name": "Github" }
package watch type FileChanges struct { Modified chan bool // Channel to get notified of modifications Truncated chan bool // Channel to get notified of truncations Deleted chan bool // Channel to get notified of deletions/renames } func NewFileChanges() *FileChanges { return &FileChanges{ make(chan bool, 1), make(chan bool, 1), make(chan bool, 1)} } func (fc *FileChanges) NotifyModified() { sendOnlyIfEmpty(fc.Modified) } func (fc *FileChanges) NotifyTruncated() { sendOnlyIfEmpty(fc.Truncated) } func (fc *FileChanges) NotifyDeleted() { sendOnlyIfEmpty(fc.Deleted) } // sendOnlyIfEmpty sends on a bool channel only if the channel has no // backlog to be read by other goroutines. This concurrency pattern // can be used to notify other goroutines if and only if they are // looking for it (i.e., subsequent notifications can be compressed // into one). func sendOnlyIfEmpty(ch chan bool) { select { case ch <- true: default: } }
{ "pile_set_name": "Github" }
/* * Streams.cpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN and VLC authors * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "Streams.hpp" #include "logic/AbstractAdaptationLogic.h" #include "http/HTTPConnection.hpp" #include "http/HTTPConnectionManager.h" #include "playlist/BaseAdaptationSet.h" #include "playlist/BaseRepresentation.h" #include "playlist/SegmentChunk.hpp" #include "plumbing/SourceStream.hpp" #include "plumbing/CommandsQueue.hpp" #include "tools/FormatNamespace.hpp" #include "tools/Debug.hpp" #include <vlc_demux.h> #include <algorithm> using namespace adaptive; using namespace adaptive::http; AbstractStream::AbstractStream(demux_t * demux_) { p_realdemux = demux_; format = StreamFormat::UNKNOWN; currentChunk = NULL; eof = false; valid = true; disabled = false; discontinuity = false; needrestart = false; inrestart = false; demuxfirstchunk = false; segmentTracker = NULL; demuxersource = NULL; demuxer = NULL; fakeesout = NULL; notfound_sequence = 0; last_buffer_status = buffering_lessthanmin; vlc_mutex_init(&lock); } bool AbstractStream::init(const StreamFormat &format_, SegmentTracker *tracker, AbstractConnectionManager *conn) { /* Don't even try if not supported or already init */ if((unsigned)format_ == StreamFormat::UNSUPPORTED || demuxersource) return false; demuxersource = new (std::nothrow) BufferedChunksSourceStream( VLC_OBJECT(p_realdemux), this ); if(demuxersource) { CommandsFactory *factory = new (std::nothrow) CommandsFactory(); if(factory) { CommandsQueue *commandsqueue = new (std::nothrow) CommandsQueue(factory); if(commandsqueue) { fakeesout = new (std::nothrow) FakeESOut(p_realdemux->out, commandsqueue); if(fakeesout) { /* All successfull */ fakeesout->setExtraInfoProvider( this ); const Role & streamRole = tracker->getStreamRole(); if(streamRole.isDefault() && streamRole.autoSelectable()) fakeesout->setPriority(ES_PRIORITY_MIN + 10); else if(!streamRole.autoSelectable()) fakeesout->setPriority(ES_PRIORITY_NOT_DEFAULTABLE); format = format_; segmentTracker = tracker; segmentTracker->registerListener(this); segmentTracker->notifyBufferingState(true); connManager = conn; fakeesout->setExpectedTimestamp(segmentTracker->getPlaybackTime()); declaredCodecs(); return true; } delete commandsqueue; commandsqueue = NULL; } else { delete factory; } } delete demuxersource; } return false; } AbstractStream::~AbstractStream() { delete currentChunk; if(segmentTracker) segmentTracker->notifyBufferingState(false); delete segmentTracker; delete demuxer; delete demuxersource; delete fakeesout; } void AbstractStream::prepareRestart(bool b_discontinuity) { if(demuxer) { /* Enqueue Del Commands for all current ES */ demuxer->drain(); fakeEsOut()->resetTimestamps(); /* Enqueue Del Commands for all current ES */ fakeEsOut()->scheduleAllForDeletion(); if(b_discontinuity) fakeEsOut()->schedulePCRReset(); fakeEsOut()->commandsQueue()->Commit(); /* ignoring demuxer's own Del commands */ fakeEsOut()->commandsQueue()->setDrop(true); delete demuxer; fakeEsOut()->commandsQueue()->setDrop(false); demuxer = NULL; } } void AbstractStream::setLanguage(const std::string &lang) { language = lang; } void AbstractStream::setDescription(const std::string &desc) { description = desc; } vlc_tick_t AbstractStream::getPCR() const { vlc_mutex_locker locker(&lock); if(!valid || disabled) return VLC_TICK_INVALID; return fakeEsOut()->commandsQueue()->getPCR(); } vlc_tick_t AbstractStream::getMinAheadTime() const { if(!segmentTracker) return 0; return segmentTracker->getMinAheadTime(); } vlc_tick_t AbstractStream::getFirstDTS() const { vlc_mutex_locker locker(&lock); if(!valid || disabled) return VLC_TICK_INVALID; vlc_tick_t dts = fakeEsOut()->commandsQueue()->getFirstDTS(); if(dts == VLC_TICK_INVALID) dts = fakeEsOut()->commandsQueue()->getPCR(); return dts; } int AbstractStream::esCount() const { return fakeEsOut()->esCount(); } bool AbstractStream::seekAble() const { bool restarting = fakeEsOut()->restarting(); bool draining = fakeEsOut()->commandsQueue()->isDraining(); bool eof = fakeEsOut()->commandsQueue()->isEOF(); msg_Dbg(p_realdemux, "demuxer %p, fakeesout restarting %d, " "discontinuity %d, commandsqueue draining %d, commandsqueue eof %d", static_cast<void *>(demuxer), restarting, discontinuity, draining, eof); if(!valid || restarting || discontinuity || (!eof && draining)) { msg_Warn(p_realdemux, "not seekable"); return false; } else { return true; } } bool AbstractStream::isSelected() const { return fakeEsOut()->hasSelectedEs(); } bool AbstractStream::reactivate(vlc_tick_t basetime) { vlc_mutex_locker locker(&lock); if(setPosition(basetime, false)) { setDisabled(false); return true; } else { eof = true; /* can't reactivate */ return false; } } bool AbstractStream::startDemux() { if(demuxer) return false; demuxersource->Reset(); demuxer = createDemux(format); if(!demuxer && format != StreamFormat()) msg_Err(p_realdemux, "Failed to create demuxer %p %s", (void *)demuxer, format.str().c_str()); demuxfirstchunk = true; return !!demuxer; } bool AbstractStream::restartDemux() { bool b_ret = true; if(!demuxer) { fakeesout->recycleAll(); b_ret = startDemux(); } else if(demuxer->needsRestartOnSeek()) { inrestart = true; /* Push all ES as recycling candidates */ fakeEsOut()->recycleAll(); /* Restart with ignoring es_Del pushes to queue when terminating demux */ fakeEsOut()->commandsQueue()->setDrop(true); demuxer->destroy(); fakeEsOut()->commandsQueue()->setDrop(false); b_ret = demuxer->create(); inrestart = false; } else { fakeEsOut()->commandsQueue()->Commit(); } return b_ret; } void AbstractStream::setDisabled(bool b) { if(disabled != b) segmentTracker->notifyBufferingState(!b); disabled = b; } bool AbstractStream::isValid() const { vlc_mutex_locker locker(&lock); return valid; } bool AbstractStream::isDisabled() const { vlc_mutex_locker locker(&lock); return disabled; } bool AbstractStream::decodersDrained() { return fakeEsOut()->decodersDrained(); } AbstractStream::buffering_status AbstractStream::getLastBufferStatus() const { return last_buffer_status; } vlc_tick_t AbstractStream::getDemuxedAmount(vlc_tick_t from) const { return fakeEsOut()->commandsQueue()->getDemuxedAmount(from); } AbstractStream::buffering_status AbstractStream::bufferize(vlc_tick_t nz_deadline, vlc_tick_t i_min_buffering, vlc_tick_t i_extra_buffering, bool b_keep_alive) { last_buffer_status = doBufferize(nz_deadline, i_min_buffering, i_extra_buffering, b_keep_alive); return last_buffer_status; } AbstractStream::buffering_status AbstractStream::doBufferize(vlc_tick_t nz_deadline, vlc_tick_t i_min_buffering, vlc_tick_t i_extra_buffering, bool b_keep_alive) { vlc_mutex_lock(&lock); /* Ensure it is configured */ if(!segmentTracker || !connManager || !valid) { vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } /* Disable streams that are not selected (alternate streams) */ if(esCount() && !isSelected() && !fakeEsOut()->restarting() && !b_keep_alive) { setDisabled(true); segmentTracker->reset(); fakeEsOut()->commandsQueue()->Abort(false); msg_Dbg(p_realdemux, "deactivating %s stream %s", format.str().c_str(), description.c_str()); vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } if(fakeEsOut()->commandsQueue()->isDraining()) { vlc_mutex_unlock(&lock); return AbstractStream::buffering_suspended; } segmentTracker->setStartPosition(); /* Reached end of live playlist */ if(!segmentTracker->bufferingAvailable()) { vlc_mutex_unlock(&lock); return AbstractStream::buffering_suspended; } if(!demuxer) { format = segmentTracker->getCurrentFormat(); if(!startDemux()) { /* If demux fails because of probing failure / wrong format*/ if(discontinuity) { msg_Dbg( p_realdemux, "Draining on format change" ); prepareRestart(); discontinuity = false; fakeEsOut()->commandsQueue()->setDraining(); vlc_mutex_unlock(&lock); return AbstractStream::buffering_ongoing; } valid = false; /* Prevent further retries */ fakeEsOut()->commandsQueue()->setEOF(true); vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } } const vlc_tick_t i_total_buffering = i_min_buffering + i_extra_buffering; vlc_tick_t i_demuxed = fakeEsOut()->commandsQueue()->getDemuxedAmount(nz_deadline); segmentTracker->notifyBufferingLevel(i_min_buffering, i_demuxed, i_total_buffering); if(i_demuxed < i_total_buffering) /* not already demuxed */ { vlc_tick_t nz_extdeadline = fakeEsOut()->commandsQueue()->getBufferingLevel() + (i_total_buffering - i_demuxed) / 4; nz_deadline = std::max(nz_deadline, nz_extdeadline); /* need to read, demuxer still buffering, ... */ vlc_mutex_unlock(&lock); Demuxer::Status demuxStatus = demuxer->demux(nz_deadline); vlc_mutex_lock(&lock); if(demuxStatus != Demuxer::Status::STATUS_SUCCESS) { if(discontinuity || needrestart) { msg_Dbg(p_realdemux, "Restarting demuxer"); prepareRestart(discontinuity); if(discontinuity) { msg_Dbg(p_realdemux, "Draining on discontinuity"); fakeEsOut()->commandsQueue()->setDraining(); discontinuity = false; } needrestart = false; vlc_mutex_unlock(&lock); return AbstractStream::buffering_ongoing; } fakeEsOut()->commandsQueue()->setEOF(true); vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } i_demuxed = fakeEsOut()->commandsQueue()->getDemuxedAmount(nz_deadline); segmentTracker->notifyBufferingLevel(i_min_buffering, i_demuxed, i_total_buffering); } vlc_mutex_unlock(&lock); if(i_demuxed < i_total_buffering) /* need to read more */ { if(i_demuxed < i_min_buffering) return AbstractStream::buffering_lessthanmin; /* high prio */ return AbstractStream::buffering_ongoing; } return AbstractStream::buffering_full; } AbstractStream::status AbstractStream::dequeue(vlc_tick_t nz_deadline, vlc_tick_t *pi_pcr) { vlc_mutex_locker locker(&lock); *pi_pcr = nz_deadline; if(fakeEsOut()->commandsQueue()->isDraining()) { AdvDebug(vlc_tick_t pcrvalue = fakeEsOut()->commandsQueue()->getPCR(); vlc_tick_t dtsvalue = fakeEsOut()->commandsQueue()->getFirstDTS(); msg_Dbg(p_realdemux, "Stream %s pcr %" PRId64 " dts %" PRId64 " deadline %" PRId64 " [DRAINING]", description.c_str(), pcrvalue, dtsvalue, nz_deadline)); *pi_pcr = fakeEsOut()->commandsQueue()->Process(p_realdemux->out, VLC_TICK_0 + nz_deadline); if(!fakeEsOut()->commandsQueue()->isEmpty()) return AbstractStream::status_demuxed; if(!fakeEsOut()->commandsQueue()->isEOF()) { fakeEsOut()->commandsQueue()->Abort(true); /* reset buffering level and flags */ return AbstractStream::status_discontinuity; } } if(!valid || disabled || fakeEsOut()->commandsQueue()->isEOF()) { *pi_pcr = nz_deadline; return AbstractStream::status_eof; } vlc_tick_t bufferingLevel = fakeEsOut()->commandsQueue()->getBufferingLevel(); AdvDebug(vlc_tick_t pcrvalue = fakeEsOut()->commandsQueue()->getPCR(); vlc_tick_t dtsvalue = fakeEsOut()->commandsQueue()->getFirstDTS(); msg_Dbg(p_realdemux, "Stream %s pcr %" PRId64 " dts %" PRId64 " deadline %" PRId64 " buflevel %" PRId64, description.c_str(), pcrvalue, dtsvalue, nz_deadline, bufferingLevel)); if(nz_deadline + VLC_TICK_0 <= bufferingLevel) /* demuxed */ { *pi_pcr = fakeEsOut()->commandsQueue()->Process( p_realdemux->out, VLC_TICK_0 + nz_deadline ); return AbstractStream::status_demuxed; } return AbstractStream::status_buffering; } std::string AbstractStream::getContentType() { if (currentChunk == NULL && !eof) { const bool b_restarting = fakeEsOut()->restarting(); currentChunk = segmentTracker->getNextChunk(!b_restarting, connManager); } if(currentChunk) return currentChunk->getContentType(); else return std::string(); } block_t * AbstractStream::readNextBlock() { if (currentChunk == NULL && !eof) { const bool b_restarting = fakeEsOut()->restarting(); currentChunk = segmentTracker->getNextChunk(!b_restarting, connManager); } if(discontinuity && demuxfirstchunk) { /* clear up discontinuity on demux start (discontinuity on start segment bug) */ discontinuity = false; } if(discontinuity || needrestart) { msg_Info(p_realdemux, "Encountered discontinuity"); /* Force stream/demuxer to end for this call */ return NULL; } if(currentChunk == NULL) { eof = true; return NULL; } const bool b_segment_head_chunk = (currentChunk->getBytesRead() == 0); block_t *block = currentChunk->readBlock(); if(block == NULL) { if(currentChunk->getRequestStatus() == RequestStatus::NotFound && ++notfound_sequence < 3) { discontinuity = true; } delete currentChunk; currentChunk = NULL; return NULL; } else notfound_sequence = 0; demuxfirstchunk = false; if (currentChunk->isEmpty()) { delete currentChunk; currentChunk = NULL; } block = checkBlock(block, b_segment_head_chunk); return block; } bool AbstractStream::setPosition(vlc_tick_t time, bool tryonly) { if(!seekAble()) return false; bool b_needs_restart = demuxer ? demuxer->needsRestartOnSeek() : true; bool ret = segmentTracker->setPositionByTime(time, b_needs_restart, tryonly); if(!tryonly && ret) { // clear eof flag before restartDemux() to prevent readNextBlock() fail eof = false; demuxfirstchunk = true; notfound_sequence = 0; if(b_needs_restart) { if(currentChunk) delete currentChunk; currentChunk = NULL; needrestart = false; fakeEsOut()->resetTimestamps(); vlc_tick_t seekMediaTime = segmentTracker->getPlaybackTime(true); fakeEsOut()->setExpectedTimestamp(seekMediaTime); if( !restartDemux() ) { msg_Info(p_realdemux, "Restart demux failed"); eof = true; valid = false; ret = false; } else { fakeEsOut()->commandsQueue()->setEOF(false); } } else fakeEsOut()->commandsQueue()->Abort( true ); // in some cases, media time seek != sent dts // es_out_Control(p_realdemux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, // VLC_TICK_0 + time); } return ret; } bool AbstractStream::getMediaPlaybackTimes(vlc_tick_t *start, vlc_tick_t *end, vlc_tick_t *length, vlc_tick_t *mediaStart, vlc_tick_t *demuxStart) const { return (segmentTracker->getMediaPlaybackRange(start, end, length) && fakeEsOut()->getStartTimestamps(mediaStart, demuxStart)); } void AbstractStream::runUpdates() { if(valid && !disabled) segmentTracker->updateSelected(); } void AbstractStream::fillExtraFMTInfo( es_format_t *p_fmt ) const { if(!p_fmt->psz_language && !language.empty()) p_fmt->psz_language = strdup(language.c_str()); if(!p_fmt->psz_description && !description.empty()) p_fmt->psz_description = strdup(description.c_str()); } AbstractDemuxer * AbstractStream::createDemux(const StreamFormat &format) { AbstractDemuxer *ret = newDemux( VLC_OBJECT(p_realdemux), format, (es_out_t *)fakeEsOut(), demuxersource ); if(ret && !ret->create()) { delete ret; ret = NULL; } else fakeEsOut()->commandsQueue()->Commit(); return ret; } AbstractDemuxer *AbstractStream::newDemux(vlc_object_t *p_obj, const StreamFormat &format, es_out_t *out, AbstractSourceStream *source) const { AbstractDemuxer *ret = NULL; switch((unsigned)format) { case StreamFormat::MP4: ret = new Demuxer(p_obj, "mp4", out, source); break; case StreamFormat::MPEG2TS: ret = new Demuxer(p_obj, "ts", out, source); break; default: case StreamFormat::UNSUPPORTED: break; } return ret; } void AbstractStream::trackerEvent(const SegmentTrackerEvent &event) { switch(event.type) { case SegmentTrackerEvent::DISCONTINUITY: discontinuity = true; break; case SegmentTrackerEvent::FORMATCHANGE: /* Check if our current demux is still valid */ if(*event.u.format.f != format || format == StreamFormat(StreamFormat::UNKNOWN)) { /* Format has changed between segments, we need to drain and change demux */ msg_Info(p_realdemux, "Changing stream format %s -> %s", format.str().c_str(), event.u.format.f->str().c_str()); format = *event.u.format.f; /* This is an implict discontinuity */ discontinuity = true; } break; case SegmentTrackerEvent::SWITCHING: if(demuxer && !inrestart) { if(!demuxer->bitstreamSwitchCompatible() || (event.u.switching.next && !event.u.switching.next->getAdaptationSet()->isBitSwitchable())) needrestart = true; } break; case SegmentTrackerEvent::SEGMENT_CHANGE: if(demuxer && demuxer->needsRestartOnEachSegment() && !inrestart) { needrestart = true; } break; default: break; } } static void add_codec_string_from_fourcc(vlc_fourcc_t fourcc, std::list<std::string> &codecs) { std::string codec; codec.insert(0, reinterpret_cast<const char *>(&fourcc), 4); codecs.push_back(codec); } void AbstractStream::declaredCodecs() { const std::string & streamDesc = segmentTracker->getStreamDescription(); const std::string & streamLang = segmentTracker->getStreamLanguage(); std::list<std::string> codecs = segmentTracker->getCurrentCodecs(); if(codecs.empty()) { const StreamFormat format = segmentTracker->getCurrentFormat(); switch(format) { case StreamFormat::TTML: add_codec_string_from_fourcc(VLC_CODEC_TTML, codecs); break; case StreamFormat::WEBVTT: add_codec_string_from_fourcc(VLC_CODEC_WEBVTT, codecs); break; default: break; } } for(std::list<std::string>::const_iterator it = codecs.begin(); it != codecs.end(); ++it) { FormatNamespace fnsp(*it); es_format_t fmt; es_format_Init(&fmt, fnsp.getFmt()->i_cat, fnsp.getFmt()->i_codec); es_format_Copy(&fmt, fnsp.getFmt()); if(!streamLang.empty()) fmt.psz_language = strdup(streamLang.c_str()); if(!streamDesc.empty()) fmt.psz_description = strdup(streamDesc.c_str()); fakeEsOut()->declareEs( &fmt ); es_format_Clean(&fmt); } } FakeESOut::LockedFakeEsOut AbstractStream::fakeEsOut() { return fakeesout->WithLock(); } FakeESOut::LockedFakeEsOut AbstractStream::fakeEsOut() const { return fakeesout->WithLock(); }
{ "pile_set_name": "Github" }
# Natural Language Tools ## Update This project is being merged into Natural, Visit [https://github.com/NaturalNode/natural](https://github.com/NaturalNode/natural) for the latest changes. ## Abstract After leaning about IBM's Watson *1, and reading Mind vs Machine *2, I wanted to better understand the state of Natural Language Processing, Artificial Intelligence and Natural Language Generation. This project is not a port of any existing libraries, although it does contain some code ported from Pythons NLTK, it serves more of a glue layer between existing tools, ideas and projects already used today. * 1 http://en.wikipedia.org/wiki/Watson_(artificial_intelligence_software) * 2 http://www.theatlantic.com/magazine/archive/2011/03/mind-vs-machine/8386/ ## Setup Download, fork or clone the code, setup the 2 dependancies below. * To use the POS Tagger download and install from http://code.google.com/p/hunpos/ * To use the Named Entity Tagger download and install from http://nlp.stanford.edu/software/CRF-NER.shtml ## What's Included ### Tokenization - SpaceTokenizer - TabTokenizer - RegexpTokenizer - WordTokenizer - WordPunctTokenizer (new) - TreeBank Tokenizer (new) ### POS Tagger (Parts of Speech Tagger) - HunposTagger - Project Home http://code.google.com/p/hunpos/ (DEPENDANCY) - 38 POS Tags http://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html ### NE Tagger (Named Entity Tagger) - The Stanford Named Entity Recognizer - http://nlp.stanford.edu/software/CRF-NER.shtml (DEPENDANCY) - Download and run the Java Server - java -mx600m -cp stanford-ner.jar edu.stanford.nlp.ie.NERServer -loadClassifier classifiers/ner-eng-ie.crf-4-conll-distsim.ser.gz -port 8000 ### Sentence Analyses - Break a sentence down into different parts, subject, predicate etc. ### Stemmer - Using the Porter Stemming Algorithm. - More information about the algorithm can be found here - http://tartarus.org/~martin/PorterStemmer/. ### TF-IDF (term frequency–inverse document frequency) - http://en.wikipedia.org/wiki/Tf%E2%80%93idf ### n-gram - http://en.wikipedia.org/wiki/N-gram - bigrams - trigrams `Util.bigram(['The','fox','ran','fast']); // [ [ 'The', 'fox' ],[ 'fox', 'ran' ],[ 'ran', 'fast' ] ] Util.trigram(['The','fox','ran','fast']); // [ [ 'The', 'fox', 'ran' ], [ 'fox', 'ran', 'fast' ] ]` ### Wordnet Bindings - Wordnet bindings have been started, you must download the wordnet database before you can play with it. ## What's Not yet Included aka TODO ### Sentence Boundary Detection - http://www.attivio.com/blog/57-unified-information-access/263-doing-things-with-words-part-two-sentence-boundary-detection.html - NLTK Source http://code.google.com/p/nltk/source/browse/trunk/nltk/nltk/tokenize/punkt.py ### Sentiment Analysis - http://en.wikipedia.org/wiki/Sentiment_analysis ### Bayes' theorem - http://en.wikipedia.org/wiki/Bayes'_theorem ### NLU #### Implement YAGO This is started and well underway - http://www.mpi-inf.mpg.de/yago-naga/yago/ #### DBPedia Bindings ## Other NODE Projects of Interest - http://harthur.github.com/brain/ ## MIT License Copyright (c) 2011 Rob Ellis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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.
{ "pile_set_name": "Github" }
9 10 11 12 13 7 8 9 10 11
{ "pile_set_name": "Github" }
--- title: 程序员如何切入区块链去中心化应用开发 permalink: devDapp date: 2018-08-31 11:30:55 categories: - 以太坊 - Dapp tags: - Dapp入门 - 以太坊概念 author: Tiny熊 --- 前段时间一个以太坊游戏应用:[Fomo3D](http://exitscam.me/play)异常火爆,在短短的几天内就吸引了几万的以太币投入游戏,第一轮游戏一个“黑客”用了一个非常巧妙的利用以太坊规则成为了最终赢家,拿走了1万多以太币奖金。 区块链应用的价值由这个游戏反映的淋漓尽致,Fomo3D游戏能够成功核心所依赖的是以太坊提供的一个可信、不可篡改平台。当游戏的规则确定之后,一切都按规则运行,无人可干预。今天这篇就来介绍一下程序员如何切入去中心化应用开发。 <!-- more --> ## 中心化应用 作为对比,先来看看中心化应用,其实就是现有的互联网应用,为什么它是中心化应用,看看它的架构图: ![](https://img.learnblockchain.cn/2018/capp.jpg!wl) 平时我们接触的是应用的前端(或称客户端),前端可以是HTML5的web页面、 小程序、APP, 在前端展现的内容通常发送一个请求到服务器,服务器返回相应的内容给前端。在前端的动作同样也会转化请求发送到服务器,服务器处理之后返回数据到前端。也就是说我们所有看到的内容或者操作都是中心化的服务器控制,因此说是中心化应用。 ## 去中心化应用DAPP 而去中心化应用有什么不同呢? 看看它的架构图: ![](https://img.learnblockchain.cn/2018/dapp.jpg!wl) 前端的表现上是一样的, 还是H5页面、 小程序、APP,DAPP和传统App关键是后端部分不同,是后端不再是一个中心化的服务器,而是分布式网络上任意节点,注意可以是 **任意一个节点**,在应用中给节点发送的请求通常称为 **交易**,交易和中心化下的请求有几个很大的不同是:交易的数据经过用户个人签名之后发送到节点,节点收到交易请求之后,会把 **请求广播到整个网络**,交易在网络达成共识之后,才算是真正的执行(真正其作用的执行不一是连接的后端节点,尽管后端也会执行)。以及中心化下的请求大多数都是同步的(及时拿到结果), 而交易大多数是异步的,这也是在开发去中心应用时需要注意的地方, 从节点上获得数据状态(比如交易的结果),一般是通过事件回调来获得。 ## 如何开发 在开发中心化应用最重要两部分是 **客户端UI表现**和 **后端服务程序**, UI表现通过HTTP请求连接到后端服务程序,后端服务程序运行在服务器上,比如Nginx Apached等等。 开发一个去中心化应用最重要也是两部分: **客户端UI表现**及 **智能合约**,智能合约的作用就像后端服务程序,智能合约是运行在节点的EVM上, 客户端调用智能合约,是通过向节点发起RPC请求完成。 下面是一个对比: 客户端UI <=> 客户端UI HTTP <=> RPC 后端服务程序 <=> 智能合约 Nginx/Apache <=> 节点 因此对于去中心化应用来说,程序员可以从两个方面切入: 一个是 **去中心化应用的客户端开发**, 熟悉已经熟悉客户端软件(如Web\APP等)开发的同学,只需要了解一下客户端跟区块链节点通信的API接口,如果是在当前应用最广泛的区块链平台以太坊上开发去中心化应用,那么需要了解Web3 这个库,Web3对节点暴露出来的JSON-RPC接口进行了封装,比如Web3提供的功能有:获取节点状态,获取账号信息,调用合约、监听合约事件等等。 目前的主流语言都有Web3的实现,列举一些实现给大家参考: * [JavaScript Web3.js](https://github.com/ethereum/web3.js) * [Python Web3.py](https://github.com/ethereum/web3.py) * [Haskell hs-web3](https://github.com/airalab/hs-web3) * [Java web3j](https://github.com/web3j/web3j) * [Scala web3j-scala](https://github.com/mslinn/web3j-scala) * [Purescript purescript-web3](https://github.com/f-o-a-m/purescript-web3) * [PHP web3.php](https://github.com/sc0Vu/web3.php) * [PHP ethereum-php](https://github.com/digitaldonkey/ethereum-php) 另一个切入点是 **智能合约的开发**,在以太坊现在推荐的语言是Solidity,有一些同学对新学一门语言有一些畏惧,Solidity的语法其实很简洁,有过一两门其他语言基础(开发经验)的同学三五天就可以学会。 下面用一个Hello合约,体会下Solidity的语法: ```js contract Hello { function hello() public returns(string) { return "Hello World"; } } ``` 如果把上面的contract关键字更改为class,就和其他语言定义一个类一样。 有兴趣的同学可以进一步学习一下这个DApp开发案例[Web3与智能合约交互实战](https://learnblockchain.cn/2018/04/15/web3-html/), 在DAPP的开发过程中,一些开发工具可以帮助我们事半功倍,如:Truffle开发框架以及Ganache工具来模拟节点等,这篇文章[一步步教你开发、部署第一个去中心化应用](https://learnblockchain.cn/2018/01/12/first-dapp/) 另外强烈安利两门课程给大家: 1. [深入详解以太坊智能合约语言Solidity](https://ke.qq.com/course/326528)。 2. [以太坊DAPP开发实战](https://ke.qq.com/course/335169) - 轻轻松松学会DAPP开发 ## 补充 对于想切入到去中心化应用开发的同学,对区块链运行的原理了解肯定会是加分项,尤其是各类共识机制([POW](https://learnblockchain.cn/2017/11/04/bitcoin-pow/),POS,DPOS等)的理解,P2P网络的理解,以及各类加密和Hash算法的运用。有一些同学想做区块链底层开发,对区块链运行的原理则是必须项。 欢迎来[知识星球](https://learnblockchain.cn/images/zsxq.png)提问,星球内已经聚集了300多位区块链技术爱好者。 [深入浅出区块链](https://learnblockchain.cn/) - 系统学习区块链,打造最好的区块链技术博客。
{ "pile_set_name": "Github" }
from enthought.tvtk.api import tvtk cone = tvtk.ConeSource( height=3.0, radius=1.0, resolution=10 ) cone_mapper = tvtk.PolyDataMapper( input = cone.output ) cone_actor = tvtk.Actor( mapper=cone_mapper ) cone_actor.property.representation = "w" ren1 = tvtk.Renderer() ren1.add_actor( cone_actor ) ren1.background = 0.1, 0.2, 0.4 ren_win = tvtk.RenderWindow() ren_win.add_renderer( ren1 ) ren_win.size = 300, 300 iren = tvtk.RenderWindowInteractor( render_window = ren_win ) iren.initialize() iren.start()
{ "pile_set_name": "Github" }
/* * Creation : 20 avr. 2015 */ package org.sonar.samples.java; import org.slf4j.Logger; /** * A class with extends another class outside the JVM but in classpath */ public class AvoidSuperClassCheck extends Logger { // Noncompliant {{The usage of super class org.slf4j.Logger is forbidden}} protected AvoidSuperClassCheck(String name) { super(name); } }
{ "pile_set_name": "Github" }
module mkncdio !----------------------------------------------------------------------- !BOP ! ! !MODULE: mkncdio ! ! !DESCRIPTION: ! Generic interfaces to write fields to netcdf files, and other useful netcdf operations ! ! !USES: use shr_kind_mod , only : r8 => shr_kind_r8 use shr_sys_mod , only : shr_sys_flush ! ! !PUBLIC TYPES: implicit none include 'netcdf.inc' save private public :: check_ret ! checks return status of netcdf calls public :: ncd_defvar ! define netCDF input variable public :: ncd_def_spatial_var ! define spatial netCDF variable (convenience wrapper to ncd_defvar) public :: ncd_put_time_slice ! write a single time slice of a variable public :: get_dim_lengths ! get dimension lengths of a netcdf variable interface ncd_def_spatial_var module procedure ncd_def_spatial_var_0lev module procedure ncd_def_spatial_var_1lev module procedure ncd_def_spatial_var_2lev end interface ncd_def_spatial_var interface ncd_put_time_slice module procedure ncd_put_time_slice_1d module procedure ncd_put_time_slice_2d end interface ncd_put_time_slice public :: convert_latlon ! convert a latitude or longitude variable to degrees E / N ! ! !REVISION HISTORY: ! ! ! !PRIVATE MEMBER FUNCTIONS: ! private :: get_time_slice_beg_and_len ! determine beg and len vectors for writing a time slice logical :: masterproc = .true. ! always use 1 proc real(r8) :: spval = 1.e36 ! special value public :: nf_open public :: nf_close public :: nf_write public :: nf_sync public :: nf_inq_attlen public :: nf_inq_dimlen public :: nf_inq_dimname public :: nf_inq_varid public :: nf_inq_varndims public :: nf_inq_vardimid public :: nf_get_att_double public :: nf_get_att_text public :: nf_get_var_double public :: nf_get_vara_double public :: nf_get_var_int public :: nf_get_vara_int public :: nf_put_var_double public :: nf_put_vara_double public :: nf_put_var_int public :: nf_put_vara_int public :: nf_inq_dimid public :: nf_max_name public :: nf_max_var_dims public :: nf_noerr public :: nf_nowrite public :: nf_enotatt public :: nf_strerror !EOP !----------------------------------------------------------------------- contains !----------------------------------------------------------------------- !BOP ! ! !IROUTINE: check_ret ! ! !INTERFACE: subroutine check_ret(ret, calling, varexists) ! ! !DESCRIPTION: ! Check return status from netcdf call ! ! !ARGUMENTS: implicit none integer, intent(in) :: ret character(len=*) :: calling logical, intent(out), optional :: varexists ! ! !REVISION HISTORY: ! !EOP !----------------------------------------------------------------------- if ( present(varexists) ) varexists = .true. if ( present(varexists) .and. ret == NF_ENOTVAR )then varexists = .false. else if (ret /= NF_NOERR) then write(6,*)'netcdf error from ',trim(calling), ' rcode = ', ret, & ' error = ', NF_STRERROR(ret) call abort() end if end subroutine check_ret !----------------------------------------------------------------------- !BOP ! ! !IROUTINE: ncd_defvar ! ! !INTERFACE: subroutine ncd_defvar(ncid, varname, xtype, & dim1name, dim2name, dim3name, dim4name, dim5name, & long_name, units, cell_method, missing_value, fill_value, & imissing_value, ifill_value) ! ! !DESCRIPTION: ! Define a netcdf variable ! ! !ARGUMENTS: implicit none integer , intent(in) :: ncid ! input unit character(len=*), intent(in) :: varname ! variable name integer , intent(in) :: xtype ! external type character(len=*), intent(in), optional :: dim1name ! dimension name character(len=*), intent(in), optional :: dim2name ! dimension name character(len=*), intent(in), optional :: dim3name ! dimension name character(len=*), intent(in), optional :: dim4name ! dimension name character(len=*), intent(in), optional :: dim5name ! dimension name character(len=*), intent(in), optional :: long_name ! attribute character(len=*), intent(in), optional :: units ! attribute character(len=*), intent(in), optional :: cell_method ! attribute real(r8) , intent(in), optional :: missing_value ! attribute for real real(r8) , intent(in), optional :: fill_value ! attribute for real integer , intent(in), optional :: imissing_value ! attribute for int integer , intent(in), optional :: ifill_value ! attribute for int ! ! !REVISION HISTORY: ! ! ! !LOCAL VARIABLES: !EOP integer :: n ! indices integer :: ndims ! dimension counter integer :: dimid(5) ! dimension ids integer :: varid ! variable id integer :: itmp ! temporary character(len=256) :: str ! temporary character(len=32) :: subname='NCD_DEFVAR_REAL' ! subroutine name !----------------------------------------------------------------------- if (.not. masterproc) return ! Determine dimension ids for variable dimid(:) = 0 if (present(dim1name)) then call check_ret(nf_inq_dimid(ncid, dim1name, dimid(1)), subname) end if if (present(dim2name)) then call check_ret(nf_inq_dimid(ncid, dim2name, dimid(2)), subname) end if if (present(dim3name)) then call check_ret(nf_inq_dimid(ncid, dim3name, dimid(3)), subname) end if if (present(dim4name)) then call check_ret(nf_inq_dimid(ncid, dim4name, dimid(4)), subname) end if if (present(dim5name)) then call check_ret(nf_inq_dimid(ncid, dim5name, dimid(5)), subname) end if ! Define variable if (present(dim1name)) then ndims = 0 do n = 1, size(dimid) if (dimid(n) /= 0) ndims = ndims + 1 end do call check_ret(nf_def_var(ncid, trim(varname), xtype, ndims, dimid(1:ndims), varid), subname) else call check_ret(nf_def_var(ncid, varname, xtype, 0, 0, varid), subname) end if if (present(long_name)) then call check_ret(nf_put_att_text(ncid, varid, 'long_name', len_trim(long_name), trim(long_name)), subname) end if if (present(units)) then call check_ret(nf_put_att_text(ncid, varid, 'units', len_trim(units), trim(units)), subname) end if if (present(cell_method)) then str = 'time: ' // trim(cell_method) call check_ret(nf_put_att_text(ncid, varid, 'cell_method', len_trim(str), trim(str)), subname) end if if (present(fill_value)) then call check_ret(nf_put_att_double(ncid, varid, '_FillValue', xtype, 1, fill_value), subname) end if if (present(missing_value)) then call check_ret(nf_put_att_double(ncid, varid, 'missing_value', xtype, 1, missing_value), subname) end if if (present(ifill_value)) then call check_ret(nf_put_att_int(ncid, varid, '_FillValue', xtype, 1, ifill_value), subname) end if if (present(imissing_value)) then call check_ret(nf_put_att_int(ncid, varid, 'missing_value', xtype, 1, imissing_value), subname) end if end subroutine ncd_defvar ! ======================================================================== ! ncd_def_spatial_var routines: define a spatial netCDF variable (convenience wrapper to ! ncd_defvar) ! ======================================================================== !----------------------------------------------------------------------- subroutine ncd_def_spatial_var_0lev(ncid, varname, xtype, long_name, units) ! ! !DESCRIPTION: ! Define a spatial netCDF variable (convenience wrapper to ncd_defvar) ! ! The variable in question has ONLY spatial dimensions (no level or time dimensions) ! ! !USES: use mkvarctl, only : outnc_1d ! ! !ARGUMENTS: integer , intent(in) :: ncid ! input unit character(len=*) , intent(in) :: varname ! variable name integer , intent(in) :: xtype ! external type character(len=*) , intent(in) :: long_name ! attribute character(len=*) , intent(in) :: units ! attribute ! ! !LOCAL VARIABLES: character(len=*), parameter :: subname = 'ncd_def_spatial_var_0lev' !----------------------------------------------------------------------- if (outnc_1d) then call ncd_defvar(ncid=ncid, varname=varname, xtype=xtype, & dim1name='gridcell', & long_name=long_name, units=units) else call ncd_defvar(ncid=ncid, varname=varname, xtype=xtype, & dim1name='lsmlon', dim2name='lsmlat', & long_name=long_name, units=units) end if end subroutine ncd_def_spatial_var_0lev !----------------------------------------------------------------------- subroutine ncd_def_spatial_var_1lev(ncid, varname, xtype, lev1name, long_name, units) ! ! !DESCRIPTION: ! Define a spatial netCDF variable (convenience wrapper to ncd_defvar) ! ! The variable in question has one level (or time) dimension in addition to its ! spatial dimensions ! ! !USES: use mkvarctl, only : outnc_1d ! ! !ARGUMENTS: integer , intent(in) :: ncid ! input unit character(len=*) , intent(in) :: varname ! variable name integer , intent(in) :: xtype ! external type character(len=*) , intent(in) :: lev1name ! name of level (or time) dimension character(len=*) , intent(in) :: long_name ! attribute character(len=*) , intent(in) :: units ! attribute ! ! !LOCAL VARIABLES: character(len=*), parameter :: subname = 'ncd_def_spatial_var_1lev' !----------------------------------------------------------------------- if (outnc_1d) then call ncd_defvar(ncid=ncid, varname=varname, xtype=xtype, & dim1name='gridcell', dim2name=lev1name, & long_name=long_name, units=units) else call ncd_defvar(ncid=ncid, varname=varname, xtype=xtype, & dim1name='lsmlon', dim2name='lsmlat',dim3name=lev1name, & long_name=long_name, units=units) end if end subroutine ncd_def_spatial_var_1lev !----------------------------------------------------------------------- subroutine ncd_def_spatial_var_2lev(ncid, varname, xtype, lev1name, lev2name, long_name, units) ! ! !DESCRIPTION: ! Define a spatial netCDF variable (convenience wrapper to ncd_defvar) ! ! The variable in question has two level (or time) dimensions in addition to its ! spatial dimensions ! ! !USES: use mkvarctl, only : outnc_1d ! ! !ARGUMENTS: integer , intent(in) :: ncid ! input unit character(len=*) , intent(in) :: varname ! variable name integer , intent(in) :: xtype ! external type character(len=*) , intent(in) :: lev1name ! name of first level (or time) dimension character(len=*) , intent(in) :: lev2name ! name of second level (or time) dimension character(len=*) , intent(in) :: long_name ! attribute character(len=*) , intent(in) :: units ! attribute ! ! !LOCAL VARIABLES: character(len=*), parameter :: subname = 'ncd_def_spatial_var_2lev' !----------------------------------------------------------------------- if (outnc_1d) then call ncd_defvar(ncid=ncid, varname=varname, xtype=xtype, & dim1name='gridcell', dim2name=lev1name, dim3name=lev2name, & long_name=long_name, units=units) else call ncd_defvar(ncid=ncid, varname=varname, xtype=xtype, & dim1name='lsmlon', dim2name='lsmlat', dim3name=lev1name, dim4name=lev2name, & long_name=long_name, units=units) end if end subroutine ncd_def_spatial_var_2lev ! ======================================================================== ! ncd_put_time_slice routines: write a single time slice of a variable ! ======================================================================== !----------------------------------------------------------------------- subroutine ncd_put_time_slice_1d(ncid, varid, time_index, data) ! ! !DESCRIPTION: ! Write a single time slice of a 1-d variable ! ! !USES: ! ! !ARGUMENTS: integer , intent(in) :: ncid ! netCDF id integer , intent(in) :: varid ! variable id integer , intent(in) :: time_index ! time index in file real(r8), intent(in) :: data(:) ! data to write (a single time slice) ! ! !LOCAL VARIABLES: integer, allocatable :: beg(:) ! begin indices for each dimension integer, allocatable :: len(:) ! length along each dimension character(len=*), parameter :: subname = 'ncd_put_time_slice_1d' !----------------------------------------------------------------------- call get_time_slice_beg_and_len(ncid, varid, time_index, beg, len) call check_ret(nf_put_vara_double(ncid, varid, beg, len, data), subname) deallocate(beg, len) end subroutine ncd_put_time_slice_1d !----------------------------------------------------------------------- subroutine ncd_put_time_slice_2d(ncid, varid, time_index, data) ! ! !DESCRIPTION: ! Write a single time slice of a 2-d variable ! ! !USES: ! ! !ARGUMENTS: integer , intent(in) :: ncid ! netCDF id integer , intent(in) :: varid ! variable id integer , intent(in) :: time_index ! time index in file real(r8), intent(in) :: data(:,:) ! data to write (a single time slice) ! ! !LOCAL VARIABLES: integer, allocatable :: beg(:) ! begin indices for each dimension integer, allocatable :: len(:) ! length along each dimension character(len=*), parameter :: subname = 'ncd_put_time_slice_2d' !----------------------------------------------------------------------- call get_time_slice_beg_and_len(ncid, varid, time_index, beg, len) call check_ret(nf_put_vara_double(ncid, varid, beg, len, data), subname) deallocate(beg, len) end subroutine ncd_put_time_slice_2d !----------------------------------------------------------------------- subroutine get_time_slice_beg_and_len(ncid, varid, time_index, beg, len) ! ! !DESCRIPTION: ! Determine beg and len vectors for writing a time slice. ! ! Assumes time is the last dimension of the given variable. ! ! Allocates memory for beg & len. ! ! !USES: ! ! !ARGUMENTS: integer , intent(in) :: ncid ! netcdf ID integer , intent(in) :: varid ! variable ID integer , intent(in) :: time_index ! time index in file integer, allocatable, intent(out) :: beg(:) ! begin indices for each dimension integer, allocatable, intent(out) :: len(:) ! length along each dimension ! ! !LOCAL VARIABLES: integer :: n ! index integer :: ndims ! number of dimensions integer, allocatable :: dimids(:) ! dimension IDs character(len=*), parameter :: subname = 'get_time_slice_beg_and_len' !----------------------------------------------------------------------- call check_ret(nf_inq_varndims(ncid, varid, ndims), subname) allocate(beg(ndims)) allocate(len(ndims)) allocate(dimids(ndims)) call check_ret(nf_inq_vardimid(ncid, varid, dimids), subname) beg(1:ndims-1) = 1 do n = 1,ndims-1 call check_ret(nf_inq_dimlen(ncid, dimids(n), len(n)), subname) end do len(ndims) = 1 beg(ndims) = time_index deallocate(dimids) end subroutine get_time_slice_beg_and_len !------------------------------------------------------------------------------ !BOP ! ! !IROUTINE: get_dim_lengths ! ! !INTERFACE: subroutine get_dim_lengths(ncid, varname, ndims, dim_lengths) ! ! !DESCRIPTION: ! Returns the number of dimensions and an array containing the dimension lengths of a ! variable in an open netcdf file. ! ! Entries 1:ndims in the returned dim_lengths array contain the dimension lengths; the ! remaining entries in that vector are meaningless. The dim_lengths array must be large ! enough to hold all ndims values; if not, the code aborts (this can be ensured by passing ! in an array of length nf_max_var_dims). ! ! !USES: ! ! !ARGUMENTS: implicit none integer , intent(in) :: ncid ! netcdf id of an open netcdf file character(len=*), intent(in) :: varname ! name of variable of interest integer , intent(out):: ndims ! number of dimensions of variable integer , intent(out):: dim_lengths(:) ! lengths of dimensions of variable ! ! !REVISION HISTORY: ! Author: Bill Sacks ! ! ! !LOCAL VARIABLES: integer :: varid integer :: dimids(size(dim_lengths)) integer :: i character(len=*), parameter :: subname = 'get_dim_lengths' !EOP !------------------------------------------------------------------------------ call check_ret(nf_inq_varid(ncid, varname, varid), subname) call check_ret(nf_inq_varndims(ncid, varid, ndims), subname) if (ndims > size(dim_lengths)) then write(6,*) trim(subname), ' ERROR: dim_lengths too small' call abort() end if call check_ret(nf_inq_vardimid(ncid, varid, dimids), subname) dim_lengths(:) = 0 ! pre-fill with 0 so we won't have garbage in elements past ndims do i = 1, ndims call check_ret(nf_inq_dimlen(ncid, dimids(i), dim_lengths(i)), subname) end do end subroutine get_dim_lengths !---------------------------------------------------------------------------- !BOP ! ! !IROUTINE: convert_latlon ! ! !INTERFACE: subroutine convert_latlon(ncid, varname, data) ! ! !DESCRIPTION: ! Convert a latitude or longitude variable from its units in the input file to degrees E / ! degrees N. Currently, this just handles conversions from radians to degrees. ! ! Assumes that the longitude / latitude variable has already been read from file, into ! the variable given by 'data'. ncid & varname give the file ID and variable name from ! which this variable was read (needed to obtain the variable's units). ! ! !USES: use shr_const_mod, only : SHR_CONST_PI ! ! !ARGUMENTS: implicit none integer , intent(in) :: ncid ! ID of open netcdf file character(len=*), intent(in) :: varname ! name of lat or lon variable that was read into 'data' real(r8) , intent(inout):: data(:) ! latitude or longitude data ! ! !REVISION HISTORY: ! Author: Bill Sacks ! ! ! !LOCAL VARIABLES: !EOP integer :: ier ! error return code integer :: varid ! netCDF variable id integer :: units_len ! length of units attribute on file character(len=256) :: units ! units attribute character(len= 32) :: subname = 'convert_latlon' !----------------------------------------------------------------- call check_ret(nf_inq_varid (ncid, varname, varid), subname) ier = nf_inq_attlen(ncid, varid, 'units', units_len) ! Only do the following processing if there is no error; if ier /= NF_NOERR, that ! probably means there isn't a units attribute -- in that case, assume units are ! degrees and need no conversion if (ier == NF_NOERR) then if (units_len > len(units)) then write(6,*) trim(subname), ' ERROR: units variable not long enough to hold attributue' call abort() end if call check_ret(nf_get_att_text(ncid, varid, 'units', units), subname) if (units(1:7) == 'radians') then ! convert from radians to degrees data(:) = data(:) * 180._r8 / SHR_CONST_PI end if end if end subroutine convert_latlon !------------------------------------------------------------------------------ end module mkncdio
{ "pile_set_name": "Github" }
<?php $container->loadFromExtension('wouterj_eloquent', []);
{ "pile_set_name": "Github" }
# ID3v2.3.0 Specifications # http://id3.org/id3v2.3.0 meta: id: id3v2_3 license: CC0-1.0 endian: be file-extension: - mp3 seq: - id: tag type: tag types: # Section 3. ID3v2 overview tag: seq: - id: header type: header - id: header_ex type: header_ex if: header.flags.flag_headerex - id: frames type: frame repeat: until repeat-until: _io.pos + _.size > header.size.value or _.is_invalid - id: padding if: header.flags.flag_headerex size: header_ex.padding_size - _io.pos # Section 3.1. ID3v2 header header: doc: ID3v2 fixed header doc-ref: Section 3.1. ID3v2 header seq: - id: magic contents: 'ID3' - id: version_major type: u1 - id: version_revision type: u1 - id: flags type: flags - id: size type: u4be_synchsafe types: flags: seq: - id: flag_unsynchronization type: b1 - id: flag_headerex type: b1 - id: flag_experimental type: b1 - id: reserved type: b5 header_ex: doc: ID3v2 extended header doc-ref: Section 3.2. ID3v2 extended header seq: - id: size type: u4 - id: flags_ex type: flags_ex - id: padding_size type: u4 - id: crc type: u4 if: flags_ex.flag_crc types: flags_ex: seq: - id: flag_crc type: b1 - id: reserved type: b15 # Section 3.3. ID3v2 frame overview frame: seq: - id: id type: str size: 4 encoding: ASCII - id: size type: u4 - id: flags type: flags - id: data size: size types: flags: seq: - id: flag_discard_alter_tag type: b1 - id: flag_discard_alter_file type: b1 - id: flag_read_only type: b1 - id: reserved1 type: b5 - id: flag_compressed type: b1 - id: flag_encrypted type: b1 - id: flag_grouping type: b1 - id: reserved2 type: b5 instances: is_invalid: value: "id == '\x00\x00\x00\x00'" # Section 6.2. Synchsafe integers u1be_synchsafe: seq: - id: padding type: b1 - id: value type: b7 u2be_synchsafe: seq: - id: byte0 type: u1be_synchsafe - id: byte1 type: u1be_synchsafe instances: value: value: (byte0.value << 7) | byte1.value u4be_synchsafe: seq: - id: short0 type: u2be_synchsafe - id: short1 type: u2be_synchsafe instances: value: value: (short0.value << 14) | short1.value
{ "pile_set_name": "Github" }
// // MessagePack for C++ static resolution routine // // Copyright (C) 2015-2016 MIZUKI Hirata // // Distributed under 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) // #ifndef MSGPACK_ITERATOR_HPP #define MSGPACK_ITERATOR_HPP #include <msgpack/iterator_decl.hpp> #include <msgpack/v1/iterator.hpp> #endif // MSGPACK_ITERATOR_HPP
{ "pile_set_name": "Github" }
<!-- Licensed to JumpMind Inc under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. JumpMind Inc licenses this file to you under the GNU General Public License, version 3.0 (GPLv3) (the "License"); you may not use this file except in compliance with the License. You should have received a copy of the GNU General Public License, version 3.0 (GPLv3) along with this library; if not, see <http://www.gnu.org/licenses/>. 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. --> <ui> <component-ui id="Format Delimited UI" componentId="Format Delimited"> <iconImage>org/jumpmind/metl/core/runtime/component/metl-delimitedformatter-out-48x48-color.png</iconImage> <className>org.jumpmind.metl.ui.views.design.EditFormatPanel</className> </component-ui> <component-ui id="Parse Delimited UI" componentId="Parse Delimited"> <iconImage>org/jumpmind/metl/core/runtime/component/metl-delimitedformatter-in-48x48-color.png</iconImage> <className>org.jumpmind.metl.ui.views.design.EditFormatPanel</className> </component-ui> <component-ui id="Format Fixed UI" componentId="Format Fixed"> <iconImage>org/jumpmind/metl/core/runtime/component/metl-fixed-length-48x48-color.png</iconImage> <className>org.jumpmind.metl.ui.views.design.EditFormatPanel</className> </component-ui> <component-ui id="Parse Fixed UI" componentId="Parse Fixed"> <iconImage>org/jumpmind/metl/core/runtime/component/metl-fixed-length-48x48-color.png</iconImage> <className>org.jumpmind.metl.ui.views.design.EditFormatPanel</className> </component-ui> </ui>
{ "pile_set_name": "Github" }
import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.nn.functional as F from torch.nn import init import math from utils import transition, global_pool, compress, clique_block class build_cliquenet(nn.Module): def __init__(self, input_channels, list_channels, list_layer_num, if_att): super(build_cliquenet, self).__init__() self.fir_trans = nn.Conv2d(3, input_channels, kernel_size=7, stride=2, padding=3, bias=False) self.fir_bn = nn.BatchNorm2d(input_channels) self.fir_pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.block_num = len(list_channels) self.if_att = if_att self.list_block = nn.ModuleList() self.list_trans = nn.ModuleList() self.list_gb = nn.ModuleList() self.list_gb_channel = [] self.list_compress = nn.ModuleList() input_size_init = 56 for i in xrange(self.block_num): if i == 0: self.list_block.append(clique_block(input_channels=input_channels, channels_per_layer=list_channels[0], layer_num=list_layer_num[0], loop_num=1, keep_prob=0.8)) self.list_gb_channel.append(input_channels + list_channels[0] * list_layer_num[0]) else : self.list_block.append(clique_block(input_channels=list_channels[i-1] * list_layer_num[i-1], channels_per_layer=list_channels[i], layer_num=list_layer_num[i], loop_num=1, keep_prob=0.8)) self.list_gb_channel.append(list_channels[i-1] * list_layer_num[i-1] + list_channels[i] * list_layer_num[i]) if i < self.block_num - 1: self.list_trans.append(transition(self.if_att, current_size=input_size_init, input_channels=list_channels[i] * list_layer_num[i], keep_prob=0.8)) self.list_gb.append(global_pool(input_size=input_size_init, input_channels=self.list_gb_channel[i] // 2)) self.list_compress.append(compress(input_channels=self.list_gb_channel[i], keep_prob=0.8)) input_size_init = input_size_init // 2 self.fc = nn.Linear(in_features=sum(self.list_gb_channel) // 2, out_features=1000) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.bias.data.zero_() def forward(self, x): output = self.fir_trans(x) output = self.fir_bn(output) output = F.relu(output) output = self.fir_pool(output) feature_I_list = [] # use stage II + stage II mode for i in xrange(self.block_num): block_feature_I, block_feature_II = self.list_block[i](output) block_feature_I = self.list_compress[i](block_feature_I) feature_I_list.append(self.list_gb[i](block_feature_I)) if i < self.block_num - 1: output = self.list_trans[i](block_feature_II) final_feature = feature_I_list[0] for block_id in range(1, len(feature_I_list)): final_feature=torch.cat((final_feature, feature_I_list[block_id]), 1) final_feature = final_feature.view(final_feature.size()[0], final_feature.size()[1]) output = self.fc(final_feature) return output
{ "pile_set_name": "Github" }
.\" $Id: u_misc.3,v 1.1 2005/09/23 13:04:38 tho Exp $
{ "pile_set_name": "Github" }
--- external help file: Module Name: Az.MariaDb online version: https://docs.microsoft.com/en-us/powershell/module/az.mariadb/new-azmariadbreplica schema: 2.0.0 --- # New-AzMariaDbReplica ## SYNOPSIS Creates a replica of a MariaDB server. ## SYNTAX ### ServerName (Default) ``` New-AzMariaDbReplica -MasterName <String> -ReplicaName <String> -ResourceGroupName <String> [-SubscriptionId <String>] [-Location <String>] [-Sku <String>] [-Tag <Hashtable>] [-DefaultProfile <PSObject>] [-AsJob] [-NoWait] [-Confirm] [-WhatIf] [<CommonParameters>] ``` ### ServerObject ``` New-AzMariaDbReplica -Master <IServer> -ReplicaName <String> [-SubscriptionId <String>] [-Location <String>] [-Sku <String>] [-Tag <Hashtable>] [-DefaultProfile <PSObject>] [-AsJob] [-NoWait] [-Confirm] [-WhatIf] [<CommonParameters>] ``` ## DESCRIPTION Creates a replica of a MariaDB server. ## EXAMPLES ### Example 1: Create a replica db for a MariaDB ```powershell PS C:\> New-AzMariaDbReplica -MasterName mariadb-test-9pebvn -ReplicaName mariadb-test-9pebvn-rep01 -ResourceGroupName mariadb-test-qu5ov0 Name Location AdministratorLogin Version StorageProfileStorageMb SkuName SkuTier SslEnforcement ---- -------- ------------------ ------- ----------------------- ------- ------- -------------- mariadb-test-9pebvn-rep01 eastus xpwjyfdgui 10.2 7168 GP_Gen5_4 GeneralPurpose Enabled ``` This command creates a replica db for a MariaDB. ### Example 2: Create a replica db for a MariaDB ```powershell PS C:\> Get-AzMariaDbServer -Name mariadb-test-9pebvn -ResourceGroupName mariadb-test-qu5ov0 | New-AzMariaDbReplica -ReplicaName mariadb-test-9pebvn-rep02 Name Location AdministratorLogin Version StorageProfileStorageMb SkuName SkuTier SslEnforcement ---- -------- ------------------ ------- ----------------------- ------- ------- -------------- mariadb-test-9pebvn-rep02 eastus xpwjyfdgui 10.2 7168 GP_Gen5_4 GeneralPurpose Enabled ``` This command creates a replica db for a MariaDB. ### Example 3: Create a replica db for a MariaDB ```powershell PS C:\> $mariaDb = Get-AzMariaDbServer -Name mariadb-test-9pebvn -ResourceGroupName mariadb-test-qu5ov0 PS C:\> New-AzMariaDbReplica -Master $mariaDb -ReplicaName mariadb-test-9pebvn-rep03 Name Location AdministratorLogin Version StorageProfileStorageMb SkuName SkuTier SslEnforcement ---- -------- ------------------ ------- ----------------------- ------- ------- -------------- mariadb-test-9pebvn-rep03 eastus xpwjyfdgui 10.2 7168 GP_Gen5_4 GeneralPurpose Enabled ``` This command with parameter inputobject creates a replica db with parameter inputobject for a MariaDB. ## PARAMETERS ### -AsJob Run the command as a job ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DefaultProfile region DefaultParameters The credentials, account, tenant, and subscription used for communication with Azure. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: AzureRMContext, AzureCredential Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Location The location the resource resides in. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Master The source server object to restore from. To construct, see NOTES section for MASTER properties and create a hash table. ```yaml Type: Microsoft.Azure.PowerShell.Cmdlets.MariaDb.Models.Api20180601Preview.IServer Parameter Sets: ServerObject Aliases: InputObject Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -MasterName MariaDB server name. ```yaml Type: System.String Parameter Sets: ServerName Aliases: ServerName Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoWait Run the command asynchronously ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ReplicaName Replica name. ```yaml Type: System.String Parameter Sets: (All) Aliases: ReplicaServerName, Name Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceGroupName You can obtain this value from the Azure Resource Manager API or the portal. ```yaml Type: System.String Parameter Sets: ServerName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Sku The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SubscriptionId The subscription ID is part of the URI for every service call. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: (Get-AzContext).Subscription.Id Accept pipeline input: False Accept wildcard characters: False ``` ### -Tag Application-specific metadata in the form of key-value pairs. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.Azure.PowerShell.Cmdlets.MariaDb.Models.Api20180601Preview.IServer ## OUTPUTS ### Microsoft.Azure.PowerShell.Cmdlets.MariaDb.Models.Api20180601Preview.IServer ## NOTES ALIASES COMPLEX PARAMETER PROPERTIES To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. MASTER <IServer>: The source server object to restore from. - `Location <String>`: The location the resource resides in. - `[Tag <ITrackedResourceTags>]`: Application-specific metadata in the form of key-value pairs. - `[(Any) <String>]`: This indicates any property can be added to this object. - `[AdministratorLogin <String>]`: The administrator's login name of a server. Can only be specified when the server is being created (and is required for creation). - `[EarliestRestoreDate <DateTime?>]`: Earliest restore point creation time (ISO8601 format) - `[FullyQualifiedDomainName <String>]`: The fully qualified domain name of a server. - `[IdentityType <IdentityType?>]`: The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource. - `[MasterServerId <String>]`: The master server id of a replica server. - `[ReplicaCapacity <Int32?>]`: The maximum number of replicas that a master server can have. - `[ReplicationRole <String>]`: The replication role of the server. - `[SkuCapacity <Int32?>]`: The scale up/out capacity, representing server's compute units. - `[SkuFamily <String>]`: The family of hardware. - `[SkuName <String>]`: The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. - `[SkuSize <String>]`: The size code, to be interpreted by resource as appropriate. - `[SkuTier <SkuTier?>]`: The tier of the particular SKU, e.g. Basic. - `[SslEnforcement <SslEnforcementEnum?>]`: Enable ssl enforcement or not when connect to server. - `[StorageProfileBackupRetentionDay <Int32?>]`: Backup retention days for the server. - `[StorageProfileGeoRedundantBackup <GeoRedundantBackup?>]`: Enable Geo-redundant or not for server backup. - `[StorageProfileStorageAutogrow <StorageAutogrow?>]`: Enable Storage Auto Grow. - `[StorageProfileStorageMb <Int32?>]`: Max storage allowed for a server. - `[UserVisibleState <ServerState?>]`: A state of a server that is visible to user. - `[Version <ServerVersion?>]`: Server version. ## RELATED LINKS
{ "pile_set_name": "Github" }
<?php namespace Oro\Bundle\VisibilityBundle\Tests\Unit\EventListener; use Oro\Bundle\FrontendBundle\Request\FrontendHelper; use Oro\Bundle\ProductBundle\Event\ProductSearchQueryRestrictionEvent; use Oro\Bundle\SearchBundle\Query\Modifier\QueryModifierInterface; use Oro\Bundle\SearchBundle\Query\Query; use Oro\Bundle\VisibilityBundle\EventListener\ProductSearchQueryRestrictionEventListener; class ProductSearchQueryRestrictionEventListenerTest extends \PHPUnit\Framework\TestCase { public function testOnSearchQueryWithFrontendRequest() { $listener = new ProductSearchQueryRestrictionEventListener( $this->getFrontendHelper(true), $this->getQueryModifier($this->once()) ); $listener->onSearchQuery($this->getEvent()); } public function testOnSearchQueryWithoutFrontendRequest() { $listener = new ProductSearchQueryRestrictionEventListener( $this->getFrontendHelper(false), $this->getQueryModifier($this->never()) ); $listener->onSearchQuery($this->getEvent()); } /** * @param bool $isFrontendRequest * * @return FrontendHelper|\PHPUnit\Framework\MockObject\MockObject */ private function getFrontendHelper($isFrontendRequest = true) { /** @var FrontendHelper|\PHPUnit\Framework\MockObject\MockObject $frontendHelper */ $frontendHelper = $this->getMockBuilder(FrontendHelper::class) ->disableOriginalConstructor()->getMock(); $frontendHelper ->expects($this->once()) ->method('isFrontendRequest') ->willReturn($isFrontendRequest); return $frontendHelper; } /** * @param \PHPUnit\Framework\MockObject\Rule\InvokedCount $expectedToBeCalled * * @return QueryModifierInterface|\PHPUnit\Framework\MockObject\MockObject */ private function getQueryModifier(\PHPUnit\Framework\MockObject\Rule\InvokedCount $expectedToBeCalled) { /** @var QueryModifierInterface|\PHPUnit\Framework\MockObject\MockObject $queryModifier */ $queryModifier = $this->getMockBuilder(QueryModifierInterface::class)->getMock(); $queryModifier ->expects($expectedToBeCalled) ->method('modify'); return $queryModifier; } /** * @return ProductSearchQueryRestrictionEvent */ private function getEvent() { return new ProductSearchQueryRestrictionEvent(new Query()); } }
{ "pile_set_name": "Github" }
/** */ function isNull(val){ return val === null; } module.exports = isNull;
{ "pile_set_name": "Github" }
#!/usr/bin/env python # coding=utf8 # author=evi1m0@201503 # poc: http://www.beebeeto.com/pdb/poc-2015-0052/ # install: https://pypi.python.org/pypi/ds_store import sys from ds_store import DSStore if len(sys.argv) < 2: print '[*] Usage: %s path/.DS_Store' % sys.argv[0] sys.exit() filelist = [] filename = sys.argv[1] try: with DSStore.open(filename, 'r+') as obj: for i in obj: filelist.append(i.filename) except Exception, e: print '[-] Error: %s' % str(e) for name in set(list(filelist)): print '[*] ' + name
{ "pile_set_name": "Github" }
import readNumberLiteral from './literal/readNumberLiteral'; import readBooleanLiteral from './literal/readBooleanLiteral'; import readStringLiteral from './literal/readStringLiteral'; import readTemplateStringLiteral from './literal/readTemplateStringLiteral'; import readObjectLiteral from './literal/readObjectLiteral'; import readArrayLiteral from './literal/readArrayLiteral'; import readRegexpLiteral from './literal/readRegexpLiteral'; export default function readLiteral(parser) { return ( readNumberLiteral(parser) || readBooleanLiteral(parser) || readStringLiteral(parser) || readTemplateStringLiteral(parser) || readObjectLiteral(parser) || readArrayLiteral(parser) || readRegexpLiteral(parser) ); }
{ "pile_set_name": "Github" }
package com.intellij.flex.uiDesigner { import com.intellij.flex.uiDesigner.plaf.aqua.IdeaAquaLookAndFeel; public class Main extends MainWindowedApplication { } }
{ "pile_set_name": "Github" }
/**************************************************************************** * MeshLab o o * * A versatile mesh processing toolbox o o * * _ O _ * * Copyright(C) 2005 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * 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 (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #include <math.h> #include <limits> #include <stdlib.h> #include "decorate_background.h" #include <wrap/gl/addons.h> #include <meshlab/glarea.h> #include <common/GLExtensionsManager.h> #include <common/pluginmanager.h> using namespace vcg; QString DecorateBackgroundPlugin::decorationName(FilterIDType id) const { switch (id) { case DP_SHOW_CUBEMAPPED_ENV: return tr("Cube mapped background"); case DP_SHOW_GRID: return tr("Background Grid"); } assert(0); return QString(); } QString DecorateBackgroundPlugin::decorationInfo(FilterIDType id) const { switch(id) { case DP_SHOW_CUBEMAPPED_ENV : return tr("Draws a customizable cube mapped background that is sync with trackball rotation"); case DP_SHOW_GRID : return tr("Draws a gridded background that can be used as a reference."); } assert(0); return QString(); } QString DecorateBackgroundPlugin::pluginName() const { return "DecorateBackGround"; } void DecorateBackgroundPlugin::initGlobalParameterList(const QAction* action, RichParameterList &parset) { switch(ID(action)) { case DP_SHOW_CUBEMAPPED_ENV : if(!parset.hasParameter(CubeMapPathParam())) { QString cubemapDirPath = PluginManager::getBaseDirPath() + QString("/textures/cubemaps/uffizi.jpg"); //parset.addParam(RichString(CubeMapPathParam(), cubemapDirPath,"","")); } break; case DP_SHOW_GRID : parset.addParam(RichFloat(BoxRatioParam(),1.2f,"Box Ratio","The size of the grid around the object w.r.t. the bbox of the object")); parset.addParam(RichFloat(GridMajorParam(),10.0f,"Major Spacing","")); parset.addParam(RichFloat(GridMinorParam(),1.0f,"Minor Spacing","")); parset.addParam(RichBool(GridBackParam(),true,"Front grid culling","")); parset.addParam(RichBool(ShowShadowParam(),false,"Show silhouette","")); parset.addParam(RichColor(GridColorBackParam(), QColor(163,116,35,255), "Back Grid Color", "")); parset.addParam(RichColor(GridColorFrontParam(),QColor(22,139,119,255),"Front grid Color","")); parset.addParam(RichFloat(GridBaseLineWidthParam(),1.0f,"Line Width","The width of the lines of the grid")); break; } } bool DecorateBackgroundPlugin::startDecorate(const QAction * action, MeshDocument &/*m*/, const RichParameterList * parset, GLArea * gla) { if (!GLExtensionsManager::initializeGLextensions_notThrowing()) { return false; } switch(ID(action)) { case DP_SHOW_CUBEMAPPED_ENV : if(parset->hasParameter(CubeMapPathParam()) == false) qDebug("CubeMapPath was not set!!!"); cubemapFileName = parset->getString(CubeMapPathParam()); break; case DP_SHOW_GRID: /*QMetaObject::Connection aaa =*/ connect(gla, SIGNAL(transmitShot(QString, Shotm)), this, SLOT(setValue(QString, Shotm))); /*QMetaObject::Connection bbb =*/ connect(this, SIGNAL(askViewerShot(QString)), gla, SLOT(sendViewerShot(QString))); break; } return true; } void DecorateBackgroundPlugin::decorateDoc(const QAction* a, MeshDocument &m, const RichParameterList * parset, GLArea * gla, QPainter *, GLLogStream &) { static QString lastname("uninitialized"); switch(ID(a)) { case DP_SHOW_CUBEMAPPED_ENV : { if(!cm.IsValid() || (lastname != cubemapFileName ) ) { qDebug( "Current CubeMapPath Dir: %s ",qUtf8Printable(cubemapFileName)); GLExtensionsManager::initializeGLextensions(); bool ret = cm.Load(qUtf8Printable(cubemapFileName)); lastname=cubemapFileName; if(! ret ) return; //QMessageBox::warning(gla,"Cubemapped background decoration","Warning unable to load cube map images: " + cubemapFileName ); cm.radius=10; } if(!cm.IsValid()) return; Matrix44f tr; glGetv(GL_MODELVIEW_MATRIX,tr); // Remove the translation from the current matrix by simply padding the last column of the matrix tr.SetColumn(3,Point4f(0,0,0,1.0)); //Remove the scaling from the the current matrix by adding an inverse scaling matrix float scale = 1.0/pow(tr.Determinant(),1.0f/3.0f); Matrix44f Scale; Scale.SetDiagonal(scale); tr=tr*Scale; glMatrixMode(GL_PROJECTION); glPushMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); cm.DrawEnvCube(tr); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } break; case DP_SHOW_GRID : { emit this->askViewerShot("backGrid"); float scaleBB = parset->getFloat(BoxRatioParam()); float majorTick = fabs(parset->getFloat(GridMajorParam())); float minorTick = fabs(parset->getFloat(GridMinorParam())); bool backFlag = parset->getBool(GridBackParam()); bool shadowFlag = parset->getBool(ShowShadowParam()); Color4b backColor = parset->getColor4b(GridColorBackParam()); Color4b frontColor = parset->getColor4b(GridColorFrontParam()); float baseLineWidth = parset->getFloat(GridBaseLineWidthParam()); Box3m bb = m.bbox(); float scalefactor = std::max(0.1, (scaleBB - 1.0)); bb.Offset((bb.max - bb.min)*(scalefactor/2.0)); // minortick should never be more than majortick if (minorTick > majorTick) minorTick = majorTick; // check if user asked for a grid that is too dense // if more than 100-200k ticks, the rendering will slow down too much and crash on some drivers int ticks = ((bb.Dim()[0] + bb.Dim()[1] + bb.Dim()[2]) / minorTick) + ((bb.Dim()[0] + bb.Dim()[1] + bb.Dim()[2]) / majorTick); if (ticks > 200000) { if (log10(bb.Diag()) > 0.0) majorTick = pow(10, floor(log10(bb.Diag()) -1)); else majorTick = pow(10, floor(log10(bb.Diag()) + 1)); minorTick = majorTick / 2.0; } MLSceneGLSharedDataContext* shared = NULL; QGLContext* cont = NULL; if ((gla != NULL) && (gla->mvc() != NULL)) { cont = gla->context(); shared = gla->mvc()->sharedDataContext(); } DrawGriddedCube(shared,cont,*m.mm(), bb, majorTick, minorTick, backFlag, shadowFlag, backColor, frontColor,baseLineWidth); } break; } } // Note minG/maxG is wider than minP/maxP. void DrawGridPlane(int axis, int side, // 0 is min 1 is max Point3m minP, Point3m maxP, Point3m minG, Point3m maxG, // the box with vertex positions snapped to the grid (enlarging it). float majorTick, float minorTick, Color4b lineColor, float baseLineWidth=1.0f) { int xAxis = (1+axis)%3; int yAxis = (2+axis)%3; int zAxis = (0+axis)%3; // the axis perpendicular to the plane we want to draw (e.g. if i want to draw plane xy I write '2') Color4b majorColor=lineColor; Color4b minorColor; Color4b axisColor; minorColor[0] = std::min(255.0, lineColor[0] * 2.0); // minorcolor is 2 times brighter and half solid w.r.t. majorcolor minorColor[1] = std::min(255.0, lineColor[1] * 2.0); minorColor[2] = std::min(255.0, lineColor[2] * 2.0); minorColor[3] = std::min(127.0, lineColor[3] / 2.0); axisColor[0] = lineColor[0] * 0.66; // axiscolor is 2/3 darker w.r.t. majorcolor axisColor[1] = lineColor[1] * 0.66; axisColor[2] = lineColor[2] * 0.66; axisColor[3] = 255; // We draw orizontal and vertical lines onto the XY plane snapped with the major ticks Point3m p1,p2,p3,p4; p1[zAxis] = p2[zAxis] = p3[zAxis] = p4[zAxis] = side ? maxG[zAxis] : minG[zAxis]; float aMin,aMax,bMin,bMax; p1[yAxis] = minG[yAxis]; p2[yAxis] = maxG[yAxis]; p3[xAxis] = minG[xAxis]; p4[xAxis] = maxG[xAxis]; aMin = minG[xAxis]; aMax = maxG[xAxis]; bMin = minG[yAxis]; bMax = maxG[yAxis]; glLineWidth(baseLineWidth*0.5f); glColor(minorColor); glBegin(GL_LINES); for (float alpha = aMin; alpha <= aMax; alpha += minorTick) { p1[xAxis] = p2[xAxis] = alpha; glVertex(p1); glVertex(p2); } for (float alpha = bMin; alpha <= bMax; alpha += minorTick) { p3[yAxis] = p4[yAxis] = alpha; glVertex(p3); glVertex(p4); } glEnd(); glLineWidth(baseLineWidth*1.0f); glColor(majorColor); glBegin(GL_LINES); for (float alpha = aMin; alpha <= aMax; alpha += majorTick) { p1[xAxis] = p2[xAxis] = alpha; glVertex(p1); glVertex(p2); } for (float alpha = bMin; alpha <= bMax; alpha += majorTick) { p3[yAxis] = p4[yAxis] = alpha; glVertex(p3); glVertex(p4); } glEnd(); // Draw the axis glColor(axisColor); glLineWidth(baseLineWidth*1.5f); glBegin(GL_LINES); if(minP[xAxis]*maxP[xAxis] <0 ) { p1[yAxis]=minG[yAxis]; p2[yAxis]=maxG[yAxis]; p1[xAxis]=p2[xAxis]=0; glVertex(p1); glVertex(p2); } if(minP[yAxis]*maxP[yAxis] <0 ) { p1[xAxis]=minG[xAxis]; p2[xAxis]=maxG[xAxis]; p1[yAxis]=p2[yAxis]=0; glVertex(p1); glVertex(p2); } glEnd(); } /* return true if the side of a box is front facing with respet of the give viewpoint. side 0, axis i == min on than i-th axis side 1, axis i == min on than i-th axis questo capita se il prodotto scalare tra il vettore normale entro della faccia */ bool FrontFacing(Point3m viewPos, int axis, int side, Point3m minP, Point3m maxP) { assert (side==0 || side ==1); assert (axis>=0 && axis < 3); Point3m N(0,0,0); Point3m C = (minP+maxP)/2.0; if(side == 1) { C[axis] = maxP[axis]; N[axis]=-1; } if(side == 0) { C[axis] = minP[axis]; N[axis]=1; } Point3m vpc = viewPos-C; // qDebug("FaceCenter %f %f %f - %f %f %f",C[0],C[1],C[2],N[0],N[1],N[2]); // qDebug("VPC %f %f %f",vpc[0],vpc[1],vpc[2]); return vpc*N > 0; } void DrawFlatMesh(MLSceneGLSharedDataContext* shared,QGLContext* cont,MeshModel &m, int axis, int side, Point3m minG, Point3m maxG) { if ((shared == NULL) || (cont == NULL)) return; glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_LIGHTING); glPushMatrix(); Point3m trans = side?maxG:minG; Point3m scale(1.0f,1.0f,1.0); trans[(axis+1)%3]=0; trans[(axis+2)%3]=0; scale[axis]=0; glTranslate(trans); glScale(scale); shared->draw(m.id(),cont); // m.render(GLW::DMFlat,GLW::CMNone,GLW::TMNone); glPopMatrix(); glPopAttrib(); } void DecorateBackgroundPlugin::DrawGriddedCube(MLSceneGLSharedDataContext* shared, QGLContext* cont, MeshModel &m, const Box3m &bb, Scalarm majorTick, Scalarm minorTick, bool backCullFlag, bool shadowFlag, Color4b frontColor, Color4b backColor, float baseLineWidth) { glPushAttrib(GL_ALL_ATTRIB_BITS); Point3m minP,maxP, minG,maxG; minP=bb.min;maxP=bb.max; // Make the box well rounded wrt to major tick (only increase) for(int i=0;i<3;++i) // foreach axis { if (minP[i] == 0) minG[i] = -majorTick; else minG[i] = minP[i] + fmod(fabs(minP[i]), majorTick) - majorTick; if (maxP[i] == 0) maxG[i] = majorTick; else maxG[i] = maxP[i] - fmod(fabs(maxP[i]), majorTick) + majorTick; } glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); glColor3f(0.8f,0.8f,0.8f); glEnable(GL_LINE_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glDepthMask(GL_FALSE); Point3m viewPos = Point3m::Construct(this->curShot.GetViewPoint()); // qDebug("BG Grid MajorTick %4.2f MinorTick %4.2f ## camera pos %7.3f %7.3f %7.3f", majorTick, minorTick, viewPos[0],viewPos[1],viewPos[2]); // qDebug("BG Grid boxF %7.3f %7.3f %7.3f # %7.3f %7.3f %7.3f",minP[0],minP[1],minP[2],maxP[0],maxP[1],maxP[2]); // qDebug("BG Grid boxG %7.3f %7.3f %7.3f # %7.3f %7.3f %7.3f",minG[0],minG[1],minG[2],maxG[0],maxG[1],maxG[2]); for (int ii=0;ii<3;++ii) { for(int jj=0;jj<2;++jj) { bool front = FrontFacing(viewPos,ii,jj,minP,maxP); if( front || !backCullFlag) { DrawGridPlane(ii,jj,minP,maxP,minG,maxG,majorTick,minorTick,front?frontColor:backColor,baseLineWidth); if(shadowFlag) { glPushAttrib(GL_COLOR_BUFFER_BIT); glBlendColor(1.0f,1.0f,1.0f,0.4f); glBlendFunc(GL_CONSTANT_COLOR, GL_ONE); DrawFlatMesh(shared,cont,m,ii,jj,minG,maxG); glPopAttrib(); } } } } glDisable(GL_BLEND); glPopAttrib(); } void DecorateBackgroundPlugin::setValue(QString, Shotm val) { curShot=val; } MESHLAB_PLUGIN_NAME_EXPORTER(DecorateBackgroundPlugin)
{ "pile_set_name": "Github" }
/* * Kiwix Android * Copyright (c) 2019 Kiwix <android.kiwix.org> * 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 3 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, see <http://www.gnu.org/licenses/>. * */ package org.kiwix.kiwixmobile.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class IOUtils { private IOUtils() { //utility class } private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private static final int EOF = -1; public static byte[] toByteArray(final InputStream input) throws IOException { try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { copy(input, output); return output.toByteArray(); } } private static int copy(final InputStream input, final OutputStream output) throws IOException { final long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; } private static long copyLarge(final InputStream input, final OutputStream output) throws IOException { final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } }
{ "pile_set_name": "Github" }
/** * @file NCDBuf.h * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * 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. Neither the name of the author 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 AUTHOR 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 NCD_NCDBUF_H #define NCD_NCDBUF_H #include <stddef.h> #include <misc/BRefTarget.h> #include <structure/LinkedList0.h> #include <base/DebugObject.h> typedef struct { size_t buf_size; LinkedList0 used_bufs_list; LinkedList0 free_bufs_list; DebugObject d_obj; } NCDBufStore; typedef struct { NCDBufStore *store; LinkedList0Node list_node; BRefTarget ref_target; char data[]; } NCDBuf; void NCDBufStore_Init (NCDBufStore *o, size_t buf_size); void NCDBufStore_Free (NCDBufStore *o); size_t NCDBufStore_BufSize (NCDBufStore *o); NCDBuf * NCDBufStore_GetBuf (NCDBufStore *o); BRefTarget * NCDBuf_RefTarget (NCDBuf *o); char * NCDBuf_Data (NCDBuf *o); #endif
{ "pile_set_name": "Github" }
{ "insecure-registries": ["mtksms10.mediatek.inc:5000", "mtksitap54.mediatek.inc:5000"] }
{ "pile_set_name": "Github" }
<?php namespace One\Http; use One\Facades\Log; class Request { protected $server = []; protected $cookie = []; protected $get = []; protected $post = []; protected $files = []; protected $request = []; public $fd = 0; public $args = []; public $class = ''; public $func = ''; public $as_name = ''; public function __construct() { $this->server = &$_SERVER; $this->cookie = &$_COOKIE; $this->get = &$_GET; $this->post = &$_POST; $this->files = &$_FILES; $this->request = &$_REQUEST; } /** * @return string|null */ public function ip($ks = ['REMOTE_ADDR']) { foreach ($ks as $k){ $ip = $this->server($k); if($ip !== null){ return $ip; } } return null; } /** * @param $name * @return mixed|null */ public function server($name = null, $default = null) { if ($name === null) { return $this->server; } if (isset($this->server[$name])) { return $this->server[$name]; } $name = strtolower($name); if (isset($this->server[$name])) { return $this->server[$name]; } $name = str_replace('_', '-', $name); if (isset($this->server[$name])) { return $this->server[$name]; } return $default; } /** * @return mixed|null */ public function userAgent() { return $this->server('HTTP_USER_AGENT'); } /** * @return string */ public function uri() { $path = urldecode(array_get_not_null($this->server, ['request_uri', 'REQUEST_URI', 'argv.1'])); $paths = explode('?', $path); return '/' . trim($paths[0], '/'); } /** * request unique id * @return string */ public function id() { return Log::getTraceId(); } protected function getFromArr($arr, $key, $default = null) { if ($key === null) { return $arr; } return array_get($arr, $key, $default); } /** * @param $key * @param $default * @return mixed|null */ public function get($key = null, $default = null) { return $this->getFromArr($this->get, $key, $default); } /** * @param $key * @return mixed|null */ public function post($key = null, $default = null) { return $this->getFromArr($this->post, $key, $default); } /** * @param int $i * @return mixed|null */ public function arg($i = null, $default = null) { global $argv; return $this->getFromArr($argv, $i, $default); } /** * @param $key * @return mixed|null */ public function res($key = null, $default = null) { return $this->getFromArr($this->request, $key, $default); } /** * @param $key * @return mixed|null */ public function cookie($key = null, $default = null) { return $this->getFromArr($this->cookie, $key, $default); } /** * @return string */ public function input() { return file_get_contents('php://input'); } /** * @return array */ public function json() { return json_decode($this->input(), true); } /** * @return array */ public function file() { $files = []; foreach ($this->files as $name => $fs) { $keys = array_keys($fs); if (is_array($fs[$keys[0]])) { foreach ($keys as $k => $v) { foreach ($fs[$v] as $i => $val) { $files[$name][$i][$v] = $val; } } } else { $files[$name] = $fs; } } return $files; } /** * @return string */ public function method() { return strtolower($this->server('REQUEST_METHOD')); } /** * @return bool */ public function isJson() { if ($this->server('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' || strpos($this->server('HTTP_ACCEPT'), '/json') !== false) { return true; } else { return false; } } }
{ "pile_set_name": "Github" }
package m7mdra.com.htmlrecycler.viewholder import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import m7mdra.com.htmlrecycler.R class ListItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) { val listItem=view.findViewById<TextView>(R.id.listItem) }
{ "pile_set_name": "Github" }
/* Copyright (C) 2007-2014 Free Software Foundation, Inc. This file is part of BFD, the Binary File Descriptor library. 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 3 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. */ #include <machine/vmparam.h> #include <sys/param.h> /* This is an ugly way to hack around the incorrect * definition of UPAGES in i386/machparam.h. * * The definition should specify the size reserved * for "struct user" in core files in PAGES, * but instead it gives it in 512-byte core-clicks * for i386 and i860. UPAGES is used only in trad-core.c. */ #if UPAGES == 16 #undef UPAGES #define UPAGES 2 #endif #if UPAGES != 2 FIXME!! UPAGES is neither 2 nor 16 #endif #define HOST_PAGE_SIZE 1 #define HOST_SEGMENT_SIZE NBPG #define HOST_MACHINE_ARCH bfd_arch_i386 #define HOST_TEXT_START_ADDR USRTEXT #define HOST_STACK_END_ADDR USRSTACK
{ "pile_set_name": "Github" }
package com.gdp.mooc.biz; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.gdp.mooc.entity.Course; public interface CourseBiz { public List<Course> selectAllCourse(); Course selectByPrimaryKey(int id); int updateByPrimaryKeySelective(Course record); List<Course> coursesearch(String search); List<Course> freeCourse(); List<Course> vipCourse(); int deleteByPrimaryKey(String id); int savecourse(HttpServletRequest req); }
{ "pile_set_name": "Github" }
#define USB_CFG_DEVICE_NAME 'D','i','g','i','B','l','i','n','k' #define USB_CFG_DEVICE_NAME_LEN 9 #include <DigiUSB.h> byte in = 0; int Blue = 0; int Red = 0; int Green = 0; int next = 0; void setup() { DigiUSB.begin(); pinMode(0,OUTPUT); pinMode(1,OUTPUT); pinMode(2,OUTPUT); } void loop() { setBlue(); DigiUSB.refresh(); setBlue(); if (DigiUSB.available() > 0) { in = 0; in = DigiUSB.read(); if (next == 0){ if(in == 115){ next = 1; DigiUSB.println("Start"); } } else if (next == 1){ Red = in; DigiUSB.print("Red "); DigiUSB.println(in,DEC); next = 2; } else if (next == 2){ Green = in; DigiUSB.print("Green "); DigiUSB.println(in,DEC); next = 3; } else if (next == 3){ Blue = in; DigiUSB.print("Blue "); DigiUSB.println(in,DEC); next = 0; } } analogWrite(0,Red); analogWrite(1,Green); setBlue(); } void setBlue(){ if(Blue == 0){ digitalWrite(2,LOW); return; } else if(Blue == 255){ digitalWrite(2,HIGH); return; } // On period for (int x=0;x<Blue;x++){ digitalWrite(2,HIGH); } // Off period for(int x=0;x<(255-Blue);x++){ digitalWrite(2,LOW); } }
{ "pile_set_name": "Github" }
qcodes.logger.log_analysis -------------------------- .. automodule:: qcodes.logger.log_analysis :members:
{ "pile_set_name": "Github" }
+++ Title = "Bráulio Scarpelli" image = "braulio-scarpelli.jpg" type = "speaker" linktitle = "adriano-tavares" +++
{ "pile_set_name": "Github" }
# Dependencies markdown: rdiscount pygments: true # Permalinks permalink: pretty # Server destination: ./_gh_pages exclude: [".editorconfig", ".gitignore", ".ruby-version", "bower.json", "composer.json", "CONTRIBUTING.md", "CNAME", "LICENSE", "Gruntfile.js", "package.json", "node_modules", "README.md", "less"] port: 9001 # Custom vars repo: https://github.com/twbs/bootstrap download: https://github.com/twbs/bootstrap/archive/v3.0.0.zip download_dist: https://github.com/twbs/bootstrap/releases/download/v3.0.0/bootstrap-3.0.0-dist.zip blog: http://blog.getbootstrap.com expo: http://expo.getbootstrap.com cdn_css: //netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css cdn_theme_css: //netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css cdn_js: //netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js
{ "pile_set_name": "Github" }
package micdoodle8.mods.galacticraft.planets.mars.util; import micdoodle8.mods.galacticraft.api.GalacticraftRegistry; import micdoodle8.mods.galacticraft.core.GalacticraftCore; import micdoodle8.mods.galacticraft.core.inventory.ContainerParaChest; import micdoodle8.mods.galacticraft.core.inventory.ContainerRocketInventory; import micdoodle8.mods.galacticraft.core.network.PacketSimple; import micdoodle8.mods.galacticraft.core.network.PacketSimple.EnumSimplePacket; import micdoodle8.mods.galacticraft.core.recipe.NasaWorkbenchRecipe; import micdoodle8.mods.galacticraft.core.util.GCCoreUtil; import micdoodle8.mods.galacticraft.planets.mars.entities.EntityCargoRocket; import micdoodle8.mods.galacticraft.planets.mars.entities.EntityLandingBalloons; import micdoodle8.mods.galacticraft.planets.mars.entities.EntitySlimeling; import micdoodle8.mods.galacticraft.planets.mars.inventory.ContainerLaunchControllerAdvanced; import micdoodle8.mods.galacticraft.planets.mars.inventory.ContainerSlimeling; import micdoodle8.mods.galacticraft.planets.mars.network.PacketSimpleMars; import micdoodle8.mods.galacticraft.planets.mars.network.PacketSimpleMars.EnumSimplePacketMars; import micdoodle8.mods.galacticraft.planets.mars.tile.TileEntityLaunchController; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import java.util.HashMap; public class MarsUtil { public static void addRocketBenchT2Recipe(ItemStack result, HashMap<Integer, ItemStack> input) { GalacticraftRegistry.addT2RocketRecipe(new NasaWorkbenchRecipe(result, input)); } public static void adCargoRocketRecipe(ItemStack result, HashMap<Integer, ItemStack> input) { GalacticraftRegistry.addCargoRocketRecipe(new NasaWorkbenchRecipe(result, input)); } public static void openParachestInventory(EntityPlayerMP player, EntityLandingBalloons landerInv) { player.getNextWindowId(); player.closeContainer(); int windowId = player.currentWindowId; GalacticraftCore.packetPipeline.sendTo(new PacketSimple(EnumSimplePacket.C_OPEN_PARACHEST_GUI, GCCoreUtil.getDimensionID(player.world), new Object[] { windowId, 1, landerInv.getEntityId() }), player); player.openContainer = new ContainerParaChest(player.inventory, landerInv, player); player.openContainer.windowId = windowId; player.openContainer.addListener(player); } public static void openSlimelingInventory(EntityPlayerMP player, EntitySlimeling slimeling) { player.getNextWindowId(); player.closeContainer(); int windowId = player.currentWindowId; GalacticraftCore.packetPipeline.sendTo(new PacketSimpleMars(EnumSimplePacketMars.C_OPEN_CUSTOM_GUI, GCCoreUtil.getDimensionID(player.world), new Object[] { windowId, 0, slimeling.getEntityId() }), player); player.openContainer = new ContainerSlimeling(player.inventory, slimeling, player); player.openContainer.windowId = windowId; player.openContainer.addListener(player); } public static void openCargoRocketInventory(EntityPlayerMP player, EntityCargoRocket rocket) { player.getNextWindowId(); player.closeContainer(); int windowId = player.currentWindowId; GalacticraftCore.packetPipeline.sendTo(new PacketSimpleMars(EnumSimplePacketMars.C_OPEN_CUSTOM_GUI, GCCoreUtil.getDimensionID(player.world), new Object[] { windowId, 1, rocket.getEntityId() }), player); player.openContainer = new ContainerRocketInventory(player.inventory, rocket, rocket.rocketType, player); player.openContainer.windowId = windowId; player.openContainer.addListener(player); } public static void openAdvancedLaunchController(EntityPlayerMP player, TileEntityLaunchController launchController) { player.getNextWindowId(); player.closeContainer(); int windowId = player.currentWindowId; GalacticraftCore.packetPipeline.sendTo(new PacketSimpleMars(EnumSimplePacketMars.C_OPEN_CUSTOM_GUI_TILE, GCCoreUtil.getDimensionID(player.world), new Object[] { windowId, 0, launchController.getPos() }), player); player.openContainer = new ContainerLaunchControllerAdvanced(player.inventory, launchController, player); player.openContainer.windowId = windowId; player.openContainer.addListener(player); } }
{ "pile_set_name": "Github" }
package cms.utils; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.lang3.StringUtils; /** * 字符串工具类 * */ public class StringUtil { /** * 解析一个带 token 分隔符的字符串,这个方法的效率比直接调用String的split()方法快大约1倍 * @param tokenedStr * @param token * @return String[] */ public static String[] splitString(String tokenedStr, String token) { String[] ids = null; if (tokenedStr != null) { StringTokenizer st = new StringTokenizer(tokenedStr, token); final int arraySize = st.countTokens(); if (arraySize > 0) { ids = new String[arraySize]; int counter = 0; while (st.hasMoreTokens()) { ids[counter++] = st.nextToken(); } } } return ids; } /** * 把字符串数组组合成一个以指定分隔符分隔的字符串。 * @param strs 字符串数组 * @param seperator 分隔符 * @return */ public static String mergeString(String[] strs, String seperator) { StringBuilder sb = new StringBuilder(); mergeString(strs, seperator, sb); return sb.toString(); } /** * 把List数组组合成一个以指定分隔符分隔的字符串。 * @param list List数组 * @param seperator 分隔符 * @return */ public static String mergeString(List list, String seperator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { if (i != 0 && list.get(i).toString()!= null && !"".equals(list.get(i).toString().trim())) { sb.append(seperator); } if(list.get(i).toString()!= null && !"".equals(list.get(i).toString().trim())){ sb.append(list.get(i)); } } return sb.toString(); } /** * 把字符串数组组合成一个以指定分隔符分隔的字符串,并追加到给定的<code>StringBuilder</code> * @param strs 字符串数组 * @param seperator 分隔符 * @return **/ public static void mergeString(String[] strs, String seperator, StringBuilder sb) { for (int i = 0; i < strs.length; i++) { if (i != 0) { sb.append(seperator); } sb.append(strs[i]); } } /** * 按字节长度截取字符串 * @param str 要截取的字符串 * @param length 截取长度 * @return * @throws Exception */ public static String bSubstring(String str, int length) throws Exception{ byte[] bytes = str.getBytes("Unicode"); int n = 0; // 表示当前的字节数 int i = 2; // 要截取的字节数,从第3个字节开始 for (; i < bytes.length && n < length; i++){ // 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节 if (i % 2 == 1){ n++; // 在UCS2第二个字节时n加1 }else{ // 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节 if (bytes[i] != 0){ n++; } } } // 如果i为奇数时,处理成偶数 if (i % 2 == 1){ // 该UCS2字符是汉字时,去掉这个截一半的汉字 if (bytes[i - 1] != 0) i = i - 1; // 该UCS2字符是字母或数字,则保留该字符 else i = i + 1; } return new String(bytes, 0, i, "Unicode"); } /** * 清除前后空格&nbsp; * @param html * @return public static String clearSpace(String html){ return html.replaceAll("^&nbsp;|&nbsp;$",""); } */ /** * 替换空格&nbsp; * @param html * @return */ public static String replaceSpace(String html){ return html.toLowerCase().replaceAll("(?i)&nbsp;",""); } /** * 转义like语句中的 * <code>'_'</code><code>'%'</code> * 将<code>'?'</code>转成sql的<code>'/_'</code> * 将<code>'%'</code>转成sql的<code>'/%'</code> * <p> * 例如搜索<code>?aa*bb?c_d%f</code>将转化成<br/> * <code>_aa%bb_c/_d/%f</code> * </p> * @param likeStr * @return * @author <a href="http://jdkcn.com" mce_href="http://jdkcn.com">somebody</a> */ public static String escapeSQLLike(String likeStr) { String str = StringUtils.replace(likeStr, "_", "/_"); str = StringUtils.replace(str, "%", "/%"); str = StringUtils.replace(str, "?", "_"); str = StringUtils.replace(str, "*", "%"); return str; } }
{ "pile_set_name": "Github" }
module.exports = require('./every');
{ "pile_set_name": "Github" }
package chapter02.section02.thread_2_2_11.project_1_twoStop; public class ThreadB extends Thread { private Service service; public ThreadB(Service service) { super(); this.service = service; } @Override public void run() { service.methodB(); } }
{ "pile_set_name": "Github" }
doc/modules .pybuild/
{ "pile_set_name": "Github" }
package press import android.annotation.SuppressLint import press.di.AppComponent import press.di.DaggerAppComponent @Suppress("unused") @SuppressLint("Registered") class ReleasePressApp : PressApp() { override fun buildDependencyGraph(): AppComponent = DaggerAppComponent.builder().build() }
{ "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.pinot.core.geospatial.transform.function; import com.google.common.base.Preconditions; import java.util.EnumSet; import org.apache.pinot.common.Utils; import org.apache.pinot.core.geospatial.GeometryUtils; import org.apache.pinot.core.geospatial.serde.GeometrySerializer; import org.apache.pinot.core.operator.blocks.ProjectionBlock; import org.apache.pinot.core.plan.DocIdSetPlanNode; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.io.ParseException; /** * Constructor function for polygon object from text. */ public class StPolygonFunction extends ConstructFromTextFunction { public static final String FUNCTION_NAME = "ST_Polygon"; @Override protected GeometryFactory getGeometryFactory() { return GeometryUtils.GEOMETRY_FACTORY; } @Override public String getName() { return FUNCTION_NAME; } @Override public byte[][] transformToBytesValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new byte[DocIdSetPlanNode.MAX_DOC_PER_CALL][]; } String[] argumentValues = _transformFunction.transformToStringValuesSV(projectionBlock); int length = projectionBlock.getNumDocs(); for (int i = 0; i < length; i++) { try { Geometry geometry = _reader.read(argumentValues[i]); Preconditions.checkArgument(geometry instanceof Polygon, "The geometry object must be polygon"); _results[i] = GeometrySerializer.serialize(geometry); } catch (ParseException e) { new RuntimeException(String.format("Failed to parse geometry from string: %s", argumentValues[i])); } } return _results; } }
{ "pile_set_name": "Github" }
# Customizations for the virtlxcd.service systemd unit VIRTLXCD_ARGS="--timeout 120"
{ "pile_set_name": "Github" }
// // AppDelegate.h // YLFaceuDemo // // Created by guikz-xueba on 16/5/22. // Copyright © 2016年 guikz. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
{ "pile_set_name": "Github" }
--- kind: Template apiVersion: v1 metadata: name: glusterblock-provisioner labels: glusterfs: block-template glusterblock: template annotations: description: glusterblock provisioner template tags: glusterfs objects: - kind: ClusterRole apiVersion: v1 metadata: name: glusterblock-provisioner-runner labels: glusterfs: block-provisioner-runner-clusterrole glusterblock: provisioner-runner-clusterrole rules: - apiGroups: [""] resources: ["persistentvolumes"] verbs: ["get", "list", "watch", "create", "delete"] - apiGroups: [""] resources: ["persistentvolumeclaims"] verbs: ["get", "list", "watch", "update"] - apiGroups: ["storage.k8s.io"] resources: ["storageclasses"] verbs: ["get", "list", "watch"] - apiGroups: [""] resources: ["events"] verbs: ["list", "watch", "create", "update", "patch"] - apiGroups: [""] resources: ["services"] verbs: ["get"] - apiGroups: [""] resources: ["secrets"] verbs: ["get", "create", "delete"] - apiGroups: [""] resources: ["routes"] verbs: ["get", "list"] - apiVersion: v1 kind: ServiceAccount metadata: name: glusterblock-${CLUSTER_NAME}-provisioner labels: glusterfs: block-${CLUSTER_NAME}-provisioner-sa glusterblock: ${CLUSTER_NAME}-provisioner-sa - apiVersion: v1 kind: ClusterRoleBinding metadata: name: glusterblock-${CLUSTER_NAME}-provisioner roleRef: name: glusterblock-provisioner-runner subjects: - kind: ServiceAccount name: glusterblock-${CLUSTER_NAME}-provisioner namespace: ${NAMESPACE} - kind: DeploymentConfig apiVersion: v1 metadata: name: glusterblock-${CLUSTER_NAME}-provisioner-dc labels: glusterfs: block-${CLUSTER_NAME}-provisioner-dc glusterblock: ${CLUSTER_NAME}-provisioner-dc annotations: description: Defines how to deploy the glusterblock provisioner pod. spec: replicas: 1 selector: glusterfs: block-${CLUSTER_NAME}-provisioner-pod triggers: - type: ConfigChange strategy: type: Recreate template: metadata: name: glusterblock-provisioner labels: glusterfs: block-${CLUSTER_NAME}-provisioner-pod spec: serviceAccountName: glusterblock-${CLUSTER_NAME}-provisioner containers: - name: glusterblock-provisioner image: ${IMAGE_NAME}:${IMAGE_VERSION} imagePullPolicy: IfNotPresent env: - name: PROVISIONER_NAME value: gluster.org/glusterblock parameters: - name: IMAGE_NAME displayName: glusterblock provisioner container image name required: True - name: IMAGE_VERSION displayName: glusterblock provisioner container image version required: True - name: NAMESPACE displayName: glusterblock provisioner namespace description: The namespace in which these resources are being created required: True - name: CLUSTER_NAME displayName: GlusterFS cluster name description: A unique name to identify which heketi service manages this cluster, useful for running multiple heketi instances value: storage
{ "pile_set_name": "Github" }
// Copyright 2008 the V8 project authors. 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. function f0() { return this; } assertTrue(this === f0.call(), "1"); assertTrue(this === f0.call(this), "w"); assertTrue(this === f0.call(this, 1), "w"); assertTrue(this === f0.call(this, 1, 2), "w"); assertTrue(this === f0.call(null), "3a"); assertTrue(this === f0.call(null, 1), "3b"); assertTrue(this === f0.call(null, 1, 2), "3c"); assertTrue(this === f0.call(void 0), "4a"); assertTrue(this === f0.call(void 0, 1), "4b"); assertTrue(this === f0.call(void 0, 1, 2), "4c"); var x = {}; assertTrue(x === f0.call(x)); assertTrue(x === f0.call(x, 1)); assertTrue(x === f0.call(x, 1, 2)); function f1(a) { a = a || 'i'; return this[a]; } assertEquals(1, f1.call({i:1})); assertEquals(42, f1.call({i:42}, 'i')); assertEquals(87, f1.call({j:87}, 'j', 1)); assertEquals(99, f1.call({k:99}, 'k', 1, 2)); function f2(a, b) { a = a || 'n'; b = b || 2; return this[a] + b; } var x = {n: 1}; assertEquals(3, f2.call(x)); assertEquals(14, f2.call({i:12}, 'i')); assertEquals(42, f2.call(x, 'n', 41)); assertEquals(87, f2.call(x, 'n', 86, 1)); assertEquals(99, f2.call(x, 'n', 98, 1, 2)); function fn() { return arguments.length; } assertEquals(0, fn.call()); assertEquals(0, fn.call(this)); assertEquals(0, fn.call(null)); assertEquals(0, fn.call(void 0)); assertEquals(1, fn.call(this, 1)); assertEquals(2, fn.call(this, 1, 2)); assertEquals(3, fn.call(this, 1, 2, 3));
{ "pile_set_name": "Github" }
<?php /** * @author Adam (charrondev) Charron <adam.c@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ namespace Vanilla\Formatting\Quill; use Vanilla\Formatting\Quill\Blots\AbstractBlot; use Vanilla\Formatting\Quill\Blots\Lines\AbstractLineTerminatorBlot; /** * Class for sorting operations into blots and groups. */ class BlotGroupCollection implements \IteratorAggregate { /** @var array[] The operations to parse. */ private $operations; /** @var string[] The blots that we are allowed to parse out. */ private $allowedBlotClasses; /** @var string The parsing mode to be passed through to blots when they are created. */ private $parseMode = Parser::PARSE_MODE_NORMAL; /** @var BlotGroup[] The array of groups being built up. */ private $groups; /** @var AbstractBlot The blot being build up in the iteration */ private $inProgressBlot; /** @var BlotGroup the group being built up in the iteration. */ private $inProgressGroup; /** @var array[] the line being built up in the iteration. */ private $inProgressLine; /** @var array The primary operation being iterated. */ private $currentOp; /** @var array The next operation being iterated. */ private $nextOp; /** @var array The previous operation being iterated. */ private $prevOp; // ITERABLE IMPLEMENTATION /** * @inheritdoc */ public function getIterator() { return new \ArrayIterator($this->groups); } /** * BlotGroupCollection constructor. * * @param array[] $operations The operations to generate groups for. * @param string[] $allowedBlotClasses The class names of the blots we are allowed to create in the groups. * @param string $parseMode The parsing mode to create the blots with. */ public function __construct(array $operations, array $allowedBlotClasses, string $parseMode) { $this->operations = $operations; $this->allowedBlotClasses = $allowedBlotClasses; $this->parseMode = $parseMode; $this->createBlotGroups(); } /** * Push the current line into the group and reset the line. */ private function clearLine() { $this->inProgressGroup->pushBlots($this->inProgressLine); $this->inProgressLine = []; } /** * Get the previous blot group. * * @return BlotGroup|null */ private function getPreviousBlotGroup(): ?BlotGroup { return $this->groups[count($this->groups) - 1] ?? null; } /** * Push the group into our groups array and start a new one. * Do not push an empty group. */ private function clearBlotGroup() { if ($this->inProgressGroup->isEmpty()) { return; } $currentGroup = $this->inProgressGroup; $prevGroup = $this->getPreviousBlotGroup(); if ($prevGroup && $prevGroup->canNest($currentGroup)) { $prevGroup->nestGroup($currentGroup); } elseif ($prevGroup && $prevGroup->canMerge($currentGroup)) { // Merge the current group into the previous one. $prevGroup->pushBlots($currentGroup->getBlotsAndGroups()); } else { $this->groups[] = $this->inProgressGroup; } $this->inProgressGroup = new BlotGroup(); } /** * Create Blots and their groups. */ private function createBlotGroups() { $this->inProgressGroup = new BlotGroup(); $this->inProgressLine = []; $this->groups = []; for ($i = 0; $i < count($this->operations); $i++) { $this->currentOp = $this->operations[$i]; $this->prevOp = $this->operations[$i - 1] ?? []; $this->nextOp = $this->operations[$i + 1] ?? []; $this->inProgressBlot = $this->getCurrentBlot(); // In event of break blots we want to clear the group if applicable and the skip to the next item. if ($this->currentOp === Parser::BREAK_OPERATION) { $this->clearLine(); $this->clearBlotGroup(); continue; } if (($this->inProgressBlot->shouldClearCurrentGroup($this->inProgressGroup))) { // Ask the blot if it should close the current group. $this->clearBlotGroup(); } // Ask the blot if it should close the current group. if ($this->inProgressBlot instanceof AbstractLineTerminatorBlot) { // Clear the line because we we had line terminator. $this->clearLine(); } // Push the blot into our current line. $this->inProgressLine[] = $this->inProgressBlot; // Clear the line because we have a line terminator. if ($this->inProgressBlot instanceof AbstractLineTerminatorBlot) { $this->clearLine(); } // Some block type blots get a group (and line) all to themselves. if ($this->inProgressBlot->isOwnGroup()) { $this->clearLine(); $this->clearBlotGroup(); } } // Iteration is done so we need to clear the line then the group. $this->clearLine(); if (!$this->inProgressGroup->isEmpty()) { $this->clearBlotGroup(); } } /** * Get the matching blot for a sequence of operations. Returns the default if no match is found. * @return AbstractBlot */ public function getCurrentBlot(): AbstractBlot { // Fallback to a TextBlot if possible. Otherwise we fallback to rendering nothing at all. $blotClass = Blots\TextBlot::matches($this->currentOp) ? Blots\TextBlot::class : Blots\NullBlot::class; foreach ($this->allowedBlotClasses as $blot) { // Find the matching blot type for the current, last, and next operation. if ($blot::matches($this->currentOp)) { $blotClass = $blot; break; } } return new $blotClass($this->currentOp, $this->prevOp, $this->nextOp, $this->parseMode); } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: fe8140fa12794bc43a7946977ca55fa8 timeCreated: 1492492199 licenseType: Free NativeFormatImporter: mainObjectFileID: 100100000 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
form textTest { height = 100% width = 240 layout = LAYOUT_VERTICAL label topLabel { text = Text fontSize = 22 } button fontButton { width = 100% height = 50 text = Font (arial) } button wrapButton : fontButton { text = Word Wrap (On) } button clipRectButton : fontButton { text = Clipping (On) } button reverseButton : fontButton { text = Reverse Text (Off) } button switchClipRegionButton : fontButton { text = Clip Region (Viewport) } button simpleAdvancedButton : fontButton { text = Font API (Advanced) } label { size = 10,10 } label sizeLabel : topLabel { text = Size (18) } container size { width = 100% button smallerButton { width = 50 height = 50 text = - } button biggerButton : smallerButton { x = 50 text = + } } label { size = 10,10 } label alignmentLabel : topLabel { text = Align (Top-left) } container alignments { width = 100% layout = LAYOUT_FLOW button topLeftButton { size = 60, 60 text = fontSize = 20 } button topCenterButton : topLeftButton { text = ^ } button topRightButton : topLeftButton { text = } button centerLeftButton : topLeftButton { text = < } button centerButton : topLeftButton { text = . } button centerRightButton : topLeftButton { text = > } button bottomLeftButton : topLeftButton { text = } button bottomCenterButton : topLeftButton { text = v } button bottomRightButton : topLeftButton { text = } } }
{ "pile_set_name": "Github" }
/*++ NDK Version: 0098 Copyright (c) Alex Ionescu. All rights reserved. Header Name: lpctypes.h Abstract: Type definitions for the Loader. Author: Alex Ionescu (alexi@tinykrnl.org) - Updated - 27-Feb-2006 --*/ #ifndef _KETYPES_H #define _KETYPES_H // // Dependencies // #include <umtypes.h> #ifndef NTOS_MODE_USER #include <haltypes.h> #include <potypes.h> #include <ifssupp.h> #endif // // Context Record Flags // #define CONTEXT_DEBUGGER (CONTEXT_FULL | CONTEXT_FLOATING_POINT) // // Maximum System Descriptor Table Entries // #define SSDT_MAX_ENTRIES 2 // // Processor Architectures // #define PROCESSOR_ARCHITECTURE_INTEL 0 #define PROCESSOR_ARCHITECTURE_MIPS 1 #define PROCESSOR_ARCHITECTURE_ALPHA 2 #define PROCESSOR_ARCHITECTURE_PPC 3 #define PROCESSOR_ARCHITECTURE_SHX 4 #define PROCESSOR_ARCHITECTURE_ARM 5 #define PROCESSOR_ARCHITECTURE_IA64 6 #define PROCESSOR_ARCHITECTURE_ALPHA64 7 #define PROCESSOR_ARCHITECTURE_MSIL 8 #define PROCESSOR_ARCHITECTURE_AMD64 9 #define PROCESSOR_ARCHITECTURE_UNKNOWN 0xFFFF // // Object Type Mask for Kernel Dispatcher Objects // #define KOBJECT_TYPE_MASK 0x7F #define KOBJECT_LOCK_BIT 0x80 // // Dispatcher Priority increments // #define THREAD_ALERT_INCREMENT 2 // // Physical memory offset of KUSER_SHARED_DATA // #define KI_USER_SHARED_DATA_PHYSICAL 0x41000 // // Quantum values and decrements // #define MAX_QUANTUM 0x7F #define WAIT_QUANTUM_DECREMENT 1 #define CLOCK_QUANTUM_DECREMENT 3 // // Kernel Feature Bits // #define KF_V86_VIS 0x00000001 #define KF_RDTSC 0x00000002 #define KF_CR4 0x00000004 #define KF_CMOV 0x00000008 #define KF_GLOBAL_PAGE 0x00000010 #define KF_LARGE_PAGE 0x00000020 #define KF_MTRR 0x00000040 #define KF_CMPXCHG8B 0x00000080 #define KF_MMX 0x00000100 #define KF_WORKING_PTE 0x00000200 #define KF_PAT 0x00000400 #define KF_FXSR 0x00000800 #define KF_FAST_SYSCALL 0x00001000 #define KF_XMMI 0x00002000 #define KF_3DNOW 0x00004000 #define KF_AMDK6MTRR 0x00008000 #define KF_XMMI64 0x00010000 #define KF_DTS 0x00020000 #define KF_NX_BIT 0x20000000 #define KF_NX_DISABLED 0x40000000 #define KF_NX_ENABLED 0x80000000 // // Internal Exception Codes // #define KI_EXCEPTION_INTERNAL 0x10000000 #define KI_EXCEPTION_ACCESS_VIOLATION (KI_EXCEPTION_INTERNAL | 0x04) #ifndef NTOS_MODE_USER // // Number of dispatch codes supported by KINTERRUPT // #ifdef _M_AMD64 #define DISPATCH_LENGTH 4 #elif (NTDDI_VERSION >= NTDDI_LONGHORN) #define DISPATCH_LENGTH 135 #else #define DISPATCH_LENGTH 106 #endif #else // // KPROCESSOR_MODE Type // typedef CCHAR KPROCESSOR_MODE; // // Dereferencable pointer to KUSER_SHARED_DATA in User-Mode // #define SharedUserData ((KUSER_SHARED_DATA *)USER_SHARED_DATA) // // Maximum WOW64 Entries in KUSER_SHARED_DATA // #define MAX_WOW64_SHARED_ENTRIES 16 // // Maximum Processor Features supported in KUSER_SHARED_DATA // #define PROCESSOR_FEATURE_MAX 64 // // Event Types // typedef enum _EVENT_TYPE { NotificationEvent, SynchronizationEvent } EVENT_TYPE; // // Timer Types // typedef enum _TIMER_TYPE { NotificationTimer, SynchronizationTimer } TIMER_TYPE; // // Wait Types // typedef enum _WAIT_TYPE { WaitAll, WaitAny } WAIT_TYPE; // // Processor Execution Modes // typedef enum _MODE { KernelMode, UserMode, MaximumMode } MODE; // // Wait Reasons // typedef enum _KWAIT_REASON { Executive, FreePage, PageIn, PoolAllocation, DelayExecution, Suspended, UserRequest, WrExecutive, WrFreePage, WrPageIn, WrPoolAllocation, WrDelayExecution, WrSuspended, WrUserRequest, WrEventPair, WrQueue, WrLpcReceive, WrLpcReply, WrVirtualMemory, WrPageOut, WrRendezvous, Spare2, WrGuardedMutex, Spare4, Spare5, Spare6, WrKernel, WrResource, WrPushLock, WrMutex, WrQuantumEnd, WrDispatchInt, WrPreempted, WrYieldExecution, MaximumWaitReason } KWAIT_REASON; // // Profiling Sources // typedef enum _KPROFILE_SOURCE { ProfileTime, ProfileAlignmentFixup, ProfileTotalIssues, ProfilePipelineDry, ProfileLoadInstructions, ProfilePipelineFrozen, ProfileBranchInstructions, ProfileTotalNonissues, ProfileDcacheMisses, ProfileIcacheMisses, ProfileCacheMisses, ProfileBranchMispredictions, ProfileStoreInstructions, ProfileFpInstructions, ProfileIntegerInstructions, Profile2Issue, Profile3Issue, Profile4Issue, ProfileSpecialInstructions, ProfileTotalCycles, ProfileIcacheIssues, ProfileDcacheAccesses, ProfileMemoryBarrierCycles, ProfileLoadLinkedIssues, ProfileMaximum } KPROFILE_SOURCE; // // NT Product and Architecture Types // typedef enum _NT_PRODUCT_TYPE { NtProductWinNt = 1, NtProductLanManNt, NtProductServer } NT_PRODUCT_TYPE, *PNT_PRODUCT_TYPE; typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE { StandardDesign, NEC98x86, EndAlternatives } ALTERNATIVE_ARCHITECTURE_TYPE; #endif // // Thread States // typedef enum _KTHREAD_STATE { Initialized, Ready, Running, Standby, Terminated, Waiting, Transition, DeferredReady, #if (NTDDI_VERSION >= NTDDI_WS03) GateWait #endif } KTHREAD_STATE, *PKTHREAD_STATE; // // Kernel Object Types // typedef enum _KOBJECTS { EventNotificationObject = 0, EventSynchronizationObject = 1, MutantObject = 2, ProcessObject = 3, QueueObject = 4, SemaphoreObject = 5, ThreadObject = 6, GateObject = 7, TimerNotificationObject = 8, TimerSynchronizationObject = 9, Spare2Object = 10, Spare3Object = 11, Spare4Object = 12, Spare5Object = 13, Spare6Object = 14, Spare7Object = 15, Spare8Object = 16, Spare9Object = 17, ApcObject = 18, DpcObject = 19, DeviceQueueObject = 20, EventPairObject = 21, InterruptObject = 22, ProfileObject = 23, ThreadedDpcObject = 24, MaximumKernelObject = 25 } KOBJECTS; // // Adjust reasons // typedef enum _ADJUST_REASON { AdjustNone = 0, AdjustUnwait = 1, AdjustBoost = 2 } ADJUST_REASON; // // Continue Status // typedef enum _KCONTINUE_STATUS { ContinueError = 0, ContinueSuccess, ContinueProcessorReselected, ContinueNextProcessor } KCONTINUE_STATUS; // // Process States // typedef enum _KPROCESS_STATE { ProcessInMemory, ProcessOutOfMemory, ProcessInTransition, ProcessInSwap, ProcessOutSwap, } KPROCESS_STATE, *PKPROCESS_STATE; // // NtVdmControl Classes // typedef enum _VDMSERVICECLASS { VdmStartExecution = 0, VdmQueueInterrupt = 1, VdmDelayInterrupt = 2, VdmInitialize = 3, VdmFeatures = 4, VdmSetInt21Handler = 5, VdmQueryDir = 6, VdmPrinterDirectIoOpen = 7, VdmPrinterDirectIoClose = 8, VdmPrinterInitialize = 9, VdmSetLdtEntries = 10, VdmSetProcessLdtInfo = 11, VdmAdlibEmulation = 12, VdmPMCliControl = 13, VdmQueryVdmProcess = 14, } VDMSERVICECLASS; #ifdef NTOS_MODE_USER // // APC Normal Routine // typedef VOID (NTAPI *PKNORMAL_ROUTINE)( _In_ PVOID NormalContext, _In_ PVOID SystemArgument1, _In_ PVOID SystemArgument2 ); // // Timer Routine // typedef VOID (NTAPI *PTIMER_APC_ROUTINE)( _In_ PVOID TimerContext, _In_ ULONG TimerLowValue, _In_ LONG TimerHighValue ); // // System Time Structure // typedef struct _KSYSTEM_TIME { ULONG LowPart; LONG High1Time; LONG High2Time; } KSYSTEM_TIME, *PKSYSTEM_TIME; // // Shared Kernel User Data // typedef struct _KUSER_SHARED_DATA { ULONG TickCountLowDeprecated; ULONG TickCountMultiplier; volatile KSYSTEM_TIME InterruptTime; volatile KSYSTEM_TIME SystemTime; volatile KSYSTEM_TIME TimeZoneBias; USHORT ImageNumberLow; USHORT ImageNumberHigh; WCHAR NtSystemRoot[260]; ULONG MaxStackTraceDepth; ULONG CryptoExponent; ULONG TimeZoneId; ULONG LargePageMinimum; ULONG Reserved2[7]; NT_PRODUCT_TYPE NtProductType; BOOLEAN ProductTypeIsValid; ULONG NtMajorVersion; ULONG NtMinorVersion; BOOLEAN ProcessorFeatures[PROCESSOR_FEATURE_MAX]; ULONG Reserved1; ULONG Reserved3; volatile ULONG TimeSlip; ALTERNATIVE_ARCHITECTURE_TYPE AlternativeArchitecture; LARGE_INTEGER SystemExpirationDate; ULONG SuiteMask; BOOLEAN KdDebuggerEnabled; #if (NTDDI_VERSION >= NTDDI_WINXPSP2) UCHAR NXSupportPolicy; #endif volatile ULONG ActiveConsoleId; volatile ULONG DismountCount; ULONG ComPlusPackage; ULONG LastSystemRITEventTickCount; ULONG NumberOfPhysicalPages; BOOLEAN SafeBootMode; ULONG TraceLogging; ULONG Fill0; ULONGLONG TestRetInstruction; ULONG SystemCall; ULONG SystemCallReturn; ULONGLONG SystemCallPad[3]; union { volatile KSYSTEM_TIME TickCount; volatile ULONG64 TickCountQuad; }; ULONG Cookie; #if (NTDDI_VERSION >= NTDDI_WS03) LONGLONG ConsoleSessionForegroundProcessId; ULONG Wow64SharedInformation[MAX_WOW64_SHARED_ENTRIES]; #endif #if (NTDDI_VERSION >= NTDDI_LONGHORN) USHORT UserModeGlobalLogger[8]; ULONG HeapTracingPid[2]; ULONG CritSecTracingPid[2]; union { ULONG SharedDataFlags; struct { ULONG DbgErrorPortPresent:1; ULONG DbgElevationEnabled:1; ULONG DbgVirtEnabled:1; ULONG DbgInstallerDetectEnabled:1; ULONG SpareBits:28; }; }; ULONG ImageFileExecutionOptions; KAFFINITY ActiveProcessorAffinity; #endif } KUSER_SHARED_DATA, *PKUSER_SHARED_DATA; // // VDM Structures // #include "pshpack1.h" typedef struct _VdmVirtualIca { LONG ica_count[8]; LONG ica_int_line; LONG ica_cpu_int; USHORT ica_base; USHORT ica_hipiri; USHORT ica_mode; UCHAR ica_master; UCHAR ica_irr; UCHAR ica_isr; UCHAR ica_imr; UCHAR ica_ssr; } VDMVIRTUALICA, *PVDMVIRTUALICA; #include "poppack.h" typedef struct _VdmIcaUserData { PVOID pIcaLock; PVDMVIRTUALICA pIcaMaster; PVDMVIRTUALICA pIcaSlave; PULONG pDelayIrq; PULONG pUndelayIrq; PULONG pDelayIret; PULONG pIretHooked; PULONG pAddrIretBopTable; PHANDLE phWowIdleEvent; PLARGE_INTEGER pIcaTimeout; PHANDLE phMainThreadSuspended; } VDMICAUSERDATA, *PVDMICAUSERDATA; typedef struct _VDM_INITIALIZE_DATA { PVOID TrapcHandler; PVDMICAUSERDATA IcaUserData; } VDM_INITIALIZE_DATA, *PVDM_INITIALIZE_DATA; #else // // System Thread Start Routine // typedef VOID (NTAPI *PKSYSTEM_ROUTINE)( PKSTART_ROUTINE StartRoutine, PVOID StartContext ); // // APC Environment Types // typedef enum _KAPC_ENVIRONMENT { OriginalApcEnvironment, AttachedApcEnvironment, CurrentApcEnvironment, InsertApcEnvironment } KAPC_ENVIRONMENT; // // PRCB DPC Data // typedef struct _KDPC_DATA { LIST_ENTRY DpcListHead; ULONG_PTR DpcLock; #ifdef _M_AMD64 volatile LONG DpcQueueDepth; #else volatile ULONG DpcQueueDepth; #endif ULONG DpcCount; } KDPC_DATA, *PKDPC_DATA; // // Per-Processor Lookaside List // typedef struct _PP_LOOKASIDE_LIST { struct _GENERAL_LOOKASIDE *P; struct _GENERAL_LOOKASIDE *L; } PP_LOOKASIDE_LIST, *PPP_LOOKASIDE_LIST; // // Architectural Types // #include <arch/ketypes.h> // // Kernel Memory Node // #include <pshpack1.h> typedef struct _KNODE { SLIST_HEADER DeadStackList; SLIST_HEADER PfnDereferenceSListHead; KAFFINITY ProcessorMask; ULONG Color; UCHAR Seed; UCHAR NodeNumber; ULONG Flags; ULONG MmShiftedColor; ULONG FreeCount[2]; struct _SINGLE_LIST_ENTRY *PfnDeferredList; } KNODE, *PKNODE; #include <poppack.h> // // Kernel Profile Object // typedef struct _KPROFILE { CSHORT Type; CSHORT Size; LIST_ENTRY ProfileListEntry; struct _KPROCESS *Process; PVOID RangeBase; PVOID RangeLimit; ULONG BucketShift; PVOID Buffer; ULONG_PTR Segment; KAFFINITY Affinity; KPROFILE_SOURCE Source; BOOLEAN Started; } KPROFILE, *PKPROFILE; // // Kernel Interrupt Object // typedef struct _KINTERRUPT { CSHORT Type; CSHORT Size; LIST_ENTRY InterruptListEntry; PKSERVICE_ROUTINE ServiceRoutine; #if (NTDDI_VERSION >= NTDDI_LONGHORN) PKSERVICE_ROUTINE MessageServiceRoutine; ULONG MessageIndex; #endif PVOID ServiceContext; KSPIN_LOCK SpinLock; ULONG TickCount; PKSPIN_LOCK ActualLock; PKINTERRUPT_ROUTINE DispatchAddress; ULONG Vector; KIRQL Irql; KIRQL SynchronizeIrql; BOOLEAN FloatingSave; BOOLEAN Connected; CCHAR Number; BOOLEAN ShareVector; KINTERRUPT_MODE Mode; #if (NTDDI_VERSION >= NTDDI_LONGHORN) KINTERRUPT_POLARITY Polarity; #endif ULONG ServiceCount; ULONG DispatchCount; #if (NTDDI_VERSION >= NTDDI_LONGHORN) ULONGLONG Rsvd1; #endif #ifdef _M_AMD64 PKTRAP_FRAME TrapFrame; PVOID Reserved; #endif ULONG DispatchCode[DISPATCH_LENGTH]; } KINTERRUPT; // // Kernel Event Pair Object // typedef struct _KEVENT_PAIR { CSHORT Type; CSHORT Size; KEVENT LowEvent; KEVENT HighEvent; } KEVENT_PAIR, *PKEVENT_PAIR; // // Kernel No Execute Options // typedef struct _KEXECUTE_OPTIONS { UCHAR ExecuteDisable:1; UCHAR ExecuteEnable:1; UCHAR DisableThunkEmulation:1; UCHAR Permanent:1; UCHAR ExecuteDispatchEnable:1; UCHAR ImageDispatchEnable:1; UCHAR Spare:2; } KEXECUTE_OPTIONS, *PKEXECUTE_OPTIONS; #if (NTDDI_VERSION >= NTDDI_WIN7) typedef union _KWAIT_STATUS_REGISTER { UCHAR Flags; struct { UCHAR State:2; UCHAR Affinity:1; UCHAR Priority:1; UCHAR Apc:1; UCHAR UserApc:1; UCHAR Alert:1; UCHAR Unused:1; }; } KWAIT_STATUS_REGISTER, *PKWAIT_STATUS_REGISTER; typedef struct _COUNTER_READING { enum _HARDWARE_COUNTER_TYPE Type; ULONG Index; ULONG64 Start; ULONG64 Total; }COUNTER_READING, *PCOUNTER_READING; typedef struct _KTHREAD_COUNTERS { ULONG64 WaitReasonBitMap; struct _THREAD_PERFORMANCE_DATA* UserData; ULONG Flags; ULONG ContextSwitches; ULONG64 CycleTimeBias; ULONG64 HardwareCounters; COUNTER_READING HwCounter[16]; }KTHREAD_COUNTERS, *PKTHREAD_COUNTERS; #endif // // Kernel Thread (KTHREAD) // typedef struct _KTHREAD { DISPATCHER_HEADER Header; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ ULONGLONG CycleTime; #ifndef _WIN64 // [ ULONG HighCycleTime; #endif // ] ULONGLONG QuantumTarget; #else // ][ LIST_ENTRY MutantListHead; #endif // ] PVOID InitialStack; ULONG_PTR StackLimit; // FIXME: PVOID PVOID KernelStack; KSPIN_LOCK ThreadLock; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ KWAIT_STATUS_REGISTER WaitRegister; BOOLEAN Running; BOOLEAN Alerted[2]; union { struct { ULONG KernelStackResident:1; ULONG ReadyTransition:1; ULONG ProcessReadyQueue:1; ULONG WaitNext:1; ULONG SystemAffinityActive:1; ULONG Alertable:1; ULONG GdiFlushActive:1; ULONG UserStackWalkActive:1; ULONG ApcInterruptRequest:1; ULONG ForceDeferSchedule:1; ULONG QuantumEndMigrate:1; ULONG UmsDirectedSwitchEnable:1; ULONG TimerActive:1; ULONG Reserved:19; }; LONG MiscFlags; }; #endif // ] union { KAPC_STATE ApcState; struct { UCHAR ApcStateFill[FIELD_OFFSET(KAPC_STATE, UserApcPending) + 1]; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ SCHAR Priority; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ /* On x86, the following members "fall out" of the union */ volatile ULONG NextProcessor; volatile ULONG DeferredProcessor; #else // ][ /* On x86, the following members "fall out" of the union */ volatile USHORT NextProcessor; volatile USHORT DeferredProcessor; #endif // ] #else // ][ UCHAR ApcQueueable; /* On x86, the following members "fall out" of the union */ volatile UCHAR NextProcessor; volatile UCHAR DeferredProcessor; UCHAR AdjustReason; SCHAR AdjustIncrement; #endif // ] }; }; KSPIN_LOCK ApcQueueLock; #ifndef _M_AMD64 // [ ULONG ContextSwitches; volatile UCHAR State; UCHAR NpxState; KIRQL WaitIrql; KPROCESSOR_MODE WaitMode; #endif // ] LONG_PTR WaitStatus; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ PKWAIT_BLOCK WaitBlockList; #else // ][ union { PKWAIT_BLOCK WaitBlockList; PKGATE GateObject; }; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ union { struct { ULONG KernelStackResident:1; ULONG ReadyTransition:1; ULONG ProcessReadyQueue:1; ULONG WaitNext:1; ULONG SystemAffinityActive:1; ULONG Alertable:1; ULONG GdiFlushActive:1; ULONG Reserved:25; }; LONG MiscFlags; }; #else // ][ BOOLEAN Alertable; BOOLEAN WaitNext; #endif // ] UCHAR WaitReason; #if (NTDDI_VERSION < NTDDI_LONGHORN) SCHAR Priority; BOOLEAN EnableStackSwap; #endif // ] volatile UCHAR SwapBusy; BOOLEAN Alerted[MaximumMode]; #endif // ] union { LIST_ENTRY WaitListEntry; SINGLE_LIST_ENTRY SwapListEntry; }; PKQUEUE Queue; #ifndef _M_AMD64 // [ ULONG WaitTime; union { struct { SHORT KernelApcDisable; SHORT SpecialApcDisable; }; ULONG CombinedApcDisable; }; #endif // ] struct _TEB *Teb; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ KTIMER Timer; #else // ][ union { KTIMER Timer; struct { UCHAR TimerFill[FIELD_OFFSET(KTIMER, Period) + sizeof(LONG)]; #if !defined(_WIN64) // [ }; }; #endif // ] #endif // ] union { struct { ULONG AutoAlignment:1; ULONG DisableBoost:1; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ ULONG EtwStackTraceApc1Inserted:1; ULONG EtwStackTraceApc2Inserted:1; ULONG CycleChargePending:1; ULONG CalloutActive:1; ULONG ApcQueueable:1; ULONG EnableStackSwap:1; ULONG GuiThread:1; ULONG ReservedFlags:23; #else // ][ LONG ReservedFlags:30; #endif // ] }; LONG ThreadFlags; }; #if defined(_WIN64) && (NTDDI_VERSION < NTDDI_WIN7) // [ }; }; #endif // ] #if (NTDDI_VERSION >= NTDDI_WIN7) // [ #if defined(_WIN64) // [ ULONG Spare0; #else // ][ PVOID ServiceTable; #endif // ] #endif // ] union { DECLSPEC_ALIGN(8) KWAIT_BLOCK WaitBlock[THREAD_WAIT_OBJECTS + 1]; #if (NTDDI_VERSION < NTDDI_WIN7) // [ struct { UCHAR WaitBlockFill0[FIELD_OFFSET(KWAIT_BLOCK, SpareByte)]; // 32bit = 23, 64bit = 43 #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ UCHAR IdealProcessor; #else // ][ BOOLEAN SystemAffinityActive; #endif // ] }; struct { UCHAR WaitBlockFill1[1 * sizeof(KWAIT_BLOCK) + FIELD_OFFSET(KWAIT_BLOCK, SpareByte)]; // 47 / 91 CCHAR PreviousMode; }; struct { UCHAR WaitBlockFill2[2 * sizeof(KWAIT_BLOCK) + FIELD_OFFSET(KWAIT_BLOCK, SpareByte)]; // 71 / 139 UCHAR ResourceIndex; }; struct { UCHAR WaitBlockFill3[3 * sizeof(KWAIT_BLOCK) + FIELD_OFFSET(KWAIT_BLOCK, SpareByte)]; // 95 / 187 UCHAR LargeStack; }; #endif // ] #ifdef _M_AMD64 // [ struct { UCHAR WaitBlockFill4[FIELD_OFFSET(KWAIT_BLOCK, SpareLong)]; ULONG ContextSwitches; }; struct { UCHAR WaitBlockFill5[1 * sizeof(KWAIT_BLOCK) + FIELD_OFFSET(KWAIT_BLOCK, SpareLong)]; UCHAR State; UCHAR NpxState; UCHAR WaitIrql; CHAR WaitMode; }; struct { UCHAR WaitBlockFill6[2 * sizeof(KWAIT_BLOCK) + FIELD_OFFSET(KWAIT_BLOCK, SpareLong)]; ULONG WaitTime; }; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ struct { UCHAR WaitBlockFill7[168]; PVOID TebMappedLowVa; struct _UMS_CONTROL_BLOCK* Ucb; }; #endif // ] struct { #if (NTDDI_VERSION >= NTDDI_WIN7) // [ UCHAR WaitBlockFill8[188]; #else // ][ UCHAR WaitBlockFill7[3 * sizeof(KWAIT_BLOCK) + FIELD_OFFSET(KWAIT_BLOCK, SpareLong)]; #endif // ] union { struct { SHORT KernelApcDisable; SHORT SpecialApcDisable; }; ULONG CombinedApcDisable; }; }; #endif // ] }; LIST_ENTRY QueueListEntry; PKTRAP_FRAME TrapFrame; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ PVOID FirstArgument; union // 2 elements, 0x8 bytes (sizeof) { PVOID CallbackStack; ULONG_PTR CallbackDepth; }; #else // ][ PVOID CallbackStack; #endif // ] #if (NTDDI_VERSION < NTDDI_LONGHORN) || ((NTDDI_VERSION < NTDDI_WIN7) && !defined(_WIN64)) // [ PVOID ServiceTable; #endif // ] #if (NTDDI_VERSION < NTDDI_LONGHORN) && defined(_WIN64) // [ ULONG KernelLimit; #endif // ] UCHAR ApcStateIndex; #if (NTDDI_VERSION < NTDDI_LONGHORN) // [ UCHAR IdealProcessor; BOOLEAN Preempted; BOOLEAN ProcessReadyQueue; #ifdef _WIN64 // [ PVOID Win32kTable; ULONG Win32kLimit; #endif // ] BOOLEAN KernelStackResident; #endif // ] SCHAR BasePriority; SCHAR PriorityDecrement; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ BOOLEAN Preempted; UCHAR AdjustReason; CHAR AdjustIncrement; #if (NTDDI_VERSION >= NTDDI_WIN7) UCHAR PreviousMode; #else UCHAR Spare01; #endif #endif // ] CHAR Saturation; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ ULONG SystemCallNumber; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ ULONG FreezeCount; #else // ][ ULONG Spare02; #endif // ] #endif // ] #if (NTDDI_VERSION >= NTDDI_WIN7) // [ GROUP_AFFINITY UserAffinity; struct _KPROCESS *Process; GROUP_AFFINITY Affinity; ULONG IdealProcessor; ULONG UserIdealProcessor; #else // ][ KAFFINITY UserAffinity; struct _KPROCESS *Process; KAFFINITY Affinity; #endif // ] PKAPC_STATE ApcStatePointer[2]; union { KAPC_STATE SavedApcState; struct { UCHAR SavedApcStateFill[FIELD_OFFSET(KAPC_STATE, UserApcPending) + 1]; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ UCHAR WaitReason; #else // ][ CCHAR FreezeCount; #endif // ] #ifndef _WIN64 // [ }; }; #endif // ] CCHAR SuspendCount; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ CCHAR Spare1; #else // ][ UCHAR UserIdealProcessor; #endif // ] #if (NTDDI_VERSION >= NTDDI_WIN7) // [ #elif (NTDDI_VERSION >= NTDDI_LONGHORN) // ][ UCHAR Spare03; #else // ][ UCHAR CalloutActive; #endif // ] #ifdef _WIN64 // [ UCHAR CodePatchInProgress; }; }; #endif // ] #if defined(_M_IX86) // [ #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ UCHAR OtherPlatformFill; #else // ][ UCHAR Iopl; #endif // ] #endif // ] PVOID Win32Thread; PVOID StackBase; union { KAPC SuspendApc; struct { UCHAR SuspendApcFill0[1]; #if (NTDDI_VERSION >= NTDDI_WIN7) // [ UCHAR ResourceIndex; #elif (NTDDI_VERSION >= NTDDI_LONGHORN) // ][ CHAR Spare04; #else // ][ SCHAR Quantum; #endif // ] }; struct { UCHAR SuspendApcFill1[3]; UCHAR QuantumReset; }; struct { UCHAR SuspendApcFill2[4]; ULONG KernelTime; }; struct { UCHAR SuspendApcFill3[FIELD_OFFSET(KAPC, SystemArgument1)]; #if (NTDDI_VERSION >= NTDDI_LONGHORN) PKPRCB WaitPrcb; #else PVOID TlsArray; #endif }; struct { UCHAR SuspendApcFill4[FIELD_OFFSET(KAPC, SystemArgument2)]; // 40 / 72 PVOID LegoData; }; struct { UCHAR SuspendApcFill5[FIELD_OFFSET(KAPC, Inserted) + 1]; // 47 / 83 #if (NTDDI_VERSION >= NTDDI_WIN7) // [ UCHAR LargeStack; #else // ][ UCHAR PowerState; #endif // ] #ifdef _WIN64 // [ ULONG UserTime; #endif // ] }; }; #ifndef _WIN64 // [ ULONG UserTime; #endif // ] union { KSEMAPHORE SuspendSemaphore; struct { UCHAR SuspendSemaphorefill[FIELD_OFFSET(KSEMAPHORE, Limit) + 4]; // 20 / 28 #ifdef _WIN64 // [ ULONG SListFaultCount; #endif // ] }; }; #ifndef _WIN64 // [ ULONG SListFaultCount; #endif // ] LIST_ENTRY ThreadListEntry; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ LIST_ENTRY MutantListHead; #endif // ] PVOID SListFaultAddress; #ifdef _M_AMD64 // [ LONG64 ReadOperationCount; LONG64 WriteOperationCount; LONG64 OtherOperationCount; LONG64 ReadTransferCount; LONG64 WriteTransferCount; LONG64 OtherTransferCount; #endif // ] #if (NTDDI_VERSION >= NTDDI_WIN7) // [ PKTHREAD_COUNTERS ThreadCounters; PXSTATE_SAVE XStateSave; #elif (NTDDI_VERSION >= NTDDI_LONGHORN) // ][ PVOID MdlForLockedTeb; #endif // ] } KTHREAD; #define ASSERT_THREAD(object) \ ASSERT((((object)->Header.Type & KOBJECT_TYPE_MASK) == ThreadObject)) // // Kernel Process (KPROCESS) // typedef struct _KPROCESS { DISPATCHER_HEADER Header; LIST_ENTRY ProfileListHead; #if (NTDDI_VERSION >= NTDDI_LONGHORN) ULONG_PTR DirectoryTableBase; ULONG Unused0; #else ULONG_PTR DirectoryTableBase[2]; #endif #if defined(_M_IX86) KGDTENTRY LdtDescriptor; KIDTENTRY Int21Descriptor; #endif USHORT IopmOffset; #if defined(_M_IX86) UCHAR Iopl; UCHAR Unused; #endif volatile ULONG ActiveProcessors; ULONG KernelTime; ULONG UserTime; LIST_ENTRY ReadyListHead; SINGLE_LIST_ENTRY SwapListEntry; PVOID VdmTrapcHandler; LIST_ENTRY ThreadListHead; KSPIN_LOCK ProcessLock; KAFFINITY Affinity; union { struct { LONG AutoAlignment:1; LONG DisableBoost:1; LONG DisableQuantum:1; LONG ReservedFlags:29; }; LONG ProcessFlags; }; SCHAR BasePriority; SCHAR QuantumReset; UCHAR State; UCHAR ThreadSeed; UCHAR PowerState; UCHAR IdealNode; UCHAR Visited; union { KEXECUTE_OPTIONS Flags; UCHAR ExecuteOptions; }; ULONG StackCount; LIST_ENTRY ProcessListEntry; #if (NTDDI_VERSION >= NTDDI_LONGHORN) // [ ULONGLONG CycleTime; #endif // ] } KPROCESS; #define ASSERT_PROCESS(object) \ ASSERT((((object)->Header.Type & KOBJECT_TYPE_MASK) == ProcessObject)) // // System Service Table Descriptor // typedef struct _KSERVICE_TABLE_DESCRIPTOR { PULONG_PTR Base; PULONG Count; ULONG Limit; #if defined(_IA64_) LONG TableBaseGpOffset; #endif PUCHAR Number; } KSERVICE_TABLE_DESCRIPTOR, *PKSERVICE_TABLE_DESCRIPTOR; // // Exported Loader Parameter Block // extern struct _LOADER_PARAMETER_BLOCK NTSYSAPI *KeLoaderBlock; // // Exported Hardware Data // extern KAFFINITY NTSYSAPI KeActiveProcessors; #if (NTDDI_VERSION >= NTDDI_LONGHORN) extern volatile CCHAR NTSYSAPI KeNumberProcessors; #else #if (NTDDI_VERSION >= NTDDI_WINXP) extern CCHAR NTSYSAPI KeNumberProcessors; #else //extern PCCHAR KeNumberProcessors; extern NTSYSAPI CCHAR KeNumberProcessors; //FIXME: Note to Alex: I won't fix this atm, since I prefer to discuss this with you first. #endif #endif extern ULONG NTSYSAPI KiDmaIoCoherency; extern ULONG NTSYSAPI KeMaximumIncrement; extern ULONG NTSYSAPI KeMinimumIncrement; extern ULONG NTSYSAPI KeDcacheFlushCount; extern ULONG NTSYSAPI KeIcacheFlushCount; extern ULONG_PTR NTSYSAPI KiBugCheckData[]; extern BOOLEAN NTSYSAPI KiEnableTimerWatchdog; // // Exported System Service Descriptor Tables // extern KSERVICE_TABLE_DESCRIPTOR NTSYSAPI KeServiceDescriptorTable[SSDT_MAX_ENTRIES]; extern KSERVICE_TABLE_DESCRIPTOR NTSYSAPI KeServiceDescriptorTableShadow[SSDT_MAX_ENTRIES]; #endif // !NTOS_MODE_USER #endif // _KETYPES_H
{ "pile_set_name": "Github" }
/** * Copyright (C) 2008, Creative Technology Ltd. All Rights Reserved. * * This source file is released under GPL v2 license (no other versions). * See the COPYING file included in the main directory of this source * distribution for the license terms and conditions. * * @File ctpcm.h * * @Brief * This file contains the definition of the pcm device functions. * * @Author Liu Chun * @Date Mar 28 2008 * */ #ifndef CTPCM_H #define CTPCM_H #include "ctatc.h" int ct_alsa_pcm_create(struct ct_atc *atc, enum CTALSADEVS device, const char *device_name); #endif /* CTPCM_H */
{ "pile_set_name": "Github" }
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * 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. */ package com.liferay.ide.upgrade.problems.core.internal.liferay70; import com.liferay.ide.upgrade.problems.core.AutoFileMigrator; import com.liferay.ide.upgrade.problems.core.FileMigrator; import com.liferay.ide.upgrade.problems.core.internal.JSPTagMigrator; import org.osgi.service.component.annotations.Component; /** * @author Gregory Amerson */ @Component( property = { "file.extensions=jsp,jspf", "problem.title=Moved the Expando Custom Field Tags to liferay-expando Taglib", "problem.section=#moved-the-expando-custom-field-tags-to-liferay-expando-taglib", "problem.summary=Moved the Expando Custom Field Tags to liferay-expando Taglib", "problem.tickets=LPS-69400", "auto.correct=jsptag", "version=7.0" }, service = {AutoFileMigrator.class, FileMigrator.class} ) public class DeprecatedExpandoCustomFieldTags extends JSPTagMigrator { public DeprecatedExpandoCustomFieldTags() { super(new String[0], new String[0], new String[0], new String[0], _TAG_NAMES, _NEW_TAG_NAMES); } private static final String[] _NEW_TAG_NAMES = { "liferay-expando:custom-attribute", "liferay-expando:custom-attribute-list", "liferay-expando:custom-attributes-available" }; private static final String[] _TAG_NAMES = { "liferay-ui:custom-attribute", "liferay-ui:custom-attribute-list", "liferay-ui:custom-attributes-available" }; }
{ "pile_set_name": "Github" }
// Copyright 2017 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 bpf // A Setter is a type which can attach a compiled BPF filter to itself. type Setter interface { SetBPF(filter []RawInstruction) error }
{ "pile_set_name": "Github" }
# Maximum Information This test case verifies support of a BCFzip file that contains all information available in the schema. ## Testing process 1. Import _MaximumInformation.bcfzip_. 2. Verify the bcfzip was imported correctly: > 1. There are two topics within the zip file: > > Maximum Content - 63E78882-7C6A-4BF7-8982-FC478AFB9C97 > > Referenced topic - 5019D939-62A4-45D9-B205-FAB602C98FE8 > 2. Verify that all information can be processed. 3. Export the topic you imported to _exported.bcfzip_. 4. Verify that no information was lost during the export
{ "pile_set_name": "Github" }
/* * Copyright (c) 2019-2020 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */ package org.geysermc.connector.entity.living.animal; import com.github.steveice10.mc.protocol.data.game.entity.metadata.EntityMetadata; import com.nukkitx.math.vector.Vector3f; import com.nukkitx.protocol.bedrock.data.entity.EntityData; import org.geysermc.connector.entity.living.AbstractFishEntity; import org.geysermc.connector.entity.type.EntityType; import org.geysermc.connector.network.session.GeyserSession; public class PufferFishEntity extends AbstractFishEntity { public PufferFishEntity(long entityId, long geyserId, EntityType entityType, Vector3f position, Vector3f motion, Vector3f rotation) { super(entityId, geyserId, entityType, position, motion, rotation); } @Override public void updateBedrockMetadata(EntityMetadata entityMetadata, GeyserSession session) { if (entityMetadata.getId() == 16) { // Transfers correctly but doesn't apply on the client int puffsize = (int) entityMetadata.getValue(); metadata.put(EntityData.PUFFERFISH_SIZE, puffsize); metadata.put(EntityData.VARIANT, puffsize); } super.updateBedrockMetadata(entityMetadata, session); } }
{ "pile_set_name": "Github" }
Card: OpenForum Name: #CARD_OPENFORUM Description: #CARD_OPENFORUM_DESC Icon: CardIcons::9 Color: #10f1af Class: Effect Rarity: Epic Base Purchase Cost: 2 Base Play Cost: 6 CreateEffect(OpenForum) AI: BuyWeight(0.5) AI: PlayWhenInfluenceStronk(0.5) Effect: OpenForum Name: #EFFECT_OPENFORUM Color: #ff00dd Icon: CardIcons::9 Upkeep: 0.25 ModInfluenceStackSize(+1) ModAttribute(InfluencePlacementMod, Add, -1)
{ "pile_set_name": "Github" }
#!/usr/bin/perl use strict; use warnings; use LWP::UserAgent (); use Getopt::Long qw(GetOptions); use Encode; use Encode::Locale; GetOptions(\my %opt, 'parse-head', 'max-length=n', 'keep-client-headers', 'method=s', 'agent=s', 'request',) || usage(); my $url = shift || usage(); @ARGV && usage(); sub usage { (my $progname = $0) =~ s,.*/,,; die <<"EOT"; Usage: $progname [options] <url> Recognized options are: --agent <str> --keep-client-headers --max-length <n> --method <str> --parse-head --request EOT } my $ua = LWP::UserAgent->new( parse_head => $opt{'parse-head'} || 0, keep_alive => 1, env_proxy => 1, agent => $opt{agent} || "lwp-dump/$LWP::UserAgent::VERSION ", ); my $req = HTTP::Request->new($opt{method} || 'GET' => decode(locale => $url)); my $res = $ua->simple_request($req); $res->remove_header(grep /^Client-/, $res->header_field_names) unless $opt{'keep-client-headers'} or ($res->header("Client-Warning") || "") eq "Internal response"; if ($opt{request}) { $res->request->dump; print "\n"; } $res->dump(maxlength => $opt{'max-length'}); __END__ =head1 NAME lwp-dump - See what headers and content is returned for a URL =head1 SYNOPSIS B<lwp-dump> [ I<options> ] I<URL> =head1 DESCRIPTION The B<lwp-dump> program will get the resource identified by the URL and then dump the response object to STDOUT. This will display the headers returned and the initial part of the content, escaped so that it's safe to display even binary content. The escapes syntax used is the same as for Perl's double quoted strings. If there is no content the string "(no content)" is shown in its place. The following options are recognized: =over =item B<--agent> I<string> Override the user agent string passed to the server. =item B<--keep-client-headers> LWP internally generate various C<Client-*> headers that are stripped by B<lwp-dump> in order to show the headers exactly as the server provided them. This option will suppress this. =item B<--max-length> I<n> How much of the content to show. The default is 512. Set this to 0 for unlimited. If the content is longer then the string is chopped at the limit and the string "...\n(### more bytes not shown)" appended. =item B<--method> I<string> Use the given method for the request instead of the default "GET". =item B<--parse-head> By default B<lwp-dump> will not try to initialize headers by looking at the head section of HTML documents. This option enables this. This corresponds to L<LWP::UserAgent/"parse_head">. =item B<--request> Also dump the request sent. =back =head1 SEE ALSO L<lwp-request>, L<LWP>, L<HTTP::Message/"dump">
{ "pile_set_name": "Github" }
// Package stats keeps track of all the different statistics collected by the report /* * Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. */ package stats import ( "time" ) type PrimitiveStat struct { AISLoaderStat Fatal bool `json:"fatal"` OpType string `json:"op_type"` ID string `json:"id"` // Soakprim assumes responsibility for filling RecipeName string `json:"recipe_name"` // Report package assumes responsibility for filling RecipeNum int `json:"recipe_num"` // Report package assumes responsibility for filling } // AISLoaderStat is a response from AISLoader, keep json consistent with the `jsonStats` struct in AISLoader type AISLoaderStat struct { LatencyMin time.Duration `json:"min_latency"` Latency time.Duration `json:"latency"` // Average LatencyMax time.Duration `json:"max_latency"` Throughput int64 `json:"throughput"` // bytes TotalSize int64 `json:"bytes"` RequestCount int64 `json:"count"` ErrorsCount int64 `json:"errors"` StartTime time.Time `json:"start_time"` Duration time.Duration `json:"duration"` } func (ps PrimitiveStat) getHeadingsText() map[string]string { return map[string]string{ "startTime": "Start (excel timestamp)", "endTime": "End (excel timestamp)", "recName": "Recipe Name", "recNum": "Recipe Num", "primID": "Primitive ID", "opType": "Operation Type", "minLatency": "Min Latency (ms)", "avgLatency": "Avg Latency (ms)", "maxLatency": "Max Latency (ms)", "throughput": "Throughput (B/s)", "totSize": "Total Size (B)", "reqCount": "Request Count", "errCount": "Error Count", "fatal": "Fatal", } } func (ps PrimitiveStat) getHeadingsOrder() []string { return []string{ "startTime", "endTime", "recName", "recNum", "primID", "opType", "minLatency", "avgLatency", "maxLatency", "throughput", "totSize", "reqCount", "errCount", "fatal", } } func (ps PrimitiveStat) getContents() map[string]interface{} { if ps.Fatal { return map[string]interface{}{ "startTime": getTimestamp(ps.StartTime), "recName": ps.RecipeName, "recNum": ps.RecipeNum, "primID": ps.ID, "fatal": true, } } return map[string]interface{}{ "startTime": getTimestamp(ps.StartTime), "endTime": getTimestamp(ps.StartTime.Add(ps.Duration)), "recName": ps.RecipeName, "recNum": ps.RecipeNum, "primID": ps.ID, "opType": ps.OpType, "minLatency": getMilliseconds(ps.LatencyMin), "avgLatency": getMilliseconds(ps.Latency), "maxLatency": getMilliseconds(ps.LatencyMax), "throughput": ps.Throughput, "totSize": ps.TotalSize, "reqCount": ps.RequestCount, "errCount": ps.ErrorsCount, "fatal": false, } }
{ "pile_set_name": "Github" }
package com.sgrain.boot.common.exception; import com.sgrain.boot.common.enums.AppHttpStatus; /** * @Description: 业务异常 * @Version: 1.0 */ public class BusinessException extends RuntimeException{ /** * 状态码 */ private int status; /** * 异常信息 */ private String errorMessage; public BusinessException(AppHttpStatus httpStatus){ this.status = httpStatus.getStatus(); this.errorMessage = httpStatus.getMessage(); } public BusinessException(int status, String errorMessage){ this.status = status; this.errorMessage = errorMessage; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
{ "pile_set_name": "Github" }
package com.roli.juce; import android.app.DialogFragment; import android.content.Intent; import android.os.Bundle; public class FragmentOverlay extends DialogFragment { @Override public void onCreate (Bundle state) { super.onCreate (state); cppThis = getArguments ().getLong ("cppThis"); if (cppThis != 0) onCreateNative (cppThis, state); } @Override public void onStart () { super.onStart (); if (cppThis != 0) onStartNative (cppThis); } public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults) { if (cppThis != 0) onRequestPermissionsResultNative (cppThis, requestCode, permissions, grantResults); } @Override public void onActivityResult (int requestCode, int resultCode, Intent data) { if (cppThis != 0) onActivityResultNative (cppThis, requestCode, resultCode, data); } public void close () { cppThis = 0; dismiss (); } //============================================================================== private long cppThis = 0; private native void onActivityResultNative (long myself, int requestCode, int resultCode, Intent data); private native void onCreateNative (long myself, Bundle state); private native void onStartNative (long myself); private native void onRequestPermissionsResultNative (long myself, int requestCode, String[] permissions, int[] grantResults); }
{ "pile_set_name": "Github" }
; RUN: opt < %s -sccp -S | not grep select @A = constant i32 10 define i712 @test1() { %P = getelementptr i32, i32* @A, i32 0 %B = ptrtoint i32* %P to i64 %BB = and i64 %B, undef %C = icmp sge i64 %BB, 0 %X = select i1 %C, i712 0, i712 1 ret i712 %X } define i712 @test2(i1 %C) { %X = select i1 %C, i712 0, i712 undef ret i712 %X }
{ "pile_set_name": "Github" }
<?php /* * Project: template_lite, a smarter template engine * File: class.template.php * Author: Paul Lockaby <paul@paullockaby.com>, Mark Dickenson <akapanamajack@sourceforge.net> * Copyright: 2003,2004,2005 by Paul Lockaby, 2005,2006 Mark Dickenson * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * The latest version of template_lite can be obtained from: * http://templatelite.sourceforge.net * */ if (!defined('TEMPLATE_LITE_DIR')) { define('TEMPLATE_LITE_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR); } class Template_Lite { // public configuration variables var $left_delimiter = "{"; // the left delimiter for template tags var $right_delimiter = "}"; // the right delimiter for template tags var $cache = false; // whether or not to allow caching of files var $force_compile = false; // force a compile regardless of saved state var $template_dir = "templates"; // where the templates are to be found var $plugins_dir = array("plugins"); // where the plugins are to be found var $compile_dir = "compiled"; // the directory to store the compiled files in var $config_dir = "templates"; // where the config files are var $cache_dir = "cached"; // where cache files are stored var $config_overwrite = false; var $config_booleanize = true; var $config_fix_new_lines = true; var $config_read_hidden = true; var $cache_lifetime = 0; // how long the file in cache should be considered "fresh" var $encode_file_name = true; // Set this to false if you do not want the name of the compiled/cached file to be md5 encoded. var $php_extract_vars = false; // Set this to true if you want the $this->_tpl variables to be extracted for use by PHP code inside the template. var $reserved_template_varname = "templatelite"; var $default_modifiers = array(); var $debugging = false; var $compiler_file = 'class.compiler.php'; var $compiler_class = 'Template_Lite_Compiler'; var $config_class = 'config'; // gzip output configuration var $send_now = 1; var $force_compression = 0; var $compression_level = 9; var $enable_gzip = 1; // private internal variables var $_vars = array(); // stores all internal assigned variables var $_confs = array(); // stores all internal config variables var $_plugins = array( 'modifier' => array(), 'function' => array(), 'block' => array(), 'compiler' => array(), 'resource' => array(), 'prefilter' => array(), 'postfilter' => array(), 'outputfilter' => array()); var $_linenum = 0; // the current line number in the file we are processing var $_file = ""; // the current file we are processing var $_config_obj = null; var $_compile_obj = null; var $_cache_id = null; var $_cache_dir = ""; // stores where this specific file is going to be cached var $_cache_info = array('config' => array(), 'template' => array()); var $_sl_md5 = '39fc70570b8b60cbc1b85839bf242aff'; var $_version = 'V2.10 Template Lite 4 January 2007 (c) 2005-2007 Mark Dickenson. All rights reserved. Released LGPL.'; var $_version_date = "2007-01-04 10:34:21"; var $_config_module_loaded = false; var $_templatelite_debug_info = array(); var $_templatelite_debug_loop = false; var $_templatelite_debug_dir = ""; var $_inclusion_depth = 0; var $_null = null; var $_resource_type = 1; var $_resource_time; var $_sections = array(); var $_foreach = array(); function Template_Lite() { $this->_version_date = strtotime($this->_version_date); } function load_filter($type, $name) { switch ($type) { case 'output': include_once( $this->_get_plugin_dir($type . "filter." . $name . ".php") . $type . "filter." . $name . ".php"); $this->_plugins['outputfilter'][$name] = "template_" . $type . "filter_" . $name; break; case 'pre': case 'post': if (!isset($this->_plugins[$type . 'filter'][$name])) { $this->_plugins[$type . 'filter'][$name] = "template_" . $type . "filter_" . $name; } break; } } function assign($key, $value = null) { if (is_array($key)) { foreach($key as $var => $val) if ($var != "") { $this->_vars[$var] = $val; } } else { if ($key != "") { $this->_vars[$key] = $value; } } } function assign_by_ref($key, $value = null) { if ($key != '') { $this->_vars[$key] = &$value; } } function assign_config($key, $value = null) { if (is_array($key)) { foreach($key as $var => $val) { if ($var != "") { $this->_confs[$var] = $val; } } } else { if ($key != "") { $this->_confs[$key] = $value; } } } function append($key, $value=null, $merge=false) { if (is_array($key)) { foreach ($key as $_key => $_value) { if ($_key != '') { if(!@is_array($this->_vars[$_key])) { settype($this->_vars[$_key],'array'); } if($merge && is_array($_value)) { foreach($_value as $_mergekey => $_mergevalue) { $this->_vars[$_key][$_mergekey] = $_mergevalue; } } else { $this->_vars[$_key][] = $_value; } } } } else { if ($key != '' && isset($value)) { if(!@is_array($this->_vars[$key])) { settype($this->_vars[$key],'array'); } if($merge && is_array($value)) { foreach($value as $_mergekey => $_mergevalue) { $this->_vars[$key][$_mergekey] = $_mergevalue; } } else { $this->_vars[$key][] = $value; } } } } function append_by_ref($key, &$value, $merge=false) { if ($key != '' && isset($value)) { if(!@is_array($this->_vars[$key])) { settype($this->_vars[$key],'array'); } if ($merge && is_array($value)) { foreach($value as $_key => $_val) { $this->_vars[$key][$_key] = &$value[$_key]; } } else { $this->_vars[$key][] = &$value; } } } function clear_assign($key = null) { if ($key == null) { $this->_vars = array(); } else { if (is_array($key)) { foreach($key as $index => $value) { if (in_array($value, $this->_vars)) { unset($this->_vars[$index]); } } } else { if (in_array($key, $this->_vars)) { unset($this->_vars[$index]); } } } } function clear_all_assign() { $this->_vars = array(); } function clear_config($key = null) { if ($key == null) { $this->_conf = array(); } else { if (is_array($key)) { foreach($key as $index => $value) { if (in_array($value, $this->_conf)) { unset($this->_conf[$index]); } } } else { if (in_array($key, $this->_conf)) { unset($this->_conf[$key]); } } } } function &get_template_vars($key = null) { if ($key == null) { return $this->_vars; } else { if (isset($this->_vars[$key])) { return $this->_vars[$key]; } else { return $this->_null; } } } function &get_config_vars($key = null) { if ($key == null) { return $this->_confs; } else { if (isset($this->_confs[$key])) { return $this->_confs[$key]; } else { return $this->_null; } } } function clear_compiled_tpl($file = null) { $this->_destroy_dir($file, null, $this->_get_dir($this->compile_dir)); } function clear_cache($file = null, $cache_id = null, $compile_id = null, $exp_time = null) { if (!$this->cache) { return; } $this->_destroy_dir($file, $cache_id, $this->_get_dir($this->cache_dir)); } function clear_all_cache($exp_time = null) { $this->clear_cache(); } function is_cached($file, $cache_id = null) { if (!$this->force_compile && $this->cache && $this->_is_cached($file, $cache_id)) { return true; } else { return false; } } function register_modifier($modifier, $implementation) { $this->_plugins['modifier'][$modifier] = $implementation; } function unregister_modifier($modifier) { unset($this->_plugins['modifier'][$modifier]); } function register_function($function, $implementation) { $this->_plugins['function'][$function] = $implementation; } function unregister_function($function) { unset($this->_plugins['function'][$function]); } function register_block($function, $implementation) { $this->_plugins['block'][$function] = $implementation; } function unregister_block($function) { unset($this->_plugins['block'][$function]); } function register_compiler($function, $implementation) { $this->_plugins['compiler'][$function] = $implementation; } function unregister_compiler($function) { unset($this->_plugins['compiler'][$function]); } function register_prefilter($function) { $_name = (is_array($function)) ? $function[1] : $function; $this->_plugins['prefilter'][$_name] = $_name; } function unregister_prefilter($function) { unset($this->_plugins['prefilter'][$function]); } function register_postfilter($function) { $_name = (is_array($function)) ? $function[1] : $function; $this->_plugins['postfilter'][$_name] = $_name; } function unregister_postfilter($function) { unset($this->_plugins['postfilter'][$function]); } function register_outputfilter($function) { $_name = (is_array($function)) ? $function[1] : $function; $this->_plugins['outputfilter'][$_name] = $_name; } function unregister_outputfilter($function) { unset($this->_plugins['outputfilter'][$function]); } function register_resource($type, $functions) { if (count($functions) == 4) { $this->_plugins['resource'][$type] = $functions; } else { $this->trigger_error("malformed function-list for '$type' in register_resource"); } } function unregister_resource($type) { unset($this->_plugins['resource'][$type]); } function template_exists($file) { if (file_exists($this->_get_dir($this->template_dir).$file)) { $this->_resource_time = filemtime($this->_get_dir($this->template_dir).$file); $this->_resource_type = 1; return true; } else { if (file_exists($file)) { $this->_resource_time = filemtime($file); $this->_resource_type = "file"; return true; } return false; } } function _get_resource($file) { $_resource_name = explode(':', trim($file)); if (count($_resource_name) == 1 || $_resource_name[0] == "file") { if($_resource_name[0] == "file") { $file = substr($file, 5); } $exists = $this->template_exists($file); if (!$exists) { $this->trigger_error("file '$file' does not exist", E_USER_ERROR); } } else { $this->_resource_type = $_resource_name[0]; $file = substr($file, strlen($this->_resource_type) + 1); $exists = isset($this->_plugins['resource'][$this->_resource_type]) && call_user_func_array($this->_plugins['resource'][$this->_resource_type][1], array($file, &$resource_timestamp, &$this)); if (!$exists) { $this->trigger_error("file '$file' does not exist", E_USER_ERROR); } $this->_resource_time = $resource_timestamp; } return $file; } function display($file, $cache_id = null) { $this->fetch($file, $cache_id, true); } function fetch($file, $cache_id = null, $display = false) { $file = $this->_get_resource($file); if ($this->debugging) { $this->_templatelite_debug_info[] = array('type' => 'template', 'filename' => $file, 'depth' => 0, 'exec_time' => array_sum(explode(' ', microtime())) ); $included_tpls_idx = count($this->_templatelite_debug_info) - 1; } $this->_cache_id = $cache_id; $this->template_dir = $this->_get_dir($this->template_dir); $this->compile_dir = $this->_get_dir($this->compile_dir); if ($this->cache) { $this->_cache_dir = $this->_build_dir($this->cache_dir, $this->_cache_id); } $name = ($this->encode_file_name) ? md5((($this->_resource_type == 1) ? $this->template_dir.$file : $this->_resource_type . "_" . $file)).'.php' : str_replace(".", "_", str_replace("/", "_", $this->_resource_type . "_" . $file)).'.php'; $this->_error_level = $this->debugging ? error_reporting() : error_reporting(error_reporting() & ~E_NOTICE); // $this->_error_level = error_reporting(E_ALL); if (!$this->force_compile && $this->cache && $this->_is_cached($file, $cache_id)) { ob_start(); include($this->_cache_dir.$name); $output = ob_get_contents(); ob_end_clean(); $output = substr($output, strpos($output, "\n") + 1); } else { $output = $this->_fetch_compile($file, $cache_id); if ($this->cache) { $f = fopen($this->_cache_dir.$name, "w"); fwrite($f, serialize($this->_cache_info) . "\n$output"); fclose($f); } } if (strpos($output, $this->_sl_md5) !== false) { preg_match_all('!' . $this->_sl_md5 . '{_run_insert (.*)}' . $this->_sl_md5 . '!U',$output,$_match); foreach($_match[1] as $value) { $arguments = unserialize($value); $output = str_replace($this->_sl_md5 . '{_run_insert ' . $value . '}' . $this->_sl_md5, call_user_func_array('insert_' . $arguments['name'], array((array)$arguments, $this)), $output); } } foreach ($this->_plugins['outputfilter'] as $function) { $output = $function($output, $this); } error_reporting($this->_error_level); if ($this->debugging) { $this->_templatelite_debug_info[$included_tpls_idx]['exec_time'] = array_sum(explode(' ', microtime())) - $this->_templatelite_debug_info[$included_tpls_idx]['exec_time']; } if ($display) { echo $output; if($this->debugging && !$this->_templatelite_debug_loop) { $this->debugging = false; if(!function_exists("template_generate_debug_output")) { require_once(TEMPLATE_LITE_DIR . "internal/template.generate_debug_output.php"); } $debug_output = template_generate_debug_output($this); $this->debugging = true; echo $debug_output; } } else { return $output; } } function config_load($file, $section_name = null, $var_name = null) { require_once(TEMPLATE_LITE_DIR . "internal/template.config_loader.php"); } function _is_cached($file, $cache_id) { $this->_cache_dir = $this->_get_dir($this->cache_dir, $cache_id); $this->config_dir = $this->_get_dir($this->config_dir); $this->template_dir = $this->_get_dir($this->template_dir); $file = $this->_get_resource($file); $name = ($this->encode_file_name) ? md5((($this->_resource_type == 1) ? $this->template_dir.$file : $this->_resource_type . "_" . $file)).'.php' : str_replace(".", "_", str_replace("/", "_", $this->_resource_type . "_" . $file)).'.php'; if (file_exists($this->_cache_dir.$name) && (((time() - filemtime($this->_cache_dir.$name)) < $this->cache_lifetime) || $this->cache_lifetime == -1) && (filemtime($this->_cache_dir.$name) > $this->_resource_time)) { $fh = fopen($this->_cache_dir.$name, "r"); if (!feof($fh) && ($line = fgets($fh, filesize($this->_cache_dir.$name)))) { $includes = unserialize($line); if (isset($includes['template'])) { foreach($includes['template'] as $value) { if (!(file_exists($this->template_dir.$value) && (filemtime($this->_cache_dir.$name) > filemtime($this->template_dir.$value)))) { return false; } } } if (isset($includes['config'])) { foreach($includes['config'] as $value) { if (!(file_exists($this->config_dir.$value) && (filemtime($this->_cache_dir.$name) > filemtime($this->config_dir.$value)))) { return false; } } } } fclose($fh); } else { return false; } return true; } function _fetch_compile_include($_templatelite_include_file, $_templatelite_include_vars) { if(!function_exists("template_fetch_compile_include")) { require_once(TEMPLATE_LITE_DIR . "internal/template.fetch_compile_include.php"); } return template_fetch_compile_include($_templatelite_include_file, $_templatelite_include_vars, $this); } function _fetch_compile($file) { $this->template_dir = $this->_get_dir($this->template_dir); $name = ($this->encode_file_name) ? md5((($this->_resource_type == 1) ? $this->template_dir.$file : $this->_resource_type . "_" . $file)).'.php' : str_replace(".", "_", str_replace("/", "_", $this->_resource_type . "_" . $file)).'.php'; if ($this->cache) { array_push($this->_cache_info['template'], $file); } if (!$this->force_compile && file_exists($this->compile_dir.'c_'.$name) && (filemtime($this->compile_dir.'c_'.$name) > $this->_resource_time) && (filemtime($this->compile_dir.'c_'.$name) > $this->_version_date)) { ob_start(); include($this->compile_dir.'c_'.$name); $output = ob_get_contents(); ob_end_clean(); error_reporting($this->_error_level); return $output; } $file_contents = ""; if($this->_resource_type == 1) { $f = fopen($this->template_dir . $file, "r"); $size = filesize($this->template_dir . $file); if ($size > 0) { $file_contents = fread($f, $size); } } else if($this->_resource_type == "file") { $f = fopen($file, "r"); $size = filesize($file); if ($size > 0) { $file_contents = fread($f, $size); } } else { call_user_func_array($this->_plugins['resource'][$this->_resource_type][0], array($file, &$file_contents, &$this)); } $this->_file = $file; fclose($f); if (!is_object($this->_compile_obj)) { if (file_exists(TEMPLATE_LITE_DIR . $this->compiler_file)) { require_once(TEMPLATE_LITE_DIR . $this->compiler_file); } else { require_once($this->compiler_file); } $this->_compile_obj = new $this->compiler_class; } $this->_compile_obj->left_delimiter = $this->left_delimiter; $this->_compile_obj->right_delimiter = $this->right_delimiter; $this->_compile_obj->plugins_dir = &$this->plugins_dir; $this->_compile_obj->template_dir = &$this->template_dir; $this->_compile_obj->_vars = &$this->_vars; $this->_compile_obj->_confs = &$this->_confs; $this->_compile_obj->_plugins = &$this->_plugins; $this->_compile_obj->_linenum = &$this->_linenum; $this->_compile_obj->_file = &$this->_file; $this->_compile_obj->php_extract_vars = &$this->php_extract_vars; $this->_compile_obj->reserved_template_varname = &$this->reserved_template_varname; $this->_compile_obj->default_modifiers = $this->default_modifiers; $output = $this->_compile_obj->_compile_file($file_contents); $f = fopen($this->compile_dir.'c_'.$name, "w"); fwrite($f, $output); fclose($f); ob_start(); eval(' ?>' . $output . '<?php '); $output = ob_get_contents(); ob_end_clean(); return $output; } function _run_modifier() { $arguments = func_get_args(); list($variable, $modifier, $php_function, $_map_array) = array_splice($arguments, 0, 4); array_unshift($arguments, $variable); if ($_map_array && is_array($variable)) { foreach($variable as $key => $value) { if($php_function == "PHP") { $variable[$key] = call_user_func_array($modifier, $arguments); } else { $variable[$key] = call_user_func_array($this->_plugins["modifier"][$modifier], $arguments); } } } else { if($php_function == "PHP") { $variable = call_user_func_array($modifier, $arguments); } else { $variable = call_user_func_array($this->_plugins["modifier"][$modifier], $arguments); } } return $variable; } function _run_insert($arguments) { if ($this->cache) { return $this->_sl_md5 . '{_run_insert ' . serialize((array)$arguments) . '}' . $this->_sl_md5; } else { if (!function_exists('insert_' . $arguments['name'])) { $this->trigger_error("function 'insert_" . $arguments['name'] . "' does not exist in 'insert'", E_USER_ERROR); } if (isset($arguments['assign'])) { $this->assign($arguments['assign'], call_user_func_array('insert_' . $arguments['name'], array((array)$arguments, $this))); } else { return call_user_func_array('insert_' . $arguments['name'], array((array)$arguments, $this)); } } } function _get_dir($dir, $id = null) { if (empty($dir)) { $dir = '.'; } if (substr($dir, -1) != DIRECTORY_SEPARATOR) { $dir .= DIRECTORY_SEPARATOR; } if (!empty($id)) { $_args = explode('|', $id); if (count($_args) == 1 && empty($_args[0])) { return $dir; } foreach($_args as $value) { $dir .= $value.DIRECTORY_SEPARATOR; } } return $dir; } function _get_plugin_dir($plugin_name) { static $_path_array = null; $plugin_dir_path = ""; $_plugin_dir_list = is_array($this->plugins_dir) ? $this->plugins_dir : (array)$this->plugins_dir; foreach ($_plugin_dir_list as $_plugin_dir) { if (!preg_match("/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/", $_plugin_dir)) { // path is relative if (file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR . $_plugin_dir . DIRECTORY_SEPARATOR . $plugin_name)) { $plugin_dir_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . $_plugin_dir . DIRECTORY_SEPARATOR; break; } } else { // path is absolute if(!isset($_path_array)) { $_ini_include_path = ini_get('include_path'); if(strstr($_ini_include_path,';')) { // windows pathnames $_path_array = explode(';',$_ini_include_path); } else { $_path_array = explode(':',$_ini_include_path); } } if(!in_array($_plugin_dir,$_path_array)) { array_unshift($_path_array,$_plugin_dir); } foreach ($_path_array as $_include_path) { if (file_exists($_include_path . DIRECTORY_SEPARATOR . $plugin_name)) { $plugin_dir_path = $_include_path . DIRECTORY_SEPARATOR; break 2; } } } } return $plugin_dir_path; } // function _parse_resource_link($resource_link) // { // $stuffing = "file:/this/is/the/time_5-23.tpl"; // $stuffing_data = explode(":", $stuffing); // preg_match_all('/(?:([0-9a-z._-]+))/i', $stuffing, $stuff); // print_r($stuff); // echo "<br>Path: " . str_replace($stuff[0][count($stuff[0]) - 1], "", $stuffing); // echo "<br>Filename: " . $stuff[0][count($stuff[0]) - 1]; // } function _build_dir($dir, $id) { if(!function_exists("template_build_dir")) { require_once(TEMPLATE_LITE_DIR . "internal/template.build_dir.php"); } return template_build_dir($dir, $id, $this); } function _destroy_dir($file, $id, $dir) { if(!function_exists("template_destroy_dir")) { require_once(TEMPLATE_LITE_DIR . "internal/template.destroy_dir.php"); } return template_destroy_dir($file, $id, $dir, $this); } function trigger_error($error_msg, $error_type = E_USER_ERROR, $file = null, $line = null) { if(isset($file) && isset($line)) { $info = ' ('.basename($file).", line $line)"; } else { $info = null; } trigger_error('TPL: [in ' . $this->_file . ' line ' . $this->_linenum . "]: syntax error: $error_msg$info", $error_type); } } ?>
{ "pile_set_name": "Github" }