file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
transmute_int_to_float.rs
use super::TRANSMUTE_INT_TO_FLOAT; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::sugg; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; /// Checks for `transmute_int_to_float` lint. /// Returns `true` if it's triggered, otherwise returns `false`. pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, e: &'tcx Expr<'_>,
match (&from_ty.kind(), &to_ty.kind()) { (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => { span_lint_and_then( cx, TRANSMUTE_INT_TO_FLOAT, e.span, &format!("transmute from a `{}` to a `{}`", from_ty, to_ty), |diag| { let arg = sugg::Sugg::hir(cx, &args[0], ".."); let arg = if let ty::Int(int_ty) = from_ty.kind() { arg.as_ty(format!( "u{}", int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string()) )) } else { arg }; diag.span_suggestion( e.span, "consider using", format!("{}::from_bits({})", to_ty, arg.to_string()), Applicability::Unspecified, ); }, ); true }, _ => false, } }
from_ty: Ty<'tcx>, to_ty: Ty<'tcx>, args: &'tcx [Expr<'_>], const_context: bool, ) -> bool {
random_line_split
transmute_int_to_float.rs
use super::TRANSMUTE_INT_TO_FLOAT; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::sugg; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; /// Checks for `transmute_int_to_float` lint. /// Returns `true` if it's triggered, otherwise returns `false`. pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>, args: &'tcx [Expr<'_>], const_context: bool, ) -> bool
{ match (&from_ty.kind(), &to_ty.kind()) { (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => { span_lint_and_then( cx, TRANSMUTE_INT_TO_FLOAT, e.span, &format!("transmute from a `{}` to a `{}`", from_ty, to_ty), |diag| { let arg = sugg::Sugg::hir(cx, &args[0], ".."); let arg = if let ty::Int(int_ty) = from_ty.kind() { arg.as_ty(format!( "u{}", int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string()) )) } else { arg }; diag.span_suggestion( e.span, "consider using", format!("{}::from_bits({})", to_ty, arg.to_string()), Applicability::Unspecified, ); }, ); true }, _ => false, } }
identifier_body
transmute_int_to_float.rs
use super::TRANSMUTE_INT_TO_FLOAT; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::sugg; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; /// Checks for `transmute_int_to_float` lint. /// Returns `true` if it's triggered, otherwise returns `false`. pub(super) fn
<'tcx>( cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>, args: &'tcx [Expr<'_>], const_context: bool, ) -> bool { match (&from_ty.kind(), &to_ty.kind()) { (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => { span_lint_and_then( cx, TRANSMUTE_INT_TO_FLOAT, e.span, &format!("transmute from a `{}` to a `{}`", from_ty, to_ty), |diag| { let arg = sugg::Sugg::hir(cx, &args[0], ".."); let arg = if let ty::Int(int_ty) = from_ty.kind() { arg.as_ty(format!( "u{}", int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string()) )) } else { arg }; diag.span_suggestion( e.span, "consider using", format!("{}::from_bits({})", to_ty, arg.to_string()), Applicability::Unspecified, ); }, ); true }, _ => false, } }
check
identifier_name
trace_time.py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ctypes import ctypes.util import logging import os import platform import sys import time import threading GET_TICK_COUNT_LAST_NOW = 0 # If GET_TICK_COUNTER_LAST_NOW is less than the current time, the clock has # rolled over, and this needs to be accounted for. GET_TICK_COUNT_WRAPAROUNDS = 0 # The current detected platform _CLOCK = None _NOW_FUNCTION = None # Mapping of supported platforms and what is returned by sys.platform. _PLATFORMS = { 'mac': 'darwin', 'linux': 'linux', 'windows': 'win32', 'cygwin': 'cygwin', 'freebsd': 'freebsd', 'sunos': 'sunos5', 'bsd': 'bsd' } # Mapping of what to pass get_clocktime based on platform. _CLOCK_MONOTONIC = { 'linux': 1, 'freebsd': 4, 'bsd': 3, 'sunos5': 4 } _LINUX_CLOCK = 'LINUX_CLOCK_MONOTONIC' _MAC_CLOCK = 'MAC_MACH_ABSOLUTE_TIME' _WIN_HIRES = 'WIN_QPC' _WIN_LORES = 'WIN_ROLLOVER_PROTECTED_TIME_GET_TIME' def InitializeMacNowFunction(plat): """Sets a monotonic clock for the Mac platform. Args: plat: Platform that is being run on. Unused in GetMacNowFunction. Passed for consistency between initilaizers. """ del plat # Unused global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _MAC_CLOCK libc = ctypes.CDLL('/usr/lib/libc.dylib', use_errno=True) class MachTimebaseInfoData(ctypes.Structure): """System timebase info. Defined in <mach/mach_time.h>.""" _fields_ = (('numer', ctypes.c_uint32), ('denom', ctypes.c_uint32)) mach_absolute_time = libc.mach_absolute_time mach_absolute_time.restype = ctypes.c_uint64 timebase = MachTimebaseInfoData() libc.mach_timebase_info(ctypes.byref(timebase)) ticks_per_second = timebase.numer / timebase.denom * 1.0e9 def MacNowFunctionImpl(): return mach_absolute_time() / ticks_per_second _NOW_FUNCTION = MacNowFunctionImpl def GetClockGetTimeClockNumber(plat): for key in _CLOCK_MONOTONIC: if plat.startswith(key): return _CLOCK_MONOTONIC[key] raise LookupError('Platform not in clock dicitonary') def InitializeLinuxNowFunction(plat): """Sets a monotonic clock for linux platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _LINUX_CLOCK clock_monotonic = GetClockGetTimeClockNumber(plat) try: # Attempt to find clock_gettime in the C library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True).clock_gettime except AttributeError: # If not able to find int in the C library, look in rt library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('rt'), use_errno=True).clock_gettime class Timespec(ctypes.Structure): """Time specification, as described in clock_gettime(3).""" _fields_ = (('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long)) def LinuxNowFunctionImpl(): ts = Timespec() if clock_gettime(clock_monotonic, ctypes.pointer(ts)): errno = ctypes.get_errno() raise OSError(errno, os.strerror(errno)) return ts.tv_sec + ts.tv_nsec / 1.0e9 _NOW_FUNCTION = LinuxNowFunctionImpl def IsQPCUsable():
def InitializeWinNowFunction(plat): """Sets a monotonic clock for windows platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement if IsQPCUsable(): _CLOCK = _WIN_HIRES qpc_return = ctypes.c_int64() qpc_frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(qpc_frequency)) qpc_frequency = float(qpc_frequency.value) qpc = ctypes.windll.Kernel32.QueryPerformanceCounter def WinNowFunctionImpl(): qpc(ctypes.byref(qpc_return)) return qpc_return.value / qpc_frequency else: _CLOCK = _WIN_LORES kernel32 = (ctypes.cdll.kernel32 if plat.startswith(_PLATFORMS['cygwin']) else ctypes.windll.kernel32) get_tick_count_64 = getattr(kernel32, 'GetTickCount64', None) # Windows Vista or newer if get_tick_count_64: get_tick_count_64.restype = ctypes.c_ulonglong def WinNowFunctionImpl(): return get_tick_count_64() / 1000.0 else: # Pre Vista. get_tick_count = kernel32.GetTickCount get_tick_count.restype = ctypes.c_uint32 get_tick_count_lock = threading.Lock() def WinNowFunctionImpl(): global GET_TICK_COUNT_LAST_NOW # pylint: disable=global-statement global GET_TICK_COUNT_WRAPAROUNDS # pylint: disable=global-statement with get_tick_count_lock: current_sample = get_tick_count() if current_sample < GET_TICK_COUNT_LAST_NOW: GET_TICK_COUNT_WRAPAROUNDS += 1 GET_TICK_COUNT_LAST_NOW = current_sample final_ms = GET_TICK_COUNT_WRAPAROUNDS << 32 final_ms += GET_TICK_COUNT_LAST_NOW return final_ms / 1000.0 _NOW_FUNCTION = WinNowFunctionImpl def InitializeNowFunction(plat): """Sets a monotonic clock for the current platform. Args: plat: Platform that is being run on. """ if plat.startswith(_PLATFORMS['mac']): InitializeMacNowFunction(plat) elif (plat.startswith(_PLATFORMS['linux']) or plat.startswith(_PLATFORMS['freebsd']) or plat.startswith(_PLATFORMS['bsd']) or plat.startswith(_PLATFORMS['sunos'])): InitializeLinuxNowFunction(plat) elif (plat.startswith(_PLATFORMS['windows']) or plat.startswith(_PLATFORMS['cygwin'])): InitializeWinNowFunction(plat) else: raise RuntimeError('%s is not a supported platform.' % plat) global _NOW_FUNCTION global _CLOCK assert _NOW_FUNCTION, 'Now function not properly set during initialization.' assert _CLOCK, 'Clock not properly set during initialization.' def Now(): return _NOW_FUNCTION() * 1e6 # convert from seconds to microseconds def GetClock(): return _CLOCK InitializeNowFunction(sys.platform)
"""Determines if system can query the performance counter. The performance counter is a high resolution timer on windows systems. Some chipsets have unreliable performance counters, so this checks that one of those chipsets is not present. Returns: True if QPC is useable, false otherwise. """ # Sample output: 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' info = platform.processor() if 'AuthenticAMD' in info and 'Family 15' in info: return False try: # If anything goes wrong during this, assume QPC isn't available. frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(frequency)) if float(frequency.value) <= 0: return False except Exception: # pylint: disable=broad-except logging.exception('Error when determining if QPC is usable.') return False return True
identifier_body
trace_time.py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ctypes import ctypes.util import logging import os import platform import sys import time import threading GET_TICK_COUNT_LAST_NOW = 0 # If GET_TICK_COUNTER_LAST_NOW is less than the current time, the clock has # rolled over, and this needs to be accounted for. GET_TICK_COUNT_WRAPAROUNDS = 0 # The current detected platform _CLOCK = None _NOW_FUNCTION = None # Mapping of supported platforms and what is returned by sys.platform. _PLATFORMS = { 'mac': 'darwin', 'linux': 'linux', 'windows': 'win32', 'cygwin': 'cygwin', 'freebsd': 'freebsd', 'sunos': 'sunos5', 'bsd': 'bsd' } # Mapping of what to pass get_clocktime based on platform. _CLOCK_MONOTONIC = { 'linux': 1, 'freebsd': 4, 'bsd': 3, 'sunos5': 4 } _LINUX_CLOCK = 'LINUX_CLOCK_MONOTONIC' _MAC_CLOCK = 'MAC_MACH_ABSOLUTE_TIME' _WIN_HIRES = 'WIN_QPC' _WIN_LORES = 'WIN_ROLLOVER_PROTECTED_TIME_GET_TIME'
Args: plat: Platform that is being run on. Unused in GetMacNowFunction. Passed for consistency between initilaizers. """ del plat # Unused global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _MAC_CLOCK libc = ctypes.CDLL('/usr/lib/libc.dylib', use_errno=True) class MachTimebaseInfoData(ctypes.Structure): """System timebase info. Defined in <mach/mach_time.h>.""" _fields_ = (('numer', ctypes.c_uint32), ('denom', ctypes.c_uint32)) mach_absolute_time = libc.mach_absolute_time mach_absolute_time.restype = ctypes.c_uint64 timebase = MachTimebaseInfoData() libc.mach_timebase_info(ctypes.byref(timebase)) ticks_per_second = timebase.numer / timebase.denom * 1.0e9 def MacNowFunctionImpl(): return mach_absolute_time() / ticks_per_second _NOW_FUNCTION = MacNowFunctionImpl def GetClockGetTimeClockNumber(plat): for key in _CLOCK_MONOTONIC: if plat.startswith(key): return _CLOCK_MONOTONIC[key] raise LookupError('Platform not in clock dicitonary') def InitializeLinuxNowFunction(plat): """Sets a monotonic clock for linux platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _LINUX_CLOCK clock_monotonic = GetClockGetTimeClockNumber(plat) try: # Attempt to find clock_gettime in the C library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True).clock_gettime except AttributeError: # If not able to find int in the C library, look in rt library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('rt'), use_errno=True).clock_gettime class Timespec(ctypes.Structure): """Time specification, as described in clock_gettime(3).""" _fields_ = (('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long)) def LinuxNowFunctionImpl(): ts = Timespec() if clock_gettime(clock_monotonic, ctypes.pointer(ts)): errno = ctypes.get_errno() raise OSError(errno, os.strerror(errno)) return ts.tv_sec + ts.tv_nsec / 1.0e9 _NOW_FUNCTION = LinuxNowFunctionImpl def IsQPCUsable(): """Determines if system can query the performance counter. The performance counter is a high resolution timer on windows systems. Some chipsets have unreliable performance counters, so this checks that one of those chipsets is not present. Returns: True if QPC is useable, false otherwise. """ # Sample output: 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' info = platform.processor() if 'AuthenticAMD' in info and 'Family 15' in info: return False try: # If anything goes wrong during this, assume QPC isn't available. frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(frequency)) if float(frequency.value) <= 0: return False except Exception: # pylint: disable=broad-except logging.exception('Error when determining if QPC is usable.') return False return True def InitializeWinNowFunction(plat): """Sets a monotonic clock for windows platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement if IsQPCUsable(): _CLOCK = _WIN_HIRES qpc_return = ctypes.c_int64() qpc_frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(qpc_frequency)) qpc_frequency = float(qpc_frequency.value) qpc = ctypes.windll.Kernel32.QueryPerformanceCounter def WinNowFunctionImpl(): qpc(ctypes.byref(qpc_return)) return qpc_return.value / qpc_frequency else: _CLOCK = _WIN_LORES kernel32 = (ctypes.cdll.kernel32 if plat.startswith(_PLATFORMS['cygwin']) else ctypes.windll.kernel32) get_tick_count_64 = getattr(kernel32, 'GetTickCount64', None) # Windows Vista or newer if get_tick_count_64: get_tick_count_64.restype = ctypes.c_ulonglong def WinNowFunctionImpl(): return get_tick_count_64() / 1000.0 else: # Pre Vista. get_tick_count = kernel32.GetTickCount get_tick_count.restype = ctypes.c_uint32 get_tick_count_lock = threading.Lock() def WinNowFunctionImpl(): global GET_TICK_COUNT_LAST_NOW # pylint: disable=global-statement global GET_TICK_COUNT_WRAPAROUNDS # pylint: disable=global-statement with get_tick_count_lock: current_sample = get_tick_count() if current_sample < GET_TICK_COUNT_LAST_NOW: GET_TICK_COUNT_WRAPAROUNDS += 1 GET_TICK_COUNT_LAST_NOW = current_sample final_ms = GET_TICK_COUNT_WRAPAROUNDS << 32 final_ms += GET_TICK_COUNT_LAST_NOW return final_ms / 1000.0 _NOW_FUNCTION = WinNowFunctionImpl def InitializeNowFunction(plat): """Sets a monotonic clock for the current platform. Args: plat: Platform that is being run on. """ if plat.startswith(_PLATFORMS['mac']): InitializeMacNowFunction(plat) elif (plat.startswith(_PLATFORMS['linux']) or plat.startswith(_PLATFORMS['freebsd']) or plat.startswith(_PLATFORMS['bsd']) or plat.startswith(_PLATFORMS['sunos'])): InitializeLinuxNowFunction(plat) elif (plat.startswith(_PLATFORMS['windows']) or plat.startswith(_PLATFORMS['cygwin'])): InitializeWinNowFunction(plat) else: raise RuntimeError('%s is not a supported platform.' % plat) global _NOW_FUNCTION global _CLOCK assert _NOW_FUNCTION, 'Now function not properly set during initialization.' assert _CLOCK, 'Clock not properly set during initialization.' def Now(): return _NOW_FUNCTION() * 1e6 # convert from seconds to microseconds def GetClock(): return _CLOCK InitializeNowFunction(sys.platform)
def InitializeMacNowFunction(plat): """Sets a monotonic clock for the Mac platform.
random_line_split
trace_time.py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ctypes import ctypes.util import logging import os import platform import sys import time import threading GET_TICK_COUNT_LAST_NOW = 0 # If GET_TICK_COUNTER_LAST_NOW is less than the current time, the clock has # rolled over, and this needs to be accounted for. GET_TICK_COUNT_WRAPAROUNDS = 0 # The current detected platform _CLOCK = None _NOW_FUNCTION = None # Mapping of supported platforms and what is returned by sys.platform. _PLATFORMS = { 'mac': 'darwin', 'linux': 'linux', 'windows': 'win32', 'cygwin': 'cygwin', 'freebsd': 'freebsd', 'sunos': 'sunos5', 'bsd': 'bsd' } # Mapping of what to pass get_clocktime based on platform. _CLOCK_MONOTONIC = { 'linux': 1, 'freebsd': 4, 'bsd': 3, 'sunos5': 4 } _LINUX_CLOCK = 'LINUX_CLOCK_MONOTONIC' _MAC_CLOCK = 'MAC_MACH_ABSOLUTE_TIME' _WIN_HIRES = 'WIN_QPC' _WIN_LORES = 'WIN_ROLLOVER_PROTECTED_TIME_GET_TIME' def InitializeMacNowFunction(plat): """Sets a monotonic clock for the Mac platform. Args: plat: Platform that is being run on. Unused in GetMacNowFunction. Passed for consistency between initilaizers. """ del plat # Unused global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _MAC_CLOCK libc = ctypes.CDLL('/usr/lib/libc.dylib', use_errno=True) class MachTimebaseInfoData(ctypes.Structure): """System timebase info. Defined in <mach/mach_time.h>.""" _fields_ = (('numer', ctypes.c_uint32), ('denom', ctypes.c_uint32)) mach_absolute_time = libc.mach_absolute_time mach_absolute_time.restype = ctypes.c_uint64 timebase = MachTimebaseInfoData() libc.mach_timebase_info(ctypes.byref(timebase)) ticks_per_second = timebase.numer / timebase.denom * 1.0e9 def MacNowFunctionImpl(): return mach_absolute_time() / ticks_per_second _NOW_FUNCTION = MacNowFunctionImpl def GetClockGetTimeClockNumber(plat): for key in _CLOCK_MONOTONIC: if plat.startswith(key): return _CLOCK_MONOTONIC[key] raise LookupError('Platform not in clock dicitonary') def InitializeLinuxNowFunction(plat): """Sets a monotonic clock for linux platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _LINUX_CLOCK clock_monotonic = GetClockGetTimeClockNumber(plat) try: # Attempt to find clock_gettime in the C library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True).clock_gettime except AttributeError: # If not able to find int in the C library, look in rt library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('rt'), use_errno=True).clock_gettime class Timespec(ctypes.Structure): """Time specification, as described in clock_gettime(3).""" _fields_ = (('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long)) def LinuxNowFunctionImpl(): ts = Timespec() if clock_gettime(clock_monotonic, ctypes.pointer(ts)): errno = ctypes.get_errno() raise OSError(errno, os.strerror(errno)) return ts.tv_sec + ts.tv_nsec / 1.0e9 _NOW_FUNCTION = LinuxNowFunctionImpl def IsQPCUsable(): """Determines if system can query the performance counter. The performance counter is a high resolution timer on windows systems. Some chipsets have unreliable performance counters, so this checks that one of those chipsets is not present. Returns: True if QPC is useable, false otherwise. """ # Sample output: 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' info = platform.processor() if 'AuthenticAMD' in info and 'Family 15' in info: return False try: # If anything goes wrong during this, assume QPC isn't available. frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(frequency)) if float(frequency.value) <= 0: return False except Exception: # pylint: disable=broad-except logging.exception('Error when determining if QPC is usable.') return False return True def InitializeWinNowFunction(plat): """Sets a monotonic clock for windows platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement if IsQPCUsable():
else: _CLOCK = _WIN_LORES kernel32 = (ctypes.cdll.kernel32 if plat.startswith(_PLATFORMS['cygwin']) else ctypes.windll.kernel32) get_tick_count_64 = getattr(kernel32, 'GetTickCount64', None) # Windows Vista or newer if get_tick_count_64: get_tick_count_64.restype = ctypes.c_ulonglong def WinNowFunctionImpl(): return get_tick_count_64() / 1000.0 else: # Pre Vista. get_tick_count = kernel32.GetTickCount get_tick_count.restype = ctypes.c_uint32 get_tick_count_lock = threading.Lock() def WinNowFunctionImpl(): global GET_TICK_COUNT_LAST_NOW # pylint: disable=global-statement global GET_TICK_COUNT_WRAPAROUNDS # pylint: disable=global-statement with get_tick_count_lock: current_sample = get_tick_count() if current_sample < GET_TICK_COUNT_LAST_NOW: GET_TICK_COUNT_WRAPAROUNDS += 1 GET_TICK_COUNT_LAST_NOW = current_sample final_ms = GET_TICK_COUNT_WRAPAROUNDS << 32 final_ms += GET_TICK_COUNT_LAST_NOW return final_ms / 1000.0 _NOW_FUNCTION = WinNowFunctionImpl def InitializeNowFunction(plat): """Sets a monotonic clock for the current platform. Args: plat: Platform that is being run on. """ if plat.startswith(_PLATFORMS['mac']): InitializeMacNowFunction(plat) elif (plat.startswith(_PLATFORMS['linux']) or plat.startswith(_PLATFORMS['freebsd']) or plat.startswith(_PLATFORMS['bsd']) or plat.startswith(_PLATFORMS['sunos'])): InitializeLinuxNowFunction(plat) elif (plat.startswith(_PLATFORMS['windows']) or plat.startswith(_PLATFORMS['cygwin'])): InitializeWinNowFunction(plat) else: raise RuntimeError('%s is not a supported platform.' % plat) global _NOW_FUNCTION global _CLOCK assert _NOW_FUNCTION, 'Now function not properly set during initialization.' assert _CLOCK, 'Clock not properly set during initialization.' def Now(): return _NOW_FUNCTION() * 1e6 # convert from seconds to microseconds def GetClock(): return _CLOCK InitializeNowFunction(sys.platform)
_CLOCK = _WIN_HIRES qpc_return = ctypes.c_int64() qpc_frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(qpc_frequency)) qpc_frequency = float(qpc_frequency.value) qpc = ctypes.windll.Kernel32.QueryPerformanceCounter def WinNowFunctionImpl(): qpc(ctypes.byref(qpc_return)) return qpc_return.value / qpc_frequency
conditional_block
trace_time.py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ctypes import ctypes.util import logging import os import platform import sys import time import threading GET_TICK_COUNT_LAST_NOW = 0 # If GET_TICK_COUNTER_LAST_NOW is less than the current time, the clock has # rolled over, and this needs to be accounted for. GET_TICK_COUNT_WRAPAROUNDS = 0 # The current detected platform _CLOCK = None _NOW_FUNCTION = None # Mapping of supported platforms and what is returned by sys.platform. _PLATFORMS = { 'mac': 'darwin', 'linux': 'linux', 'windows': 'win32', 'cygwin': 'cygwin', 'freebsd': 'freebsd', 'sunos': 'sunos5', 'bsd': 'bsd' } # Mapping of what to pass get_clocktime based on platform. _CLOCK_MONOTONIC = { 'linux': 1, 'freebsd': 4, 'bsd': 3, 'sunos5': 4 } _LINUX_CLOCK = 'LINUX_CLOCK_MONOTONIC' _MAC_CLOCK = 'MAC_MACH_ABSOLUTE_TIME' _WIN_HIRES = 'WIN_QPC' _WIN_LORES = 'WIN_ROLLOVER_PROTECTED_TIME_GET_TIME' def InitializeMacNowFunction(plat): """Sets a monotonic clock for the Mac platform. Args: plat: Platform that is being run on. Unused in GetMacNowFunction. Passed for consistency between initilaizers. """ del plat # Unused global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _MAC_CLOCK libc = ctypes.CDLL('/usr/lib/libc.dylib', use_errno=True) class MachTimebaseInfoData(ctypes.Structure): """System timebase info. Defined in <mach/mach_time.h>.""" _fields_ = (('numer', ctypes.c_uint32), ('denom', ctypes.c_uint32)) mach_absolute_time = libc.mach_absolute_time mach_absolute_time.restype = ctypes.c_uint64 timebase = MachTimebaseInfoData() libc.mach_timebase_info(ctypes.byref(timebase)) ticks_per_second = timebase.numer / timebase.denom * 1.0e9 def MacNowFunctionImpl(): return mach_absolute_time() / ticks_per_second _NOW_FUNCTION = MacNowFunctionImpl def GetClockGetTimeClockNumber(plat): for key in _CLOCK_MONOTONIC: if plat.startswith(key): return _CLOCK_MONOTONIC[key] raise LookupError('Platform not in clock dicitonary') def InitializeLinuxNowFunction(plat): """Sets a monotonic clock for linux platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement _CLOCK = _LINUX_CLOCK clock_monotonic = GetClockGetTimeClockNumber(plat) try: # Attempt to find clock_gettime in the C library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True).clock_gettime except AttributeError: # If not able to find int in the C library, look in rt library. clock_gettime = ctypes.CDLL(ctypes.util.find_library('rt'), use_errno=True).clock_gettime class Timespec(ctypes.Structure): """Time specification, as described in clock_gettime(3).""" _fields_ = (('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long)) def LinuxNowFunctionImpl(): ts = Timespec() if clock_gettime(clock_monotonic, ctypes.pointer(ts)): errno = ctypes.get_errno() raise OSError(errno, os.strerror(errno)) return ts.tv_sec + ts.tv_nsec / 1.0e9 _NOW_FUNCTION = LinuxNowFunctionImpl def IsQPCUsable(): """Determines if system can query the performance counter. The performance counter is a high resolution timer on windows systems. Some chipsets have unreliable performance counters, so this checks that one of those chipsets is not present. Returns: True if QPC is useable, false otherwise. """ # Sample output: 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' info = platform.processor() if 'AuthenticAMD' in info and 'Family 15' in info: return False try: # If anything goes wrong during this, assume QPC isn't available. frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(frequency)) if float(frequency.value) <= 0: return False except Exception: # pylint: disable=broad-except logging.exception('Error when determining if QPC is usable.') return False return True def
(plat): """Sets a monotonic clock for windows platforms. Args: plat: Platform that is being run on. """ global _CLOCK # pylint: disable=global-statement global _NOW_FUNCTION # pylint: disable=global-statement if IsQPCUsable(): _CLOCK = _WIN_HIRES qpc_return = ctypes.c_int64() qpc_frequency = ctypes.c_int64() ctypes.windll.Kernel32.QueryPerformanceFrequency( ctypes.byref(qpc_frequency)) qpc_frequency = float(qpc_frequency.value) qpc = ctypes.windll.Kernel32.QueryPerformanceCounter def WinNowFunctionImpl(): qpc(ctypes.byref(qpc_return)) return qpc_return.value / qpc_frequency else: _CLOCK = _WIN_LORES kernel32 = (ctypes.cdll.kernel32 if plat.startswith(_PLATFORMS['cygwin']) else ctypes.windll.kernel32) get_tick_count_64 = getattr(kernel32, 'GetTickCount64', None) # Windows Vista or newer if get_tick_count_64: get_tick_count_64.restype = ctypes.c_ulonglong def WinNowFunctionImpl(): return get_tick_count_64() / 1000.0 else: # Pre Vista. get_tick_count = kernel32.GetTickCount get_tick_count.restype = ctypes.c_uint32 get_tick_count_lock = threading.Lock() def WinNowFunctionImpl(): global GET_TICK_COUNT_LAST_NOW # pylint: disable=global-statement global GET_TICK_COUNT_WRAPAROUNDS # pylint: disable=global-statement with get_tick_count_lock: current_sample = get_tick_count() if current_sample < GET_TICK_COUNT_LAST_NOW: GET_TICK_COUNT_WRAPAROUNDS += 1 GET_TICK_COUNT_LAST_NOW = current_sample final_ms = GET_TICK_COUNT_WRAPAROUNDS << 32 final_ms += GET_TICK_COUNT_LAST_NOW return final_ms / 1000.0 _NOW_FUNCTION = WinNowFunctionImpl def InitializeNowFunction(plat): """Sets a monotonic clock for the current platform. Args: plat: Platform that is being run on. """ if plat.startswith(_PLATFORMS['mac']): InitializeMacNowFunction(plat) elif (plat.startswith(_PLATFORMS['linux']) or plat.startswith(_PLATFORMS['freebsd']) or plat.startswith(_PLATFORMS['bsd']) or plat.startswith(_PLATFORMS['sunos'])): InitializeLinuxNowFunction(plat) elif (plat.startswith(_PLATFORMS['windows']) or plat.startswith(_PLATFORMS['cygwin'])): InitializeWinNowFunction(plat) else: raise RuntimeError('%s is not a supported platform.' % plat) global _NOW_FUNCTION global _CLOCK assert _NOW_FUNCTION, 'Now function not properly set during initialization.' assert _CLOCK, 'Clock not properly set during initialization.' def Now(): return _NOW_FUNCTION() * 1e6 # convert from seconds to microseconds def GetClock(): return _CLOCK InitializeNowFunction(sys.platform)
InitializeWinNowFunction
identifier_name
main.rs
extern crate ffmpeg_next as ffmpeg; extern crate pretty_env_logger; use std::env; use std::process::Command; use std::thread; use std::time; use futures::{FutureExt, StreamExt}; use http::Uri; use warp::Filter; use getopts::Options; //ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8 fn run(input_address: Uri, output_file: &str) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i",
"c:a", "aac", "-b:a", "160000", "-ac", "2", "s", "854x480", "-c:v", "libx264", "-b:v", "800000", "-hls_time", "10", "-hls_list_size", "10", "-start_number", "1", output_file, ]) .spawn() .ok() .map(|child| child.id()) } fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i", format!("{}", input_address).as_str(), "-f", "mpeg1video", "-b", "800k", "-r", "30", format!("{}", output_address).as_str(), ]) .spawn() .ok() .map(|child| child.id()) } fn run_http_server() { println!("Trying to run http server"); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async { pretty_env_logger::init(); let dispatch_websocket = |ws: warp::ws::Ws| { // And then our closure will be called when it completes... ws.on_upgrade(|websocket| { // Just echo all messages back... let (tx, rx) = websocket.split(); rx.forward(tx).map(|result| { if let Err(e) = result { eprintln!("websocket error: {:?}", e); } else { let info = result.unwrap(); println!("{:?}", info) } }) }) }; let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket); warp::serve(videos_endpoint) .run(([127, 0, 0, 1], 3030)) .await; }) } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("o", "", "set output file name", "NAME"); opts.optopt("i", "", "set input file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } if !matches.opt_str("o").is_some() || !matches.opt_str("i").is_some() { print_usage(&program, opts); return; } let input = matches.opt_str("i").expect("Expected input file"); let output = matches.opt_str("o").expect("Expected output file"); let pos_uri_input = input.parse::<Uri>(); let pos_uri_output = output.parse::<Uri>(); let uri_input = match pos_uri_input { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; let uri_output = match pos_uri_output { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; thread::spawn(move || run_http_server()); thread::sleep(time::Duration::from_secs(5)); if let Some(return_id) = run_http(uri_input, uri_output) { println!("Type of return value {}", return_id); } else { println!("Error t get id") } thread::sleep(time::Duration::from_secs(20)); }
format!("{}", input_address).as_str(), "-y",
random_line_split
main.rs
extern crate ffmpeg_next as ffmpeg; extern crate pretty_env_logger; use std::env; use std::process::Command; use std::thread; use std::time; use futures::{FutureExt, StreamExt}; use http::Uri; use warp::Filter; use getopts::Options; //ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8 fn run(input_address: Uri, output_file: &str) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i", format!("{}", input_address).as_str(), "-y", "c:a", "aac", "-b:a", "160000", "-ac", "2", "s", "854x480", "-c:v", "libx264", "-b:v", "800000", "-hls_time", "10", "-hls_list_size", "10", "-start_number", "1", output_file, ]) .spawn() .ok() .map(|child| child.id()) } fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i", format!("{}", input_address).as_str(), "-f", "mpeg1video", "-b", "800k", "-r", "30", format!("{}", output_address).as_str(), ]) .spawn() .ok() .map(|child| child.id()) } fn run_http_server() { println!("Trying to run http server"); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async { pretty_env_logger::init(); let dispatch_websocket = |ws: warp::ws::Ws| { // And then our closure will be called when it completes... ws.on_upgrade(|websocket| { // Just echo all messages back... let (tx, rx) = websocket.split(); rx.forward(tx).map(|result| { if let Err(e) = result { eprintln!("websocket error: {:?}", e); } else { let info = result.unwrap(); println!("{:?}", info) } }) }) }; let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket); warp::serve(videos_endpoint) .run(([127, 0, 0, 1], 3030)) .await; }) } fn print_usage(program: &str, opts: Options)
fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("o", "", "set output file name", "NAME"); opts.optopt("i", "", "set input file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } if !matches.opt_str("o").is_some() || !matches.opt_str("i").is_some() { print_usage(&program, opts); return; } let input = matches.opt_str("i").expect("Expected input file"); let output = matches.opt_str("o").expect("Expected output file"); let pos_uri_input = input.parse::<Uri>(); let pos_uri_output = output.parse::<Uri>(); let uri_input = match pos_uri_input { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; let uri_output = match pos_uri_output { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; thread::spawn(move || run_http_server()); thread::sleep(time::Duration::from_secs(5)); if let Some(return_id) = run_http(uri_input, uri_output) { println!("Type of return value {}", return_id); } else { println!("Error t get id") } thread::sleep(time::Duration::from_secs(20)); }
{ let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); }
identifier_body
main.rs
extern crate ffmpeg_next as ffmpeg; extern crate pretty_env_logger; use std::env; use std::process::Command; use std::thread; use std::time; use futures::{FutureExt, StreamExt}; use http::Uri; use warp::Filter; use getopts::Options; //ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8 fn run(input_address: Uri, output_file: &str) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i", format!("{}", input_address).as_str(), "-y", "c:a", "aac", "-b:a", "160000", "-ac", "2", "s", "854x480", "-c:v", "libx264", "-b:v", "800000", "-hls_time", "10", "-hls_list_size", "10", "-start_number", "1", output_file, ]) .spawn() .ok() .map(|child| child.id()) } fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i", format!("{}", input_address).as_str(), "-f", "mpeg1video", "-b", "800k", "-r", "30", format!("{}", output_address).as_str(), ]) .spawn() .ok() .map(|child| child.id()) } fn run_http_server() { println!("Trying to run http server"); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async { pretty_env_logger::init(); let dispatch_websocket = |ws: warp::ws::Ws| { // And then our closure will be called when it completes... ws.on_upgrade(|websocket| { // Just echo all messages back... let (tx, rx) = websocket.split(); rx.forward(tx).map(|result| { if let Err(e) = result { eprintln!("websocket error: {:?}", e); } else { let info = result.unwrap(); println!("{:?}", info) } }) }) }; let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket); warp::serve(videos_endpoint) .run(([127, 0, 0, 1], 3030)) .await; }) } fn
(program: &str, opts: Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("o", "", "set output file name", "NAME"); opts.optopt("i", "", "set input file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } if !matches.opt_str("o").is_some() || !matches.opt_str("i").is_some() { print_usage(&program, opts); return; } let input = matches.opt_str("i").expect("Expected input file"); let output = matches.opt_str("o").expect("Expected output file"); let pos_uri_input = input.parse::<Uri>(); let pos_uri_output = output.parse::<Uri>(); let uri_input = match pos_uri_input { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; let uri_output = match pos_uri_output { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; thread::spawn(move || run_http_server()); thread::sleep(time::Duration::from_secs(5)); if let Some(return_id) = run_http(uri_input, uri_output) { println!("Type of return value {}", return_id); } else { println!("Error t get id") } thread::sleep(time::Duration::from_secs(20)); }
print_usage
identifier_name
main.rs
extern crate ffmpeg_next as ffmpeg; extern crate pretty_env_logger; use std::env; use std::process::Command; use std::thread; use std::time; use futures::{FutureExt, StreamExt}; use http::Uri; use warp::Filter; use getopts::Options; //ffmpeg -i rtsp://192.xxx.xxx:5554 -y c:a aac -b:a 160000 -ac 2 s 854x480 -c:v libx264 -b:v 800000 -hls_time 10 -hls_list_size 10 -start_number 1 playlist.m3u8 fn run(input_address: Uri, output_file: &str) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i", format!("{}", input_address).as_str(), "-y", "c:a", "aac", "-b:a", "160000", "-ac", "2", "s", "854x480", "-c:v", "libx264", "-b:v", "800000", "-hls_time", "10", "-hls_list_size", "10", "-start_number", "1", output_file, ]) .spawn() .ok() .map(|child| child.id()) } fn run_http(input_address: Uri, output_address: Uri) -> Option<u32> { Command::new("ffmpeg") .args(&[ "-i", format!("{}", input_address).as_str(), "-f", "mpeg1video", "-b", "800k", "-r", "30", format!("{}", output_address).as_str(), ]) .spawn() .ok() .map(|child| child.id()) } fn run_http_server() { println!("Trying to run http server"); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async { pretty_env_logger::init(); let dispatch_websocket = |ws: warp::ws::Ws| { // And then our closure will be called when it completes... ws.on_upgrade(|websocket| { // Just echo all messages back... let (tx, rx) = websocket.split(); rx.forward(tx).map(|result| { if let Err(e) = result { eprintln!("websocket error: {:?}", e); } else { let info = result.unwrap(); println!("{:?}", info) } }) }) }; let videos_endpoint = warp::path("videos").and(warp::ws()).map(dispatch_websocket); warp::serve(videos_endpoint) .run(([127, 0, 0, 1], 3030)) .await; }) } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("o", "", "set output file name", "NAME"); opts.optopt("i", "", "set input file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) =>
}; if matches.opt_present("h") { print_usage(&program, opts); return; } if !matches.opt_str("o").is_some() || !matches.opt_str("i").is_some() { print_usage(&program, opts); return; } let input = matches.opt_str("i").expect("Expected input file"); let output = matches.opt_str("o").expect("Expected output file"); let pos_uri_input = input.parse::<Uri>(); let pos_uri_output = output.parse::<Uri>(); let uri_input = match pos_uri_input { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; let uri_output = match pos_uri_output { Ok(v) => v, Err(_) => { print_usage(&program, opts); return; } }; thread::spawn(move || run_http_server()); thread::sleep(time::Duration::from_secs(5)); if let Some(return_id) = run_http(uri_input, uri_output) { println!("Type of return value {}", return_id); } else { println!("Error t get id") } thread::sleep(time::Duration::from_secs(20)); }
{ panic!(f.to_string()) }
conditional_block
menuShortcuts.py
# coding=utf-8 from qtpy import QtWidgets class MenuShortcuts(QtWidgets.QWidget): """ Window displaying the application shortcuts """ def __init__(self):
QtWidgets.QWidget.__init__(self) self.setWindowTitle('Shortcuts') l = QtWidgets.QGridLayout() self.setLayout(l) lk = QtWidgets.QLabel('<b>Key</b>') ld = QtWidgets.QLabel('<b>Description</b>') l.addWidget(lk, 0, 0) l.addWidget(ld, 0, 1) line = QtWidgets.QFrame(self) line.setLineWidth(2) line.setMidLineWidth(1) line.setFrameShape(QtWidgets.QFrame.HLine) line.setFrameShadow(QtWidgets.QFrame.Raised) l.addWidget(line, 1, 0, 1, 2) self._r = 2 def addShortcut(self, key, description): lk = QtWidgets.QLabel(key) ld = QtWidgets.QLabel(description) l = self.layout() l.addWidget(lk, self._r, 0) l.addWidget(ld, self._r, 1) self._r += 1
random_line_split
menuShortcuts.py
# coding=utf-8 from qtpy import QtWidgets class MenuShortcuts(QtWidgets.QWidget): """ Window displaying the application shortcuts """ def __init__(self): QtWidgets.QWidget.__init__(self) self.setWindowTitle('Shortcuts') l = QtWidgets.QGridLayout() self.setLayout(l) lk = QtWidgets.QLabel('<b>Key</b>') ld = QtWidgets.QLabel('<b>Description</b>') l.addWidget(lk, 0, 0) l.addWidget(ld, 0, 1) line = QtWidgets.QFrame(self) line.setLineWidth(2) line.setMidLineWidth(1) line.setFrameShape(QtWidgets.QFrame.HLine) line.setFrameShadow(QtWidgets.QFrame.Raised) l.addWidget(line, 1, 0, 1, 2) self._r = 2 def addShortcut(self, key, description):
lk = QtWidgets.QLabel(key) ld = QtWidgets.QLabel(description) l = self.layout() l.addWidget(lk, self._r, 0) l.addWidget(ld, self._r, 1) self._r += 1
identifier_body
menuShortcuts.py
# coding=utf-8 from qtpy import QtWidgets class
(QtWidgets.QWidget): """ Window displaying the application shortcuts """ def __init__(self): QtWidgets.QWidget.__init__(self) self.setWindowTitle('Shortcuts') l = QtWidgets.QGridLayout() self.setLayout(l) lk = QtWidgets.QLabel('<b>Key</b>') ld = QtWidgets.QLabel('<b>Description</b>') l.addWidget(lk, 0, 0) l.addWidget(ld, 0, 1) line = QtWidgets.QFrame(self) line.setLineWidth(2) line.setMidLineWidth(1) line.setFrameShape(QtWidgets.QFrame.HLine) line.setFrameShadow(QtWidgets.QFrame.Raised) l.addWidget(line, 1, 0, 1, 2) self._r = 2 def addShortcut(self, key, description): lk = QtWidgets.QLabel(key) ld = QtWidgets.QLabel(description) l = self.layout() l.addWidget(lk, self._r, 0) l.addWidget(ld, self._r, 1) self._r += 1
MenuShortcuts
identifier_name
minicurl.py
#!/usr/bin/python import sys import urlparse import os import requests def chunkedFetchUrl(url, local_filename=None, **kwargs):
url=sys.argv[1] parsed=urlparse.urlparse(url) (h,t) = os.path.split(parsed.path) t = t or 'index.html' bits = parsed.netloc.split('.') if len(bits)==3: d=bits[1] elif len(bits)==2: d=bits[0] else: d=parsed.netloc full=os.path.join(d,h[1:]) try: os.makedirs(full) except Exception as e: print >> sys.stderr, e chunkedFetchUrl(url, local_filename=os.path.join(full, t))
"""Adapted from http://stackoverflow.com/q/16694907""" if not local_filename: local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True, **kwargs) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return local_filename
identifier_body
minicurl.py
#!/usr/bin/python import sys import urlparse import os import requests def chunkedFetchUrl(url, local_filename=None, **kwargs): """Adapted from http://stackoverflow.com/q/16694907""" if not local_filename: local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True, **kwargs) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024):
return local_filename url=sys.argv[1] parsed=urlparse.urlparse(url) (h,t) = os.path.split(parsed.path) t = t or 'index.html' bits = parsed.netloc.split('.') if len(bits)==3: d=bits[1] elif len(bits)==2: d=bits[0] else: d=parsed.netloc full=os.path.join(d,h[1:]) try: os.makedirs(full) except Exception as e: print >> sys.stderr, e chunkedFetchUrl(url, local_filename=os.path.join(full, t))
if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush()
conditional_block
minicurl.py
#!/usr/bin/python import sys import urlparse import os import requests def
(url, local_filename=None, **kwargs): """Adapted from http://stackoverflow.com/q/16694907""" if not local_filename: local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True, **kwargs) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return local_filename url=sys.argv[1] parsed=urlparse.urlparse(url) (h,t) = os.path.split(parsed.path) t = t or 'index.html' bits = parsed.netloc.split('.') if len(bits)==3: d=bits[1] elif len(bits)==2: d=bits[0] else: d=parsed.netloc full=os.path.join(d,h[1:]) try: os.makedirs(full) except Exception as e: print >> sys.stderr, e chunkedFetchUrl(url, local_filename=os.path.join(full, t))
chunkedFetchUrl
identifier_name
minicurl.py
#!/usr/bin/python import sys import urlparse import os import requests def chunkedFetchUrl(url, local_filename=None, **kwargs): """Adapted from http://stackoverflow.com/q/16694907""" if not local_filename: local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True, **kwargs) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024):
f.flush() return local_filename url=sys.argv[1] parsed=urlparse.urlparse(url) (h,t) = os.path.split(parsed.path) t = t or 'index.html' bits = parsed.netloc.split('.') if len(bits)==3: d=bits[1] elif len(bits)==2: d=bits[0] else: d=parsed.netloc full=os.path.join(d,h[1:]) try: os.makedirs(full) except Exception as e: print >> sys.stderr, e chunkedFetchUrl(url, local_filename=os.path.join(full, t))
if chunk: # filter out keep-alive new chunks f.write(chunk)
random_line_split
upload_latest.rs
use crate::{api_client::{self, Client}, common::ui::{Status, UIWriter, UI}, error::{Error, Result}, PRODUCT, VERSION}; use habitat_core::{crypto::keys::{Key, KeyCache, PublicOriginSigningKey, SecretOriginSigningKey}, origin::Origin}; use reqwest::StatusCode; pub async fn start(ui: &mut UI, bldr_url: &str, token: &str, origin: &Origin, with_secret: bool, key_cache: &KeyCache) -> Result<()>
{ let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?; ui.begin(format!("Uploading latest public origin key {}", &origin))?; // Figure out the latest public key let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?; // The path to the key in the cache let public_keyfile = key_cache.path_in_cache(&public_key); ui.status(Status::Uploading, public_keyfile.display())?; // TODO (CM): Really, we just need to pass the key itself; it's // got all the information match api_client.put_origin_key(public_key.named_revision().name(), public_key.named_revision().revision(), &public_keyfile, token, ui.progress()) .await { Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?, Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => { ui.status(Status::Using, format!("public key revision {} which already exists in the depot", public_key.named_revision()))?; } Err(err) => return Err(Error::from(err)), } ui.end(format!("Upload of public origin key {} complete.", public_key.named_revision()))?; if with_secret { // get matching secret key let secret_key: SecretOriginSigningKey = key_cache.secret_signing_key(public_key.named_revision())?; let secret_keyfile = key_cache.path_in_cache(&secret_key); ui.status(Status::Uploading, secret_keyfile.display())?; match api_client.put_origin_secret_key(secret_key.named_revision().name(), secret_key.named_revision().revision(), &secret_keyfile, token, ui.progress()) .await { Ok(()) => { ui.status(Status::Uploaded, secret_key.named_revision())?; ui.end(format!("Upload of secret origin key {} complete.", secret_key.named_revision()))?; } Err(e) => { return Err(Error::APIClient(e)); } } } Ok(()) }
identifier_body
upload_latest.rs
use crate::{api_client::{self, Client}, common::ui::{Status, UIWriter, UI}, error::{Error, Result}, PRODUCT, VERSION}; use habitat_core::{crypto::keys::{Key, KeyCache, PublicOriginSigningKey, SecretOriginSigningKey}, origin::Origin}; use reqwest::StatusCode; pub async fn
(ui: &mut UI, bldr_url: &str, token: &str, origin: &Origin, with_secret: bool, key_cache: &KeyCache) -> Result<()> { let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?; ui.begin(format!("Uploading latest public origin key {}", &origin))?; // Figure out the latest public key let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?; // The path to the key in the cache let public_keyfile = key_cache.path_in_cache(&public_key); ui.status(Status::Uploading, public_keyfile.display())?; // TODO (CM): Really, we just need to pass the key itself; it's // got all the information match api_client.put_origin_key(public_key.named_revision().name(), public_key.named_revision().revision(), &public_keyfile, token, ui.progress()) .await { Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?, Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => { ui.status(Status::Using, format!("public key revision {} which already exists in the depot", public_key.named_revision()))?; } Err(err) => return Err(Error::from(err)), } ui.end(format!("Upload of public origin key {} complete.", public_key.named_revision()))?; if with_secret { // get matching secret key let secret_key: SecretOriginSigningKey = key_cache.secret_signing_key(public_key.named_revision())?; let secret_keyfile = key_cache.path_in_cache(&secret_key); ui.status(Status::Uploading, secret_keyfile.display())?; match api_client.put_origin_secret_key(secret_key.named_revision().name(), secret_key.named_revision().revision(), &secret_keyfile, token, ui.progress()) .await { Ok(()) => { ui.status(Status::Uploaded, secret_key.named_revision())?; ui.end(format!("Upload of secret origin key {} complete.", secret_key.named_revision()))?; } Err(e) => { return Err(Error::APIClient(e)); } } } Ok(()) }
start
identifier_name
upload_latest.rs
use crate::{api_client::{self, Client}, common::ui::{Status, UIWriter, UI}, error::{Error, Result},
PRODUCT, VERSION}; use habitat_core::{crypto::keys::{Key, KeyCache, PublicOriginSigningKey, SecretOriginSigningKey}, origin::Origin}; use reqwest::StatusCode; pub async fn start(ui: &mut UI, bldr_url: &str, token: &str, origin: &Origin, with_secret: bool, key_cache: &KeyCache) -> Result<()> { let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?; ui.begin(format!("Uploading latest public origin key {}", &origin))?; // Figure out the latest public key let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?; // The path to the key in the cache let public_keyfile = key_cache.path_in_cache(&public_key); ui.status(Status::Uploading, public_keyfile.display())?; // TODO (CM): Really, we just need to pass the key itself; it's // got all the information match api_client.put_origin_key(public_key.named_revision().name(), public_key.named_revision().revision(), &public_keyfile, token, ui.progress()) .await { Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?, Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => { ui.status(Status::Using, format!("public key revision {} which already exists in the depot", public_key.named_revision()))?; } Err(err) => return Err(Error::from(err)), } ui.end(format!("Upload of public origin key {} complete.", public_key.named_revision()))?; if with_secret { // get matching secret key let secret_key: SecretOriginSigningKey = key_cache.secret_signing_key(public_key.named_revision())?; let secret_keyfile = key_cache.path_in_cache(&secret_key); ui.status(Status::Uploading, secret_keyfile.display())?; match api_client.put_origin_secret_key(secret_key.named_revision().name(), secret_key.named_revision().revision(), &secret_keyfile, token, ui.progress()) .await { Ok(()) => { ui.status(Status::Uploaded, secret_key.named_revision())?; ui.end(format!("Upload of secret origin key {} complete.", secret_key.named_revision()))?; } Err(e) => { return Err(Error::APIClient(e)); } } } Ok(()) }
random_line_split
models.py
from __future__ import absolute_import, unicode_literals from six import text_type from django.db import models from django.db.models.query import QuerySet from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailsearch import index from wagtail.wagtailsearch.backends import get_search_backend class PollQuerySet(QuerySet): def search(self, query_string, fields=None, backend='default'): """ This runs a search query on all the pages in the QuerySet """ search_backend = get_search_backend(backend) return search_backend.search(query_string, self) @python_2_unicode_compatible class Vote(models.Model): question = ParentalKey('Question', related_name='votes') ip = models.GenericIPAddressField() time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question.question class Meta: verbose_name = _('vote') verbose_name_plural = _('votes') @python_2_unicode_compatible class Question(ClusterableModel, models.Model): poll = ParentalKey('Poll', related_name='questions') question = models.CharField(max_length=128, verbose_name=_('Question')) def __str__(self): return self.question class Meta: verbose_name = _('question') verbose_name_plural = _('questions') @python_2_unicode_compatible class Poll(ClusterableModel, models.Model, index.Indexed): title = models.CharField(max_length=128, verbose_name=_('Title')) date_created = models.DateTimeField(default=timezone.now) class Meta: verbose_name = _('poll') verbose_name_plural = _('polls') panels = [ FieldPanel('title'), InlinePanel('questions', label=_('Questions'), min_num=1) ] search_fields = ( index.SearchField('title', partial_match=True, boost=5), index.SearchField('id', boost=10), ) objects = PollQuerySet.as_manager() def get_nice_url(self): return slugify(text_type(self)) def get_template(self, request): try: return self.template except AttributeError: return '{0}/{1}.html'.format(self._meta.app_label, self._meta.model_name) def form(self): # Stops circular import
def __str__(self): return self.title
from .forms import VoteForm return VoteForm(self)
identifier_body
models.py
from __future__ import absolute_import, unicode_literals from six import text_type from django.db import models from django.db.models.query import QuerySet from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailsearch import index from wagtail.wagtailsearch.backends import get_search_backend class PollQuerySet(QuerySet): def search(self, query_string, fields=None, backend='default'): """ This runs a search query on all the pages in the QuerySet """ search_backend = get_search_backend(backend) return search_backend.search(query_string, self) @python_2_unicode_compatible class Vote(models.Model): question = ParentalKey('Question', related_name='votes') ip = models.GenericIPAddressField() time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question.question class Meta: verbose_name = _('vote') verbose_name_plural = _('votes') @python_2_unicode_compatible class Question(ClusterableModel, models.Model): poll = ParentalKey('Poll', related_name='questions') question = models.CharField(max_length=128, verbose_name=_('Question')) def __str__(self): return self.question class Meta: verbose_name = _('question') verbose_name_plural = _('questions') @python_2_unicode_compatible class Poll(ClusterableModel, models.Model, index.Indexed): title = models.CharField(max_length=128, verbose_name=_('Title')) date_created = models.DateTimeField(default=timezone.now) class
: verbose_name = _('poll') verbose_name_plural = _('polls') panels = [ FieldPanel('title'), InlinePanel('questions', label=_('Questions'), min_num=1) ] search_fields = ( index.SearchField('title', partial_match=True, boost=5), index.SearchField('id', boost=10), ) objects = PollQuerySet.as_manager() def get_nice_url(self): return slugify(text_type(self)) def get_template(self, request): try: return self.template except AttributeError: return '{0}/{1}.html'.format(self._meta.app_label, self._meta.model_name) def form(self): # Stops circular import from .forms import VoteForm return VoteForm(self) def __str__(self): return self.title
Meta
identifier_name
models.py
from __future__ import absolute_import, unicode_literals from six import text_type from django.db import models from django.db.models.query import QuerySet from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailsearch import index from wagtail.wagtailsearch.backends import get_search_backend class PollQuerySet(QuerySet): def search(self, query_string, fields=None, backend='default'): """ This runs a search query on all the pages in the QuerySet """ search_backend = get_search_backend(backend) return search_backend.search(query_string, self) @python_2_unicode_compatible class Vote(models.Model): question = ParentalKey('Question', related_name='votes') ip = models.GenericIPAddressField() time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question.question class Meta: verbose_name = _('vote') verbose_name_plural = _('votes') @python_2_unicode_compatible class Question(ClusterableModel, models.Model): poll = ParentalKey('Poll', related_name='questions') question = models.CharField(max_length=128, verbose_name=_('Question')) def __str__(self): return self.question class Meta: verbose_name = _('question') verbose_name_plural = _('questions') @python_2_unicode_compatible class Poll(ClusterableModel, models.Model, index.Indexed): title = models.CharField(max_length=128, verbose_name=_('Title')) date_created = models.DateTimeField(default=timezone.now) class Meta: verbose_name = _('poll') verbose_name_plural = _('polls') panels = [ FieldPanel('title'), InlinePanel('questions', label=_('Questions'), min_num=1) ]
) objects = PollQuerySet.as_manager() def get_nice_url(self): return slugify(text_type(self)) def get_template(self, request): try: return self.template except AttributeError: return '{0}/{1}.html'.format(self._meta.app_label, self._meta.model_name) def form(self): # Stops circular import from .forms import VoteForm return VoteForm(self) def __str__(self): return self.title
search_fields = ( index.SearchField('title', partial_match=True, boost=5), index.SearchField('id', boost=10),
random_line_split
leaflet-tilelayer-cordova.js
/* * L.TileLayer.Cordova * A subclass of L.TileLayer which provides caching of tiles to a local filesystem using Cordova's File API * as well as methods for "switching" the layer between online mode (load from URLs) or offline mode (load from local stash) * Intended use is with Cordova/Phonegap applications, to cache tiles for later use. * * This plugin requires the following Cordova/Phonegap plugins: * File cordova plugins add org.apache.cordova.file * File-Transfer cordova plugins add org.apache.cordova.file-transfer * Additionally, these Cordova/Phonegap plugins are invaluable for development and debugging: * Console cordova plugins add org.apache.cordova.console * * It accepts the usual L.TileLayer options, plus the following (some are REQUIRED). * folder REQUIRED. A folder path under which tiles are stored. The name of your app may be good, e.g. "My Trail App" * name REQUIRED. A unique name for this TileLayer, for naming the tiles and then fetching them later. Keep it brief, e.g. "terrain" * debug Boolean indicating whether to display verbose debugging out to console. Defaults to false. Great for using GapDebug, logcat, Xcode console, ... * * Accepts an optional success_callback, which will be called when the time-intensive filesystem activities are complete. */ L.tileLayerCordova = function (url,options,success_callback) { return new L.TileLayer.Cordova(url,options,success_callback); } L.TileLayer.Cordova = L.TileLayer.extend({ initialize: function (url, options, success_callback) { // check required options or else choke and die options = L.extend({ folder: null, name: null, autocache: false, debug: false }, options); if (! options.folder) throw "L.TileLayer.Cordova: missing required option: folder"; if (! options.name) throw "L.TileLayer.Cordova: missing required option: name"; L.TileLayer.prototype.initialize.call(this, url, options); L.setOptions(this, options); // connect to the filesystem or else die loudly // save a handle to the filesystem, and also use it to open a directory handle to our stated folder // thus: self.fshandle and self.dirhandle // // also set the ._url for both online and offline use // we have two versions of URL which may be the _url at any given time: offline and online // online is the HTTP one we were given as the 'url' parameter here to initialize() // offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png // tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates var myself = this; myself._url_online = myself._url; // Do this early, so it's done before the time-intensive filesystem activity starts. if (! window.requestFileSystem && this.options.debug) console.log("L.TileLayer.Cordova: device does not support requestFileSystem"); if (! window.requestFileSystem) throw "L.TileLayer.Cordova: device does not support requestFileSystem"; if (myself.options.debug) console.log("Opening filesystem"); window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, function (fshandle) { if (myself.options.debug) console.log("requestFileSystem OK " + options.folder); myself.fshandle = fshandle; myself.fshandle.root.getDirectory( options.folder, { create:true, exclusive:false }, function (dirhandle) { if (myself.options.debug) console.log("getDirectory OK " + options.folder); myself.dirhandle = dirhandle; myself.dirhandle.setMetadata(null, null, { "com.apple.MobileBackup":1}); // Android's toURL() has a trailing / but iOS does not; better to have 2 than to have 0 ! myself._url_offline = dirhandle.toURL() + '/' + [ myself.options.name,'{z}','{x}','{y}' ].join('-') + '.png'; if (success_callback) success_callback(); }, function (error) { if (myself.options.debug) console.log("getDirectory failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": getDirectory failed with code " + error.code; } ); }, function (error) { if (myself.options.debug) console.log("requestFileSystem failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": requestFileSystem failed with code " + error.code; } ); // done, return ourselves because method chaining is cool return this; }, /* * Toggle between online and offline functionality
goOnline: function () { // use this layer in online mode this.setUrl( this._url_online ); }, goOffline: function () { // use this layer in online mode this.setUrl( this._url_offline ); }, /* * Returns current online/offline state. */ isOnline: function() { return (this._url == this._url_online); }, isOffline: function() { return (this._url == this._url_offline); }, /* * A set of functions to do the tile downloads, and to provide suporting calculations related thereto * In particular, a user interface for downloading tiles en masse, would call calculateXYZListFromPyramid() to egt a list of tiles, * then make decisions about whether this is a good idea (e.g. too many tiles), then call downloadXYZList() with success/error callbacks */ calculateXYZListFromPyramid: function (lat, lon, zmin, zmax) { // given a latitude and longitude, and a range of zoom levels, return the list of XYZ trios comprising that view // the caller may then call downloadXYZList() with progress and error callbacks to do that fetching var xyzlist = []; for (z=zmin; z<=zmax; z++) { var t_x = this.getX(lon, z); var t_y = this.getY(lat, z); var radius = z==zmin ? 0 : Math.pow(2 , z - zmin - 1); if (this.options.debug) console.log("Calculate pyramid: Z " + z + " : " + "Radius of " + radius ); for (var x=t_x-radius; x<=t_x+radius; x++) { for (var y=t_y-radius; y<=t_y+radius; y++) { xyzlist.push({ x:x, y:y, z:z }); } } } // done! return xyzlist; }, calculateXYZListFromBounds: function(bounds, zmin, zmax) { // Given a bounds (such as that obtained by calling MAP.getBounds()) and a range of zoom levels, returns the list of XYZ trios comprising that view. // The caller may then call downloadXYZList() with progress and error callbacks to do the fetching. var xyzlist = []; for (z = zmin; z <= zmax; z++) { // Figure out the tile for the northwest point of the bounds. t1_x = this.getX(bounds.getNorthWest().lng, z); t1_y = this.getY(bounds.getNorthWest().lat, z); // Figure out the tile for the southeast point of the bounds. t2_x = this.getX(bounds.getSouthEast().lng, z); t2_y = this.getY(bounds.getSouthEast().lat, z); // Now that we have the coordinates of the two opposing points (in the correct order!), we can iterate over the square. for (var x = t1_x; x <= t2_x; x++) { for (var y = t1_y; y <= t2_y; y++) { xyzlist.push({ x:x, y:y, z:z }); } } } return xyzlist; }, getX: function(lon, z) { return Math.floor((lon+180)/360*Math.pow(2,z)); }, getY: function(lat, z) { var y = Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z)); // issue 25: Y calculation for TMS if (this.options.tms) { y = Math.pow(2, z) - y - 1; } return y; }, getLng: function(x, z) { return (x/Math.pow(2,z)*360-180); }, getLat: function(y, z) { var n=Math.PI-2*Math.PI*y/Math.pow(2,z); return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))); }, downloadAndStoreTile: function (x,y,z,success_callback,error_callback) { var myself = this; var filename = myself.dirhandle.toURL() + '/' + [ myself.options.name, z, x, y ].join('-') + '.png'; var sourceurl = myself._url_online.replace('{z}',z).replace('{x}',x).replace('{y}',y); if (myself.options.subdomains) { var idx = Math.floor(Math.random() * myself.options.subdomains.length); var dom = myself.options.subdomains[idx]; sourceurl = sourceurl.replace('{s}',dom); } if (myself.options.debug) console.log("Download " + sourceurl + " => " + filename); var transfer = new FileTransfer(); transfer.download( sourceurl, filename, function(file) { // tile downloaded OK; set the iOS "don't back up" flag then move on file.setMetadata(null, null, { "com.apple.MobileBackup":1 }); if (success_callback) success_callback(); }, function(error) { var errmsg; switch (error.code) { case FileTransferError.FILE_NOT_FOUND_ERR: errmsg = "File not found:\n" + sourceurl; break; case FileTransferError.INVALID_URL_ERR: errmsg = "Invalid URL:\n" + sourceurl; break; case FileTransferError.CONNECTION_ERR: errmsg = "Connection error at the web server.\n"; break; } if (error_callback) error_callback(errmsg); } ); }, downloadXYZList: function (xyzlist,overwrite,progress_callback,complete_callback,error_callback) { var myself = this; function runThisOneByIndex(xyzs,index,cbprog,cbdone,cberr) { var x = xyzs[index].x; var y = xyzs[index].y; var z = xyzs[index].z; // thanks to closures this function would call downloadAndStoreTile() for this XYZ, then do the callbacks and all... // all we need to do is call it below, depending on the overwrite outcome function doneWithIt() { // the download was skipped and not an error, so call the progress callback; then either move on to the next one, or else call our success callback // if the progress callback returns false (not null, not undefiend... false) then do not proceed to the next tile; this allows cancellation from the caller code if (cbprog) { var keepgoing = cbprog(index,xyzs.length); if (keepgoing === false) { return; } } if (index+1 < xyzs.length) { runThisOneByIndex(xyzs,index+1,cbprog,cbdone,cberr); } else { if (cbdone) cbdone(); } } function yesReally() { myself.downloadAndStoreTile( x,y,z, doneWithIt, function (errmsg) { // an error in downloading, so we bail on the whole process and run the error callback if (cberr) cberr(errmsg); } ); } // trick: if 'overwrite' is true we can just go ahead and download // BUT... if overwrite is false, then test that the file doesn't exist first by failing to open it if (overwrite) { if (myself.options.debug) console.log("Tile " + z + '/' + x + '/' + y + " -- " + "Overwrite=true so proceeding."); yesReally(); } else { var filename = [ myself.options.name, z, x, y ].join('-') + '.png'; myself.dirhandle.getFile( filename, { create:false }, function () { // opened the file OK, and we didn't ask for overwrite... we're done here, same as if we had downloaded properly if (myself.options.debug) console.log(filename + " exists. Skipping."); doneWithIt(); }, function () { // failed to open file, guess we are good to download it since we don't have it if (myself.options.debug) console.log(filename + " missing. Fetching."); yesReally(); } ); } } runThisOneByIndex(xyzlist,0,progress_callback,complete_callback,error_callback); }, /* * * Other maintenance functions, e.g. count up the cache's usage, and empty the cache * */ getDiskUsage: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { // a mix of files & directories. In our case we know it's all files and all cached tiles, so just add up the filesize var files = 0; var bytes = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(files,bytes); return; } // workaround for smoeone storing multiple layers in one folder, or other files in this folder // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].file( function (fileinfo) { bytes += fileinfo.size; files++; processFileEntry(index+1); }, function () { // failed to get file info? impossible, but if it somehow happens just skip on to the next file processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: getDiskUsage: Failed to read directory"; }); }, emptyCache: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { var success = 0; var failed = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(success,failed); return; } // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].remove( function () { success++; processFileEntry(index+1); }, function () { failed++; processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: emptyCache: Failed to read directory"; }); }, getCacheContents: function(done_callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); dirReader.readEntries(function (entries) { var retval = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.isFile) { var myEntry = { name: e.name, fullPath: e.fullPath, nativeURL: e.nativeURL }; // Extract the x,y,z pieces from the filename. var parts_outer = e.name.split("."); if (parts_outer.length >= 1) { var parts = parts_outer[0].split('-'); if (parts.length >= 4) { myEntry['z'] = parts[1]; myEntry['x'] = parts[2]; myEntry['y'] = parts[3]; myEntry['lat'] = myself.getLat(myEntry.y, myEntry.z); myEntry['lng'] = myself.getLng(myEntry.x, myEntry.z); } } retval.push(myEntry); } } if (done_callback) done_callback(retval); }, function() { throw "L.TileLayer.Cordova: getCacheContents: Failed to read directory"; }); } }); // end of L.TileLayer.Cordova class
* essentially this just calls setURL() with either the ._url_online or ._url_offline, and lets L.TileLayer reload the tiles... or try, anyway */
random_line_split
leaflet-tilelayer-cordova.js
/* * L.TileLayer.Cordova * A subclass of L.TileLayer which provides caching of tiles to a local filesystem using Cordova's File API * as well as methods for "switching" the layer between online mode (load from URLs) or offline mode (load from local stash) * Intended use is with Cordova/Phonegap applications, to cache tiles for later use. * * This plugin requires the following Cordova/Phonegap plugins: * File cordova plugins add org.apache.cordova.file * File-Transfer cordova plugins add org.apache.cordova.file-transfer * Additionally, these Cordova/Phonegap plugins are invaluable for development and debugging: * Console cordova plugins add org.apache.cordova.console * * It accepts the usual L.TileLayer options, plus the following (some are REQUIRED). * folder REQUIRED. A folder path under which tiles are stored. The name of your app may be good, e.g. "My Trail App" * name REQUIRED. A unique name for this TileLayer, for naming the tiles and then fetching them later. Keep it brief, e.g. "terrain" * debug Boolean indicating whether to display verbose debugging out to console. Defaults to false. Great for using GapDebug, logcat, Xcode console, ... * * Accepts an optional success_callback, which will be called when the time-intensive filesystem activities are complete. */ L.tileLayerCordova = function (url,options,success_callback) { return new L.TileLayer.Cordova(url,options,success_callback); } L.TileLayer.Cordova = L.TileLayer.extend({ initialize: function (url, options, success_callback) { // check required options or else choke and die options = L.extend({ folder: null, name: null, autocache: false, debug: false }, options); if (! options.folder) throw "L.TileLayer.Cordova: missing required option: folder"; if (! options.name) throw "L.TileLayer.Cordova: missing required option: name"; L.TileLayer.prototype.initialize.call(this, url, options); L.setOptions(this, options); // connect to the filesystem or else die loudly // save a handle to the filesystem, and also use it to open a directory handle to our stated folder // thus: self.fshandle and self.dirhandle // // also set the ._url for both online and offline use // we have two versions of URL which may be the _url at any given time: offline and online // online is the HTTP one we were given as the 'url' parameter here to initialize() // offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png // tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates var myself = this; myself._url_online = myself._url; // Do this early, so it's done before the time-intensive filesystem activity starts. if (! window.requestFileSystem && this.options.debug) console.log("L.TileLayer.Cordova: device does not support requestFileSystem"); if (! window.requestFileSystem) throw "L.TileLayer.Cordova: device does not support requestFileSystem"; if (myself.options.debug) console.log("Opening filesystem"); window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, function (fshandle) { if (myself.options.debug) console.log("requestFileSystem OK " + options.folder); myself.fshandle = fshandle; myself.fshandle.root.getDirectory( options.folder, { create:true, exclusive:false }, function (dirhandle) { if (myself.options.debug) console.log("getDirectory OK " + options.folder); myself.dirhandle = dirhandle; myself.dirhandle.setMetadata(null, null, { "com.apple.MobileBackup":1}); // Android's toURL() has a trailing / but iOS does not; better to have 2 than to have 0 ! myself._url_offline = dirhandle.toURL() + '/' + [ myself.options.name,'{z}','{x}','{y}' ].join('-') + '.png'; if (success_callback) success_callback(); }, function (error) { if (myself.options.debug) console.log("getDirectory failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": getDirectory failed with code " + error.code; } ); }, function (error) { if (myself.options.debug) console.log("requestFileSystem failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": requestFileSystem failed with code " + error.code; } ); // done, return ourselves because method chaining is cool return this; }, /* * Toggle between online and offline functionality * essentially this just calls setURL() with either the ._url_online or ._url_offline, and lets L.TileLayer reload the tiles... or try, anyway */ goOnline: function () { // use this layer in online mode this.setUrl( this._url_online ); }, goOffline: function () { // use this layer in online mode this.setUrl( this._url_offline ); }, /* * Returns current online/offline state. */ isOnline: function() { return (this._url == this._url_online); }, isOffline: function() { return (this._url == this._url_offline); }, /* * A set of functions to do the tile downloads, and to provide suporting calculations related thereto * In particular, a user interface for downloading tiles en masse, would call calculateXYZListFromPyramid() to egt a list of tiles, * then make decisions about whether this is a good idea (e.g. too many tiles), then call downloadXYZList() with success/error callbacks */ calculateXYZListFromPyramid: function (lat, lon, zmin, zmax) { // given a latitude and longitude, and a range of zoom levels, return the list of XYZ trios comprising that view // the caller may then call downloadXYZList() with progress and error callbacks to do that fetching var xyzlist = []; for (z=zmin; z<=zmax; z++) { var t_x = this.getX(lon, z); var t_y = this.getY(lat, z); var radius = z==zmin ? 0 : Math.pow(2 , z - zmin - 1); if (this.options.debug) console.log("Calculate pyramid: Z " + z + " : " + "Radius of " + radius ); for (var x=t_x-radius; x<=t_x+radius; x++) { for (var y=t_y-radius; y<=t_y+radius; y++) { xyzlist.push({ x:x, y:y, z:z }); } } } // done! return xyzlist; }, calculateXYZListFromBounds: function(bounds, zmin, zmax) { // Given a bounds (such as that obtained by calling MAP.getBounds()) and a range of zoom levels, returns the list of XYZ trios comprising that view. // The caller may then call downloadXYZList() with progress and error callbacks to do the fetching. var xyzlist = []; for (z = zmin; z <= zmax; z++) { // Figure out the tile for the northwest point of the bounds. t1_x = this.getX(bounds.getNorthWest().lng, z); t1_y = this.getY(bounds.getNorthWest().lat, z); // Figure out the tile for the southeast point of the bounds. t2_x = this.getX(bounds.getSouthEast().lng, z); t2_y = this.getY(bounds.getSouthEast().lat, z); // Now that we have the coordinates of the two opposing points (in the correct order!), we can iterate over the square. for (var x = t1_x; x <= t2_x; x++) { for (var y = t1_y; y <= t2_y; y++) { xyzlist.push({ x:x, y:y, z:z }); } } } return xyzlist; }, getX: function(lon, z) { return Math.floor((lon+180)/360*Math.pow(2,z)); }, getY: function(lat, z) { var y = Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z)); // issue 25: Y calculation for TMS if (this.options.tms) { y = Math.pow(2, z) - y - 1; } return y; }, getLng: function(x, z) { return (x/Math.pow(2,z)*360-180); }, getLat: function(y, z) { var n=Math.PI-2*Math.PI*y/Math.pow(2,z); return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))); }, downloadAndStoreTile: function (x,y,z,success_callback,error_callback) { var myself = this; var filename = myself.dirhandle.toURL() + '/' + [ myself.options.name, z, x, y ].join('-') + '.png'; var sourceurl = myself._url_online.replace('{z}',z).replace('{x}',x).replace('{y}',y); if (myself.options.subdomains) { var idx = Math.floor(Math.random() * myself.options.subdomains.length); var dom = myself.options.subdomains[idx]; sourceurl = sourceurl.replace('{s}',dom); } if (myself.options.debug) console.log("Download " + sourceurl + " => " + filename); var transfer = new FileTransfer(); transfer.download( sourceurl, filename, function(file) { // tile downloaded OK; set the iOS "don't back up" flag then move on file.setMetadata(null, null, { "com.apple.MobileBackup":1 }); if (success_callback) success_callback(); }, function(error) { var errmsg; switch (error.code) { case FileTransferError.FILE_NOT_FOUND_ERR: errmsg = "File not found:\n" + sourceurl; break; case FileTransferError.INVALID_URL_ERR: errmsg = "Invalid URL:\n" + sourceurl; break; case FileTransferError.CONNECTION_ERR: errmsg = "Connection error at the web server.\n"; break; } if (error_callback) error_callback(errmsg); } ); }, downloadXYZList: function (xyzlist,overwrite,progress_callback,complete_callback,error_callback) { var myself = this; function runThisOneByIndex(xyzs,index,cbprog,cbdone,cberr) { var x = xyzs[index].x; var y = xyzs[index].y; var z = xyzs[index].z; // thanks to closures this function would call downloadAndStoreTile() for this XYZ, then do the callbacks and all... // all we need to do is call it below, depending on the overwrite outcome function
() { // the download was skipped and not an error, so call the progress callback; then either move on to the next one, or else call our success callback // if the progress callback returns false (not null, not undefiend... false) then do not proceed to the next tile; this allows cancellation from the caller code if (cbprog) { var keepgoing = cbprog(index,xyzs.length); if (keepgoing === false) { return; } } if (index+1 < xyzs.length) { runThisOneByIndex(xyzs,index+1,cbprog,cbdone,cberr); } else { if (cbdone) cbdone(); } } function yesReally() { myself.downloadAndStoreTile( x,y,z, doneWithIt, function (errmsg) { // an error in downloading, so we bail on the whole process and run the error callback if (cberr) cberr(errmsg); } ); } // trick: if 'overwrite' is true we can just go ahead and download // BUT... if overwrite is false, then test that the file doesn't exist first by failing to open it if (overwrite) { if (myself.options.debug) console.log("Tile " + z + '/' + x + '/' + y + " -- " + "Overwrite=true so proceeding."); yesReally(); } else { var filename = [ myself.options.name, z, x, y ].join('-') + '.png'; myself.dirhandle.getFile( filename, { create:false }, function () { // opened the file OK, and we didn't ask for overwrite... we're done here, same as if we had downloaded properly if (myself.options.debug) console.log(filename + " exists. Skipping."); doneWithIt(); }, function () { // failed to open file, guess we are good to download it since we don't have it if (myself.options.debug) console.log(filename + " missing. Fetching."); yesReally(); } ); } } runThisOneByIndex(xyzlist,0,progress_callback,complete_callback,error_callback); }, /* * * Other maintenance functions, e.g. count up the cache's usage, and empty the cache * */ getDiskUsage: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { // a mix of files & directories. In our case we know it's all files and all cached tiles, so just add up the filesize var files = 0; var bytes = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(files,bytes); return; } // workaround for smoeone storing multiple layers in one folder, or other files in this folder // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].file( function (fileinfo) { bytes += fileinfo.size; files++; processFileEntry(index+1); }, function () { // failed to get file info? impossible, but if it somehow happens just skip on to the next file processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: getDiskUsage: Failed to read directory"; }); }, emptyCache: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { var success = 0; var failed = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(success,failed); return; } // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].remove( function () { success++; processFileEntry(index+1); }, function () { failed++; processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: emptyCache: Failed to read directory"; }); }, getCacheContents: function(done_callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); dirReader.readEntries(function (entries) { var retval = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.isFile) { var myEntry = { name: e.name, fullPath: e.fullPath, nativeURL: e.nativeURL }; // Extract the x,y,z pieces from the filename. var parts_outer = e.name.split("."); if (parts_outer.length >= 1) { var parts = parts_outer[0].split('-'); if (parts.length >= 4) { myEntry['z'] = parts[1]; myEntry['x'] = parts[2]; myEntry['y'] = parts[3]; myEntry['lat'] = myself.getLat(myEntry.y, myEntry.z); myEntry['lng'] = myself.getLng(myEntry.x, myEntry.z); } } retval.push(myEntry); } } if (done_callback) done_callback(retval); }, function() { throw "L.TileLayer.Cordova: getCacheContents: Failed to read directory"; }); } }); // end of L.TileLayer.Cordova class
doneWithIt
identifier_name
leaflet-tilelayer-cordova.js
/* * L.TileLayer.Cordova * A subclass of L.TileLayer which provides caching of tiles to a local filesystem using Cordova's File API * as well as methods for "switching" the layer between online mode (load from URLs) or offline mode (load from local stash) * Intended use is with Cordova/Phonegap applications, to cache tiles for later use. * * This plugin requires the following Cordova/Phonegap plugins: * File cordova plugins add org.apache.cordova.file * File-Transfer cordova plugins add org.apache.cordova.file-transfer * Additionally, these Cordova/Phonegap plugins are invaluable for development and debugging: * Console cordova plugins add org.apache.cordova.console * * It accepts the usual L.TileLayer options, plus the following (some are REQUIRED). * folder REQUIRED. A folder path under which tiles are stored. The name of your app may be good, e.g. "My Trail App" * name REQUIRED. A unique name for this TileLayer, for naming the tiles and then fetching them later. Keep it brief, e.g. "terrain" * debug Boolean indicating whether to display verbose debugging out to console. Defaults to false. Great for using GapDebug, logcat, Xcode console, ... * * Accepts an optional success_callback, which will be called when the time-intensive filesystem activities are complete. */ L.tileLayerCordova = function (url,options,success_callback) { return new L.TileLayer.Cordova(url,options,success_callback); } L.TileLayer.Cordova = L.TileLayer.extend({ initialize: function (url, options, success_callback) { // check required options or else choke and die options = L.extend({ folder: null, name: null, autocache: false, debug: false }, options); if (! options.folder) throw "L.TileLayer.Cordova: missing required option: folder"; if (! options.name) throw "L.TileLayer.Cordova: missing required option: name"; L.TileLayer.prototype.initialize.call(this, url, options); L.setOptions(this, options); // connect to the filesystem or else die loudly // save a handle to the filesystem, and also use it to open a directory handle to our stated folder // thus: self.fshandle and self.dirhandle // // also set the ._url for both online and offline use // we have two versions of URL which may be the _url at any given time: offline and online // online is the HTTP one we were given as the 'url' parameter here to initialize() // offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png // tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates var myself = this; myself._url_online = myself._url; // Do this early, so it's done before the time-intensive filesystem activity starts. if (! window.requestFileSystem && this.options.debug) console.log("L.TileLayer.Cordova: device does not support requestFileSystem"); if (! window.requestFileSystem) throw "L.TileLayer.Cordova: device does not support requestFileSystem"; if (myself.options.debug) console.log("Opening filesystem"); window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, function (fshandle) { if (myself.options.debug) console.log("requestFileSystem OK " + options.folder); myself.fshandle = fshandle; myself.fshandle.root.getDirectory( options.folder, { create:true, exclusive:false }, function (dirhandle) { if (myself.options.debug) console.log("getDirectory OK " + options.folder); myself.dirhandle = dirhandle; myself.dirhandle.setMetadata(null, null, { "com.apple.MobileBackup":1}); // Android's toURL() has a trailing / but iOS does not; better to have 2 than to have 0 ! myself._url_offline = dirhandle.toURL() + '/' + [ myself.options.name,'{z}','{x}','{y}' ].join('-') + '.png'; if (success_callback) success_callback(); }, function (error) { if (myself.options.debug) console.log("getDirectory failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": getDirectory failed with code " + error.code; } ); }, function (error) { if (myself.options.debug) console.log("requestFileSystem failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": requestFileSystem failed with code " + error.code; } ); // done, return ourselves because method chaining is cool return this; }, /* * Toggle between online and offline functionality * essentially this just calls setURL() with either the ._url_online or ._url_offline, and lets L.TileLayer reload the tiles... or try, anyway */ goOnline: function () { // use this layer in online mode this.setUrl( this._url_online ); }, goOffline: function () { // use this layer in online mode this.setUrl( this._url_offline ); }, /* * Returns current online/offline state. */ isOnline: function() { return (this._url == this._url_online); }, isOffline: function() { return (this._url == this._url_offline); }, /* * A set of functions to do the tile downloads, and to provide suporting calculations related thereto * In particular, a user interface for downloading tiles en masse, would call calculateXYZListFromPyramid() to egt a list of tiles, * then make decisions about whether this is a good idea (e.g. too many tiles), then call downloadXYZList() with success/error callbacks */ calculateXYZListFromPyramid: function (lat, lon, zmin, zmax) { // given a latitude and longitude, and a range of zoom levels, return the list of XYZ trios comprising that view // the caller may then call downloadXYZList() with progress and error callbacks to do that fetching var xyzlist = []; for (z=zmin; z<=zmax; z++) { var t_x = this.getX(lon, z); var t_y = this.getY(lat, z); var radius = z==zmin ? 0 : Math.pow(2 , z - zmin - 1); if (this.options.debug) console.log("Calculate pyramid: Z " + z + " : " + "Radius of " + radius ); for (var x=t_x-radius; x<=t_x+radius; x++) { for (var y=t_y-radius; y<=t_y+radius; y++) { xyzlist.push({ x:x, y:y, z:z }); } } } // done! return xyzlist; }, calculateXYZListFromBounds: function(bounds, zmin, zmax) { // Given a bounds (such as that obtained by calling MAP.getBounds()) and a range of zoom levels, returns the list of XYZ trios comprising that view. // The caller may then call downloadXYZList() with progress and error callbacks to do the fetching. var xyzlist = []; for (z = zmin; z <= zmax; z++) { // Figure out the tile for the northwest point of the bounds. t1_x = this.getX(bounds.getNorthWest().lng, z); t1_y = this.getY(bounds.getNorthWest().lat, z); // Figure out the tile for the southeast point of the bounds. t2_x = this.getX(bounds.getSouthEast().lng, z); t2_y = this.getY(bounds.getSouthEast().lat, z); // Now that we have the coordinates of the two opposing points (in the correct order!), we can iterate over the square. for (var x = t1_x; x <= t2_x; x++) { for (var y = t1_y; y <= t2_y; y++) { xyzlist.push({ x:x, y:y, z:z }); } } } return xyzlist; }, getX: function(lon, z) { return Math.floor((lon+180)/360*Math.pow(2,z)); }, getY: function(lat, z) { var y = Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z)); // issue 25: Y calculation for TMS if (this.options.tms) { y = Math.pow(2, z) - y - 1; } return y; }, getLng: function(x, z) { return (x/Math.pow(2,z)*360-180); }, getLat: function(y, z) { var n=Math.PI-2*Math.PI*y/Math.pow(2,z); return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))); }, downloadAndStoreTile: function (x,y,z,success_callback,error_callback) { var myself = this; var filename = myself.dirhandle.toURL() + '/' + [ myself.options.name, z, x, y ].join('-') + '.png'; var sourceurl = myself._url_online.replace('{z}',z).replace('{x}',x).replace('{y}',y); if (myself.options.subdomains) { var idx = Math.floor(Math.random() * myself.options.subdomains.length); var dom = myself.options.subdomains[idx]; sourceurl = sourceurl.replace('{s}',dom); } if (myself.options.debug) console.log("Download " + sourceurl + " => " + filename); var transfer = new FileTransfer(); transfer.download( sourceurl, filename, function(file) { // tile downloaded OK; set the iOS "don't back up" flag then move on file.setMetadata(null, null, { "com.apple.MobileBackup":1 }); if (success_callback) success_callback(); }, function(error) { var errmsg; switch (error.code) { case FileTransferError.FILE_NOT_FOUND_ERR: errmsg = "File not found:\n" + sourceurl; break; case FileTransferError.INVALID_URL_ERR: errmsg = "Invalid URL:\n" + sourceurl; break; case FileTransferError.CONNECTION_ERR: errmsg = "Connection error at the web server.\n"; break; } if (error_callback) error_callback(errmsg); } ); }, downloadXYZList: function (xyzlist,overwrite,progress_callback,complete_callback,error_callback) { var myself = this; function runThisOneByIndex(xyzs,index,cbprog,cbdone,cberr) { var x = xyzs[index].x; var y = xyzs[index].y; var z = xyzs[index].z; // thanks to closures this function would call downloadAndStoreTile() for this XYZ, then do the callbacks and all... // all we need to do is call it below, depending on the overwrite outcome function doneWithIt()
function yesReally() { myself.downloadAndStoreTile( x,y,z, doneWithIt, function (errmsg) { // an error in downloading, so we bail on the whole process and run the error callback if (cberr) cberr(errmsg); } ); } // trick: if 'overwrite' is true we can just go ahead and download // BUT... if overwrite is false, then test that the file doesn't exist first by failing to open it if (overwrite) { if (myself.options.debug) console.log("Tile " + z + '/' + x + '/' + y + " -- " + "Overwrite=true so proceeding."); yesReally(); } else { var filename = [ myself.options.name, z, x, y ].join('-') + '.png'; myself.dirhandle.getFile( filename, { create:false }, function () { // opened the file OK, and we didn't ask for overwrite... we're done here, same as if we had downloaded properly if (myself.options.debug) console.log(filename + " exists. Skipping."); doneWithIt(); }, function () { // failed to open file, guess we are good to download it since we don't have it if (myself.options.debug) console.log(filename + " missing. Fetching."); yesReally(); } ); } } runThisOneByIndex(xyzlist,0,progress_callback,complete_callback,error_callback); }, /* * * Other maintenance functions, e.g. count up the cache's usage, and empty the cache * */ getDiskUsage: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { // a mix of files & directories. In our case we know it's all files and all cached tiles, so just add up the filesize var files = 0; var bytes = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(files,bytes); return; } // workaround for smoeone storing multiple layers in one folder, or other files in this folder // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].file( function (fileinfo) { bytes += fileinfo.size; files++; processFileEntry(index+1); }, function () { // failed to get file info? impossible, but if it somehow happens just skip on to the next file processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: getDiskUsage: Failed to read directory"; }); }, emptyCache: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { var success = 0; var failed = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(success,failed); return; } // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].remove( function () { success++; processFileEntry(index+1); }, function () { failed++; processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: emptyCache: Failed to read directory"; }); }, getCacheContents: function(done_callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); dirReader.readEntries(function (entries) { var retval = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.isFile) { var myEntry = { name: e.name, fullPath: e.fullPath, nativeURL: e.nativeURL }; // Extract the x,y,z pieces from the filename. var parts_outer = e.name.split("."); if (parts_outer.length >= 1) { var parts = parts_outer[0].split('-'); if (parts.length >= 4) { myEntry['z'] = parts[1]; myEntry['x'] = parts[2]; myEntry['y'] = parts[3]; myEntry['lat'] = myself.getLat(myEntry.y, myEntry.z); myEntry['lng'] = myself.getLng(myEntry.x, myEntry.z); } } retval.push(myEntry); } } if (done_callback) done_callback(retval); }, function() { throw "L.TileLayer.Cordova: getCacheContents: Failed to read directory"; }); } }); // end of L.TileLayer.Cordova class
{ // the download was skipped and not an error, so call the progress callback; then either move on to the next one, or else call our success callback // if the progress callback returns false (not null, not undefiend... false) then do not proceed to the next tile; this allows cancellation from the caller code if (cbprog) { var keepgoing = cbprog(index,xyzs.length); if (keepgoing === false) { return; } } if (index+1 < xyzs.length) { runThisOneByIndex(xyzs,index+1,cbprog,cbdone,cberr); } else { if (cbdone) cbdone(); } }
identifier_body
leaflet-tilelayer-cordova.js
/* * L.TileLayer.Cordova * A subclass of L.TileLayer which provides caching of tiles to a local filesystem using Cordova's File API * as well as methods for "switching" the layer between online mode (load from URLs) or offline mode (load from local stash) * Intended use is with Cordova/Phonegap applications, to cache tiles for later use. * * This plugin requires the following Cordova/Phonegap plugins: * File cordova plugins add org.apache.cordova.file * File-Transfer cordova plugins add org.apache.cordova.file-transfer * Additionally, these Cordova/Phonegap plugins are invaluable for development and debugging: * Console cordova plugins add org.apache.cordova.console * * It accepts the usual L.TileLayer options, plus the following (some are REQUIRED). * folder REQUIRED. A folder path under which tiles are stored. The name of your app may be good, e.g. "My Trail App" * name REQUIRED. A unique name for this TileLayer, for naming the tiles and then fetching them later. Keep it brief, e.g. "terrain" * debug Boolean indicating whether to display verbose debugging out to console. Defaults to false. Great for using GapDebug, logcat, Xcode console, ... * * Accepts an optional success_callback, which will be called when the time-intensive filesystem activities are complete. */ L.tileLayerCordova = function (url,options,success_callback) { return new L.TileLayer.Cordova(url,options,success_callback); } L.TileLayer.Cordova = L.TileLayer.extend({ initialize: function (url, options, success_callback) { // check required options or else choke and die options = L.extend({ folder: null, name: null, autocache: false, debug: false }, options); if (! options.folder) throw "L.TileLayer.Cordova: missing required option: folder"; if (! options.name) throw "L.TileLayer.Cordova: missing required option: name"; L.TileLayer.prototype.initialize.call(this, url, options); L.setOptions(this, options); // connect to the filesystem or else die loudly // save a handle to the filesystem, and also use it to open a directory handle to our stated folder // thus: self.fshandle and self.dirhandle // // also set the ._url for both online and offline use // we have two versions of URL which may be the _url at any given time: offline and online // online is the HTTP one we were given as the 'url' parameter here to initialize() // offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png // tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates var myself = this; myself._url_online = myself._url; // Do this early, so it's done before the time-intensive filesystem activity starts. if (! window.requestFileSystem && this.options.debug) console.log("L.TileLayer.Cordova: device does not support requestFileSystem"); if (! window.requestFileSystem) throw "L.TileLayer.Cordova: device does not support requestFileSystem"; if (myself.options.debug) console.log("Opening filesystem"); window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, function (fshandle) { if (myself.options.debug) console.log("requestFileSystem OK " + options.folder); myself.fshandle = fshandle; myself.fshandle.root.getDirectory( options.folder, { create:true, exclusive:false }, function (dirhandle) { if (myself.options.debug) console.log("getDirectory OK " + options.folder); myself.dirhandle = dirhandle; myself.dirhandle.setMetadata(null, null, { "com.apple.MobileBackup":1}); // Android's toURL() has a trailing / but iOS does not; better to have 2 than to have 0 ! myself._url_offline = dirhandle.toURL() + '/' + [ myself.options.name,'{z}','{x}','{y}' ].join('-') + '.png'; if (success_callback) success_callback(); }, function (error) { if (myself.options.debug) console.log("getDirectory failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": getDirectory failed with code " + error.code; } ); }, function (error) { if (myself.options.debug) console.log("requestFileSystem failed (code " + error.code + ")" + options.folder); throw "L.TileLayer.Cordova: " + options.name + ": requestFileSystem failed with code " + error.code; } ); // done, return ourselves because method chaining is cool return this; }, /* * Toggle between online and offline functionality * essentially this just calls setURL() with either the ._url_online or ._url_offline, and lets L.TileLayer reload the tiles... or try, anyway */ goOnline: function () { // use this layer in online mode this.setUrl( this._url_online ); }, goOffline: function () { // use this layer in online mode this.setUrl( this._url_offline ); }, /* * Returns current online/offline state. */ isOnline: function() { return (this._url == this._url_online); }, isOffline: function() { return (this._url == this._url_offline); }, /* * A set of functions to do the tile downloads, and to provide suporting calculations related thereto * In particular, a user interface for downloading tiles en masse, would call calculateXYZListFromPyramid() to egt a list of tiles, * then make decisions about whether this is a good idea (e.g. too many tiles), then call downloadXYZList() with success/error callbacks */ calculateXYZListFromPyramid: function (lat, lon, zmin, zmax) { // given a latitude and longitude, and a range of zoom levels, return the list of XYZ trios comprising that view // the caller may then call downloadXYZList() with progress and error callbacks to do that fetching var xyzlist = []; for (z=zmin; z<=zmax; z++)
// done! return xyzlist; }, calculateXYZListFromBounds: function(bounds, zmin, zmax) { // Given a bounds (such as that obtained by calling MAP.getBounds()) and a range of zoom levels, returns the list of XYZ trios comprising that view. // The caller may then call downloadXYZList() with progress and error callbacks to do the fetching. var xyzlist = []; for (z = zmin; z <= zmax; z++) { // Figure out the tile for the northwest point of the bounds. t1_x = this.getX(bounds.getNorthWest().lng, z); t1_y = this.getY(bounds.getNorthWest().lat, z); // Figure out the tile for the southeast point of the bounds. t2_x = this.getX(bounds.getSouthEast().lng, z); t2_y = this.getY(bounds.getSouthEast().lat, z); // Now that we have the coordinates of the two opposing points (in the correct order!), we can iterate over the square. for (var x = t1_x; x <= t2_x; x++) { for (var y = t1_y; y <= t2_y; y++) { xyzlist.push({ x:x, y:y, z:z }); } } } return xyzlist; }, getX: function(lon, z) { return Math.floor((lon+180)/360*Math.pow(2,z)); }, getY: function(lat, z) { var y = Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z)); // issue 25: Y calculation for TMS if (this.options.tms) { y = Math.pow(2, z) - y - 1; } return y; }, getLng: function(x, z) { return (x/Math.pow(2,z)*360-180); }, getLat: function(y, z) { var n=Math.PI-2*Math.PI*y/Math.pow(2,z); return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))); }, downloadAndStoreTile: function (x,y,z,success_callback,error_callback) { var myself = this; var filename = myself.dirhandle.toURL() + '/' + [ myself.options.name, z, x, y ].join('-') + '.png'; var sourceurl = myself._url_online.replace('{z}',z).replace('{x}',x).replace('{y}',y); if (myself.options.subdomains) { var idx = Math.floor(Math.random() * myself.options.subdomains.length); var dom = myself.options.subdomains[idx]; sourceurl = sourceurl.replace('{s}',dom); } if (myself.options.debug) console.log("Download " + sourceurl + " => " + filename); var transfer = new FileTransfer(); transfer.download( sourceurl, filename, function(file) { // tile downloaded OK; set the iOS "don't back up" flag then move on file.setMetadata(null, null, { "com.apple.MobileBackup":1 }); if (success_callback) success_callback(); }, function(error) { var errmsg; switch (error.code) { case FileTransferError.FILE_NOT_FOUND_ERR: errmsg = "File not found:\n" + sourceurl; break; case FileTransferError.INVALID_URL_ERR: errmsg = "Invalid URL:\n" + sourceurl; break; case FileTransferError.CONNECTION_ERR: errmsg = "Connection error at the web server.\n"; break; } if (error_callback) error_callback(errmsg); } ); }, downloadXYZList: function (xyzlist,overwrite,progress_callback,complete_callback,error_callback) { var myself = this; function runThisOneByIndex(xyzs,index,cbprog,cbdone,cberr) { var x = xyzs[index].x; var y = xyzs[index].y; var z = xyzs[index].z; // thanks to closures this function would call downloadAndStoreTile() for this XYZ, then do the callbacks and all... // all we need to do is call it below, depending on the overwrite outcome function doneWithIt() { // the download was skipped and not an error, so call the progress callback; then either move on to the next one, or else call our success callback // if the progress callback returns false (not null, not undefiend... false) then do not proceed to the next tile; this allows cancellation from the caller code if (cbprog) { var keepgoing = cbprog(index,xyzs.length); if (keepgoing === false) { return; } } if (index+1 < xyzs.length) { runThisOneByIndex(xyzs,index+1,cbprog,cbdone,cberr); } else { if (cbdone) cbdone(); } } function yesReally() { myself.downloadAndStoreTile( x,y,z, doneWithIt, function (errmsg) { // an error in downloading, so we bail on the whole process and run the error callback if (cberr) cberr(errmsg); } ); } // trick: if 'overwrite' is true we can just go ahead and download // BUT... if overwrite is false, then test that the file doesn't exist first by failing to open it if (overwrite) { if (myself.options.debug) console.log("Tile " + z + '/' + x + '/' + y + " -- " + "Overwrite=true so proceeding."); yesReally(); } else { var filename = [ myself.options.name, z, x, y ].join('-') + '.png'; myself.dirhandle.getFile( filename, { create:false }, function () { // opened the file OK, and we didn't ask for overwrite... we're done here, same as if we had downloaded properly if (myself.options.debug) console.log(filename + " exists. Skipping."); doneWithIt(); }, function () { // failed to open file, guess we are good to download it since we don't have it if (myself.options.debug) console.log(filename + " missing. Fetching."); yesReally(); } ); } } runThisOneByIndex(xyzlist,0,progress_callback,complete_callback,error_callback); }, /* * * Other maintenance functions, e.g. count up the cache's usage, and empty the cache * */ getDiskUsage: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { // a mix of files & directories. In our case we know it's all files and all cached tiles, so just add up the filesize var files = 0; var bytes = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(files,bytes); return; } // workaround for smoeone storing multiple layers in one folder, or other files in this folder // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].file( function (fileinfo) { bytes += fileinfo.size; files++; processFileEntry(index+1); }, function () { // failed to get file info? impossible, but if it somehow happens just skip on to the next file processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: getDiskUsage: Failed to read directory"; }); }, emptyCache: function (callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); var name_match = new RegExp('^' + myself.options.name + '-'); dirReader.readEntries(function (entries) { var success = 0; var failed = 0; function processFileEntry(index) { if (index >= entries.length) { if (callback) callback(success,failed); return; } // if this file doesn't start with our own name, it's not for this tile layer if (entries[index].isFile && name_match.exec(entries[index].name)) { entries[index].remove( function () { success++; processFileEntry(index+1); }, function () { failed++; processFileEntry(index+1); } ); } else { // skip it; next! processFileEntry(index+1); } } processFileEntry(0); }, function () { throw "L.TileLayer.Cordova: emptyCache: Failed to read directory"; }); }, getCacheContents: function(done_callback) { var myself = this; var dirReader = myself.dirhandle.createReader(); dirReader.readEntries(function (entries) { var retval = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.isFile) { var myEntry = { name: e.name, fullPath: e.fullPath, nativeURL: e.nativeURL }; // Extract the x,y,z pieces from the filename. var parts_outer = e.name.split("."); if (parts_outer.length >= 1) { var parts = parts_outer[0].split('-'); if (parts.length >= 4) { myEntry['z'] = parts[1]; myEntry['x'] = parts[2]; myEntry['y'] = parts[3]; myEntry['lat'] = myself.getLat(myEntry.y, myEntry.z); myEntry['lng'] = myself.getLng(myEntry.x, myEntry.z); } } retval.push(myEntry); } } if (done_callback) done_callback(retval); }, function() { throw "L.TileLayer.Cordova: getCacheContents: Failed to read directory"; }); } }); // end of L.TileLayer.Cordova class
{ var t_x = this.getX(lon, z); var t_y = this.getY(lat, z); var radius = z==zmin ? 0 : Math.pow(2 , z - zmin - 1); if (this.options.debug) console.log("Calculate pyramid: Z " + z + " : " + "Radius of " + radius ); for (var x=t_x-radius; x<=t_x+radius; x++) { for (var y=t_y-radius; y<=t_y+radius; y++) { xyzlist.push({ x:x, y:y, z:z }); } } }
conditional_block
Branch.js
var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) { this.gid = Math.round(Math.random() * maxSegments); this.topPoint = origin; this.radius = baseRadius; this.maxSegments = maxSegments; this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.genes.pSubBranch) : 0; this.segmentLenght = baseSegment; this.depth = depth; //current position of the branch in chain this.tree = tree; this.segments = 0; //always start in 0 //Directions are represented as a Vector3 where dirx*i+diry*j+dirz*k and //each dir is the magnitude that can go from 0 to 1 and multiplies the max segment lenght //Starting direction is UP this.direction = { x: 0, y: 1, z: 0 }; this.material = new THREE.MeshLambertMaterial({ color: Math.floor(Math.random()*16777215),//tree.genes.color, side: 2, shading: THREE.FlatShading }); }; /** * Conceptually grows and renders the branch * @param {THREE.Scene} scene The scene to which the branch belongs */ Branch.prototype.grow = function (scene) { var thisBranch = this; //calculate new direction, our drawing space is a 200x200x200 cube var newX = newPos('x'); var newY = newPos('y'); var newZ = newPos('z'); if (newY < 0 || newY > 300 ){ // newZ < -100 || newZ > 100 || // newX < -100 || newX > 100) { randomizeDir(); return true; } else { //direction is ok and branch is going to grow thisBranch.segments += 1; } var destination = new THREE.Vector3(newX, newY, newZ); var lcurve = new THREE.LineCurve3(this.topPoint, destination); var geometry = new THREE.TubeGeometry( lcurve, //path thisBranch.tree.genes.segmentLenght, //segments thisBranch.radius, //radius 8, //radiusSegments true //opened, muuuch more efficient but not so nice ); // modify next segment's radius thisBranch.radius = thisBranch.radius * thisBranch.tree.genes.radiusDimP; var tube = new THREE.Mesh(geometry, this.material); scene.add(tube); this.topPoint = destination; randomizeDir(); //Helper functions. function randomizeDir() { //we want our dir to be from -1 to thisBranch.direction.x = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.y = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.z = (thisBranch.tree.mtwister.random() * 2) - 1; } function
(dimension) { return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght); } //calculate segment lenght for new segment thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim; if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) { thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius, thisBranch.segmentLenght, this.maxSegments, this.depth); } //check if we can kill branch if (thisBranch.radius <= thisBranch.tree.genes.minRadius) { return false; //kill branch } //Kill if we have reached the max number of segments if (thisBranch.segments > thisBranch.maxSegments) { return false; } else { return true; } };
newPos
identifier_name
Branch.js
var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) { this.gid = Math.round(Math.random() * maxSegments); this.topPoint = origin; this.radius = baseRadius; this.maxSegments = maxSegments; this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.genes.pSubBranch) : 0; this.segmentLenght = baseSegment; this.depth = depth; //current position of the branch in chain this.tree = tree; this.segments = 0; //always start in 0 //Directions are represented as a Vector3 where dirx*i+diry*j+dirz*k and //each dir is the magnitude that can go from 0 to 1 and multiplies the max segment lenght //Starting direction is UP this.direction = { x: 0, y: 1, z: 0 }; this.material = new THREE.MeshLambertMaterial({ color: Math.floor(Math.random()*16777215),//tree.genes.color, side: 2, shading: THREE.FlatShading }); }; /** * Conceptually grows and renders the branch * @param {THREE.Scene} scene The scene to which the branch belongs */ Branch.prototype.grow = function (scene) { var thisBranch = this; //calculate new direction, our drawing space is a 200x200x200 cube var newX = newPos('x'); var newY = newPos('y'); var newZ = newPos('z'); if (newY < 0 || newY > 300 ){ // newZ < -100 || newZ > 100 || // newX < -100 || newX > 100) { randomizeDir(); return true; } else { //direction is ok and branch is going to grow thisBranch.segments += 1; } var destination = new THREE.Vector3(newX, newY, newZ); var lcurve = new THREE.LineCurve3(this.topPoint, destination); var geometry = new THREE.TubeGeometry( lcurve, //path thisBranch.tree.genes.segmentLenght, //segments thisBranch.radius, //radius 8, //radiusSegments true //opened, muuuch more efficient but not so nice ); // modify next segment's radius thisBranch.radius = thisBranch.radius * thisBranch.tree.genes.radiusDimP; var tube = new THREE.Mesh(geometry, this.material); scene.add(tube); this.topPoint = destination; randomizeDir(); //Helper functions. function randomizeDir() { //we want our dir to be from -1 to thisBranch.direction.x = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.y = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.z = (thisBranch.tree.mtwister.random() * 2) - 1; } function newPos(dimension) { return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght); } //calculate segment lenght for new segment thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim; if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) { thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius, thisBranch.segmentLenght, this.maxSegments, this.depth); } //check if we can kill branch if (thisBranch.radius <= thisBranch.tree.genes.minRadius) { return false; //kill branch } //Kill if we have reached the max number of segments if (thisBranch.segments > thisBranch.maxSegments) { return false; } else
};
{ return true; }
conditional_block
Branch.js
var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) { this.gid = Math.round(Math.random() * maxSegments); this.topPoint = origin; this.radius = baseRadius; this.maxSegments = maxSegments; this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.genes.pSubBranch) : 0; this.segmentLenght = baseSegment; this.depth = depth; //current position of the branch in chain this.tree = tree; this.segments = 0; //always start in 0 //Directions are represented as a Vector3 where dirx*i+diry*j+dirz*k and //each dir is the magnitude that can go from 0 to 1 and multiplies the max segment lenght //Starting direction is UP this.direction = { x: 0, y: 1, z: 0 }; this.material = new THREE.MeshLambertMaterial({ color: Math.floor(Math.random()*16777215),//tree.genes.color, side: 2, shading: THREE.FlatShading }); }; /** * Conceptually grows and renders the branch * @param {THREE.Scene} scene The scene to which the branch belongs */ Branch.prototype.grow = function (scene) { var thisBranch = this; //calculate new direction, our drawing space is a 200x200x200 cube var newX = newPos('x'); var newY = newPos('y'); var newZ = newPos('z'); if (newY < 0 || newY > 300 ){ // newZ < -100 || newZ > 100 || // newX < -100 || newX > 100) { randomizeDir(); return true; } else { //direction is ok and branch is going to grow thisBranch.segments += 1; } var destination = new THREE.Vector3(newX, newY, newZ); var lcurve = new THREE.LineCurve3(this.topPoint, destination); var geometry = new THREE.TubeGeometry( lcurve, //path thisBranch.tree.genes.segmentLenght, //segments thisBranch.radius, //radius 8, //radiusSegments true //opened, muuuch more efficient but not so nice ); // modify next segment's radius thisBranch.radius = thisBranch.radius * thisBranch.tree.genes.radiusDimP; var tube = new THREE.Mesh(geometry, this.material); scene.add(tube); this.topPoint = destination; randomizeDir(); //Helper functions. function randomizeDir() { //we want our dir to be from -1 to thisBranch.direction.x = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.y = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.z = (thisBranch.tree.mtwister.random() * 2) - 1; } function newPos(dimension)
//calculate segment lenght for new segment thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim; if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) { thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius, thisBranch.segmentLenght, this.maxSegments, this.depth); } //check if we can kill branch if (thisBranch.radius <= thisBranch.tree.genes.minRadius) { return false; //kill branch } //Kill if we have reached the max number of segments if (thisBranch.segments > thisBranch.maxSegments) { return false; } else { return true; } };
{ return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght); }
identifier_body
Branch.js
var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) { this.gid = Math.round(Math.random() * maxSegments); this.topPoint = origin; this.radius = baseRadius; this.maxSegments = maxSegments; this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.genes.pSubBranch) : 0; this.segmentLenght = baseSegment; this.depth = depth; //current position of the branch in chain this.tree = tree; this.segments = 0; //always start in 0 //Directions are represented as a Vector3 where dirx*i+diry*j+dirz*k and //each dir is the magnitude that can go from 0 to 1 and multiplies the max segment lenght //Starting direction is UP this.direction = { x: 0, y: 1, z: 0 }; this.material = new THREE.MeshLambertMaterial({ color: Math.floor(Math.random()*16777215),//tree.genes.color, side: 2, shading: THREE.FlatShading }); }; /** * Conceptually grows and renders the branch * @param {THREE.Scene} scene The scene to which the branch belongs */ Branch.prototype.grow = function (scene) { var thisBranch = this; //calculate new direction, our drawing space is a 200x200x200 cube var newX = newPos('x'); var newY = newPos('y'); var newZ = newPos('z'); if (newY < 0 || newY > 300 ){ // newZ < -100 || newZ > 100 || // newX < -100 || newX > 100) { randomizeDir(); return true; } else { //direction is ok and branch is going to grow thisBranch.segments += 1;
} var destination = new THREE.Vector3(newX, newY, newZ); var lcurve = new THREE.LineCurve3(this.topPoint, destination); var geometry = new THREE.TubeGeometry( lcurve, //path thisBranch.tree.genes.segmentLenght, //segments thisBranch.radius, //radius 8, //radiusSegments true //opened, muuuch more efficient but not so nice ); // modify next segment's radius thisBranch.radius = thisBranch.radius * thisBranch.tree.genes.radiusDimP; var tube = new THREE.Mesh(geometry, this.material); scene.add(tube); this.topPoint = destination; randomizeDir(); //Helper functions. function randomizeDir() { //we want our dir to be from -1 to thisBranch.direction.x = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.y = (thisBranch.tree.mtwister.random() * 2) - 1; thisBranch.direction.z = (thisBranch.tree.mtwister.random() * 2) - 1; } function newPos(dimension) { return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght); } //calculate segment lenght for new segment thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim; if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) { thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius, thisBranch.segmentLenght, this.maxSegments, this.depth); } //check if we can kill branch if (thisBranch.radius <= thisBranch.tree.genes.minRadius) { return false; //kill branch } //Kill if we have reached the max number of segments if (thisBranch.segments > thisBranch.maxSegments) { return false; } else { return true; } };
random_line_split
pypi_cache_server.py
''' Pypi cache server Original author: Victor-mortal ''' import os import httplib import urlparse import logging import locale import json import hashlib import webob import gevent from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey CACHE_DIR = '.cache' wsgi = wsgi_fast # comment to use pywsgi host = '0.0.0.0' port = 8080 class Proxy(object): """A WSGI based web proxy application """ def
(self, chunkSize=4096, timeout=60, dropHeaders=['transfer-encoding'], pypiHost=None, log=None): """ @param log: logger of logging library """ self.log = log if self.log is None: self.log = logging.getLogger('proxy') self.chunkSize = chunkSize self.timeout = timeout self.dropHeaders = dropHeaders self.pypiHost = pypiHost def yieldData(self, response, cache_file=None): while True: data = response.read(self.chunkSize) yield data if cache_file: cache_file.write(data) if len(data) < self.chunkSize: break if cache_file: cache_file.close() def _rewrite(self, req, start_response): path = req.path_info if req.query_string: path += '?' + req.query_string parts = urlparse.urlparse(path) headers = req.headers md = hashlib.md5() md.update(' '.join('%s:%s'%v for v in headers.iteritems())) md.update(path) cache_file = os.path.join(CACHE_DIR, md.hexdigest()) if os.path.exists(cache_file): o = json.load( open(cache_file+'.js', 'rb') ) start_response(o['response'], o['headers']) return self.yieldData( open(cache_file) ) self.log.debug('Request from %s to %s', req.remote_addr, path) url = path conn = httplib.HTTPConnection(self.pypiHost, timeout=self.timeout) #headers['X-Forwarded-For'] = req.remote_addr #headers['X-Real-IP'] = req.remote_addr try: conn.request(req.method, url, headers=headers, body=req.body) response = conn.getresponse() except Exception, e: msg = str(e) if os.name == 'nt': _, encoding = locale.getdefaultlocale() msg = msg.decode(encoding) self.log.warn('Bad gateway with reason: %s', msg, exc_info=True) start_response('502 Bad gateway', []) return ['Bad gateway'] headers = [(k, v) for (k, v) in response.getheaders()\ if k not in self.dropHeaders] start_response('%s %s' % (response.status, response.reason), headers) json.dump( {'headers': headers, 'response': '%s %s' % (response.status, response.reason)}, open(cache_file+'.js', 'wb')) return self.yieldData(response, cache_file=open(cache_file, 'wb')) def __call__(self, env, start_response): req = webob.Request(env) return self._rewrite(req, start_response) if __name__ == '__main__': if not os.path.isdir(CACHE_DIR): os.mkdir(CACHE_DIR) monkey.patch_all() handler = Proxy(pypiHost='pypi.python.org:80') wsgi.WSGIServer((host, port), handler).serve_forever() run()
__init__
identifier_name
pypi_cache_server.py
''' Pypi cache server Original author: Victor-mortal ''' import os import httplib import urlparse import logging import locale import json import hashlib import webob import gevent from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey CACHE_DIR = '.cache' wsgi = wsgi_fast # comment to use pywsgi host = '0.0.0.0' port = 8080 class Proxy(object): """A WSGI based web proxy application """ def __init__(self, chunkSize=4096, timeout=60, dropHeaders=['transfer-encoding'], pypiHost=None, log=None): """ @param log: logger of logging library """ self.log = log if self.log is None: self.log = logging.getLogger('proxy') self.chunkSize = chunkSize self.timeout = timeout self.dropHeaders = dropHeaders self.pypiHost = pypiHost def yieldData(self, response, cache_file=None): while True: data = response.read(self.chunkSize) yield data if cache_file: cache_file.write(data) if len(data) < self.chunkSize: break if cache_file: cache_file.close() def _rewrite(self, req, start_response): path = req.path_info if req.query_string: path += '?' + req.query_string parts = urlparse.urlparse(path) headers = req.headers md = hashlib.md5() md.update(' '.join('%s:%s'%v for v in headers.iteritems())) md.update(path) cache_file = os.path.join(CACHE_DIR, md.hexdigest()) if os.path.exists(cache_file):
self.log.debug('Request from %s to %s', req.remote_addr, path) url = path conn = httplib.HTTPConnection(self.pypiHost, timeout=self.timeout) #headers['X-Forwarded-For'] = req.remote_addr #headers['X-Real-IP'] = req.remote_addr try: conn.request(req.method, url, headers=headers, body=req.body) response = conn.getresponse() except Exception, e: msg = str(e) if os.name == 'nt': _, encoding = locale.getdefaultlocale() msg = msg.decode(encoding) self.log.warn('Bad gateway with reason: %s', msg, exc_info=True) start_response('502 Bad gateway', []) return ['Bad gateway'] headers = [(k, v) for (k, v) in response.getheaders()\ if k not in self.dropHeaders] start_response('%s %s' % (response.status, response.reason), headers) json.dump( {'headers': headers, 'response': '%s %s' % (response.status, response.reason)}, open(cache_file+'.js', 'wb')) return self.yieldData(response, cache_file=open(cache_file, 'wb')) def __call__(self, env, start_response): req = webob.Request(env) return self._rewrite(req, start_response) if __name__ == '__main__': if not os.path.isdir(CACHE_DIR): os.mkdir(CACHE_DIR) monkey.patch_all() handler = Proxy(pypiHost='pypi.python.org:80') wsgi.WSGIServer((host, port), handler).serve_forever() run()
o = json.load( open(cache_file+'.js', 'rb') ) start_response(o['response'], o['headers']) return self.yieldData( open(cache_file) )
conditional_block
pypi_cache_server.py
''' Pypi cache server Original author: Victor-mortal ''' import os import httplib import urlparse import logging import locale import json import hashlib import webob import gevent from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey CACHE_DIR = '.cache' wsgi = wsgi_fast # comment to use pywsgi host = '0.0.0.0' port = 8080 class Proxy(object): """A WSGI based web proxy application """ def __init__(self, chunkSize=4096, timeout=60, dropHeaders=['transfer-encoding'], pypiHost=None, log=None): """ @param log: logger of logging library """ self.log = log if self.log is None: self.log = logging.getLogger('proxy') self.chunkSize = chunkSize self.timeout = timeout self.dropHeaders = dropHeaders self.pypiHost = pypiHost def yieldData(self, response, cache_file=None): while True: data = response.read(self.chunkSize) yield data if cache_file: cache_file.write(data) if len(data) < self.chunkSize: break
def _rewrite(self, req, start_response): path = req.path_info if req.query_string: path += '?' + req.query_string parts = urlparse.urlparse(path) headers = req.headers md = hashlib.md5() md.update(' '.join('%s:%s'%v for v in headers.iteritems())) md.update(path) cache_file = os.path.join(CACHE_DIR, md.hexdigest()) if os.path.exists(cache_file): o = json.load( open(cache_file+'.js', 'rb') ) start_response(o['response'], o['headers']) return self.yieldData( open(cache_file) ) self.log.debug('Request from %s to %s', req.remote_addr, path) url = path conn = httplib.HTTPConnection(self.pypiHost, timeout=self.timeout) #headers['X-Forwarded-For'] = req.remote_addr #headers['X-Real-IP'] = req.remote_addr try: conn.request(req.method, url, headers=headers, body=req.body) response = conn.getresponse() except Exception, e: msg = str(e) if os.name == 'nt': _, encoding = locale.getdefaultlocale() msg = msg.decode(encoding) self.log.warn('Bad gateway with reason: %s', msg, exc_info=True) start_response('502 Bad gateway', []) return ['Bad gateway'] headers = [(k, v) for (k, v) in response.getheaders()\ if k not in self.dropHeaders] start_response('%s %s' % (response.status, response.reason), headers) json.dump( {'headers': headers, 'response': '%s %s' % (response.status, response.reason)}, open(cache_file+'.js', 'wb')) return self.yieldData(response, cache_file=open(cache_file, 'wb')) def __call__(self, env, start_response): req = webob.Request(env) return self._rewrite(req, start_response) if __name__ == '__main__': if not os.path.isdir(CACHE_DIR): os.mkdir(CACHE_DIR) monkey.patch_all() handler = Proxy(pypiHost='pypi.python.org:80') wsgi.WSGIServer((host, port), handler).serve_forever() run()
if cache_file: cache_file.close()
random_line_split
pypi_cache_server.py
''' Pypi cache server Original author: Victor-mortal ''' import os import httplib import urlparse import logging import locale import json import hashlib import webob import gevent from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey CACHE_DIR = '.cache' wsgi = wsgi_fast # comment to use pywsgi host = '0.0.0.0' port = 8080 class Proxy(object): """A WSGI based web proxy application """ def __init__(self, chunkSize=4096, timeout=60, dropHeaders=['transfer-encoding'], pypiHost=None, log=None): """ @param log: logger of logging library """ self.log = log if self.log is None: self.log = logging.getLogger('proxy') self.chunkSize = chunkSize self.timeout = timeout self.dropHeaders = dropHeaders self.pypiHost = pypiHost def yieldData(self, response, cache_file=None): while True: data = response.read(self.chunkSize) yield data if cache_file: cache_file.write(data) if len(data) < self.chunkSize: break if cache_file: cache_file.close() def _rewrite(self, req, start_response):
def __call__(self, env, start_response): req = webob.Request(env) return self._rewrite(req, start_response) if __name__ == '__main__': if not os.path.isdir(CACHE_DIR): os.mkdir(CACHE_DIR) monkey.patch_all() handler = Proxy(pypiHost='pypi.python.org:80') wsgi.WSGIServer((host, port), handler).serve_forever() run()
path = req.path_info if req.query_string: path += '?' + req.query_string parts = urlparse.urlparse(path) headers = req.headers md = hashlib.md5() md.update(' '.join('%s:%s'%v for v in headers.iteritems())) md.update(path) cache_file = os.path.join(CACHE_DIR, md.hexdigest()) if os.path.exists(cache_file): o = json.load( open(cache_file+'.js', 'rb') ) start_response(o['response'], o['headers']) return self.yieldData( open(cache_file) ) self.log.debug('Request from %s to %s', req.remote_addr, path) url = path conn = httplib.HTTPConnection(self.pypiHost, timeout=self.timeout) #headers['X-Forwarded-For'] = req.remote_addr #headers['X-Real-IP'] = req.remote_addr try: conn.request(req.method, url, headers=headers, body=req.body) response = conn.getresponse() except Exception, e: msg = str(e) if os.name == 'nt': _, encoding = locale.getdefaultlocale() msg = msg.decode(encoding) self.log.warn('Bad gateway with reason: %s', msg, exc_info=True) start_response('502 Bad gateway', []) return ['Bad gateway'] headers = [(k, v) for (k, v) in response.getheaders()\ if k not in self.dropHeaders] start_response('%s %s' % (response.status, response.reason), headers) json.dump( {'headers': headers, 'response': '%s %s' % (response.status, response.reason)}, open(cache_file+'.js', 'wb')) return self.yieldData(response, cache_file=open(cache_file, 'wb'))
identifier_body
IR_dec_comb.py
# -*- coding: utf-8 -*- """ Created on Tue Jul 22 07:54:05 2014 @author: charleslelosq Carnegie Institution for Science """ import sys sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/") import csv import numpy as np import scipy import matplotlib import matplotlib.gridspec as gridspec from pylab import * from StringIO import StringIO from scipy import interpolate # to fit spectra we use the lmfit software of Matt Newville, CARS, university of Chicago, available on the web from lmfit import minimize, Minimizer, Parameters, Parameter, report_fit, fit_report from spectratools import * #Charles' libraries and functions from Tkinter import * import tkMessageBox from tkFileDialog import askopenfilename #### We define a set of functions that will be used for fitting data #### unfortunatly, as we use lmfit (which is convenient because it can fix or release #### easily the parameters) we are not able to use arrays for parameters... #### so it is a little bit long to write all the things, but in a way quite robust also... #### gaussian and pseudovoigt functions are available in spectratools #### if you need a voigt, fix the gaussian-to-lorentzian ratio to 1 in the parameter definition before #### doing the data fit def residual(pars, x, data=None, eps=None): # unpack parameters: # extract .value attribute for each parameter
##### CORE OF THE CALCULATION BELOW #### CALLING THE DATA NAMES tkMessageBox.showinfo( "Open file", "Please open the list of spectra") Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file with open(filename) as inputfile: results = list(csv.reader(inputfile)) # we read the data list #### LOOP FOR BEING ABLE TO TREAT MULTIPLE DATA #### WARNING: OUTPUT ARE AUTOMATICALLY GENERATED IN A DIRECTORY CALLED "DECONV" #### (see end) THAT SHOULD BE PRESENT !!!!!!!!!! for lg in range(len(results)): name = str(results[lg]).strip('[]') name = name[1:-1] # to remove unwanted "" sample = np.genfromtxt(name) # get the sample to deconvolute # we set here the lower and higher bonds for the interest region lb = 4700 ### MAY NEED TO AJUST THAT hb = 6000 interestspectra = sample[np.where((sample[:,0] > lb)&(sample[:,0] < hb))] ese0 = interestspectra[:,2]/abs(interestspectra[:,1]) #take ese as a percentage, we assume that the treatment was made correctly for error determination... if not, please put sigma = None interestspectra[:,1] = interestspectra[:,1]/np.amax(interestspectra[:,1])*100 # normalise spectra to maximum, easier to handle after sigma = abs(ese0*interestspectra[:,1]) #calculate good ese #sigma = None # you can activate that if you are not sure about the errors xfit = interestspectra[:,0] # region to be fitted data = interestspectra[:,1] # region to be fitted params = Parameters() ####################### FOR MELT: ####################### COMMENT IF NOT WANTED # (Name, Value, Vary, Min, Max, Expr) params.add_many(('a1', 1, True, 0, None, None), ('f1', 5200, True, 750, None, None), ('l1', 1, True, 0, None, None), ('a2', 1, True, 0, None, None), ('f2', 5400, True, None, None, None), ('l2', 1, True, None, None, None)) result = minimize(residual_melt, params, args=(xfit, data)) # fit data with leastsq model from scipy model = fit_report(params) # the report yout, peak1,peak2,= residual_melt(params,xfit) # the different peaks #### We just calculate the different areas up to 4700 cmm-1 and those of the gaussians # Select interest areas for calculating the areas of OH and H2Omol peaks intarea45 = sample[np.where((sample[:,0]> 4100) & (sample[:,0]<4700))] area4500 = np.trapz(intarea45[:,1],intarea45[:,0]) esearea4500 = 1/sqrt(area4500) # We assume that RELATIVE errors on areas are globally equal to 1/sqrt(Area) # now for the gaussians # unpack parameters: # extract .value attribute for each parameter a1 = pars['a1'].value a2 = pars['a2'].value l1 = pars['l1'].value l2 = pars['l2'].value AireG1 = gaussianarea(a1,l1) AireG2 = gaussianarea(a2,l2) ##### WE DO A NICE FIGURE THAT CAN BE IMPROVED FOR PUBLICATION fig = figure() plot(sample[:,0],sample[:,1],'k-') plot(xfit,yout,'r-') plot(xfit,peak1,'b-') plot(xfit,peak2,'b-') xlim(lb,hb) ylim(0,np.max(sample[:,1])) xlabel("Wavenumber, cm$^{-1}$", fontsize = 18, fontweight = "bold") ylabel("Absorption, a. u.", fontsize = 18, fontweight = "bold") text(4000,np.max(intarea45[:,1])+0.03*np.max(intarea45[:,1]),('Area OH: \n'+'%.1f' % area4500),color='b',fontsize = 16) text(4650,a1 + 0.05*a1,('Area pic 1$: \n'+ '%.1f' % AireG1),color='b',fontsize = 16) text(5000,a2 + 0.05*a2,('OH/H$_2$O$_{mol}$: \n'+'%.3f' % ratioOH_H2O+'\n+/-'+'%.3f' % eseratioOH_H2O),color='r',fontsize = 16) ##### output of data, fitted peaks, parameters, and the figure in pdf ##### all goes into the ./deconv/ folder name.rfind('/') nameout = name[name.rfind('/')+1::] namesample = nameout[0:nameout.find('.')] pathint = str('/deconv/') # the output folder ext1 = '_ydec.txt' ext2 = '_params.txt' ext3 = '.pdf' pathout1 = pathbeg+pathint+namesample+ext1 pathout2 = pathbeg+pathint+namesample+ext2 pathout3 = pathbeg+pathint+namesample+ext3 matout = np.vstack((xfit,data,yout,peak1,peak2)) matout = np.transpose(matout) np.savetxt(pathout1,matout) # saving the arrays of spectra fd = os.open( pathout2, os.O_RDWR|os.O_CREAT ) # Open a file and create it if it do not exist fo = os.fdopen(fd, "w+") # Now get a file object for the above file. fo.write(model) # write the parameters in it fo.close() savefig(pathout3) # save the figure
a1 = pars['a1'].value a2 = pars['a2'].value f1 = pars['f1'].value f2 = pars['f2'].value l1 = pars['l1'].value l2 = pars['l2'].value # Gaussian model peak1 = gaussian(x,a1,f1,l1) peak2 = gaussian(x,a2,f2,l2) model = peak1 + peak2 if data is None: return model, peak1, peak2 if eps is None: return (model - data) return (model - data)/eps
identifier_body
IR_dec_comb.py
# -*- coding: utf-8 -*- """ Created on Tue Jul 22 07:54:05 2014 @author: charleslelosq Carnegie Institution for Science """ import sys sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/") import csv import numpy as np import scipy import matplotlib import matplotlib.gridspec as gridspec from pylab import * from StringIO import StringIO from scipy import interpolate # to fit spectra we use the lmfit software of Matt Newville, CARS, university of Chicago, available on the web from lmfit import minimize, Minimizer, Parameters, Parameter, report_fit, fit_report from spectratools import * #Charles' libraries and functions from Tkinter import * import tkMessageBox from tkFileDialog import askopenfilename #### We define a set of functions that will be used for fitting data #### unfortunatly, as we use lmfit (which is convenient because it can fix or release #### easily the parameters) we are not able to use arrays for parameters... #### so it is a little bit long to write all the things, but in a way quite robust also... #### gaussian and pseudovoigt functions are available in spectratools #### if you need a voigt, fix the gaussian-to-lorentzian ratio to 1 in the parameter definition before #### doing the data fit def residual(pars, x, data=None, eps=None): # unpack parameters: # extract .value attribute for each parameter a1 = pars['a1'].value a2 = pars['a2'].value f1 = pars['f1'].value f2 = pars['f2'].value l1 = pars['l1'].value l2 = pars['l2'].value # Gaussian model peak1 = gaussian(x,a1,f1,l1) peak2 = gaussian(x,a2,f2,l2) model = peak1 + peak2 if data is None: return model, peak1, peak2 if eps is None: return (model - data) return (model - data)/eps ##### CORE OF THE CALCULATION BELOW #### CALLING THE DATA NAMES tkMessageBox.showinfo( "Open file", "Please open the list of spectra") Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file with open(filename) as inputfile: results = list(csv.reader(inputfile)) # we read the data list #### LOOP FOR BEING ABLE TO TREAT MULTIPLE DATA #### WARNING: OUTPUT ARE AUTOMATICALLY GENERATED IN A DIRECTORY CALLED "DECONV" #### (see end) THAT SHOULD BE PRESENT !!!!!!!!!! for lg in range(len(results)):
name = str(results[lg]).strip('[]') name = name[1:-1] # to remove unwanted "" sample = np.genfromtxt(name) # get the sample to deconvolute # we set here the lower and higher bonds for the interest region lb = 4700 ### MAY NEED TO AJUST THAT hb = 6000 interestspectra = sample[np.where((sample[:,0] > lb)&(sample[:,0] < hb))] ese0 = interestspectra[:,2]/abs(interestspectra[:,1]) #take ese as a percentage, we assume that the treatment was made correctly for error determination... if not, please put sigma = None interestspectra[:,1] = interestspectra[:,1]/np.amax(interestspectra[:,1])*100 # normalise spectra to maximum, easier to handle after sigma = abs(ese0*interestspectra[:,1]) #calculate good ese #sigma = None # you can activate that if you are not sure about the errors xfit = interestspectra[:,0] # region to be fitted data = interestspectra[:,1] # region to be fitted params = Parameters() ####################### FOR MELT: ####################### COMMENT IF NOT WANTED # (Name, Value, Vary, Min, Max, Expr) params.add_many(('a1', 1, True, 0, None, None), ('f1', 5200, True, 750, None, None), ('l1', 1, True, 0, None, None), ('a2', 1, True, 0, None, None), ('f2', 5400, True, None, None, None), ('l2', 1, True, None, None, None)) result = minimize(residual_melt, params, args=(xfit, data)) # fit data with leastsq model from scipy model = fit_report(params) # the report yout, peak1,peak2,= residual_melt(params,xfit) # the different peaks #### We just calculate the different areas up to 4700 cmm-1 and those of the gaussians # Select interest areas for calculating the areas of OH and H2Omol peaks intarea45 = sample[np.where((sample[:,0]> 4100) & (sample[:,0]<4700))] area4500 = np.trapz(intarea45[:,1],intarea45[:,0]) esearea4500 = 1/sqrt(area4500) # We assume that RELATIVE errors on areas are globally equal to 1/sqrt(Area) # now for the gaussians # unpack parameters: # extract .value attribute for each parameter a1 = pars['a1'].value a2 = pars['a2'].value l1 = pars['l1'].value l2 = pars['l2'].value AireG1 = gaussianarea(a1,l1) AireG2 = gaussianarea(a2,l2) ##### WE DO A NICE FIGURE THAT CAN BE IMPROVED FOR PUBLICATION fig = figure() plot(sample[:,0],sample[:,1],'k-') plot(xfit,yout,'r-') plot(xfit,peak1,'b-') plot(xfit,peak2,'b-') xlim(lb,hb) ylim(0,np.max(sample[:,1])) xlabel("Wavenumber, cm$^{-1}$", fontsize = 18, fontweight = "bold") ylabel("Absorption, a. u.", fontsize = 18, fontweight = "bold") text(4000,np.max(intarea45[:,1])+0.03*np.max(intarea45[:,1]),('Area OH: \n'+'%.1f' % area4500),color='b',fontsize = 16) text(4650,a1 + 0.05*a1,('Area pic 1$: \n'+ '%.1f' % AireG1),color='b',fontsize = 16) text(5000,a2 + 0.05*a2,('OH/H$_2$O$_{mol}$: \n'+'%.3f' % ratioOH_H2O+'\n+/-'+'%.3f' % eseratioOH_H2O),color='r',fontsize = 16) ##### output of data, fitted peaks, parameters, and the figure in pdf ##### all goes into the ./deconv/ folder name.rfind('/') nameout = name[name.rfind('/')+1::] namesample = nameout[0:nameout.find('.')] pathint = str('/deconv/') # the output folder ext1 = '_ydec.txt' ext2 = '_params.txt' ext3 = '.pdf' pathout1 = pathbeg+pathint+namesample+ext1 pathout2 = pathbeg+pathint+namesample+ext2 pathout3 = pathbeg+pathint+namesample+ext3 matout = np.vstack((xfit,data,yout,peak1,peak2)) matout = np.transpose(matout) np.savetxt(pathout1,matout) # saving the arrays of spectra fd = os.open( pathout2, os.O_RDWR|os.O_CREAT ) # Open a file and create it if it do not exist fo = os.fdopen(fd, "w+") # Now get a file object for the above file. fo.write(model) # write the parameters in it fo.close() savefig(pathout3) # save the figure
conditional_block
IR_dec_comb.py
# -*- coding: utf-8 -*- """ Created on Tue Jul 22 07:54:05 2014 @author: charleslelosq Carnegie Institution for Science """ import sys sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/") import csv import numpy as np import scipy import matplotlib import matplotlib.gridspec as gridspec from pylab import * from StringIO import StringIO from scipy import interpolate # to fit spectra we use the lmfit software of Matt Newville, CARS, university of Chicago, available on the web from lmfit import minimize, Minimizer, Parameters, Parameter, report_fit, fit_report from spectratools import * #Charles' libraries and functions from Tkinter import * import tkMessageBox from tkFileDialog import askopenfilename #### We define a set of functions that will be used for fitting data #### unfortunatly, as we use lmfit (which is convenient because it can fix or release #### easily the parameters) we are not able to use arrays for parameters... #### so it is a little bit long to write all the things, but in a way quite robust also... #### gaussian and pseudovoigt functions are available in spectratools #### if you need a voigt, fix the gaussian-to-lorentzian ratio to 1 in the parameter definition before #### doing the data fit def residual(pars, x, data=None, eps=None): # unpack parameters: # extract .value attribute for each parameter a1 = pars['a1'].value a2 = pars['a2'].value f1 = pars['f1'].value f2 = pars['f2'].value l1 = pars['l1'].value l2 = pars['l2'].value # Gaussian model peak1 = gaussian(x,a1,f1,l1) peak2 = gaussian(x,a2,f2,l2) model = peak1 + peak2 if data is None: return model, peak1, peak2 if eps is None: return (model - data) return (model - data)/eps ##### CORE OF THE CALCULATION BELOW #### CALLING THE DATA NAMES tkMessageBox.showinfo( "Open file", "Please open the list of spectra") Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file with open(filename) as inputfile: results = list(csv.reader(inputfile)) # we read the data list #### LOOP FOR BEING ABLE TO TREAT MULTIPLE DATA #### WARNING: OUTPUT ARE AUTOMATICALLY GENERATED IN A DIRECTORY CALLED "DECONV" #### (see end) THAT SHOULD BE PRESENT !!!!!!!!!! for lg in range(len(results)): name = str(results[lg]).strip('[]') name = name[1:-1] # to remove unwanted "" sample = np.genfromtxt(name) # get the sample to deconvolute # we set here the lower and higher bonds for the interest region lb = 4700 ### MAY NEED TO AJUST THAT hb = 6000 interestspectra = sample[np.where((sample[:,0] > lb)&(sample[:,0] < hb))]
interestspectra[:,1] = interestspectra[:,1]/np.amax(interestspectra[:,1])*100 # normalise spectra to maximum, easier to handle after sigma = abs(ese0*interestspectra[:,1]) #calculate good ese #sigma = None # you can activate that if you are not sure about the errors xfit = interestspectra[:,0] # region to be fitted data = interestspectra[:,1] # region to be fitted params = Parameters() ####################### FOR MELT: ####################### COMMENT IF NOT WANTED # (Name, Value, Vary, Min, Max, Expr) params.add_many(('a1', 1, True, 0, None, None), ('f1', 5200, True, 750, None, None), ('l1', 1, True, 0, None, None), ('a2', 1, True, 0, None, None), ('f2', 5400, True, None, None, None), ('l2', 1, True, None, None, None)) result = minimize(residual_melt, params, args=(xfit, data)) # fit data with leastsq model from scipy model = fit_report(params) # the report yout, peak1,peak2,= residual_melt(params,xfit) # the different peaks #### We just calculate the different areas up to 4700 cmm-1 and those of the gaussians # Select interest areas for calculating the areas of OH and H2Omol peaks intarea45 = sample[np.where((sample[:,0]> 4100) & (sample[:,0]<4700))] area4500 = np.trapz(intarea45[:,1],intarea45[:,0]) esearea4500 = 1/sqrt(area4500) # We assume that RELATIVE errors on areas are globally equal to 1/sqrt(Area) # now for the gaussians # unpack parameters: # extract .value attribute for each parameter a1 = pars['a1'].value a2 = pars['a2'].value l1 = pars['l1'].value l2 = pars['l2'].value AireG1 = gaussianarea(a1,l1) AireG2 = gaussianarea(a2,l2) ##### WE DO A NICE FIGURE THAT CAN BE IMPROVED FOR PUBLICATION fig = figure() plot(sample[:,0],sample[:,1],'k-') plot(xfit,yout,'r-') plot(xfit,peak1,'b-') plot(xfit,peak2,'b-') xlim(lb,hb) ylim(0,np.max(sample[:,1])) xlabel("Wavenumber, cm$^{-1}$", fontsize = 18, fontweight = "bold") ylabel("Absorption, a. u.", fontsize = 18, fontweight = "bold") text(4000,np.max(intarea45[:,1])+0.03*np.max(intarea45[:,1]),('Area OH: \n'+'%.1f' % area4500),color='b',fontsize = 16) text(4650,a1 + 0.05*a1,('Area pic 1$: \n'+ '%.1f' % AireG1),color='b',fontsize = 16) text(5000,a2 + 0.05*a2,('OH/H$_2$O$_{mol}$: \n'+'%.3f' % ratioOH_H2O+'\n+/-'+'%.3f' % eseratioOH_H2O),color='r',fontsize = 16) ##### output of data, fitted peaks, parameters, and the figure in pdf ##### all goes into the ./deconv/ folder name.rfind('/') nameout = name[name.rfind('/')+1::] namesample = nameout[0:nameout.find('.')] pathint = str('/deconv/') # the output folder ext1 = '_ydec.txt' ext2 = '_params.txt' ext3 = '.pdf' pathout1 = pathbeg+pathint+namesample+ext1 pathout2 = pathbeg+pathint+namesample+ext2 pathout3 = pathbeg+pathint+namesample+ext3 matout = np.vstack((xfit,data,yout,peak1,peak2)) matout = np.transpose(matout) np.savetxt(pathout1,matout) # saving the arrays of spectra fd = os.open( pathout2, os.O_RDWR|os.O_CREAT ) # Open a file and create it if it do not exist fo = os.fdopen(fd, "w+") # Now get a file object for the above file. fo.write(model) # write the parameters in it fo.close() savefig(pathout3) # save the figure
ese0 = interestspectra[:,2]/abs(interestspectra[:,1]) #take ese as a percentage, we assume that the treatment was made correctly for error determination... if not, please put sigma = None
random_line_split
IR_dec_comb.py
# -*- coding: utf-8 -*- """ Created on Tue Jul 22 07:54:05 2014 @author: charleslelosq Carnegie Institution for Science """ import sys sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/") import csv import numpy as np import scipy import matplotlib import matplotlib.gridspec as gridspec from pylab import * from StringIO import StringIO from scipy import interpolate # to fit spectra we use the lmfit software of Matt Newville, CARS, university of Chicago, available on the web from lmfit import minimize, Minimizer, Parameters, Parameter, report_fit, fit_report from spectratools import * #Charles' libraries and functions from Tkinter import * import tkMessageBox from tkFileDialog import askopenfilename #### We define a set of functions that will be used for fitting data #### unfortunatly, as we use lmfit (which is convenient because it can fix or release #### easily the parameters) we are not able to use arrays for parameters... #### so it is a little bit long to write all the things, but in a way quite robust also... #### gaussian and pseudovoigt functions are available in spectratools #### if you need a voigt, fix the gaussian-to-lorentzian ratio to 1 in the parameter definition before #### doing the data fit def
(pars, x, data=None, eps=None): # unpack parameters: # extract .value attribute for each parameter a1 = pars['a1'].value a2 = pars['a2'].value f1 = pars['f1'].value f2 = pars['f2'].value l1 = pars['l1'].value l2 = pars['l2'].value # Gaussian model peak1 = gaussian(x,a1,f1,l1) peak2 = gaussian(x,a2,f2,l2) model = peak1 + peak2 if data is None: return model, peak1, peak2 if eps is None: return (model - data) return (model - data)/eps ##### CORE OF THE CALCULATION BELOW #### CALLING THE DATA NAMES tkMessageBox.showinfo( "Open file", "Please open the list of spectra") Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file with open(filename) as inputfile: results = list(csv.reader(inputfile)) # we read the data list #### LOOP FOR BEING ABLE TO TREAT MULTIPLE DATA #### WARNING: OUTPUT ARE AUTOMATICALLY GENERATED IN A DIRECTORY CALLED "DECONV" #### (see end) THAT SHOULD BE PRESENT !!!!!!!!!! for lg in range(len(results)): name = str(results[lg]).strip('[]') name = name[1:-1] # to remove unwanted "" sample = np.genfromtxt(name) # get the sample to deconvolute # we set here the lower and higher bonds for the interest region lb = 4700 ### MAY NEED TO AJUST THAT hb = 6000 interestspectra = sample[np.where((sample[:,0] > lb)&(sample[:,0] < hb))] ese0 = interestspectra[:,2]/abs(interestspectra[:,1]) #take ese as a percentage, we assume that the treatment was made correctly for error determination... if not, please put sigma = None interestspectra[:,1] = interestspectra[:,1]/np.amax(interestspectra[:,1])*100 # normalise spectra to maximum, easier to handle after sigma = abs(ese0*interestspectra[:,1]) #calculate good ese #sigma = None # you can activate that if you are not sure about the errors xfit = interestspectra[:,0] # region to be fitted data = interestspectra[:,1] # region to be fitted params = Parameters() ####################### FOR MELT: ####################### COMMENT IF NOT WANTED # (Name, Value, Vary, Min, Max, Expr) params.add_many(('a1', 1, True, 0, None, None), ('f1', 5200, True, 750, None, None), ('l1', 1, True, 0, None, None), ('a2', 1, True, 0, None, None), ('f2', 5400, True, None, None, None), ('l2', 1, True, None, None, None)) result = minimize(residual_melt, params, args=(xfit, data)) # fit data with leastsq model from scipy model = fit_report(params) # the report yout, peak1,peak2,= residual_melt(params,xfit) # the different peaks #### We just calculate the different areas up to 4700 cmm-1 and those of the gaussians # Select interest areas for calculating the areas of OH and H2Omol peaks intarea45 = sample[np.where((sample[:,0]> 4100) & (sample[:,0]<4700))] area4500 = np.trapz(intarea45[:,1],intarea45[:,0]) esearea4500 = 1/sqrt(area4500) # We assume that RELATIVE errors on areas are globally equal to 1/sqrt(Area) # now for the gaussians # unpack parameters: # extract .value attribute for each parameter a1 = pars['a1'].value a2 = pars['a2'].value l1 = pars['l1'].value l2 = pars['l2'].value AireG1 = gaussianarea(a1,l1) AireG2 = gaussianarea(a2,l2) ##### WE DO A NICE FIGURE THAT CAN BE IMPROVED FOR PUBLICATION fig = figure() plot(sample[:,0],sample[:,1],'k-') plot(xfit,yout,'r-') plot(xfit,peak1,'b-') plot(xfit,peak2,'b-') xlim(lb,hb) ylim(0,np.max(sample[:,1])) xlabel("Wavenumber, cm$^{-1}$", fontsize = 18, fontweight = "bold") ylabel("Absorption, a. u.", fontsize = 18, fontweight = "bold") text(4000,np.max(intarea45[:,1])+0.03*np.max(intarea45[:,1]),('Area OH: \n'+'%.1f' % area4500),color='b',fontsize = 16) text(4650,a1 + 0.05*a1,('Area pic 1$: \n'+ '%.1f' % AireG1),color='b',fontsize = 16) text(5000,a2 + 0.05*a2,('OH/H$_2$O$_{mol}$: \n'+'%.3f' % ratioOH_H2O+'\n+/-'+'%.3f' % eseratioOH_H2O),color='r',fontsize = 16) ##### output of data, fitted peaks, parameters, and the figure in pdf ##### all goes into the ./deconv/ folder name.rfind('/') nameout = name[name.rfind('/')+1::] namesample = nameout[0:nameout.find('.')] pathint = str('/deconv/') # the output folder ext1 = '_ydec.txt' ext2 = '_params.txt' ext3 = '.pdf' pathout1 = pathbeg+pathint+namesample+ext1 pathout2 = pathbeg+pathint+namesample+ext2 pathout3 = pathbeg+pathint+namesample+ext3 matout = np.vstack((xfit,data,yout,peak1,peak2)) matout = np.transpose(matout) np.savetxt(pathout1,matout) # saving the arrays of spectra fd = os.open( pathout2, os.O_RDWR|os.O_CREAT ) # Open a file and create it if it do not exist fo = os.fdopen(fd, "w+") # Now get a file object for the above file. fo.write(model) # write the parameters in it fo.close() savefig(pathout3) # save the figure
residual
identifier_name
mod.rs
pub mod buffers; pub mod cursor; pub mod position; pub mod movement; pub mod insert; use gfx::Screen; use config::Players; use px8::PX8Config; use px8::editor::State; use self::buffers::BufferManager; use self::cursor::Cursor; use px8::editor::text::buffers::TextBuffer; use px8::editor::text::buffers::SplitBuffer; use px8::editor::text::buffers::Buffer; use std::sync::{Arc, Mutex}; use std::cmp::{max, min}; use std::collections::HashMap; use time; pub struct TextEditor { pub buffers: BufferManager, } impl TextEditor { pub fn new(state: Arc<Mutex<State>>) -> TextEditor { TextEditor { buffers: BufferManager::new(), } } pub fn init(&mut self, config: Arc<Mutex<PX8Config>>, screen: &mut Screen, filename: String, code: String) { info!("[GFX_EDITOR] Init"); info!("[GFX_EDITOR] {:?}", self.pos()); let mut new_buffer: Buffer = SplitBuffer::from_str(&code).into(); new_buffer.title = Some(filename); let new_buffer_index = self.buffers.new_buffer(new_buffer); self.buffers.switch_to(new_buffer_index); self.hint(); } pub fn update(&mut self, players: Arc<Mutex<Players>>) -> bool { true } /// Hint the buffer about the cursor position. pub fn hint(&mut self) { let x = self.cursor().x; let y = self.cursor().y; self.buffers.current_buffer_mut().focus_hint_y(y); self.buffers.current_buffer_mut().focus_hint_x(x); } pub fn draw(&mut self, players: Arc<Mutex<Players>>, screen: &mut Screen) { let (scroll_x, scroll_y) = { let current_buffer = self.buffers.current_buffer_info(); (current_buffer.scroll_x, current_buffer.scroll_y) }; let (pos_x, pos_y) = self.pos(); let w = screen.width; screen.rect(4 * (pos_x - scroll_x) as i32, (8 * (pos_y - scroll_y) as i32) + 8, 4 * (pos_x - scroll_x) as i32 + 4, (8 * (pos_y - scroll_y) as i32) + 8 + 8, 8); for (y, row) in self.buffers .current_buffer() .lines() .enumerate() { for (x, c) in row.chars().enumerate() { let c = if c == '\t'
else { c }; let pos_char_x = 4 * (x - scroll_x) as i32; let pos_char_y = 8 * (y - scroll_y) as i32; //info!("OFF C {:?} X {:?} {:?}", c, pos_char_x, pos_char_y); screen.print_char(c, pos_char_x, pos_char_y + 8, 7); } } } }
{ ' ' }
conditional_block
mod.rs
pub mod buffers; pub mod cursor; pub mod position; pub mod movement; pub mod insert; use gfx::Screen; use config::Players; use px8::PX8Config; use px8::editor::State; use self::buffers::BufferManager; use self::cursor::Cursor; use px8::editor::text::buffers::TextBuffer; use px8::editor::text::buffers::SplitBuffer; use px8::editor::text::buffers::Buffer; use std::sync::{Arc, Mutex}; use std::cmp::{max, min}; use std::collections::HashMap; use time; pub struct TextEditor { pub buffers: BufferManager, } impl TextEditor { pub fn new(state: Arc<Mutex<State>>) -> TextEditor { TextEditor { buffers: BufferManager::new(), } } pub fn init(&mut self, config: Arc<Mutex<PX8Config>>, screen: &mut Screen, filename: String, code: String) { info!("[GFX_EDITOR] Init"); info!("[GFX_EDITOR] {:?}", self.pos()); let mut new_buffer: Buffer = SplitBuffer::from_str(&code).into(); new_buffer.title = Some(filename); let new_buffer_index = self.buffers.new_buffer(new_buffer); self.buffers.switch_to(new_buffer_index); self.hint(); } pub fn update(&mut self, players: Arc<Mutex<Players>>) -> bool { true } /// Hint the buffer about the cursor position. pub fn hint(&mut self) {
let y = self.cursor().y; self.buffers.current_buffer_mut().focus_hint_y(y); self.buffers.current_buffer_mut().focus_hint_x(x); } pub fn draw(&mut self, players: Arc<Mutex<Players>>, screen: &mut Screen) { let (scroll_x, scroll_y) = { let current_buffer = self.buffers.current_buffer_info(); (current_buffer.scroll_x, current_buffer.scroll_y) }; let (pos_x, pos_y) = self.pos(); let w = screen.width; screen.rect(4 * (pos_x - scroll_x) as i32, (8 * (pos_y - scroll_y) as i32) + 8, 4 * (pos_x - scroll_x) as i32 + 4, (8 * (pos_y - scroll_y) as i32) + 8 + 8, 8); for (y, row) in self.buffers .current_buffer() .lines() .enumerate() { for (x, c) in row.chars().enumerate() { let c = if c == '\t' { ' ' } else { c }; let pos_char_x = 4 * (x - scroll_x) as i32; let pos_char_y = 8 * (y - scroll_y) as i32; //info!("OFF C {:?} X {:?} {:?}", c, pos_char_x, pos_char_y); screen.print_char(c, pos_char_x, pos_char_y + 8, 7); } } } }
let x = self.cursor().x;
random_line_split
mod.rs
pub mod buffers; pub mod cursor; pub mod position; pub mod movement; pub mod insert; use gfx::Screen; use config::Players; use px8::PX8Config; use px8::editor::State; use self::buffers::BufferManager; use self::cursor::Cursor; use px8::editor::text::buffers::TextBuffer; use px8::editor::text::buffers::SplitBuffer; use px8::editor::text::buffers::Buffer; use std::sync::{Arc, Mutex}; use std::cmp::{max, min}; use std::collections::HashMap; use time; pub struct TextEditor { pub buffers: BufferManager, } impl TextEditor { pub fn new(state: Arc<Mutex<State>>) -> TextEditor { TextEditor { buffers: BufferManager::new(), } } pub fn
(&mut self, config: Arc<Mutex<PX8Config>>, screen: &mut Screen, filename: String, code: String) { info!("[GFX_EDITOR] Init"); info!("[GFX_EDITOR] {:?}", self.pos()); let mut new_buffer: Buffer = SplitBuffer::from_str(&code).into(); new_buffer.title = Some(filename); let new_buffer_index = self.buffers.new_buffer(new_buffer); self.buffers.switch_to(new_buffer_index); self.hint(); } pub fn update(&mut self, players: Arc<Mutex<Players>>) -> bool { true } /// Hint the buffer about the cursor position. pub fn hint(&mut self) { let x = self.cursor().x; let y = self.cursor().y; self.buffers.current_buffer_mut().focus_hint_y(y); self.buffers.current_buffer_mut().focus_hint_x(x); } pub fn draw(&mut self, players: Arc<Mutex<Players>>, screen: &mut Screen) { let (scroll_x, scroll_y) = { let current_buffer = self.buffers.current_buffer_info(); (current_buffer.scroll_x, current_buffer.scroll_y) }; let (pos_x, pos_y) = self.pos(); let w = screen.width; screen.rect(4 * (pos_x - scroll_x) as i32, (8 * (pos_y - scroll_y) as i32) + 8, 4 * (pos_x - scroll_x) as i32 + 4, (8 * (pos_y - scroll_y) as i32) + 8 + 8, 8); for (y, row) in self.buffers .current_buffer() .lines() .enumerate() { for (x, c) in row.chars().enumerate() { let c = if c == '\t' { ' ' } else { c }; let pos_char_x = 4 * (x - scroll_x) as i32; let pos_char_y = 8 * (y - scroll_y) as i32; //info!("OFF C {:?} X {:?} {:?}", c, pos_char_x, pos_char_y); screen.print_char(c, pos_char_x, pos_char_y + 8, 7); } } } }
init
identifier_name
json.js
dojo.provide("tests._base.json");
[ //Not testing dojo.toJson() on its own since Rhino will output the object properties in a different order. //Still valid json, but just in a different order than the source string. // take a json-compatible object, convert it to a json string, then put it back into json. function toAndFromJson(t){ var testObj = {a:"a", b:1, c:"c", d:"d", e:{e1:"e1", e2:2}, f:[1,2,3], g:"g",h:{h1:{h2:{h3:"h3"}}}}; var mirrorObj = dojo.fromJson(dojo.toJson(testObj)); t.assertEqual("a", mirrorObj.a); t.assertEqual(1, mirrorObj.b); t.assertEqual("c", mirrorObj.c); t.assertEqual("d", mirrorObj.d); t.assertEqual("e1", mirrorObj.e.e1); t.assertEqual(2, mirrorObj.e.e2); t.assertEqual(1, mirrorObj.f[0]); t.assertEqual(2, mirrorObj.f[1]); t.assertEqual(3, mirrorObj.f[2]); t.assertEqual("g", mirrorObj.g); t.assertEqual("h3", mirrorObj.h.h1.h2.h3); var badJson; try{ badJson = dojo.fromJson("bad json"); // this should throw an exception, and not set badJson }catch(e){ } t.assertEqual(undefined,badJson); } ] );
tests.register("tests._base.json",
random_line_split
iconWarning.tsx
import React from 'react'; import SvgIcon from './svgIcon'; type Props = React.ComponentProps<typeof SvgIcon>;
return ( <SvgIcon {...props} ref={ref}> <path d="M13.87,15.26H2.13A2.1,2.1,0,0,1,0,13.16a2.07,2.07,0,0,1,.27-1L6.17,1.8a2.1,2.1,0,0,1,1.27-1,2.11,2.11,0,0,1,2.39,1L15.7,12.11a2.1,2.1,0,0,1-1.83,3.15ZM8,2.24a.44.44,0,0,0-.16,0,.58.58,0,0,0-.37.28L1.61,12.86a.52.52,0,0,0-.08.3.6.6,0,0,0,.6.6H13.87a.54.54,0,0,0,.3-.08.59.59,0,0,0,.22-.82L8.53,2.54h0a.61.61,0,0,0-.23-.22A.54.54,0,0,0,8,2.24Z" /> <path d="M8,10.37a.75.75,0,0,1-.75-.75V5.92a.75.75,0,0,1,1.5,0v3.7A.74.74,0,0,1,8,10.37Z" /> <circle cx="8" cy="11.79" r="0.76" /> </SvgIcon> ); }); IconWarning.displayName = 'IconWarning'; export {IconWarning};
const IconWarning = React.forwardRef(function IconWarning( props: Props, ref: React.Ref<SVGSVGElement> ) {
random_line_split
Status.js
'use strict'; var util = require('util'); var Promise = require('bluebird'); var uuid = require('../../utils/uuid'); var errors = require('../../errors'); var EmbeddedModel = require('../../EmbeddedModel'); // Schema Validator // ---------------- var validator = require('jjv')(); validator.addSchema(require('../../schemas/cycle')); // EmbeddedModel Constructor // ------------------------- function Status (conn, data, parent)
// EmbeddedModel Configuration // --------------------------- Status.key = 'statuses'; Status.collections = {}; Status.validate = function(data) { return validator.validate('http://www.gandhi.io/schema/cycle#/definitions/status', data, {useDefault: true, removeAdditional: true}); }; Status.create = function(conn, data, parent) { if(!parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); // generate a new uuid data.id = uuid(); var err = Status.validate(data); if(err) return Promise.reject(new errors.ValidationError('The input is invalid.', err)); return new Status(conn, data, parent) .then(function(status) { return status.save(conn); }); }; // Public Methods // -------------- util.inherits(Status, EmbeddedModel); // check authorizations for update Status.prototype.update = function(conn, delta) { var self = this; if(!self.parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); return EmbeddedModel.prototype.update.call(self, conn, delta); }; // check authorizations for delete Status.prototype.delete = function(conn) { var self = this; if(!self.parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); return EmbeddedModel.prototype.delete.call(self, conn); }; module.exports = Status;
{ return EmbeddedModel.call(this, conn, data, parent) .then(function(self) { // check authorizations if(!self.parent.authorizations['cycle/statuses:read']) return Promise.reject(new errors.ForbiddenError()); // cycle_id self.cycle_id = self.parent.id; return self; }); }
identifier_body
Status.js
'use strict'; var util = require('util'); var Promise = require('bluebird'); var uuid = require('../../utils/uuid'); var errors = require('../../errors'); var EmbeddedModel = require('../../EmbeddedModel'); // Schema Validator // ---------------- var validator = require('jjv')(); validator.addSchema(require('../../schemas/cycle')); // EmbeddedModel Constructor // ------------------------- function Status (conn, data, parent) { return EmbeddedModel.call(this, conn, data, parent) .then(function(self) { // check authorizations if(!self.parent.authorizations['cycle/statuses:read']) return Promise.reject(new errors.ForbiddenError()); // cycle_id self.cycle_id = self.parent.id; return self; }); } // EmbeddedModel Configuration // --------------------------- Status.key = 'statuses'; Status.collections = {}; Status.validate = function(data) { return validator.validate('http://www.gandhi.io/schema/cycle#/definitions/status', data, {useDefault: true, removeAdditional: true}); }; Status.create = function(conn, data, parent) { if(!parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); // generate a new uuid data.id = uuid(); var err = Status.validate(data); if(err) return Promise.reject(new errors.ValidationError('The input is invalid.', err)); return new Status(conn, data, parent) .then(function(status) { return status.save(conn); }); }; // Public Methods // -------------- util.inherits(Status, EmbeddedModel); // check authorizations for update Status.prototype.update = function(conn, delta) { var self = this; if(!self.parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); return EmbeddedModel.prototype.update.call(self, conn, delta); }; // check authorizations for delete Status.prototype.delete = function(conn) { var self = this;
}; module.exports = Status;
if(!self.parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); return EmbeddedModel.prototype.delete.call(self, conn);
random_line_split
Status.js
'use strict'; var util = require('util'); var Promise = require('bluebird'); var uuid = require('../../utils/uuid'); var errors = require('../../errors'); var EmbeddedModel = require('../../EmbeddedModel'); // Schema Validator // ---------------- var validator = require('jjv')(); validator.addSchema(require('../../schemas/cycle')); // EmbeddedModel Constructor // ------------------------- function
(conn, data, parent) { return EmbeddedModel.call(this, conn, data, parent) .then(function(self) { // check authorizations if(!self.parent.authorizations['cycle/statuses:read']) return Promise.reject(new errors.ForbiddenError()); // cycle_id self.cycle_id = self.parent.id; return self; }); } // EmbeddedModel Configuration // --------------------------- Status.key = 'statuses'; Status.collections = {}; Status.validate = function(data) { return validator.validate('http://www.gandhi.io/schema/cycle#/definitions/status', data, {useDefault: true, removeAdditional: true}); }; Status.create = function(conn, data, parent) { if(!parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); // generate a new uuid data.id = uuid(); var err = Status.validate(data); if(err) return Promise.reject(new errors.ValidationError('The input is invalid.', err)); return new Status(conn, data, parent) .then(function(status) { return status.save(conn); }); }; // Public Methods // -------------- util.inherits(Status, EmbeddedModel); // check authorizations for update Status.prototype.update = function(conn, delta) { var self = this; if(!self.parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); return EmbeddedModel.prototype.update.call(self, conn, delta); }; // check authorizations for delete Status.prototype.delete = function(conn) { var self = this; if(!self.parent.authorizations['cycle/statuses:write']) return Promise.reject(new errors.ForbiddenError()); return EmbeddedModel.prototype.delete.call(self, conn); }; module.exports = Status;
Status
identifier_name
macros.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Standard library macros //! //! This modules contains a set of macros which are exported from the standard //! library. Each macro is available for use when linking against the standard //! library. #![experimental] #![macro_escape] /// The entry point for panic of Rust tasks. /// /// This macro is used to inject panic into a Rust task, causing the task to /// unwind and panic entirely. Each task's panic can be reaped as the /// `Box<Any>` type, and the single-argument form of the `panic!` macro will be /// the value which is transmitted. /// /// The multi-argument form of this macro panics with a string and has the /// `format!` syntax for building a string. /// /// # Example /// /// ```should_fail /// # #![allow(unreachable_code)] /// panic!(); /// panic!("this is a terrible mistake!"); /// panic!(4i); // panic with the value of 4 to be collected elsewhere /// panic!("this is a {} {message}", "fancy", message = "message"); /// ``` #[macro_export] macro_rules! panic( () => ({ panic!("explicit panic") }); ($msg:expr) => ({ // static requires less code at runtime, more constant data static _FILE_LINE: (&'static str, uint) = (file!(), line!()); ::std::rt::begin_unwind($msg, &_FILE_LINE) }); ($fmt:expr, $($arg:tt)*) => ({ // a closure can't have return type !, so we need a full // function to pass to format_args!, *and* we need the // file and line numbers right here; so an inner bare fn // is our only choice. // // LLVM doesn't tend to inline this, presumably because begin_unwind_fmt // is #[cold] and #[inline(never)] and because this is flagged as cold // as returning !. We really do want this to be inlined, however, // because it's just a tiny wrapper. Small wins (156K to 149K in size) // were seen when forcing this to be inlined, and that number just goes // up with the number of calls to panic!() // // The leading _'s are to avoid dead code warnings if this is // used inside a dead function. Just `#[allow(dead_code)]` is // insufficient, since the user may have // `#[forbid(dead_code)]` and which cannot be overridden. #[inline(always)] fn _run_fmt(fmt: &::std::fmt::Arguments) -> ! { static _FILE_LINE: (&'static str, uint) = (file!(), line!()); ::std::rt::begin_unwind_fmt(fmt, &_FILE_LINE) } format_args!(_run_fmt, $fmt, $($arg)*) }); ) /// Ensure that a boolean expression is `true` at runtime. /// /// This will invoke the `panic!` macro if the provided expression cannot be /// evaluated to `true` at runtime. /// /// # Example /// /// ``` /// // the panic message for these assertions is the stringified value of the /// // expression given. /// assert!(true); /// # fn some_computation() -> bool { true } /// assert!(some_computation()); /// /// // assert with a custom message /// # let x = true; /// assert!(x, "x wasn't true!"); /// # let a = 3i; let b = 27i; /// assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] macro_rules! assert( ($cond:expr) => ( if !$cond { panic!(concat!("assertion failed: ", stringify!($cond))) } ); ($cond:expr, $($arg:expr),+) => ( if !$cond { panic!($($arg),+) } );
/// Asserts that two expressions are equal to each other, testing equality in /// both directions. /// /// On panic, this macro will print the values of the expressions. /// /// # Example /// /// ``` /// let a = 3i; /// let b = 1i + 2i; /// assert_eq!(a, b); /// ``` #[macro_export] macro_rules! assert_eq( ($given:expr , $expected:expr) => ({ match (&($given), &($expected)) { (given_val, expected_val) => { // check both directions of equality.... if !((*given_val == *expected_val) && (*expected_val == *given_val)) { panic!("assertion failed: `(left == right) && (right == left)` \ (left: `{}`, right: `{}`)", *given_val, *expected_val) } } } }) ) /// Ensure that a boolean expression is `true` at runtime. /// /// This will invoke the `panic!` macro if the provided expression cannot be /// evaluated to `true` at runtime. /// /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for /// checks that are too expensive to be present in a release build but may be /// helpful during development. /// /// # Example /// /// ``` /// // the panic message for these assertions is the stringified value of the /// // expression given. /// debug_assert!(true); /// # fn some_expensive_computation() -> bool { true } /// debug_assert!(some_expensive_computation()); /// /// // assert with a custom message /// # let x = true; /// debug_assert!(x, "x wasn't true!"); /// # let a = 3i; let b = 27i; /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] macro_rules! debug_assert( ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); }) ) /// Asserts that two expressions are equal to each other, testing equality in /// both directions. /// /// On panic, this macro will print the values of the expressions. /// /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!` /// useful for checks that are too expensive to be present in a release build /// but may be helpful during development. /// /// # Example /// /// ``` /// let a = 3i; /// let b = 1i + 2i; /// debug_assert_eq!(a, b); /// ``` #[macro_export] macro_rules! debug_assert_eq( ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); }) ) /// A utility macro for indicating unreachable code. It will panic if /// executed. This is occasionally useful to put after loops that never /// terminate normally, but instead directly return from a function. /// /// # Example /// /// ```{.rust} /// struct Item { weight: uint } /// /// fn choose_weighted_item(v: &[Item]) -> Item { /// assert!(!v.is_empty()); /// let mut so_far = 0u; /// for item in v.iter() { /// so_far += item.weight; /// if so_far > 100 { /// return *item; /// } /// } /// // The above loop always returns, so we must hint to the /// // type checker that it isn't possible to get down here /// unreachable!(); /// } /// ``` #[macro_export] macro_rules! unreachable( () => ({ panic!("internal error: entered unreachable code") }); ($msg:expr) => ({ unreachable!("{}", $msg) }); ($fmt:expr, $($arg:tt)*) => ({ panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*) }); ) /// A standardised placeholder for marking unfinished code. It panics with the /// message `"not yet implemented"` when executed. #[macro_export] macro_rules! unimplemented( () => (panic!("not yet implemented")) ) /// Use the syntax described in `std::fmt` to create a value of type `String`. /// See `std::fmt` for more information. /// /// # Example /// /// ``` /// format!("test"); /// format!("hello {}", "world!"); /// format!("x = {}, y = {y}", 10i, y = 30i); /// ``` #[macro_export] macro_rules! format( ($($arg:tt)*) => ( format_args!(::std::fmt::format, $($arg)*) ) ) /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`. /// See `std::fmt` for more information. /// /// # Example /// /// ``` /// # #![allow(unused_must_use)] /// use std::io::MemWriter; /// /// let mut w = MemWriter::new(); /// write!(&mut w, "test"); /// write!(&mut w, "formatted {}", "arguments"); /// ``` #[macro_export] macro_rules! write( ($dst:expr, $($arg:tt)*) => ({ format_args_method!($dst, write_fmt, $($arg)*) }) ) /// Equivalent to the `write!` macro, except that a newline is appended after /// the message is written. #[macro_export] macro_rules! writeln( ($dst:expr, $fmt:expr $($arg:tt)*) => ( write!($dst, concat!($fmt, "\n") $($arg)*) ) ) /// Equivalent to the `println!` macro except that a newline is not printed at /// the end of the message. #[macro_export] macro_rules! print( ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*)) ) /// Macro for printing to a task's stdout handle. /// /// Each task can override its stdout handle via `std::io::stdio::set_stdout`. /// The syntax of this macro is the same as that used for `format!`. For more /// information, see `std::fmt` and `std::io::stdio`. /// /// # Example /// /// ``` /// println!("hello there!"); /// println!("format {} arguments", "some"); /// ``` #[macro_export] macro_rules! println( ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*)) ) /// Declare a task-local key with a specific type. /// /// # Example /// /// ``` /// local_data_key!(my_integer: int) /// /// my_integer.replace(Some(2)); /// println!("{}", my_integer.get().map(|a| *a)); /// ``` #[macro_export] macro_rules! local_data_key( ($name:ident: $ty:ty) => ( #[allow(non_upper_case_globals)] static $name: ::std::local_data::Key<$ty> = &::std::local_data::KeyValueKey; ); (pub $name:ident: $ty:ty) => ( #[allow(non_upper_case_globals)] pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::KeyValueKey; ); ) /// Helper macro for unwrapping `Result` values while returning early with an /// error if the value of the expression is `Err`. For more information, see /// `std::io`. #[macro_export] macro_rules! try ( ($expr:expr) => ({ match $expr { Ok(val) => val, Err(err) => return Err(::std::error::FromError::from_error(err)) } }) ) /// Create a `std::vec::Vec` containing the arguments. #[macro_export] macro_rules! vec[ ($($x:expr),*) => ({ use std::slice::BoxedSlicePrelude; let xs: ::std::boxed::Box<[_]> = box [$($x),*]; xs.into_vec() }); ($($x:expr,)*) => (vec![$($x),*]) ] /// A macro to select an event from a number of receivers. /// /// This macro is used to wait for the first event to occur on a number of /// receivers. It places no restrictions on the types of receivers given to /// this macro, this can be viewed as a heterogeneous select. /// /// # Example /// /// ``` /// let (tx1, rx1) = channel(); /// let (tx2, rx2) = channel(); /// # fn long_running_task() {} /// # fn calculate_the_answer() -> int { 42i } /// /// spawn(proc() { long_running_task(); tx1.send(()) }); /// spawn(proc() { tx2.send(calculate_the_answer()) }); /// /// select! ( /// () = rx1.recv() => println!("the long running task finished first"), /// answer = rx2.recv() => { /// println!("the answer was: {}", answer); /// } /// ) /// ``` /// /// For more information about select, see the `std::comm::Select` structure. #[macro_export] #[experimental] macro_rules! select { ( $($name:pat = $rx:ident.$meth:ident() => $code:expr),+ ) => ({ use std::comm::Select; let sel = Select::new(); $( let mut $rx = sel.handle(&$rx); )+ unsafe { $( $rx.add(); )+ } let ret = sel.wait(); $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+ { unreachable!() } }) } // When testing the standard library, we link to the liblog crate to get the // logging macros. In doing so, the liblog crate was linked against the real // version of libstd, and uses a different std::fmt module than the test crate // uses. To get around this difference, we redefine the log!() macro here to be // just a dumb version of what it should be. #[cfg(test)] macro_rules! log ( ($lvl:expr, $($args:tt)*) => ( if log_enabled!($lvl) { println!($($args)*) } ) ) /// Built-in macros to the compiler itself. /// /// These macros do not have any corresponding definition with a `macro_rules!` /// macro, but are documented here. Their implementations can be found hardcoded /// into libsyntax itself. #[cfg(dox)] pub mod builtin { /// The core macro for formatted string creation & output. /// /// This macro takes as its first argument a callable expression which will /// receive as its first argument a value of type `&fmt::Arguments`. This /// value can be passed to the functions in `std::fmt` for performing useful /// functions. All other formatting macros (`format!`, `write!`, /// `println!`, etc) are proxied through this one. /// /// For more information, see the documentation in `std::fmt`. /// /// # Example /// /// ```rust /// use std::fmt; /// /// let s = format_args!(fmt::format, "hello {}", "world"); /// assert_eq!(s, format!("hello {}", "world")); /// /// format_args!(|args| { /// // pass `args` to another function, etc. /// }, "hello {}", "world"); /// ``` #[macro_export] macro_rules! format_args( ($closure:expr, $fmt:expr $($args:tt)*) => ({ /* compiler built-in */ }) ) /// Inspect an environment variable at compile time. /// /// This macro will expand to the value of the named environment variable at /// compile time, yielding an expression of type `&'static str`. /// /// If the environment variable is not defined, then a compilation error /// will be emitted. To not emit a compile error, use the `option_env!` /// macro instead. /// /// # Example /// /// ```rust /// let path: &'static str = env!("PATH"); /// println!("the $PATH variable at the time of compiling was: {}", path); /// ``` #[macro_export] macro_rules! env( ($name:expr) => ({ /* compiler built-in */ }) ) /// Optionally inspect an environment variable at compile time. /// /// If the named environment variable is present at compile time, this will /// expand into an expression of type `Option<&'static str>` whose value is /// `Some` of the value of the environment variable. If the environment /// variable is not present, then this will expand to `None`. /// /// A compile time error is never emitted when using this macro regardless /// of whether the environment variable is present or not. /// /// # Example /// /// ```rust /// let key: Option<&'static str> = option_env!("SECRET_KEY"); /// println!("the secret key might be: {}", key); /// ``` #[macro_export] macro_rules! option_env( ($name:expr) => ({ /* compiler built-in */ }) ) /// Concatenate literals into a static byte slice. /// /// This macro takes any number of comma-separated literal expressions, /// yielding an expression of type `&'static [u8]` which is the /// concatenation (left to right) of all the literals in their byte format. /// /// This extension currently only supports string literals, character /// literals, and integers less than 256. The byte slice returned is the /// utf8-encoding of strings and characters. /// /// # Example /// /// ``` /// let rust = bytes!("r", 'u', "st", 255); /// assert_eq!(rust[1], b'u'); /// assert_eq!(rust[4], 255); /// ``` #[macro_export] macro_rules! bytes( ($($e:expr),*) => ({ /* compiler built-in */ }) ) /// Concatenate identifiers into one identifier. /// /// This macro takes any number of comma-separated identifiers, and /// concatenates them all into one, yielding an expression which is a new /// identifier. Note that hygiene makes it such that this macro cannot /// capture local variables, and macros are only allowed in item, /// statement or expression position, meaning this macro may be difficult to /// use in some situations. /// /// # Example /// /// ``` /// #![feature(concat_idents)] /// /// # fn main() { /// fn foobar() -> int { 23 } /// /// let f = concat_idents!(foo, bar); /// println!("{}", f()); /// # } /// ``` #[macro_export] macro_rules! concat_idents( ($($e:ident),*) => ({ /* compiler built-in */ }) ) /// Concatenates literals into a static string slice. /// /// This macro takes any number of comma-separated literals, yielding an /// expression of type `&'static str` which represents all of the literals /// concatenated left-to-right. /// /// Integer and floating point literals are stringified in order to be /// concatenated. /// /// # Example /// /// ``` /// let s = concat!("test", 10i, 'b', true); /// assert_eq!(s, "test10btrue"); /// ``` #[macro_export] macro_rules! concat( ($($e:expr),*) => ({ /* compiler built-in */ }) ) /// A macro which expands to the line number on which it was invoked. /// /// The expanded expression has type `uint`, and the returned line is not /// the invocation of the `line!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `line!()` macro. /// /// # Example /// /// ``` /// let current_line = line!(); /// println!("defined on line: {}", current_line); /// ``` #[macro_export] macro_rules! line( () => ({ /* compiler built-in */ }) ) /// A macro which expands to the column number on which it was invoked. /// /// The expanded expression has type `uint`, and the returned column is not /// the invocation of the `col!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `col!()` macro. /// /// # Example /// /// ``` /// let current_col = col!(); /// println!("defined on column: {}", current_col); /// ``` #[macro_export] macro_rules! col( () => ({ /* compiler built-in */ }) ) /// A macro which expands to the file name from which it was invoked. /// /// The expanded expression has type `&'static str`, and the returned file /// is not the invocation of the `file!()` macro itself, but rather the /// first macro invocation leading up to the invocation of the `file!()` /// macro. /// /// # Example /// /// ``` /// let this_file = file!(); /// println!("defined in file: {}", this_file); /// ``` #[macro_export] macro_rules! file( () => ({ /* compiler built-in */ }) ) /// A macro which stringifies its argument. /// /// This macro will yield an expression of type `&'static str` which is the /// stringification of all the tokens passed to the macro. No restrictions /// are placed on the syntax of the macro invocation itself. /// /// # Example /// /// ``` /// let one_plus_one = stringify!(1 + 1); /// assert_eq!(one_plus_one, "1 + 1"); /// ``` #[macro_export] macro_rules! stringify( ($t:tt) => ({ /* compiler built-in */ }) ) /// Includes a utf8-encoded file as a string. /// /// This macro will yield an expression of type `&'static str` which is the /// contents of the filename specified. The file is located relative to the /// current file (similarly to how modules are found), /// /// # Example /// /// ```rust,ignore /// let secret_key = include_str!("secret-key.ascii"); /// ``` #[macro_export] macro_rules! include_str( ($file:expr) => ({ /* compiler built-in */ }) ) /// Includes a file as a byte slice. /// /// This macro will yield an expression of type `&'static [u8]` which is /// the contents of the filename specified. The file is located relative to /// the current file (similarly to how modules are found), /// /// # Example /// /// ```rust,ignore /// let secret_key = include_bin!("secret-key.bin"); /// ``` #[macro_export] macro_rules! include_bin( ($file:expr) => ({ /* compiler built-in */ }) ) /// Expands to a string that represents the current module path. /// /// The current module path can be thought of as the hierarchy of modules /// leading back up to the crate root. The first component of the path /// returned is the name of the crate currently being compiled. /// /// # Example /// /// ```rust /// mod test { /// pub fn foo() { /// assert!(module_path!().ends_with("test")); /// } /// } /// /// test::foo(); /// ``` #[macro_export] macro_rules! module_path( () => ({ /* compiler built-in */ }) ) /// Boolean evaluation of configuration flags. /// /// In addition to the `#[cfg]` attribute, this macro is provided to allow /// boolean expression evaluation of configuration flags. This frequently /// leads to less duplicated code. /// /// The syntax given to this macro is the same syntax as the `cfg` /// attribute. /// /// # Example /// /// ```rust /// let my_directory = if cfg!(windows) { /// "windows-specific-directory" /// } else { /// "unix-directory" /// }; /// ``` #[macro_export] macro_rules! cfg( ($cfg:tt) => ({ /* compiler built-in */ }) ) }
)
random_line_split
tutils.py
from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs):
class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default)
""" Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret))
identifier_body
tutils.py
from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes):
""" fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default)
""" Construct a tcp.Read object from bytes.
random_line_split
tutils.py
from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def
(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default)
__enter__
identifier_name
tutils.py
from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types):
else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default)
if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb)
conditional_block
lib.es6.set.d.ts
/*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ interface Set<T> { add(value: T): Set<T>; clear(): void; delete(value: T): boolean; entries(): IterableIterator<[T, T]>; forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void; has(value: T): boolean; keys(): IterableIterator<T>; size: number; values(): IterableIterator<T>; [Symbol.iterator]():IterableIterator<T>; [Symbol.toStringTag]: string; }
interface SetConstructor { new <T>(): Set<T>; new <T>(iterable: Iterable<T>): Set<T>; prototype: Set<any>; } declare var Set: SetConstructor;
random_line_split
issue-3753.rs
// run-pass // Issue #3656 // Issue Name: pub method preceded by attribute can't be parsed // Abstract: Visibility parsing failed when compiler parsing use std::f64; #[derive(Copy, Clone)] pub struct Point { x: f64, y: f64 } #[derive(Copy, Clone)] pub enum
{ Circle(Point, f64), Rectangle(Point, Point) } impl Shape { pub fn area(&self, sh: Shape) -> f64 { match sh { Shape::Circle(_, size) => f64::consts::PI * size * size, Shape::Rectangle(Point {x, y}, Point {x: x2, y: y2}) => (x2 - x) * (y2 - y) } } } pub fn main(){ let s = Shape::Circle(Point { x: 1.0, y: 2.0 }, 3.0); println!("{}", s.area(s)); }
Shape
identifier_name
issue-3753.rs
// run-pass // Issue #3656 // Issue Name: pub method preceded by attribute can't be parsed // Abstract: Visibility parsing failed when compiler parsing use std::f64; #[derive(Copy, Clone)]
pub struct Point { x: f64, y: f64 } #[derive(Copy, Clone)] pub enum Shape { Circle(Point, f64), Rectangle(Point, Point) } impl Shape { pub fn area(&self, sh: Shape) -> f64 { match sh { Shape::Circle(_, size) => f64::consts::PI * size * size, Shape::Rectangle(Point {x, y}, Point {x: x2, y: y2}) => (x2 - x) * (y2 - y) } } } pub fn main(){ let s = Shape::Circle(Point { x: 1.0, y: 2.0 }, 3.0); println!("{}", s.area(s)); }
random_line_split
PieChart.js
import SVG from './SVG'; import Radium from 'radium'; import { layout, svg } from 'd3'; import { Spring } from 'react-motion'; import { Component, PropTypes } from 'react'; export default class PieChart extends Component { static defaultProps = { data: PropTypes.array.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, outerRadius: PropTypes.number.isRequired, innerRadius: PropTypes.number.isRequired
state = { ...[...Array(this.props.data.length)].map(() => false) } onMouseOver = (i) => () => this.setState({ [i]: true }) onMouseOut = (i) => () => this.setState({ [i]: false }) render() { const { innerRadius, outerRadius, width, height } = this.props; const pie = layout.pie().padAngle(.02); const arc = svg.arc().padRadius(outerRadius).innerRadius(innerRadius); return ( <SVG width={width} height={height}> <g transform={`translate(${width / 2}, ${height / 2})`}> { pie(this.props.data).map( (dataPoint, i) => <Spring key={i} endValue={{ val: this.state[i] ? outerRadius : outerRadius - 20 }}> { ({ val }) => <Path d={arc({ ...dataPoint, outerRadius: val })} onMouseOver={this.onMouseOver(i)} onMouseOut={this.onMouseOut(i)} /> } </Spring>) } </g> </SVG> ); } } @Radium class Path extends Component { render() { return ( <path style={{ fill: '#CCCCCC', stroke: '#333333', strokeWidth: 1.5, transition: 'fill 250ms linear', cursor: 'pointer', ':hover': { fill: '#999999', stroke: '#000000' } }} d={this.props.d} onMouseOver={this.props.onMouseOver} onMouseOut={this.props.onMouseOut} /> ); } }
}
random_line_split
PieChart.js
import SVG from './SVG'; import Radium from 'radium'; import { layout, svg } from 'd3'; import { Spring } from 'react-motion'; import { Component, PropTypes } from 'react'; export default class PieChart extends Component { static defaultProps = { data: PropTypes.array.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, outerRadius: PropTypes.number.isRequired, innerRadius: PropTypes.number.isRequired } state = { ...[...Array(this.props.data.length)].map(() => false) } onMouseOver = (i) => () => this.setState({ [i]: true }) onMouseOut = (i) => () => this.setState({ [i]: false }) render() { const { innerRadius, outerRadius, width, height } = this.props; const pie = layout.pie().padAngle(.02); const arc = svg.arc().padRadius(outerRadius).innerRadius(innerRadius); return ( <SVG width={width} height={height}> <g transform={`translate(${width / 2}, ${height / 2})`}> { pie(this.props.data).map( (dataPoint, i) => <Spring key={i} endValue={{ val: this.state[i] ? outerRadius : outerRadius - 20 }}> { ({ val }) => <Path d={arc({ ...dataPoint, outerRadius: val })} onMouseOver={this.onMouseOver(i)} onMouseOut={this.onMouseOut(i)} /> } </Spring>) } </g> </SVG> ); } } @Radium class Path extends Component { render()
}
{ return ( <path style={{ fill: '#CCCCCC', stroke: '#333333', strokeWidth: 1.5, transition: 'fill 250ms linear', cursor: 'pointer', ':hover': { fill: '#999999', stroke: '#000000' } }} d={this.props.d} onMouseOver={this.props.onMouseOver} onMouseOut={this.props.onMouseOut} /> ); }
identifier_body
PieChart.js
import SVG from './SVG'; import Radium from 'radium'; import { layout, svg } from 'd3'; import { Spring } from 'react-motion'; import { Component, PropTypes } from 'react'; export default class PieChart extends Component { static defaultProps = { data: PropTypes.array.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, outerRadius: PropTypes.number.isRequired, innerRadius: PropTypes.number.isRequired } state = { ...[...Array(this.props.data.length)].map(() => false) } onMouseOver = (i) => () => this.setState({ [i]: true }) onMouseOut = (i) => () => this.setState({ [i]: false }) render() { const { innerRadius, outerRadius, width, height } = this.props; const pie = layout.pie().padAngle(.02); const arc = svg.arc().padRadius(outerRadius).innerRadius(innerRadius); return ( <SVG width={width} height={height}> <g transform={`translate(${width / 2}, ${height / 2})`}> { pie(this.props.data).map( (dataPoint, i) => <Spring key={i} endValue={{ val: this.state[i] ? outerRadius : outerRadius - 20 }}> { ({ val }) => <Path d={arc({ ...dataPoint, outerRadius: val })} onMouseOver={this.onMouseOver(i)} onMouseOut={this.onMouseOut(i)} /> } </Spring>) } </g> </SVG> ); } } @Radium class
extends Component { render() { return ( <path style={{ fill: '#CCCCCC', stroke: '#333333', strokeWidth: 1.5, transition: 'fill 250ms linear', cursor: 'pointer', ':hover': { fill: '#999999', stroke: '#000000' } }} d={this.props.d} onMouseOver={this.props.onMouseOver} onMouseOut={this.props.onMouseOut} /> ); } }
Path
identifier_name
rustbox.rs
extern crate gag; extern crate libc; extern crate num; extern crate time; extern crate termbox_sys as termbox; #[macro_use] extern crate bitflags; pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL}; use std::error::Error; use std::fmt; use std::io; use std::char; use std::default::Default; use std::marker::PhantomData; use num::FromPrimitive; use termbox::RawEvent; use libc::c_int; use gag::Hold; use time::Duration; pub mod keyboard; pub mod mouse; pub use self::running::running; pub use keyboard::Key; pub use mouse::Mouse; #[derive(Clone, Copy, Debug)] pub enum Event { KeyEventRaw(u8, u16, u32), KeyEvent(Key), ResizeEvent(i32, i32), MouseEvent(Mouse, i32, i32), NoEvent } #[derive(Clone, Copy, Debug)] pub enum InputMode { Current = 0x00, /// When ESC sequence is in the buffer and it doesn't match any known /// ESC sequence => ESC means TB_KEY_ESC Esc = 0x01, /// When ESC sequence is in the buffer and it doesn't match any known /// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event. Alt = 0x02, /// Same as `Esc` but enables mouse events EscMouse = 0x05, /// Same as `Alt` but enables mouse events AltMouse = 0x06 } #[derive(Clone, Copy, PartialEq)] #[repr(C,u16)] pub enum Color { Default = 0x00, Black = 0x01, Red = 0x02, Green = 0x03, Yellow = 0x04, Blue = 0x05, Magenta = 0x06, Cyan = 0x07, White = 0x08, } mod style { bitflags! { #[repr(C)] flags Style: u16 { const TB_NORMAL_COLOR = 0x000F, const RB_BOLD = 0x0100, const RB_UNDERLINE = 0x0200, const RB_REVERSE = 0x0400, const RB_NORMAL = 0x0000, const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits, } } impl Style { pub fn from_color(color: super::Color) -> Style { Style { bits: color as u16 & TB_NORMAL_COLOR.bits } } } } const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 }; #[derive(Debug)] pub enum EventError { TermboxError, Unknown(isize), } impl fmt::Display for EventError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl Error for EventError { fn description(&self) -> &str { match *self { EventError::TermboxError => "Error in Termbox", // I don't know how to format this without lifetime error. // EventError::Unknown(n) => &format!("There was an unknown error. Error code: {}", n), EventError::Unknown(_) => "Unknown error in Termbox", } } } impl FromPrimitive for EventError { fn from_i64(n: i64) -> Option<EventError> { match n { -1 => Some(EventError::TermboxError), n => Some(EventError::Unknown(n as isize)), } } fn from_u64(n: u64) -> Option<EventError> { Some(EventError::Unknown(n as isize)) } } pub type EventResult = Result<Event, EventError>; /// Unpack a RawEvent to an Event /// /// if the `raw` parameter is true, then the Event variant will be the raw /// representation of the event. /// for instance KeyEventRaw instead of KeyEvent /// /// This is useful if you want to interpret the raw event data yourself, rather /// than having rustbox translate it to its own representation. fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult { match ev_type { 0 => Ok(Event::NoEvent), 1 => Ok( if raw { Event::KeyEventRaw(ev.emod, ev.key, ev.ch) } else { let k = match ev.key { 0 => char::from_u32(ev.ch).map(|c| Key::Char(c)), a => Key::from_code(a), }; if let Some(key) = k { Event::KeyEvent(key) } else { Event::KeyEvent(Key::Unknown(ev.key)) } }), 2 => Ok(Event::ResizeEvent(ev.w, ev.h)), 3 => { let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left); Ok(Event::MouseEvent(mouse, ev.x, ev.y)) }, // `unwrap` is safe here because FromPrimitive for EventError only returns `Some`. n => Err(FromPrimitive::from_isize(n as isize).unwrap()), } } #[derive(Debug)] pub enum InitError { BufferStderrFailed(io::Error), AlreadyOpen, UnsupportedTerminal, FailedToOpenTTy, PipeTrapError, Unknown(isize), } impl fmt::Display for InitError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl Error for InitError { fn description(&self) -> &str { match *self { InitError::BufferStderrFailed(_) => "Could not redirect stderr", InitError::AlreadyOpen => "RustBox is already open", InitError::UnsupportedTerminal => "Unsupported terminal", InitError::FailedToOpenTTy => "Failed to open TTY", InitError::PipeTrapError => "Pipe trap error", InitError::Unknown(_) => "Unknown error from Termbox", } } fn cause(&self) -> Option<&Error> { match *self { InitError::BufferStderrFailed(ref e) => Some(e), _ => None } } } impl FromPrimitive for InitError { fn from_i64(n: i64) -> Option<InitError> { match n { -1 => Some(InitError::UnsupportedTerminal), -2 => Some(InitError::FailedToOpenTTy), -3 => Some(InitError::PipeTrapError), n => Some(InitError::Unknown(n as isize)), } } fn from_u64(n: u64) -> Option<InitError> { Some(InitError::Unknown(n as isize)) } } #[allow(missing_copy_implementations)] pub struct RustBox { // We only bother to redirect stderr for the moment, since it's used for panic! _stderr: Option<Hold>, // RAII lock. // // Note that running *MUST* be the last field in the destructor, since destructors run in // top-down order. Otherwise it will not properly protect the above fields. _running: running::RunningGuard, // Termbox is not thread safe. See #39. _phantom: PhantomData<*mut ()>, } #[derive(Clone, Copy,Debug)] pub struct InitOptions { /// Use this option to initialize with a specific input mode /// /// See InputMode enum for details on the variants. pub input_mode: InputMode, /// Use this option to automatically buffer stderr while RustBox is running. It will be /// written when RustBox exits. /// /// This option uses a nonblocking OS pipe to buffer stderr output. This means that if the /// pipe fills up, subsequent writes will fail until RustBox exits. If this is a concern for /// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr /// to a log file or another process that is capable of handling it better. pub buffer_stderr: bool, } impl Default for InitOptions { fn default() -> Self { InitOptions { input_mode: InputMode::Current, buffer_stderr: false, } } } mod running { use std::sync::atomic::{self, AtomicBool}; // The state of the RustBox is protected by the lock. Yay, global state! static RUSTBOX_RUNNING: AtomicBool = atomic::ATOMIC_BOOL_INIT; /// true iff RustBox is currently running. Beware of races here--don't rely on this for anything /// critical unless you happen to know that RustBox cannot change state when it is called (a good /// usecase would be checking to see if it's worth risking double printing backtraces to avoid /// having them swallowed up by RustBox). pub fn running() -> bool { RUSTBOX_RUNNING.load(atomic::Ordering::SeqCst) } // Internal RAII guard used to ensure we release the running lock whenever we acquire it. #[allow(missing_copy_implementations)] pub struct RunningGuard(()); pub fn run() -> Option<RunningGuard> { // Ensure that we are not already running and simultaneously set RUSTBOX_RUNNING using an // atomic swap. This ensures that contending threads don't trample each other. if RUSTBOX_RUNNING.swap(true, atomic::Ordering::SeqCst) { // The Rustbox was already running. None } else { // The RustBox was not already running, and now we have the lock. Some(RunningGuard(())) } } impl Drop for RunningGuard { fn drop(&mut self) { // Indicate that we're free now. We could probably get away with lower atomicity here, // but there's no reason to take that chance. RUSTBOX_RUNNING.store(false, atomic::Ordering::SeqCst); } } } impl RustBox { /// Initialize rustbox. /// /// For the default options, you can use: /// /// ``` /// use rustbox::RustBox; /// use std::default::Default; /// let rb = RustBox::init(Default::default()); /// ``` /// /// Otherwise, you can specify: /// /// ``` /// use rustbox::{RustBox, InitOptions}; /// use std::default::Default; /// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc, ..Default::default() }); /// ``` pub fn init(opts: InitOptions) -> Result<RustBox, InitError> { let running = match running::run() { Some(r) => r, None => return Err(InitError::AlreadyOpen), }; let stderr = if opts.buffer_stderr { Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e)))) } else { None }; // Create the RustBox. let rb = unsafe { match termbox::tb_init() { 0 => RustBox { _stderr: stderr, _running: running, _phantom: PhantomData, }, res => { return Err(FromPrimitive::from_isize(res as isize).unwrap()) } }}; match opts.input_mode { InputMode::Current => (), _ => rb.set_input_mode(opts.input_mode), } Ok(rb) } pub fn width(&self) -> usize { unsafe { termbox::tb_width() as usize } } pub fn height(&self) -> usize { unsafe { termbox::tb_height() as usize } } pub fn clear(&self) { unsafe { termbox::tb_clear() } } pub fn present(&self)
pub fn set_cursor(&self, x: isize, y: isize) { unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) } } pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) { termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg) } pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) { let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB); let bg = Style::from_color(bg); for (i, ch) in s.chars().enumerate() { unsafe { self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits()); } } } pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) { let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB); let bg = Style::from_color(bg); unsafe { self.change_cell(x, y, ch as u32, fg.bits(), bg.bits()); } } pub fn poll_event(&self, raw: bool) -> EventResult { let mut ev = NIL_RAW_EVENT; let rc = unsafe { termbox::tb_poll_event(&mut ev) }; unpack_event(rc, &ev, raw) } pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult { let mut ev = NIL_RAW_EVENT; let rc = unsafe { termbox::tb_peek_event(&mut ev, timeout.num_milliseconds() as c_int) }; unpack_event(rc, &ev, raw) } pub fn set_input_mode(&self, mode: InputMode) { unsafe { termbox::tb_select_input_mode(mode as c_int); } } } impl Drop for RustBox { fn drop(&mut self) { // Since only one instance of the RustBox is ever accessible, we should not // need to do this atomically. // Note: we should definitely have RUSTBOX_RUNNING = true here. unsafe { termbox::tb_shutdown(); } } }
{ unsafe { termbox::tb_present() } }
identifier_body
rustbox.rs
extern crate gag; extern crate libc; extern crate num; extern crate time; extern crate termbox_sys as termbox; #[macro_use] extern crate bitflags; pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL}; use std::error::Error; use std::fmt; use std::io; use std::char; use std::default::Default; use std::marker::PhantomData; use num::FromPrimitive; use termbox::RawEvent; use libc::c_int; use gag::Hold; use time::Duration; pub mod keyboard; pub mod mouse; pub use self::running::running; pub use keyboard::Key; pub use mouse::Mouse; #[derive(Clone, Copy, Debug)] pub enum Event { KeyEventRaw(u8, u16, u32), KeyEvent(Key), ResizeEvent(i32, i32), MouseEvent(Mouse, i32, i32), NoEvent } #[derive(Clone, Copy, Debug)] pub enum InputMode { Current = 0x00, /// When ESC sequence is in the buffer and it doesn't match any known /// ESC sequence => ESC means TB_KEY_ESC Esc = 0x01, /// When ESC sequence is in the buffer and it doesn't match any known /// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event. Alt = 0x02, /// Same as `Esc` but enables mouse events EscMouse = 0x05, /// Same as `Alt` but enables mouse events AltMouse = 0x06 } #[derive(Clone, Copy, PartialEq)] #[repr(C,u16)] pub enum Color { Default = 0x00, Black = 0x01, Red = 0x02, Green = 0x03, Yellow = 0x04, Blue = 0x05, Magenta = 0x06, Cyan = 0x07, White = 0x08, } mod style { bitflags! { #[repr(C)] flags Style: u16 { const TB_NORMAL_COLOR = 0x000F, const RB_BOLD = 0x0100, const RB_UNDERLINE = 0x0200, const RB_REVERSE = 0x0400, const RB_NORMAL = 0x0000, const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits, } } impl Style { pub fn from_color(color: super::Color) -> Style { Style { bits: color as u16 & TB_NORMAL_COLOR.bits } } } } const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 }; #[derive(Debug)] pub enum EventError { TermboxError, Unknown(isize), } impl fmt::Display for EventError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl Error for EventError { fn description(&self) -> &str { match *self { EventError::TermboxError => "Error in Termbox", // I don't know how to format this without lifetime error. // EventError::Unknown(n) => &format!("There was an unknown error. Error code: {}", n), EventError::Unknown(_) => "Unknown error in Termbox", } } } impl FromPrimitive for EventError { fn from_i64(n: i64) -> Option<EventError> { match n { -1 => Some(EventError::TermboxError), n => Some(EventError::Unknown(n as isize)), } } fn from_u64(n: u64) -> Option<EventError> { Some(EventError::Unknown(n as isize)) } } pub type EventResult = Result<Event, EventError>; /// Unpack a RawEvent to an Event /// /// if the `raw` parameter is true, then the Event variant will be the raw /// representation of the event. /// for instance KeyEventRaw instead of KeyEvent /// /// This is useful if you want to interpret the raw event data yourself, rather /// than having rustbox translate it to its own representation. fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult { match ev_type { 0 => Ok(Event::NoEvent), 1 => Ok( if raw { Event::KeyEventRaw(ev.emod, ev.key, ev.ch) } else { let k = match ev.key { 0 => char::from_u32(ev.ch).map(|c| Key::Char(c)), a => Key::from_code(a), }; if let Some(key) = k { Event::KeyEvent(key) } else { Event::KeyEvent(Key::Unknown(ev.key)) } }), 2 => Ok(Event::ResizeEvent(ev.w, ev.h)), 3 => { let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left); Ok(Event::MouseEvent(mouse, ev.x, ev.y)) }, // `unwrap` is safe here because FromPrimitive for EventError only returns `Some`. n => Err(FromPrimitive::from_isize(n as isize).unwrap()), } } #[derive(Debug)] pub enum InitError { BufferStderrFailed(io::Error), AlreadyOpen, UnsupportedTerminal, FailedToOpenTTy, PipeTrapError, Unknown(isize), } impl fmt::Display for InitError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl Error for InitError { fn description(&self) -> &str { match *self { InitError::BufferStderrFailed(_) => "Could not redirect stderr", InitError::AlreadyOpen => "RustBox is already open", InitError::UnsupportedTerminal => "Unsupported terminal", InitError::FailedToOpenTTy => "Failed to open TTY", InitError::PipeTrapError => "Pipe trap error", InitError::Unknown(_) => "Unknown error from Termbox", } } fn cause(&self) -> Option<&Error> { match *self { InitError::BufferStderrFailed(ref e) => Some(e), _ => None } } } impl FromPrimitive for InitError { fn from_i64(n: i64) -> Option<InitError> { match n { -1 => Some(InitError::UnsupportedTerminal), -2 => Some(InitError::FailedToOpenTTy), -3 => Some(InitError::PipeTrapError), n => Some(InitError::Unknown(n as isize)), } } fn from_u64(n: u64) -> Option<InitError> { Some(InitError::Unknown(n as isize)) } } #[allow(missing_copy_implementations)] pub struct RustBox { // We only bother to redirect stderr for the moment, since it's used for panic! _stderr: Option<Hold>, // RAII lock. // // Note that running *MUST* be the last field in the destructor, since destructors run in // top-down order. Otherwise it will not properly protect the above fields. _running: running::RunningGuard, // Termbox is not thread safe. See #39. _phantom: PhantomData<*mut ()>, } #[derive(Clone, Copy,Debug)] pub struct InitOptions { /// Use this option to initialize with a specific input mode /// /// See InputMode enum for details on the variants. pub input_mode: InputMode, /// Use this option to automatically buffer stderr while RustBox is running. It will be /// written when RustBox exits. /// /// This option uses a nonblocking OS pipe to buffer stderr output. This means that if the /// pipe fills up, subsequent writes will fail until RustBox exits. If this is a concern for /// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr /// to a log file or another process that is capable of handling it better. pub buffer_stderr: bool, } impl Default for InitOptions { fn default() -> Self { InitOptions { input_mode: InputMode::Current, buffer_stderr: false, } } } mod running { use std::sync::atomic::{self, AtomicBool}; // The state of the RustBox is protected by the lock. Yay, global state! static RUSTBOX_RUNNING: AtomicBool = atomic::ATOMIC_BOOL_INIT; /// true iff RustBox is currently running. Beware of races here--don't rely on this for anything /// critical unless you happen to know that RustBox cannot change state when it is called (a good /// usecase would be checking to see if it's worth risking double printing backtraces to avoid /// having them swallowed up by RustBox). pub fn running() -> bool { RUSTBOX_RUNNING.load(atomic::Ordering::SeqCst) } // Internal RAII guard used to ensure we release the running lock whenever we acquire it. #[allow(missing_copy_implementations)] pub struct RunningGuard(()); pub fn run() -> Option<RunningGuard> { // Ensure that we are not already running and simultaneously set RUSTBOX_RUNNING using an // atomic swap. This ensures that contending threads don't trample each other. if RUSTBOX_RUNNING.swap(true, atomic::Ordering::SeqCst) { // The Rustbox was already running. None } else { // The RustBox was not already running, and now we have the lock. Some(RunningGuard(())) } } impl Drop for RunningGuard { fn drop(&mut self) { // Indicate that we're free now. We could probably get away with lower atomicity here, // but there's no reason to take that chance. RUSTBOX_RUNNING.store(false, atomic::Ordering::SeqCst); } } } impl RustBox { /// Initialize rustbox. /// /// For the default options, you can use: /// /// ``` /// use rustbox::RustBox; /// use std::default::Default; /// let rb = RustBox::init(Default::default()); /// ``` /// /// Otherwise, you can specify: /// /// ``` /// use rustbox::{RustBox, InitOptions}; /// use std::default::Default; /// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc, ..Default::default() }); /// ``` pub fn init(opts: InitOptions) -> Result<RustBox, InitError> { let running = match running::run() { Some(r) => r, None => return Err(InitError::AlreadyOpen), }; let stderr = if opts.buffer_stderr { Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e)))) } else { None }; // Create the RustBox. let rb = unsafe { match termbox::tb_init() { 0 => RustBox { _stderr: stderr, _running: running, _phantom: PhantomData, }, res => { return Err(FromPrimitive::from_isize(res as isize).unwrap()) } }}; match opts.input_mode { InputMode::Current => (), _ => rb.set_input_mode(opts.input_mode), } Ok(rb) } pub fn width(&self) -> usize { unsafe { termbox::tb_width() as usize } } pub fn height(&self) -> usize { unsafe { termbox::tb_height() as usize } } pub fn clear(&self) { unsafe { termbox::tb_clear() } } pub fn present(&self) { unsafe { termbox::tb_present() } } pub fn set_cursor(&self, x: isize, y: isize) { unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) } } pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) { termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg) } pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) { let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB); let bg = Style::from_color(bg); for (i, ch) in s.chars().enumerate() { unsafe { self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits()); } } } pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) { let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB); let bg = Style::from_color(bg); unsafe { self.change_cell(x, y, ch as u32, fg.bits(), bg.bits()); } } pub fn poll_event(&self, raw: bool) -> EventResult { let mut ev = NIL_RAW_EVENT; let rc = unsafe { termbox::tb_poll_event(&mut ev) }; unpack_event(rc, &ev, raw) } pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult { let mut ev = NIL_RAW_EVENT; let rc = unsafe { termbox::tb_peek_event(&mut ev, timeout.num_milliseconds() as c_int) }; unpack_event(rc, &ev, raw) } pub fn set_input_mode(&self, mode: InputMode) { unsafe { termbox::tb_select_input_mode(mode as c_int); } } } impl Drop for RustBox { fn
(&mut self) { // Since only one instance of the RustBox is ever accessible, we should not // need to do this atomically. // Note: we should definitely have RUSTBOX_RUNNING = true here. unsafe { termbox::tb_shutdown(); } } }
drop
identifier_name
rustbox.rs
extern crate gag; extern crate libc; extern crate num; extern crate time; extern crate termbox_sys as termbox; #[macro_use] extern crate bitflags; pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL}; use std::error::Error; use std::fmt; use std::io; use std::char; use std::default::Default; use std::marker::PhantomData; use num::FromPrimitive; use termbox::RawEvent; use libc::c_int; use gag::Hold; use time::Duration; pub mod keyboard; pub mod mouse; pub use self::running::running; pub use keyboard::Key; pub use mouse::Mouse; #[derive(Clone, Copy, Debug)] pub enum Event { KeyEventRaw(u8, u16, u32), KeyEvent(Key), ResizeEvent(i32, i32), MouseEvent(Mouse, i32, i32), NoEvent } #[derive(Clone, Copy, Debug)] pub enum InputMode { Current = 0x00, /// When ESC sequence is in the buffer and it doesn't match any known /// ESC sequence => ESC means TB_KEY_ESC Esc = 0x01, /// When ESC sequence is in the buffer and it doesn't match any known /// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event. Alt = 0x02, /// Same as `Esc` but enables mouse events EscMouse = 0x05, /// Same as `Alt` but enables mouse events AltMouse = 0x06 } #[derive(Clone, Copy, PartialEq)] #[repr(C,u16)] pub enum Color { Default = 0x00, Black = 0x01, Red = 0x02, Green = 0x03, Yellow = 0x04, Blue = 0x05, Magenta = 0x06, Cyan = 0x07, White = 0x08, } mod style { bitflags! { #[repr(C)] flags Style: u16 { const TB_NORMAL_COLOR = 0x000F, const RB_BOLD = 0x0100, const RB_UNDERLINE = 0x0200, const RB_REVERSE = 0x0400, const RB_NORMAL = 0x0000, const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits, } } impl Style { pub fn from_color(color: super::Color) -> Style { Style { bits: color as u16 & TB_NORMAL_COLOR.bits } } } } const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 }; #[derive(Debug)] pub enum EventError { TermboxError, Unknown(isize), } impl fmt::Display for EventError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl Error for EventError { fn description(&self) -> &str { match *self { EventError::TermboxError => "Error in Termbox", // I don't know how to format this without lifetime error. // EventError::Unknown(n) => &format!("There was an unknown error. Error code: {}", n), EventError::Unknown(_) => "Unknown error in Termbox", } } } impl FromPrimitive for EventError { fn from_i64(n: i64) -> Option<EventError> { match n { -1 => Some(EventError::TermboxError), n => Some(EventError::Unknown(n as isize)), } } fn from_u64(n: u64) -> Option<EventError> { Some(EventError::Unknown(n as isize)) } } pub type EventResult = Result<Event, EventError>; /// Unpack a RawEvent to an Event /// /// if the `raw` parameter is true, then the Event variant will be the raw /// representation of the event. /// for instance KeyEventRaw instead of KeyEvent /// /// This is useful if you want to interpret the raw event data yourself, rather /// than having rustbox translate it to its own representation. fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult { match ev_type { 0 => Ok(Event::NoEvent), 1 => Ok( if raw { Event::KeyEventRaw(ev.emod, ev.key, ev.ch) } else { let k = match ev.key { 0 => char::from_u32(ev.ch).map(|c| Key::Char(c)), a => Key::from_code(a), }; if let Some(key) = k { Event::KeyEvent(key) } else { Event::KeyEvent(Key::Unknown(ev.key)) } }), 2 => Ok(Event::ResizeEvent(ev.w, ev.h)), 3 => { let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left); Ok(Event::MouseEvent(mouse, ev.x, ev.y)) }, // `unwrap` is safe here because FromPrimitive for EventError only returns `Some`. n => Err(FromPrimitive::from_isize(n as isize).unwrap()), } } #[derive(Debug)] pub enum InitError { BufferStderrFailed(io::Error), AlreadyOpen, UnsupportedTerminal, FailedToOpenTTy, PipeTrapError, Unknown(isize), } impl fmt::Display for InitError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}", self.description()) }
impl Error for InitError { fn description(&self) -> &str { match *self { InitError::BufferStderrFailed(_) => "Could not redirect stderr", InitError::AlreadyOpen => "RustBox is already open", InitError::UnsupportedTerminal => "Unsupported terminal", InitError::FailedToOpenTTy => "Failed to open TTY", InitError::PipeTrapError => "Pipe trap error", InitError::Unknown(_) => "Unknown error from Termbox", } } fn cause(&self) -> Option<&Error> { match *self { InitError::BufferStderrFailed(ref e) => Some(e), _ => None } } } impl FromPrimitive for InitError { fn from_i64(n: i64) -> Option<InitError> { match n { -1 => Some(InitError::UnsupportedTerminal), -2 => Some(InitError::FailedToOpenTTy), -3 => Some(InitError::PipeTrapError), n => Some(InitError::Unknown(n as isize)), } } fn from_u64(n: u64) -> Option<InitError> { Some(InitError::Unknown(n as isize)) } } #[allow(missing_copy_implementations)] pub struct RustBox { // We only bother to redirect stderr for the moment, since it's used for panic! _stderr: Option<Hold>, // RAII lock. // // Note that running *MUST* be the last field in the destructor, since destructors run in // top-down order. Otherwise it will not properly protect the above fields. _running: running::RunningGuard, // Termbox is not thread safe. See #39. _phantom: PhantomData<*mut ()>, } #[derive(Clone, Copy,Debug)] pub struct InitOptions { /// Use this option to initialize with a specific input mode /// /// See InputMode enum for details on the variants. pub input_mode: InputMode, /// Use this option to automatically buffer stderr while RustBox is running. It will be /// written when RustBox exits. /// /// This option uses a nonblocking OS pipe to buffer stderr output. This means that if the /// pipe fills up, subsequent writes will fail until RustBox exits. If this is a concern for /// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr /// to a log file or another process that is capable of handling it better. pub buffer_stderr: bool, } impl Default for InitOptions { fn default() -> Self { InitOptions { input_mode: InputMode::Current, buffer_stderr: false, } } } mod running { use std::sync::atomic::{self, AtomicBool}; // The state of the RustBox is protected by the lock. Yay, global state! static RUSTBOX_RUNNING: AtomicBool = atomic::ATOMIC_BOOL_INIT; /// true iff RustBox is currently running. Beware of races here--don't rely on this for anything /// critical unless you happen to know that RustBox cannot change state when it is called (a good /// usecase would be checking to see if it's worth risking double printing backtraces to avoid /// having them swallowed up by RustBox). pub fn running() -> bool { RUSTBOX_RUNNING.load(atomic::Ordering::SeqCst) } // Internal RAII guard used to ensure we release the running lock whenever we acquire it. #[allow(missing_copy_implementations)] pub struct RunningGuard(()); pub fn run() -> Option<RunningGuard> { // Ensure that we are not already running and simultaneously set RUSTBOX_RUNNING using an // atomic swap. This ensures that contending threads don't trample each other. if RUSTBOX_RUNNING.swap(true, atomic::Ordering::SeqCst) { // The Rustbox was already running. None } else { // The RustBox was not already running, and now we have the lock. Some(RunningGuard(())) } } impl Drop for RunningGuard { fn drop(&mut self) { // Indicate that we're free now. We could probably get away with lower atomicity here, // but there's no reason to take that chance. RUSTBOX_RUNNING.store(false, atomic::Ordering::SeqCst); } } } impl RustBox { /// Initialize rustbox. /// /// For the default options, you can use: /// /// ``` /// use rustbox::RustBox; /// use std::default::Default; /// let rb = RustBox::init(Default::default()); /// ``` /// /// Otherwise, you can specify: /// /// ``` /// use rustbox::{RustBox, InitOptions}; /// use std::default::Default; /// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc, ..Default::default() }); /// ``` pub fn init(opts: InitOptions) -> Result<RustBox, InitError> { let running = match running::run() { Some(r) => r, None => return Err(InitError::AlreadyOpen), }; let stderr = if opts.buffer_stderr { Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e)))) } else { None }; // Create the RustBox. let rb = unsafe { match termbox::tb_init() { 0 => RustBox { _stderr: stderr, _running: running, _phantom: PhantomData, }, res => { return Err(FromPrimitive::from_isize(res as isize).unwrap()) } }}; match opts.input_mode { InputMode::Current => (), _ => rb.set_input_mode(opts.input_mode), } Ok(rb) } pub fn width(&self) -> usize { unsafe { termbox::tb_width() as usize } } pub fn height(&self) -> usize { unsafe { termbox::tb_height() as usize } } pub fn clear(&self) { unsafe { termbox::tb_clear() } } pub fn present(&self) { unsafe { termbox::tb_present() } } pub fn set_cursor(&self, x: isize, y: isize) { unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) } } pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) { termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg) } pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) { let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB); let bg = Style::from_color(bg); for (i, ch) in s.chars().enumerate() { unsafe { self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits()); } } } pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) { let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB); let bg = Style::from_color(bg); unsafe { self.change_cell(x, y, ch as u32, fg.bits(), bg.bits()); } } pub fn poll_event(&self, raw: bool) -> EventResult { let mut ev = NIL_RAW_EVENT; let rc = unsafe { termbox::tb_poll_event(&mut ev) }; unpack_event(rc, &ev, raw) } pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult { let mut ev = NIL_RAW_EVENT; let rc = unsafe { termbox::tb_peek_event(&mut ev, timeout.num_milliseconds() as c_int) }; unpack_event(rc, &ev, raw) } pub fn set_input_mode(&self, mode: InputMode) { unsafe { termbox::tb_select_input_mode(mode as c_int); } } } impl Drop for RustBox { fn drop(&mut self) { // Since only one instance of the RustBox is ever accessible, we should not // need to do this atomically. // Note: we should definitely have RUSTBOX_RUNNING = true here. unsafe { termbox::tb_shutdown(); } } }
}
random_line_split
ipc.ts
import { ipcMain, IpcMainInvokeEvent, WebContents, webContents } from 'electron' import { Result } from 'stencila' import { InvokeTypes } from '../../preload/types' export function valueToSuccessResult<V>( value?: V, errors?: Result['errors'] ): Result<V> export function
( value?: undefined, errors?: Result['errors'] ): Result<undefined> { return { ok: true, value, errors: errors ?? [], } } // Send the passed IPC message to all open windows of the configuration change. // Each window should register a corresponding listener and react as needed to the changes. export const sendToAllWindows = ( ...args: Parameters<WebContents['send']> ): void => { webContents.getAllWebContents().forEach((wc) => { wc.send(...args) }) } /** * A wrapper around Electron's `ipcMain.handle` function in order to enable type * type safe invocation of both the Invoke and Handle aspects. * For details see `/preload/types.d.ts` */ export function handle<F extends InvokeTypes>( channel: F['channel'], listener: (ipcEvent: IpcMainInvokeEvent, ...args: F['args']) => F['result'] ): void export function handle<F extends InvokeTypes>( channel: F['channel'], listener: (ipcEvent: IpcMainInvokeEvent, args: F['args']) => F['result'] ): void { ipcMain.handle(channel, listener) }
valueToSuccessResult
identifier_name
ipc.ts
import { ipcMain, IpcMainInvokeEvent, WebContents, webContents } from 'electron' import { Result } from 'stencila' import { InvokeTypes } from '../../preload/types' export function valueToSuccessResult<V>( value?: V, errors?: Result['errors'] ): Result<V> export function valueToSuccessResult( value?: undefined, errors?: Result['errors'] ): Result<undefined> { return { ok: true, value, errors: errors ?? [], } } // Send the passed IPC message to all open windows of the configuration change. // Each window should register a corresponding listener and react as needed to the changes. export const sendToAllWindows = ( ...args: Parameters<WebContents['send']> ): void => { webContents.getAllWebContents().forEach((wc) => { wc.send(...args) }) } /** * A wrapper around Electron's `ipcMain.handle` function in order to enable type * type safe invocation of both the Invoke and Handle aspects. * For details see `/preload/types.d.ts` */ export function handle<F extends InvokeTypes>( channel: F['channel'], listener: (ipcEvent: IpcMainInvokeEvent, ...args: F['args']) => F['result'] ): void export function handle<F extends InvokeTypes>( channel: F['channel'], listener: (ipcEvent: IpcMainInvokeEvent, args: F['args']) => F['result'] ): void
{ ipcMain.handle(channel, listener) }
identifier_body
ipc.ts
import { ipcMain, IpcMainInvokeEvent, WebContents, webContents } from 'electron' import { Result } from 'stencila' import { InvokeTypes } from '../../preload/types' export function valueToSuccessResult<V>( value?: V, errors?: Result['errors'] ): Result<V> export function valueToSuccessResult( value?: undefined, errors?: Result['errors'] ): Result<undefined> { return { ok: true, value, errors: errors ?? [], } } // Send the passed IPC message to all open windows of the configuration change. // Each window should register a corresponding listener and react as needed to the changes. export const sendToAllWindows = ( ...args: Parameters<WebContents['send']> ): void => { webContents.getAllWebContents().forEach((wc) => { wc.send(...args) }) } /** * A wrapper around Electron's `ipcMain.handle` function in order to enable type
* type safe invocation of both the Invoke and Handle aspects. * For details see `/preload/types.d.ts` */ export function handle<F extends InvokeTypes>( channel: F['channel'], listener: (ipcEvent: IpcMainInvokeEvent, ...args: F['args']) => F['result'] ): void export function handle<F extends InvokeTypes>( channel: F['channel'], listener: (ipcEvent: IpcMainInvokeEvent, args: F['args']) => F['result'] ): void { ipcMain.handle(channel, listener) }
random_line_split
pluginconf_d.py
""" pluginconf.d configuration file - Files ======================================= Shared mappers for parsing and extracting data from ``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained in this module are: PluginConfD - files ``/etc/yum/pluginconf.d/*.conf`` --------------------------------------------------- PluginConfDIni - files ``/etc/yum/pluginconf.d/*.conf`` ------------------------------------------------------- """ from insights.core import IniConfigFile, LegacyItemAccess, Parser from insights.core.plugins import parser from insights.parsers import get_active_lines from insights.specs import Specs from insights.util import deprecated @parser(Specs.pluginconf_d) class PluginConfD(LegacyItemAccess, Parser): """ .. warning:: This parser is deprecated, please use :py:class:`insights.parsers.pluginconf_d.PluginConfDIni` instead Class to parse configuration file under ``pluginconf.d`` Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 """ def
(self, content): deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.") plugin_dict = {} section_dict = {} key = None for line in get_active_lines(content): if line.startswith('['): section_dict = {} plugin_dict[line[1:-1]] = section_dict elif '=' in line: key, _, value = line.partition("=") key = key.strip() section_dict[key] = value.strip() else: if key: section_dict[key] = ','.join([section_dict[key], line]) self.data = plugin_dict def __iter__(self): for sec in self.data: yield sec @parser(Specs.pluginconf_d) class PluginConfDIni(IniConfigFile): """ Read yum plugin config files, in INI format, using the standard INI file parser class. Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 [test] test_multiline_config = http://example.com/repos/test/ http://mirror_example.com/repos/test/ Examples: >>> type(conf) <class 'insights.parsers.pluginconf_d.PluginConfDIni'> >>> conf.sections() ['main', 'test'] >>> conf.has_option('main', 'gpgcheck') True >>> conf.get("main", "enabled") '0' >>> conf.getint("main", "timeout") 120 >>> conf.getboolean("main", "enabled") False >>> conf.get("test", "test_multiline_config") 'http://example.com/repos/test/ http://mirror_example.com/repos/test/' """ pass
parse_content
identifier_name
pluginconf_d.py
""" pluginconf.d configuration file - Files ======================================= Shared mappers for parsing and extracting data from ``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained in this module are: PluginConfD - files ``/etc/yum/pluginconf.d/*.conf`` --------------------------------------------------- PluginConfDIni - files ``/etc/yum/pluginconf.d/*.conf`` ------------------------------------------------------- """ from insights.core import IniConfigFile, LegacyItemAccess, Parser from insights.core.plugins import parser from insights.parsers import get_active_lines from insights.specs import Specs from insights.util import deprecated @parser(Specs.pluginconf_d) class PluginConfD(LegacyItemAccess, Parser): """ .. warning:: This parser is deprecated, please use :py:class:`insights.parsers.pluginconf_d.PluginConfDIni` instead Class to parse configuration file under ``pluginconf.d`` Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 """ def parse_content(self, content): deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.") plugin_dict = {} section_dict = {} key = None for line in get_active_lines(content): if line.startswith('['): section_dict = {} plugin_dict[line[1:-1]] = section_dict elif '=' in line: key, _, value = line.partition("=") key = key.strip() section_dict[key] = value.strip() else:
self.data = plugin_dict def __iter__(self): for sec in self.data: yield sec @parser(Specs.pluginconf_d) class PluginConfDIni(IniConfigFile): """ Read yum plugin config files, in INI format, using the standard INI file parser class. Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 [test] test_multiline_config = http://example.com/repos/test/ http://mirror_example.com/repos/test/ Examples: >>> type(conf) <class 'insights.parsers.pluginconf_d.PluginConfDIni'> >>> conf.sections() ['main', 'test'] >>> conf.has_option('main', 'gpgcheck') True >>> conf.get("main", "enabled") '0' >>> conf.getint("main", "timeout") 120 >>> conf.getboolean("main", "enabled") False >>> conf.get("test", "test_multiline_config") 'http://example.com/repos/test/ http://mirror_example.com/repos/test/' """ pass
if key: section_dict[key] = ','.join([section_dict[key], line])
conditional_block
pluginconf_d.py
""" pluginconf.d configuration file - Files ======================================= Shared mappers for parsing and extracting data from ``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained in this module are: PluginConfD - files ``/etc/yum/pluginconf.d/*.conf`` --------------------------------------------------- PluginConfDIni - files ``/etc/yum/pluginconf.d/*.conf`` ------------------------------------------------------- """ from insights.core import IniConfigFile, LegacyItemAccess, Parser from insights.core.plugins import parser from insights.parsers import get_active_lines from insights.specs import Specs from insights.util import deprecated @parser(Specs.pluginconf_d) class PluginConfD(LegacyItemAccess, Parser): """ .. warning:: This parser is deprecated, please use :py:class:`insights.parsers.pluginconf_d.PluginConfDIni` instead Class to parse configuration file under ``pluginconf.d`` Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 """ def parse_content(self, content): deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.") plugin_dict = {} section_dict = {} key = None for line in get_active_lines(content): if line.startswith('['): section_dict = {} plugin_dict[line[1:-1]] = section_dict elif '=' in line: key, _, value = line.partition("=") key = key.strip() section_dict[key] = value.strip() else: if key: section_dict[key] = ','.join([section_dict[key], line]) self.data = plugin_dict def __iter__(self):
@parser(Specs.pluginconf_d) class PluginConfDIni(IniConfigFile): """ Read yum plugin config files, in INI format, using the standard INI file parser class. Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 [test] test_multiline_config = http://example.com/repos/test/ http://mirror_example.com/repos/test/ Examples: >>> type(conf) <class 'insights.parsers.pluginconf_d.PluginConfDIni'> >>> conf.sections() ['main', 'test'] >>> conf.has_option('main', 'gpgcheck') True >>> conf.get("main", "enabled") '0' >>> conf.getint("main", "timeout") 120 >>> conf.getboolean("main", "enabled") False >>> conf.get("test", "test_multiline_config") 'http://example.com/repos/test/ http://mirror_example.com/repos/test/' """ pass
for sec in self.data: yield sec
identifier_body
pluginconf_d.py
""" pluginconf.d configuration file - Files ======================================= Shared mappers for parsing and extracting data from ``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained in this module are: PluginConfD - files ``/etc/yum/pluginconf.d/*.conf`` --------------------------------------------------- PluginConfDIni - files ``/etc/yum/pluginconf.d/*.conf`` ------------------------------------------------------- """ from insights.core import IniConfigFile, LegacyItemAccess, Parser from insights.core.plugins import parser from insights.parsers import get_active_lines from insights.specs import Specs from insights.util import deprecated @parser(Specs.pluginconf_d) class PluginConfD(LegacyItemAccess, Parser): """ .. warning:: This parser is deprecated, please use :py:class:`insights.parsers.pluginconf_d.PluginConfDIni` instead Class to parse configuration file under ``pluginconf.d`` Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 """ def parse_content(self, content): deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.") plugin_dict = {} section_dict = {} key = None for line in get_active_lines(content): if line.startswith('['): section_dict = {} plugin_dict[line[1:-1]] = section_dict elif '=' in line: key, _, value = line.partition("=") key = key.strip() section_dict[key] = value.strip() else: if key: section_dict[key] = ','.join([section_dict[key], line]) self.data = plugin_dict def __iter__(self): for sec in self.data: yield sec @parser(Specs.pluginconf_d) class PluginConfDIni(IniConfigFile): """ Read yum plugin config files, in INI format, using the standard INI file parser class. Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 [test]
http://mirror_example.com/repos/test/ Examples: >>> type(conf) <class 'insights.parsers.pluginconf_d.PluginConfDIni'> >>> conf.sections() ['main', 'test'] >>> conf.has_option('main', 'gpgcheck') True >>> conf.get("main", "enabled") '0' >>> conf.getint("main", "timeout") 120 >>> conf.getboolean("main", "enabled") False >>> conf.get("test", "test_multiline_config") 'http://example.com/repos/test/ http://mirror_example.com/repos/test/' """ pass
test_multiline_config = http://example.com/repos/test/
random_line_split
color.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::AzFloat; use azure::azure_hl::Color as AzColor;
r: (r as AzFloat) / (255.0 as AzFloat), g: (g as AzFloat) / (255.0 as AzFloat), b: (b as AzFloat) / (255.0 as AzFloat), a: 1.0 as AzFloat } } #[inline] pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor { AzColor { r: r, g: g, b: b, a: a } }
pub type Color = AzColor; #[inline] pub fn rgb(r: u8, g: u8, b: u8) -> AzColor { AzColor {
random_line_split
color.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::AzFloat; use azure::azure_hl::Color as AzColor; pub type Color = AzColor; #[inline] pub fn rgb(r: u8, g: u8, b: u8) -> AzColor
#[inline] pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor { AzColor { r: r, g: g, b: b, a: a } }
{ AzColor { r: (r as AzFloat) / (255.0 as AzFloat), g: (g as AzFloat) / (255.0 as AzFloat), b: (b as AzFloat) / (255.0 as AzFloat), a: 1.0 as AzFloat } }
identifier_body
color.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::AzFloat; use azure::azure_hl::Color as AzColor; pub type Color = AzColor; #[inline] pub fn rgb(r: u8, g: u8, b: u8) -> AzColor { AzColor { r: (r as AzFloat) / (255.0 as AzFloat), g: (g as AzFloat) / (255.0 as AzFloat), b: (b as AzFloat) / (255.0 as AzFloat), a: 1.0 as AzFloat } } #[inline] pub fn
(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor { AzColor { r: r, g: g, b: b, a: a } }
rgba
identifier_name
extension_tests.py
"""Tests for cement.core.extension.""" from cement.core import exc, backend, extension, handler, output, interface from cement.utils import test class IBogus(interface.Interface): class IMeta: label = 'bogus' class BogusExtensionHandler(extension.CementExtensionHandler): class Meta: interface = IBogus label = 'bogus' class ExtensionTestCase(test.CementCoreTestCase): @test.raises(exc.FrameworkError) def
(self): # the handler type bogus doesn't exist handler.register(BogusExtensionHandler) def test_load_extensions(self): ext = extension.CementExtensionHandler() ext._setup(self.app) ext.load_extensions(['cement.ext.ext_configparser']) def test_load_extensions_again(self): ext = extension.CementExtensionHandler() ext._setup(self.app) ext.load_extensions(['cement.ext.ext_configparser']) ext.load_extensions(['cement.ext.ext_configparser']) @test.raises(exc.FrameworkError) def test_load_bogus_extension(self): ext = extension.CementExtensionHandler() ext._setup(self.app) ext.load_extensions(['bogus']) def test_get_loaded_extensions(self): ext = extension.CementExtensionHandler() ext._setup(self.app) res = 'cement.ext.ext_json' not in ext.get_loaded_extensions() self.ok(res) ext.load_extensions(['json']) res = 'cement.ext.ext_json' in ext.get_loaded_extensions() self.ok(res)
test_invalid_extension_handler
identifier_name
extension_tests.py
"""Tests for cement.core.extension.""" from cement.core import exc, backend, extension, handler, output, interface from cement.utils import test class IBogus(interface.Interface): class IMeta:
class BogusExtensionHandler(extension.CementExtensionHandler): class Meta: interface = IBogus label = 'bogus' class ExtensionTestCase(test.CementCoreTestCase): @test.raises(exc.FrameworkError) def test_invalid_extension_handler(self): # the handler type bogus doesn't exist handler.register(BogusExtensionHandler) def test_load_extensions(self): ext = extension.CementExtensionHandler() ext._setup(self.app) ext.load_extensions(['cement.ext.ext_configparser']) def test_load_extensions_again(self): ext = extension.CementExtensionHandler() ext._setup(self.app) ext.load_extensions(['cement.ext.ext_configparser']) ext.load_extensions(['cement.ext.ext_configparser']) @test.raises(exc.FrameworkError) def test_load_bogus_extension(self): ext = extension.CementExtensionHandler() ext._setup(self.app) ext.load_extensions(['bogus']) def test_get_loaded_extensions(self): ext = extension.CementExtensionHandler() ext._setup(self.app) res = 'cement.ext.ext_json' not in ext.get_loaded_extensions() self.ok(res) ext.load_extensions(['json']) res = 'cement.ext.ext_json' in ext.get_loaded_extensions() self.ok(res)
label = 'bogus'
identifier_body
extension_tests.py
"""Tests for cement.core.extension.""" from cement.core import exc, backend, extension, handler, output, interface from cement.utils import test class IBogus(interface.Interface): class IMeta: label = 'bogus' class BogusExtensionHandler(extension.CementExtensionHandler): class Meta: interface = IBogus label = 'bogus' class ExtensionTestCase(test.CementCoreTestCase): @test.raises(exc.FrameworkError) def test_invalid_extension_handler(self): # the handler type bogus doesn't exist handler.register(BogusExtensionHandler) def test_load_extensions(self): ext = extension.CementExtensionHandler()
ext._setup(self.app) ext.load_extensions(['cement.ext.ext_configparser']) ext.load_extensions(['cement.ext.ext_configparser']) @test.raises(exc.FrameworkError) def test_load_bogus_extension(self): ext = extension.CementExtensionHandler() ext._setup(self.app) ext.load_extensions(['bogus']) def test_get_loaded_extensions(self): ext = extension.CementExtensionHandler() ext._setup(self.app) res = 'cement.ext.ext_json' not in ext.get_loaded_extensions() self.ok(res) ext.load_extensions(['json']) res = 'cement.ext.ext_json' in ext.get_loaded_extensions() self.ok(res)
ext._setup(self.app) ext.load_extensions(['cement.ext.ext_configparser']) def test_load_extensions_again(self): ext = extension.CementExtensionHandler()
random_line_split
changeImgsParams.js
define([ ], ( ) => { function handleChange(imgSArr, callback) { let name = sessionStorage.getItem('fancy-gallery-order'); let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal'; let shuffled = parseInt(sessionStorage.getItem('fancy-gallery-shuffled'), 10) === 1; let speed = parseInt(sessionStorage.getItem('fancy-gallery-speed', 10)); let plugin = sessionStorage.getItem('fancy-gallery-plugin'); insertCss(JSON.parse(sessionStorage.getItem('fancy-gallery-configJSON')), plugin, callback); ; for (let i = 0, max = imgSArr.length; i < max; i++)
} function changeImgsParams(imgSArr, callback) { window.ee.addListener('orderChanged', () => { handleChange(imgSArr, callback); }); } return changeImgsParams; });
{ imgSArr[i].setSequence({ name: name, direction, shuffled, speed }); // imgSArr[i].setElementsX(); }
conditional_block
changeImgsParams.js
define([ ], ( ) => { function handleChange(imgSArr, callback) { let name = sessionStorage.getItem('fancy-gallery-order'); let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal'; let shuffled = parseInt(sessionStorage.getItem('fancy-gallery-shuffled'), 10) === 1; let speed = parseInt(sessionStorage.getItem('fancy-gallery-speed', 10)); let plugin = sessionStorage.getItem('fancy-gallery-plugin');
for (let i = 0, max = imgSArr.length; i < max; i++) { imgSArr[i].setSequence({ name: name, direction, shuffled, speed }); // imgSArr[i].setElementsX(); } } function changeImgsParams(imgSArr, callback) { window.ee.addListener('orderChanged', () => { handleChange(imgSArr, callback); }); } return changeImgsParams; });
insertCss(JSON.parse(sessionStorage.getItem('fancy-gallery-configJSON')), plugin, callback); ;
random_line_split
changeImgsParams.js
define([ ], ( ) => { function handleChange(imgSArr, callback) { let name = sessionStorage.getItem('fancy-gallery-order'); let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal'; let shuffled = parseInt(sessionStorage.getItem('fancy-gallery-shuffled'), 10) === 1; let speed = parseInt(sessionStorage.getItem('fancy-gallery-speed', 10)); let plugin = sessionStorage.getItem('fancy-gallery-plugin'); insertCss(JSON.parse(sessionStorage.getItem('fancy-gallery-configJSON')), plugin, callback); ; for (let i = 0, max = imgSArr.length; i < max; i++) { imgSArr[i].setSequence({ name: name, direction, shuffled, speed }); // imgSArr[i].setElementsX(); } } function changeImgsParams(imgSArr, callback)
return changeImgsParams; });
{ window.ee.addListener('orderChanged', () => { handleChange(imgSArr, callback); }); }
identifier_body
changeImgsParams.js
define([ ], ( ) => { function handleChange(imgSArr, callback) { let name = sessionStorage.getItem('fancy-gallery-order'); let direction = parseInt(sessionStorage.getItem('fancy-gallery-reversed'), 10) === 1 ? 'reverse' : 'normal'; let shuffled = parseInt(sessionStorage.getItem('fancy-gallery-shuffled'), 10) === 1; let speed = parseInt(sessionStorage.getItem('fancy-gallery-speed', 10)); let plugin = sessionStorage.getItem('fancy-gallery-plugin'); insertCss(JSON.parse(sessionStorage.getItem('fancy-gallery-configJSON')), plugin, callback); ; for (let i = 0, max = imgSArr.length; i < max; i++) { imgSArr[i].setSequence({ name: name, direction, shuffled, speed }); // imgSArr[i].setElementsX(); } } function
(imgSArr, callback) { window.ee.addListener('orderChanged', () => { handleChange(imgSArr, callback); }); } return changeImgsParams; });
changeImgsParams
identifier_name
nileServer.js
const express = require('express'); const path = require('path'); const fs = require('fs'); const bodyParser = require('body-parser') // const formidable = require('formidable'); // const createTorrent = require('create-torrent'); // const WebTorrent = require('webtorrent'); const socketController = require('./socketController');
// Pass server instance to use socket controller const socket = new socketController(server, socketLimit); // create nile.js mini-app through express Router const nileServer = express.Router(); // endpoint for receiving magnet URI from Broadcaster nileServer.post('/magnet', (req, res, next) => { socket.emitNewMagnet(req.body.magnetURI); res.sendStatus(200); }); return nileServer; }
// max # of sockets to keep open const socketLimit = 1; // takes in Node Server instance and returns Express Router module.exports = function nileServer(server) {
random_line_split
export-glob-imports-target.rs
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a glob-export functions as an import // when referenced within its own local scope. // Modified to not use export since it's going away. --pcw
use foo::bar::*; pub mod bar { pub static a : int = 10; } pub fn zum() { let _b = a; } } pub fn main() { }
mod foo {
random_line_split
export-glob-imports-target.rs
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a glob-export functions as an import // when referenced within its own local scope. // Modified to not use export since it's going away. --pcw mod foo { use foo::bar::*; pub mod bar { pub static a : int = 10; } pub fn zum() { let _b = a; } } pub fn main()
{ }
identifier_body
export-glob-imports-target.rs
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a glob-export functions as an import // when referenced within its own local scope. // Modified to not use export since it's going away. --pcw mod foo { use foo::bar::*; pub mod bar { pub static a : int = 10; } pub fn zum() { let _b = a; } } pub fn
() { }
main
identifier_name
StringData.js
/** * Data that contains a string. * @param {string} value * @param {boolean} [isValid=true] * @constructor */ function StringData(value, isValid) { Data.call(this, Data.types.string, value, isValid); } StringData.prototype = Object.create(Data.prototype); StringData.prototype.constructor = StringData; /** * If the value could represent a number, it is converted to valid NumData. Otherwise, invalid NumData(0) is returned * @return {NumData} */ StringData.prototype.asNum = function() { if (this.isNumber()) { return new NumData(parseFloat(this.getValue()), this.isValid); } else { return new NumData(0, false); } }; /** * The string is a valid boolean if it is "true" or "false" (any casing) * @return {BoolData} */ StringData.prototype.asBool = function() { if (this.getValue().toUpperCase() === "TRUE") { return new BoolData(true, this.isValid); } else if (this.getValue().toUpperCase() === "FALSE") { return new BoolData(false, this.isValid); } return new BoolData(false, false); }; /** * @return {StringData} */ StringData.prototype.asString = function() {
* @return {boolean} */ StringData.prototype.isNumber = function() { //from https://en.wikipedia.org/wiki/Regular_expression const numberRE = /^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/; return numberRE.test(this.getValue()); }; /** * Imports StringData from XML * @param {Node} dataNode * @return {StringData|null} */ StringData.importXml = function(dataNode) { const value = XmlWriter.getTextNode(dataNode, "value"); if (value == null) return null; return new StringData(value); };
return this; }; /** * Checks to see if the number can be converted to a valid number
random_line_split
StringData.js
/** * Data that contains a string. * @param {string} value * @param {boolean} [isValid=true] * @constructor */ function StringData(value, isValid)
StringData.prototype = Object.create(Data.prototype); StringData.prototype.constructor = StringData; /** * If the value could represent a number, it is converted to valid NumData. Otherwise, invalid NumData(0) is returned * @return {NumData} */ StringData.prototype.asNum = function() { if (this.isNumber()) { return new NumData(parseFloat(this.getValue()), this.isValid); } else { return new NumData(0, false); } }; /** * The string is a valid boolean if it is "true" or "false" (any casing) * @return {BoolData} */ StringData.prototype.asBool = function() { if (this.getValue().toUpperCase() === "TRUE") { return new BoolData(true, this.isValid); } else if (this.getValue().toUpperCase() === "FALSE") { return new BoolData(false, this.isValid); } return new BoolData(false, false); }; /** * @return {StringData} */ StringData.prototype.asString = function() { return this; }; /** * Checks to see if the number can be converted to a valid number * @return {boolean} */ StringData.prototype.isNumber = function() { //from https://en.wikipedia.org/wiki/Regular_expression const numberRE = /^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/; return numberRE.test(this.getValue()); }; /** * Imports StringData from XML * @param {Node} dataNode * @return {StringData|null} */ StringData.importXml = function(dataNode) { const value = XmlWriter.getTextNode(dataNode, "value"); if (value == null) return null; return new StringData(value); };
{ Data.call(this, Data.types.string, value, isValid); }
identifier_body
StringData.js
/** * Data that contains a string. * @param {string} value * @param {boolean} [isValid=true] * @constructor */ function
(value, isValid) { Data.call(this, Data.types.string, value, isValid); } StringData.prototype = Object.create(Data.prototype); StringData.prototype.constructor = StringData; /** * If the value could represent a number, it is converted to valid NumData. Otherwise, invalid NumData(0) is returned * @return {NumData} */ StringData.prototype.asNum = function() { if (this.isNumber()) { return new NumData(parseFloat(this.getValue()), this.isValid); } else { return new NumData(0, false); } }; /** * The string is a valid boolean if it is "true" or "false" (any casing) * @return {BoolData} */ StringData.prototype.asBool = function() { if (this.getValue().toUpperCase() === "TRUE") { return new BoolData(true, this.isValid); } else if (this.getValue().toUpperCase() === "FALSE") { return new BoolData(false, this.isValid); } return new BoolData(false, false); }; /** * @return {StringData} */ StringData.prototype.asString = function() { return this; }; /** * Checks to see if the number can be converted to a valid number * @return {boolean} */ StringData.prototype.isNumber = function() { //from https://en.wikipedia.org/wiki/Regular_expression const numberRE = /^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/; return numberRE.test(this.getValue()); }; /** * Imports StringData from XML * @param {Node} dataNode * @return {StringData|null} */ StringData.importXml = function(dataNode) { const value = XmlWriter.getTextNode(dataNode, "value"); if (value == null) return null; return new StringData(value); };
StringData
identifier_name
mod.rs
use std::ops::{Deref, DerefMut}; use std::io::Read; use rocket::outcome::Outcome; use rocket::request::Request; use rocket::data::{self, Data, FromData}; use rocket::response::{self, Responder, content}; use rocket::http::Status; use serde::{Serialize, Deserialize}; use serde_json; pub use serde_json::Value; pub use serde_json::error::Error as SerdeError; /// The JSON type: implements `FromData` and `Responder`, allowing you to easily /// consume and respond with JSON. /// /// If you're receiving JSON data, simple add a `data` parameter to your route /// arguments and ensure the type o the parameter is a `JSON<T>`, where `T` is /// some type you'd like to parse from JSON. `T` must implement `Deserialize` /// from [Serde](https://github.com/serde-rs/json). The data is parsed from the /// HTTP request body. /// /// ```rust,ignore /// #[post("/users/", format = "application/json", data = "<user>")] /// fn new_user(user: JSON<User>) { /// ... /// } /// ``` /// You don't _need_ to use `format = "application/json"`, but it _may_ be what /// you want. Using `format = application/json` means that any request that /// doesn't specify "application/json" as its first `Content-Type:` header /// parameter will not be routed to this handler. /// /// If you're responding with JSON data, return a `JSON<T>` type, where `T` /// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The /// content type of the response is set to `application/json` automatically. /// /// ```rust,ignore /// #[get("/users/<id>")] /// fn user(id: usize) -> JSON<User> { /// let user_from_id = User::from(id); /// ... /// JSON(user_from_id) /// } /// ``` /// #[derive(Debug)] pub struct JSON<T>(pub T); impl<T> JSON<T> { /// Consumes the JSON wrapper and returns the wrapped item. /// /// # Example
/// # use rocket_contrib::JSON; /// let string = "Hello".to_string(); /// let my_json = JSON(string); /// assert_eq!(my_json.into_inner(), "Hello".to_string()); /// ``` pub fn into_inner(self) -> T { self.0 } } /// Maximum size of JSON is 1MB. /// TODO: Determine this size from some configuration parameter. const MAX_SIZE: u64 = 1048576; impl<T: Deserialize> FromData for JSON<T> { type Error = SerdeError; fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> { if !request.content_type().map_or(false, |ct| ct.is_json()) { error_!("Content-Type is not JSON."); return Outcome::Forward(data); } let reader = data.open().take(MAX_SIZE); match serde_json::from_reader(reader).map(|val| JSON(val)) { Ok(value) => Outcome::Success(value), Err(e) => { error_!("Couldn't parse JSON body: {:?}", e); Outcome::Failure((Status::BadRequest, e)) } } } } // Serializes the wrapped value into JSON. Returns a response with Content-Type // JSON and a fixed-size body with the serialization. If serialization fails, an // `Err` of `Status::InternalServerError` is returned. impl<T: Serialize> Responder<'static> for JSON<T> { fn respond(self) -> response::Result<'static> { serde_json::to_string(&self.0).map(|string| { content::JSON(string).respond().unwrap() }).map_err(|e| { error_!("JSON failed to serialize: {:?}", e); Status::InternalServerError }) } } impl<T> Deref for JSON<T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { &self.0 } } impl<T> DerefMut for JSON<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { &mut self.0 } } /// A macro to create ad-hoc JSON serializable values using JSON syntax. /// /// # Usage /// /// To import the macro, add the `#[macro_use]` attribute to the `extern crate /// rocket_contrib` invocation: /// /// ```rust,ignore /// #[macro_use] extern crate rocket_contrib; /// ``` /// /// The return type of a macro invocation is /// [Value](/rocket_contrib/enum.Value.html). A value created with this macro /// can be returned from a handler as follows: /// /// ```rust,ignore /// use rocket_contrib::{JSON, Value}; /// /// #[get("/json")] /// fn get_json() -> JSON<Value> { /// JSON(json!({ /// "key": "value", /// "array": [1, 2, 3, 4] /// })) /// } /// ``` /// /// # Examples /// /// Create a simple JSON object with two keys: `"username"` and `"id"`: /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!({ /// "username": "mjordan", /// "id": 23 /// }); /// # } /// ``` /// /// Create a more complex object with a nested object and array: /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!({ /// "code": 200, /// "success": true, /// "payload": { /// "features": ["serde", "json"], /// "ids": [12, 121], /// }, /// }); /// # } /// ``` /// /// Variables or expressions can be interpolated into the JSON literal. Any type /// interpolated into an array element or object value must implement Serde's /// `Serialize` trait, while any type interpolated into a object key must /// implement `Into<String>`. /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let code = 200; /// let features = vec!["serde", "json"]; /// /// let value = json!({ /// "code": code, /// "success": code == 200, /// "payload": { /// features[0]: features[1] /// } /// }); /// # } /// ``` /// /// Trailing commas are allowed inside both arrays and objects. /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!([ /// "notice", /// "the", /// "trailing", /// "comma -->", /// ]); /// # } /// ``` #[macro_export] macro_rules! json { ($($json:tt)+) => { json_internal!($($json)+) }; }
/// ```rust
random_line_split
mod.rs
use std::ops::{Deref, DerefMut}; use std::io::Read; use rocket::outcome::Outcome; use rocket::request::Request; use rocket::data::{self, Data, FromData}; use rocket::response::{self, Responder, content}; use rocket::http::Status; use serde::{Serialize, Deserialize}; use serde_json; pub use serde_json::Value; pub use serde_json::error::Error as SerdeError; /// The JSON type: implements `FromData` and `Responder`, allowing you to easily /// consume and respond with JSON. /// /// If you're receiving JSON data, simple add a `data` parameter to your route /// arguments and ensure the type o the parameter is a `JSON<T>`, where `T` is /// some type you'd like to parse from JSON. `T` must implement `Deserialize` /// from [Serde](https://github.com/serde-rs/json). The data is parsed from the /// HTTP request body. /// /// ```rust,ignore /// #[post("/users/", format = "application/json", data = "<user>")] /// fn new_user(user: JSON<User>) { /// ... /// } /// ``` /// You don't _need_ to use `format = "application/json"`, but it _may_ be what /// you want. Using `format = application/json` means that any request that /// doesn't specify "application/json" as its first `Content-Type:` header /// parameter will not be routed to this handler. /// /// If you're responding with JSON data, return a `JSON<T>` type, where `T` /// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The /// content type of the response is set to `application/json` automatically. /// /// ```rust,ignore /// #[get("/users/<id>")] /// fn user(id: usize) -> JSON<User> { /// let user_from_id = User::from(id); /// ... /// JSON(user_from_id) /// } /// ``` /// #[derive(Debug)] pub struct JSON<T>(pub T); impl<T> JSON<T> { /// Consumes the JSON wrapper and returns the wrapped item. /// /// # Example /// ```rust /// # use rocket_contrib::JSON; /// let string = "Hello".to_string(); /// let my_json = JSON(string); /// assert_eq!(my_json.into_inner(), "Hello".to_string()); /// ``` pub fn into_inner(self) -> T
} /// Maximum size of JSON is 1MB. /// TODO: Determine this size from some configuration parameter. const MAX_SIZE: u64 = 1048576; impl<T: Deserialize> FromData for JSON<T> { type Error = SerdeError; fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> { if !request.content_type().map_or(false, |ct| ct.is_json()) { error_!("Content-Type is not JSON."); return Outcome::Forward(data); } let reader = data.open().take(MAX_SIZE); match serde_json::from_reader(reader).map(|val| JSON(val)) { Ok(value) => Outcome::Success(value), Err(e) => { error_!("Couldn't parse JSON body: {:?}", e); Outcome::Failure((Status::BadRequest, e)) } } } } // Serializes the wrapped value into JSON. Returns a response with Content-Type // JSON and a fixed-size body with the serialization. If serialization fails, an // `Err` of `Status::InternalServerError` is returned. impl<T: Serialize> Responder<'static> for JSON<T> { fn respond(self) -> response::Result<'static> { serde_json::to_string(&self.0).map(|string| { content::JSON(string).respond().unwrap() }).map_err(|e| { error_!("JSON failed to serialize: {:?}", e); Status::InternalServerError }) } } impl<T> Deref for JSON<T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { &self.0 } } impl<T> DerefMut for JSON<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { &mut self.0 } } /// A macro to create ad-hoc JSON serializable values using JSON syntax. /// /// # Usage /// /// To import the macro, add the `#[macro_use]` attribute to the `extern crate /// rocket_contrib` invocation: /// /// ```rust,ignore /// #[macro_use] extern crate rocket_contrib; /// ``` /// /// The return type of a macro invocation is /// [Value](/rocket_contrib/enum.Value.html). A value created with this macro /// can be returned from a handler as follows: /// /// ```rust,ignore /// use rocket_contrib::{JSON, Value}; /// /// #[get("/json")] /// fn get_json() -> JSON<Value> { /// JSON(json!({ /// "key": "value", /// "array": [1, 2, 3, 4] /// })) /// } /// ``` /// /// # Examples /// /// Create a simple JSON object with two keys: `"username"` and `"id"`: /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!({ /// "username": "mjordan", /// "id": 23 /// }); /// # } /// ``` /// /// Create a more complex object with a nested object and array: /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!({ /// "code": 200, /// "success": true, /// "payload": { /// "features": ["serde", "json"], /// "ids": [12, 121], /// }, /// }); /// # } /// ``` /// /// Variables or expressions can be interpolated into the JSON literal. Any type /// interpolated into an array element or object value must implement Serde's /// `Serialize` trait, while any type interpolated into a object key must /// implement `Into<String>`. /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let code = 200; /// let features = vec!["serde", "json"]; /// /// let value = json!({ /// "code": code, /// "success": code == 200, /// "payload": { /// features[0]: features[1] /// } /// }); /// # } /// ``` /// /// Trailing commas are allowed inside both arrays and objects. /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!([ /// "notice", /// "the", /// "trailing", /// "comma -->", /// ]); /// # } /// ``` #[macro_export] macro_rules! json { ($($json:tt)+) => { json_internal!($($json)+) }; }
{ self.0 }
identifier_body
mod.rs
use std::ops::{Deref, DerefMut}; use std::io::Read; use rocket::outcome::Outcome; use rocket::request::Request; use rocket::data::{self, Data, FromData}; use rocket::response::{self, Responder, content}; use rocket::http::Status; use serde::{Serialize, Deserialize}; use serde_json; pub use serde_json::Value; pub use serde_json::error::Error as SerdeError; /// The JSON type: implements `FromData` and `Responder`, allowing you to easily /// consume and respond with JSON. /// /// If you're receiving JSON data, simple add a `data` parameter to your route /// arguments and ensure the type o the parameter is a `JSON<T>`, where `T` is /// some type you'd like to parse from JSON. `T` must implement `Deserialize` /// from [Serde](https://github.com/serde-rs/json). The data is parsed from the /// HTTP request body. /// /// ```rust,ignore /// #[post("/users/", format = "application/json", data = "<user>")] /// fn new_user(user: JSON<User>) { /// ... /// } /// ``` /// You don't _need_ to use `format = "application/json"`, but it _may_ be what /// you want. Using `format = application/json` means that any request that /// doesn't specify "application/json" as its first `Content-Type:` header /// parameter will not be routed to this handler. /// /// If you're responding with JSON data, return a `JSON<T>` type, where `T` /// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The /// content type of the response is set to `application/json` automatically. /// /// ```rust,ignore /// #[get("/users/<id>")] /// fn user(id: usize) -> JSON<User> { /// let user_from_id = User::from(id); /// ... /// JSON(user_from_id) /// } /// ``` /// #[derive(Debug)] pub struct JSON<T>(pub T); impl<T> JSON<T> { /// Consumes the JSON wrapper and returns the wrapped item. /// /// # Example /// ```rust /// # use rocket_contrib::JSON; /// let string = "Hello".to_string(); /// let my_json = JSON(string); /// assert_eq!(my_json.into_inner(), "Hello".to_string()); /// ``` pub fn
(self) -> T { self.0 } } /// Maximum size of JSON is 1MB. /// TODO: Determine this size from some configuration parameter. const MAX_SIZE: u64 = 1048576; impl<T: Deserialize> FromData for JSON<T> { type Error = SerdeError; fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> { if !request.content_type().map_or(false, |ct| ct.is_json()) { error_!("Content-Type is not JSON."); return Outcome::Forward(data); } let reader = data.open().take(MAX_SIZE); match serde_json::from_reader(reader).map(|val| JSON(val)) { Ok(value) => Outcome::Success(value), Err(e) => { error_!("Couldn't parse JSON body: {:?}", e); Outcome::Failure((Status::BadRequest, e)) } } } } // Serializes the wrapped value into JSON. Returns a response with Content-Type // JSON and a fixed-size body with the serialization. If serialization fails, an // `Err` of `Status::InternalServerError` is returned. impl<T: Serialize> Responder<'static> for JSON<T> { fn respond(self) -> response::Result<'static> { serde_json::to_string(&self.0).map(|string| { content::JSON(string).respond().unwrap() }).map_err(|e| { error_!("JSON failed to serialize: {:?}", e); Status::InternalServerError }) } } impl<T> Deref for JSON<T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { &self.0 } } impl<T> DerefMut for JSON<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { &mut self.0 } } /// A macro to create ad-hoc JSON serializable values using JSON syntax. /// /// # Usage /// /// To import the macro, add the `#[macro_use]` attribute to the `extern crate /// rocket_contrib` invocation: /// /// ```rust,ignore /// #[macro_use] extern crate rocket_contrib; /// ``` /// /// The return type of a macro invocation is /// [Value](/rocket_contrib/enum.Value.html). A value created with this macro /// can be returned from a handler as follows: /// /// ```rust,ignore /// use rocket_contrib::{JSON, Value}; /// /// #[get("/json")] /// fn get_json() -> JSON<Value> { /// JSON(json!({ /// "key": "value", /// "array": [1, 2, 3, 4] /// })) /// } /// ``` /// /// # Examples /// /// Create a simple JSON object with two keys: `"username"` and `"id"`: /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!({ /// "username": "mjordan", /// "id": 23 /// }); /// # } /// ``` /// /// Create a more complex object with a nested object and array: /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!({ /// "code": 200, /// "success": true, /// "payload": { /// "features": ["serde", "json"], /// "ids": [12, 121], /// }, /// }); /// # } /// ``` /// /// Variables or expressions can be interpolated into the JSON literal. Any type /// interpolated into an array element or object value must implement Serde's /// `Serialize` trait, while any type interpolated into a object key must /// implement `Into<String>`. /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let code = 200; /// let features = vec!["serde", "json"]; /// /// let value = json!({ /// "code": code, /// "success": code == 200, /// "payload": { /// features[0]: features[1] /// } /// }); /// # } /// ``` /// /// Trailing commas are allowed inside both arrays and objects. /// /// ```rust /// # #![allow(unused_variables)] /// # #[macro_use] extern crate rocket_contrib; /// # fn main() { /// let value = json!([ /// "notice", /// "the", /// "trailing", /// "comma -->", /// ]); /// # } /// ``` #[macro_export] macro_rules! json { ($($json:tt)+) => { json_internal!($($json)+) }; }
into_inner
identifier_name
archive_ro.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around LLVM's archive (.a) code use libc; use ArchiveRef; use std::ffi::CString; use std::slice; use std::path::Path; pub struct ArchiveRO { ptr: ArchiveRef, } impl ArchiveRO { /// Opens a static archive for read-only purposes. This is more optimized /// than the `open` method because it uses LLVM's internal `Archive` class /// rather than shelling out to `ar` for everything. /// /// If this archive is used with a mutable method, then an error will be /// raised. pub fn open(dst: &Path) -> Option<ArchiveRO> { return unsafe { let s = path2cstr(dst); let ar = ::LLVMRustOpenArchive(s.as_ptr()); if ar.is_null() { None } else { Some(ArchiveRO { ptr: ar }) } }; #[cfg(unix)] fn path2cstr(p: &Path) -> CString { use std::os::unix::prelude::*; use std::ffi::OsStr; let p: &OsStr = p.as_ref(); CString::new(p.as_bytes()).unwrap() } #[cfg(windows)] fn path2cstr(p: &Path) -> CString { CString::new(p.to_str().unwrap()).unwrap() } } /// Reads a file in the archive pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> { unsafe { let mut size = 0 as libc::size_t; let file = CString::new(file).unwrap(); let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(), &mut size); if ptr.is_null()
else { Some(slice::from_raw_parts(ptr as *const u8, size as usize)) } } } } impl Drop for ArchiveRO { fn drop(&mut self) { unsafe { ::LLVMRustDestroyArchive(self.ptr); } } }
{ None }
conditional_block
archive_ro.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around LLVM's archive (.a) code use libc; use ArchiveRef; use std::ffi::CString; use std::slice; use std::path::Path; pub struct ArchiveRO { ptr: ArchiveRef, } impl ArchiveRO { /// Opens a static archive for read-only purposes. This is more optimized /// than the `open` method because it uses LLVM's internal `Archive` class /// rather than shelling out to `ar` for everything. /// /// If this archive is used with a mutable method, then an error will be /// raised. pub fn open(dst: &Path) -> Option<ArchiveRO> { return unsafe { let s = path2cstr(dst); let ar = ::LLVMRustOpenArchive(s.as_ptr()); if ar.is_null() { None } else { Some(ArchiveRO { ptr: ar }) } }; #[cfg(unix)] fn path2cstr(p: &Path) -> CString { use std::os::unix::prelude::*; use std::ffi::OsStr; let p: &OsStr = p.as_ref(); CString::new(p.as_bytes()).unwrap() }
} /// Reads a file in the archive pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> { unsafe { let mut size = 0 as libc::size_t; let file = CString::new(file).unwrap(); let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(), &mut size); if ptr.is_null() { None } else { Some(slice::from_raw_parts(ptr as *const u8, size as usize)) } } } } impl Drop for ArchiveRO { fn drop(&mut self) { unsafe { ::LLVMRustDestroyArchive(self.ptr); } } }
#[cfg(windows)] fn path2cstr(p: &Path) -> CString { CString::new(p.to_str().unwrap()).unwrap() }
random_line_split
archive_ro.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around LLVM's archive (.a) code use libc; use ArchiveRef; use std::ffi::CString; use std::slice; use std::path::Path; pub struct ArchiveRO { ptr: ArchiveRef, } impl ArchiveRO { /// Opens a static archive for read-only purposes. This is more optimized /// than the `open` method because it uses LLVM's internal `Archive` class /// rather than shelling out to `ar` for everything. /// /// If this archive is used with a mutable method, then an error will be /// raised. pub fn open(dst: &Path) -> Option<ArchiveRO> { return unsafe { let s = path2cstr(dst); let ar = ::LLVMRustOpenArchive(s.as_ptr()); if ar.is_null() { None } else { Some(ArchiveRO { ptr: ar }) } }; #[cfg(unix)] fn path2cstr(p: &Path) -> CString { use std::os::unix::prelude::*; use std::ffi::OsStr; let p: &OsStr = p.as_ref(); CString::new(p.as_bytes()).unwrap() } #[cfg(windows)] fn
(p: &Path) -> CString { CString::new(p.to_str().unwrap()).unwrap() } } /// Reads a file in the archive pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> { unsafe { let mut size = 0 as libc::size_t; let file = CString::new(file).unwrap(); let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(), &mut size); if ptr.is_null() { None } else { Some(slice::from_raw_parts(ptr as *const u8, size as usize)) } } } } impl Drop for ArchiveRO { fn drop(&mut self) { unsafe { ::LLVMRustDestroyArchive(self.ptr); } } }
path2cstr
identifier_name
archive_ro.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around LLVM's archive (.a) code use libc; use ArchiveRef; use std::ffi::CString; use std::slice; use std::path::Path; pub struct ArchiveRO { ptr: ArchiveRef, } impl ArchiveRO { /// Opens a static archive for read-only purposes. This is more optimized /// than the `open` method because it uses LLVM's internal `Archive` class /// rather than shelling out to `ar` for everything. /// /// If this archive is used with a mutable method, then an error will be /// raised. pub fn open(dst: &Path) -> Option<ArchiveRO> { return unsafe { let s = path2cstr(dst); let ar = ::LLVMRustOpenArchive(s.as_ptr()); if ar.is_null() { None } else { Some(ArchiveRO { ptr: ar }) } }; #[cfg(unix)] fn path2cstr(p: &Path) -> CString { use std::os::unix::prelude::*; use std::ffi::OsStr; let p: &OsStr = p.as_ref(); CString::new(p.as_bytes()).unwrap() } #[cfg(windows)] fn path2cstr(p: &Path) -> CString
} /// Reads a file in the archive pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> { unsafe { let mut size = 0 as libc::size_t; let file = CString::new(file).unwrap(); let ptr = ::LLVMRustArchiveReadSection(self.ptr, file.as_ptr(), &mut size); if ptr.is_null() { None } else { Some(slice::from_raw_parts(ptr as *const u8, size as usize)) } } } } impl Drop for ArchiveRO { fn drop(&mut self) { unsafe { ::LLVMRustDestroyArchive(self.ptr); } } }
{ CString::new(p.to_str().unwrap()).unwrap() }
identifier_body
sup.server.protocol.ts
import { Upload } from './../models/upload/upload.model'; import { SUPController } from './sup.server.controller'; const yellow = '\x1b[33m%s\x1b[0m: '; export class SUP { constructor(private io: SocketIOClient.Manager) { } registerIO() { this.io.on('connection', (socket: SocketIOClient.Socket) => { console.log(yellow, 'Socket connected!'); socket.on('NextChunk', (data) => { console.log(yellow, 'Receiving data.'); SUPController.nextChunk(data, socket); }); socket.on('NextFile', (data) => { console.log(yellow, 'Receiving next File.'); SUPController.nextFile(data, socket); }); }); } static handshake(data, cb): void { SUPController.handshake(data, cb); } static
(data, cb): void { SUPController.pause(data, cb); } static continue(data, cb): void { SUPController.continue(data, cb); } static abort(data, cb): void { SUPController.abort(data, cb); } }
pause
identifier_name
sup.server.protocol.ts
import { Upload } from './../models/upload/upload.model'; import { SUPController } from './sup.server.controller'; const yellow = '\x1b[33m%s\x1b[0m: '; export class SUP { constructor(private io: SocketIOClient.Manager) { } registerIO() { this.io.on('connection', (socket: SocketIOClient.Socket) => { console.log(yellow, 'Socket connected!');
console.log(yellow, 'Receiving next File.'); SUPController.nextFile(data, socket); }); }); } static handshake(data, cb): void { SUPController.handshake(data, cb); } static pause(data, cb): void { SUPController.pause(data, cb); } static continue(data, cb): void { SUPController.continue(data, cb); } static abort(data, cb): void { SUPController.abort(data, cb); } }
socket.on('NextChunk', (data) => { console.log(yellow, 'Receiving data.'); SUPController.nextChunk(data, socket); }); socket.on('NextFile', (data) => {
random_line_split
sup.server.protocol.ts
import { Upload } from './../models/upload/upload.model'; import { SUPController } from './sup.server.controller'; const yellow = '\x1b[33m%s\x1b[0m: '; export class SUP { constructor(private io: SocketIOClient.Manager) { } registerIO() { this.io.on('connection', (socket: SocketIOClient.Socket) => { console.log(yellow, 'Socket connected!'); socket.on('NextChunk', (data) => { console.log(yellow, 'Receiving data.'); SUPController.nextChunk(data, socket); }); socket.on('NextFile', (data) => { console.log(yellow, 'Receiving next File.'); SUPController.nextFile(data, socket); }); }); } static handshake(data, cb): void
static pause(data, cb): void { SUPController.pause(data, cb); } static continue(data, cb): void { SUPController.continue(data, cb); } static abort(data, cb): void { SUPController.abort(data, cb); } }
{ SUPController.handshake(data, cb); }
identifier_body
anchorGenerator.py
# anchorGenerator from models.anchor import * # main function if __name__=='__main__': # TEMP: Wipe existing anchors # anchors = Anchor.all(size=1000) # Anchor.delete_all(anchors) # THIS IS TEMPORARY:
anchors = {'Vaccination', 'Vaccinations', 'Vaccine', 'Vaccines', 'Inoculation', 'Immunization', 'Shot', 'Chickenpox', 'Disease', 'Diseases', 'Hepatitis A', 'Hepatitis B', 'infection', 'infections', 'measles', 'outbreak', 'mumps', 'rabies', 'tetanus', 'virus', 'autism'} seed = 'vaccination' for anchor in anchors: a = Anchor.getOrCreate(anchor) a.findInstances() a.save() """ query = { "size": 0, "query": { "filtered": { "query": { "query_string": { "query": "*", "analyze_wildcard": True } } } }, "aggs": { "2": { "terms": { "field": "title", "size": 100, "order": { "_count": "desc" } } } } } response = es.search(index="crowdynews"', 'body=query) retrieved = now() anchors = {} # go through each retrieved document for hit in response['aggregations']['2']['buckets']: key = hit['key'] if validKey(key): anchors[key] = hit['doc_count'] addBulk(anchors) """
conditional_block
anchorGenerator.py
# anchorGenerator from models.anchor import * # main function if __name__=='__main__': # TEMP: Wipe existing anchors # anchors = Anchor.all(size=1000) # Anchor.delete_all(anchors) # THIS IS TEMPORARY: anchors = {'Vaccination', 'Vaccinations', 'Vaccine', 'Vaccines', 'Inoculation', 'Immunization', 'Shot', 'Chickenpox', 'Disease', 'Diseases', 'Hepatitis A', 'Hepatitis B', 'infection', 'infections', 'measles', 'outbreak', 'mumps', 'rabies', 'tetanus', 'virus', 'autism'} seed = 'vaccination' for anchor in anchors: a = Anchor.getOrCreate(anchor) a.findInstances() a.save() """ query = { "size": 0, "query": { "filtered": { "query": { "query_string": { "query": "*", "analyze_wildcard": True } } }
"aggs": { "2": { "terms": { "field": "title", "size": 100, "order": { "_count": "desc" } } } } } response = es.search(index="crowdynews"', 'body=query) retrieved = now() anchors = {} # go through each retrieved document for hit in response['aggregations']['2']['buckets']: key = hit['key'] if validKey(key): anchors[key] = hit['doc_count'] addBulk(anchors) """
},
random_line_split
postmessage.js
// @license // Redistribution and use in source and binary forms ... // Class for sending and receiving postMessages. // Based off the library by Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com) // // Dependencies: // * None // // Copyright 2014 Carnegie Mellon University. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ''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 CARNEGIE MELLON UNIVERSITY 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. // // The views and conclusions contained in the software and documentation are those of the // authors and should not be interpreted as representing official policies, either expressed // or implied, of Carnegie Mellon University. // // Authors: // Paul Dille (pdille@andrew.cmu.edu) // "use strict"; (function(window) { // Send postMessages. window.pm = function(options) { pm.send(options); }; // Bind a handler to a postMessage response. window.pm.bind = function(type, fn) { pm.bind(type, fn); }; // Unbind postMessage handlers window.pm.unbind = function(type, fn) { pm.unbind(type, fn); }; var pm = { // The origin domain. _origin: null, // Internal storage (keep track of listeners, etc). data: function(key, value) { if (value === undefined) { return pm._data[key]; } pm._data[key] = value; return value; }, _data: {}, // Send postMessages. send: function(options) { if (!options) { console.warn("Need to specify at least 3 options (origin, target, type)."); return; } if (options.origin) { if (!pm._origin) { pm._origin = options.origin; } } else { console.warn("postMessage origin must be specified."); return; } var target = options.target; if (!target) { console.warn("postMessage target window required."); return; } if (!options.type) { console.warn("postMessage message type required."); return; } var msg = {data: options.data, type: options.type}; if ("postMessage" in target) { // Send the postMessage. try { target.postMessage(JSON.stringify(msg), options.origin); } catch (ex) { console.warn("postMessage failed with " + ex.name + ":", ex.message); } } else { console.warn("postMessage not supported"); } }, // Listen to incoming postMessages. bind: function(type, fn) { if (!pm.data("listening.postMessage")) { if (window.addEventListener) { window.addEventListener("message", pm._dispatch, false); } // Make sure we create only one receiving postMessage listener. pm.data("listening.postMessage", true); } // Keep track of listeners and their handlers. var listeners = pm.data("listeners.postMessage"); if (!listeners) { listeners = {}; pm.data("listeners.postMessage", listeners); } var fns = listeners[type]; if (!fns) { fns = []; listeners[type] = fns; } fns.push({fn: fn, origin: pm._origin}); }, // Unbind postMessage listeners. unbind: function(type, fn) { var listeners = pm.data("listeners.postMessage"); if (listeners) { if (type) { if (fn) { // Remove specific listener var fns = listeners[type]; if (fns) { var newListeners = []; for (var i = 0, len = fns.length; i < len; i++) { var obj = fns[i]; if (obj.fn !== fn)
} listeners[type] = newListeners; } } else { // Remove all listeners by type delete listeners[type]; } } else { // Unbind all listeners of all types for (var i in listeners) { delete listeners[i]; } } } }, // Run the handler, if one exists, based on the type defined in the postMessage. _dispatch: function(e) { var msg = {}; try { msg = JSON.parse(e.data); } catch (ex) { console.warn("postMessage data parsing failed: ", ex); return; } if (!msg.type) { console.warn("postMessage message type required."); return; } var listeners = pm.data("listeners.postMessage") || {}; var fns = listeners[msg.type] || []; for (var i = 0, len = fns.length; i < len; i++) { var obj = fns[i]; if (obj.origin && obj.origin !== '*' && e.origin !== obj.origin) { console.warn("postMessage message origin mismatch: ", e.origin, obj.origin); continue; } // Run handler try { obj.fn(msg.data); } catch (ex) { throw ex; } } } }; })(this);
{ newListeners.push(obj); }
conditional_block
postmessage.js
// @license // Redistribution and use in source and binary forms ... // Class for sending and receiving postMessages. // Based off the library by Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com) // // Dependencies: // * None // // Copyright 2014 Carnegie Mellon University. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ''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 CARNEGIE MELLON UNIVERSITY 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. // // The views and conclusions contained in the software and documentation are those of the // authors and should not be interpreted as representing official policies, either expressed // or implied, of Carnegie Mellon University. // // Authors: // Paul Dille (pdille@andrew.cmu.edu) //
"use strict"; (function(window) { // Send postMessages. window.pm = function(options) { pm.send(options); }; // Bind a handler to a postMessage response. window.pm.bind = function(type, fn) { pm.bind(type, fn); }; // Unbind postMessage handlers window.pm.unbind = function(type, fn) { pm.unbind(type, fn); }; var pm = { // The origin domain. _origin: null, // Internal storage (keep track of listeners, etc). data: function(key, value) { if (value === undefined) { return pm._data[key]; } pm._data[key] = value; return value; }, _data: {}, // Send postMessages. send: function(options) { if (!options) { console.warn("Need to specify at least 3 options (origin, target, type)."); return; } if (options.origin) { if (!pm._origin) { pm._origin = options.origin; } } else { console.warn("postMessage origin must be specified."); return; } var target = options.target; if (!target) { console.warn("postMessage target window required."); return; } if (!options.type) { console.warn("postMessage message type required."); return; } var msg = {data: options.data, type: options.type}; if ("postMessage" in target) { // Send the postMessage. try { target.postMessage(JSON.stringify(msg), options.origin); } catch (ex) { console.warn("postMessage failed with " + ex.name + ":", ex.message); } } else { console.warn("postMessage not supported"); } }, // Listen to incoming postMessages. bind: function(type, fn) { if (!pm.data("listening.postMessage")) { if (window.addEventListener) { window.addEventListener("message", pm._dispatch, false); } // Make sure we create only one receiving postMessage listener. pm.data("listening.postMessage", true); } // Keep track of listeners and their handlers. var listeners = pm.data("listeners.postMessage"); if (!listeners) { listeners = {}; pm.data("listeners.postMessage", listeners); } var fns = listeners[type]; if (!fns) { fns = []; listeners[type] = fns; } fns.push({fn: fn, origin: pm._origin}); }, // Unbind postMessage listeners. unbind: function(type, fn) { var listeners = pm.data("listeners.postMessage"); if (listeners) { if (type) { if (fn) { // Remove specific listener var fns = listeners[type]; if (fns) { var newListeners = []; for (var i = 0, len = fns.length; i < len; i++) { var obj = fns[i]; if (obj.fn !== fn) { newListeners.push(obj); } } listeners[type] = newListeners; } } else { // Remove all listeners by type delete listeners[type]; } } else { // Unbind all listeners of all types for (var i in listeners) { delete listeners[i]; } } } }, // Run the handler, if one exists, based on the type defined in the postMessage. _dispatch: function(e) { var msg = {}; try { msg = JSON.parse(e.data); } catch (ex) { console.warn("postMessage data parsing failed: ", ex); return; } if (!msg.type) { console.warn("postMessage message type required."); return; } var listeners = pm.data("listeners.postMessage") || {}; var fns = listeners[msg.type] || []; for (var i = 0, len = fns.length; i < len; i++) { var obj = fns[i]; if (obj.origin && obj.origin !== '*' && e.origin !== obj.origin) { console.warn("postMessage message origin mismatch: ", e.origin, obj.origin); continue; } // Run handler try { obj.fn(msg.data); } catch (ex) { throw ex; } } } }; })(this);
random_line_split