text
stringlengths
2
99k
meta
dict
/*============================================================================= Copyright (c) 2001-2008 Joel de Guzman Copyright (c) 2001-2008 Hartmut Kaiser http://spirit.sourceforge.net/ 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 BOOST_SPIRIT_INCLUDE_CLASSIC_CLOSURE #define BOOST_SPIRIT_INCLUDE_CLASSIC_CLOSURE #include <boost/spirit/home/classic/attribute/closure.hpp> #endif
{ "pile_set_name": "Github" }
.. _collaborators: ============= Collaborators ============= List of software projects pyiron collaborates with in alphabetical order: ASE === The Atomic Simulation Environment (ASE) is a set of tools and Python modules for setting up, manipulating, running, visualizing and analyzing atomistic simulations. The code is freely available under the GNU LGPL license. https://wiki.fysik.dtu.dk/ase/ LAMMPS ====== LAMMPS stands for Large-scale Atomic/Molecular Massively Parallel Simulator. LAMMPS is a classical molecular dynamics simulation code designed to run efficiently on parallel computers. It was developed at Sandia National Laboratories, a US Department of Energy facility, with funding from the DOE. It is an open-source code, distributed freely under the terms of the GNU Public License (GPL). http://lammps.sandia.gov NGLview ======= An IPython/Jupyter widget to interactively view molecular structures and trajectories. Utilizes the embeddable NGL Viewer for rendering. Support for showing data from the file-system, RCSB PDB, simpletraj and from objects of analysis libraries mdtraj, pytraj, mdanalysis, ParmEd, rdkit, ase, HTMD, biopython, cctbx, pyrosetta, schrodinger's Structure. https://github.com/arose/nglview OpenKIM ======= OpenKIM is a cyberinfrastructure for improving the reliability of molecular and multiscale simulations of materials. It includes a repository of interatomic potentials that are exhaustively tested, tools to help select among existing potentials and develop new ones, and standard integration methods for using potentials in major simulation codes. Visit the `OpenKIM Website <https://openkim.org/>`_. OVITO ===== OVITO is a scientific visualization and analysis software for atomistic and particle simulation data. It helps scientists gain better insights into materials phenomena and physical processes. The program is freely available for all major platforms under an open source license. It has served in a growing number of computational simulation studies as a powerful tool to analyze, understand and illustrate simulation results. https://www.ovito.org S/PHI/nX ======== S/PHI/nX is a C++ library for materials simulation, mostly electronic-structure theory. It also is a program (sphinx) to perform such simulations using density-functional theory, and k.p theory. In addition, the package offers dozens of specialized programs (add-ons) for smaller tasks related to setup, analysis, post-processing, and other types of simulations. https://sxrepo.mpie.de VASP ==== The Vienna Ab initio Simulation Package: atomic scale materials modelling from first principles. https://www.vasp.at
{ "pile_set_name": "Github" }
// Copyright 2013 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/profiler/tick-sample.h" #include <cinttypes> #include "include/v8-profiler.h" #include "src/execution/frames-inl.h" #include "src/execution/simulator.h" #include "src/execution/vm-state-inl.h" #include "src/heap/heap-inl.h" // For MemoryAllocator::code_range. #include "src/logging/counters.h" #include "src/sanitizer/asan.h" #include "src/sanitizer/msan.h" namespace v8 { namespace internal { namespace { bool IsSamePage(i::Address ptr1, i::Address ptr2) { const uint32_t kPageSize = 4096; i::Address mask = ~static_cast<i::Address>(kPageSize - 1); return (ptr1 & mask) == (ptr2 & mask); } // Check if the code at specified address could potentially be a // frame setup code. bool IsNoFrameRegion(i::Address address) { struct Pattern { int bytes_count; i::byte bytes[8]; int offsets[4]; }; static Pattern patterns[] = { #if V8_HOST_ARCH_IA32 // push %ebp // mov %esp,%ebp {3, {0x55, 0x89, 0xE5}, {0, 1, -1}}, // pop %ebp // ret N {2, {0x5D, 0xC2}, {0, 1, -1}}, // pop %ebp // ret {2, {0x5D, 0xC3}, {0, 1, -1}}, #elif V8_HOST_ARCH_X64 // pushq %rbp // movq %rsp,%rbp {4, {0x55, 0x48, 0x89, 0xE5}, {0, 1, -1}}, // popq %rbp // ret N {2, {0x5D, 0xC2}, {0, 1, -1}}, // popq %rbp // ret {2, {0x5D, 0xC3}, {0, 1, -1}}, #endif {0, {}, {}} }; i::byte* pc = reinterpret_cast<i::byte*>(address); for (Pattern* pattern = patterns; pattern->bytes_count; ++pattern) { for (int* offset_ptr = pattern->offsets; *offset_ptr != -1; ++offset_ptr) { int offset = *offset_ptr; if (!offset || IsSamePage(address, address - offset)) { MSAN_MEMORY_IS_INITIALIZED(pc - offset, pattern->bytes_count); if (!memcmp(pc - offset, pattern->bytes, pattern->bytes_count)) return true; } else { // It is not safe to examine bytes on another page as it might not be // allocated thus causing a SEGFAULT. // Check the pattern part that's on the same page and // pessimistically assume it could be the entire pattern match. MSAN_MEMORY_IS_INITIALIZED(pc, pattern->bytes_count - offset); if (!memcmp(pc, pattern->bytes + offset, pattern->bytes_count - offset)) return true; } } } return false; } #if defined(USE_SIMULATOR) class SimulatorHelper { public: // Returns true if register values were successfully retrieved // from the simulator, otherwise returns false. static bool FillRegisters(Isolate* isolate, v8::RegisterState* state); }; bool SimulatorHelper::FillRegisters(Isolate* isolate, v8::RegisterState* state) { Simulator* simulator = isolate->thread_local_top()->simulator_; // Check if there is active simulator. if (simulator == nullptr) return false; #if V8_TARGET_ARCH_ARM if (!simulator->has_bad_pc()) { state->pc = reinterpret_cast<void*>(simulator->get_pc()); } state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp)); state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::r11)); state->lr = reinterpret_cast<void*>(simulator->get_register(Simulator::lr)); #elif V8_TARGET_ARCH_ARM64 state->pc = reinterpret_cast<void*>(simulator->pc()); state->sp = reinterpret_cast<void*>(simulator->sp()); state->fp = reinterpret_cast<void*>(simulator->fp()); state->lr = reinterpret_cast<void*>(simulator->lr()); #elif V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64 if (!simulator->has_bad_pc()) { state->pc = reinterpret_cast<void*>(simulator->get_pc()); } state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp)); state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp)); #elif V8_TARGET_ARCH_PPC if (!simulator->has_bad_pc()) { state->pc = reinterpret_cast<void*>(simulator->get_pc()); } state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp)); state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp)); state->lr = reinterpret_cast<void*>(simulator->get_lr()); #elif V8_TARGET_ARCH_S390 if (!simulator->has_bad_pc()) { state->pc = reinterpret_cast<void*>(simulator->get_pc()); } state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp)); state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp)); state->lr = reinterpret_cast<void*>(simulator->get_register(Simulator::ra)); #endif if (state->sp == 0 || state->fp == 0) { // It possible that the simulator is interrupted while it is updating // the sp or fp register. ARM64 simulator does this in two steps: // first setting it to zero and then setting it to the new value. // Bailout if sp/fp doesn't contain the new value. // // FIXME: The above doesn't really solve the issue. // If a 64-bit target is executed on a 32-bit host even the final // write is non-atomic, so it might obtain a half of the result. // Moreover as long as the register set code uses memcpy (as of now), // it is not guaranteed to be atomic even when both host and target // are of same bitness. return false; } return true; } #endif // USE_SIMULATOR // Returns the native context for a JavaScript frame. If the frame wasn't a // JavaScript frame, it'll return kNullAddress. Address ScrapeNativeContextAddress(Heap* heap, Address context_address) { #if !defined(V8_TARGET_ARCH_IA32) && !defined(V8_TARGET_ARCH_X64) return kNullAddress; #else DCHECK_EQ(heap->gc_state(), Heap::NOT_IN_GC); // If the value is tagged, we're looking at a JavaScript frame. if (!HAS_STRONG_HEAP_OBJECT_TAG(context_address)) return kNullAddress; i::Object object(context_address); return i::Context::cast(object).map().native_context().ptr(); #endif } } // namespace DISABLE_ASAN void TickSample::Init(Isolate* v8_isolate, const RegisterState& reg_state, RecordCEntryFrame record_c_entry_frame, bool update_stats, bool use_simulator_reg_state, base::TimeDelta sampling_interval) { this->update_stats = update_stats; SampleInfo info; RegisterState regs = reg_state; if (!GetStackSample(v8_isolate, &regs, record_c_entry_frame, stack, kMaxFramesCount, &info, use_simulator_reg_state, contexts)) { // It is executing JS but failed to collect a stack trace. // Mark the sample as spoiled. pc = nullptr; return; } state = info.vm_state; pc = regs.pc; frames_count = static_cast<unsigned>(info.frames_count); has_external_callback = info.external_callback_entry != nullptr; top_context = info.top_context; if (has_external_callback) { external_callback_entry = info.external_callback_entry; } else if (frames_count) { // sp register may point at an arbitrary place in memory, make // sure sanitizers don't complain about it. ASAN_UNPOISON_MEMORY_REGION(regs.sp, sizeof(void*)); MSAN_MEMORY_IS_INITIALIZED(regs.sp, sizeof(void*)); // Sample potential return address value for frameless invocation of // stubs (we'll figure out later, if this value makes sense). // TODO(petermarshall): This read causes guard page violations on Windows. // Either fix this mechanism for frameless stubs or remove it. // tos = // i::ReadUnalignedValue<void*>(reinterpret_cast<i::Address>(regs.sp)); tos = nullptr; } else { tos = nullptr; } this->sampling_interval = sampling_interval; timestamp = base::TimeTicks::HighResolutionNow(); } bool TickSample::GetStackSample(Isolate* v8_isolate, RegisterState* regs, RecordCEntryFrame record_c_entry_frame, void** frames, size_t frames_limit, v8::SampleInfo* sample_info, bool use_simulator_reg_state, void** contexts) { i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); sample_info->frames_count = 0; sample_info->vm_state = isolate->current_vm_state(); sample_info->external_callback_entry = nullptr; sample_info->top_context = nullptr; if (sample_info->vm_state == GC) return true; i::Address js_entry_sp = isolate->js_entry_sp(); if (js_entry_sp == 0) return true; // Not executing JS now. #if defined(USE_SIMULATOR) if (use_simulator_reg_state) { if (!i::SimulatorHelper::FillRegisters(isolate, regs)) return false; } #else USE(use_simulator_reg_state); #endif DCHECK(regs->sp); // Check whether we interrupted setup/teardown of a stack frame in JS code. // Avoid this check for C++ code, as that would trigger false positives. if (regs->pc && isolate->heap()->memory_allocator()->code_range().contains( reinterpret_cast<i::Address>(regs->pc)) && IsNoFrameRegion(reinterpret_cast<i::Address>(regs->pc))) { // The frame is not setup, so it'd be hard to iterate the stack. Bailout. return false; } i::ExternalCallbackScope* scope = isolate->external_callback_scope(); i::Address handler = i::Isolate::handler(isolate->thread_local_top()); // If there is a handler on top of the external callback scope then // we have already entered JavaScript again and the external callback // is not the top function. if (scope && scope->scope_address() < handler) { i::Address* external_callback_entry_ptr = scope->callback_entrypoint_address(); sample_info->external_callback_entry = external_callback_entry_ptr == nullptr ? nullptr : reinterpret_cast<void*>(*external_callback_entry_ptr); } i::SafeStackFrameIterator it(isolate, reinterpret_cast<i::Address>(regs->pc), reinterpret_cast<i::Address>(regs->fp), reinterpret_cast<i::Address>(regs->sp), reinterpret_cast<i::Address>(regs->lr), js_entry_sp); i::Address top_context_address = it.top_context_address(); if (top_context_address != i::kNullAddress) { sample_info->top_context = reinterpret_cast<void*>( i::ScrapeNativeContextAddress(isolate->heap(), top_context_address)); } else { sample_info->top_context = nullptr; } if (it.done()) return true; size_t i = 0; if (record_c_entry_frame == kIncludeCEntryFrame && (it.top_frame_type() == internal::StackFrame::EXIT || it.top_frame_type() == internal::StackFrame::BUILTIN_EXIT)) { frames[i] = reinterpret_cast<void*>(isolate->c_function()); if (contexts) contexts[i] = sample_info->top_context; i++; } // If we couldn't get a context address from the top frame due to execution // being in a callback, borrow it from the next context on the stack. bool borrows_top_context = it.top_frame_type() == i::StackFrame::EXIT || it.top_frame_type() == i::StackFrame::BUILTIN_EXIT; i::RuntimeCallTimer* timer = isolate->counters()->runtime_call_stats()->current_timer(); for (; !it.done() && i < frames_limit; it.Advance()) { while (timer && reinterpret_cast<i::Address>(timer) < it.frame()->fp() && i < frames_limit) { if (contexts) contexts[i] = nullptr; frames[i++] = reinterpret_cast<void*>(timer->counter()); timer = timer->parent(); } if (i == frames_limit) break; // Attempt to read the native context associated with the frame from the // heap for standard frames. if (it.frame()->is_standard() && (contexts || borrows_top_context)) { i::Address context_address = base::Memory<i::Address>( it.frame()->fp() + i::StandardFrameConstants::kContextOffset); i::Address native_context_address = i::ScrapeNativeContextAddress(isolate->heap(), context_address); if (contexts) contexts[i] = reinterpret_cast<void*>(native_context_address); if (borrows_top_context) { DCHECK(!sample_info->top_context); sample_info->top_context = reinterpret_cast<void*>(native_context_address); } } else if (contexts) { contexts[i] = nullptr; } borrows_top_context = false; if (it.frame()->is_interpreted()) { // For interpreted frames use the bytecode array pointer as the pc. i::InterpretedFrame* frame = static_cast<i::InterpretedFrame*>(it.frame()); // Since the sampler can interrupt execution at any point the // bytecode_array might be garbage, so don't actually dereference it. We // avoid the frame->GetXXX functions since they call BytecodeArray::cast, // which has a heap access in its DCHECK. i::Address bytecode_array = base::Memory<i::Address>( frame->fp() + i::InterpreterFrameConstants::kBytecodeArrayFromFp); i::Address bytecode_offset = base::Memory<i::Address>( frame->fp() + i::InterpreterFrameConstants::kBytecodeOffsetFromFp); // If the bytecode array is a heap object and the bytecode offset is a // Smi, use those, otherwise fall back to using the frame's pc. if (HAS_STRONG_HEAP_OBJECT_TAG(bytecode_array) && HAS_SMI_TAG(bytecode_offset)) { frames[i++] = reinterpret_cast<void*>( bytecode_array + i::Internals::SmiValue(bytecode_offset)); continue; } } frames[i++] = reinterpret_cast<void*>(it.frame()->pc()); } sample_info->frames_count = i; return true; } void TickSample::print() const { PrintF("TickSample: at %p\n", this); PrintF(" - state: %s\n", StateToString(state)); PrintF(" - pc: %p\n", pc); PrintF(" - stack: (%u frames)\n", frames_count); for (unsigned i = 0; i < frames_count; i++) { PrintF(" %p\n", stack[i]); } PrintF(" - has_external_callback: %d\n", has_external_callback); PrintF(" - %s: %p\n", has_external_callback ? "external_callback_entry" : "tos", tos); PrintF(" - update_stats: %d\n", update_stats); PrintF(" - sampling_interval: %" PRId64 "\n", sampling_interval.InMicroseconds()); PrintF("\n"); } } // namespace internal } // namespace v8
{ "pile_set_name": "Github" }
from dataclasses import dataclass from enum import Enum from functools import partial import typing as t from .errors import DIErrors NameOrInterface = t.Union[type, str] Constructor = t.Union[t.Type, t.Callable] Kwargs = t.Dict[str, t.Any] # keyword-arguments of a Constructor ScopeFunction = t.Callable[[Constructor, Kwargs], t.Any] _CONTAINER_REF = '__di_container__' _CONTEXT_REF = '__di_context__' _SCOPE_TYPE_REF = '__di_scope__' @dataclass(frozen=True) class DIContext: """ Describes the way a component might be requested from the Container. It can be at one of two states: * indeterminate - the context value will become determined when you bound its value to the state of some target (a DI component) with `DIContext.determine` method. * determined - the context is static, nothing is to be determined. You can check the container with the DIContext only when the context is determined. NB: DIContext is immutable, so calling `DIContext.determine` on a indeterminate context will produce a new DIContext instance. :cvar interface: an interface of the dependency. It's often used along with annotations about the variable/argument that requests the dependency. :cvar name: an arbitrary string describing dependency (an alternative to `interface` argument). Simple to use, but it doesn't give any information about its interface. :cvar qualifier: an object of any type that adds a finer grade granularity about the dependency; i.e. you may want a component of `IDao` interface: not just anyone, but the one that is modeling some specific schema; the qualifier describes the latter condition. :cvar get_qualifier: a function that can produce a qualifier from a component. Signature of (target: Component) -> qualifier: str """ name: str = None interface: t.Type = None qualifier: t.Any = None get_qualifier: t.Callable[[t.Any], t.Any] = None def __post_init__(self): if self.qualifier and self.get_qualifier: raise DIErrors.CONTRADICTORY_QUALIFIER_DEFINED.with_params( qualifier=self.qualifier, get_qualifier=self.get_qualifier) def is_determined(self): """ Checks whether qualifier is already determined and static or yet has to be determined by calling `get_qualifier` on an instance of a component. """ return self.get_qualifier is None def determine(self, target: t.Any) -> 'DIContext': if self.is_determined(): return self qualifier = self.get_qualifier(target) return DIContext(name=self.name, interface=self.interface, qualifier=qualifier) def get(self, container: 'Container') -> t.Any: """ Finds a injected instance of the dependency declared by the `Inject` attributes using given container. Prioritizes name vs. interface precedence & collision when seeking for a dependency. """ if self.name and self.interface: # exactly only one of those two defined raise DIErrors.AMBIGUOUS_DEFINITION.with_params( name=self.name, interface=self.interface) if not self.is_determined(): raise DIErrors.INDETERMINATE_CONTEXT_BEING_RESOLVED.with_params( name=self.name, interface=self.interface, get_qualifier=self.get_qualifier ) if self.name: return container.find_by_name(self.name, self.qualifier) elif self.interface: return container.find_by_interface(self.interface, self.qualifier) else: raise DIErrors.NO_IDENTIFIER_SPECIFIED @dataclass(frozen=True) class DIResolution: """ Describes what has been registered as a dependency: :cvar constructor: a type or a callable that builds the dependency instance :cvar kwargs: a kwargs dict that specifies keyword arguments for the dependency constructor """ constructor: Constructor kwargs: Kwargs = None class Container: """ Dependency Injection container. It is the basic object in the Dependency Injection mechanism and makes all the components use DI machinery for its own purposes. """ def __init__(self, default_scope: 'Scopes' = None): self._constructor_registry: t.Dict[DIContext, DIResolution] = {} self._singleton_registry = {} self._default_scope = default_scope def register_by_name( self, name: str, constructor: Constructor, qualifier: t.Any = None, kwargs: Kwargs = None, scope: 'Scopes' = None, ): """ Registering constructors by name and (optional) qualifier. :param name: name as the identifier of the constructor registration :param constructor: a type or a callable that can construct an instance of the dependency. Expected signature: (Container, **kwargs) -> dependency_instance :param qualifier: (optional) arbitrary object to narrow the context of identifying the constructor. The typical use case is a situation when multiple constructors are registered for the same interface, but for different target components. :param kwargs: (optional) keyword arguments of the constructor :param scope: (optional) scope of the registration. If provided, it defines when the constructor is called to provide a new instance of the dependency. It overrides scope declared with a `scope` decorator on the constructor, if any, and the default scope of the container. """ context = DIContext(name=name, qualifier=qualifier) self._register( context=context, constructor=constructor, kwargs=kwargs, scope=scope ) def register_by_interface( self, interface: type, constructor: Constructor, qualifier: t.Any = None, kwargs: Kwargs = None, scope: 'Scopes' = None, ): """ Registering constructors by interface and (optional) qualifier. :param interface: a type that defines API of the injected dependency. :param constructor: a type or a callable that can construct an instance of the dependency. Expected signature: (Container, **kwargs) -> dependency_instance :param qualifier: (optional) arbitrary object to narrow the context of identifying the constructor. The typical use case is a situation when multiple constructors are registered for the same interface, but for different target components. :param kwargs: (optional) keyword arguments of the constructor :param scope: (optional) scope of the registration. If provided, it defines when the constructor is called to provide a new instance of the dependency. It overrides scope declared with a `scope` decorator on the constructor, if any, and the default scope of the container. """ context = DIContext(interface=interface, qualifier=qualifier) # TODO Refs #20: should I register superclasses of the interface as well? self._register( context=context, constructor=constructor, kwargs=kwargs, scope=scope ) def _register( self, context: DIContext, constructor: Constructor, kwargs: Kwargs = None, scope: 'Scopes' = None, ): """Technical detail of registering a constructor""" if context in self._constructor_registry: raise DIErrors.ALREADY_REGISTERED.with_params(context=context) self._constructor_registry[context] = DIResolution(constructor=constructor, kwargs=kwargs) if scope is not None: setattr(constructor, _SCOPE_TYPE_REF, scope) def find_by_name(self, name: str, qualifier: t.Any = None) -> t.Any: """Finding registered constructor by name.""" return self._find(DIContext(name=name, qualifier=qualifier)) def find_by_interface(self, interface: type, qualifier: t.Any = None) -> t.Any: """Finding registered constructor by interface.""" # TODO Refs #20: should I look for the subclasses of the interface as well? return self._find(DIContext(interface=interface, qualifier=qualifier)) def _find(self, context: DIContext) -> t.Any: try: resolution = self._constructor_registry[context] except KeyError: raise DIErrors.DEFINITION_NOT_FOUND.with_params(context=context) return self._get_object(resolution, context) def _get_object(self, resolution: DIResolution, context: DIContext = None) -> t.Any: """ Gets proper scope type and creates instance of registered constructor accordingly. """ kwargs = resolution.kwargs or {} constructor = resolution.constructor context = context or DIContext() scope_function = get_scope_type(constructor) or self._default_scope return scope_function(self, constructor, kwargs, context) # Implementation of the scopes def instance_scope( self, constructor: Constructor, kwargs: Kwargs, context: DIContext = None ) -> t.Any: """Every injection makes a new instance.""" instance = constructor(**kwargs) set_di_context(instance, self, context) return instance def singleton_scope( self, constructor: Constructor, kwargs: Kwargs, context: DIContext ) -> t.Any: """First injection makes a new instance, later ones return the same instance.""" try: instance = self._singleton_registry[constructor] except KeyError: instance = self._singleton_registry[constructor] = constructor(**kwargs) set_di_context(instance, self, context) return instance class Scopes(Enum): INSTANCE: 'Scopes' = partial(Container.instance_scope) SINGLETON: 'Scopes' = partial(Container.singleton_scope) def __call__( self, container: Container, constructor: Constructor, kwargs: Kwargs, context: DIContext = None, ) -> t.Any: return self.value(container, constructor, kwargs, context) def __repr__(self): return f"<Scopes.{self.name}>" def set_di_context(instance: t.Any, container: Container, context: DIContext) -> None: """ A helper function to set DI container & DI context to an arbitrary object to conform Dependency Injection mechanics. """ # supporting immutable instances object.__setattr__(instance, _CONTAINER_REF, container) object.__setattr__(instance, _CONTEXT_REF, context) def get_di_container(instance: t.Any) -> Container: """ A helper function to extract the container from an arbitrary object that can serve as a component. """ return getattr(instance, _CONTAINER_REF, None) def get_di_context(instance: t.Any) -> DIContext: """ A helper function to get from an arbitrary object its DI context. """ return getattr(instance, _CONTEXT_REF, None) def get_scope_type(constructor: Constructor) -> t.Optional[Scopes]: """ A helper function to extract the scope type from a constructor. """ return getattr(constructor, _SCOPE_TYPE_REF, None) def set_scope_type(constructor: Constructor, scope: Scopes) -> None: """ A helper function to set the scope type on a constructor. """ setattr(constructor, _SCOPE_TYPE_REF, scope)
{ "pile_set_name": "Github" }
(8,10)-(8,15) A type specifier is expected here. (8,16)-(8,19) Encountered unexpected token `int`.
{ "pile_set_name": "Github" }
<component name="libraryTable"> <library name="Dart SDK"> <CLASSES> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/async" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/collection" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/convert" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/core" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/developer" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/html" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/io" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/isolate" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/math" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/mirrors" /> <root url="file://$USER_HOME$/flutter/bin/cache/dart-sdk/lib/typed_data" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
{ "pile_set_name": "Github" }
{% extends 'emails/base.txt' %} {% block subject -%} {{ subject }} {%- endblock %} {% block header -%}{%- endblock %} {% block body -%} {{ body }} {%- endblock %} {% block footer_title -%} Call for Abstracts {%- endblock %} {% block footer_url -%} {{ event.external_url }} {%- endblock %}
{ "pile_set_name": "Github" }
.active_itemAll{ width: 560px; align-items: center; } .active_item{ display: flex; align-items: center; line-height:36px; font-size: 20px; span{ flex: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .active_logo{ display: flex; width: 28px; height: 28px; align-items: center; justify-content: center; font-size: 20px; margin-right: 12px; font-style: normal; box-sizing: border-box; text-align: center; border-radius: 4px; } } .show_active{ display: flex; position: relative; flex-grow:1; .active_item:first-child{ padding-right:140px; } .active_item:not(:first-child){ margin-top: 2.5px; } .show_more{ position: absolute; right: 0; top: 0; padding: 3px 20px 7.5px 0; height: 100%; color: #999; text-align: right; font-size: 20px; line-height: 1; span{ display: inline-block; transform: scale(0.85); } .show_num{ display: flex; align-items: center; } svg{ width: .173333rem; height: .173333rem; opacity: .9; -webkit-transition: all .3s ease-in-out; transition: all .3s ease-in-out; -webkit-transform: rotate(0deg); transform: rotate(0deg); fill: currentColor; will-change: transform; transition: all .3s ease-in-out; } .nowSvg{ transform: rotate(180deg); } } .on { &::after{ transform:rotate(-180deg); } } }
{ "pile_set_name": "Github" }
// Copyright (c) 2014, AEON, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder 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 HOLDER 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #pragma once #include <vector> #include "cryptonote_core/account.h" #include "cryptonote_core/cryptonote_basic.h" #include "cryptonote_core/cryptonote_format_utils.h" #include "crypto/crypto.h" template<size_t a_ring_size> class multi_tx_test_base { static_assert(0 < a_ring_size, "ring_size must be greater than 0"); public: static const size_t ring_size = a_ring_size; static const size_t real_source_idx = ring_size / 2; bool init() { using namespace cryptonote; std::vector<tx_source_entry::output_entry> output_entries; for (size_t i = 0; i < ring_size; ++i) { m_miners[i].generate(); if (!construct_miner_tx(0, 0, 0, 2, 0, m_miners[i].get_keys().m_account_address, m_miner_txs[i])) return false; txout_to_key tx_out = boost::get<txout_to_key>(m_miner_txs[i].vout[0].target); output_entries.push_back(std::make_pair(i, tx_out.key)); m_public_keys[i] = tx_out.key; m_public_key_ptrs[i] = &m_public_keys[i]; } m_source_amount = m_miner_txs[0].vout[0].amount; tx_source_entry source_entry; source_entry.amount = m_source_amount; source_entry.real_out_tx_key = get_tx_pub_key_from_extra(m_miner_txs[real_source_idx]); source_entry.real_output_in_tx_index = 0; source_entry.outputs.swap(output_entries); source_entry.real_output = real_source_idx; m_sources.push_back(source_entry); return true; } protected: cryptonote::account_base m_miners[ring_size]; cryptonote::transaction m_miner_txs[ring_size]; uint64_t m_source_amount; std::vector<cryptonote::tx_source_entry> m_sources; crypto::public_key m_public_keys[ring_size]; const crypto::public_key* m_public_key_ptrs[ring_size]; };
{ "pile_set_name": "Github" }
/* * Copyright © 2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.security.auth; import io.cdap.cdap.common.conf.CConfiguration; import java.io.IOException; /** * Maintains secret keys in memory and uses them to sign and validate authentication tokens. */ public class InMemoryKeyManager extends MapBackedKeyManager { /** * Create an InMemoryKeyManager that stores keys in memory only. * @param conf */ public InMemoryKeyManager(CConfiguration conf) { super(conf); } @Override public void doInit() throws IOException { generateKey(); } @Override public void shutDown() { // nothing to do } }
{ "pile_set_name": "Github" }
#### Golang + Instagram Private API <p align="center"><img width=100% src="https://raw.githubusercontent.com/ahmdrz/goinsta/v1/resources/goinsta-image.png"></p> > Unofficial Instagram API for Golang [![Build Status](https://travis-ci.org/ahmdrz/goinsta.svg?branch=master)](https://travis-ci.org/ahmdrz/goinsta) [![GoDoc](https://godoc.org/github.com/ahmdrz/goinsta?status.svg)](https://godoc.org/github.com/ahmdrz/goinsta) [![Go Report Card](https://goreportcard.com/badge/github.com/ahmdrz/goinsta)](https://goreportcard.com/report/github.com/ahmdrz/goinsta) [![Gitter chat](https://badges.gitter.im/goinsta/community.png)](https://gitter.im/goinsta/community) ### Features * **HTTP2 by default. Goinsta uses HTTP2 client enhancing performance.** * **Object independency. Can handle multiple instagram accounts.** * **Like Instagram mobile application**. Goinsta is very similar to Instagram official application. * **Simple**. Goinsta is made by lazy programmers! * **Backup methods**. You can use `Export` and `Import` functions. * **Security**. Your password is only required to login. After login your password is deleted. * **No External Dependencies**. GoInsta will not use any Go packages outside of the standard library. ### Package installation `go get -u -v gopkg.in/ahmdrz/goinsta.v2` ### Example ```go package main import ( "fmt" "gopkg.in/ahmdrz/goinsta.v2" ) func main() { insta := goinsta.New("USERNAME", "PASSWORD") // Export your configuration // after exporting you can use Import function instead of New function. // insta, err := goinsta.Import("~/.goinsta") // it's useful when you want use goinsta repeatedly. insta.Export("~/.goinsta") ... } ``` ### Projects using `goinsta` - [go-instabot](https://github.com/tducasse/go-instabot) - [nick_bot](https://github.com/icholy/nick_bot) - [instagraph](https://github.com/ahmdrz/instagraph) - [icrawler](https://github.com/themester/icrawler) - [ermes](https://github.com/borteo/ermes) - [instafeed](https://github.com/falzm/instafeed) - [goinstadownload](https://github.com/alejoloaiza/goinstadownload) - [InstagramStoriesDownloader](https://github.com/DiSiqueira/InstagramStoriesDownloader) - [gridcube-challenge](https://github.com/rodrwan/gridcube-challenge) - [nyaakitties](https://github.com/gracechang/nyaakitties) - [InstaFollower](https://github.com/Unanoc/InstaFollower) - [follow-sync](https://github.com/kirsle/follow-sync) - [Game DB](https://github.com/gamedb/gamedb) - ... ### Legal This code is in no way affiliated with, authorized, maintained, sponsored or endorsed by Instagram or any of its affiliates or subsidiaries. This is an independent and unofficial API. Use at your own risk. ### Versioning Goinsta used gopkg.in as versioning control. Stable new API is the version v2.0. You can get it using: ```bash $ go get -u -v gopkg.in/ahmdrz/goinsta.v2 ``` Or If you have `GO111MODULE=on` ``` $ go get -u github.com/ahmdrz/goinsta/v2 ``` ### Donate **Ahmdrz** ![btc](https://raw.githubusercontent.com/reek/anti-adblock-killer/gh-pages/images/bitcoin.png) Bitcoin: `1KjcfrBPJtM4MfBSGTqpC6RcoEW1KBh15X` **Mester** ![btc](https://raw.githubusercontent.com/reek/anti-adblock-killer/gh-pages/images/bitcoin.png) Bitcoin: `37aogDJYBFkdSJTWG7TgcpgNweGHPCy1Ks` [![Analytics](https://ga-beacon.appspot.com/UA-107698067-1/readme-page)](https://github.com/igrigorik/ga-beacon)
{ "pile_set_name": "Github" }
let t: Array<string> = new Array<string>(); console.log(t);
{ "pile_set_name": "Github" }
// Copyright Joyent, Inc. and other Node contributors. // // 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. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); };
{ "pile_set_name": "Github" }
package org.infinispan.container.entries.metadata; import org.infinispan.metadata.Metadata; /** * Marker interface for metadata aware cache entry. * * @author Galder Zamarreño * @since 5.3 */ public interface MetadataAware { /** * Get metadata of this cache entry. * * @return a Metadata instance */ Metadata getMetadata(); /** * Set the metadata in the cache entry. * * @param metadata to apply to the cache entry */ void setMetadata(Metadata metadata); }
{ "pile_set_name": "Github" }
module.exports = { local: function(y, m, d, H, M, S, L) { return new Date(y, m||0, d||1, H||0, M||0, S||0, L||0); }, utc: function(y, m, d, H, M, S, L) { return new Date(Date.UTC(y, m||0, d||1, H||0, M||0, S||0, L||0)); }, enUS: { number: { decimal: '.', thousands: ',', grouping: [3], currency: ['$', ''] }, time: { dateTime: '%x, %X', date: '%-m/%-d/%Y', time: '%-I:%M:%S %p', periods: ['AM', 'PM'], days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] } }, deDE: { number: { decimal: ',', thousands: '.', grouping: [3], currency: ['', '\u00a0€'] }, time: { dateTime: '%A, der %e. %B %Y, %X', date: '%d.%m.%Y', time: '%H:%M:%S', periods: ['AM', 'PM'], days: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], shortDays: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], shortMonths: ['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'] } } };
{ "pile_set_name": "Github" }
/* In-software asymmetric public-key crypto subtype * * See Documentation/crypto/asymmetric-keys.txt * * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #define pr_fmt(fmt) "PKEY: "fmt #include <linux/module.h> #include <linux/export.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <keys/asymmetric-subtype.h> #include "public_key.h" MODULE_LICENSE("GPL"); const char *const pkey_algo_name[PKEY_ALGO__LAST] = { [PKEY_ALGO_DSA] = "DSA", [PKEY_ALGO_RSA] = "RSA", }; EXPORT_SYMBOL_GPL(pkey_algo_name); const struct public_key_algorithm *pkey_algo[PKEY_ALGO__LAST] = { #if defined(CONFIG_PUBLIC_KEY_ALGO_RSA) || \ defined(CONFIG_PUBLIC_KEY_ALGO_RSA_MODULE) [PKEY_ALGO_RSA] = &RSA_public_key_algorithm, #endif }; EXPORT_SYMBOL_GPL(pkey_algo); const char *const pkey_id_type_name[PKEY_ID_TYPE__LAST] = { [PKEY_ID_PGP] = "PGP", [PKEY_ID_X509] = "X509", }; EXPORT_SYMBOL_GPL(pkey_id_type_name); /* * Provide a part of a description of the key for /proc/keys. */ static void public_key_describe(const struct key *asymmetric_key, struct seq_file *m) { struct public_key *key = asymmetric_key->payload.data; if (key) seq_printf(m, "%s.%s", pkey_id_type_name[key->id_type], key->algo->name); } /* * Destroy a public key algorithm key. */ void public_key_destroy(void *payload) { struct public_key *key = payload; int i; if (key) { for (i = 0; i < ARRAY_SIZE(key->mpi); i++) mpi_free(key->mpi[i]); kfree(key); } } EXPORT_SYMBOL_GPL(public_key_destroy); /* * Verify a signature using a public key. */ int public_key_verify_signature(const struct public_key *pk, const struct public_key_signature *sig) { const struct public_key_algorithm *algo; BUG_ON(!pk); BUG_ON(!pk->mpi[0]); BUG_ON(!pk->mpi[1]); BUG_ON(!sig); BUG_ON(!sig->digest); BUG_ON(!sig->mpi[0]); algo = pk->algo; if (!algo) { if (pk->pkey_algo >= PKEY_ALGO__LAST) return -ENOPKG; algo = pkey_algo[pk->pkey_algo]; if (!algo) return -ENOPKG; } if (!algo->verify_signature) return -ENOTSUPP; if (sig->nr_mpi != algo->n_sig_mpi) { pr_debug("Signature has %u MPI not %u\n", sig->nr_mpi, algo->n_sig_mpi); return -EINVAL; } return algo->verify_signature(pk, sig); } EXPORT_SYMBOL_GPL(public_key_verify_signature); static int public_key_verify_signature_2(const struct key *key, const struct public_key_signature *sig) { const struct public_key *pk = key->payload.data; return public_key_verify_signature(pk, sig); } /* * Public key algorithm asymmetric key subtype */ struct asymmetric_key_subtype public_key_subtype = { .owner = THIS_MODULE, .name = "public_key", .name_len = sizeof("public_key") - 1, .describe = public_key_describe, .destroy = public_key_destroy, .verify_signature = public_key_verify_signature_2, }; EXPORT_SYMBOL_GPL(public_key_subtype);
{ "pile_set_name": "Github" }
% Copyright 2006 by Till Tantau % % This file may be distributed and/or modified % % 1. under the LaTeX Project Public License and/or % 2. under the GNU Free Documentation License. % % See the file doc/generic/pgf/licenses/LICENSE for more details. \section{Transformations} \pgfname\ has a powerful transformation mechanism that is similar to the transformation capabilities of \textsc{metafont}. The present section explains how you can access it in \tikzname. \subsection{The Different Coordinate Systems} It is a long process from a coordinate like, say, $(1,2)$ or $(1\mathrm{cm},5\mathrm{pt})$, to the position a point is finally placed on the display or paper. In order to find out where the point should go, it is constantly ``transformed,'' which means that it is mostly shifted around and possibly rotated, slanted, scaled, and otherwise mutilated. In detail, (at least) the following transformations are applied to a coordinate like $(1,2)$ before a point on the screen is chosen: \begin{enumerate} \item \pgfname\ interprets a coordinate like $(1,2)$ in its $xy$-coordinate system as ``add the current $x$-vector once and the current $y$-vector twice to obtain the new point.'' \item \pgfname\ applies its coordinate transformation matrix to the resulting coordinate. This yields the final position of the point inside the picture. \item The backend driver (like |dvips| or |pdftex|) adds transformation commands such that the coordinate is shifted to the correct position in \TeX's page coordinate system. \item \textsc{pdf} (or PostScript) apply the canvas transformation matrix to the point, which can once more change the position on the page. \item The viewer application or the printer applies the device transformation matrix to transform the coordinate to its final pixel coordinate on the screen or paper. \end{enumerate} In reality, the process is even more involved, but the above should give the idea: A point is constantly transformed by changes of the coordinate system. In \tikzname, you only have access to the first two coordinate systems: The $xy$-coordinate system and the coordinate transformation matrix (these will be explained later). \pgfname\ also allows you to change the canvas transformation matrix, but you have to use commands of the core layer directly to do so and you ``better know what you are doing'' when you do this. The moment you start modifying the canvas matrix, \pgfname\ immediately loses track of all coordinates and shapes, anchors, and bounding box computations will no longer work. \subsection{The XY- and XYZ-Coordinate Systems} \label{section-xyz} The first and easiest coordinate systems are \pgfname's $xy$- and $xyz$-coordinate systems. The idea is very simple: Whenever you specify a coordinate like |(2,3)| this means $2v_x + 3v_y$, where $v_x$ is the current \emph{$x$-vector} and $v_y$ is the current \emph{$y$-vector}. Similarly, the coordinate |(1,2,3)| means $v_x + 2v_y + 3v_z$. Unlike other packages, \pgfname\ does not insist that $v_x$ actually has a $y$-component of $0$, that is, that it is a horizontal vector. Instead, the $x$-vector can point anywhere you want. Naturally, \emph{normally} you will want the $x$-vector to point horizontally. One undesirable effect of this flexibility is that it is not possible to provide mixed coordinates as in $(1,2\mathrm{pt})$. Life is hard. To change the $x$-, $y$-, and $z$-vectors, you can use the following options: \begin{key}{/tikz/x=\meta{value} (initially 1cm)} If \meta{value} is a dimension, the $x$-vector of \pgfname's $xyz$-coordinate system is set up to point \meta{value} to the right, that is, to $(\meta{value},0pt)$. \begin{codeexample}[] \begin{tikzpicture} \draw (0,0) -- +(1,0); \draw[x=2cm,color=red] (0,0.1) -- +(1,0); \end{tikzpicture} \end{codeexample} \begin{codeexample}[] \tikz \draw[x=1.5cm] (0,0) grid (2,2); \end{codeexample} The last example shows that the size of steppings in grids, just like all other dimensions, are not affected by the $x$-vector. After all, the $x$-vector is only used to determine the coordinate of the upper right corner of the grid. If \meta{value} is a coordinate, the $x$-vector of \pgfname's $xyz$-coordinate system to the specified coordinate. If \meta{value} contains a comma, it must be put in braces. \begin{codeexample}[] \begin{tikzpicture} \draw (0,0) -- (1,0); \draw[x={(2cm,0.5cm)},color=red] (0,0) -- (1,0); \end{tikzpicture} \end{codeexample} You can use this, for example, to exchange the meaning of the $x$- and $y$-coordinate. \begin{codeexample}[] \begin{tikzpicture}[smooth] \draw plot coordinates{(1,0) (2,0.5) (3,0) (3,1)}; \draw[x={(0cm,1cm)},y={(1cm,0cm)},color=red] plot coordinates{(1,0) (2,0.5) (3,0) (3,1)}; \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/y=\meta{value} (initially 1cm)} Works like the |x=| option, only if \meta{value} is a dimension, the resulting vector points to $(0,\meta{value})$. \end{key} \begin{key}{/tikz/z=\meta{value} (initially \normalfont$-3.85$mm)} Works like the |y=| option, but now a dimension is the point $(\meta{value},\meta{value})$. \begin{codeexample}[] \begin{tikzpicture}[z=-1cm,->,thick] \draw[color=red] (0,0,0) -- (1,0,0); \draw[color=blue] (0,0,0) -- (0,1,0); \draw[color=orange] (0,0,0) -- (0,0,1); \end{tikzpicture} \end{codeexample} \end{key} \subsection{Coordinate Transformations} \pgfname\ and \tikzname\ allow you to specify \emph{coordinate transformations}. Whenever you specify a coordinate as in |(1,0)| or |(1cm,1pt)| or |(30:2cm)|, this coordinate is first ``reduced'' to a position of the form ``$x$ points to the right and $y$ points upwards.'' For example, |(1in,5pt)| is reduced to ``$72\frac{72}{100}$ points to the right and 5 points upwards'' and |(90:100pt)| means ``0pt to the right and 100 points upwards.'' The next step is to apply the current \emph{coordinate transformation matrix} to the coordinate. For example, the coordinate transformation matrix might currently be set such that it adds a certain constant to the $x$ value. Also, it might be set up such that it, say, exchanges the $x$ and $y$ value. In general, any ``standard'' transformation like translation, rotation, slanting, or scaling or any combination thereof is possible. (Internally, \pgfname\ keeps track of a coordinate transformation matrix very much like the concatenation matrix used by \textsc{pdf} or PostScript.) \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) rectangle (1,0.5); \begin{scope}[xshift=1cm] \draw [red] (0,0) rectangle (1,0.5); \draw[yshift=1cm] [blue] (0,0) rectangle (1,0.5); \draw[rotate=30] [orange] (0,0) rectangle (1,0.5); \end{scope} \end{tikzpicture} \end{codeexample} The most important aspect of the coordinate transformation matrix is \emph{that it applies to coordinates only!} In particular, the coordinate transformation has no effect on things like the line width or the dash pattern or the shading angle. In certain cases, it is not immediately clear whether the coordinate transformation matrix \emph{should} apply to a certain dimension. For example, should the coordinate transformation matrix apply to grids? (It does.) And what about the size of arced corners? (It does not.) The general rule is ``If there is no `coordinate' involved, even `indirectly,' the matrix is not applied.'' However, sometimes, you simply have to try or look it up in the documentation whether the matrix will be applied. Setting the matrix cannot be done directly. Rather, all you can do is to ``add'' another transformation to the current matrix. However, all transformations are local to the current \TeX-group. All transformations are added using graphic options, which are described below. Transformations apply immediately when they are encountered ``in the middle of a path'' and they apply only to the coordinates on the path following the transformation option. \begin{codeexample}[] \tikz \draw (0,0) rectangle (1,0.5) [xshift=2cm] (0,0) rectangle (1,0.5); \end{codeexample} A final word of warning: You should refrain from using ``aggressive'' transformations like a scaling of a factor of 10000. The reason is that all transformations are done using \TeX, which has a fairly low accuracy. Furthermore, in certain situations it is necessary that \tikzname\ \emph{inverts} the current transformation matrix and this will fail if the transformation matrix is badly conditioned or even singular (if you do not know what singular matrices are, you are blessed). \begin{key}{/tikz/shift={\ttfamily\char`\{}\meta{coordinate}{\ttfamily\char`\}}} Adds the \meta{coordinate} to all coordinates. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[shift={(1,1)},blue] (0,0) -- (1,1) -- (1,0); \draw[shift={(30:1cm)},red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/shift only} This option does not take any parameter. Its effect is to cancel all current transformations except for the shifting. This means that the origin will remain where it is, but any rotation around the origin or scaling relative to the origin or skewing will no longer have an effect. This option is useful in situations where a complicated transformation is used to ``get to a position,'' but you then wish to draw something ``normal'' at this position. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[rotate=30,xshift=2cm,blue] (0,0) -- (1,1) -- (1,0); \draw[rotate=30,xshift=2cm,shift only,red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/xshift=\meta{dimension}} Adds \meta{dimension} to the $x$ value of all coordinates. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[xshift=2cm,blue] (0,0) -- (1,1) -- (1,0); \draw[xshift=-10pt,red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/yshift=\meta{dimension}} Adds \meta{dimension} to the $y$ value of all coordinates. \end{key} \begin{key}{/tikz/scale=\meta{factor}} Multiplies all coordinates by the given \meta{factor}. The \meta{factor} should not be excessively large in absolute terms or very close to zero. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[scale=2,blue] (0,0) -- (1,1) -- (1,0); \draw[scale=-1,red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/scale around={\ttfamily\char`\{}\meta{factor}|:|\meta{coordinate}{\ttfamily\char`\}}} Scales the coordinate system by \meta{factor}, with the ``origin of scaling'' centered on \meta{coordinate} rather than the origin. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[scale=2,blue] (0,0) -- (1,1) -- (1,0); \draw[scale around={2:(1,1)},red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/xscale=\meta{factor}} Multiplies only the $x$-value of all coordinates by the given \meta{factor}. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[xscale=2,blue] (0,0) -- (1,1) -- (1,0); \draw[xscale=-1,red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/yscale=\meta{factor}} Multiplies only the $y$-value of all coordinates by \meta{factor}. \end{key} \begin{key}{/tikz/xslant=\meta{factor}} Slants the coordinate horizontally by the given \meta{factor}: \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[xslant=2,blue] (0,0) -- (1,1) -- (1,0); \draw[xslant=-1,red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/yslant=\meta{factor}} Slants the coordinate vertically by the given \meta{factor}: \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[yslant=2,blue] (0,0) -- (1,1) -- (1,0); \draw[yslant=-1,red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/rotate=\meta{degree}} Rotates the coordinate system by \meta{degree}: \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[rotate=40,blue] (0,0) -- (1,1) -- (1,0); \draw[rotate=-20,red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/rotate around={\ttfamily\char`\{}\meta{degree}|:|\meta{coordinate}{\ttfamily\char`\}}} Rotates the coordinate system by \meta{degree} around the point \meta{coordinate}. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[rotate around={40:(1,1)},blue] (0,0) -- (1,1) -- (1,0); \draw[rotate around={-20:(1,1)},red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/rotate around x=\meta{angle}} This key sets the $x$, $y$ and $z$ vectors of the \pgfname\ $xyz$-coordinate system so that they are rotated by \meta{angle} around the axis corresponding to the $x$-vector. The rotation is applied so that when looking towards the origin along this axis, positive angles result in an anticlockwise rotation. \begin{codeexample}[] \begin{tikzpicture}[>=stealth] \draw [->] (0,0,0) -- (2,0,0) node [at end, right] {$x$}; \draw [->] (0,0,0) -- (0,2,0) node [at end, left] {$y$}; \draw [->] (0,0,0) -- (0,0,2) node [at end, left] {$z$}; \draw [red, rotate around x=0] (0,0,0) -- (1,1,0) -- (1,0,0); \draw [green, rotate around x=45] (0,0,0) -- (1,1,0) -- (1,0,0); \draw [blue, rotate around x=90] (0,0,0) -- (1,1,0) -- (1,0,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/rotate around y=\meta{angle}} This key sets the $x$, $y$ and $z$ vectors of the \pgfname\ $xyz$-coordinate system so that they are rotated by \meta{angle} around the axis corresponding to the $y$-vector. The rotation is applied so that when looking towards the origin along this axis, positive angles result in an anticlockwise rotation. \begin{codeexample}[] \begin{tikzpicture}[>=stealth] \draw [->] (0,0,0) -- (2,0,0) node [at end, right] {$x$}; \draw [->] (0,0,0) -- (0,2,0) node [at end, left] {$y$}; \draw [->] (0,0,0) -- (0,0,2) node [at end, left] {$z$}; \draw [red, rotate around y=0] (0,0,0) -- (1,1,0) -- (1,0,0); \draw [green, rotate around y=-45] (0,0,0) -- (1,1,0) -- (1,0,0); \draw [blue, rotate around y=-90] (0,0,0) -- (1,1,0) -- (1,0,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/rotate around z=\meta{angle}} This key sets the $x$, $y$ and $z$ vectors of the \pgfname\ $xyz$-coordinate system so that they are rotated by \meta{angle} around the axis corresponding to the $z$-vector. The rotation is applied so that when looking towards the origin along this axis, positive angles result in an anticlockwise rotation. \begin{codeexample}[] \begin{tikzpicture}[>=stealth] \draw [->] (0,0,0) -- (2,0,0) node [at end, right] {$x$}; \draw [->] (0,0,0) -- (0,2,0) node [at end, left] {$y$}; \draw [->] (0,0,0) -- (0,0,2) node [at end, left] {$z$}; \draw [red, rotate around z=0] (0,0) -- (1,1) -- (1,0); \draw [green, rotate around z=45] (0,0) -- (1,1) -- (1,0); \draw [blue, rotate around z=90] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/cm={\ttfamily\char`\{}\meta{$a$}|,|\meta{$b$}|,|\meta{$c$}|,|\meta{$d$}|,|\meta{coordinate}{\ttfamily\char`\}}} applies the following transformation to all coordinates: Let $(x,y)$ be the coordinate to be transformed and let \meta{coordinate} specify the point $(t_x,t_y)$. Then the new coordinate is given by $\left(\begin{smallmatrix} a & c \\ b & d\end{smallmatrix}\right) \left(\begin{smallmatrix} x \\ y \end{smallmatrix}\right) + \left(\begin{smallmatrix} t_x \\ t_y \end{smallmatrix}\right)$. Usually, you do not use this option directly. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[cm={1,1,0,1,(0,0)},blue] (0,0) -- (1,1) -- (1,0); \draw[cm={0,1,1,0,(1cm,1cm)},red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key} \begin{key}{/tikz/reset cm} Completely resets the coordinate transformation matrix to the identity matrix. This will destroy not only the transformations applied in the current scope, but also all transformations inherited from surrounding scopes. Do not use this option, unless you really, really know what you are doing. \end{key} \subsection{Canvas Transformations} A \emph{canvas transformation}, see Section~\ref{section-design-transformations} for details, is best thought of as a transformation in which the drawing canvas is stretched or rotated. Imaging writing something on a balloon (the canvas) and then blowing air into the balloon: Not only does the text become larger, the thin lines also become larger. In particular, if you scale the canvas by a factor of two, all lines are twice as thick. Canvas transformations should be used with great care. In most circumstances you do \emph{not} want line widths to change in a picture as this creates visual inconsistency. Just as important, when you use canvas transformations \emph{\pgfname\ loses track of positions of nodes and of picture sizes} since it does not take the effect of canvas transformations into account when it computes coordinates of nodes (do not, however, rely on this; it may change in the future). Finally, note that a canvas transformation always applies to a path as a whole, it is not possible (as for coordinate transformations) to use different transformations in different parts of a path. In short, you should not use canvas transformations unless you really know what you are doing. \begin{key}{/tikz/transform canvas=\meta{options}} The \meta{options} should contain coordinate transformations options like |scale| or |xshift|. Multiple options can be given, their effects accumulate in the usual manner. The effect of these \meta{options} (immediately) changes the current canvas transformation matrix. The coordinate transformation matrix is not changed. Tracking of the picture size is (locally) switched off and the node coordinate will no longer be correct. \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \draw (0,0) -- (1,1) -- (1,0); \draw[transform canvas={scale=2},blue] (0,0) -- (1,1) -- (1,0); \draw[transform canvas={rotate=180},red] (0,0) -- (1,1) -- (1,0); \end{tikzpicture} \end{codeexample} \end{key}
{ "pile_set_name": "Github" }
export const pkgName = '@syncfusion/ej2-angular-charts'; export const pkgVer = '^18.2.58'; export const moduleName = 'ChartModule, AccumulationChartModule, RangeNavigatorModule, SparklineModule, SmithchartModule, StockChartModule, BulletChartModule'; export const themeVer = '~18.2.58';
{ "pile_set_name": "Github" }
1 1000 40 258 8 132 4 136 5 17 10 788 19 408 7 665 9 667 7 157 16 670 13 674 2 549 17 553 16 47 18 439 6 313 8 571 8 700 10 194 17 325 3 584 17 713 11 209 8 739 2 342 10 569 16 345 7 477 9 355 11 484 5 102 10 465 17 622 3 241 2 370 6 756 10 118 16 413 13 251 9 766 15
{ "pile_set_name": "Github" }
[ { "status": 0, "autime": 0, "isPlayground": false, "sortValues": null, "lastOpen": "0001-01-01T00:00:00Z", "sourceInstance": "", "linkedCount": 0, "rawPhase": "", "owner": "", "closeNotes": "", "notifyTime": "0001-01-01T00:00:00Z", "id": "", "closingUserId": "", "canvases": null, "rawType": "Web", "linkedIncidents": null, "dueDate": "0001-01-01T00:00:00Z", "hasRole": false, "dbotMirrorInstance": "", "version": 0, "openDuration": 0, "details": "", "closed": "0001-01-01T00:00:00Z", "reminder": "0001-01-01T00:00:00Z", "type": "", "attachment": null, "rawName": "", "category": "", "dbotMirrorTags": null, "parent": "", "previousRoles": null, "activated": "0001-01-01T00:00:00Z", "runStatus": "", "occurred": "0001-01-01T00:00:00Z", "ShardID": 0, "rawCategory": "", "reason": "", "closeReason": "", "feedBased": false, "phase": "", "lastJobRunTime": "0001-01-01T00:00:00Z", "CustomFields": null, "account": "", "rawCloseReason": "", "dbotDirtyFields": null, "severity": 0, "dbotMirrorDirection": "", "name": "", "roles": null, "created": "0001-01-01T00:00:00Z", "rawJSON": "{\"dest_category\":\"string\",\"app\":\"string\",\"site\":\"string\",\"uri_path\":\"string\",\"tag\":\"string\",\"cookie\":\"string\",\"user_category\":\"string\",\"duration\":\"number\",\"dest_bunit\":\"string\",\"response_time\":\"number\",\"category\":\"string\",\"cached\":\"boolean\",\"src_category\":\"string\",\"src_priority\":\"string\",\"src_bunit\":\"string\",\"user_bunit\":\"string\",\"user_priority\":\"string\",\"dest_priority\":\"string\",\"uri_query\":\"string\"}", "modified": "0001-01-01T00:00:00Z", "sla": 0, "labels": null, "investigationId": "", "dbotCreatedBy": "", "playbookId": "", "sourceBrand": "", "droppedCount": 0, "dbotMirrorId": "" } ]
{ "pile_set_name": "Github" }
define("oasis", ["oasis/util","oasis/xhr","oasis/connect","rsvp","oasis/logger","oasis/version","oasis/config","oasis/sandbox","oasis/sandbox_init","oasis/events","oasis/service","oasis/iframe_adapter","oasis/webworker_adapter","oasis/inline_adapter"], function(__dependency1__, __dependency2__, __dependency3__, RSVP, logger, Version, OasisConfiguration, Sandbox, autoInitializeSandbox, Events, Service, IframeAdapter, WebworkerAdapter, InlineAdapter) { "use strict"; var assert = __dependency1__.assert; var delegate = __dependency1__.delegate; var xhr = __dependency2__.xhr; var connect = __dependency3__.connect; var connectCapabilities = __dependency3__.connectCapabilities; var portFor = __dependency3__.portFor; function Oasis() { // Data structures used by Oasis when creating sandboxes this.packages = {}; this.requestId = 0; this.oasisId = 'oasis' + (+new Date()); this.consumers = {}; this.services = []; // Data structures used when connecting to a parent sandbox this.ports = {}; this.handlers = {}; this.receivedPorts = false; this.configuration = new OasisConfiguration(); this.events = new Events(); this.didCreate(); } Oasis.Version = Version; Oasis.Service = Oasis.Consumer = Service; Oasis.RSVP = RSVP; Oasis.reset = function () { Oasis.adapters = { iframe: new IframeAdapter(), webworker: new WebworkerAdapter(), inline: new InlineAdapter() }; }; Oasis.reset(); Oasis.prototype = { logger: logger, log: function () { this.logger.log.apply(this.logger, arguments); }, on: delegate('events', 'on'), off: delegate('events', 'off'), trigger: delegate('events', 'trigger'), didCreate: function() {}, xhr: xhr, /** This is the entry point that allows the containing environment to create a child sandbox. Options: * `capabilities`: an array of registered services * `url`: a registered URL to a JavaScript file that will initialize the sandbox in the sandboxed environment * `adapter`: a reference to an adapter that will handle the lifecycle of the sandbox. Right now, there are iframe and web worker adapters. @param {Object} options */ createSandbox: function (options) { return new Sandbox(this, options); }, /** This registers a sandbox type inside of the containing environment so that it can be referenced by URL in `createSandbox`. Options: * `capabilities`: An array of service names that will be supplied when calling `createSandbox` * `url`: The URL of the JavaScript file that contains the sandbox code @param {Object} options */ register: function (options) { assert(options.capabilities, "You are trying to register a package without any capabilities. Please provide a list of requested capabilities, or an empty array ([])."); this.packages[options.url] = options; }, configure: function(name, value) { this.configuration[name] = value; }, autoInitializeSandbox: autoInitializeSandbox, connect: connect, connectCapabilities: connectCapabilities, portFor: portFor }; return Oasis; }); define("oasis/base_adapter", ["oasis/util","oasis/shims","oasis/connect","oasis/message_channel","rsvp","oasis/logger"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, RSVP, Logger) { "use strict"; var mustImplement = __dependency1__.mustImplement; var addEventListener = __dependency2__.addEventListener; var removeEventListener = __dependency2__.removeEventListener; var a_indexOf = __dependency2__.a_indexOf; var a_filter = __dependency2__.a_filter; var connectCapabilities = __dependency3__.connectCapabilities; var PostMessageMessageChannel = __dependency4__.PostMessageMessageChannel; function BaseAdapter() { this._unsupportedCapabilities = []; } BaseAdapter.prototype = { initializeSandbox: mustImplement('BaseAdapter', 'initializeSandbox'), name: mustImplement('BaseAdapter', 'name'), unsupportedCapabilities: function () { return this._unsupportedCapabilities; }, addUnsupportedCapability: function (capability) { this._unsupportedCapabilities.push(capability); }, filterCapabilities: function(capabilities) { var unsupported = this._unsupportedCapabilities; return a_filter.call(capabilities, function (capability) { var index = a_indexOf.call(unsupported, capability); return index === -1; }); }, createChannel: function(oasis) { var channel = new PostMessageMessageChannel(oasis); channel.port1.start(); return channel; }, environmentPort: function(sandbox, channel) { return channel.port1; }, sandboxPort: function(sandbox, channel) { return channel.port2; }, proxyPort: function(sandbox, port) { return port; }, connectSandbox: function (receiver, oasis) { var adapter = this; Logger.log("Sandbox listening for initialization message"); function initializeOasisSandbox(event) { if (!event.data.isOasisInitialization) { return; } removeEventListener(receiver, 'message', initializeOasisSandbox); adapter.initializeOasisSandbox(event, oasis); } addEventListener(receiver, 'message', initializeOasisSandbox); adapter.oasisLoaded(oasis); }, initializeOasisSandbox: function (event, oasis) { var adapter = this; oasis.configuration.eventCallback(function () { Logger.log("sandbox: received initialization message."); oasis.connectCapabilities(event.data.capabilities, event.ports); adapter.didConnect(oasis); }); }, createInitializationMessage: function (sandbox) { return { isOasisInitialization: true, capabilities: sandbox._capabilitiesToConnect, }; }, oasisLoadedMessage: "oasisSandboxLoaded", sandboxInitializedMessage: "oasisSandboxInitialized" }; return BaseAdapter; }); define("oasis/config", [], function() { "use strict"; /** Stores Oasis configuration. Options include: - `eventCallback` - a function that wraps `message` event handlers. By default the event hanlder is simply invoked. - `allowSameOrigin` - a card can be hosted on the same domain - `reconnect` - the default reconnect options for iframe sandboxes. Possible values are: - "none" - do not allow sandbox reconnection - "verify" - only allow reconnections from the original origin of the sandbox - "any" - allow any sandbox reconnections. Only use this setting if you are using Oasis strictly for isolation of trusted applications or if it's safe to connect your sandbox to arbitrary origins. This is an advanced setting and should be used with care. */ function OasisConfiguration() { this.eventCallback = function (callback) { callback(); }; this.allowSameOrigin = false; this.reconnect = 'verify'; } return OasisConfiguration; }); define("oasis/connect", ["oasis/util","oasis/shims","oasis/message_channel","rsvp","oasis/logger","exports"], function(__dependency1__, __dependency2__, __dependency3__, RSVP, Logger, __exports__) { "use strict"; var assert = __dependency1__.assert; var a_forEach = __dependency2__.a_forEach; var PostMessagePort = __dependency3__.PostMessagePort; function registerHandler(oasis, capability, options) { var port = oasis.ports[capability]; if (port) { Logger.log(oasis.oasisId, "sandbox: found port, setting up '" + capability + "'"); options.setupCapability(port); if (options.promise) { options.promise.then(function() { port.start(); })['catch'](RSVP.rethrow); } else { port.start(); } } else if (!oasis.receivedPorts) { Logger.log("No port found, saving handler for '" + capability + "'"); oasis.handlers[capability] = options; } else { Logger.log("No port was sent for capability '" + capability + "'"); options.rejectCapability(); } } /** This is the main entry point that allows sandboxes to connect back to their containing environment. It can be called either with a set of named consumers, with callbacks, or using promises. Example // Using promises Oasis.connect('foo').then( function (port) { port.send('hello'); }, function () { // error }); // using callbacks Oasis.connect('foo', function (port) { port.send('hello'); }, errorHandler); // connecting several consumers at once. var ConsumerA = Oasis.Consumer.extend({ initialize: function (port) { this.port = port; }, error: function () { } }); var ConsumerB = Oasis.Consumer.extend({ initialize: function (port) { this.port = port; }, error: function () { } }); Oasis.connect({ consumers: { capabilityA: ConsumerA, capabilityB: ConsumerB } }); @param {String} capability the name of the service to connect to, or an object containing named consumers to connect. @param {Function?} callback the callback to trigger once the other side of the connection is available. @param {Function?} errorCallback the callback to trigger if the capability is not provided by the environment. @return {Promise} a promise that will be resolved once the other side of the connection is available. You can use this instead of the callbacks. */ function connect(capability, callback, errorCallback) { if (typeof capability === 'object') { return connectConsumers(this, capability.consumers); } else if (callback) { return connectCallbacks(this, capability, callback, errorCallback); } else { return connectPromise(this, capability); } } function connectCapabilities(capabilities, eventPorts) { var oasis = this; a_forEach.call(capabilities, function(capability, i) { var handler = oasis.handlers[capability], port = new PostMessagePort(oasis, eventPorts[i]); if (handler) { Logger.log("Invoking handler for '" + capability + "'"); RSVP.resolve(handler.setupCapability(port)).then(function () { port.start(); })['catch'](RSVP.rethrow); } oasis.ports[capability] = port; }); // for each handler w/o capability, reject for( var prop in oasis.handlers ) { if( ! oasis.ports[prop] ) { oasis.handlers[prop].rejectCapability(); } } this.receivedPorts = true; } function portFor(capability) { var port = this.ports[capability]; assert(port, "You asked for the port for the '" + capability + "' capability, but the environment did not provide one."); return port; } function connectConsumers(oasis, consumers) { function setupCapability(Consumer, name) { return function(port) { var consumer = new Consumer(port); oasis.consumers[name] = consumer; consumer.initialize(port, name); }; } function rejectCapability(prop) { return function () { consumers[prop].prototype.error(); }; } for (var prop in consumers) { registerHandler(oasis, prop, { setupCapability: setupCapability(consumers[prop], prop), rejectCapability: rejectCapability(prop) }); } } function connectCallbacks(oasis, capability, callback, errorCallback) { Logger.log("Connecting to '" + capability + "' with callback."); registerHandler(oasis, capability, { setupCapability: function(port) { callback(port); }, rejectCapability: function () { if (errorCallback) { errorCallback(); } } }); } function connectPromise(oasis, capability) { Logger.log("Connecting to '" + capability + "' with promise."); var defered = RSVP.defer(); registerHandler(oasis, capability, { promise: defered.promise, setupCapability: function(port) { defered.resolve(port); return defered.promise; }, rejectCapability: function () { defered.reject(); } }); return defered.promise; } __exports__.registerHandler = registerHandler; __exports__.connect = connect; __exports__.connectCapabilities = connectCapabilities; __exports__.portFor = portFor; }); define("oasis/events", [], function() { "use strict"; var a_slice = Array.prototype.slice; function Events() { this.listenerArrays = {}; } Events.prototype = { on: function (eventName, listener) { var listeners = this.listenerArrays[eventName] = this.listenerArrays[eventName] || []; listeners.push(listener); }, off: function (eventName, listener) { var listeners = this.listenerArrays[eventName]; if (!listeners) { return; } for (var i=0; i<listeners.length; ++i) { if (listeners[i] === listener) { listeners.splice(i, 1); break; } } }, clear: function(eventName) { delete this.listenerArrays[eventName]; }, trigger: function(eventName) { var listeners = this.listenerArrays[eventName]; if (!listeners) { return; } var args = a_slice.call(arguments, 1); for (var i=0; i<listeners.length; ++i) { listeners[i].apply(null, args); } } }; return Events; }); define("oasis/iframe_adapter", ["oasis/util","oasis/shims","rsvp","oasis/logger","oasis/base_adapter"], function(__dependency1__, __dependency2__, RSVP, Logger, BaseAdapter) { "use strict"; var assert = __dependency1__.assert; var extend = __dependency1__.extend; var a_forEach = __dependency2__.a_forEach; var addEventListener = __dependency2__.addEventListener; var removeEventListener = __dependency2__.removeEventListener; var a_map = __dependency2__.a_map; /*global Window, UUID */ function verifySandbox(oasis, sandboxUrl) { var iframe = document.createElement('iframe'), link; if( (oasis.configuration.allowSameOrigin && iframe.sandbox !== undefined) || (iframe.sandbox === undefined) ) { // The sandbox attribute isn't supported (IE8/9) or we want a child iframe // to access resources from its own domain (youtube iframe), // we need to make sure the sandbox is loaded from a separate domain link = document.createElement('a'); link.href = sandboxUrl; if( !link.host || (link.protocol === window.location.protocol && link.host === window.location.host) ) { throw new Error("Security: iFrames from the same host cannot be sandboxed in older browsers and is disallowed. " + "For HTML5 browsers supporting the `sandbox` attribute on iframes, you can add the `allow-same-origin` flag" + "only if you host the sandbox on a separate domain."); } } } function verifyCurrentSandboxOrigin(sandbox, event) { var linkOriginal, linkCurrent; if (sandbox.firstLoad || sandbox.options.reconnect === "any") { return true; } if (!sandbox.oasis.configuration.allowSameOrigin || event.origin === "null") { fail(); } else { linkOriginal = document.createElement('a'); linkCurrent = document.createElement('a'); linkOriginal.href = sandbox.options.url; linkCurrent.href = event.origin; if (linkCurrent.protocol === linkOriginal.protocol && linkCurrent.host === linkOriginal.host) { return true; } fail(); } function fail() { sandbox.onerror( new Error("Cannot reconnect null origins unless `reconnect` is set to " + "'any'. `reconnect: 'verify' requires `allowSameOrigin: " + "true`")); } } function isUrl(s) { var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return regexp.test(s); } var IframeAdapter = extend(BaseAdapter, { //------------------------------------------------------------------------- // Environment API initializeSandbox: function(sandbox) { var options = sandbox.options, iframe = document.createElement('iframe'), sandboxAttributes = ['allow-scripts']; if( sandbox.oasis.configuration.allowSameOrigin ) { sandboxAttributes.push('allow-same-origin'); } if( options && options.sandbox && options.sandbox.popups ) { sandboxAttributes.push('allow-popups'); } iframe.name = sandbox.options.url + '?uuid=' + UUID.generate(); iframe.sandbox = sandboxAttributes.join(' '); iframe.seamless = true; // rendering-specific code if (options.width) { iframe.width = options.width; } else if (options.height) { iframe.height = options.height; } // Error handling inside the iFrame iframe.errorHandler = function(event) { if(!event.data.sandboxException) {return;} try { // verify this message came from the expected sandbox; try/catch // because ie8 will disallow reading contentWindow in the case of // another sandbox's message if( event.source !== iframe.contentWindow ) {return;} } catch(e) { return; } sandbox.onerror( event.data.sandboxException ); }; addEventListener(window, 'message', iframe.errorHandler); verifySandbox( sandbox.oasis, sandbox.options.url ); iframe.src = sandbox.options.url; Logger.log('Initializing sandbox ' + iframe.name); // Promise that sandbox has loaded and capabilities connected at least once. // This does not mean that the sandbox will be loaded & connected in the // face of reconnects (eg pages that navigate) sandbox._waitForLoadDeferred().resolve(new RSVP.Promise( function(resolve, reject) { iframe.initializationHandler = function (event) { if( event.data !== sandbox.adapter.sandboxInitializedMessage ) {return;} try { // verify this message came from the expected sandbox; try/catch // because ie8 will disallow reading contentWindow in the case of // another sandbox's message if( event.source !== iframe.contentWindow ) {return;} } catch(e) { return; } removeEventListener(window, 'message', iframe.initializationHandler); sandbox.oasis.configuration.eventCallback(function () { Logger.log("container: iframe sandbox has initialized (capabilities connected)"); resolve(sandbox); }); }; addEventListener(window, 'message', iframe.initializationHandler); })); sandbox.el = iframe; iframe.oasisLoadHandler = function (event) { if( event.data !== sandbox.adapter.oasisLoadedMessage ) {return;} try { // verify this message came from the expected sandbox; try/catch // because ie8 will disallow reading contentWindow in the case of // another sandbox's message if( event.source !== iframe.contentWindow ) {return;} } catch(e) { return; } Logger.log("container: iframe sandbox has loaded Oasis"); if (verifyCurrentSandboxOrigin(sandbox, event)) { sandbox.createAndTransferCapabilities(); } if (sandbox.options.reconnect === "none") { removeEventListener(window, 'message', iframe.oasisLoadHandler); } }; addEventListener(window, 'message', iframe.oasisLoadHandler); }, startSandbox: function(sandbox) { var head = document.head || document.documentElement.getElementsByTagName('head')[0]; head.appendChild(sandbox.el); }, terminateSandbox: function(sandbox) { var el = sandbox.el; sandbox.terminated = true; if (el.loadHandler) { // no load handler for HTML sandboxes removeEventListener(el, 'load', el.loadHandler); } removeEventListener(window, 'message', el.initializationHandler); removeEventListener(window, 'message', el.oasisLoadHandler); if (el.parentNode) { Logger.log("Terminating sandbox ", sandbox.el.name); el.parentNode.removeChild(el); } sandbox.el = null; }, connectPorts: function(sandbox, ports) { var rawPorts = a_map.call(ports, function(port) { return port.port; }), message = this.createInitializationMessage(sandbox); if (sandbox.terminated) { return; } Window.postMessage(sandbox.el.contentWindow, message, '*', rawPorts); }, //------------------------------------------------------------------------- // Sandbox API connectSandbox: function(oasis) { return BaseAdapter.prototype.connectSandbox.call(this, window, oasis); }, oasisLoaded: function() { window.parent.postMessage(this.oasisLoadedMessage, '*', []); }, didConnect: function() { window.parent.postMessage(this.sandboxInitializedMessage, '*', []); }, name: function(sandbox) { return sandbox.el.name; } }); return IframeAdapter; }); define("oasis/inline_adapter", ["oasis/util","oasis/config","oasis/shims","oasis/xhr","rsvp","oasis/logger","oasis/base_adapter"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, RSVP, Logger, BaseAdapter) { "use strict"; var assert = __dependency1__.assert; var extend = __dependency1__.extend; var noop = __dependency1__.noop; var configuration = __dependency2__.configuration; var a_forEach = __dependency3__.a_forEach; var a_map = __dependency3__.a_map; var xhr = __dependency4__.xhr; /*global self, postMessage, importScripts */ var InlineAdapter = extend(BaseAdapter, { //------------------------------------------------------------------------- // Environment API initializeSandbox: function(sandbox) { sandbox.el = document.createElement('div'); var oasis = sandbox.sandboxedOasis = new Oasis(); sandbox.sandboxedOasis.sandbox = sandbox; RSVP.async(function () { sandbox.createAndTransferCapabilities(); }); }, startSandbox: function(sandbox) { var body = document.body || document.documentElement.getElementsByTagName('body')[0]; body.appendChild(sandbox.el); }, terminateSandbox: function(sandbox) { var el = sandbox.el; if (el.parentNode) { Logger.log("Terminating sandbox ", sandbox.el.name); el.parentNode.removeChild(el); } sandbox.el = null; }, connectPorts: function(sandbox, ports) { var rawPorts = a_map.call(ports, function(oasisPort){ return oasisPort.port; }), message = this.createInitializationMessage(sandbox), event = { data: message, ports: rawPorts }; // Normally `connectSandbox` is called in autoinitialization, but there // isn't a real sandbox here. this.connectSandbox(sandbox.sandboxedOasis, event); }, fetchResource: function (url, oasis) { var adapter = this; return xhr(url, { dataType: 'text' }, oasis).then(function (code) { return adapter.wrapResource(code); })['catch'](RSVP.rethrow); }, wrapResource: function (code) { return new Function("oasis", code); }, //------------------------------------------------------------------------- // Sandbox API connectSandbox: function(oasis, pseudoEvent) { return this.initializeOasisSandbox(pseudoEvent, oasis); }, oasisLoaded: noop, didConnect: function(oasis) { var adapter = this; return oasis.sandbox._waitForLoadDeferred().resolve(loadSandboxJS()['catch'](RSVP.rethrow)); function applySandboxJS(sandboxFn) { Logger.log("sandbox: inline sandbox initialized"); sandboxFn(oasis); return oasis.sandbox; } function loadSandboxJS() { return new RSVP.Promise(function (resolve, reject) { resolve(adapter.fetchResource(oasis.sandbox.options.url, oasis). then(applySandboxJS)); }); } }, }); return InlineAdapter; }); define("oasis/logger", [], function() { "use strict"; function Logger() { this.enabled = false; } Logger.prototype = { enable: function () { this.enabled = true; }, disable: function () { this.enabled = false; }, log: function () { if (logger.enabled) { if (typeof console !== 'undefined' && typeof console.log === 'function') { console.log.apply(console, arguments); } else if (typeof console !== 'undefined' && typeof console.log === 'object') { // Log in IE try { switch (arguments.length) { case 1: console.log(arguments[0]); break; case 2: console.log(arguments[0], arguments[1]); break; default: console.log(arguments[0], arguments[1], arguments[2]); } } catch(e) {} } } } }; var logger = new Logger(); return logger; }); define("oasis/message_channel", ["oasis/util","rsvp","exports"], function(__dependency1__, RSVP, __exports__) { "use strict"; var extend = __dependency1__.extend; var mustImplement = __dependency1__.mustImplement; /** OasisPort is an interface that adapters can use to implement ports. Ports are passed into the `initialize` method of services and consumers, and are available as `this.port` on services and consumers. Ports are the low-level API that can be used to communicate with the other side of a connection. In general, you will probably want to use the `events` and `requests` objects inside your service or consumer rather than manually listen for events and requests. @constructor @param {OasisPort} oasis @param {OasisPort} port */ function OasisPort(oasis, port) {} function getRequestId(oasis) { return oasis.oasisId + '-' + oasis.requestId++; } OasisPort.prototype = { /** This allows you to register an event handler for a particular event name. @param {String} eventName the name of the event @param {Function} callback the callback to call when the event occurs @param {any?} binding an optional value of `this` inside of the callback */ on: mustImplement('OasisPort', 'on'), /** Allows you to register an event handler that is called for all events that are sent to the port. */ all: mustImplement('OasisPort', 'all'), /** This allows you to unregister an event handler for an event name and callback. You should not pass in the optional binding. @param {String} eventName the name of the event @param {Function} callback a reference to the callback that was passed into `.on`. */ off: mustImplement('OasisPort', 'off'), /** This method sends an event to the other side of the connection. @param {String} eventName the name of the event @param {Structured?} data optional data to pass along with the event */ send: mustImplement('OasisPort', 'send'), /** @private Adapters should implement this to start receiving messages from the other side of the connection. It is up to the adapter to make sure that no messages are dropped if they are sent before `start` is called. */ start: mustImplement('OasisPort', 'start'), /** @private Adapters should implement this to stop receiving messages from the other side of the connection. */ close: mustImplement('OasisPort', 'close'), /** This method sends a request to the other side of the connection. @param {String} requestName the name of the request @return {Promise} a promise that will be resolved with the value provided by the other side of the connection, or rejected if the other side indicates retrieving the value resulted in an error. The fulfillment value must be structured data. */ request: function(eventName) { var oasis = this.oasis; var port = this; var args = [].slice.call(arguments, 1); return new RSVP.Promise(function (resolve, reject) { var requestId = getRequestId(oasis); var clearObservers = function () { port.off('@response:' + eventName, observer); port.off('@errorResponse:' + eventName, errorObserver); }; var observer = function(event) { if (event.requestId === requestId) { clearObservers(); resolve(event.data); } }; var errorObserver = function (event) { if (event.requestId === requestId) { clearObservers(); reject(event.data); } }; port.on('@response:' + eventName, observer, port); port.on('@errorResponse:' + eventName, errorObserver, port); port.send('@request:' + eventName, { requestId: requestId, args: args }); }); }, /** This method registers a callback to be called when a request is made by the other side of the connection. The callback will be called with any arguments passed in the request. It may either return a value directly, or return a promise if the value must be retrieved asynchronously. Examples: // This completes the request immediately. service.onRequest('name', function () { return 'David'; }); // This completely the request asynchronously. service.onRequest('name', function () { return new Oasis.RSVP.Promise(function (resolve, reject) { setTimeout( function() { resolve('David'); }, 200); }); }); @param {String} requestName the name of the request @param {Function} callback the callback to be called when a request is made. @param {any?} binding the value of `this` in the callback */ onRequest: function(eventName, callback, binding) { var self = this; this.on('@request:' + eventName, function(data) { var requestId = data.requestId, args = data.args, getResponse = new RSVP.Promise(function (resolve, reject) { var value = callback.apply(binding, data.args); if (undefined !== value) { resolve(value); } else { reject("@request:" + eventName + " [" + data.requestId + "] did not return a value. If you want to return a literal `undefined` return `RSVP.resolve(undefined)`"); } }); getResponse.then(function (value) { self.send('@response:' + eventName, { requestId: requestId, data: value }); }, function (error) { var value = error; if (error instanceof Error) { value = { message: error.message, stack: error.stack }; } self.send('@errorResponse:' + eventName, { requestId: requestId, data: value }); }); }); } }; function OasisMessageChannel(oasis) {} OasisMessageChannel.prototype = { start: mustImplement('OasisMessageChannel', 'start') }; var PostMessageMessageChannel = extend(OasisMessageChannel, { initialize: function(oasis) { this.channel = new MessageChannel(); this.port1 = new PostMessagePort(oasis, this.channel.port1); this.port2 = new PostMessagePort(oasis, this.channel.port2); }, start: function() { this.port1.start(); this.port2.start(); }, destroy: function() { this.port1.close(); this.port2.close(); delete this.port1; delete this.port2; delete this.channel; } }); var PostMessagePort = extend(OasisPort, { initialize: function(oasis, port) { this.oasis = oasis; this.port = port; this._callbacks = []; }, on: function(eventName, callback, binding) { var oasis = this.oasis; function wrappedCallback(event) { if (event.data.type === eventName) { oasis.configuration.eventCallback(function () { return callback.call(binding, event.data.data); }); } } this._callbacks.push([callback, wrappedCallback]); this.port.addEventListener('message', wrappedCallback); }, all: function(callback, binding) { var oasis = this.oasis; function wrappedCallback(event) { oasis.configuration.eventCallback(function () { callback.call(binding, event.data.type, event.data.data); }); } this.port.addEventListener('message', wrappedCallback); }, off: function(eventName, callback) { var foundCallback; for (var i=0, l=this._callbacks.length; i<l; i++) { foundCallback = this._callbacks[i]; if (foundCallback[0] === callback) { this.port.removeEventListener('message', foundCallback[1]); } } }, send: function(eventName, data) { this.port.postMessage({ type: eventName, data: data }); }, start: function() { this.port.start(); }, close: function() { var foundCallback; for (var i=0, l=this._callbacks.length; i<l; i++) { foundCallback = this._callbacks[i]; this.port.removeEventListener('message', foundCallback[1]); } this._callbacks = []; this.port.close(); } }); __exports__.OasisPort = OasisPort; __exports__.PostMessageMessageChannel = PostMessageMessageChannel; __exports__.PostMessagePort = PostMessagePort; }); define("oasis/sandbox", ["oasis/util","oasis/shims","oasis/message_channel","rsvp","oasis/logger"], function(__dependency1__, __dependency2__, __dependency3__, RSVP, Logger) { "use strict"; var assert = __dependency1__.assert; var uniq = __dependency1__.uniq; var reverseMerge = __dependency1__.reverseMerge; var a_forEach = __dependency2__.a_forEach; var a_reduce = __dependency2__.a_reduce; var a_filter = __dependency2__.a_filter; var OasisPort = __dependency3__.OasisPort; var OasisSandbox = function(oasis, options) { options = reverseMerge(options || {}, { reconnect: oasis.configuration.reconnect }); var reconnect = options.reconnect; assert( reconnect === "none" || reconnect === "verify" || reconnect === "any", "`reconnect` must be one of 'none', 'verify' or 'any'. '" + reconnect + "' is invalid."); this.connections = {}; this.wiretaps = []; this.oasis = oasis; // Generic capabilities code var pkg = oasis.packages[options.url]; var capabilities = options.capabilities; if (!capabilities) { assert(pkg, "You are trying to create a sandbox from an unregistered URL without providing capabilities. Please use Oasis.register to register your package or pass a list of capabilities to createSandbox."); capabilities = pkg.capabilities; } pkg = pkg || {}; this.adapter = options.adapter || Oasis.adapters.iframe; this._capabilitiesToConnect = this._filterCapabilities(capabilities); this.envPortDefereds = {}; this.sandboxPortDefereds = {}; this.channels = {}; this.capabilities = {}; this.options = options; this.firstLoad = true; var sandbox = this; this.promisePorts(); this.adapter.initializeSandbox(this); }; OasisSandbox.prototype = { waitForLoad: function () { return this._waitForLoadDeferred().promise; }, wiretap: function(callback) { this.wiretaps.push(callback); }, connect: function(capability) { var portPromise = this.envPortDefereds[capability].promise; assert(portPromise, "Connect was called on '" + capability + "' but no such capability was registered."); return portPromise; }, createAndTransferCapabilities: function () { if (!this.firstLoad) { this.promisePorts(); } this.createChannels(); this.connectPorts(); // subsequent calls to `createAndTransferCapabilities` requires new port promises this.firstLoad = false; }, promisePorts: function () { a_forEach.call(this._capabilitiesToConnect, function(capability) { this.envPortDefereds[capability] = RSVP.defer(); this.sandboxPortDefereds[capability] = RSVP.defer(); }, this); }, createChannels: function () { var sandbox = this, services = this.options.services || {}, channels = this.channels; a_forEach.call(this._capabilitiesToConnect, function (capability) { Logger.log("container: Will create port for '" + capability + "'"); var service = services[capability], channel, port; // If an existing port is provided, just // pass it along to the new sandbox. // TODO: This should probably be an OasisPort if possible if (service instanceof OasisPort) { port = this.adapter.proxyPort(this, service); this.capabilities[capability] = service; } else { channel = channels[capability] = this.adapter.createChannel(sandbox.oasis); var environmentPort = this.adapter.environmentPort(this, channel), sandboxPort = this.adapter.sandboxPort(this, channel); Logger.log("container: Wiretapping '" + capability + "'"); environmentPort.all(function(eventName, data) { a_forEach.call(this.wiretaps, function(wiretap) { wiretap(capability, { type: eventName, data: data, direction: 'received' }); }); }, this); a_forEach.call(this.wiretaps, function(wiretap) { var originalSend = environmentPort.send; environmentPort.send = function(eventName, data) { wiretap(capability, { type: eventName, data: data, direction: 'sent' }); originalSend.apply(environmentPort, arguments); }; }); if (service) { Logger.log("container: Creating service for '" + capability + "'"); /*jshint newcap:false*/ // Generic service = new service(environmentPort, this); service.initialize(environmentPort, capability); sandbox.oasis.services.push(service); this.capabilities[capability] = service; } // Law of Demeter violation port = sandboxPort; this.envPortDefereds[capability].resolve(environmentPort); } Logger.log("container: Port created for '" + capability + "'"); this.sandboxPortDefereds[capability].resolve(port); }, this); }, destroyChannels: function() { for( var prop in this.channels ) { this.channels[prop].destroy(); delete this.channels[prop]; } this.channels = []; }, connectPorts: function () { var sandbox = this; var allSandboxPortPromises = a_reduce.call(this._capabilitiesToConnect, function (accumulator, capability) { return accumulator.concat(sandbox.sandboxPortDefereds[capability].promise); }, []); RSVP.all(allSandboxPortPromises).then(function (ports) { Logger.log("container: All " + ports.length + " ports created. Transferring them."); sandbox.adapter.connectPorts(sandbox, ports); })['catch'](RSVP.rethrow); }, start: function(options) { this.adapter.startSandbox(this, options); }, terminate: function() { var sandbox = this, channel, environmentPort; if( this.isTerminated ) { return; } this.isTerminated = true; this.adapter.terminateSandbox(this); this.destroyChannels(); for( var index=0 ; index<sandbox.oasis.services.length ; index++) { sandbox.oasis.services[index].destroy(); delete sandbox.oasis.services[index]; } sandbox.oasis.services = []; }, onerror: function(error) { throw error; }, name: function() { return this.adapter.name(this); }, // Oasis internal _filterCapabilities: function(capabilities) { return uniq.call(this.adapter.filterCapabilities(capabilities)); }, _waitForLoadDeferred: function () { if (!this._loadDeferred) { // the adapter will resolve this this._loadDeferred = RSVP.defer(); } return this._loadDeferred; } }; return OasisSandbox; }); define("oasis/sandbox_init", [], function() { "use strict"; function autoInitializeSandbox () { if (typeof window !== 'undefined') { if (/PhantomJS/.test(navigator.userAgent)) { // We don't support phantomjs for several reasons, including // - window.constructor vs Window // - postMessage must not have ports (but recall in IE postMessage must // have ports) // - because of the above we need to polyfill, but we fail to do so // because we see MessageChannel in global object // - we erroneously try to decode the oasis load message; alternatively // we should just encode the init message // - all the things we haven't noticed yet return; } if (window.parent && window.parent !== window) { Oasis.adapters.iframe.connectSandbox(this); } } else { Oasis.adapters.webworker.connectSandbox(this); } } return autoInitializeSandbox; }); define("oasis/service", ["oasis/shims"], function(__dependency1__) { "use strict"; var o_create = __dependency1__.o_create; /** This is a base class that services and consumers can subclass to easily implement a number of events and requests at once. Example: var MetadataService = Oasis.Service.extend({ initialize: function() { this.send('data', this.sandbox.data); }, events: { changed: function(data) { this.sandbox.data = data; } }, requests: { valueForProperty: function(name, promise) { promise.resolve(this.sandbox.data[name]); } } }); In the above example, the metadata service implements the Service API using `initialize`, `events` and `requests`. Both services (implemented in the containing environment) and consumers (implemented in the sandbox) use the same API for registering events and requests. In the containing environment, a service is registered in the `createSandbox` method. In the sandbox, a consumer is registered using `Oasis.connect`. ### `initialize` Oasis calls the `initialize` method once the other side of the connection has initialized the connection. This method is useful to pass initial data back to the other side of the connection. You can also set up events or requests manually, but you will usually want to use the `events` and `requests` sections for events and requests. ### `events` The `events` object is a list of event names and associated callbacks. Oasis will automatically set up listeners for each named event, and trigger the callback with the data provided by the other side of the connection. ### `requests` The `requests` object is a list of request names and associated callbacks. Oasis will automatically set up listeners for requests made by the other side of the connection, and trigger the callback with the request information as well as a promise that you should use to fulfill the request. Once you have the information requested, you should call `promise.resolve` with the response data. @constructor @param {OasisPort} port @param {OasisSandbox} sandbox in the containing environment, the OasisSandbox that this service is connected to. */ function Service (port, sandbox) { var service = this, prop, callback; this.sandbox = sandbox; this.port = port; function xform(callback) { return function() { return callback.apply(service, arguments); }; } for (prop in this.events) { callback = this.events[prop]; port.on(prop, xform(callback)); } for (prop in this.requests) { callback = this.requests[prop]; port.onRequest(prop, xform(callback)); } } Service.prototype = { /** This hook is called when the connection is established. When `initialize` is called, it is safe to register listeners and send data to the other side. The implementation of Oasis makes it impossible for messages to get dropped on the floor due to timing issues. @param {OasisPort} port the port to the other side of the connection @param {String} name the name of the service */ initialize: function() {}, /** This hooks is called when an attempt is made to connect to a capability the environment does not provide. */ error: function() {}, /** This hook is called when the connection is stopped. When `destroy` is called, it is safe to unregister listeners. */ destroy: function() {}, /** This method can be used to send events to the other side of the connection. @param {String} eventName the name of the event to send to the other side of the connection @param {Structured} data an additional piece of data to include as the data for the event. */ send: function() { return this.port.send.apply(this.port, arguments); }, /** This method can be used to request data from the other side of the connection. @param {String} requestName the name of the request to send to the other side of the connection. @return {Promise} a promise that will be resolved by the other side of the connection. Use `.then` to wait for the resolution. */ request: function() { return this.port.request.apply(this.port, arguments); } }; Service.extend = function extend(object) { var superConstructor = this; function Service() { if (Service.prototype.init) { Service.prototype.init.call(this); } superConstructor.apply(this, arguments); } Service.extend = extend; var ServiceProto = Service.prototype = o_create(this.prototype); for (var prop in object) { ServiceProto[prop] = object[prop]; } return Service; }; return Service; }); define("oasis/shims", ["exports"], function(__exports__) { "use strict"; var K = function() {}; function o_create(obj, props) { K.prototype = obj; obj = new K(); if (props) { K.prototype = obj; for (var prop in props) { K.prototype[prop] = props[prop].value; } obj = new K(); } K.prototype = null; return obj; } // If it turns out we need a better polyfill we can grab mozilla's at: // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.removeEventListener?redirectlocale=en-US&redirectslug=DOM%2FEventTarget.removeEventListener#Polyfill_to_support_older_browsers function addEventListener(receiver, eventName, fn) { if (receiver.addEventListener) { return receiver.addEventListener(eventName, fn); } else if (receiver.attachEvent) { return receiver.attachEvent('on' + eventName, fn); } } function removeEventListener(receiver, eventName, fn) { if (receiver.removeEventListener) { return receiver.removeEventListener(eventName, fn); } else if (receiver.detachEvent) { return receiver.detachEvent('on' + eventName, fn); } } function isNativeFunc(func) { // This should probably work in all browsers likely to have ES5 array methods return func && Function.prototype.toString.call(func).indexOf('[native code]') > -1; } var a_forEach = isNativeFunc(Array.prototype.forEach) ? Array.prototype.forEach : function(fun /*, thisp */) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { fun.call(thisp, t[i], i, t); } } }; var a_reduce = isNativeFunc(Array.prototype.reduce) ? Array.prototype.reduce : function(callback, opt_initialValue){ if (null === this || 'undefined' === typeof this) { // At the moment all modern browsers, that support strict mode, have // native implementation of Array.prototype.reduce. For instance, IE8 // does not support strict mode, so this check is actually useless. throw new TypeError( 'Array.prototype.reduce called on null or undefined'); } if ('function' !== typeof callback) { throw new TypeError(callback + ' is not a function'); } var index = 0, length = this.length >>> 0, value, isValueSet = false; if (1 < arguments.length) { value = opt_initialValue; isValueSet = true; } for ( ; length > index; ++index) { if (!this.hasOwnProperty(index)) continue; if (isValueSet) { value = callback(value, this[index], index, this); } else { value = this[index]; isValueSet = true; } } if (!isValueSet) { throw new TypeError('Reduce of empty array with no initial value'); } return value; }; var a_map = isNativeFunc(Array.prototype.map) ? Array.prototype.map : function(callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (thisArg) { T = thisArg; } // 6. Let A be a new array created as if by the expression new Array(len) where Array is // the standard built-in constructor with that name and len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while(k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[ k ]; // ii. Let mappedValue be the result of calling the Call internal method of callback // with T as the this value and argument list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true}, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true }); // For best browser support, use the following: A[ k ] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; var a_indexOf = isNativeFunc(Array.prototype.indexOf) ? Array.prototype.indexOf : function (searchElement /*, fromIndex */ ) { /* jshint eqeqeq:false */ "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; var a_filter = isNativeFunc(Array.prototype.filter) ? Array.prototype.filter : function(fun /*, thisp*/) { 'use strict'; if (!this) { throw new TypeError(); } var objects = Object(this); var len = objects.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisp = arguments[1]; for (var i in objects) { if (objects.hasOwnProperty(i)) { if (fun.call(thisp, objects[i], i, objects)) { res.push(objects[i]); } } } return res; }; __exports__.o_create = o_create; __exports__.addEventListener = addEventListener; __exports__.removeEventListener = removeEventListener; __exports__.a_forEach = a_forEach; __exports__.a_reduce = a_reduce; __exports__.a_map = a_map; __exports__.a_indexOf = a_indexOf; __exports__.a_filter = a_filter; }); define("oasis/util", ["oasis/shims","exports"], function(__dependency1__, __exports__) { "use strict"; var o_create = __dependency1__.o_create; var a_filter = __dependency1__.a_filter; function assert(assertion, string) { if (!assertion) { throw new Error(string); } } function noop() { } function mustImplement(className, name) { return function() { throw new Error("Subclasses of " + className + " must implement " + name); }; } function extend(parent, object) { function OasisObject() { parent.apply(this, arguments); if (this.initialize) { this.initialize.apply(this, arguments); } } OasisObject.prototype = o_create(parent.prototype); for (var prop in object) { if (!object.hasOwnProperty(prop)) { continue; } OasisObject.prototype[prop] = object[prop]; } return OasisObject; } function delegate(delegateeProperty, delegatedMethod) { return function () { var delegatee = this[delegateeProperty]; return delegatee[delegatedMethod].apply(delegatee, arguments); }; } function uniq() { var seen = {}; return a_filter.call(this, function (item) { var _seen = !seen.hasOwnProperty(item); seen[item] = true; return _seen; }); } function reverseMerge(a, b) { for (var prop in b) { if (!b.hasOwnProperty(prop)) { continue; } if (! (prop in a)) { a[prop] = b[prop]; } } return a; } __exports__.assert = assert; __exports__.noop = noop; __exports__.mustImplement = mustImplement; __exports__.extend = extend; __exports__.delegate = delegate; __exports__.uniq = uniq; __exports__.reverseMerge = reverseMerge; }); define("oasis/version", [], function() { "use strict"; return '0.4.0'; }); define("oasis/webworker_adapter", ["oasis/util","oasis/shims","rsvp","oasis/logger","oasis/base_adapter"], function(__dependency1__, __dependency2__, RSVP, Logger, BaseAdapter) { "use strict"; var assert = __dependency1__.assert; var extend = __dependency1__.extend; var a_forEach = __dependency2__.a_forEach; var addEventListener = __dependency2__.addEventListener; var removeEventListener = __dependency2__.removeEventListener; /*global self, postMessage, importScripts, UUID */ var WebworkerAdapter = extend(BaseAdapter, { type: 'js', //------------------------------------------------------------------------- // Environment API initializeSandbox: function(sandbox) { var worker = new Worker(sandbox.options.url); worker.name = sandbox.options.url + '?uuid=' + UUID.generate(); sandbox.worker = worker; // Error handling inside the worker worker.errorHandler = function(event) { if(!event.data.sandboxException) {return;} sandbox.onerror( event.data.sandboxException ); }; addEventListener(worker, 'message', worker.errorHandler); sandbox._waitForLoadDeferred().resolve(new RSVP.Promise( function(resolve, reject) { worker.initializationHandler = function (event) { sandbox.oasis.configuration.eventCallback(function () { if( event.data !== sandbox.adapter.sandboxInitializedMessage ) {return;} removeEventListener(worker, 'message', worker.initializationHandler); Logger.log("worker sandbox initialized"); resolve(sandbox); }); }; addEventListener(worker, 'message', worker.initializationHandler); })); worker.loadHandler = function (event) { sandbox.oasis.configuration.eventCallback(function () { if( event.data !== sandbox.adapter.oasisLoadedMessage ) {return;} removeEventListener(worker, 'message', worker.loadHandler); Logger.log("worker sandbox initialized"); sandbox.createAndTransferCapabilities(); }); }; addEventListener(worker, 'message', worker.loadHandler); }, startSandbox: function(sandbox) { }, terminateSandbox: function(sandbox) { var worker = sandbox.worker; removeEventListener(worker, 'message', worker.loadHandler); removeEventListener(worker, 'message', worker.initializationHandler); sandbox.worker.terminate(); }, connectPorts: function(sandbox, ports) { var rawPorts = ports.map(function(port) { return port.port; }), message = this.createInitializationMessage(sandbox); Worker.postMessage(sandbox.worker, message, rawPorts); }, connectSandbox: function(oasis) { return BaseAdapter.prototype.connectSandbox.call(this, self, oasis); }, //------------------------------------------------------------------------- // Sandbox API name: function(sandbox) { return sandbox.worker.name; }, oasisLoaded: function() { postMessage(this.oasisLoadedMessage, []); }, didConnect: function() { postMessage(this.sandboxInitializedMessage, []); } }); return WebworkerAdapter; }); define("oasis/xhr", ["oasis/util","rsvp","exports"], function(__dependency1__, RSVP, __exports__) { "use strict"; var noop = __dependency1__.noop; /*global XDomainRequest */ var a_slice = Array.prototype.slice; function acceptsHeader(options) { var dataType = options.dataType; if (dataType && accepts[dataType]) { return accepts[dataType]; } return accepts['*']; } function xhrSetRequestHeader(xhr, options) { xhr.setRequestHeader("Accepts", acceptsHeader(options)); } function xhrGetLoadStatus(xhr) { return xhr.status; } function xdrGetLoadStatus() { return 200; } var NONE = {}; function trigger(event, oasis) { if (!oasis) { return; } var args = a_slice.call(arguments, 2); args.unshift(event); oasis.trigger.apply(oasis, args); } var accepts = { "*": "*/*", text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }; var XHR, setRequestHeader, getLoadStatus, send; try { if ('withCredentials' in new XMLHttpRequest()) { XHR = XMLHttpRequest; setRequestHeader = xhrSetRequestHeader; getLoadStatus = xhrGetLoadStatus; } else if (typeof XDomainRequest !== 'undefined') { XHR = XDomainRequest; setRequestHeader = noop; getLoadStatus = xdrGetLoadStatus; } } catch( exception ) { if (typeof XDomainRequest !== 'undefined') { XHR = XDomainRequest; setRequestHeader = noop; getLoadStatus = xdrGetLoadStatus; } } // else inline adapter with cross-domain cards is not going to work function xhr(url, options, oasis) { if (!oasis && this instanceof Oasis) { oasis = this; } if (!options) { options = NONE; } return new RSVP.Promise(function(resolve, reject){ var xhr = new XHR(); xhr.open("get", url, true); setRequestHeader(xhr, options); if (options.timeout) { xhr.timeout = options.timeout; } xhr.onload = function () { trigger('xhr.load', oasis, url, options, xhr); var status = getLoadStatus(xhr); if (status >= 200 && status < 300) { resolve(xhr.responseText); } else { reject(xhr); } }; xhr.onprogress = noop; xhr.ontimeout = function () { trigger('xhr.timeout', oasis, url, options, xhr); reject(xhr); }; xhr.onerror = function () { trigger('xhr.error', oasis, url, options, xhr); reject(xhr); }; trigger('xhr.send', oasis, url, options, xhr); xhr.send(); }); } __exports__.xhr = xhr; });
{ "pile_set_name": "Github" }
// Copyright 2012 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. // Tick Processor's code flow. function processArguments(args) { var processor = new ArgumentsProcessor(args); if (processor.parse()) { return processor.result(); } else { processor.printUsageAndExit(); } } function initSourceMapSupport() { // Pull dev tools source maps into our name space. SourceMap = WebInspector.SourceMap; // Overwrite the load function to load scripts synchronously. SourceMap.load = function(sourceMapURL) { var content = readFile(sourceMapURL); var sourceMapObject = (JSON.parse(content)); return new SourceMap(sourceMapURL, sourceMapObject); }; } var entriesProviders = { 'unix': UnixCppEntriesProvider, 'windows': WindowsCppEntriesProvider, 'mac': MacCppEntriesProvider }; var params = processArguments(arguments); var sourceMap = null; if (params.sourceMap) { initSourceMapSupport(); sourceMap = SourceMap.load(params.sourceMap); } var tickProcessor = new TickProcessor( new (entriesProviders[params.platform])(params.nm, params.objdump, params.targetRootFS, params.apkEmbeddedLibrary), params.separateIc, params.separateBytecodes, params.separateBuiltins, params.separateStubs, params.callGraphSize, params.ignoreUnknown, params.stateFilter, params.distortion, params.range, sourceMap, params.timedRange, params.pairwiseTimedRange, params.onlySummary, params.runtimeTimerFilter, params.preprocessJson); tickProcessor.processLogFile(params.logFileName); tickProcessor.printStatistics();
{ "pile_set_name": "Github" }
// // NSDate+Day.m // NSDate+Calendar // // Created by Belkevich Alexey on 3/16/12. // Copyright (c) 2012 okolodev. All rights reserved. // #import "NSDate+Day.h" #import "NSDate+Components.h" @implementation NSDate (Day) - (NSInteger)day { return [self dateComponentsDate].day; } - (NSUInteger)daysInMonth { NSRange range = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self]; return range.length; } - (NSUInteger)dayInYear { return [[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:self]; } - (NSDate *)dateToday { NSDateComponents *components = [self dateComponentsDate]; return [[NSCalendar currentCalendar] dateFromComponents:components]; } - (NSDate *)dateYesterday { NSDateComponents *components = [self dateComponentsDate]; components.day--; return [[NSCalendar currentCalendar] dateFromComponents:components]; } - (NSDate *)dateTomorrow { NSDateComponents *components = [self dateComponentsDate]; components.day++; return [[NSCalendar currentCalendar] dateFromComponents:components]; } - (NSDate *)dateBySettingDay:(NSInteger)day { NSDateComponents *components = [self dateComponentsDateTime]; components.day = day; return [[NSCalendar currentCalendar] dateFromComponents:components]; } - (NSDate *)dateByAddingDays:(NSInteger)days { NSDateComponents *components = [[NSDateComponents alloc] init]; components.day = days; return [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self options:0]; } @end
{ "pile_set_name": "Github" }
package metrics import ( "fmt" "net/url" ) // The MetricSink interface is used to transmit metrics information // to an external system type MetricSink interface { // A Gauge should retain the last value it is set to SetGauge(key []string, val float32) SetGaugeWithLabels(key []string, val float32, labels []Label) // Should emit a Key/Value pair for each call EmitKey(key []string, val float32) // Counters should accumulate values IncrCounter(key []string, val float32) IncrCounterWithLabels(key []string, val float32, labels []Label) // Samples are for timing information, where quantiles are used AddSample(key []string, val float32) AddSampleWithLabels(key []string, val float32, labels []Label) } // BlackholeSink is used to just blackhole messages type BlackholeSink struct{} func (*BlackholeSink) SetGauge(key []string, val float32) {} func (*BlackholeSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {} func (*BlackholeSink) EmitKey(key []string, val float32) {} func (*BlackholeSink) IncrCounter(key []string, val float32) {} func (*BlackholeSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {} func (*BlackholeSink) AddSample(key []string, val float32) {} func (*BlackholeSink) AddSampleWithLabels(key []string, val float32, labels []Label) {} // FanoutSink is used to sink to fanout values to multiple sinks type FanoutSink []MetricSink func (fh FanoutSink) SetGauge(key []string, val float32) { fh.SetGaugeWithLabels(key, val, nil) } func (fh FanoutSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { for _, s := range fh { s.SetGaugeWithLabels(key, val, labels) } } func (fh FanoutSink) EmitKey(key []string, val float32) { for _, s := range fh { s.EmitKey(key, val) } } func (fh FanoutSink) IncrCounter(key []string, val float32) { fh.IncrCounterWithLabels(key, val, nil) } func (fh FanoutSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { for _, s := range fh { s.IncrCounterWithLabels(key, val, labels) } } func (fh FanoutSink) AddSample(key []string, val float32) { fh.AddSampleWithLabels(key, val, nil) } func (fh FanoutSink) AddSampleWithLabels(key []string, val float32, labels []Label) { for _, s := range fh { s.AddSampleWithLabels(key, val, labels) } } // sinkURLFactoryFunc is an generic interface around the *SinkFromURL() function provided // by each sink type type sinkURLFactoryFunc func(*url.URL) (MetricSink, error) // sinkRegistry supports the generic NewMetricSink function by mapping URL // schemes to metric sink factory functions var sinkRegistry = map[string]sinkURLFactoryFunc{ "statsd": NewStatsdSinkFromURL, "statsite": NewStatsiteSinkFromURL, "inmem": NewInmemSinkFromURL, } // NewMetricSinkFromURL allows a generic URL input to configure any of the // supported sinks. The scheme of the URL identifies the type of the sink, the // and query parameters are used to set options. // // "statsd://" - Initializes a StatsdSink. The host and port are passed through // as the "addr" of the sink // // "statsite://" - Initializes a StatsiteSink. The host and port become the // "addr" of the sink // // "inmem://" - Initializes an InmemSink. The host and port are ignored. The // "interval" and "duration" query parameters must be specified with valid // durations, see NewInmemSink for details. func NewMetricSinkFromURL(urlStr string) (MetricSink, error) { u, err := url.Parse(urlStr) if err != nil { return nil, err } sinkURLFactoryFunc := sinkRegistry[u.Scheme] if sinkURLFactoryFunc == nil { return nil, fmt.Errorf( "cannot create metric sink, unrecognized sink name: %q", u.Scheme) } return sinkURLFactoryFunc(u) }
{ "pile_set_name": "Github" }
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.weex.http; import java.util.HashMap; import java.util.Map; /** * Created by sospartan on 5/26/16. */ public class Status { public static final String UNKNOWN_STATUS = "unknown status"; public static final String ERR_INVALID_REQUEST = "ERR_INVALID_REQUEST"; public static final String ERR_CONNECT_FAILED = "ERR_CONNECT_FAILED"; private static Map<String,String> statusMap = new HashMap<>(); static { statusMap.put("100","Continue"); statusMap.put("101","Switching Protocol"); statusMap.put("200","OK"); statusMap.put("201","Created"); statusMap.put("202","Accepted"); statusMap.put("203","Non-Authoritative Information"); statusMap.put("204","No Content"); statusMap.put("205","Reset Content"); statusMap.put("206","Partial Content"); statusMap.put("300","Multiple Choice"); statusMap.put("301","Moved Permanently"); statusMap.put("302","Found"); statusMap.put("303","See Other"); statusMap.put("304","Not Modified"); statusMap.put("305","Use Proxy"); statusMap.put("306","unused"); statusMap.put("307","Temporary Redirect"); statusMap.put("308","Permanent Redirect"); statusMap.put("400","Bad Request"); statusMap.put("401","Unauthorized"); statusMap.put("402","Payment Required"); statusMap.put("403","Forbidden"); statusMap.put("404","Not Found"); statusMap.put("405","Method Not Allowed"); statusMap.put("406","Not Acceptable"); statusMap.put("407","Proxy Authentication Required"); statusMap.put("408","Request Timeout"); statusMap.put("409","Conflict"); statusMap.put("410","Gone"); statusMap.put("411","Length Required"); statusMap.put("412","Precondition Failed"); statusMap.put("413","Payload Too Large"); statusMap.put("414","URI Too Long"); statusMap.put("415","Unsupported Media Type"); statusMap.put("416","Requested Range Not Satisfiable"); statusMap.put("417","Expectation Failed"); statusMap.put("418","I'm a teapot"); statusMap.put("421","Misdirected Request"); statusMap.put("426","Upgrade Required"); statusMap.put("428","Precondition Required"); statusMap.put("429","Too Many Requests"); statusMap.put("431","Request Header Fields Too Large"); statusMap.put("500","Internal Server Error"); statusMap.put("501","Not Implemented"); statusMap.put("502","Bad Gateway"); statusMap.put("503","Service Unavailable"); statusMap.put("504","Gateway Timeout"); statusMap.put("505","HTTP Version Not Supported"); statusMap.put("506","Variant Also Negotiates"); statusMap.put("507","Variant Also Negotiates"); statusMap.put("511","Network Authentication Required"); } public static String getStatusText(String code){ if(!statusMap.containsKey(code)) return UNKNOWN_STATUS; return statusMap.get(code); } }
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/codecommit/CodeCommit_EXPORTS.h> #include <aws/codecommit/model/ObjectTypeEnum.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace CodeCommit { namespace Model { /** * <p>Information about the type of an object in a merge operation.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/ObjectTypes">AWS * API Reference</a></p> */ class AWS_CODECOMMIT_API ObjectTypes { public: ObjectTypes(); ObjectTypes(Aws::Utils::Json::JsonView jsonValue); ObjectTypes& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The type of the object in the source branch.</p> */ inline const ObjectTypeEnum& GetSource() const{ return m_source; } /** * <p>The type of the object in the source branch.</p> */ inline bool SourceHasBeenSet() const { return m_sourceHasBeenSet; } /** * <p>The type of the object in the source branch.</p> */ inline void SetSource(const ObjectTypeEnum& value) { m_sourceHasBeenSet = true; m_source = value; } /** * <p>The type of the object in the source branch.</p> */ inline void SetSource(ObjectTypeEnum&& value) { m_sourceHasBeenSet = true; m_source = std::move(value); } /** * <p>The type of the object in the source branch.</p> */ inline ObjectTypes& WithSource(const ObjectTypeEnum& value) { SetSource(value); return *this;} /** * <p>The type of the object in the source branch.</p> */ inline ObjectTypes& WithSource(ObjectTypeEnum&& value) { SetSource(std::move(value)); return *this;} /** * <p>The type of the object in the destination branch.</p> */ inline const ObjectTypeEnum& GetDestination() const{ return m_destination; } /** * <p>The type of the object in the destination branch.</p> */ inline bool DestinationHasBeenSet() const { return m_destinationHasBeenSet; } /** * <p>The type of the object in the destination branch.</p> */ inline void SetDestination(const ObjectTypeEnum& value) { m_destinationHasBeenSet = true; m_destination = value; } /** * <p>The type of the object in the destination branch.</p> */ inline void SetDestination(ObjectTypeEnum&& value) { m_destinationHasBeenSet = true; m_destination = std::move(value); } /** * <p>The type of the object in the destination branch.</p> */ inline ObjectTypes& WithDestination(const ObjectTypeEnum& value) { SetDestination(value); return *this;} /** * <p>The type of the object in the destination branch.</p> */ inline ObjectTypes& WithDestination(ObjectTypeEnum&& value) { SetDestination(std::move(value)); return *this;} /** * <p>The type of the object in the base commit of the merge.</p> */ inline const ObjectTypeEnum& GetBase() const{ return m_base; } /** * <p>The type of the object in the base commit of the merge.</p> */ inline bool BaseHasBeenSet() const { return m_baseHasBeenSet; } /** * <p>The type of the object in the base commit of the merge.</p> */ inline void SetBase(const ObjectTypeEnum& value) { m_baseHasBeenSet = true; m_base = value; } /** * <p>The type of the object in the base commit of the merge.</p> */ inline void SetBase(ObjectTypeEnum&& value) { m_baseHasBeenSet = true; m_base = std::move(value); } /** * <p>The type of the object in the base commit of the merge.</p> */ inline ObjectTypes& WithBase(const ObjectTypeEnum& value) { SetBase(value); return *this;} /** * <p>The type of the object in the base commit of the merge.</p> */ inline ObjectTypes& WithBase(ObjectTypeEnum&& value) { SetBase(std::move(value)); return *this;} private: ObjectTypeEnum m_source; bool m_sourceHasBeenSet; ObjectTypeEnum m_destination; bool m_destinationHasBeenSet; ObjectTypeEnum m_base; bool m_baseHasBeenSet; }; } // namespace Model } // namespace CodeCommit } // namespace Aws
{ "pile_set_name": "Github" }
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = ['FBResNet', #'fbresnet18', 'fbresnet34', 'fbresnet50', 'fbresnet101', 'fbresnet152'] pretrained_settings = { 'fbresnet152': { 'imagenet': { 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/fbresnet152-2e20f6b4.pth', 'input_space': 'RGB', 'input_size': [3, 224, 224], 'input_range': [0, 1], 'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225], 'num_classes': 1000 } } } def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=True) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=True) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=True) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class FBResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 # Special attributs self.input_space = None self.input_size = (299, 299, 3) self.mean = None self.std = None super(FBResNet, self).__init__() # Modules self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=True) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AvgPool2d(7) self.last_linear = nn.Linear(512 * block.expansion, num_classes) 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_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=True), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def features(self, input): x = self.conv1(input) self.conv1_input = x.clone() x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) return x def logits(self, features): x = self.avgpool(features) x = x.view(x.size(0), -1) x = self.last_linear(x) return x def forward(self, input): x = self.features(input) x = self.logits(x) return x def fbresnet18(num_classes=1000): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes) return model def fbresnet34(num_classes=1000): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes) return model def fbresnet50(num_classes=1000): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes) return model def fbresnet101(num_classes=1000): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) return model def fbresnet152(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['fbresnet152'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 748f2cea7209e3144a2fe264eccfe7d0 ModelImporter: serializedVersion: 23 fileIDToRecycleName: 100000: Chest 100002: //RootNode 100004: Head 100006: Hips 100008: Jaw 100010: JawEnd 100012: LeftEye 100014: LeftFoot 100016: LeftHand 100018: LeftIndexDistal 100020: LeftIndexDistalEnd 100022: LeftIndexIntermediate 100024: LeftIndexProximal 100026: LeftLowerArm 100028: LeftLowerLeg 100030: LeftMiddleDistal 100032: LeftMiddleDistalEnd 100034: LeftMiddleIntermediate 100036: LeftMiddleProximal 100038: LeftPinkyDistal 100040: LeftPinkyDistalEnd 100042: LeftPinkyIntermediate 100044: LeftPinkyProximal 100046: LeftRingDistal 100048: LeftRingDistalEnd 100050: LeftRingIntermediate 100052: LeftRingProximal 100054: LeftShoulder 100056: LeftThumbDistal 100058: LeftThumbDistalEnd 100060: LeftThumbIntermediate 100062: LeftThumbProximal 100064: LeftToes 100066: LeftToesEnd 100068: LeftUpperArm 100070: LeftUpperLeg 100072: Neck 100074: RightEye 100076: RightFoot 100078: RightHand 100080: RightIndexDistal 100082: RightIndexDistalEnd 100084: RightIndexIntermediate 100086: RightIndexProximal 100088: RightLowerArm 100090: RightLowerLeg 100092: RightMiddleDistal 100094: RightMiddleDistalEnd 100096: RightMiddleIntermediate 100098: RightMiddleProximal 100100: RightPinkyDistal 100102: RightPinkyDistalEnd 100104: RightPinkyIntermediate 100106: RightPinkyProximal 100108: RightRingDistal 100110: RightRingDistalEnd 100112: RightRingIntermediate 100114: RightRingProximal 100116: RightShoulder 100118: RightThumbDistal 100120: RightThumbDistalEnd 100122: RightThumbIntermediate 100124: RightThumbProximal 100126: RightToes 100128: RightToesEnd 100130: RightUpperArm 100132: RightUpperLeg 100134: Root 100136: Spine 100138: UpperChest 400000: Chest 400002: //RootNode 400004: Head 400006: Hips 400008: Jaw 400010: JawEnd 400012: LeftEye 400014: LeftFoot 400016: LeftHand 400018: LeftIndexDistal 400020: LeftIndexDistalEnd 400022: LeftIndexIntermediate 400024: LeftIndexProximal 400026: LeftLowerArm 400028: LeftLowerLeg 400030: LeftMiddleDistal 400032: LeftMiddleDistalEnd 400034: LeftMiddleIntermediate 400036: LeftMiddleProximal 400038: LeftPinkyDistal 400040: LeftPinkyDistalEnd 400042: LeftPinkyIntermediate 400044: LeftPinkyProximal 400046: LeftRingDistal 400048: LeftRingDistalEnd 400050: LeftRingIntermediate 400052: LeftRingProximal 400054: LeftShoulder 400056: LeftThumbDistal 400058: LeftThumbDistalEnd 400060: LeftThumbIntermediate 400062: LeftThumbProximal 400064: LeftToes 400066: LeftToesEnd 400068: LeftUpperArm 400070: LeftUpperLeg 400072: Neck 400074: RightEye 400076: RightFoot 400078: RightHand 400080: RightIndexDistal 400082: RightIndexDistalEnd 400084: RightIndexIntermediate 400086: RightIndexProximal 400088: RightLowerArm 400090: RightLowerLeg 400092: RightMiddleDistal 400094: RightMiddleDistalEnd 400096: RightMiddleIntermediate 400098: RightMiddleProximal 400100: RightPinkyDistal 400102: RightPinkyDistalEnd 400104: RightPinkyIntermediate 400106: RightPinkyProximal 400108: RightRingDistal 400110: RightRingDistalEnd 400112: RightRingIntermediate 400114: RightRingProximal 400116: RightShoulder 400118: RightThumbDistal 400120: RightThumbDistalEnd 400122: RightThumbIntermediate 400124: RightThumbProximal 400126: RightToes 400128: RightToesEnd 400130: RightUpperArm 400132: RightUpperLeg 400134: Root 400136: Spine 400138: UpperChest 7400000: RunForwardsJump_Frame01 7400002: RunForwardsJump_Frame01_Mirror 9500000: //RootNode externalObjects: {} materials: importMaterials: 1 materialName: 0 materialSearch: 1 materialLocation: 1 animations: legacyGenerateAnimations: 4 bakeSimulation: 0 resampleCurves: 1 optimizeGameObjects: 0 motionNodeName: rigImportErrors: rigImportWarnings: animationImportErrors: animationImportWarnings: animationRetargetingWarnings: animationDoRetargetingWarnings: 0 importAnimatedCustomProperties: 0 importConstraints: 0 animationCompression: 1 animationRotationError: 0.5 animationPositionError: 0.5 animationScaleError: 0.5 animationWrapMode: 0 extraExposedTransformPaths: [] extraUserProperties: [] clipAnimations: - serializedVersion: 16 name: RunForwardsJump_Frame01 takeName: Take 001 firstFrame: 1 lastFrame: 40 wrapMode: 0 orientationOffsetY: 0 level: 0 cycleOffset: 0 loop: 0 hasAdditiveReferencePose: 0 loopTime: 1 loopBlend: 1 loopBlendOrientation: 1 loopBlendPositionY: 1 loopBlendPositionXZ: 1 keepOriginalOrientation: 0 keepOriginalPositionY: 1 keepOriginalPositionXZ: 0 heightFromFeet: 0 mirror: 0 bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000 curves: [] events: [] transformMask: [] maskType: 3 maskSource: {instanceID: 0} additiveReferencePoseFrame: 0 - serializedVersion: 16 name: RunForwardsJump_Frame01_Mirror takeName: Take 001 firstFrame: 1 lastFrame: 40 wrapMode: 0 orientationOffsetY: 0 level: 0 cycleOffset: 0 loop: 0 hasAdditiveReferencePose: 0 loopTime: 1 loopBlend: 1 loopBlendOrientation: 1 loopBlendPositionY: 1 loopBlendPositionXZ: 1 keepOriginalOrientation: 0 keepOriginalPositionY: 1 keepOriginalPositionXZ: 0 heightFromFeet: 0 mirror: 1 bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000 curves: [] events: [] transformMask: [] maskType: 3 maskSource: {instanceID: 0} additiveReferencePoseFrame: 0 isReadable: 1 meshes: lODScreenPercentages: [] globalScale: 1 meshCompression: 0 addColliders: 0 importVisibility: 1 importBlendShapes: 1 importCameras: 1 importLights: 1 swapUVChannels: 0 generateSecondaryUV: 0 useFileUnits: 1 optimizeMeshForGPU: 1 keepQuads: 0 weldVertices: 1 preserveHierarchy: 0 indexFormat: 0 secondaryUVAngleDistortion: 8 secondaryUVAreaDistortion: 15.000001 secondaryUVHardAngle: 88 secondaryUVPackMargin: 4 useFileScale: 1 previousCalculatedGlobalScale: 0.01 hasPreviousCalculatedGlobalScale: 1 tangentSpace: normalSmoothAngle: 60 normalImportMode: 0 tangentImportMode: 3 normalCalculationMode: 4 importAnimation: 1 copyAvatar: 1 humanDescription: serializedVersion: 2 human: - boneName: Hips humanName: Hips limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftUpperLeg humanName: LeftUpperLeg limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightUpperLeg humanName: RightUpperLeg limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftLowerLeg humanName: LeftLowerLeg limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightLowerLeg humanName: RightLowerLeg limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftFoot humanName: LeftFoot limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightFoot humanName: RightFoot limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: Spine humanName: Spine limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: Chest humanName: Chest limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: Neck humanName: Neck limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: Head humanName: Head limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftShoulder humanName: LeftShoulder limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightShoulder humanName: RightShoulder limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftUpperArm humanName: LeftUpperArm limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightUpperArm humanName: RightUpperArm limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftLowerArm humanName: LeftLowerArm limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightLowerArm humanName: RightLowerArm limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftHand humanName: LeftHand limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightHand humanName: RightHand limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftToes humanName: LeftToes limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightToes humanName: RightToes limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftEye humanName: LeftEye limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightEye humanName: RightEye limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: Jaw humanName: Jaw limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftThumbProximal humanName: Left Thumb Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftThumbIntermediate humanName: Left Thumb Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftThumbDistal humanName: Left Thumb Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftIndexProximal humanName: Left Index Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftIndexIntermediate humanName: Left Index Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftIndexDistal humanName: Left Index Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftMiddleProximal humanName: Left Middle Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftMiddleIntermediate humanName: Left Middle Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftMiddleDistal humanName: Left Middle Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftRingProximal humanName: Left Ring Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftRingIntermediate humanName: Left Ring Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftRingDistal humanName: Left Ring Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftPinkyProximal humanName: Left Little Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftPinkyIntermediate humanName: Left Little Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: LeftPinkyDistal humanName: Left Little Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightThumbProximal humanName: Right Thumb Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightThumbIntermediate humanName: Right Thumb Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightThumbDistal humanName: Right Thumb Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightIndexProximal humanName: Right Index Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightIndexIntermediate humanName: Right Index Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightIndexDistal humanName: Right Index Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightMiddleProximal humanName: Right Middle Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightMiddleIntermediate humanName: Right Middle Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightMiddleDistal humanName: Right Middle Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightRingProximal humanName: Right Ring Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightRingIntermediate humanName: Right Ring Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightRingDistal humanName: Right Ring Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightPinkyProximal humanName: Right Little Proximal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightPinkyIntermediate humanName: Right Little Intermediate limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: RightPinkyDistal humanName: Right Little Distal limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 - boneName: UpperChest humanName: UpperChest limit: min: {x: 0, y: 0, z: 0} max: {x: 0, y: 0, z: 0} value: {x: 0, y: 0, z: 0} length: 0 modified: 0 skeleton: - name: defaultfemale_rig(Clone) parentName: position: {x: 0, y: 0, z: 0} rotation: {x: 0, y: 0, z: 0, w: 1} scale: {x: 1, y: 1, z: 1} - name: Body parentName: defaultfemale_rig(Clone) position: {x: -0, y: 0, z: 0} rotation: {x: 0, y: -0, z: -0, w: 1} scale: {x: 1, y: 1, z: 1} - name: Root parentName: defaultfemale_rig(Clone) position: {x: -0, y: 0, z: 0} rotation: {x: 0, y: -0, z: -0, w: 1} scale: {x: 1, y: 1, z: 1} - name: Hips parentName: Root position: {x: -1.3312027e-32, y: 0.8692137, z: 0.030971607} rotation: {x: 0.5, y: -0.5, z: -0.5, w: 0.5} scale: {x: 1, y: 1, z: 1} - name: Spine parentName: Hips position: {x: -0.076805644, y: 0.0010977649, z: 4.785846e-17} rotation: {x: 0, y: -0, z: -0, w: 1} scale: {x: 1, y: 1, z: 1} - name: Chest parentName: Spine position: {x: -0.10399994, y: -4.440892e-18, z: 1.1005485e-17} rotation: {x: 0, y: -0, z: -0, w: 1} scale: {x: 1, y: 1, z: 1} - name: UpperChest parentName: Chest position: {x: -0.10000036, y: -1.7763568e-17, z: -2.3896762e-17} rotation: {x: 0, y: -0, z: -0, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightShoulder parentName: UpperChest position: {x: -0.15174031, y: 0.004668527, z: -0.023324499} rotation: {x: 0.5, y: 0.5, z: -0.5, w: 0.5} scale: {x: 1, y: 1, z: 1} - name: RightUpperArm parentName: RightShoulder position: {x: 0.1215205, y: -0.01563, z: 0.0296894} rotation: {x: 0.0000000017555596, y: -0.014622055, z: 0.00000012004962, w: 0.9998931} scale: {x: 1, y: 1, z: 1} - name: RightLowerArm parentName: RightUpperArm position: {x: 0.24382727, y: -0.000000058523955, z: -0.000000022256911} rotation: {x: 0.0000000019174404, y: 0.015977193, z: -0.00000011999579, w: 0.9998724} scale: {x: 1, y: 1, z: 1} - name: RightHand parentName: RightLowerArm position: {x: 0.22894184, y: -5.134808e-11, z: 0.0000020656983} rotation: {x: 8.631089e-25, y: -0.0013552951, z: 2.6508945e-23, w: 0.9999991} scale: {x: 1, y: 1, z: 1} - name: RightPinkyProximal parentName: RightHand position: {x: 0.08387999, y: -0.00037999984, z: 0.026014276} rotation: {x: 1, y: 1.556642e-14, z: 0.00000000765598, w: -6.123246e-17} scale: {x: 1, y: 1, z: 1} - name: RightPinkyIntermediate parentName: RightPinkyProximal position: {x: 0.0177784, y: 0.0000042994275, z: -0.000000016072681} rotation: {x: 8.191156e-22, y: -0.000000007652775, z: 1.5528472e-14, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightPinkyDistal parentName: RightPinkyIntermediate position: {x: 0.014883991, y: 0.0000029045614, z: 0.000000004083737} rotation: {x: 8.271806e-25, y: 6.7220535e-18, z: -2.6533602e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightPinkyDistalEnd parentName: RightPinkyDistal position: {x: 0.01554674, y: -0.000009335179, z: 0.000000029614585} rotation: {x: 0.0000010102065, y: 6.7220535e-18, z: -3.3311337e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightRingProximal parentName: RightHand position: {x: 0.08864199, y: -0.0025, z: 0.008555825} rotation: {x: 1, y: 2.6520677e-23, z: 6.7220535e-18, w: -6.123234e-17} scale: {x: 1, y: 1, z: 1} - name: RightRingIntermediate parentName: RightRingProximal position: {x: 0.028351422, y: 0.000000118793274, z: 0.0000000030276448} rotation: {x: 4.135903e-25, y: 6.7220535e-18, z: -2.6533602e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightRingDistal parentName: RightRingIntermediate position: {x: 0.024773668, y: -0.0000005334987, z: -1.8684333e-10} rotation: {x: 4.135903e-25, y: 6.7220535e-18, z: -2.6533602e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightRingDistalEnd parentName: RightRingDistal position: {x: 0.019770548, y: -0.0000070654687, z: -0.0000000065839605} rotation: {x: 4.135903e-25, y: 6.7220535e-18, z: -2.6533602e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightMiddleProximal parentName: RightHand position: {x: 0.091359, y: -0.0027, z: -0.0121138245} rotation: {x: 1, y: 2.6533602e-23, z: 6.7220535e-18, w: -6.123234e-17} scale: {x: 1, y: 1, z: 1} - name: RightMiddleIntermediate parentName: RightMiddleProximal position: {x: 0.03278326, y: 0.0000057416637, z: -0.000000037388556} rotation: {x: 8.271806e-25, y: 6.7220535e-18, z: -2.6533602e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightMiddleDistal parentName: RightMiddleIntermediate position: {x: 0.024582865, y: -0.000003002054, z: -0.000000035323986} rotation: {x: 4.135903e-25, y: 6.7220535e-18, z: -2.6546526e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightMiddleDistalEnd parentName: RightMiddleDistal position: {x: 0.021146365, y: -0.000001895531, z: 0.000000012172779} rotation: {x: 0.0000010029821, y: 6.7220535e-18, z: -3.3288624e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightIndexProximal parentName: RightHand position: {x: 0.089671, y: -0.0029400003, z: -0.034472425} rotation: {x: 1, y: 2.6533602e-23, z: 6.7220535e-18, w: -6.123234e-17} scale: {x: 1, y: 1, z: 1} - name: RightIndexIntermediate parentName: RightIndexProximal position: {x: 0.026809353, y: 0.000004049856, z: 0.0000000059569842} rotation: {x: 8.271806e-25, y: 6.7220535e-18, z: -2.6533602e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightIndexDistal parentName: RightIndexIntermediate position: {x: 0.022327757, y: -0.000005660982, z: 0.000000037771883} rotation: {x: 8.271806e-25, y: 6.7220535e-18, z: -2.6520677e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightIndexDistalEnd parentName: RightIndexDistal position: {x: 0.019863686, y: -0.0000020741666, z: -0.000000058040403} rotation: {x: 1.2407709e-24, y: 6.7220535e-18, z: -2.6533602e-23, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightThumbProximal parentName: RightHand position: {x: 0.028403, y: 0.0026799997, z: -0.024262024} rotation: {x: -0.7071051, y: 0.0011197575, z: -0.0009201257, w: 0.70710707} scale: {x: 1, y: 1, z: 1} - name: RightThumbIntermediate parentName: RightThumbProximal position: {x: 0.012866616, y: 0.02410067, z: 0.0007770431} rotation: {x: -0.0007402685, y: -0.0012375537, z: 0.5124907, w: 0.8586916} scale: {x: 1, y: 1, z: 1} - name: RightThumbDistal parentName: RightThumbIntermediate position: {x: 0.033680853, y: 0.00000013176813, z: -1.0658141e-13} rotation: {x: 1.0495076e-16, y: -1.9569849e-16, z: 2.0538705e-32, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightThumbDistalEnd parentName: RightThumbDistal position: {x: 0.026808364, y: -0.00000053287914, z: 0.0000000022359978} rotation: {x: 1.04950803e-16, y: -1.9569849e-16, z: -2.7755572e-17, w: 1} scale: {x: 1, y: 1, z: 1} - name: Neck parentName: UpperChest position: {x: -0.22180894, y: -0.021184636, z: -1.05055544e-16} rotation: {x: 2.3897904e-32, y: -8.63648e-33, z: -0.10163171, w: 0.9948221} scale: {x: 1, y: 1, z: 1} - name: Head parentName: Neck position: {x: -0.09056838, y: -3.5527136e-17, z: 1.1949222e-17} rotation: {x: 2.640332e-32, y: -1.5887779e-32, z: 0.1016317, w: 0.9948221} scale: {x: 1, y: 1, z: 1} - name: Jaw parentName: Head position: {x: 0.013113437, y: 0.011265113, z: 0.0000073231295} rotation: {x: 4.777775e-32, y: 1.7322846e-32, z: -0.82937473, w: 0.55869275} scale: {x: 1, y: 1, z: 1} - name: JawEnd parentName: Jaw position: {x: -0.094001085, y: 0, z: -1.650481e-17} rotation: {x: 1.2325952e-32, y: 4.9303807e-32, z: -2.7755576e-17, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftEye parentName: Head position: {x: -0.071607426, y: 0.10076878, z: 0.030001726} rotation: {x: 3.0505177e-32, y: 4.357883e-33, z: -0.7071068, w: 0.7071068} scale: {x: 1, y: 1, z: 1} - name: RightEye parentName: Head position: {x: -0.07160636, y: 0.10076881, z: -0.029998273} rotation: {x: 3.0505177e-32, y: 4.357883e-33, z: -0.7071068, w: 0.7071068} scale: {x: 1, y: 1, z: 1} - name: LeftShoulder parentName: UpperChest position: {x: -0.15174149, y: 0.004668562, z: 0.023324465} rotation: {x: -0.5, y: 0.5, z: 0.5, w: 0.5} scale: {x: 1, y: 1, z: 1} - name: LeftUpperArm parentName: LeftShoulder position: {x: -0.1215209, y: 0.015633445, z: -0.029689433} rotation: {x: 0.0000000017555596, y: -0.014622055, z: 0.00000012004962, w: 0.9998931} scale: {x: 1, y: 1, z: 1} - name: LeftLowerArm parentName: LeftUpperArm position: {x: -0.24382652, y: 5.684342e-16, z: 3.5527136e-17} rotation: {x: 0.0000000019174404, y: 0.015977193, z: -0.00000011999579, w: 0.9998724} scale: {x: 1, y: 1, z: 1} - name: LeftHand parentName: LeftLowerArm position: {x: -0.22894189, y: 1.1368684e-15, z: -0.0000020663583} rotation: {x: 8.272352e-25, y: -0.0013552951, z: 3.9730126e-26, w: 0.9999991} scale: {x: 1, y: 1, z: 1} - name: LeftPinkyProximal parentName: LeftHand position: {x: -0.08388007, y: 0.0003779601, z: -0.026014261} rotation: {x: 1, y: 7.2858386e-16, z: 1.7843535e-10, w: -0.0000000035046888} scale: {x: 1, y: 1, z: 1} - name: LeftPinkyIntermediate parentName: LeftPinkyProximal position: {x: -0.017778445, y: -8.5265126e-16, z: -1.3322676e-17} rotation: {x: 4.135903e-25, y: 4.98733e-18, z: -1.27594854e-26, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftPinkyDistal parentName: LeftPinkyIntermediate position: {x: -0.014884741, y: 8.5265126e-16, z: -9.1099794e-11} rotation: {x: -1.7540424e-33, y: 4.9873366e-18, z: -3.0727685e-26, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftPinkyDistalEnd parentName: LeftPinkyDistal position: {x: -0.015545194, y: 0, z: 0} rotation: {x: -0.0000010103315, y: 0.000000093449074, z: 9.441455e-14, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftRingProximal parentName: LeftHand position: {x: -0.08864191, y: 0.002492614, z: -0.008555825} rotation: {x: 1, y: 9.796608e-13, z: 3.787877e-10, w: -0.000000003488725} scale: {x: 1, y: 1, z: 1} - name: LeftRingIntermediate parentName: LeftRingProximal position: {x: -0.028352136, y: 0, z: 0} rotation: {x: 4.135903e-25, y: 4.98733e-18, z: -2.5684182e-26, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftRingDistal parentName: LeftRingIntermediate position: {x: -0.024773644, y: -2.842171e-16, z: 1.110223e-18} rotation: {x: 4.135903e-25, y: 4.98733e-18, z: -3.860888e-26, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftRingDistalEnd parentName: LeftRingDistal position: {x: -0.019769518, y: 0.00000006627932, z: 1.1533246e-10} rotation: {x: -0.0000010029853, y: 0.000000104158495, z: 1.0446944e-13, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftMiddleProximal parentName: LeftHand position: {x: -0.09135914, y: 0.0026978743, z: 0.01211379} rotation: {x: 1, y: 9.831164e-13, z: 3.1612182e-10, w: -0.0000000034949608} scale: {x: 1, y: 1, z: 1} - name: LeftMiddleIntermediate parentName: LeftMiddleProximal position: {x: -0.03278388, y: 0, z: 2.220446e-18} rotation: {x: 4.135903e-25, y: 4.98733e-18, z: -3.359236e-26, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftMiddleDistal parentName: LeftMiddleIntermediate position: {x: -0.024582941, y: 8.5265126e-16, z: -2.220446e-18} rotation: {x: 8.271806e-25, y: 4.9873432e-18, z: -7.742374e-27, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftMiddleDistalEnd parentName: LeftMiddleDistal position: {x: -0.021145808, y: 2.842171e-16, z: -3.813218e-11} rotation: {x: -0.0000010029694, y: 0.00000010320911, z: 1.03515585e-13, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftIndexProximal parentName: LeftHand position: {x: -0.089670934, y: 0.0029354861, z: 0.034472432} rotation: {x: 1, y: 9.852535e-13, z: 2.7204164e-10, w: -0.0000000034986678} scale: {x: 1, y: 1, z: 1} - name: LeftIndexIntermediate parentName: LeftIndexProximal position: {x: -0.026809933, y: 0, z: 1.3322676e-17} rotation: {x: 4.135903e-25, y: 4.9873168e-18, z: -1.4115581e-26, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftIndexDistal parentName: LeftIndexIntermediate position: {x: -0.022327332, y: -5.684342e-16, z: 0} rotation: {x: 4.135903e-25, y: 4.987307e-18, z: -3.0228854e-26, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftIndexDistalEnd parentName: LeftIndexDistal position: {x: -0.01986299, y: -2.842171e-16, z: -4.440892e-18} rotation: {x: -0.0000009997572, y: 0.00000013765555, z: 1.3762212e-13, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftThumbProximal parentName: LeftHand position: {x: -0.028403576, y: -0.002684717, z: 0.024262011} rotation: {x: -0.70710504, y: 0.0011197574, z: -0.00092012563, w: 0.70710707} scale: {x: 1, y: 1, z: 1} - name: LeftThumbIntermediate parentName: LeftThumbProximal position: {x: -0.0128663415, y: -0.024100708, z: -0.0007739503} rotation: {x: -0.0007402685, y: -0.0012375537, z: 0.5124907, w: 0.8586916} scale: {x: 1, y: 1, z: 1} - name: LeftThumbDistal parentName: LeftThumbIntermediate position: {x: -0.033680916, y: -7.105427e-17, z: 0} rotation: {x: 5.247536e-17, y: -9.7686616e-17, z: 5.1261402e-33, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftThumbDistalEnd parentName: LeftThumbDistal position: {x: -0.026808554, y: 0, z: 2.842171e-16} rotation: {x: 5.247532e-17, y: -9.7686616e-17, z: -5.551115e-17, w: 1} scale: {x: 1, y: 1, z: 1} - name: LeftUpperLeg parentName: Hips position: {x: 0.027625732, y: -0.01239631, z: 0.08899005} rotation: {x: 1.627618e-32, y: -2.4087165e-32, z: 0.9993648, w: -0.035637297} scale: {x: 1, y: 1, z: 1} - name: LeftLowerLeg parentName: LeftUpperLeg position: {x: -0.3932828, y: -1.7763568e-17, z: -5.3290704e-17} rotation: {x: -7.300761e-32, y: 1.7066485e-32, z: -0.06444611, w: 0.99792117} scale: {x: 1, y: 1, z: 1} - name: LeftFoot parentName: LeftLowerLeg position: {x: -0.37266436, y: 1.4210854e-16, z: 0} rotation: {x: -4.7950157e-32, y: -4.762511e-32, z: 0.02884196, w: 0.999584} scale: {x: 1, y: 1, z: 1} - name: LeftToes parentName: LeftFoot position: {x: -0.062541395, y: -0.12741902, z: 7.105427e-17} rotation: {x: -8.49787e-32, y: -1.5252589e-32, z: 0.7071068, w: 0.7071068} scale: {x: 1, y: 1, z: 1} - name: LeftToesEnd parentName: LeftToes position: {x: -0.050641473, y: 2.2204459e-17, z: -1.7763568e-17} rotation: {x: -7.087422e-32, y: 4.9303807e-32, z: -1.7347235e-17, w: 1} scale: {x: 1, y: 1, z: 1} - name: RightUpperLeg parentName: Hips position: {x: 0.027625715, y: -0.012396308, z: -0.08899} rotation: {x: 2.196318e-34, y: -6.159061e-33, z: 0.035637297, w: 0.9993648} scale: {x: 1, y: 1, z: 1} - name: RightLowerLeg parentName: RightUpperLeg position: {x: 0.39328295, y: 0.00000002356415, z: 1.0658141e-16} rotation: {x: -9.929495e-34, y: -1.537541e-32, z: -0.06444611, w: 0.99792117} scale: {x: 1, y: 1, z: 1} - name: RightFoot parentName: RightLowerLeg position: {x: 0.3726642, y: -0.000000012342044, z: 1.7763568e-17} rotation: {x: 8.887615e-34, y: -3.0802063e-32, z: 0.02884196, w: 0.999584} scale: {x: 1, y: 1, z: 1} - name: RightToes parentName: RightFoot position: {x: 0.062541395, y: 0.1274192, z: 8.8817837e-17} rotation: {x: -2.1789411e-32, y: -2.1789411e-32, z: 0.7071068, w: 0.7071068} scale: {x: 1, y: 1, z: 1} - name: RightToesEnd parentName: RightToes position: {x: 0.050640997, y: 8.715251e-15, z: 0} rotation: {x: -3.081488e-32, y: -2.4651903e-32, z: -1.7347235e-17, w: 1} scale: {x: 1, y: 1, z: 1} armTwist: 0.5 foreArmTwist: 0.5 upperLegTwist: 0.5 legTwist: 0.5 armStretch: 0.05 legStretch: 0.05 feetSpacing: 0 rootMotionBoneName: hasTranslationDoF: 0 hasExtraRoot: 1 skeletonHasParents: 1 lastHumanDescriptionAvatarSource: {fileID: 9000000, guid: f0e07a2a187e3479b8ea069b45211486, type: 3} animationType: 3 humanoidOversampling: 1 additionalBone: 0 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
The quick brown fox :[activity](activity.md animal:"dog" state:disinterest.md empty:).
{ "pile_set_name": "Github" }
DKImagePickerController ======================= [![Build Status](https://secure.travis-ci.org/zhangao0086/DKImagePickerController.svg)](http://travis-ci.org/zhangao0086/DKImagePickerController) [![Version Status](http://img.shields.io/cocoapods/v/DKImagePickerController.png)][docsLink] [![license MIT](https://img.shields.io/cocoapods/l/DKImagePickerController.svg?style=flat)][mitLink] [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) <img width="50%" height="50%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot3.png" /><img width="50%" height="50%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot4.png" /> --- <img width="50%" height="50%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot11.png" /><img width="50%" height="50%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot6.png" /> --- ## Description `DKImagePickerController` is a highly customizable, pure-Swift library. ### Features * Supports both single and multiple selection. * Supports filtering albums and sorting by type. * Supports landscape, iPad, and orientation switching. * Supports iCloud. * Supports batch exports `PHAsset` to files. * Inline mode. * Customizable `UICollectionViewLayout`. * Customizable `camera`, `photo gallery` and `photo editor`. ## Requirements * iOS 8.0+ * ARC * Swift 3.2 & 4.2 ## Installation ### CocoaPods #### iOS 8 and newer DKImagePickerController is available on CocoaPods. Simply add the following line to your podfile: ``` # For latest release in cocoapods pod 'DKImagePickerController' ``` #### For Swift 4.1 ``` pod 'DKImagePickerController', :git => 'https://github.com/zhangao0086/DKImagePickerController.git', :branch => 'Swift4' ``` #### Subspecs There are 7 subspecs available now: | Subspec | Description | |---|---| | Core | Required. | | ImageDataManager | Required. The subspec provides data to `DKImagePickerController`. | | Resource | Required. The subspec provides resource management and internationalization. | | PhotoGallery | Optional. The subspec provides preview feature for PHAsset. | | Camera | Optional. The subspec provides camera feature. | | InlineCamera | Optional. The subspec should be pushed by `UINavigationController`, like `UIImagePickerController` with `UIImagePickerControllerSourceType.camera`. | | PhotoEditor | Optional. The subspec provides basic image editing features. | This means you can install only some of the `DKImagePickerController` modules. By default, you get all subspecs. If you need to use your own photo editor, simply specify subspecs other than `PhotoEditor`: ```ruby pod 'DKImagePickerController', :subspecs => ['PhotoGallery', 'Camera', 'InlineCamera'] ``` More information, see [Extensions](#extensions). ### Carthage ``` github "zhangao0086/DKImagePickerController" ``` If you use Carthage to build your dependencies, make sure you have added `CropViewController.framework`, `DKCamera.framework`, `DKImagePickerController.framework`, `DKPhotoGallery.framework` and `SDWebImage.framework` to the _"Linked Frameworks and Libraries"_ section of your target, and have included them in your Carthage framework copying build phase. ## Getting Started #### Initialization and presentation ```swift let pickerController = DKImagePickerController() pickerController.didSelectAssets = { (assets: [DKAsset]) in print("didSelectAssets") print(assets) } self.presentViewController(pickerController, animated: true) {} ```` #### Configurations ```swift /// Use UIDelegate to Customize the picker UI. @objc public var UIDelegate: DKImagePickerControllerBaseUIDelegate! /// Forces deselect of previous selected image. allowSwipeToSelect will be ignored. @objc public var singleSelect = false /// Auto close picker on single select @objc public var autoCloseOnSingleSelect = true /// The maximum count of assets which the user will be able to select, a value of 0 means no limit. @objc public var maxSelectableCount = 0 /// Photos will be tagged with the location where they are taken. /// If true, your Info.plist should include the "Privacy - Location XXX" tag. open var containsGPSInMetadata = false /// Set the defaultAssetGroup to specify which album is the default asset group. public var defaultAssetGroup: PHAssetCollectionSubtype? /// Allow swipe to select images. @objc public var allowSwipeToSelect: Bool = false /// Allow select all @objc public var allowSelectAll: Bool = false /// A Bool value indicating whether the inline mode is enabled. @objc public var inline: Bool = false /// The type of picker interface to be displayed by the controller. @objc public var assetType: DKImagePickerControllerAssetType = .allAssets /// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored. @objc public var sourceType: DKImagePickerControllerSourceType = .both /// A Bool value indicating whether allows to select photos and videos at the same time. @objc public var allowMultipleTypes = true /// A Bool value indicating whether to allow the picker auto-rotate the screen. @objc public var allowsLandscape = false /// Set the showsEmptyAlbums to specify whether or not the empty albums is shown in the picker. @objc public var showsEmptyAlbums = true /// A Bool value indicating whether to allow the picker shows the cancel button. @objc public var showsCancelButton = false /// The block is executed when the user presses the cancel button. @objc public var didCancel: (() -> Void)? /// The block is executed when the user presses the select button. @objc public var didSelectAssets: ((_ assets: [DKAsset]) -> Void)? /// The block is executed when the number of selected assets is changed. @objc public var selectedChanged: (() -> Void)? /// A Bool value indicating whether to allow the picker to auto-export the selected assets to the specified directory when done is called. /// picker will creating a default exporter if exportsWhenCompleted is true and the exporter is nil. @objc public var exportsWhenCompleted = false @objc public var exporter: DKImageAssetExporter? /// Indicates the status of the exporter. @objc public private(set) var exportStatus = DKImagePickerControllerExportStatus.none { willSet { if self.exportStatus != newValue { self.willChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus)) } } didSet { if self.exportStatus != oldValue { self.didChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus)) self.exportStatusChanged?(self.exportStatus) } } } /// The block is executed when the exportStatus is changed. @objc public var exportStatusChanged: ((DKImagePickerControllerExportStatus) -> Void)? /// The object that acts as the data source of the picker. @objc public private(set) lazy var groupDataManager: DKImageGroupDataManager ``` ## Inline Mode <img width="30%" height="30%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot11.png" /> ```swift let groupDataManagerConfiguration = DKImageGroupDataManagerConfiguration() groupDataManagerConfiguration.fetchLimit = 10 groupDataManagerConfiguration.assetGroupTypes = [.smartAlbumUserLibrary] let groupDataManager = DKImageGroupDataManager(configuration: groupDataManagerConfiguration) self.pickerController = DKImagePickerController(groupDataManager: groupDataManager) pickerController.inline = true pickerController.UIDelegate = CustomInlineLayoutUIDelegate(imagePickerController: pickerController) pickerController.assetType = .allPhotos pickerController.sourceType = .photo let pickerView = self.pickerController.view! pickerView.frame = CGRect(x: 0, y: 170, width: self.view.bounds.width, height: 200) self.view.addSubview(pickerView) ``` ## Customizable UI <img width="30%" height="30%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot6.png" /> For example, see [CustomUIDelegate](https://github.com/zhangao0086/DKImagePickerController/tree/develop/DKImagePickerControllerDemo/CustomUIDelegate). ## Customizable Layout <img width="30%" height="30%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot10.png" /> For example, see [CustomLayoutUIDelegate](https://github.com/zhangao0086/DKImagePickerController/tree/develop/DKImagePickerControllerDemo/CustomLayoutUIDelegate). ### Conforms UIAppearance protocol <img width="30%" height="30%" src="https://raw.githubusercontent.com/zhangao0086/DKImagePickerController/develop/Screenshot9.png" /> You can easily customize the appearance of the navigation bar using the appearance proxy. ```swift UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName : UIFont(name: "Optima-BoldItalic", size: 21)!, NSForegroundColorAttributeName : UIColor.redColor() ] ``` ## Exporting to file By default, the picker uses a singleton object of `DKImageAssetExporter` to export `DKAsset` to local files. ```swift /* Configuration options for a DKImageAssetExporter. When an exporter is created, a copy of the configuration object is made - you cannot modify the configuration of an exporter after it has been created. */ @objc public class DKImageAssetExporterConfiguration: NSObject, NSCopying { @objc public var imageExportPreset = DKImageExportPresent.compatible /// videoExportPreset can be used to specify the transcoding quality for videos (via a AVAssetExportPreset* string). @objc public var videoExportPreset = AVAssetExportPresetHighestQuality #if swift(>=4.0) @objc public var avOutputFileType = AVFileType.mov #else @objc public var avOutputFileType = AVFileTypeQuickTimeMovie #endif @objc public var exportDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("DKImageAssetExporter") } /* A DKImageAssetExporter object exports DKAsset(PHAsset) from album (or iCloud) to the app's tmp directory (by default). It automatically deletes the exported directories when it receives a UIApplicationWillTerminate notification. */ @objc open class DKImageAssetExporter: DKBaseManager { /// This method starts an asynchronous export operation of a batch of asset. @discardableResult @objc public func exportAssetsAsynchronously(assets: [DKAsset], completion: ((_ info: [AnyHashable : Any]) -> Void)?) -> DKImageAssetExportRequestID } ``` This exporter can automatically convert HEIF to JPEG: ```swift @objc public enum DKImageExportPresent: Int { case compatible, // A preset for converting HEIF formatted images to JPEG. current // A preset for passing image data as-is to the client. } ``` You also can observe the export progress of each asset: ```swift @objc public protocol DKImageAssetExporterObserver { @objc optional func exporterWillBeginExporting(exporter: DKImageAssetExporter, asset: DKAsset) /// The progress can be obtained from the DKAsset. @objc optional func exporterDidUpdateProgress(exporter: DKImageAssetExporter, asset: DKAsset) /// When the asset's error is not nil, it indicates that an error occurred while exporting. @objc optional func exporterDidEndExporting(exporter: DKImageAssetExporter, asset: DKAsset) } extension DKAsset { /// The exported file will be placed in this location. /// All exported files can be automatically cleaned by the DKImageAssetDiskPurger when appropriate. @objc public var localTemporaryPath: URL? @objc public var fileName: String? /// Indicates the file's size in bytes. @objc public var fileSize: UInt /// If you export an asset whose data is not on the local device, and you have enabled downloading with the isNetworkAccessAllowed property, the progress indicates the progress of the download. A value of 0.0 indicates that the download has just started, and a value of 1.0 indicates the download is complete. @objc public var progress: Double /// Describes the error that occurred if the export has failed or been cancelled. @objc public var error: Error? } ``` For example, see `Export automatically` and `Export manually`. ## Extensions This picker uses `DKImageExtensionController` manages all extensions, you can register it with a `DKImageBaseExtension` and a specified `DKImageExtensionType` to customize `camera`, `photo gallery` and `photo editor`: ```swift /// Registers an extension for the specified type. public class func registerExtension(extensionClass: DKImageBaseExtension.Type, for type: DKImageExtensionType) public class func unregisterExtension(for type: DKImageExtensionType) ``` The `perform` function will be called with a dictionary providing current context information when an extension is triggered: ```swift /// Starts the extension. func perform(with extraInfo: [AnyHashable: Any]) /// Completes the extension. func finish() ``` The `extraInfo` will provide different information for different `DKImageExtensionType`: ##### Camera ```swift let didFinishCapturingImage = extraInfo["didFinishCapturingImage"] as? ((UIImage, [AnyHashable : Any]?) -> Void) let didCancel = extraInfo["didCancel"] as? (() -> Void) ``` For a custom camera example, see [CustomCameraExtension](DKImagePickerControllerDemo/DKImagePickerControllerDemo/CustomCamera). ##### InlineCamera The `extraInfo` is the same as for `Camera`. ##### Photo Gallery ```swift let groupId = extraInfo["groupId"] as? String let presentationIndex = extraInfo["presentationIndex"] as? Int let presentingFromImageView = extraInfo["presentingFromImageView"] as? UIImageView ``` ##### Photo Editor ```swift let image = extraInfo["image"] as? UIImage let didFinishEditing = extraInfo["didFinishEditing"] as? ((UIImage, [AnyHashable : Any]?) -> Void) let metadata = extraInfo["metadata"] as? [AnyHashable : Any] ``` ## How to use in Objective-C #### If you use [CocoaPods](http://cocoapods.org/) * Add the following two lines into your `Podfile`: ``` pod 'DKImagePickerController' use_frameworks! ``` * Import the library into your Objective-C file: ```objective-c #import <DKImagePickerController/DKImagePickerController-Swift.h> ``` #### If you use it directly in your project > See also:[Swift and Objective-C in the Same Project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) * Drag and drop the [DKCamera][DKCamera], `DKImageManager` and `DKImagePickerController` to your project * Import the library into your Objective-C file: ```objective-c #import "YourProductModuleName-Swift.h" ``` --- then you can: ```objective-c DKImagePickerController *pickerController = [DKImagePickerController new]; [pickerController setDidSelectAssets:^(NSArray * __nonnull assets) { NSLog(@"didSelectAssets"); }]; [self presentViewController:pickerController animated:YES completion:nil]; ``` ## Localization The default supported languages: > en, es, da, de, fr, hu, ja, ko, nb-NO, pt_BR, ru, tr, ur, vi, ar, it, zh-Hans, zh-Hant You can also add a hook to return your own localized string: ```swift DKImagePickerControllerResource.customLocalizationBlock = { title in if title == "picker.select.title" { return "Test(%@)" } else { return nil } } ``` or images: ```swift DKImagePickerControllerResource.customImageBlock = { imageName in if imageName == "camera" { return DKImagePickerControllerResource.photoGalleryCheckedImage() } else { return nil } } ``` ## Contributing to this project If you have feature requests or bug reports, feel free to help out by sending pull requests or by creating new issues. ## License DKImagePickerController is released under the MIT license. See LICENSE for details. [mitLink]:http://opensource.org/licenses/MIT [docsLink]:http://cocoadocs.org/docsets/DKImagePickerController [DKCamera]:https://github.com/zhangao0086/DKCamera
{ "pile_set_name": "Github" }
using System.Collections.Generic; using Orchard.DynamicForms.Elements; using Orchard.DynamicForms.Services; using Orchard.DynamicForms.ValidationRules; namespace Orchard.DynamicForms.Validators { public class CheckBoxValidator : ElementValidator<CheckBox> { private readonly IValidationRuleFactory _validationRuleFactory; public CheckBoxValidator(IValidationRuleFactory validationRuleFactory) { _validationRuleFactory = validationRuleFactory; } protected override IEnumerable<IValidationRule> GetValidationRules(CheckBox element) { var settings = element.ValidationSettings; if (settings.IsMandatory == true) yield return _validationRuleFactory.Create<Mandatory>(settings.CustomValidationMessage); } } }
{ "pile_set_name": "Github" }
{ "runOn": [ { "minServerVersion": "4.4" } ], "database_name": "sdam-tests", "collection_name": "isMaster-timeout", "data": [], "tests": [ { "description": "Network timeout on Monitor handshake", "failPoint": { "configureFailPoint": "failCommand", "mode": { "times": 2 }, "data": { "failCommands": [ "isMaster" ], "appName": "timeoutMonitorHandshakeTest", "blockConnection": true, "blockTimeMS": 1000 } }, "clientOptions": { "retryWrites": false, "connectTimeoutMS": 250, "heartbeatFrequencyMS": 500, "appname": "timeoutMonitorHandshakeTest" }, "operations": [ { "name": "waitForEvent", "object": "testRunner", "arguments": { "event": "ServerMarkedUnknownEvent", "count": 1 } }, { "name": "waitForEvent", "object": "testRunner", "arguments": { "event": "PoolClearedEvent", "count": 1 } }, { "name": "insertMany", "object": "collection", "arguments": { "documents": [ { "_id": 1 }, { "_id": 2 } ] } } ], "expectations": [ { "command_started_event": { "command": { "insert": "isMaster-timeout", "documents": [ { "_id": 1 }, { "_id": 2 } ] }, "command_name": "insert", "database_name": "sdam-tests" } } ], "outcome": { "collection": { "data": [ { "_id": 1 }, { "_id": 2 } ] } } }, { "description": "Network timeout on Monitor check", "clientOptions": { "retryWrites": false, "connectTimeoutMS": 750, "heartbeatFrequencyMS": 500, "appname": "timeoutMonitorCheckTest" }, "operations": [ { "name": "insertMany", "object": "collection", "arguments": { "documents": [ { "_id": 1 }, { "_id": 2 } ] } }, { "name": "configureFailPoint", "object": "testRunner", "arguments": { "failPoint": { "configureFailPoint": "failCommand", "mode": { "times": 2 }, "data": { "failCommands": [ "isMaster" ], "appName": "timeoutMonitorCheckTest", "blockConnection": true, "blockTimeMS": 1000 } } } }, { "name": "waitForEvent", "object": "testRunner", "arguments": { "event": "ServerMarkedUnknownEvent", "count": 1 } }, { "name": "waitForEvent", "object": "testRunner", "arguments": { "event": "PoolClearedEvent", "count": 1 } }, { "name": "insertMany", "object": "collection", "arguments": { "documents": [ { "_id": 3 }, { "_id": 4 } ] } }, { "name": "assertEventCount", "object": "testRunner", "arguments": { "event": "ServerMarkedUnknownEvent", "count": 1 } }, { "name": "assertEventCount", "object": "testRunner", "arguments": { "event": "PoolClearedEvent", "count": 1 } } ], "expectations": [ { "command_started_event": { "command": { "insert": "isMaster-timeout", "documents": [ { "_id": 1 }, { "_id": 2 } ] }, "command_name": "insert", "database_name": "sdam-tests" } }, { "command_started_event": { "command": { "insert": "isMaster-timeout", "documents": [ { "_id": 3 }, { "_id": 4 } ] }, "command_name": "insert", "database_name": "sdam-tests" } } ], "outcome": { "collection": { "data": [ { "_id": 1 }, { "_id": 2 }, { "_id": 3 }, { "_id": 4 } ] } } }, { "description": "Driver extends timeout while streaming", "clientOptions": { "retryWrites": false, "connectTimeoutMS": 250, "heartbeatFrequencyMS": 500, "appname": "extendsTimeoutTest" }, "operations": [ { "name": "insertMany", "object": "collection", "arguments": { "documents": [ { "_id": 1 }, { "_id": 2 } ] } }, { "name": "wait", "object": "testRunner", "arguments": { "ms": 2000 } }, { "name": "insertMany", "object": "collection", "arguments": { "documents": [ { "_id": 3 }, { "_id": 4 } ] } }, { "name": "assertEventCount", "object": "testRunner", "arguments": { "event": "ServerMarkedUnknownEvent", "count": 0 } }, { "name": "assertEventCount", "object": "testRunner", "arguments": { "event": "PoolClearedEvent", "count": 0 } } ], "expectations": [ { "command_started_event": { "command": { "insert": "isMaster-timeout", "documents": [ { "_id": 1 }, { "_id": 2 } ] }, "command_name": "insert", "database_name": "sdam-tests" } }, { "command_started_event": { "command": { "insert": "isMaster-timeout", "documents": [ { "_id": 3 }, { "_id": 4 } ] }, "command_name": "insert", "database_name": "sdam-tests" } } ], "outcome": { "collection": { "data": [ { "_id": 1 }, { "_id": 2 }, { "_id": 3 }, { "_id": 4 } ] } } } ] }
{ "pile_set_name": "Github" }
require 'test_helper' class StocksControllerTest < ActionController::TestCase setup do @stock = stocks(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:stocks) end test "should get new" do get :new assert_response :success end test "should create stock" do assert_difference('Stock.count') do post :create, stock: { article_id: @stock.article_id, user_id: @stock.user_id } end assert_redirected_to stock_path(assigns(:stock)) end test "should show stock" do get :show, id: @stock assert_response :success end test "should get edit" do get :edit, id: @stock assert_response :success end test "should update stock" do patch :update, id: @stock, stock: { article_id: @stock.article_id, user_id: @stock.user_id } assert_redirected_to stock_path(assigns(:stock)) end test "should destroy stock" do assert_difference('Stock.count', -1) do delete :destroy, id: @stock end assert_redirected_to stocks_path end end
{ "pile_set_name": "Github" }
<?php /* * Copyright 2005 - 2019 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonNotification\Domain\Repository; use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository; use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface; use PDO; use CentreonNotification\Domain\Entity\Escalation; use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector; use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait; class EscalationRepository extends ServiceEntityRepository implements PaginationRepositoryInterface { use CheckListOfIdsTrait; /** * {@inheritdoc} */ public static function entityClass(): string { return Escalation::class; } /** * Check list of IDs * * @return bool */ public function checkListOfIds(array $ids): bool { return $this->checkListOfIdsTrait($ids); } /** * {@inheritdoc} */ public function getPaginationList($filters = null, int $limit = null, int $offset = null, $ordering = []): array { $sql = 'SELECT SQL_CALC_FOUND_ROWS `esc_id`, `esc_name` ' . 'FROM `' . $this->getClassMetadata()->getTableName() . '`'; $collector = new StatementCollector(); $isWhere = false; if ($filters !== null) { if (array_key_exists('search', $filters) && $filters['search']) { $sql .= ' WHERE `esc_name` LIKE :search'; $collector->addValue(':search', "%{$filters['search']}%"); $isWhere = true; } if (array_key_exists('ids', $filters) && is_array($filters['ids'])) { $idsListKey = []; foreach ($filters['ids'] as $x => $id) { $key = ":id{$x}"; $idsListKey[] = $key; $collector->addValue($key, $id, PDO::PARAM_INT); unset($x, $id); } $sql .= $isWhere ? ' AND' : ' WHERE'; $sql .= ' `esc_id` IN (' . implode(',', $idsListKey) . ')'; } } $sql .= ' ORDER BY `esc_name` ASC'; if ($limit !== null) { $sql .= ' LIMIT :limit'; $collector->addValue(':limit', $limit, PDO::PARAM_INT); if ($offset !== null) { $sql .= ' OFFSET :offset'; $collector->addValue(':offset', $offset, PDO::PARAM_INT); } } $stmt = $this->db->prepare($sql); $collector->bind($stmt); $stmt->execute(); $result = []; while ($row = $stmt->fetch()) { $result[] = $this->getEntityPersister()->load($row); } return $result; } /** * {@inheritdoc} */ public function getPaginationListTotal(): int { return $this->db->numberRows(); } }
{ "pile_set_name": "Github" }
#!/bin/sh # # Since: June, 2018 # Author: dongbo.xiao@oracle.com # Description: script to start Apache HTTP Server # # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # # Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. # # Licensed under the Universal Permissive License v 1.0 as shown at http://oss.oracle.com/licenses/upl. # Generated configuration file CONFIG_FILE="config.txt" cat > $CONFIG_FILE <<-EOF [req] default_bits = 2048 prompt = no default_md = sha256 req_extensions=v3_req extensions=v3_req distinguished_name = dn [dn] C = US ST = CA L = Redwood Shores O = Oracle Corporation OU = Apache HTTP Server With Plugin CN = $VIRTUAL_HOST_NAME [v3_req] subjectAltName = @alt_names [alt_names] DNS.1 = $VIRTUAL_HOST_NAME DNS.2 = $VIRTUAL_HOST_NAME.us.oracle.com DNS.3 = $VIRTUAL_HOST_NAME.cloud.oracle.com DNS.4 = *.$VIRTUAL_HOST_NAME DNS.5 = localhost EOF echo "Generating certs for $VIRTUAL_HOST_NAME" # Generate our Private Key, CSR and Certificate # Use SHA-2 as SHA-1 is unsupported from Jan 1, 2017 openssl req -x509 -newkey rsa:2048 -sha256 -nodes -keyout "$SSL_CERT_KEY_FILE" -days 3650 -out "$SSL_CERT_FILE" -config "$CONFIG_FILE" # OPTIONAL - write an info to see the details of the generated crt openssl x509 -noout -fingerprint -text < "$SSL_CERT_FILE" > "$SSL_CERT_FILE.info" # Protect the key chmod 400 "$SSL_CERT_KEY_FILE" chmod 400 "$SSL_CERT_FILE.info"
{ "pile_set_name": "Github" }
/*CFG Analyzer, version 03/12/2007 A word in the intersection of L(G1) ... L(G2) is, e.g., "bcacb" of length 5 */ var hampiStringVar : 5; cfg S0 := "a" | "b" S0 "b" | "c" S0 "c" ; reg limit0 := fix(S0, 5); assert hampiStringVar in limit0; cfg S1 := B1 A1 | A1 C1 ; cfg A1 := "a" | "a" B1 | B1 "a" ; cfg C1 := "c" | C1 B1 ; cfg B1 := "b" "c" | "b" | B1 "c" ; reg limit1 := fix(S1, 5); assert hampiStringVar in limit1;
{ "pile_set_name": "Github" }
function eid=getintersecttri(tmppath) % % eid=getintersecttri(tmppath) % % get the IDs of self-intersecting elements from tetgen % call this when tetgen complains about self-intersection % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % % input: % tmppath: working dir, use mwpath('') in most cases % % output: % eid: an array of all intersecting surface elements, % one can read the corresponding node/elem by % [no,el]=readoff(mwpath('post_vmesh.off')); % % -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net) % exesuff=getexeext; exesuff=fallbackexeext(exesuff,'tetgen'); [status,str] = system(['"' mcpath('tetgen') exesuff '" -d "' ... tmppath filesep 'post_vmesh.poly"']); eid=[]; if(status==0) id=regexp(str, ' #([0-9]+) ', 'tokens'); for j=1:length(id) eid(end+1)=str2num(id{j}{1}); end end eid=unique_bc(eid);
{ "pile_set_name": "Github" }
// Copyright 2016 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. // This file contains tests for sizes. package types_test import ( "go/ast" "go/importer" "go/parser" "go/token" "go/types" "testing" ) // findStructType typechecks src and returns the first struct type encountered. func findStructType(t *testing.T, src string) *types.Struct { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "x.go", src, 0) if err != nil { t.Fatal(err) } info := types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} var conf types.Config _, err = conf.Check("x", fset, []*ast.File{f}, &info) if err != nil { t.Fatal(err) } for _, tv := range info.Types { if ts, ok := tv.Type.(*types.Struct); ok { return ts } } t.Fatalf("failed to find a struct type in src:\n%s\n", src) return nil } // Issue 16316 func TestMultipleSizeUse(t *testing.T) { const src = ` package main type S struct { i int b bool s string n int } ` ts := findStructType(t, src) sizes := types.StdSizes{WordSize: 4, MaxAlign: 4} if got := sizes.Sizeof(ts); got != 20 { t.Errorf("Sizeof(%v) with WordSize 4 = %d want 20", ts, got) } sizes = types.StdSizes{WordSize: 8, MaxAlign: 8} if got := sizes.Sizeof(ts); got != 40 { t.Errorf("Sizeof(%v) with WordSize 8 = %d want 40", ts, got) } } // Issue 16464 func TestAlignofNaclSlice(t *testing.T) { const src = ` package main var s struct { x *int y []byte } ` ts := findStructType(t, src) sizes := &types.StdSizes{WordSize: 4, MaxAlign: 8} var fields []*types.Var // Make a copy manually :( for i := 0; i < ts.NumFields(); i++ { fields = append(fields, ts.Field(i)) } offsets := sizes.Offsetsof(fields) if offsets[0] != 0 || offsets[1] != 4 { t.Errorf("OffsetsOf(%v) = %v want %v", ts, offsets, []int{0, 4}) } } func TestIssue16902(t *testing.T) { const src = ` package a import "unsafe" const _ = unsafe.Offsetof(struct{ x int64 }{}.x) ` fset := token.NewFileSet() f, err := parser.ParseFile(fset, "x.go", src, 0) if err != nil { t.Fatal(err) } info := types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} conf := types.Config{ Importer: importer.Default(), Sizes: &types.StdSizes{WordSize: 8, MaxAlign: 8}, } _, err = conf.Check("x", fset, []*ast.File{f}, &info) if err != nil { t.Fatal(err) } for _, tv := range info.Types { _ = conf.Sizes.Sizeof(tv.Type) _ = conf.Sizes.Alignof(tv.Type) } }
{ "pile_set_name": "Github" }
{ "type": "ancientwarfare:shapeless_research_recipe", "research": "advanced_siege_warfare", "ingredients": [ { "type": "ancientwarfare:item_count", "item": "ancientwarfarevehicle:fine_iron", "count": 5 }, { "type": "ancientwarfare:item_count", "item": "ancientwarfarevehicle:powder_case", "count": 2 }, { "item": "ancientwarfarevehicle:equipment_bay" } ], "result": { "type": "minecraft:item_nbt", "item": "ancientwarfarevehicle:spawner", "data": 9, "nbt": "{spawnData:{level:1}}" } }
{ "pile_set_name": "Github" }
// Copyright Joyent, Inc. and other Node contributors. // // 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. var assert = require('assert'); var events = require('../'); var e = new events.EventEmitter; assert.deepEqual(e._events, {}); e.setMaxListeners(5); assert.deepEqual(e._events, {});
{ "pile_set_name": "Github" }
AM_CPPFLAGS += \ -I$(top_srcdir)/cutil -I$(top_srcdir)/ccutil \ -I$(top_srcdir)/ccstruct -I$(top_srcdir)/dict \ -I$(top_srcdir)/viewer if VISIBILITY AM_CPPFLAGS += -DTESS_EXPORTS \ -fvisibility=hidden -fvisibility-inlines-hidden endif noinst_HEADERS = \ adaptive.h blobclass.h \ classify.h cluster.h clusttool.h cutoffs.h \ errorcounter.h \ featdefs.h float2int.h fpoint.h \ intfeaturedist.h intfeaturemap.h intfeaturespace.h \ intfx.h intmatcher.h intproto.h kdtree.h \ mastertrainer.h mf.h mfdefs.h mfoutline.h mfx.h \ normfeat.h normmatch.h \ ocrfeatures.h outfeat.h picofeat.h protos.h \ sampleiterator.h shapeclassifier.h shapetable.h \ tessclassifier.h trainingsample.h trainingsampleset.h if !USING_MULTIPLELIBS noinst_LTLIBRARIES = libtesseract_classify.la else lib_LTLIBRARIES = libtesseract_classify.la libtesseract_classify_la_LDFLAGS = -version-info $(GENERIC_LIBRARY_VERSION) libtesseract_classify_la_LIBADD = \ ../ccutil/libtesseract_ccutil.la \ ../cutil/libtesseract_cutil.la \ ../ccstruct/libtesseract_ccstruct.la \ ../dict/libtesseract_dict.la \ ../viewer/libtesseract_viewer.la endif libtesseract_classify_la_SOURCES = \ adaptive.cpp adaptmatch.cpp blobclass.cpp \ classify.cpp cluster.cpp clusttool.cpp cutoffs.cpp \ errorcounter.cpp \ featdefs.cpp float2int.cpp fpoint.cpp \ intfeaturedist.cpp intfeaturemap.cpp intfeaturespace.cpp \ intfx.cpp intmatcher.cpp intproto.cpp kdtree.cpp \ mastertrainer.cpp mf.cpp mfdefs.cpp mfoutline.cpp mfx.cpp \ normfeat.cpp normmatch.cpp \ ocrfeatures.cpp outfeat.cpp picofeat.cpp protos.cpp \ sampleiterator.cpp shapeclassifier.cpp shapetable.cpp \ tessclassifier.cpp trainingsample.cpp trainingsampleset.cpp
{ "pile_set_name": "Github" }
#include "stdafx.h" #include "actor.h" #include "WeaponMounted.h" #include "../xr_3da/camerabase.h" #include "ActorEffector.h" #include "CharacterPhysicsSupport.h" bool CActor::use_MountedWeapon(CHolderCustom* object) { // CHolderCustom* wpn =smart_cast<CHolderCustom*>(object); CHolderCustom* wpn =object; if(m_holder){ if(!wpn||(m_holder==wpn)){ m_holder->detach_Actor(); character_physics_support()->movement()->CreateCharacter(); m_holder=NULL; } return true; }else{ if(wpn){ Fvector center; Center(center); if(wpn->Use(Device.vCameraPosition, Device.vCameraDirection,center)){ if(wpn->attach_Actor(this)){ // destroy actor character character_physics_support()->movement()->DestroyCharacter(); PickupModeOff(); m_holder=wpn; if (pCamBobbing){ Cameras().RemoveCamEffector(eCEBobbing); pCamBobbing = NULL; } return true; } } } } return false; }
{ "pile_set_name": "Github" }
-- | Specification of Pos.Core.Coin module Test.Pos.Core.CoinSpec ( spec ) where import Universum import Test.Hspec (Expectation, Spec, anyErrorCall, describe, it, shouldBe, shouldSatisfy) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (Property, (.||.), (===)) import qualified Pos.Core.Common as C import Test.Pos.Core.Arbitrary as C import Test.Pos.Util.QuickCheck.Property (shouldThrowException, (.=.)) spec :: Spec spec = describe "Coin properties" $ do describe "Coin" $ do describe "Conversions" $ do prop unsafeIntegerCoinDesc overflowIntegerCausesError prop convertingCoinDesc coinToIntegralToCoin prop convertingWordDesc wordToCoinToWord prop convertingCoinIntegerDesc coinToIntegerToCoin prop overflowInCheckCoinErrorDesc overflowInCheckCoinError prop convertingIntegerDesc integerToCoinToInteger describe "unsafeAddcoin" $ do prop unsafeAddCoinDesc overflowInSumCausesError prop coinAdditionDesc coinAdditionWorks describe "unsafeSubCoin" $ do prop unsafeSubCoinDesc underflowInSubCausesError prop coinSubtractionDesc coinSubtractionWorks describe "unsafeMulCoin" $ do prop unsafeMulCoinDesc overflowInMulCausesError prop coinProductDesc coinProductWorks describe "sumCoin" $ do it "returns 0 as the sum of an empty list of coins" $ C.sumCoins [] `shouldBe` 0 prop sumCoinsNeverNegativeDesc sumCoinsIsNeverNegative describe "CoinPortion" $ do prop portionToDoubleToPortionDesc coinPortionToDoubleToPortion prop appliedPortionDownDesc appliedCoinPortionDown prop appliedPortionUpDesc appliedCoinPortionUp prop unsafeCoinPortionDesc overOrUnderflowDoubleCausesError where unsafeIntegerCoinDesc = "Converting an integer that is larger than 'maxCoinVal' into\ \ a coin causes a fatal exception" convertingCoinDesc = "Converting a coin to an integer and this integer to a coin\ \ changes nothing" convertingWordDesc = "Converting a 64-bit word into a coin and this coin to a 64-bit\ \ word changes nothing" overflowInCheckCoinErrorDesc = "Pass to mkCoin more than maxCoinVal coins, mkCoin must call error" convertingCoinIntegerDesc = "Converting a coin into an integer and this integer to a\ \ coin changes nothing" convertingIntegerDesc = "Converting a nonnegative integer into a coin and this coin\ \ to an integer changes nothing" unsafeAddCoinDesc = "Adding two coins whose sum causes an overflow will throw a\ \ fatal, uncatchable exception" coinAdditionDesc = "Coin addition is properly defined for two coins whose sum is less\ \ than 'maxBound :: Coin'" unsafeSubCoinDesc = "Subtracting a some amount of coins from a smaller amount will\ \ raise a fatal exception" coinSubtractionDesc = "Coin subtraction is properly defined when the subtrahend\ \ is less than the minuend" unsafeMulCoinDesc = "Multiplying two coins whose product causes an overflow will\ \ raise a fatal exception" coinProductDesc = "Coin product by an integer is properly defined for a coin and an\ \ integer whose product does not exceed 'maxBound :: Coin'" sumCoinsNeverNegativeDesc = "Adding a list of coins will never result in a negative\ \ value" portionToDoubleToPortionDesc = "Converting a coin portion into a double and this\ \ double to a coin portion changes nothing" appliedPortionDownDesc = "Applying a coin portion to a coin (down) via\ \ 'applyCoinPortionDown' and via 'floor' is the same" appliedPortionUpDesc = "Applying a coin portion to a coin (up) via\ \ 'applyCoinPortionUp' and via 'ceiling' is the same" unsafeCoinPortionDesc = "Converting a double outside the interval [0, 1] into a\ \ 'CoinPortion' will raise a fatal exception" ------------------------------------------------------------------------------------------ -- Coin ------------------------------------------------------------------------------------------ overflowInSumCausesError :: C.CoinPairOverflowSum -> Expectation overflowInSumCausesError = shouldThrowException (uncurry C.unsafeAddCoin . C.get2CSum) anyErrorCall coinAdditionWorks :: C.SafeCoinPairSum -> Property coinAdditionWorks = let longFunction = C.mkCoin . uncurry (+) . bimap C.unsafeGetCoin C.unsafeGetCoin . C.getPairSum in longFunction .=. (uncurry C.unsafeAddCoin . C.getPairSum) underflowInSubCausesError :: C.CoinPairOverflowSub -> Expectation underflowInSubCausesError = shouldThrowException (uncurry C.unsafeSubCoin . C.get2CSub) anyErrorCall coinSubtractionWorks :: C.SafeCoinPairSub -> Property coinSubtractionWorks = let longFunction = C.mkCoin . uncurry (-) . bimap C.unsafeGetCoin C.unsafeGetCoin . C.getPairSub in longFunction .=. (uncurry C.unsafeSubCoin . C.getPairSub) overflowInMulCausesError :: C.CoinPairOverflowMul -> Expectation overflowInMulCausesError = shouldThrowException (uncurry C.unsafeMulCoin . C.get2CMul) anyErrorCall coinProductWorks :: C.SafeCoinPairMul -> Property coinProductWorks = let longFunction = C.unsafeIntegerToCoin . uncurry (*) . bimap C.coinToInteger identity . C.getPairMul in longFunction .=. (uncurry C.unsafeMulCoin . C.getPairMul) overflowIntegerCausesError :: C.IntegerToCoinOverflow -> Expectation overflowIntegerCausesError = shouldThrowException (C.unsafeIntegerToCoin . C.getLargeInteger) anyErrorCall coinToIntegralToCoin :: C.Coin -> Property coinToIntegralToCoin = C.mkCoin . C.unsafeGetCoin .=. identity wordToCoinToWord :: Word64 -> Property wordToCoinToWord c = c > C.maxCoinVal .||. C.unsafeGetCoin (C.mkCoin c) === c overflowInCheckCoinError :: Expectation overflowInCheckCoinError = shouldSatisfy (C.checkCoin (C.Coin (C.maxCoinVal + 1)) :: Either Text ()) isLeft coinToIntegerToCoin :: C.Coin -> Property coinToIntegerToCoin = C.unsafeIntegerToCoin . C.coinToInteger .=. identity integerToCoinToInteger :: C.IntegerToCoinNoOverflow -> Property integerToCoinToInteger = C.Integer . C.coinToInteger . C.unsafeIntegerToCoin . C.getInteger .=. identity sumCoinsIsNeverNegative :: [C.Coin] -> Property sumCoinsIsNeverNegative = (>= 0) . C.sumCoins .=. const True ------------------------------------------------------------------------------------------ -- CoinPortion ------------------------------------------------------------------------------------------ overOrUnderflowDoubleCausesError :: C.LessThanZeroOrMoreThanOne -> Expectation overOrUnderflowDoubleCausesError = shouldThrowException (C.unsafeCoinPortionFromDouble . C.getDouble) anyErrorCall coinPortionToDoubleToPortion :: C.CoinPortion -> Property coinPortionToDoubleToPortion = C.unsafeCoinPortionFromDouble . C.coinPortionToDouble .=. identity appliedCoinPortionDown :: (C.CoinPortion, C.Coin) -> Property appliedCoinPortionDown = let applyViaRational (C.getCoinPortion -> p, C.unsafeGetCoin -> c) = C.mkCoin . floor $ (toRational p / toRational C.coinPortionDenominator) * (toRational c) in uncurry C.applyCoinPortionDown .=. applyViaRational appliedCoinPortionUp :: (C.CoinPortion, C.Coin) -> Property appliedCoinPortionUp = let applyViaRational (C.getCoinPortion -> p, C.unsafeGetCoin -> c) = C.mkCoin . ceiling $ (toRational p / toRational C.coinPortionDenominator) * (toRational c) in uncurry C.applyCoinPortionUp .=. applyViaRational
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xalan.internal.xsltc.trax; import com.sun.org.apache.xalan.internal.xsltc.runtime.Constants; import com.sun.org.apache.xerces.internal.util.XMLSymbols; import java.util.ArrayList; import java.util.List; import java.util.Stack; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.sun.org.apache.xalan.internal.xsltc.runtime.Constants; import jdk.xml.internal.JdkXmlUtils; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.Locator2; /** * @author G. Todd Miller * @author Sunitha Reddy * @author Huizhe Wang * @LastModified: Nov 2017 */ public class SAX2DOM implements ContentHandler, LexicalHandler, Constants { private Node _root = null; private Document _document = null; private Node _nextSibling = null; private Stack<Node> _nodeStk = new Stack<>(); private List<String> _namespaceDecls = null; private Node _lastSibling = null; private Locator locator = null; private boolean needToSetDocumentInfo = true; //Replace StringBuffer with StringBuilder now that we no long support jdk1.4 private StringBuilder _textBuffer = new StringBuilder(); private Node _nextSiblingCache = null; /** * JAXP document builder factory. Create a single instance and use * synchronization because the Javadoc is not explicit about * thread safety. */ private DocumentBuilderFactory _factory; private boolean _internal = true; public SAX2DOM(boolean overrideDefaultParser) throws ParserConfigurationException { _document = createDocument(overrideDefaultParser); _root = _document; } public SAX2DOM(Node root, Node nextSibling, boolean overrideDefaultParser) throws ParserConfigurationException { _root = root; if (root instanceof Document) { _document = (Document)root; } else if (root != null) { _document = root.getOwnerDocument(); } else { _document = createDocument(overrideDefaultParser); _root = _document; } _nextSibling = nextSibling; } public SAX2DOM(Node root, boolean overrideDefaultParser) throws ParserConfigurationException { this(root, null, overrideDefaultParser); } public Node getDOM() { return _root; } public void characters(char[] ch, int start, int length) { // Ignore text nodes of length 0 if (length == 0) { return; } final Node last = _nodeStk.peek(); // No text nodes can be children of root (DOM006 exception) if (last != _document) { _nextSiblingCache = _nextSibling; _textBuffer.append(ch, start, length); } } private void appendTextNode() { if (_textBuffer.length() > 0) { final Node last = _nodeStk.peek(); if (last == _root && _nextSiblingCache != null) { _lastSibling = last.insertBefore(_document.createTextNode(_textBuffer.toString()), _nextSiblingCache); } else { _lastSibling = last.appendChild(_document.createTextNode(_textBuffer.toString())); } _textBuffer.setLength(0); } } public void startDocument() { _nodeStk.push(_root); } public void endDocument() { _nodeStk.pop(); } private void setDocumentInfo() { //try to set document version if (locator == null) return; try{ _document.setXmlVersion(((Locator2)locator).getXMLVersion()); }catch(ClassCastException e){} } public void startElement(String namespace, String localName, String qName, Attributes attrs) { appendTextNode(); if (needToSetDocumentInfo) { setDocumentInfo(); needToSetDocumentInfo = false; } final Element tmp = _document.createElementNS(namespace, qName); // Add namespace declarations first if (_namespaceDecls != null) { final int nDecls = _namespaceDecls.size(); for (int i = 0; i < nDecls; i++) { final String prefix = _namespaceDecls.get(i++); if (prefix == null || prefix.equals(EMPTYSTRING)) { tmp.setAttributeNS(XMLNS_URI, XMLNS_PREFIX, _namespaceDecls.get(i)); } else { tmp.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix, _namespaceDecls.get(i)); } } _namespaceDecls.clear(); } // Add attributes to element /* final int nattrs = attrs.getLength(); for (int i = 0; i < nattrs; i++) { if (attrs.getLocalName(i) == null) { tmp.setAttribute(attrs.getQName(i), attrs.getValue(i)); } else { tmp.setAttributeNS(attrs.getURI(i), attrs.getQName(i), attrs.getValue(i)); } } */ // Add attributes to element final int nattrs = attrs.getLength(); for (int i = 0; i < nattrs; i++) { // checking if Namespace processing is being done String attQName = attrs.getQName(i); String attURI = attrs.getURI(i); String type = (attrs.getType(i) == null) ? XMLSymbols.fCDATASymbol : attrs.getType(i); if (attrs.getLocalName(i).equals("")) { tmp.setAttribute(attQName, attrs.getValue(i)); if (type.equals("ID")) { tmp.setIdAttribute(attQName, true); } } else { tmp.setAttributeNS(attURI, attQName, attrs.getValue(i)); if (type.equals("ID")) { tmp.setIdAttributeNS(attURI, attrs.getLocalName(i), true); } } } // Append this new node onto current stack node Node last = _nodeStk.peek(); // If the SAX2DOM is created with a non-null next sibling node, // insert the result nodes before the next sibling under the root. if (last == _root && _nextSibling != null) last.insertBefore(tmp, _nextSibling); else last.appendChild(tmp); // Push this node onto stack _nodeStk.push(tmp); _lastSibling = null; } public void endElement(String namespace, String localName, String qName) { appendTextNode(); _nodeStk.pop(); _lastSibling = null; } public void startPrefixMapping(String prefix, String uri) { if (_namespaceDecls == null) { _namespaceDecls = new ArrayList<>(2); } _namespaceDecls.add(prefix); _namespaceDecls.add(uri); } public void endPrefixMapping(String prefix) { // do nothing } /** * This class is only used internally so this method should never * be called. */ public void ignorableWhitespace(char[] ch, int start, int length) { } /** * adds processing instruction node to DOM. */ public void processingInstruction(String target, String data) { appendTextNode(); final Node last = _nodeStk.peek(); ProcessingInstruction pi = _document.createProcessingInstruction( target, data); if (pi != null){ if (last == _root && _nextSibling != null) last.insertBefore(pi, _nextSibling); else last.appendChild(pi); _lastSibling = pi; } } /** * This class is only used internally so this method should never * be called. */ public void setDocumentLocator(Locator locator) { this.locator = locator; } /** * This class is only used internally so this method should never * be called. */ public void skippedEntity(String name) { } /** * Lexical Handler method to create comment node in DOM tree. */ public void comment(char[] ch, int start, int length) { appendTextNode(); final Node last = _nodeStk.peek(); Comment comment = _document.createComment(new String(ch,start,length)); if (comment != null){ if (last == _root && _nextSibling != null) last.insertBefore(comment, _nextSibling); else last.appendChild(comment); _lastSibling = comment; } } // Lexical Handler methods- not implemented public void startCDATA() { } public void endCDATA() { } public void startEntity(java.lang.String name) { } public void endDTD() { } public void endEntity(String name) { } public void startDTD(String name, String publicId, String systemId) throws SAXException {} private Document createDocument(boolean overrideDefaultParser) throws ParserConfigurationException { if (_factory == null) { _factory = JdkXmlUtils.getDOMFactory(overrideDefaultParser); _internal = true; if (!(_factory instanceof com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl)) { _internal = false; } } Document doc; if (_internal) { //default implementation is thread safe doc = _factory.newDocumentBuilder().newDocument(); } else { synchronized(SAX2DOM.class) { doc = _factory.newDocumentBuilder().newDocument(); } } return doc; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- ################################################################################ # THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # # Please refer to the README for information about making permanent changes. # ################################################################################ --> <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="Globals"> <_PropertySheetDisplayName>filemq Common Settings</_PropertySheetDisplayName> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <RunCodeAnalysis>false</RunCodeAnalysis> </PropertyGroup> <!-- Configuration --> <ItemDefinitionGroup> <PreBuildEvent> <Command>copy $(BuildRoot)platform.h $(RepoRoot)include\</Command> </PreBuildEvent> <ClCompile> <AdditionalIncludeDirectories>$(RepoRoot)include\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <CompileAs>CompileAsCpp</CompileAs> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <EnablePREfast>false</EnablePREfast> <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;BASE_THREADSAFE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions Condition="'$(ConfigurationType)' == 'StaticLibrary'">LIBFILEMQ_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions Condition="'$(ConfigurationType)' == 'DynamicLibrary'">LIBFILEMQ_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ClCompile> <Link> <AdditionalDependencies>Rpcrt4.lib;Ws2_32.lib;Iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <!-- Dependencies --> <ImportGroup Label="PropertySheets"> <Import Project="$(SolutionDir)libzmq.import.props" /> <Import Project="$(SolutionDir)czmq.import.props" /> </ImportGroup> <PropertyGroup Condition="'$(DefaultLinkage)' == 'dynamic'"> <Linkage-libzmq>dynamic</Linkage-libzmq> <Linkage-czmq>dynamic</Linkage-czmq> </PropertyGroup> <PropertyGroup Condition="'$(DefaultLinkage)' == 'ltcg'"> <Linkage-libzmq>ltcg</Linkage-libzmq> <Linkage-czmq>ltcg</Linkage-czmq> </PropertyGroup> <PropertyGroup Condition="'$(DefaultLinkage)' == 'static'"> <Linkage-libzmq>static</Linkage-libzmq> <Linkage-czmq>static</Linkage-czmq> </PropertyGroup> <!-- Messages --> <Target Name="CustomInfo" BeforeTargets="PrepareForBuild"> <Message Text="Will copy $(BuildRoot)platform.h -&gt; $(RepoRoot)include\platform.h" Importance="high"/> </Target> <Target Name="LinkageInfo" BeforeTargets="PrepareForBuild"> <Message Text="Linkage-libzmq : $(Linkage-libzmq)" Importance="high"/> <Message Text="Linkage-czmq : $(Linkage-czmq)" Importance="high"/> </Target> <!-- ################################################################################ # THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # # Please refer to the README for information about making permanent changes. # ################################################################################ --> </Project>
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace Location; use Location\Distance\DistanceInterface; use Location\Formatter\Polygon\FormatterInterface; /** * Polygon Implementation * * @author Paul Vidal <paul.vidal.lujan@gmail.com> * @author Marcus Jaschen <mjaschen@gmail.com> */ class Polygon implements GeometryInterface { use GetBoundsTrait; /** * @var Coordinate[] */ protected $points = []; /** * @param Coordinate $point * * @return void */ public function addPoint(Coordinate $point): void { $this->points[] = $point; } /** * @param array $points */ public function addPoints(array $points): void { foreach ($points as $point) { $this->addPoint($point); } } /** * @return Coordinate[] */ public function getPoints(): array { return $this->points; } /** * Return all polygon point's latitudes. * * @return float[] */ public function getLats(): array { $lats = []; foreach ($this->points as $point) { /** @var Coordinate $point */ $lats[] = $point->getLat(); } return $lats; } /** * Return all polygon point's longitudes. * * @return float[] */ public function getLngs(): array { $lngs = []; foreach ($this->points as $point) { /** @var Coordinate $point */ $lngs[] = $point->getLng(); } return $lngs; } /** * @return int */ public function getNumberOfPoints(): int { return count($this->points); } /** * @param FormatterInterface $formatter * * @return string */ public function format(FormatterInterface $formatter): string { return $formatter->format($this); } /** * @return Line[] */ public function getSegments(): array { $length = count($this->points); $segments = []; if ($length <= 1) { return $segments; } for ($i = 1; $i < $length; $i++) { $segments[] = new Line($this->points[$i - 1], $this->points[$i]); } // to close the polygon we have to add the final segment between // the last point and the first point $segments[] = new Line($this->points[$i - 1], $this->points[0]); return $segments; } /** * Determine if given geometry is contained inside the polygon. This is * assumed to be true, if each point of the geometry is inside the polygon. * * Edge cases: * * - it's not detected when a line between two points is outside the polygon * - @see contains() for more restrictions * * @param GeometryInterface $geometry * * @return boolean */ public function containsGeometry(GeometryInterface $geometry): bool { $geometryInPolygon = true; foreach ($geometry->getPoints() as $point) { $geometryInPolygon = $geometryInPolygon && $this->contains($point); } return $geometryInPolygon; } /** * Determine if given point is contained inside the polygon. Uses the PNPOLY * algorithm by W. Randolph Franklin. Therfore some edge cases may not give the * expected results, e. g. if the point resides on the polygon boundary. * * @see https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html * * For special cases this calculation leads to wrong results: * * - if the polygons spans over the longitude boundaries at 180/-180 degrees * * @param Coordinate $point * * @return bool */ public function contains(Coordinate $point): bool { $numberOfPoints = $this->getNumberOfPoints(); $polygonLats = $this->getLats(); $polygonLngs = $this->getLngs(); $polygonContainsPoint = false; for ($node = 0, $altNode = ($numberOfPoints - 1); $node < $numberOfPoints; $altNode = $node++) { $condition = ($polygonLngs[$node] > $point->getLng()) !== ($polygonLngs[$altNode] > $point->getLng()) && ($point->getLat() < ($polygonLats[$altNode] - $polygonLats[$node]) * ($point->getLng() - $polygonLngs[$node]) / ($polygonLngs[$altNode] - $polygonLngs[$node]) + $polygonLats[$node]); if ($condition) { $polygonContainsPoint = ! $polygonContainsPoint; } } return $polygonContainsPoint; } /** * Calculates the polygon perimeter. * * @param DistanceInterface $calculator instance of distance calculation class * * @return float */ public function getPerimeter(DistanceInterface $calculator): float { $perimeter = 0.0; if (count($this->points) < 2) { return $perimeter; } foreach ($this->getSegments() as $segment) { $perimeter += $segment->getLength($calculator); } return $perimeter; } /** * Calculates the polygon area. * * This algorithm gives inaccurate results as it ignores * ellipsoid parameters other than to arithmetic mean radius. * The error should be < 1 % for small areas. * * @return float */ public function getArea(): float { $area = 0; if ($this->getNumberOfPoints() <= 2) { return $area; } $referencePoint = $this->points[0]; $radius = $referencePoint->getEllipsoid()->getArithmeticMeanRadius(); $segments = $this->getSegments(); foreach ($segments as $segment) { /** @var Coordinate $point1 */ $point1 = $segment->getPoint1(); /** @var Coordinate $point2 */ $point2 = $segment->getPoint2(); $x1 = deg2rad($point1->getLng() - $referencePoint->getLng()) * cos(deg2rad($point1->getLat())); $y1 = deg2rad($point1->getLat() - $referencePoint->getLat()); $x2 = deg2rad($point2->getLng() - $referencePoint->getLng()) * cos(deg2rad($point2->getLat())); $y2 = deg2rad($point2->getLat() - $referencePoint->getLat()); $area += ($x2 * $y1 - $x1 * $y2); } $area *= 0.5 * $radius ** 2; return (float)abs($area); } /** * Create a new polygon with reversed order of points, i. e. reversed * polygon direction. * * @return Polygon */ public function getReverse(): Polygon { $reversed = new self(); foreach (array_reverse($this->points) as $point) { $reversed->addPoint($point); } return $reversed; } }
{ "pile_set_name": "Github" }
var searchData= [ ['g_5fregistry',['g_Registry',['../classFling_1_1Engine.html#a57187f219f0d07f63227723f0a4d9d77',1,'Fling::Engine']]], ['gamma',['Gamma',['../structFling_1_1CameraInfoUbo.html#a1be655f49401cdcf26d428fb1edf0037',1,'Fling::CameraInfoUbo']]] ];
{ "pile_set_name": "Github" }
/* * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_CI_CICONSTANT_HPP #define SHARE_VM_CI_CICONSTANT_HPP #include "ci/ciClassList.hpp" #include "ci/ciNullObject.hpp" // ciConstant // // This class represents a constant value. class ciConstant { friend class VMStructs; private: friend class ciEnv; friend class ciField; BasicType _type; union { jint _int; jlong _long; jfloat _float; jdouble _double; ciObject* _object; } _value; public: ciConstant() { _type = T_ILLEGAL; _value._long = -1; } ciConstant(BasicType type, jint value) { assert(type != T_LONG && type != T_DOUBLE && type != T_FLOAT, "using the wrong ciConstant constructor"); _type = type; _value._int = value; } ciConstant(jlong value) { _type = T_LONG; _value._long = value; } ciConstant(jfloat value) { _type = T_FLOAT; _value._float = value; } ciConstant(jdouble value) { _type = T_DOUBLE; _value._double = value; } ciConstant(BasicType type, ciObject* p) { _type = type; _value._object = p; } BasicType basic_type() const { return _type; } jboolean as_boolean() { assert(basic_type() == T_BOOLEAN, "wrong type"); return (jboolean)_value._int; } jchar as_char() { assert(basic_type() == T_CHAR, "wrong type"); return (jchar)_value._int; } jbyte as_byte() { assert(basic_type() == T_BYTE, "wrong type"); return (jbyte)_value._int; } jshort as_short() { assert(basic_type() == T_SHORT, "wrong type"); return (jshort)_value._int; } jint as_int() { assert(basic_type() == T_BOOLEAN || basic_type() == T_CHAR || basic_type() == T_BYTE || basic_type() == T_SHORT || basic_type() == T_INT, "wrong type"); return _value._int; } jlong as_long() { assert(basic_type() == T_LONG, "wrong type"); return _value._long; } jfloat as_float() { assert(basic_type() == T_FLOAT, "wrong type"); return _value._float; } jdouble as_double() { assert(basic_type() == T_DOUBLE, "wrong type"); return _value._double; } ciObject* as_object() const { assert(basic_type() == T_OBJECT || basic_type() == T_ARRAY, "wrong type"); return _value._object; } bool is_null_or_zero() const { if (!is_java_primitive(basic_type())) { return as_object()->is_null_object(); } else if (type2size[basic_type()] == 1) { // treat float bits as int, to avoid comparison with -0 and NaN return (_value._int == 0); } else if (type2size[basic_type()] == 2) { // treat double bits as long, to avoid comparison with -0 and NaN return (_value._long == 0); } else { return false; } } bool is_valid() const { return basic_type() != T_ILLEGAL; } // Debugging output void print(); }; #endif // SHARE_VM_CI_CICONSTANT_HPP
{ "pile_set_name": "Github" }
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- namespace think; class View { // 视图实例 protected static $instance; // 模板引擎实例 public $engine; // 模板变量 protected $data = []; // 用于静态赋值的模板变量 protected static $var = []; // 视图输出替换 protected $replace = []; /** * 构造函数 * @access public * @param array $engine 模板引擎参数 * @param array $replace 字符串替换参数 */ public function __construct($engine = [], $replace = []) { // 初始化模板引擎 $this->engine($engine); // 基础替换字符串 $request = Request::instance(); $base = $request->root(); $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base; if ('' != $root) { $root = '/' . ltrim($root, '/'); } $baseReplace = [ '__ROOT__' => $root, '__URL__' => $base . '/' . $request->module() . '/' . Loader::parseName($request->controller()), '__STATIC__' => $root . '/static', '__CSS__' => $root . '/static/css', '__JS__' => $root . '/static/js', ]; $this->replace = array_merge($baseReplace, (array) $replace); } /** * 初始化视图 * @access public * @param array $engine 模板引擎参数 * @param array $replace 字符串替换参数 * @return object */ public static function instance($engine = [], $replace = []) { if (is_null(self::$instance)) { self::$instance = new self($engine, $replace); } return self::$instance; } /** * 模板变量静态赋值 * @access public * @param mixed $name 变量名 * @param mixed $value 变量值 * @return void */ public static function share($name, $value = '') { if (is_array($name)) { self::$var = array_merge(self::$var, $name); } else { self::$var[$name] = $value; } } /** * 模板变量赋值 * @access public * @param mixed $name 变量名 * @param mixed $value 变量值 * @return $this */ public function assign($name, $value = '') { if (is_array($name)) { $this->data = array_merge($this->data, $name); } else { $this->data[$name] = $value; } return $this; } /** * 设置当前模板解析的引擎 * @access public * @param array|string $options 引擎参数 * @return $this */ public function engine($options = []) { if (is_string($options)) { $type = $options; $options = []; } else { $type = !empty($options['type']) ? $options['type'] : 'Think'; } $class = false !== strpos($type, '\\') ? $type : '\\think\\view\\driver\\' . ucfirst($type); if (isset($options['type'])) { unset($options['type']); } $this->engine = new $class($options); return $this; } /** * 配置模板引擎 * @access private * @param string|array $name 参数名 * @param mixed $value 参数值 * @return $this */ public function config($name, $value = null) { $this->engine->config($name, $value); return $this; } /** * 解析和获取模板内容 用于输出 * @param string $template 模板文件名或者内容 * @param array $vars 模板输出变量 * @param array $replace 替换内容 * @param array $config 模板参数 * @param bool $renderContent 是否渲染内容 * @return string * @throws Exception */ public function fetch($template = '', $vars = [], $replace = [], $config = [], $renderContent = false) { // 模板变量 $vars = array_merge(self::$var, $this->data, $vars); // 页面缓存 ob_start(); ob_implicit_flush(0); // 渲染输出 try { $method = $renderContent ? 'display' : 'fetch'; // 允许用户自定义模板的字符串替换 $replace = array_merge($this->replace, $replace, $this->engine->config('tpl_replace_string')); $this->engine->config('tpl_replace_string', $replace); $this->engine->$method($template, $vars, $config); } catch (\Exception $e) { ob_end_clean(); throw $e; } // 获取并清空缓存 $content = ob_get_clean(); // 内容过滤标签 Hook::listen('view_filter', $content); return $content; } /** * 视图内容替换 * @access public * @param string|array $content 被替换内容(支持批量替换) * @param string $replace 替换内容 * @return $this */ public function replace($content, $replace = '') { if (is_array($content)) { $this->replace = array_merge($this->replace, $content); } else { $this->replace[$content] = $replace; } return $this; } /** * 渲染内容输出 * @access public * @param string $content 内容 * @param array $vars 模板输出变量 * @param array $replace 替换内容 * @param array $config 模板参数 * @return mixed */ public function display($content, $vars = [], $replace = [], $config = []) { return $this->fetch($content, $vars, $replace, $config, true); } /** * 模板变量赋值 * @access public * @param string $name 变量名 * @param mixed $value 变量值 */ public function __set($name, $value) { $this->data[$name] = $value; } /** * 取得模板显示变量的值 * @access protected * @param string $name 模板变量 * @return mixed */ public function __get($name) { return $this->data[$name]; } /** * 检测模板变量是否设置 * @access public * @param string $name 模板变量名 * @return bool */ public function __isset($name) { return isset($this->data[$name]); } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <title>moving modified IFRAME in document (original page about:blank, document.write modification)</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <link rel="help" href="https://html.spec.whatwg.org/#iframe-load-event-steps"> <iframe src="about:blank"></iframe> <div id="target"></div> <script> setup({ single_test: true }); onload = function() { var ifr = document.getElementsByTagName('iframe')[0]; ifr.contentDocument.open(); ifr.contentDocument.write('Modified document'); ifr.contentDocument.close(); setTimeout(function() { ifr.onload = function() { assert_equals(ifr.contentDocument.body.textContent.indexOf('Modified'), -1); done(); }; document.getElementById('target').appendChild(ifr); }, 100); } </script>
{ "pile_set_name": "Github" }
//>>built define("dojox/charting/action2d/Shake", ["dojo/_base/connect", "dojo/_base/declare", "./PlotAction", "dojo/fx", "dojo/fx/easing", "dojox/gfx/matrix", "dojox/gfx/fx"], function(Connect, declare, PlotAction, df, dfe, m, gf){ /*===== dojo.declare("dojox.charting.action2d.__ShakeCtorArgs", dojox.charting.action2d.__PlotActionCtorArgstorArgs, { // summary: // Additional arguments for highlighting actions. // shift: Number? // The amount in pixels to shift the pie slice. Default is 3. shift: 3 }); =====*/ var DEFAULT_SHIFT = 3; return declare("dojox.charting.action2d.Shake", dojox.charting.action2d.PlotAction, { // summary: // Create a shaking action for use on an element in a chart. // the data description block for the widget parser defaultParams: { duration: 400, // duration of the action in ms easing: dfe.backOut, // easing for the action shiftX: DEFAULT_SHIFT, // shift of the element along the X axis shiftY: DEFAULT_SHIFT // shift of the element along the Y axis }, optionalParams: {}, // no optional parameters constructor: function(chart, plot, kwArgs){ // summary: // Create the shaking action and connect it to the plot. // chart: dojox.charting.Chart // The chart this action belongs to. // plot: String? // The plot this action is attached to. If not passed, "default" is assumed. // kwArgs: dojox.charting.action2d.__ShakeCtorArgs? // Optional keyword arguments object for setting parameters. if(!kwArgs){ kwArgs = {}; } this.shiftX = typeof kwArgs.shiftX == "number" ? kwArgs.shiftX : DEFAULT_SHIFT; this.shiftY = typeof kwArgs.shiftY == "number" ? kwArgs.shiftY : DEFAULT_SHIFT; this.connect(); }, process: function(o){ // summary: // Process the action on the given object. // o: dojox.gfx.Shape // The object on which to process the slice moving action. if(!o.shape || !(o.type in this.overOutEvents)){ return; } var runName = o.run.name, index = o.index, vector = [], anim, shiftX = o.type == "onmouseover" ? this.shiftX : -this.shiftX, shiftY = o.type == "onmouseover" ? this.shiftY : -this.shiftY; if(runName in this.anim){ anim = this.anim[runName][index]; }else{ this.anim[runName] = {}; } if(anim){ anim.action.stop(true); }else{ this.anim[runName][index] = anim = {}; } var kwArgs = { shape: o.shape, duration: this.duration, easing: this.easing, transform: [ {name: "translate", start: [this.shiftX, this.shiftY], end: [0, 0]}, m.identity ] }; if(o.shape){ vector.push(gf.animateTransform(kwArgs)); } if(o.oultine){ kwArgs.shape = o.outline; vector.push(gf.animateTransform(kwArgs)); } if(o.shadow){ kwArgs.shape = o.shadow; vector.push(gf.animateTransform(kwArgs)); } if(!vector.length){ delete this.anim[runName][index]; return; } anim.action = df.combine(vector); if(o.type == "onmouseout"){ Connect.connect(anim.action, "onEnd", this, function(){ if(this.anim[runName]){ delete this.anim[runName][index]; } }); } anim.action.play(); } }); });
{ "pile_set_name": "Github" }
{ "name": "methods", "description": "HTTP methods that node supports", "version": "1.1.2", "contributors": [ "Douglas Christopher Wilson <doug@somethingdoug.com>", "Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)", "TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)" ], "license": "MIT", "repository": "jshttp/methods", "devDependencies": { "istanbul": "0.4.1", "mocha": "1.21.5" }, "files": [ "index.js", "HISTORY.md", "LICENSE" ], "engines": { "node": ">= 0.6" }, "scripts": { "test": "mocha --reporter spec --bail --check-leaks test/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, "browser": { "http": false }, "keywords": [ "http", "methods" ] }
{ "pile_set_name": "Github" }
/* Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. */ #include <common.hpp> class Solution { public: int removeDuplicates(vector<int> &nums) { if (nums.size() <= 2) { return nums.size(); } int i = 2; for (int j = i; j < nums.size(); ++j) { if (nums[j] > nums[i - 2]) { nums[i++] = nums[j]; } } return i; } }; //time:O(N) //space:O(1) //a better format /* int removeDuplicates(vector<int> &nums) { int i = 0; for (int n : nums) if (i < 2 || n > nums[i - 2]) nums[i++] = n; return i; } */
{ "pile_set_name": "Github" }
#!/bin/sh /etc/rc.common # Copyright (C) 2006 OpenWrt.org START=11 start() { for CONF in /etc/sysctl.conf /etc/sysctl.d/*.conf; do [ -f "$CONF" ] && sysctl -p "$CONF" -e >&- done }
{ "pile_set_name": "Github" }
Sam Alba <sam@docker.com> (@samalba) Joffrey Fuhrer <joffrey@docker.com> (@shin-) Ken Cochrane <ken@docker.com> (@kencochrane) Vincent Batts <vbatts@redhat.com> (@vbatts) Olivier Gambier <olivier@docker.com> (@dmp42)
{ "pile_set_name": "Github" }
## Process this file with automake to produce Makefile.in CC=$(CC_FOR_BUILD) LIBTOOL = @LIBTOOL@ --tag=CC noinst_PROGRAMS = testlk testlk_SOURCES = testlk.c testlk_CFLAGS=$(CFLAGS_FOR_BUILD) testlk_CPPFLAGS=$(CPPFLAGS_FOR_BUILD) testlk_LDFLAGS=$(LDFLAGS_FOR_BUILD) MAINTAINERCLEANFILES = Makefile.in
{ "pile_set_name": "Github" }
// Copyright 2014 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 http2 implements the HTTP/2 protocol. // // This package is low-level and intended to be used directly by very // few people. Most users will use it indirectly through the automatic // use by the net/http package (from Go 1.6 and later). // For use in earlier Go versions see ConfigureServer. (Transport support // requires Go 1.6 or later) // // See https://http2.github.io/ for more information on HTTP/2. // // See https://http2.golang.org/ for a test server running this code. // package http2 // import "golang.org/x/net/http2" import ( "bufio" "crypto/tls" "fmt" "io" "net/http" "os" "sort" "strconv" "strings" "sync" "golang.org/x/net/http/httpguts" ) var ( VerboseLogs bool logFrameWrites bool logFrameReads bool inTests bool ) func init() { e := os.Getenv("GODEBUG") if strings.Contains(e, "http2debug=1") { VerboseLogs = true } if strings.Contains(e, "http2debug=2") { VerboseLogs = true logFrameWrites = true logFrameReads = true } } const ( // ClientPreface is the string that must be sent by new // connections from clients. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" // SETTINGS_MAX_FRAME_SIZE default // http://http2.github.io/http2-spec/#rfc.section.6.5.2 initialMaxFrameSize = 16384 // NextProtoTLS is the NPN/ALPN protocol negotiated during // HTTP/2's TLS setup. NextProtoTLS = "h2" // http://http2.github.io/http2-spec/#SettingValues initialHeaderTableSize = 4096 initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size defaultMaxReadFrameSize = 1 << 20 ) var ( clientPreface = []byte(ClientPreface) ) type streamState int // HTTP/2 stream states. // // See http://tools.ietf.org/html/rfc7540#section-5.1. // // For simplicity, the server code merges "reserved (local)" into // "half-closed (remote)". This is one less state transition to track. // The only downside is that we send PUSH_PROMISEs slightly less // liberally than allowable. More discussion here: // https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html // // "reserved (remote)" is omitted since the client code does not // support server push. const ( stateIdle streamState = iota stateOpen stateHalfClosedLocal stateHalfClosedRemote stateClosed ) var stateName = [...]string{ stateIdle: "Idle", stateOpen: "Open", stateHalfClosedLocal: "HalfClosedLocal", stateHalfClosedRemote: "HalfClosedRemote", stateClosed: "Closed", } func (st streamState) String() string { return stateName[st] } // Setting is a setting parameter: which setting it is, and its value. type Setting struct { // ID is which setting is being set. // See http://http2.github.io/http2-spec/#SettingValues ID SettingID // Val is the value. Val uint32 } func (s Setting) String() string { return fmt.Sprintf("[%v = %d]", s.ID, s.Val) } // Valid reports whether the setting is valid. func (s Setting) Valid() error { // Limits and error codes from 6.5.2 Defined SETTINGS Parameters switch s.ID { case SettingEnablePush: if s.Val != 1 && s.Val != 0 { return ConnectionError(ErrCodeProtocol) } case SettingInitialWindowSize: if s.Val > 1<<31-1 { return ConnectionError(ErrCodeFlowControl) } case SettingMaxFrameSize: if s.Val < 16384 || s.Val > 1<<24-1 { return ConnectionError(ErrCodeProtocol) } } return nil } // A SettingID is an HTTP/2 setting as defined in // http://http2.github.io/http2-spec/#iana-settings type SettingID uint16 const ( SettingHeaderTableSize SettingID = 0x1 SettingEnablePush SettingID = 0x2 SettingMaxConcurrentStreams SettingID = 0x3 SettingInitialWindowSize SettingID = 0x4 SettingMaxFrameSize SettingID = 0x5 SettingMaxHeaderListSize SettingID = 0x6 ) var settingName = map[SettingID]string{ SettingHeaderTableSize: "HEADER_TABLE_SIZE", SettingEnablePush: "ENABLE_PUSH", SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS", SettingInitialWindowSize: "INITIAL_WINDOW_SIZE", SettingMaxFrameSize: "MAX_FRAME_SIZE", SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE", } func (s SettingID) String() string { if v, ok := settingName[s]; ok { return v } return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s)) } // validWireHeaderFieldName reports whether v is a valid header field // name (key). See httpguts.ValidHeaderName for the base rules. // // Further, http2 says: // "Just as in HTTP/1.x, header field names are strings of ASCII // characters that are compared in a case-insensitive // fashion. However, header field names MUST be converted to // lowercase prior to their encoding in HTTP/2. " func validWireHeaderFieldName(v string) bool { if len(v) == 0 { return false } for _, r := range v { if !httpguts.IsTokenRune(r) { return false } if 'A' <= r && r <= 'Z' { return false } } return true } func httpCodeString(code int) string { switch code { case 200: return "200" case 404: return "404" } return strconv.Itoa(code) } // from pkg io type stringWriter interface { WriteString(s string) (n int, err error) } // A gate lets two goroutines coordinate their activities. type gate chan struct{} func (g gate) Done() { g <- struct{}{} } func (g gate) Wait() { <-g } // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed). type closeWaiter chan struct{} // Init makes a closeWaiter usable. // It exists because so a closeWaiter value can be placed inside a // larger struct and have the Mutex and Cond's memory in the same // allocation. func (cw *closeWaiter) Init() { *cw = make(chan struct{}) } // Close marks the closeWaiter as closed and unblocks any waiters. func (cw closeWaiter) Close() { close(cw) } // Wait waits for the closeWaiter to become closed. func (cw closeWaiter) Wait() { <-cw } // bufferedWriter is a buffered writer that writes to w. // Its buffered writer is lazily allocated as needed, to minimize // idle memory usage with many connections. type bufferedWriter struct { _ incomparable w io.Writer // immutable bw *bufio.Writer // non-nil when data is buffered } func newBufferedWriter(w io.Writer) *bufferedWriter { return &bufferedWriter{w: w} } // bufWriterPoolBufferSize is the size of bufio.Writer's // buffers created using bufWriterPool. // // TODO: pick a less arbitrary value? this is a bit under // (3 x typical 1500 byte MTU) at least. Other than that, // not much thought went into it. const bufWriterPoolBufferSize = 4 << 10 var bufWriterPool = sync.Pool{ New: func() interface{} { return bufio.NewWriterSize(nil, bufWriterPoolBufferSize) }, } func (w *bufferedWriter) Available() int { if w.bw == nil { return bufWriterPoolBufferSize } return w.bw.Available() } func (w *bufferedWriter) Write(p []byte) (n int, err error) { if w.bw == nil { bw := bufWriterPool.Get().(*bufio.Writer) bw.Reset(w.w) w.bw = bw } return w.bw.Write(p) } func (w *bufferedWriter) Flush() error { bw := w.bw if bw == nil { return nil } err := bw.Flush() bw.Reset(nil) bufWriterPool.Put(bw) w.bw = nil return err } func mustUint31(v int32) uint32 { if v < 0 || v > 2147483647 { panic("out of range") } return uint32(v) } // bodyAllowedForStatus reports whether a given response status code // permits a body. See RFC 7230, section 3.3. func bodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: return false case status == 204: return false case status == 304: return false } return true } type httpError struct { _ incomparable msg string timeout bool } func (e *httpError) Error() string { return e.msg } func (e *httpError) Timeout() bool { return e.timeout } func (e *httpError) Temporary() bool { return true } var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true} type connectionStater interface { ConnectionState() tls.ConnectionState } var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }} type sorter struct { v []string // owned by sorter } func (s *sorter) Len() int { return len(s.v) } func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] } func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] } // Keys returns the sorted keys of h. // // The returned slice is only valid until s used again or returned to // its pool. func (s *sorter) Keys(h http.Header) []string { keys := s.v[:0] for k := range h { keys = append(keys, k) } s.v = keys sort.Sort(s) return keys } func (s *sorter) SortStrings(ss []string) { // Our sorter works on s.v, which sorter owns, so // stash it away while we sort the user's buffer. save := s.v s.v = ss sort.Sort(s) s.v = save } // validPseudoPath reports whether v is a valid :path pseudo-header // value. It must be either: // // *) a non-empty string starting with '/' // *) the string '*', for OPTIONS requests. // // For now this is only used a quick check for deciding when to clean // up Opaque URLs before sending requests from the Transport. // See golang.org/issue/16847 // // We used to enforce that the path also didn't start with "//", but // Google's GFE accepts such paths and Chrome sends them, so ignore // that part of the spec. See golang.org/issue/19103. func validPseudoPath(v string) bool { return (len(v) > 0 && v[0] == '/') || v == "*" } // incomparable is a zero-width, non-comparable type. Adding it to a struct // makes that struct also non-comparable, and generally doesn't add // any size (as long as it's first). type incomparable [0]func()
{ "pile_set_name": "Github" }
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; public final class RoboVmPlatformTest { public static void main(String[] args) { System.exit(new RoboVmPlatformTest().isRoboVM() ? 0 : 1); } boolean isRoboVM() { if (!"RoboVM".equals(System.getProperty("java.vm.name"))) { return false; } // This is a proxy for the private property hasJava8Classes. return Platform.get().defaultCallAdapterFactoriesSize() == 1; } }
{ "pile_set_name": "Github" }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build aix darwin freebsd linux solaris package ipv6 import ( "net" "unsafe" "golang.org/x/net/internal/socket" ) var compatFreeBSD32 bool // 386 emulation on amd64 func (so *sockOpt) setGroupReq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { var gr groupReq if ifi != nil { gr.Interface = uint32(ifi.Index) } gr.setGroup(grp) var b []byte if compatFreeBSD32 { var d [sizeofGroupReq + 4]byte s := (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) b = d[:] } else { b = (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr))[:sizeofGroupReq] } return so.Set(c, b) } func (so *sockOpt) setGroupSourceReq(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { var gsr groupSourceReq if ifi != nil { gsr.Interface = uint32(ifi.Index) } gsr.setSourceGroup(grp, src) var b []byte if compatFreeBSD32 { var d [sizeofGroupSourceReq + 4]byte s := (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) b = d[:] } else { b = (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr))[:sizeofGroupSourceReq] } return so.Set(c, b) }
{ "pile_set_name": "Github" }
{ "created_at": "2015-02-27T22:29:20.128736", "description": "Sake Build", "fork": false, "full_name": "sakeproject/sake", "language": "C#", "updated_at": "2015-02-27T23:44:24.111327" }
{ "pile_set_name": "Github" }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ir/module print returns the llvm assembly code for the module 1`] = ` "; ModuleID = 'test' source_filename = \\"test\\" define double @sin() { entry: } " `;
{ "pile_set_name": "Github" }
$icon-font-path: '/fonts/'; $primary-color: #ef5411; $select-color: fade-out($primary-color, .3); $white: #fff; $dark-gray: #4a4a4a; $gray: #999; $light-gray: #979797; // Bootstrap variable overrides $page-header-border-color: $primary-color; $alert-success-bg: transparent; $alert-info-bg: transparent; $alert-warning-bg: transparent; $alert-danger-bg: transparent; @import 'bootstrap'; @import '../../../node_modules/selectize/dist/css/selectize.bootstrap3'; @import 'peacock.css'; @import 'algolia'; @import 'admin'; @import 'pages'; @import 'posts'; @import 'projects'; @import 'series'; @import 'tags'; @font-face { font-family: 'Bebas Neue Bold'; src: url('/fonts/bebas-neue-bold.eot'); src: url('/fonts/bebas-neue-bold.eot?#iefix') format('embedded-opentype'), url('/fonts/bebas-neue-bold.woff') format('woff'), url('/fonts/bebas-neue-bold.ttf') format('truetype'), url('/fonts/bebas-neue-bold.svg#bebas_neuebold') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'Bebas Neue Regular'; src: url('/fonts/bebas-neue-regular.eot'); src: url('/fonts/bebas-neue-regular.eot?#iefix') format('embedded-opentype'), url('/fonts/bebas-neue-regular.woff') format('woff'), url('/fonts/bebas-neue-regular.ttf') format('truetype'), url('/fonts/bebas-neue-regular.svg#bebas_neue_regularregular') format('svg'); font-weight: normal; font-style: normal; } body { border-top: 3px solid $primary-color; } a { color: $primary-color; &:hover { color: darken($primary-color, 20%); } } .page-header, .page-header h3 { margin-top: 0; } ::selection { background: $select-color; } ::-moz-selection { background: $select-color; } .pagination > .active > a, .pagination > .active > a:focus, .pagination > .active > a:hover, .pagination > .active > span, .pagination > .active > span:focus, .pagination > .active > span:hover { background-color: $primary-color; border-color: darken($primary-color, 10%); } .pagination > li > a, .pagination > li > span { color: $primary-color; } .pagination > li > a:focus, .pagination > li > a:hover, .pagination > li > span:focus, .pagination > li > span:hover { color: $primary-color; } .shards { height: 100px; } header { h1 { font-family: 'Bebas Neue Bold'; font-size: 50px; margin: 10px 0; a, a:hover { color: $dark-gray; } } h2 { color: $primary-color; font-family: 'Bebas Neue Regular'; font-size: 22px; margin: 0; } .author { @extend .text-muted; font-family: 'Bebas Neue Regular'; font-size: 18px; } @media (min-width: 760px) { h1, h2, .author { text-align: right; } } } .menu { padding: 0; li { display: inline-block; font-family: 'Bebas Neue Regular'; list-style-type: none; margin: 5px 0; a, a:hover, a:active { color: $light-gray; display: inline-block; font-size: 20px; padding: 5px 10px; text-decoration: none; transition: padding .5s; } // Active navigation elements get a similar, but darker, background. &.active { background: $primary-color; a, a:hover, a:active { color: $white; } &:after { content: ''; background: $primary-color; bottom: 0; position: absolute; right: 100%; top: 0; width: 9999px; } } } } @media (min-width: 768px) { .menu { li { display: block; position: relative; text-align: right; a { padding: 5px 0; width: 100%; } &.active a { padding-right: 5px; } // Get a nice light background when hovering over the navigation items. &:hover { background: lighten($primary-color, 20%); a, a:hover, a:active { color: $white; padding-right: 5px; } &:after { content: ''; position: absolute; background: lighten($primary-color, 20%); top: 0; bottom: 0; width: 9999px; right: 100%; } } } } } h3, h4, p { color: $dark-gray; font-family: 'Avenir Next', sans-serif; } h3, h4 { font-weight: bold; line-height: 1.5; } h3 { font-size: 36px; } h4 { font-size: 24px; } p.lead { font-size: 18px; line-height: 1.6; } p { font-size: 16px; line-height: 1.8; margin-bottom: 20px; } footer { color: $light-gray; font-size: 12px; border-top: 1px solid $primary-color; padding-top: 15px; margin-top: 15px; }
{ "pile_set_name": "Github" }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /* * * (C) Copyright IBM Corp. 1998-2005 - All Rights Reserved * */ #ifndef __GLYPHPOSITIONADJUSTMENTS_H #define __GLYPHPOSITIONADJUSTMENTS_H /** * \file * \internal */ #include "LETypes.h" #include "OpenTypeTables.h" U_NAMESPACE_BEGIN class LEGlyphStorage; class LEFontInstance; class GlyphPositionAdjustments : public UMemory { private: class Adjustment : public UMemory { public: inline Adjustment(); inline Adjustment(float xPlace, float yPlace, float xAdv, float yAdv, le_int32 baseOff = -1); inline ~Adjustment(); inline float getXPlacement() const; inline float getYPlacement() const; inline float getXAdvance() const; inline float getYAdvance() const; inline le_int32 getBaseOffset() const; inline void setXPlacement(float newXPlacement); inline void setYPlacement(float newYPlacement); inline void setXAdvance(float newXAdvance); inline void setYAdvance(float newYAdvance); inline void setBaseOffset(le_int32 newBaseOffset); inline void adjustXPlacement(float xAdjustment); inline void adjustYPlacement(float yAdjustment); inline void adjustXAdvance(float xAdjustment); inline void adjustYAdvance(float yAdjustment); private: float xPlacement; float yPlacement; float xAdvance; float yAdvance; le_int32 baseOffset; // allow copying of this class because all of its fields are simple types }; class EntryExitPoint : public UMemory { public: inline EntryExitPoint(); inline ~EntryExitPoint(); inline le_bool isCursiveGlyph() const; inline le_bool baselineIsLogicalEnd() const; LEPoint *getEntryPoint(LEPoint &entryPoint) const; LEPoint *getExitPoint(LEPoint &exitPoint) const; inline void clearEntryPoint(); inline void clearExitPoint(); inline void setEntryPoint(LEPoint &newEntryPoint, le_bool baselineIsLogicalEnd); inline void setExitPoint(LEPoint &newExitPoint, le_bool baselineIsLogicalEnd); inline void setCursiveGlyph(le_bool baselineIsLogicalEnd); private: enum EntryExitFlags { EEF_HAS_ENTRY_POINT = 0x80000000L, EEF_HAS_EXIT_POINT = 0x40000000L, EEF_IS_CURSIVE_GLYPH = 0x20000000L, EEF_BASELINE_IS_LOGICAL_END = 0x10000000L }; le_uint32 fFlags; LEPoint fEntryPoint; LEPoint fExitPoint; }; le_int32 fGlyphCount; EntryExitPoint *fEntryExitPoints; Adjustment *fAdjustments; GlyphPositionAdjustments(); public: GlyphPositionAdjustments(le_int32 glyphCount); ~GlyphPositionAdjustments(); inline le_bool hasCursiveGlyphs() const; inline le_bool isCursiveGlyph(le_int32 index) const; inline le_bool baselineIsLogicalEnd(le_int32 index) const; const LEPoint *getEntryPoint(le_int32 index, LEPoint &entryPoint) const; const LEPoint *getExitPoint(le_int32 index, LEPoint &exitPoint) const; inline float getXPlacement(le_int32 index) const; inline float getYPlacement(le_int32 index) const; inline float getXAdvance(le_int32 index) const; inline float getYAdvance(le_int32 index) const; inline le_int32 getBaseOffset(le_int32 index) const; inline void setXPlacement(le_int32 index, float newXPlacement); inline void setYPlacement(le_int32 index, float newYPlacement); inline void setXAdvance(le_int32 index, float newXAdvance); inline void setYAdvance(le_int32 index, float newYAdvance); inline void setBaseOffset(le_int32 index, le_int32 newBaseOffset); inline void adjustXPlacement(le_int32 index, float xAdjustment); inline void adjustYPlacement(le_int32 index, float yAdjustment); inline void adjustXAdvance(le_int32 index, float xAdjustment); inline void adjustYAdvance(le_int32 index, float yAdjustment); void clearEntryPoint(le_int32 index); void clearExitPoint(le_int32 index); void setEntryPoint(le_int32 index, LEPoint &newEntryPoint, le_bool baselineIsLogicalEnd); void setExitPoint(le_int32 index, LEPoint &newExitPoint, le_bool baselineIsLogicalEnd); void setCursiveGlyph(le_int32 index, le_bool baselineIsLogicalEnd); void applyCursiveAdjustments(LEGlyphStorage &glyphStorage, le_bool rightToLeft, const LEFontInstance *fontInstance); }; inline GlyphPositionAdjustments::Adjustment::Adjustment() : xPlacement(0), yPlacement(0), xAdvance(0), yAdvance(0), baseOffset(-1) { // nothing else to do! } inline GlyphPositionAdjustments::Adjustment::Adjustment(float xPlace, float yPlace, float xAdv, float yAdv, le_int32 baseOff) : xPlacement(xPlace), yPlacement(yPlace), xAdvance(xAdv), yAdvance(yAdv), baseOffset(baseOff) { // nothing else to do! } inline GlyphPositionAdjustments::Adjustment::~Adjustment() { // nothing to do! } inline float GlyphPositionAdjustments::Adjustment::getXPlacement() const { return xPlacement; } inline float GlyphPositionAdjustments::Adjustment::getYPlacement() const { return yPlacement; } inline float GlyphPositionAdjustments::Adjustment::getXAdvance() const { return xAdvance; } inline float GlyphPositionAdjustments::Adjustment::getYAdvance() const { return yAdvance; } inline le_int32 GlyphPositionAdjustments::Adjustment::getBaseOffset() const { return baseOffset; } inline void GlyphPositionAdjustments::Adjustment::setXPlacement(float newXPlacement) { xPlacement = newXPlacement; } inline void GlyphPositionAdjustments::Adjustment::setYPlacement(float newYPlacement) { yPlacement = newYPlacement; } inline void GlyphPositionAdjustments::Adjustment::setXAdvance(float newXAdvance) { xAdvance = newXAdvance; } inline void GlyphPositionAdjustments::Adjustment::setYAdvance(float newYAdvance) { yAdvance = newYAdvance; } inline void GlyphPositionAdjustments::Adjustment::setBaseOffset(le_int32 newBaseOffset) { baseOffset = newBaseOffset; } inline void GlyphPositionAdjustments::Adjustment::adjustXPlacement(float xAdjustment) { xPlacement += xAdjustment; } inline void GlyphPositionAdjustments::Adjustment::adjustYPlacement(float yAdjustment) { yPlacement += yAdjustment; } inline void GlyphPositionAdjustments::Adjustment::adjustXAdvance(float xAdjustment) { xAdvance += xAdjustment; } inline void GlyphPositionAdjustments::Adjustment::adjustYAdvance(float yAdjustment) { yAdvance += yAdjustment; } inline GlyphPositionAdjustments::EntryExitPoint::EntryExitPoint() : fFlags(0) { fEntryPoint.fX = fEntryPoint.fY = fExitPoint.fX = fExitPoint.fY = 0; } inline GlyphPositionAdjustments::EntryExitPoint::~EntryExitPoint() { // nothing special to do } inline le_bool GlyphPositionAdjustments::EntryExitPoint::isCursiveGlyph() const { return (fFlags & EEF_IS_CURSIVE_GLYPH) != 0; } inline le_bool GlyphPositionAdjustments::EntryExitPoint::baselineIsLogicalEnd() const { return (fFlags & EEF_BASELINE_IS_LOGICAL_END) != 0; } inline void GlyphPositionAdjustments::EntryExitPoint::clearEntryPoint() { fFlags &= ~EEF_HAS_ENTRY_POINT; } inline void GlyphPositionAdjustments::EntryExitPoint::clearExitPoint() { fFlags &= ~EEF_HAS_EXIT_POINT; } inline void GlyphPositionAdjustments::EntryExitPoint::setEntryPoint(LEPoint &newEntryPoint, le_bool baselineIsLogicalEnd) { if (baselineIsLogicalEnd) { fFlags |= (EEF_HAS_ENTRY_POINT | EEF_IS_CURSIVE_GLYPH | EEF_BASELINE_IS_LOGICAL_END); } else { fFlags |= (EEF_HAS_ENTRY_POINT | EEF_IS_CURSIVE_GLYPH); } fEntryPoint = newEntryPoint; } inline void GlyphPositionAdjustments::EntryExitPoint::setExitPoint(LEPoint &newExitPoint, le_bool baselineIsLogicalEnd) { if (baselineIsLogicalEnd) { fFlags |= (EEF_HAS_EXIT_POINT | EEF_IS_CURSIVE_GLYPH | EEF_BASELINE_IS_LOGICAL_END); } else { fFlags |= (EEF_HAS_EXIT_POINT | EEF_IS_CURSIVE_GLYPH); } fExitPoint = newExitPoint; } inline void GlyphPositionAdjustments::EntryExitPoint::setCursiveGlyph(le_bool baselineIsLogicalEnd) { if (baselineIsLogicalEnd) { fFlags |= (EEF_IS_CURSIVE_GLYPH | EEF_BASELINE_IS_LOGICAL_END); } else { fFlags |= EEF_IS_CURSIVE_GLYPH; } } inline le_bool GlyphPositionAdjustments::isCursiveGlyph(le_int32 index) const { return fEntryExitPoints != NULL && fEntryExitPoints[index].isCursiveGlyph(); } inline le_bool GlyphPositionAdjustments::baselineIsLogicalEnd(le_int32 index) const { return fEntryExitPoints != NULL && fEntryExitPoints[index].baselineIsLogicalEnd(); } inline float GlyphPositionAdjustments::getXPlacement(le_int32 index) const { return fAdjustments[index].getXPlacement(); } inline float GlyphPositionAdjustments::getYPlacement(le_int32 index) const { return fAdjustments[index].getYPlacement(); } inline float GlyphPositionAdjustments::getXAdvance(le_int32 index) const { return fAdjustments[index].getXAdvance(); } inline float GlyphPositionAdjustments::getYAdvance(le_int32 index) const { return fAdjustments[index].getYAdvance(); } inline le_int32 GlyphPositionAdjustments::getBaseOffset(le_int32 index) const { return fAdjustments[index].getBaseOffset(); } inline void GlyphPositionAdjustments::setXPlacement(le_int32 index, float newXPlacement) { fAdjustments[index].setXPlacement(newXPlacement); } inline void GlyphPositionAdjustments::setYPlacement(le_int32 index, float newYPlacement) { fAdjustments[index].setYPlacement(newYPlacement); } inline void GlyphPositionAdjustments::setXAdvance(le_int32 index, float newXAdvance) { fAdjustments[index].setXAdvance(newXAdvance); } inline void GlyphPositionAdjustments::setYAdvance(le_int32 index, float newYAdvance) { fAdjustments[index].setYAdvance(newYAdvance); } inline void GlyphPositionAdjustments::setBaseOffset(le_int32 index, le_int32 newBaseOffset) { fAdjustments[index].setBaseOffset(newBaseOffset); } inline void GlyphPositionAdjustments::adjustXPlacement(le_int32 index, float xAdjustment) { fAdjustments[index].adjustXPlacement(xAdjustment); } inline void GlyphPositionAdjustments::adjustYPlacement(le_int32 index, float yAdjustment) { fAdjustments[index].adjustYPlacement(yAdjustment); } inline void GlyphPositionAdjustments::adjustXAdvance(le_int32 index, float xAdjustment) { fAdjustments[index].adjustXAdvance(xAdjustment); } inline void GlyphPositionAdjustments::adjustYAdvance(le_int32 index, float yAdjustment) { fAdjustments[index].adjustYAdvance(yAdjustment); } inline le_bool GlyphPositionAdjustments::hasCursiveGlyphs() const { return fEntryExitPoints != NULL; } U_NAMESPACE_END #endif
{ "pile_set_name": "Github" }
// Copyright (C) 2013 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_PYaSSERT_Hh_ #define DLIB_PYaSSERT_Hh_ #include <pybind11/pybind11.h> #define pyassert(_exp,_message) \ {if ( !(_exp) ) \ { \ namespace py = pybind11; \ PyErr_SetString( PyExc_ValueError, _message ); \ throw py::error_already_set(); \ }} #endif // DLIB_PYaSSERT_Hh_
{ "pile_set_name": "Github" }
import React, { useState, ReactChild } from 'react'; import { useStyles } from 'react-treat'; import copy from 'copy-to-clipboard'; import memoize from 'lodash/memoize'; import reactElementToJSXString from 'react-element-to-jsx-string'; import prettier from 'prettier/standalone'; import typescriptParser from 'prettier/parser-typescript'; import { createUrl } from 'sku/playroom/utils'; import { useConfig } from '../ConfigContext'; import { Box, Stack, Text, Inline, IconChevron, Hidden, } from '../../../../lib/components'; import { BoxProps } from '../../../../lib/components/Box/Box'; import { FieldOverlay } from '../../../../lib/components/private/FieldOverlay/FieldOverlay'; import { useBoxStyles } from '../../../../lib/components/Box/useBoxStyles'; import { hideFocusRingsClassName } from '../../../../lib/components/private/hideFocusRings/hideFocusRings'; import { CopyIcon } from './CopyIcon'; import { PlayIcon } from './PlayIcon'; import * as styleRefs from './Code.treat'; // @ts-ignore import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import editorTheme from './editorTheme'; import { ThemedExample } from '../ThemeSetting'; const formatSnippet = memoize( (snippet) => prettier .format(snippet, { parser: 'typescript', plugins: [typescriptParser], semi: false, }) .replace(/^;/, ''), // Remove leading semicolons from JSX ); const CodeButton = ({ component = 'button', children, className, ...restProps }: BoxProps) => { const styles = useStyles(styleRefs); return ( <Box component={component} cursor="pointer" borderRadius="standard" paddingY="xxsmall" paddingX="xsmall" position="relative" outline="none" className={[styles.button, className]} {...restProps} > <FieldOverlay variant="focus" className={[styles.focusOverlay, hideFocusRingsClassName]} /> <FieldOverlay background="neutralLight" className={styles.hoverOverlay} /> <FieldOverlay className={styles.activeOverlay} /> <Box component="span" position="relative" pointerEvents="none" userSelect="none" > <Text size="xsmall" baseline={false} tone="secondary"> {children} </Text> </Box> </Box> ); }; export const CodeBlock = ({ children, language = 'tsx', }: { children: string; language?: string; }) => { const styles = useStyles(styleRefs); return ( <Box position="relative" padding="xxsmall" borderRadius="standard" className={styles.code} > <Box padding={['medium', 'medium', 'large']}> <Text size="small" component="pre" baseline={false}> <SyntaxHighlighter language={language} style={editorTheme}> {children} </SyntaxHighlighter> </Text> </Box> </Box> ); }; interface CodeProps { playroom?: boolean; collapsedByDefault?: boolean; children: ReactChild; } export default ({ playroom = true, collapsedByDefault = false, children, }: CodeProps) => { const [hideCode, setHideCode] = useState(collapsedByDefault); const { playroomUrl } = useConfig(); const snippet = formatSnippet( typeof children === 'string' ? children : reactElementToJSXString(children, { useBooleanShorthandSyntax: false, showDefaultProps: false, showFunctions: false, filterProps: ['onChange', 'onBlur', 'onFocus'], }), ); return ( <Box position="relative" style={{ maxWidth: 864, }} > <Stack space="xsmall"> {typeof children !== 'string' && ( <ThemedExample background="body">{children}</ThemedExample> )} {hideCode ? null : <CodeBlock>{snippet}</CodeBlock>} <Inline space="xxsmall" align="right"> {collapsedByDefault ? ( <CodeButton onClick={() => setHideCode(!hideCode)}> <IconChevron direction={hideCode ? 'down' : 'up'} /> <Hidden inline below="tablet"> {hideCode ? ' View code' : ' Hide code'} </Hidden> <Hidden inline above="mobile"> {' '} Code </Hidden> </CodeButton> ) : null} {hideCode ? null : ( <CodeButton onClick={() => copy(snippet)} title="Copy code to clipboard" > <CopyIcon /> Copy </CodeButton> )} {/^import/m.test(snippet) || !playroom ? null : ( <CodeButton component="a" target="_blank" href={createUrl({ baseUrl: playroomUrl, code: snippet })} className={useBoxStyles({ component: 'a', display: 'block', })} title="Open in Playroom" > <PlayIcon />{' '} <Hidden inline below="tablet"> Open in{' '} </Hidden> Playroom </CodeButton> )} </Inline> </Stack> </Box> ); };
{ "pile_set_name": "Github" }
0 1 1.306771e-002 -1.000000e+000 8.365398e-001
{ "pile_set_name": "Github" }
2660.3.1= { holder = 1911130 liege = k_jefferson }
{ "pile_set_name": "Github" }
// Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // Preprocessed version of "boost/mpl/quote.hpp" header // -- DO NOT modify by hand! namespace boost { namespace mpl { template< typename T, bool has_type_ > struct quote_impl : T { }; template< typename T > struct quote_impl< T,false > { typedef T type; }; template< template< typename P1 > class F , typename Tag = void_ > struct quote1 { template< typename U1 > struct apply : quote_impl< F<U1> , aux::has_type< F<U1> >::value > { }; }; template< template< typename P1, typename P2 > class F , typename Tag = void_ > struct quote2 { template< typename U1, typename U2 > struct apply : quote_impl< F< U1,U2 > , aux::has_type< F< U1,U2 > >::value > { }; }; template< template< typename P1, typename P2, typename P3 > class F , typename Tag = void_ > struct quote3 { template< typename U1, typename U2, typename U3 > struct apply : quote_impl< F< U1,U2,U3 > , aux::has_type< F< U1,U2,U3 > >::value > { }; }; template< template< typename P1, typename P2, typename P3, typename P4 > class F , typename Tag = void_ > struct quote4 { template< typename U1, typename U2, typename U3, typename U4 > struct apply : quote_impl< F< U1,U2,U3,U4 > , aux::has_type< F< U1,U2,U3,U4 > >::value > { }; }; template< template< typename P1, typename P2, typename P3, typename P4 , typename P5 > class F , typename Tag = void_ > struct quote5 { template< typename U1, typename U2, typename U3, typename U4 , typename U5 > struct apply : quote_impl< F< U1,U2,U3,U4,U5 > , aux::has_type< F< U1,U2,U3,U4,U5 > >::value > { }; }; }}
{ "pile_set_name": "Github" }
site_name: Indexing v1.0.14+20200625 site_url: http://byron.github.io/google-apis-rs/google-indexing3-cli site_description: A complete library to interact with Indexing (protocol v3) repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/indexing3-cli docs_dir: docs site_dir: build_html pages: - ['index.md', 'Home'] - ['url-notifications_get-metadata.md', 'Url Notifications', 'Get Metadata'] - ['url-notifications_publish.md', 'Url Notifications', 'Publish'] theme: readthedocs copyright: Copyright &copy; 2015-2020, `Sebastian Thiel`
{ "pile_set_name": "Github" }
#!/usr/bin/env bash rm -r -f build mkdir -p build mkdir -p build/js elm-make src/Main.elm --output build/js/fplus_api_search.js if [ $? -eq 0 ] then cp ../../logo/fplus.png ./build/ cp -r ./src/highlight ./build/ cp ./src/style.css ./build/style.css cp ./src/favicon.png ./build/favicon.png cp ./src/htmlmain.js ./build/js/htmlmain.js cp ./src/index.html ./build/index.html fi ./ExploreCompile.sh ./TypeSignatureTestCompile.sh
{ "pile_set_name": "Github" }
package com.alibaba.datax.core.transport.channel.memory; import com.alibaba.datax.common.element.Record; import com.alibaba.datax.common.exception.DataXException; import com.alibaba.datax.common.util.Configuration; import com.alibaba.datax.core.transport.channel.Channel; import com.alibaba.datax.core.transport.record.TerminateRecord; import com.alibaba.datax.core.util.FrameworkErrorCode; import com.alibaba.datax.core.util.container.CoreConstant; import java.util.Collection; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * 内存Channel的具体实现,底层其实是一个ArrayBlockingQueue * */ public class MemoryChannel extends Channel { private int bufferSize = 0; private AtomicInteger memoryBytes = new AtomicInteger(0); private ArrayBlockingQueue<Record> queue = null; private ReentrantLock lock; private Condition notInsufficient, notEmpty; public MemoryChannel(final Configuration configuration) { super(configuration); this.queue = new ArrayBlockingQueue<Record>(this.getCapacity()); this.bufferSize = configuration.getInt(CoreConstant.DATAX_CORE_TRANSPORT_EXCHANGER_BUFFERSIZE); lock = new ReentrantLock(); notInsufficient = lock.newCondition(); notEmpty = lock.newCondition(); } @Override public void close() { super.close(); try { this.queue.put(TerminateRecord.get()); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } @Override public void clear(){ this.queue.clear(); } @Override protected void doPush(Record r) { try { long startTime = System.nanoTime(); this.queue.put(r); waitWriterTime += System.nanoTime() - startTime; memoryBytes.addAndGet(r.getMemorySize()); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } @Override protected void doPushAll(Collection<Record> rs) { try { long startTime = System.nanoTime(); lock.lockInterruptibly(); int bytes = getRecordBytes(rs); while (memoryBytes.get() + bytes > this.byteCapacity || rs.size() > this.queue.remainingCapacity()) { notInsufficient.await(200L, TimeUnit.MILLISECONDS); } this.queue.addAll(rs); waitWriterTime += System.nanoTime() - startTime; memoryBytes.addAndGet(bytes); notEmpty.signalAll(); } catch (InterruptedException e) { throw DataXException.asDataXException( FrameworkErrorCode.RUNTIME_ERROR, e); } finally { lock.unlock(); } } @Override protected Record doPull() { try { long startTime = System.nanoTime(); Record r = this.queue.take(); waitReaderTime += System.nanoTime() - startTime; memoryBytes.addAndGet(-r.getMemorySize()); return r; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } } @Override protected void doPullAll(Collection<Record> rs) { assert rs != null; rs.clear(); try { long startTime = System.nanoTime(); lock.lockInterruptibly(); while (this.queue.drainTo(rs, bufferSize) <= 0) { notEmpty.await(200L, TimeUnit.MILLISECONDS); } waitReaderTime += System.nanoTime() - startTime; int bytes = getRecordBytes(rs); memoryBytes.addAndGet(-bytes); notInsufficient.signalAll(); } catch (InterruptedException e) { throw DataXException.asDataXException( FrameworkErrorCode.RUNTIME_ERROR, e); } finally { lock.unlock(); } } private int getRecordBytes(Collection<Record> rs){ int bytes = 0; for(Record r : rs){ bytes += r.getMemorySize(); } return bytes; } @Override public int size() { return this.queue.size(); } @Override public boolean isEmpty() { return this.queue.isEmpty(); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Disabled</key> <true/> <key>Label</key> <string>com.apple.ntalkd</string> <key>ProgramArguments</key> <array> <string>/usr/libexec/ntalkd</string> </array> <key>inetdCompatibility</key> <dict> <key>Wait</key> <true/> </dict> <key>Sockets</key> <dict> <key>Listeners</key> <dict> <key>SockServiceName</key> <string>ntalk</string> <key>SockType</key> <string>dgram</string> </dict> </dict> </dict> </plist>
{ "pile_set_name": "Github" }
'use strict'; var $export = require('./_export'); var toObject = require('./_to-object'); var toPrimitive = require('./_to-primitive'); var toISOString = require('./_date-to-iso-string'); var classof = require('./_classof'); $export($export.P + $export.F * require('./_fails')(function () { return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; }), 'Date', { // eslint-disable-next-line no-unused-vars toJSON: function toJSON(key) { var O = toObject(this); var pv = toPrimitive(O); return typeof pv == 'number' && !isFinite(pv) ? null : (!('toISOString' in O) && classof(O) == 'Date') ? toISOString.call(O) : O.toISOString(); } });
{ "pile_set_name": "Github" }
/* Copyright 2016 Jack Humbert * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PROCESS_LEADER_H #define PROCESS_LEADER_H #include "quantum.h" bool process_leader(uint16_t keycode, keyrecord_t *record); void leader_start(void); void leader_end(void); void qk_leader_start(void); #define SEQ_ONE_KEY(key) if (leader_sequence[0] == (key) && leader_sequence[1] == 0 && leader_sequence[2] == 0 && leader_sequence[3] == 0 && leader_sequence[4] == 0) #define SEQ_TWO_KEYS(key1, key2) if (leader_sequence[0] == (key1) && leader_sequence[1] == (key2) && leader_sequence[2] == 0 && leader_sequence[3] == 0 && leader_sequence[4] == 0) #define SEQ_THREE_KEYS(key1, key2, key3) if (leader_sequence[0] == (key1) && leader_sequence[1] == (key2) && leader_sequence[2] == (key3) && leader_sequence[3] == 0 && leader_sequence[4] == 0) #define SEQ_FOUR_KEYS(key1, key2, key3, key4) if (leader_sequence[0] == (key1) && leader_sequence[1] == (key2) && leader_sequence[2] == (key3) && leader_sequence[3] == (key4) && leader_sequence[4] == 0) #define SEQ_FIVE_KEYS(key1, key2, key3, key4, key5) if (leader_sequence[0] == (key1) && leader_sequence[1] == (key2) && leader_sequence[2] == (key3) && leader_sequence[3] == (key4) && leader_sequence[4] == (key5)) #define LEADER_EXTERNS() \ extern bool leading; \ extern uint16_t leader_time; \ extern uint16_t leader_sequence[5]; \ extern uint8_t leader_sequence_size #define LEADER_DICTIONARY() if (leading && timer_elapsed(leader_time) > LEADER_TIMEOUT) #endif
{ "pile_set_name": "Github" }
#include <cstdlib.h> extern "C" { void __cxa_pure_virtual() { _terminate(1); } }
{ "pile_set_name": "Github" }
{ "ambientocclusion": false, "textures": { "particle": "tconstruct:block/slime/slime_vine", "vine": "tconstruct:block/slime/slime_vine" }, "elements": [ { "from": [ 15.2, 0, 0 ], "to": [ 15.2, 16, 16 ], "shade": false, "faces": { "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#vine", "tintindex": 0 }, "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#vine", "tintindex": 0 } } }, { "from": [ 0.8, 0, 0 ], "to": [ 0.8, 16, 16 ], "shade": false, "faces": { "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#vine", "tintindex": 0 }, "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#vine", "tintindex": 0 } } } ] }
{ "pile_set_name": "Github" }
#!/bin/sh # TODO: add shared tests once we have them. TESTS="test/server/**/*.test.js" REQUIRES=test/server/requires.js MOCHA=node_modules/.bin/mocha $MOCHA -r $REQUIRES $TESTS
{ "pile_set_name": "Github" }
; REQUIRES: asserts ; RUN: opt < %s -loop-vectorize -force-vector-width=4 -force-vector-interleave=1 -instcombine -debug-only=loop-vectorize -disable-output -print-after=instcombine 2>&1 | FileCheck %s ; RUN: opt < %s -loop-vectorize -force-vector-width=4 -force-vector-interleave=1 -enable-interleaved-mem-accesses -instcombine -debug-only=loop-vectorize -disable-output -print-after=instcombine 2>&1 | FileCheck %s --check-prefix=INTER target datalayout = "e-m:e-i64:64-i128:128-n32:64-S128" %pair = type { i32, i32 } ; CHECK-LABEL: consecutive_ptr_forward ; ; Check that a forward consecutive pointer is recognized as uniform and remains ; uniform after vectorization. ; ; CHECK: LV: Found uniform instruction: %tmp1 = getelementptr inbounds i32, i32* %a, i64 %i ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK-NOT: getelementptr ; CHECK: getelementptr inbounds i32, i32* %a, i64 %index ; CHECK-NOT: getelementptr ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; define i32 @consecutive_ptr_forward(i32* %a, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ 0, %entry ] %tmp0 = phi i32 [ %tmp3, %for.body ], [ 0, %entry ] %tmp1 = getelementptr inbounds i32, i32* %a, i64 %i %tmp2 = load i32, i32* %tmp1, align 8 %tmp3 = add i32 %tmp0, %tmp2 %i.next = add nuw nsw i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: %tmp4 = phi i32 [ %tmp3, %for.body ] ret i32 %tmp4 } ; CHECK-LABEL: consecutive_ptr_reverse ; ; Check that a reverse consecutive pointer is recognized as uniform and remains ; uniform after vectorization. ; ; CHECK: LV: Found uniform instruction: %tmp1 = getelementptr inbounds i32, i32* %a, i64 %i ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK: %offset.idx = sub i64 %n, %index ; CHECK-NOT: getelementptr ; CHECK: %[[G0:.+]] = getelementptr inbounds i32, i32* %a, i64 -3 ; CHECK: getelementptr inbounds i32, i32* %[[G0]], i64 %offset.idx ; CHECK-NOT: getelementptr ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; define i32 @consecutive_ptr_reverse(i32* %a, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ %n, %entry ] %tmp0 = phi i32 [ %tmp3, %for.body ], [ 0, %entry ] %tmp1 = getelementptr inbounds i32, i32* %a, i64 %i %tmp2 = load i32, i32* %tmp1, align 8 %tmp3 = add i32 %tmp0, %tmp2 %i.next = add nuw nsw i64 %i, -1 %cond = icmp sgt i64 %i.next, 0 br i1 %cond, label %for.body, label %for.end for.end: %tmp4 = phi i32 [ %tmp3, %for.body ] ret i32 %tmp4 } ; CHECK-LABEL: interleaved_access_forward ; INTER-LABEL: interleaved_access_forward ; ; Check that a consecutive-like pointer used by a forward interleaved group is ; recognized as uniform and remains uniform after vectorization. When ; interleaved memory accesses aren't enabled, the pointer should not be ; recognized as uniform, and it should not be uniform after vectorization. ; ; CHECK-NOT: LV: Found uniform instruction: %tmp1 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 ; CHECK-NOT: LV: Found uniform instruction: %tmp2 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 1 ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK: %[[I1:.+]] = or i64 %index, 1 ; CHECK: %[[I2:.+]] = or i64 %index, 2 ; CHECK: %[[I3:.+]] = or i64 %index, 3 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %index, i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I1]], i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I2]], i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I3]], i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %index, i32 1 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I1]], i32 1 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I2]], i32 1 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I3]], i32 1 ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; ; INTER: LV: Found uniform instruction: %tmp1 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 ; INTER: LV: Found uniform instruction: %tmp2 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 1 ; INTER: vector.body ; INTER: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; INTER-NOT: getelementptr ; INTER: getelementptr inbounds %pair, %pair* %p, i64 %index, i32 0 ; INTER-NOT: getelementptr ; INTER: br i1 {{.*}}, label %middle.block, label %vector.body ; define i32 @interleaved_access_forward(%pair* %p, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ 0, %entry ] %tmp0 = phi i32 [ %tmp6, %for.body ], [ 0, %entry ] %tmp1 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 %tmp2 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 1 %tmp3 = load i32, i32* %tmp1, align 8 %tmp4 = load i32, i32* %tmp2, align 8 %tmp5 = add i32 %tmp3, %tmp4 %tmp6 = add i32 %tmp0, %tmp5 %i.next = add nuw nsw i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: %tmp14 = phi i32 [ %tmp6, %for.body ] ret i32 %tmp14 } ; CHECK-LABEL: interleaved_access_reverse ; INTER-LABEL: interleaved_access_reverse ; ; Check that a consecutive-like pointer used by a reverse interleaved group is ; recognized as uniform and remains uniform after vectorization. When ; interleaved memory accesses aren't enabled, the pointer should not be ; recognized as uniform, and it should not be uniform after vectorization. ; ; recognized as uniform, and it should not be uniform after vectorization. ; CHECK-NOT: LV: Found uniform instruction: %tmp1 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 ; CHECK-NOT: LV: Found uniform instruction: %tmp2 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 1 ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK: %offset.idx = sub i64 %n, %index ; CHECK: %[[I1:.+]] = add i64 %offset.idx, -1 ; CHECK: %[[I2:.+]] = add i64 %offset.idx, -2 ; CHECK: %[[I3:.+]] = add i64 %offset.idx, -3 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %offset.idx, i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I1]], i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I2]], i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I3]], i32 0 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %offset.idx, i32 1 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I1]], i32 1 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I2]], i32 1 ; CHECK: getelementptr inbounds %pair, %pair* %p, i64 %[[I3]], i32 1 ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; ; INTER: LV: Found uniform instruction: %tmp1 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 ; INTER: LV: Found uniform instruction: %tmp2 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 1 ; INTER: vector.body ; INTER: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; INTER: %offset.idx = sub i64 %n, %index ; INTER-NOT: getelementptr ; INTER: %[[G0:.+]] = getelementptr inbounds %pair, %pair* %p, i64 %offset.idx, i32 0 ; INTER: getelementptr inbounds i32, i32* %[[G0]], i64 -6 ; INTER-NOT: getelementptr ; INTER: br i1 {{.*}}, label %middle.block, label %vector.body ; define i32 @interleaved_access_reverse(%pair* %p, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ %n, %entry ] %tmp0 = phi i32 [ %tmp6, %for.body ], [ 0, %entry ] %tmp1 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 %tmp2 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 1 %tmp3 = load i32, i32* %tmp1, align 8 %tmp4 = load i32, i32* %tmp2, align 8 %tmp5 = add i32 %tmp3, %tmp4 %tmp6 = add i32 %tmp0, %tmp5 %i.next = add nuw nsw i64 %i, -1 %cond = icmp sgt i64 %i.next, 0 br i1 %cond, label %for.body, label %for.end for.end: %tmp14 = phi i32 [ %tmp6, %for.body ] ret i32 %tmp14 } ; INTER-LABEL: predicated_store ; ; Check that a consecutive-like pointer used by a forward interleaved group and ; scalarized store is not recognized as uniform and is not uniform after ; vectorization. The store is scalarized because it's in a predicated block. ; Even though the load in this example is vectorized and only uses the pointer ; as if it were uniform, the store is scalarized, making the pointer ; non-uniform. ; ; INTER-NOT: LV: Found uniform instruction: %tmp0 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 ; INTER: vector.body ; INTER: %index = phi i64 [ 0, %vector.ph ], [ %index.next, {{.*}} ] ; INTER: %[[G0:.+]] = getelementptr inbounds %pair, %pair* %p, i64 %index, i32 0 ; INTER: %[[B0:.+]] = bitcast i32* %[[G0]] to <8 x i32>* ; INTER: %wide.vec = load <8 x i32>, <8 x i32>* %[[B0]], align 8 ; INTER: %[[I1:.+]] = or i64 %index, 1 ; INTER: getelementptr inbounds %pair, %pair* %p, i64 %[[I1]], i32 0 ; INTER: %[[I2:.+]] = or i64 %index, 2 ; INTER: getelementptr inbounds %pair, %pair* %p, i64 %[[I2]], i32 0 ; INTER: %[[I3:.+]] = or i64 %index, 3 ; INTER: getelementptr inbounds %pair, %pair* %p, i64 %[[I3]], i32 0 ; INTER: br i1 {{.*}}, label %middle.block, label %vector.body ; define void @predicated_store(%pair *%p, i32 %x, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %if.merge ], [ 0, %entry ] %tmp0 = getelementptr inbounds %pair, %pair* %p, i64 %i, i32 0 %tmp1 = load i32, i32* %tmp0, align 8 %tmp2 = icmp eq i32 %tmp1, %x br i1 %tmp2, label %if.then, label %if.merge if.then: store i32 %tmp1, i32* %tmp0, align 8 br label %if.merge if.merge: %i.next = add nuw nsw i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: ret void } ; CHECK-LABEL: irregular_type ; ; Check that a consecutive pointer used by a scalarized store is not recognized ; as uniform and is not uniform after vectorization. The store is scalarized ; because the stored type may required padding. ; ; CHECK-NOT: LV: Found uniform instruction: %tmp1 = getelementptr inbounds x86_fp80, x86_fp80* %a, i64 %i ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK: %[[I1:.+]] = or i64 %index, 1 ; CHECK: %[[I2:.+]] = or i64 %index, 2 ; CHECK: %[[I3:.+]] = or i64 %index, 3 ; CHECK: getelementptr inbounds x86_fp80, x86_fp80* %a, i64 %index ; CHECK: getelementptr inbounds x86_fp80, x86_fp80* %a, i64 %[[I1]] ; CHECK: getelementptr inbounds x86_fp80, x86_fp80* %a, i64 %[[I2]] ; CHECK: getelementptr inbounds x86_fp80, x86_fp80* %a, i64 %[[I3]] ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; define void @irregular_type(x86_fp80* %a, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ 0, %entry ], [ %i.next, %for.body ] %tmp0 = sitofp i32 1 to x86_fp80 %tmp1 = getelementptr inbounds x86_fp80, x86_fp80* %a, i64 %i store x86_fp80 %tmp0, x86_fp80* %tmp1, align 16 %i.next = add i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: ret void } ; CHECK-LABEL: pointer_iv_uniform ; ; Check that a pointer induction variable is recognized as uniform and remains ; uniform after vectorization. ; ; CHECK: LV: Found uniform instruction: %p = phi i32* [ %tmp03, %for.body ], [ %a, %entry ] ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK-NOT: getelementptr ; CHECK: %next.gep = getelementptr i32, i32* %a, i64 %index ; CHECK-NOT: getelementptr ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; define void @pointer_iv_uniform(i32* %a, i32 %x, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ 0, %entry ] %p = phi i32* [ %tmp03, %for.body ], [ %a, %entry ] store i32 %x, i32* %p, align 8 %tmp03 = getelementptr inbounds i32, i32* %p, i32 1 %i.next = add nuw nsw i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: ret void } ; INTER-LABEL: pointer_iv_non_uniform_0 ; ; Check that a pointer induction variable with a non-uniform user is not ; recognized as uniform and is not uniform after vectorization. The pointer ; induction variable is used by getelementptr instructions that are non-uniform ; due to scalarization of the stores. ; ; INTER-NOT: LV: Found uniform instruction: %p = phi i32* [ %tmp03, %for.body ], [ %a, %entry ] ; INTER: vector.body ; INTER: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; INTER: %[[I0:.+]] = shl i64 %index, 2 ; INTER: %next.gep = getelementptr i32, i32* %a, i64 %[[I0]] ; INTER: %[[S1:.+]] = shl i64 %index, 2 ; INTER: %[[I1:.+]] = or i64 %[[S1]], 4 ; INTER: %next.gep2 = getelementptr i32, i32* %a, i64 %[[I1]] ; INTER: %[[S2:.+]] = shl i64 %index, 2 ; INTER: %[[I2:.+]] = or i64 %[[S2]], 8 ; INTER: %next.gep3 = getelementptr i32, i32* %a, i64 %[[I2]] ; INTER: %[[S3:.+]] = shl i64 %index, 2 ; INTER: %[[I3:.+]] = or i64 %[[S3]], 12 ; INTER: %next.gep4 = getelementptr i32, i32* %a, i64 %[[I3]] ; INTER: br i1 {{.*}}, label %middle.block, label %vector.body ; define void @pointer_iv_non_uniform_0(i32* %a, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ 0, %entry ] %p = phi i32* [ %tmp03, %for.body ], [ %a, %entry ] %tmp00 = load i32, i32* %p, align 8 %tmp01 = getelementptr inbounds i32, i32* %p, i32 1 %tmp02 = load i32, i32* %tmp01, align 8 %tmp03 = getelementptr inbounds i32, i32* %p, i32 4 %tmp04 = load i32, i32* %tmp03, align 8 %tmp05 = getelementptr inbounds i32, i32* %p, i32 5 %tmp06 = load i32, i32* %tmp05, align 8 %tmp07 = sub i32 %tmp04, %tmp00 %tmp08 = sub i32 %tmp02, %tmp02 %tmp09 = getelementptr inbounds i32, i32* %p, i32 2 store i32 %tmp07, i32* %tmp09, align 8 %tmp10 = getelementptr inbounds i32, i32* %p, i32 3 store i32 %tmp08, i32* %tmp10, align 8 %i.next = add nuw nsw i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: ret void } ; CHECK-LABEL: pointer_iv_non_uniform_1 ; ; Check that a pointer induction variable with a non-uniform user is not ; recognized as uniform and is not uniform after vectorization. The pointer ; induction variable is used by a store that will be scalarized. ; ; CHECK-NOT: LV: Found uniform instruction: %p = phi x86_fp80* [%tmp1, %for.body], [%a, %entry] ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK: %next.gep = getelementptr x86_fp80, x86_fp80* %a, i64 %index ; CHECK: %[[I1:.+]] = or i64 %index, 1 ; CHECK: %next.gep2 = getelementptr x86_fp80, x86_fp80* %a, i64 %[[I1]] ; CHECK: %[[I2:.+]] = or i64 %index, 2 ; CHECK: %next.gep3 = getelementptr x86_fp80, x86_fp80* %a, i64 %[[I2]] ; CHECK: %[[I3:.+]] = or i64 %index, 3 ; CHECK: %next.gep4 = getelementptr x86_fp80, x86_fp80* %a, i64 %[[I3]] ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; define void @pointer_iv_non_uniform_1(x86_fp80* %a, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ 0, %entry ] %p = phi x86_fp80* [%tmp1, %for.body], [%a, %entry] %tmp0 = sitofp i32 1 to x86_fp80 store x86_fp80 %tmp0, x86_fp80* %p, align 16 %tmp1 = getelementptr inbounds x86_fp80, x86_fp80* %p, i32 1 %i.next = add i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: ret void } ; CHECK-LABEL: pointer_iv_mixed ; ; Check multiple pointer induction variables where only one is recognized as ; uniform and remains uniform after vectorization. The other pointer induction ; variable is not recognized as uniform and is not uniform after vectorization ; because it is stored to memory. ; ; CHECK-NOT: LV: Found uniform instruction: %p = phi i32* [ %tmp3, %for.body ], [ %a, %entry ] ; CHECK: LV: Found uniform instruction: %q = phi i32** [ %tmp4, %for.body ], [ %b, %entry ] ; CHECK: vector.body ; CHECK: %index = phi i64 [ 0, %vector.ph ], [ %index.next, %vector.body ] ; CHECK: %next.gep = getelementptr i32, i32* %a, i64 %index ; CHECK: %[[I1:.+]] = or i64 %index, 1 ; CHECK: %next.gep10 = getelementptr i32, i32* %a, i64 %[[I1]] ; CHECK: %[[I2:.+]] = or i64 %index, 2 ; CHECK: %next.gep11 = getelementptr i32, i32* %a, i64 %[[I2]] ; CHECK: %[[I3:.+]] = or i64 %index, 3 ; CHECK: %next.gep12 = getelementptr i32, i32* %a, i64 %[[I3]] ; CHECK: %[[V0:.+]] = insertelement <4 x i32*> undef, i32* %next.gep, i32 0 ; CHECK: %[[V1:.+]] = insertelement <4 x i32*> %[[V0]], i32* %next.gep10, i32 1 ; CHECK: %[[V2:.+]] = insertelement <4 x i32*> %[[V1]], i32* %next.gep11, i32 2 ; CHECK: %[[V3:.+]] = insertelement <4 x i32*> %[[V2]], i32* %next.gep12, i32 3 ; CHECK-NOT: getelementptr ; CHECK: %next.gep13 = getelementptr i32*, i32** %b, i64 %index ; CHECK-NOT: getelementptr ; CHECK: %[[B0:.+]] = bitcast i32** %next.gep13 to <4 x i32*>* ; CHECK: store <4 x i32*> %[[V3]], <4 x i32*>* %[[B0]], align 8 ; CHECK: br i1 {{.*}}, label %middle.block, label %vector.body ; define i32 @pointer_iv_mixed(i32* %a, i32** %b, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ %i.next, %for.body ], [ 0, %entry ] %p = phi i32* [ %tmp3, %for.body ], [ %a, %entry ] %q = phi i32** [ %tmp4, %for.body ], [ %b, %entry ] %tmp0 = phi i32 [ %tmp2, %for.body ], [ 0, %entry ] %tmp1 = load i32, i32* %p, align 8 %tmp2 = add i32 %tmp1, %tmp0 store i32* %p, i32** %q, align 8 %tmp3 = getelementptr inbounds i32, i32* %p, i32 1 %tmp4 = getelementptr inbounds i32*, i32** %q, i32 1 %i.next = add nuw nsw i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: %tmp5 = phi i32 [ %tmp2, %for.body ] ret i32 %tmp5 } ; INTER-LABEL: bitcast_pointer_operand ; ; Check that a pointer operand having a user other than a memory access is ; recognized as uniform after vectorization. In this test case, %tmp1 is a ; bitcast that is used by a load and a getelementptr instruction (%tmp2). Once ; %tmp2 is marked uniform, %tmp1 should be marked uniform as well. ; ; INTER: LV: Found uniform instruction: %cond = icmp slt i64 %i.next, %n ; INTER-NEXT: LV: Found uniform instruction: %tmp2 = getelementptr inbounds i8, i8* %tmp1, i64 3 ; INTER-NEXT: LV: Found uniform instruction: %tmp6 = getelementptr inbounds i8, i8* %B, i64 %i ; INTER-NEXT: LV: Found uniform instruction: %tmp1 = bitcast i64* %tmp0 to i8* ; INTER-NEXT: LV: Found uniform instruction: %tmp0 = getelementptr inbounds i64, i64* %A, i64 %i ; INTER-NEXT: LV: Found uniform instruction: %i = phi i64 [ 0, %entry ], [ %i.next, %for.body ] ; INTER-NEXT: LV: Found uniform instruction: %i.next = add nuw nsw i64 %i, 1 ; INTER: vector.body: ; INTER-NEXT: [[INDEX:%.*]] = phi i64 [ 0, %vector.ph ], [ [[INDEX_NEXT:%.*]], %vector.body ] ; INTER-NEXT: [[TMP4:%.*]] = getelementptr inbounds i64, i64* %A, i64 [[INDEX]] ; INTER-NEXT: [[TMP5:%.*]] = bitcast i64* [[TMP4]] to <32 x i8>* ; INTER-NEXT: [[WIDE_VEC:%.*]] = load <32 x i8>, <32 x i8>* [[TMP5]], align 1 ; INTER-NEXT: [[STRIDED_VEC:%.*]] = shufflevector <32 x i8> [[WIDE_VEC]], <32 x i8> undef, <4 x i32> <i32 0, i32 8, i32 16, i32 24> ; INTER-NEXT: [[STRIDED_VEC5:%.*]] = shufflevector <32 x i8> [[WIDE_VEC]], <32 x i8> undef, <4 x i32> <i32 3, i32 11, i32 19, i32 27> ; INTER-NEXT: [[TMP6:%.*]] = xor <4 x i8> [[STRIDED_VEC5]], [[STRIDED_VEC]] ; INTER-NEXT: [[TMP7:%.*]] = getelementptr inbounds i8, i8* %B, i64 [[INDEX]] ; INTER-NEXT: [[TMP8:%.*]] = bitcast i8* [[TMP7]] to <4 x i8>* ; INTER-NEXT: store <4 x i8> [[TMP6]], <4 x i8>* [[TMP8]], align 1 ; INTER-NEXT: [[INDEX_NEXT]] = add i64 [[INDEX]], 4 ; INTER: br i1 {{.*}}, label %middle.block, label %vector.body ; define void @bitcast_pointer_operand(i64* %A, i8* %B, i64 %n) { entry: br label %for.body for.body: %i = phi i64 [ 0, %entry ], [ %i.next, %for.body ] %tmp0 = getelementptr inbounds i64, i64* %A, i64 %i %tmp1 = bitcast i64* %tmp0 to i8* %tmp2 = getelementptr inbounds i8, i8* %tmp1, i64 3 %tmp3 = load i8, i8* %tmp2, align 1 %tmp4 = load i8, i8* %tmp1, align 1 %tmp5 = xor i8 %tmp3, %tmp4 %tmp6 = getelementptr inbounds i8, i8* %B, i64 %i store i8 %tmp5, i8* %tmp6 %i.next = add nuw nsw i64 %i, 1 %cond = icmp slt i64 %i.next, %n br i1 %cond, label %for.body, label %for.end for.end: ret void }
{ "pile_set_name": "Github" }
QT += core sql QT -= gui TARGET = quant_trader_bundle CONFIG += console c++14 CONFIG -= app_bundle TEMPLATE = app LAZZYQUANT_ROOT = $$PWD/../.. SOURCES += \ quant_trader_bundle.cpp \ $$LAZZYQUANT_ROOT/tick_replayer/replay_sources.cpp \ main.cpp HEADERS += \ quant_trader_bundle.h \ $$LAZZYQUANT_ROOT/tick_replayer/replay_sources.h \ $$LAZZYQUANT_ROOT/quant_trader/quant_trader_options.h \ $$LAZZYQUANT_ROOT/quant_trader/quant_trader_manager.h \ $$LAZZYQUANT_ROOT/config.h INCLUDEPATH += $$LAZZYQUANT_ROOT include($$LAZZYQUANT_ROOT/common/common.pri) include($$LAZZYQUANT_ROOT/quant_trader/quant_trader.pri) include($$LAZZYQUANT_ROOT/tick_replayer/ctp_replayer/ctp_replayer.pri) include($$LAZZYQUANT_ROOT/tick_replayer/sinyee_replayer/sinyee_replayer.pri) include($$LAZZYQUANT_ROOT/market_watcher/market_watcher.pri) include($$LAZZYQUANT_ROOT/trade_executer/trade_executer.pri) include($$LAZZYQUANT_ROOT/ctp/mduser.pri) include($$LAZZYQUANT_ROOT/ctp/trader.pri)
{ "pile_set_name": "Github" }
(alias (name dump_inheritance) (deps %{exe:../../src/hh_single_type_check.exe} %{project_root}/test/verify.py %{project_root}/test/review.sh (glob_files %{project_root}/test/dump_inheritance/HH_FLAGS) (glob_files %{project_root}/test/dump_inheritance/*.php) (glob_files %{project_root}/test/dump_inheritance/*.exp)) (action (run %{project_root}/test/verify.py %{project_root}/test/dump_inheritance --program %{exe:../../src/hh_single_type_check.exe}))) (alias (name runtest) (deps (alias dump_inheritance)))
{ "pile_set_name": "Github" }
log-view: nickname-format: '%n: ' scroller-highlight-color: '#e28964' input-text: font-family: 'Monaco' font-size: 14.0 background-color: '#1f4662' color: '#a4fff2' selected: background-color: '#a4fff2' member-list: font-family: 'Monaco' font-size: 12.0 color: '#aaaaaa' background-color: '#25323c' operator: color: '#fdc800' selected: color: '#fff' background: # gradient top-line-color: '#33404b' bottom-line-color: '#ffc600' top-color: '#33404b' bottom-color: '#33404b' server-tree: font-family: 'Monaco' font-size: 12.0 background-color: '#16222e' highlight: color: '#36434e' newtalk: color: '#4cda00' unread: color: '#4cda00' normal: active: color: '#fdc800' inactive: color: '#7d7d7d' selected: active: color: '#ffffff' inactive: color: '#8d9aa5' background: # gradient top-line-color: '#33404b' bottom-line-color: '#ffc600' top-color: '#33404b' bottom-color: '#33404b'
{ "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.camel.component.file.remote; import org.apache.camel.component.mock.MockEndpoint; public class FtpSimpleConsumeStreamingStepwiseTrueTest extends FtpSimpleConsumeStreamingStepwiseFalseTest { @Override boolean isStepwise() { return true; } @Override MockEndpoint getMockEndpoint() { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); return mock; } @Override void assertMore(MockEndpoint mock) { } }
{ "pile_set_name": "Github" }
import { Injectable } from "@graphql-modules/di"; import User from "./user.type"; import createUsers from "./user.seed"; @Injectable() export default class UserService { private readonly users: User[] = createUsers(); getAll() { return this.users; } findById(id: number) { return this.users.find(it => it.id === id); } }
{ "pile_set_name": "Github" }
package model import scalikejdbc._ import org.joda.time.DateTime import skinny.orm.SkinnyCRUDMapperWithId import skinny.orm.feature._ case class Company( id: CompanyId, name: String, url: Option[String] = None, createdAt: DateTime, updatedAt: Option[DateTime] = None, deletedAt: Option[DateTime] = None ) object Company extends SkinnyCRUDMapperWithId[CompanyId, Company] with TimestampsFeatureWithId[CompanyId, Company] with SoftDeleteWithTimestampFeatureWithId[CompanyId, Company] { override val defaultAlias = createAlias("c") def idToRawValue(id: CompanyId) = id.value def rawValueToId(value: Any) = CompanyId(value.toString.toLong) override def extract(rs: WrappedResultSet, c: ResultName[Company]): Company = autoConstruct(rs, c) }
{ "pile_set_name": "Github" }
diff --git a/Fern-Wifi-Cracker/core/fern.py b/Fern-Wifi-Cracker/core/fern.py index 286ed15..e8e5b3d 100644 --- a/Fern-Wifi-Cracker/core/fern.py +++ b/Fern-Wifi-Cracker/core/fern.py @@ -75,23 +75,7 @@ class mainwindow(QtGui.QDialog,Ui_Dialog): self.connect(self,QtCore.SIGNAL("wpa_button_false"),self.wpa_button_false) self.connect(self.database_button,QtCore.SIGNAL("clicked()"),self.database_window) - self.connect(self.update_button,QtCore.SIGNAL("clicked()"),self.update_fern) - self.connect(self,QtCore.SIGNAL("finished downloading"),self.finished_downloading_files) - self.connect(self,QtCore.SIGNAL("restart application"),self.restart_application) - self.connect(self,QtCore.SIGNAL("failed update"),self.update_fail) - self.connect(self,QtCore.SIGNAL("already latest update"),self.latest_update) - self.connect(self,QtCore.SIGNAL("previous message"),self.latest_svn) - self.connect(self,QtCore.SIGNAL("new update available"),self.new_update_avialable) - self.connect(self,QtCore.SIGNAL("current_version"),self.current_update) - self.connect(self,QtCore.SIGNAL("download failed"),self.download_failed) self.connect(self,QtCore.SIGNAL('internal scan error'),self.scan_error_display) - self.connect(self,QtCore.SIGNAL('file downloaded'),self.downloading_update_files) - - - self.update_label.setText('<font color=green>Currently installed version: Revision %s</font>'%(self.installed_revision())) - - # Display update status on main_windows - thread.start_new_thread(self.update_initializtion_check,()) self.set_WindowFlags() @@ -146,180 +130,6 @@ class mainwindow(QtGui.QDialog,Ui_Dialog): self.settings.create_settings("xterm",str()) variables.xterm_setting = self.settings.read_last_settings("xterm") - - # - # SIGNALs for update threads - # - def update_fail(self): - self.update_label.setText('<font color=red>Unable to check for updates,network timeout') - - def download_failed(self): - self.update_label.setText('<font color=red>Download failed,network timeout') - - def downloading_update_files(self): - global file_total - global files_downloaded - - self.update_label.setText('<font color=green>Downloading.. %s Complete</font>'\ - %(self.percentage(files_downloaded,file_total))) - - - def installed_revision(self): - svn_info = commands.getstatusoutput('svn info ' + directory) - if svn_info[0] == 0: - svn_version = svn_info[1].splitlines()[4].strip('Revision: ') - else: - svn_version = '94' - return svn_version - - def finished_downloading_files(self): - self.update_label.setText('<font color=green>Finished Downloading</font>') - - def restart_application(self): - self.update_label.setText('<font color=red>Please Restart application</font>') - - def latest_update(self): - self.update_label.setText('<font color=green>No new update is available for download</font>') - - def current_update(self): - self.update_label.setText('<font color=green>Currently installed version: Revision %s</font>'%(self.installed_revision())) - - - def latest_svn(self): - self.update_label.setText('<font color=green>Latest update is already installed</font>') - - def new_update_avialable(self): - self.update_label.setText('<font color=green>New Update is Available</font>') - self.update_button.setFocus() - - def update_error(self): - global svn_access - global svn_failure_message - svn_failure_message = str() - svn_failure = svn_access.stderr - svn_failure_message = svn_failure.read() - - - # - # Update Fern application via SVN,updates at ("svn checkout http://github.com/savio-code/fern-wifi-cracker/trunk/Fern-Wifi-Cracker/") - # - def update_fern(self): - global updater_control - updater_control = 1 - self.update_label.setText('<font color=green>Checking for update...</font>') - thread.start_new_thread(self.update_launcher,()) - - - def percentage(self,current,total): - float_point = float(current)/float(total) - calculation = int(float_point * 100) - percent = str(calculation) + '%' - return(percent) - - - def update_launcher(self): - ''' Downloads and installs update files - ''' - global svn_access - global file_total - global files_downloaded - global fern_directory - - file_total = int() - files_downloaded = int() - - fern_directory = os.getcwd() - - update_directory = '/tmp/Fern-Wifi-Cracker/' - - try: - online_response_check = urllib2.urlopen('https://raw.githubusercontent.com/savio-code/fern-wifi-cracker/master/Fern-Wifi-Cracker/version') - online_response = online_response_check.read() - - online_files = re.compile('total_files = \d+',re.IGNORECASE) - - for online_file_total in online_response.splitlines(): - if re.match(online_files,online_file_total): - file_total = int(online_file_total.split()[2]) - - if 'Fern-Wifi-Cracker' in os.listdir('/tmp/'): - variables.exec_command('rm -r /tmp/Fern-Wifi-Cracker') - - svn_access = subprocess.Popen('cd /tmp/ \n svn checkout https://github.com/savio-code/fern-wifi-cracker/trunk/Fern-Wifi-Cracker/',\ - shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE) - svn_update = svn_access.stdout - thread.start_new_thread(self.update_error,()) - while True: - response = svn_update.readline() - if len(response) > 0: - files_downloaded += 1 - self.emit(QtCore.SIGNAL('file downloaded')) - - if str('revision') in str(response): - self.emit(QtCore.SIGNAL("finished downloading")) - # Delete all old files (*.py,*.py etc) except ".font_setting.dat" file - for old_file in os.listdir(os.getcwd()): - if os.path.isfile(os.getcwd() + os.sep + old_file) and old_file != '.font_settings.dat': - os.remove(os.getcwd() + os.sep + old_file) - # Delete all old directories except the "key-database" directory - for old_directory in os.listdir(os.getcwd()): - if os.path.isdir(os.getcwd() + os.sep + old_directory) and old_directory != 'key-database': - shutil.rmtree(os.getcwd() + os.sep + old_directory) - - for update_file in os.listdir('/tmp/Fern-Wifi-Cracker'): # Copy New update files to working directory - if os.path.isfile(update_directory + update_file): - shutil.copyfile(update_directory + update_file,os.getcwd() + os.sep + update_file) - else: - shutil.copytree(update_directory + update_file,os.getcwd() + os.sep + update_file) - - for new_file in os.listdir(os.getcwd()): # chmod New files to allow permissions - os.chmod(os.getcwd() + os.sep + new_file,0777) - - time.sleep(5) - self.emit(QtCore.SIGNAL("restart application")) - break - if len(svn_failure_message) > 2: - self.emit(QtCore.SIGNAL("download failed")) - break - - except(urllib2.URLError,urllib2.HTTPError): - self.emit(QtCore.SIGNAL("download failed")) - - - # - # Update checker Thread - # - def update_initializtion_check(self): - global updater_control - updater_control = 0 - while updater_control != 1: - try: - online_response_thread = urllib2.urlopen('https://raw.githubusercontent.com/savio-code/fern-wifi-cracker/master/Fern-Wifi-Cracker/version') - online_response_string = '' - online_response = online_response_thread.read() - - online_version = re.compile('version = \d+\.?\d+',re.IGNORECASE) - - for version_iterate in online_response.splitlines(): - if re.match(online_version,version_iterate): - online_response_string += version_iterate - - update_version_number = float(online_response_string.split()[2]) - - if float(__version__) != update_version_number: - self.emit(QtCore.SIGNAL("new update available")) - break - - if float(__version__) == update_version_number: - self.emit(QtCore.SIGNAL("already latest update")) - time.sleep(20) - self.emit(QtCore.SIGNAL("previous message")) - break - - except Exception: - self.emit(QtCore.SIGNAL("failed update")) - time.sleep(9) - # # Launches Tool Box window # diff --git a/Fern-Wifi-Cracker/gui/main_window.py b/Fern-Wifi-Cracker/gui/main_window.py index bf18711..4c347ce 100644 --- a/Fern-Wifi-Cracker/gui/main_window.py +++ b/Fern-Wifi-Cracker/gui/main_window.py @@ -62,17 +62,11 @@ class Ui_Dialog(object): self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) spacerItem1 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) - self.update_label = QtGui.QLabel(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.update_label.sizePolicy().hasHeightForWidth()) - self.update_label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setPointSize(font_setting) - self.update_label.setFont(font) - self.update_label.setObjectName(_fromUtf8("update_label")) - self.horizontalLayout_3.addWidget(self.update_label) self.verticalLayout_24.addLayout(self.horizontalLayout_3) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) @@ -82,22 +76,13 @@ class Ui_Dialog(object): self.horizontalLayout.addItem(spacerItem2) self.verticalLayout_22 = QtGui.QVBoxLayout() self.verticalLayout_22.setObjectName(_fromUtf8("verticalLayout_22")) - self.update_button = QtGui.QPushButton(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.update_button.sizePolicy().hasHeightForWidth()) - self.update_button.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setPointSize(font_setting) - self.update_button.setFont(font) - self.update_button.setText(_fromUtf8("")) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1295008956_system-software-update.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.update_button.setIcon(icon1) - self.update_button.setIconSize(QtCore.QSize(35, 34)) - self.update_button.setObjectName(_fromUtf8("update_button")) - self.verticalLayout_22.addWidget(self.update_button) spacerItem3 = QtGui.QSpacerItem(13, 30, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.verticalLayout_22.addItem(spacerItem3) self.horizontalLayout.addLayout(self.verticalLayout_22) @@ -500,7 +485,6 @@ class Ui_Dialog(object): pythonver = str(sys.version) display = str(commands.getstatusoutput('aircrack-ng')) Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Fern WIFI Cracker", None, QtGui.QApplication.UnicodeUTF8)) - self.update_label.setText(QtGui.QApplication.translate("Dialog", "Latest update is installed: Revision 10", None, QtGui.QApplication.UnicodeUTF8)) self.py_version_label.setText(QtGui.QApplication.translate("Dialog", "Python Version: <font color=green>%s</font>"%(pythonver[0:14].replace('(',(''))), None, QtGui.QApplication.UnicodeUTF8)) self.air_version.setText(QtGui.QApplication.translate("Dialog", "Aircrack Version: <font color=green>%s</font>"%(display[11:33]), None, QtGui.QApplication.UnicodeUTF8)) self.qt_version.setText(QtGui.QApplication.translate("Dialog", "Qt Version: <font color=green>%s</font>"%(QtCore.PYQT_VERSION_STR), None, QtGui.QApplication.UnicodeUTF8))
{ "pile_set_name": "Github" }
40--Gymnastics/40_Gymnastics_Gymnastics_40_911.jpg 0
{ "pile_set_name": "Github" }
###################################################################### # Automatically generated by qmake (2.00a) Wed May 3 15:25:22 2006 ###################################################################### TEMPLATE = app TARGET += DEPENDPATH += . INCLUDEPATH += . # Input SOURCES += main.cpp
{ "pile_set_name": "Github" }
<cfscript> /** * Redirects the browser to the supplied controller/action/key, route or back to the referring page. * Internally, this function uses the `URLFor` function to build the link and the `cflocation` tag to perform the redirect. * * [section: Controller] * [category: Miscellaneous Functions] * * @back Set to `true` to redirect back to the referring page. * @addToken See documentation for your CFML engine's implementation of `cflocation`. * @statusCode See documentation for your CFML engine's implementation of `cflocation`. * @route Name of a route that you have configured in `config/routes.cfm`. * @controller Name of the controller to include in the URL. * @action Name of the action to include in the URL. * @key Key(s) to include in the URL. * @params Any additional parameters to be set in the query string (example: `wheels=cool&x=y`). Please note that CFWheels uses the `&` and `=` characters to split the parameters and encode them properly for you. However, if you need to pass in `&` or `=` as part of the value, then you need to encode them (and only them), example: `a=cats%26dogs%3Dtrouble!&b=1`. * @anchor Sets an anchor name to be appended to the path. * @onlyPath If `true`, returns only the relative URL (no protocol, host name or port). * @host Set this to override the current host. * @protocol Set this to override the current protocol. * @port Set this to override the current port number. * @url Redirect to an external URL. * @delay Set to `true` to delay the redirection until after the rest of your action code has executed. * @encode [see:URLFor]. */ public void function redirectTo( boolean back = false, boolean addToken, numeric statusCode, string route = "", string method = "", string controller = "", string action = "", any key = "", string params = "", string anchor = "", boolean onlyPath, string host, string protocol, numeric port, string url = "", boolean delay, boolean encode ) { $args(name = "redirectTo", args = arguments); // Set flash if passed in. // If more than the arguments listed in the function declaration was passed in it's possible that one of them is intended for the flash. local.functionInfo = GetMetadata(variables.redirectTo); if (StructCount(arguments) > ArrayLen(local.functionInfo.parameters)) { // Create a list of all the argument names that should not be set to the flash. // This includes arguments to the function itself or ones meant for a route. local.nonFlashArgumentNames = ""; if (Len(arguments.route)) { local.nonFlashArgumentNames = ListAppend( local.nonFlashArgumentNames, $findRoute(argumentCollection = arguments).variables ); } local.iEnd = ArrayLen(local.functionInfo.parameters); for (local.i = 1; local.i <= local.iEnd; local.i++) { local.nonFlashArgumentNames = ListAppend(local.nonFlashArgumentNames, local.functionInfo.parameters[local.i].name); } // Loop through arguments and when the first flash argument is found we set it. local.argumentNames = StructKeyList(arguments); local.iEnd = ListLen(local.argumentNames); for (local.i = 1; local.i <= local.iEnd; local.i++) { local.item = ListGetAt(local.argumentNames, local.i); if (!ListFindNoCase(local.nonFlashArgumentNames, local.item)) { local.key = ReReplaceNoCase(local.item, "^flash(.)", "\l\1"); local.flashArguments = {}; local.flashArguments[local.key] = arguments[local.item]; flashInsert(argumentCollection = local.flashArguments); } } } // Set the url that will be used in the cflocation tag. if (arguments.back) { if (Len(request.cgi.http_referer) && FindNoCase(request.cgi.server_name, request.cgi.http_referer)) { // Referrer exists and points to the same domain so it's ok to redirect to it. local.url = request.cgi.http_referer; if (Len(arguments.params)) { // Append params to the referrer url. local.params = $constructParams(params = arguments.params, encode = arguments.encode); if (Find("?", request.cgi.http_referer)) { local.params = Replace(local.params, "?", "&"); } else if (Left(local.params, 1) == "&" && !Find(request.cgi.http_referer, "?")) { local.params = Replace(local.params, "&", "?", "one"); } local.url &= local.params; } } else { // We can't redirect to the referrer so we either use a fallback route/controller/action combo or send to the root of the site. if (Len(arguments.route) || Len(arguments.controller) || Len(arguments.action)) { local.url = uRLFor(argumentCollection = arguments); } else { local.url = $get("webPath"); } } } else if (Len(arguments.url)) { local.url = arguments.url; if (Len(arguments.params)) { if (Find("?", arguments.url)) { local.url = "#local.url#&#arguments.params#"; } else { local.url = "#local.url#?#arguments.params#"; } } } else { local.url = uRLFor(argumentCollection = arguments); } // Schedule or perform the redirect right away. if (arguments.delay) { if (StructKeyExists(variables.$instance, "redirect")) { // Throw an error if the developer has already scheduled a redirect previously in this request. Throw(type = "Wheels.RedirectToAlreadyCalled", message = "`redirectTo()` was already called."); } else { // Schedule a redirect that will happen after the action code has been completed. variables.$instance.redirect = {}; variables.$instance.redirect.url = local.url; variables.$instance.redirect.addToken = arguments.addToken; variables.$instance.redirect.statusCode = arguments.statusCode; variables.$instance.redirect.$args = arguments; } } else { // Do the redirect now using cflocation. $location(url = local.url, addToken = arguments.addToken, statusCode = arguments.statusCode); } } </cfscript>
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>datasheet for ghrd_10as066n2_mm_bridge_0</title> <style type="text/css"> body { font-family:arial ;} a { text-decoration:underline ; color:#003000 ;} a:hover { text-decoration:underline ; color:0030f0 ;} td { padding : 5px ;} table.topTitle { width:100% ;} table.topTitle td.l { text-align:left ; font-weight: bold ; font-size:30px ;} table.topTitle td.r { text-align:right ; font-weight: bold ; font-size:16px ;} table.blueBar { width : 100% ; border-spacing : 0px ;} table.blueBar td { background:#0036ff ; font-size:12px ; color : white ; text-align : left ; font-weight : bold ;} table.blueBar td.l { text-align : left ;} table.blueBar td.r { text-align : right ;} table.items { width:100% ; border-collapse:collapse ;} table.items td.label { font-weight:bold ; font-size:16px ; vertical-align:top ;} table.items td.mono { font-family:courier ; font-size:12px ; white-space:pre ;} div.label { font-weight:bold ; font-size:16px ; vertical-align:top ; text-align:center ;} table.grid { border-collapse:collapse ;} table.grid td { border:1px solid #bbb ; font-size:12px ;} body { font-family:arial ;} table.x { font-family:courier ; border-collapse:collapse ; padding:2px ;} table.x td { border:1px solid #bbb ;} td.tableTitle { font-weight:bold ; text-align:center ;} table.grid { border-collapse:collapse ;} table.grid td { border:1px solid #bbb ;} table.grid td.tableTitle { font-weight:bold ; text-align:center ;} table.mmap { border-collapse:collapse ; text-size:11px ; border:1px solid #d8d8d8 ;} table.mmap td { border-color:#d8d8d8 ; border-width:1px ; border-style:solid ;} table.mmap td.empty { border-style:none ; background-color:#f0f0f0 ;} table.mmap td.slavemodule { text-align:left ; font-size:11px ; border-style:solid solid none solid ;} table.mmap td.slavem { text-align:right ; font-size:9px ; font-style:italic ; border-style:none solid none solid ;} table.mmap td.slaveb { text-align:right ; font-size:9px ; font-style:italic ; border-style:none solid solid solid ;} table.mmap td.mastermodule { text-align:center ; font-size:11px ; border-style:solid solid none solid ;} table.mmap td.masterlr { text-align:center ; font-size:9px ; font-style:italic ; border-style:none solid solid solid ;} table.mmap td.masterl { text-align:center ; font-size:9px ; font-style:italic ; border-style:none none solid solid ;} table.mmap td.masterm { text-align:center ; font-size:9px ; font-style:italic ; border-style:none none solid none ;} table.mmap td.masterr { text-align:center ; font-size:9px ; font-style:italic ; border-style:none solid solid none ;} table.mmap td.addr { font-family:courier ; font-size:9px ; text-align:right ;} table.connectionboxes { border-collapse:separate ; border-spacing:0px ; font-family:arial ;} table.connectionboxes td.from { border-bottom:1px solid black ; font-size:9px ; font-style:italic ; vertical-align:bottom ; text-align:left ;} table.connectionboxes td.to { font-size:9px ; font-style:italic ; vertical-align:top ; text-align:right ;} table.connectionboxes td.lefthandwire { border-bottom:1px solid black ; font-size:9px ; font-style:italic ; vertical-align:bottom ; text-align:right ;} table.connectionboxes td.righthandwire { border-bottom:1px solid black ; font-size:9px ; font-style:italic ; vertical-align:bottom ; text-align:left ;} table.connectionboxes td.righthandlabel { font-size:11px ; vertical-align:bottom ; text-align:left ;} table.connectionboxes td.neighbor { padding:3px ; border:1px solid black ; font-size: 11px ; background:#e8e8e8 ; vertical-align:center ; text-align:center ;} table.connectionboxes td.main { padding:8px ; border:1px solid black ; font-size: 14px ; font-weight:bold ; background:#ffffff ; vertical-align:center ; text-align:center ;} .parametersbox { border:1px solid #d0d0d0 ; display:inline-block ; max-height:160px ; overflow:auto ; width:360px ; font-size:10px ;} .flowbox { display:inline-block ;} .parametersbox table { font-size:10px ;} td.parametername { font-style:italic ;} td.parametervalue { font-weight:bold ;} div.greydiv { vertical-align:top ; text-align:center ; background:#eeeeee ; border-top:1px solid #707070 ; border-bottom:1px solid #707070 ; padding:20px ; margin:20px ; width:auto ;}</style> </head> <body> <table class="topTitle"> <tr> <td class="l">ghrd_10as066n2_mm_bridge_0</td> <td class="r"> <br/> <br/> </td> </tr> </table> <table class="blueBar"> <tr> <td class="l">2018.01.09.14:30:32</td> <td class="r">Datasheet</td> </tr> </table> <div style="width:100% ; height:10px"> </div> <div class="label">Overview</div> <div class="greydiv"> <div style="display:inline-block ; text-align:left"> <table class="connectionboxes"> <tr style="height:6px"> <td></td> </tr> </table> </div><span style="display:inline-block ; width:28px"> </span> <div style="display:inline-block ; text-align:left"><span> <br/>All Components <br/>&#160;&#160; <a href="#module_mm_bridge_0"><b>mm_bridge_0</b> </a> altera_avalon_mm_bridge 17.1</span> </div> </div> <div style="width:100% ; height:10px"> </div> <div class="label">Memory Map</div> <table class="mmap"> <tr> <td class="empty" rowspan="2"></td> </tr> </table> <a name="module_mm_bridge_0"> </a> <div> <hr/> <h2>mm_bridge_0</h2>altera_avalon_mm_bridge v17.1 <br/> <br/> <br/> <table class="flowbox"> <tr> <td class="parametersbox"> <h2>Parameters</h2> <table> <tr> <td class="parametername">DATA_WIDTH</td> <td class="parametervalue">512</td> </tr> <tr> <td class="parametername">SYMBOL_WIDTH</td> <td class="parametervalue">8</td> </tr> <tr> <td class="parametername">ADDRESS_WIDTH</td> <td class="parametervalue">32</td> </tr> <tr> <td class="parametername">USE_AUTO_ADDRESS_WIDTH</td> <td class="parametervalue">1</td> </tr> <tr> <td class="parametername">AUTO_ADDRESS_WIDTH</td> <td class="parametervalue">32</td> </tr> <tr> <td class="parametername">ADDRESS_UNITS</td> <td class="parametervalue">SYMBOLS</td> </tr> <tr> <td class="parametername">MAX_BURST_SIZE</td> <td class="parametervalue">16</td> </tr> <tr> <td class="parametername">MAX_PENDING_RESPONSES</td> <td class="parametervalue">4</td> </tr> <tr> <td class="parametername">LINEWRAPBURSTS</td> <td class="parametervalue">0</td> </tr> <tr> <td class="parametername">PIPELINE_COMMAND</td> <td class="parametervalue">1</td> </tr> <tr> <td class="parametername">PIPELINE_RESPONSE</td> <td class="parametervalue">1</td> </tr> <tr> <td class="parametername">USE_RESPONSE</td> <td class="parametervalue">0</td> </tr> <tr> <td class="parametername">deviceFamily</td> <td class="parametervalue">UNKNOWN</td> </tr> <tr> <td class="parametername">generateLegacySim</td> <td class="parametervalue">false</td> </tr> </table> </td> </tr> </table>&#160;&#160; <table class="flowbox"> <tr> <td class="parametersbox"> <h2>Software Assignments</h2>(none)</td> </tr> </table> </div> <table class="blueBar"> <tr> <td class="l">generation took 0.00 seconds</td> <td class="r">rendering took 0.00 seconds</td> </tr> </table> </body> </html>
{ "pile_set_name": "Github" }
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-571.js * @description ES5 Attributes - [[Get]] attribute is a function which involves 'this' object into statement(s) */ function testcase() { var obj = { len: 2010 }; var getFunc = function () { return this; }; Object.defineProperty(obj, "prop", { get: getFunc }); var desc = Object.getOwnPropertyDescriptor(obj, "prop"); return obj.hasOwnProperty("prop") && obj.prop === obj && desc.get === getFunc; } runTestCase(testcase);
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=struct.if_msghdr.html"> </head> <body> <p>Redirecting to <a href="struct.if_msghdr.html">struct.if_msghdr.html</a>...</p> <script>location.replace("struct.if_msghdr.html" + location.search + location.hash);</script> </body> </html>
{ "pile_set_name": "Github" }
<h2>mach_msg_descriptor</h2> <hr> <p> <strong>Structure</strong> - Specifies operations that must be performed on a given IPC message element. <h3>SYNOPSIS</h3> <pre> <strong>typedef struct</strong> <strong>{</strong> <strong>void*</strong> <var>pad1</var><strong>;</strong> <strong>mach_msg_size_t</strong> <var>pad2</var><strong>;</strong> <strong>unsigned int</strong> <var>pad3</var><strong> : 24;</strong> <strong>mach_msg_descriptor_type_t</strong> <var>type</var><strong> : 8;</strong> <strong>} mach_msg_type_descriptor_t;</strong> <strong>typedef struct</strong> <strong>{</strong> <strong>mach_port_t</strong> <var>name</var><strong>;</strong> <strong>mach_msg_size_t</strong> <var>pad1</var><strong>;</strong> <strong>unsigned int</strong> <var>pad2</var><strong> : 16;</strong> <strong>mach_msg_type_name_t</strong> <var>disposition</var><strong> : 8;</strong> <strong>mach_msg_descriptor_type_t</strong> <var>type</var><strong> : 8;</strong> <strong>} mach_msg_port_descriptor_t;</strong> <strong>typedef struct</strong> <strong>{</strong> <strong>void*</strong> <var>address</var><strong>;</strong> <strong>mach_msg_size_t</strong> <var>size</var><strong>;</strong> <strong>boolean_t</strong> <var>deallocate</var><strong> : 8;</strong> <strong>mach_msg_copy_options_t</strong> <var>copy</var><strong> : 8;</strong> <strong>unsigned int</strong> <var>pad1</var><strong> : 8;</strong> <strong>mach_msg_descriptor_type_t</strong> <var>type</var><strong> : 8;</strong> <strong>} mach_msg_ool_descriptor_t;</strong> <strong>typedef struct</strong> <strong>{</strong> <strong>void*</strong> <var>address</var><strong>;</strong> <strong>mach_msg_size_t</strong> <var>count</var><strong>;</strong> <strong>boolean_t</strong> <var>deallocate</var><strong> : 8;</strong> <strong>mach_msg_copy_options_t</strong> <var>copy</var><strong> : 8;</strong> <strong>mach_msg_type_name_t</strong> <var>disposition</var><strong> : 8;</strong> <strong>mach_msg_descriptor_type_t</strong> <var>type</var><strong> : 8;</strong> <strong>} mach_msg_ool_ports_descriptor_t;</strong> <strong>typedef union</strong> <strong>{</strong> <strong>mach_msg_port_descriptor_t</strong> <var>port</var><strong>;</strong> <strong>mach_msg_ool_descriptor_t</strong> <var>out_of_line</var><strong>;</strong> <strong>mach_msg_ool_ports_descriptor_t</strong> <var>ool_ports</var><strong>;</strong> <strong>mach_msg_type_descriptor_t</strong> <var>type</var><strong>;</strong> <strong>} mach_msg_descriptor_t;</strong> </pre> <h3>FIELDS</h3> <dl> <dt> <var>name</var> <dd> For single port descriptors, the name of the port whose right is being sent. <p> <dt> <var>disposition</var> <dd> For single port or out-of-line port array descriptors, the IPC processing to be done for the rights for the named ports. <p> <dt> <var>address</var> <dd> For out-of-line data or port array descriptors, the address of the out-of-line data or port (name) array. <p> <dt> <var>size</var> <dd> For out-of-line data descriptors, the size of the out-of-line region, in bytes. <p> <dt> <var>deallocate</var> <dd> For out-of-line data descriptors, true if the set of pages containing the array should be de-allocated when the message is sent. <p> <dt> <var>copy</var> <dd> For out-of-line descriptors, a description of the method by which the data should be copied. <p> <dt> <var>count</var> <dd> For out-of-line port array descriptors, the number of port names in the array. <p> <dt> <var>type</var> <dd> For any type of descriptor, the type of descriptor. <p> <dt> <var>port</var> <dd> A descriptor that describes a single port right. <p> <dt> <var>out_of_line</var> <dd> A descriptor that describes an out-of-line data array. <p> <dt> <var>ool_ports</var> <dd> A descriptor that describes an out-of-line port array. </dl> <h3>DESCRIPTION</h3> <p> A <strong>mach_msg_descriptor</strong> structure describes the processing to be performed for an element of kernel-processed data in a Mach message. <h3>RELATED INFORMATION</h3> <p> Functions: <a href="mach_msg.html"><strong>mach_msg</strong></a>. <p> Data Structures: <a href="mach_msg_header.html"><strong>mach_msg_header</strong></a>.
{ "pile_set_name": "Github" }
{{- if .Values.service.runHQ }} apiVersion: v1 kind: Service metadata: name: {{ include "informix-ibm.fullname" . }}{{ if not (hasSuffix "-hq" (include "informix-ibm.fullname" . ) ) }}-hq{{ end }} labels: {{ include "informix-ibm.labels" . | indent 4 }} spec: type: {{ .Values.service.type }} ports: - name: http-hq port: {{ .Values.service.port.hq }} targetPort: hq protocol: TCP selector: app.kubernetes.io/name: {{ include "informix-ibm.name" . }} app.kubernetes.io/instance: {{ .Release.Name }} {{- end }}
{ "pile_set_name": "Github" }
Import-Module PSWriteWord #-Force $FilePath = "$Env:USERPROFILE\Desktop\PSWriteWord-Example-Equation.docx" $WordDocument = New-WordDocument $FilePath $Title1 = Add-WordText -WordDocument $WordDocument -Text 'This is an example showing ', 'how to add ', 'Equation to Microsoft Word' ` -FontSize 10, 10, 10 ` -Color Blue, Red, Blue ` -Bold $false, $false, $true ` -Italic $true, $true -SpacingAfter 10 -Supress $false Set-WordParagraph -Paragraph $Title1 -Alignment center -Supress $True Add-WordEquation -WordDocument $WordDocument -Equation "y = mx + b" -Supress $True $Title2 = Add-WordText -WordDocument $WordDocument -Text 'This is 2nd example showing ', 'how to add ', 'Equation to Microsoft Word' ` -FontSize 10, 10, 10 ` -Color Blue, Red, Blue ` -Bold $false, $false, $true ` -Italic $true, $true -SpacingAfter 10 -Supress $false Set-WordParagraph -Paragraph $Title2 -Alignment center -Supress $True Add-WordEquation -WordDocument $WordDocument -Equation "x = ( -b (b - 4ac))/2a" -Supress $True Save-WordDocument $WordDocument -Supress $True Invoke-Item $FilePath
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>BuildMachineOSBuild</key> <string>16G29</string> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>IntelMausiEthernet</string> <key>CFBundleIdentifier</key> <string>com.insanelymac.IntelMausiEthernet</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>IntelMausiEthernet</string> <key>CFBundlePackageType</key> <string>KEXT</string> <key>CFBundleShortVersionString</key> <string>2.3.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>CFBundleVersion</key> <string>2.3.0</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string>8E3004b</string> <key>DTPlatformVersion</key> <string>GM</string> <key>DTSDKBuild</key> <string>16E185</string> <key>DTSDKName</key> <string>macosx10.12</string> <key>DTXcode</key> <string>0833</string> <key>DTXcodeBuild</key> <string>8E3004b</string> <key>IOKitPersonalities</key> <dict> <key>IntelMausi</key> <dict> <key>CFBundleIdentifier</key> <string>com.insanelymac.IntelMausiEthernet</string> <key>Driver_Version</key> <string>2.3.0</string> <key>IOClass</key> <string>IntelMausi</string> <key>IOPCIMatch</key> <string>0x10EA8086 0x10EB8086 0x10EF8086 0x10F08086 0x15028086 0x15038086 0x153A8086 0x153B8086 0x155A8086 0x15598086 0x15A08086 0x15A18086 0x15A28086 0x15A38086 0x156F8086 0x15708086 0x15B78086 0x15B88086 0x15D78086 0x15D88086 0x15E38086 0x15D68086</string> <key>IOProbeScore</key> <integer>1000</integer> <key>IOProviderClass</key> <string>IOPCIDevice</string> <key>enableCSO6</key> <true/> <key>enableTSO4</key> <false/> <key>enableTSO6</key> <false/> <key>maxIntrRate</key> <integer>7000</integer> </dict> </dict> <key>NSHumanReadableCopyright</key> <string>Copyright © 2014 Laura Müller. All rights reserved.</string> <key>OSBundleLibraries</key> <dict> <key>com.apple.iokit.IONetworkingFamily</key> <string>1.5.0</string> <key>com.apple.iokit.IOPCIFamily</key> <string>1.7</string> <key>com.apple.kpi.bsd</key> <string>8.10.0</string> <key>com.apple.kpi.iokit</key> <string>8.10.0</string> <key>com.apple.kpi.libkern</key> <string>8.10.0</string> <key>com.apple.kpi.mach</key> <string>8.10.0</string> </dict> <key>OSBundleRequired</key> <string>Network-Root</string> </dict> </plist>
{ "pile_set_name": "Github" }
import li_boost_shared_ptr import gc debug = False # simple shared_ptr usage - created in C++ class li_boost_shared_ptr_runme: def main(self): if (debug): print "Started" li_boost_shared_ptr.cvar.debug_shared = debug # Change loop count to run for a long time to monitor memory loopCount = 1 #5000 for i in range (0,loopCount): self.runtest() # Expect 1 instance - the one global variable (GlobalValue) if (li_boost_shared_ptr.Klass.getTotal_count() != 1): raise RuntimeError("Klass.total_count=%s" % li_boost_shared_ptr.Klass.getTotal_count()) wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count() if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING): # Expect 1 instance - the one global variable (GlobalSmartValue) if (wrapper_count != 1): raise RuntimeError("shared_ptr wrapper count=%s" % wrapper_count) if (debug): print "Finished" def runtest(self): # simple shared_ptr usage - created in C++ k = li_boost_shared_ptr.Klass("me oh my") val = k.getValue() self.verifyValue("me oh my", val) self.verifyCount(1, k) # simple shared_ptr usage - not created in C++ k = li_boost_shared_ptr.factorycreate() val = k.getValue() self.verifyValue("factorycreate", val) self.verifyCount(1, k) # pass by shared_ptr k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.smartpointertest(k) val = kret.getValue() self.verifyValue("me oh my smartpointertest", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by shared_ptr pointer k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.smartpointerpointertest(k) val = kret.getValue() self.verifyValue("me oh my smartpointerpointertest", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by shared_ptr reference k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.smartpointerreftest(k) val = kret.getValue() self.verifyValue("me oh my smartpointerreftest", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by shared_ptr pointer reference k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.smartpointerpointerreftest(k) val = kret.getValue() self.verifyValue("me oh my smartpointerpointerreftest", val) self.verifyCount(2, k) self.verifyCount(2, kret) # const pass by shared_ptr k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.constsmartpointertest(k) val = kret.getValue() self.verifyValue("me oh my", val) self.verifyCount(2, k) self.verifyCount(2, kret) # const pass by shared_ptr pointer k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.constsmartpointerpointertest(k) val = kret.getValue() self.verifyValue("me oh my", val) self.verifyCount(2, k) self.verifyCount(2, kret) # const pass by shared_ptr reference k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.constsmartpointerreftest(k) val = kret.getValue() self.verifyValue("me oh my", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by value k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.valuetest(k) val = kret.getValue() self.verifyValue("me oh my valuetest", val) self.verifyCount(1, k) self.verifyCount(1, kret) # pass by pointer k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.pointertest(k) val = kret.getValue() self.verifyValue("me oh my pointertest", val) self.verifyCount(1, k) self.verifyCount(1, kret) # pass by reference k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.reftest(k) val = kret.getValue() self.verifyValue("me oh my reftest", val) self.verifyCount(1, k) self.verifyCount(1, kret) # pass by pointer reference k = li_boost_shared_ptr.Klass("me oh my") kret = li_boost_shared_ptr.pointerreftest(k) val = kret.getValue() self.verifyValue("me oh my pointerreftest", val) self.verifyCount(1, k) self.verifyCount(1, kret) # null tests k = None if (li_boost_shared_ptr.smartpointertest(k) != None): raise RuntimeError("return was not null") if (li_boost_shared_ptr.smartpointerpointertest(k) != None): raise RuntimeError("return was not null") if (li_boost_shared_ptr.smartpointerreftest(k) != None): raise RuntimeError("return was not null") if (li_boost_shared_ptr.smartpointerpointerreftest(k) != None): raise RuntimeError("return was not null") if (li_boost_shared_ptr.nullsmartpointerpointertest(None) != "null pointer"): raise RuntimeError("not null smartpointer pointer") try: li_boost_shared_ptr.valuetest(k) raise RuntimeError("Failed to catch null pointer") except ValueError: pass if (li_boost_shared_ptr.pointertest(k) != None): raise RuntimeError("return was not null") try: li_boost_shared_ptr.reftest(k) raise RuntimeError("Failed to catch null pointer") except ValueError: pass # $owner k = li_boost_shared_ptr.pointerownertest() val = k.getValue() self.verifyValue("pointerownertest", val) self.verifyCount(1, k) k = li_boost_shared_ptr.smartpointerpointerownertest() val = k.getValue() self.verifyValue("smartpointerpointerownertest", val) self.verifyCount(1, k) # //////////////////////////////// Derived class //////////////////////////////////////// # derived pass by shared_ptr k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.derivedsmartptrtest(k) val = kret.getValue() self.verifyValue("me oh my derivedsmartptrtest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # derived pass by shared_ptr pointer k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.derivedsmartptrpointertest(k) val = kret.getValue() self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # derived pass by shared_ptr ref k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.derivedsmartptrreftest(k) val = kret.getValue() self.verifyValue("me oh my derivedsmartptrreftest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # derived pass by shared_ptr pointer ref k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k) val = kret.getValue() self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # derived pass by pointer k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.derivedpointertest(k) val = kret.getValue() self.verifyValue("me oh my derivedpointertest-Derived", val) self.verifyCount(1, k) self.verifyCount(1, kret) # derived pass by ref k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.derivedreftest(k) val = kret.getValue() self.verifyValue("me oh my derivedreftest-Derived", val) self.verifyCount(1, k) self.verifyCount(1, kret) # //////////////////////////////// Derived and base class mixed //////////////////////////////////////// # pass by shared_ptr (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.smartpointertest(k) val = kret.getValue() self.verifyValue("me oh my smartpointertest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by shared_ptr pointer (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.smartpointerpointertest(k) val = kret.getValue() self.verifyValue("me oh my smartpointerpointertest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by shared_ptr reference (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.smartpointerreftest(k) val = kret.getValue() self.verifyValue("me oh my smartpointerreftest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by shared_ptr pointer reference (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.smartpointerpointerreftest(k) val = kret.getValue() self.verifyValue("me oh my smartpointerpointerreftest-Derived", val) self.verifyCount(2, k) self.verifyCount(2, kret) # pass by value (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.valuetest(k) val = kret.getValue() self.verifyValue("me oh my valuetest", val) # note slicing self.verifyCount(1, k) self.verifyCount(1, kret) # pass by pointer (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.pointertest(k) val = kret.getValue() self.verifyValue("me oh my pointertest-Derived", val) self.verifyCount(1, k) self.verifyCount(1, kret) # pass by ref (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.reftest(k) val = kret.getValue() self.verifyValue("me oh my reftest-Derived", val) self.verifyCount(1, k) self.verifyCount(1, kret) # //////////////////////////////// Overloading tests //////////////////////////////////////// # Base class k = li_boost_shared_ptr.Klass("me oh my") self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval") self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref") self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr") self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref") self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval") self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref") self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr") self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref") # Derived class k = li_boost_shared_ptr.KlassDerived("me oh my") self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval") self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref") self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr") self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref") self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval") self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref") self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr") self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref") # 3rd derived class k = li_boost_shared_ptr.Klass3rdDerived("me oh my") val = k.getValue() self.verifyValue("me oh my-3rdDerived", val) self.verifyCount(1, k) val = li_boost_shared_ptr.test3rdupcast(k) self.verifyValue("me oh my-3rdDerived", val) self.verifyCount(1, k) # //////////////////////////////// Member variables //////////////////////////////////////// # smart pointer by value m = li_boost_shared_ptr.MemberVariables() k = li_boost_shared_ptr.Klass("smart member value") m.SmartMemberValue = k val = k.getValue() self.verifyValue("smart member value", val) self.verifyCount(2, k) kmember = m.SmartMemberValue val = kmember.getValue() self.verifyValue("smart member value", val) self.verifyCount(3, kmember) self.verifyCount(3, k) del m self.verifyCount(2, kmember) self.verifyCount(2, k) # smart pointer by pointer m = li_boost_shared_ptr.MemberVariables() k = li_boost_shared_ptr.Klass("smart member pointer") m.SmartMemberPointer = k val = k.getValue() self.verifyValue("smart member pointer", val) self.verifyCount(1, k) kmember = m.SmartMemberPointer val = kmember.getValue() self.verifyValue("smart member pointer", val) self.verifyCount(2, kmember) self.verifyCount(2, k) del m self.verifyCount(2, kmember) self.verifyCount(2, k) # smart pointer by reference m = li_boost_shared_ptr.MemberVariables() k = li_boost_shared_ptr.Klass("smart member reference") m.SmartMemberReference = k val = k.getValue() self.verifyValue("smart member reference", val) self.verifyCount(2, k) kmember = m.SmartMemberReference val = kmember.getValue() self.verifyValue("smart member reference", val) self.verifyCount(3, kmember) self.verifyCount(3, k) # The C++ reference refers to SmartMemberValue... kmemberVal = m.SmartMemberValue val = kmember.getValue() self.verifyValue("smart member reference", val) self.verifyCount(4, kmemberVal) self.verifyCount(4, kmember) self.verifyCount(4, k) del m self.verifyCount(3, kmemberVal) self.verifyCount(3, kmember) self.verifyCount(3, k) # plain by value m = li_boost_shared_ptr.MemberVariables() k = li_boost_shared_ptr.Klass("plain member value") m.MemberValue = k val = k.getValue() self.verifyValue("plain member value", val) self.verifyCount(1, k) kmember = m.MemberValue val = kmember.getValue() self.verifyValue("plain member value", val) self.verifyCount(1, kmember) self.verifyCount(1, k) del m self.verifyCount(1, kmember) self.verifyCount(1, k) # plain by pointer m = li_boost_shared_ptr.MemberVariables() k = li_boost_shared_ptr.Klass("plain member pointer") m.MemberPointer = k val = k.getValue() self.verifyValue("plain member pointer", val) self.verifyCount(1, k) kmember = m.MemberPointer val = kmember.getValue() self.verifyValue("plain member pointer", val) self.verifyCount(1, kmember) self.verifyCount(1, k) del m self.verifyCount(1, kmember) self.verifyCount(1, k) # plain by reference m = li_boost_shared_ptr.MemberVariables() k = li_boost_shared_ptr.Klass("plain member reference") m.MemberReference = k val = k.getValue() self.verifyValue("plain member reference", val) self.verifyCount(1, k) kmember = m.MemberReference val = kmember.getValue() self.verifyValue("plain member reference", val) self.verifyCount(1, kmember) self.verifyCount(1, k) del m self.verifyCount(1, kmember) self.verifyCount(1, k) # null member variables m = li_boost_shared_ptr.MemberVariables() # shared_ptr by value k = m.SmartMemberValue if (k != None): raise RuntimeError("expected null") m.SmartMemberValue = None k = m.SmartMemberValue if (k != None): raise RuntimeError("expected null") self.verifyCount(0, k) # plain by value try: m.MemberValue = None raise RuntimeError("Failed to catch null pointer") except ValueError: pass # ////////////////////////////////// Global variables //////////////////////////////////////// # smart pointer kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue if (kglobal != None): raise RuntimeError("expected null") k = li_boost_shared_ptr.Klass("smart global value") li_boost_shared_ptr.cvar.GlobalSmartValue = k self.verifyCount(2, k) kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue val = kglobal.getValue() self.verifyValue("smart global value", val) self.verifyCount(3, kglobal) self.verifyCount(3, k) self.verifyValue("smart global value", li_boost_shared_ptr.cvar.GlobalSmartValue.getValue()) li_boost_shared_ptr.cvar.GlobalSmartValue = None # plain value k = li_boost_shared_ptr.Klass("global value") li_boost_shared_ptr.cvar.GlobalValue = k self.verifyCount(1, k) kglobal = li_boost_shared_ptr.cvar.GlobalValue val = kglobal.getValue() self.verifyValue("global value", val) self.verifyCount(1, kglobal) self.verifyCount(1, k) self.verifyValue("global value", li_boost_shared_ptr.cvar.GlobalValue.getValue()) try: li_boost_shared_ptr.cvar.GlobalValue = None raise RuntimeError("Failed to catch null pointer") except ValueError: pass # plain pointer kglobal = li_boost_shared_ptr.cvar.GlobalPointer if (kglobal != None): raise RuntimeError("expected null") k = li_boost_shared_ptr.Klass("global pointer") li_boost_shared_ptr.cvar.GlobalPointer = k self.verifyCount(1, k) kglobal = li_boost_shared_ptr.cvar.GlobalPointer val = kglobal.getValue() self.verifyValue("global pointer", val) self.verifyCount(1, kglobal) self.verifyCount(1, k) li_boost_shared_ptr.cvar.GlobalPointer = None # plain reference kglobal k = li_boost_shared_ptr.Klass("global reference") li_boost_shared_ptr.cvar.GlobalReference = k self.verifyCount(1, k) kglobal = li_boost_shared_ptr.cvar.GlobalReference val = kglobal.getValue() self.verifyValue("global reference", val) self.verifyCount(1, kglobal) self.verifyCount(1, k) try: li_boost_shared_ptr.cvar.GlobalReference = None raise RuntimeError("Failed to catch null pointer") except ValueError: pass # ////////////////////////////////// Templates //////////////////////////////////////// pid = li_boost_shared_ptr.PairIntDouble(10, 20.2) if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4): raise RuntimeError("Base values wrong") if (pid.val1 != 10 or pid.val2 != 20.2): raise RuntimeError("Derived Values wrong") def verifyValue(self, expected, got): if (expected != got): raise RuntimeError("verify value failed. Expected: ", expected, " Got: ", got) def verifyCount(self, expected, k): got = li_boost_shared_ptr.use_count(k) if (expected != got): raise RuntimeError("verify use_count failed. Expected: ", expected, " Got: ", got) runme = li_boost_shared_ptr_runme() runme.main()
{ "pile_set_name": "Github" }
function fn(cond, a, b) { var y; if (cond) { var x = global.__abstract ? __abstract("number", "a") : a; y = x.toString(); } else { var x = global.__abstract ? __abstract("number", "b") : b; y = x.toString(); } return y; } inspect = function() { return fn(true, 1, 2); }; this.__optimize && __optimize(fn);
{ "pile_set_name": "Github" }
<list xmlns="http://schemas.sulu.io/list-builder/list"> <key>group-concat</key> <properties> <group-concat-property name="tags" glue=","> <field-name>name</field-name> <entity-name>SuluTagBundle:Tag</entity-name> <joins> <join> <entity-name>SuluTagBundle:Tag</entity-name> <field-name>%sulu.model.contact.class%.tags</field-name> </join> </joins> <filter type="test"> <params> <param name="testCollection" type="collection"> <param name="test1" value="%test-parameter%" /> <param name="test2" value="test" /> </param> </params> </filter> </group-concat-property> </properties> </list>
{ "pile_set_name": "Github" }
# Bitcoin URIs Represents a bitcoin payment URI. Bitcoin URI strings became the most popular way to share payment request, sometimes as a bitcoin link and others using a QR code. URI Examples: ```sh bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2 bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2&message=Payment&label=Satoshi&extra=other-param ``` ## URI Validation The main use that we expect you'll have for the `URI` class in bitcore is validating and parsing bitcoin URIs. A `URI` instance exposes the address as a bitcore `Address` object and the amount in Satoshis, if present. The code for validating URIs looks like this: ```javascript var uriString = 'bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2'; var valid = URI.isValid(uriString); var uri = new URI(uriString); console.log(uri.address.network, uri.amount); // 'livenet', 120000000 ``` ## URI Parameters All standard parameters can be found as members of the `URI` instance. However a bitcoin URI may contain other non-standard parameters, all those can be found under the `extra` namespace. See [the official BIP21 spec](https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki) for more information. ## Create URI Another important use case for the `URI` class is creating a bitcoin URI for sharing a payment request. That can be accomplished by using a dictionary to create an instance of URI. The code for creating an URI from an Object looks like this: ```javascript var uriString = new URI({ address: '12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu', amount : 10000, // in satoshis message: 'My payment request' }); var uriString = uri.toString(); ```
{ "pile_set_name": "Github" }
train_net: "./config/train_instanceSeg.prototxt" base_lr: 0.001 lr_policy: "step" gamma: 0.1 stepsize: 20000 display: 10 average_loss: 100 momentum: 0.9 weight_decay: 0.0005 # We disable standard caffe solver snapshotting and implement our own snapshot # function snapshot: 1000 snapshot_prefix: "./model/test_vgg16_mnc_instanceSeg" iter_size: 8
{ "pile_set_name": "Github" }