uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ea3589c44f5cce211004bfc5 | train | class | class AlipayMarketingActivityOrdervoucherSendModel(object):
def __init__(self):
self._activity_id = None
self._biz_dt = None
self._ch_info = None
self._merchant_order_url = None
self._out_biz_no = None
self._trade_channel = None
self._trade_no = None
... | class AlipayMarketingActivityOrdervoucherSendModel(object):
| def __init__(self):
self._activity_id = None
self._biz_dt = None
self._ch_info = None
self._merchant_order_url = None
self._out_biz_no = None
self._trade_channel = None
self._trade_no = None
self._user_id = None
@property
def activity_id(self)... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayMarketingActivityOrdervoucherSendModel(object):
| 39 | 256 | 1,034 | 11 | 28 | antopen/alipay-sdk-python-all | alipay/aop/api/domain/AlipayMarketingActivityOrdervoucherSendModel.py | Python | AlipayMarketingActivityOrdervoucherSendModel | AlipayMarketingActivityOrdervoucherSendModel | 8 | 143 | 8 | 9 | 1761fe5b2766067f9cde6d515c6ec7d99bfa2f9f | bigcode/the-stack | train |
c53d9a1103cc95112737d12c | train | function | async def index(r: aiohttp.web.RequestHandler):
if not await privilegehelper.logged_in(r) or not await privilegehelper.is_admin(r):
return aiohttp.web.HTTPForbidden()
return await utils.render_template(r, "admin.html",
totalusers=await userhelper.get_total_us... | async def index(r: aiohttp.web.RequestHandler):
| if not await privilegehelper.logged_in(r) or not await privilegehelper.is_admin(r):
return aiohttp.web.HTTPForbidden()
return await utils.render_template(r, "admin.html",
totalusers=await userhelper.get_total_users(),
us... | import aiohttp
import utils # type: ignore
from common.helpers import userhelper, privilegehelper, levelhelper # type: ignore
async def index(r: aiohttp.web.RequestHandler):
| 39 | 64 | 86 | 11 | 27 | lotus-gd/lotus-web | handlers/admin/index.py | Python | index | index | 5 | 12 | 5 | 5 | 4189bd919da4ca7550495ea13d0240de9a04b570 | bigcode/the-stack | train |
62f5ad54711657c99f6887b8 | train | function | def is_scripting():
r"""
Function that returns True when in compilation and False otherwise. This
is useful especially with the @unused decorator to leave code in your
model that is not yet TorchScript compatible.
.. testcode::
import torch
@torch.jit.unused
def unsupported... | def is_scripting():
| r"""
Function that returns True when in compilation and False otherwise. This
is useful especially with the @unused decorator to leave code in your
model that is not yet TorchScript compatible.
.. testcode::
import torch
@torch.jit.unused
def unsupported_linear_op(x):
... | fn = torch._C._jit_script_compile(
qualified_name, ast, _rcb, get_default_args(obj)
)
# Forward docstrings
fn.__doc__ = obj.__doc__
_set_jit_function_cache(obj, fn)
return fn
def is_scripting():
| 64 | 64 | 112 | 5 | 58 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | is_scripting | is_scripting | 938 | 957 | 938 | 938 | 92a0b0956b300c9d3dd902f73408b393e9f776aa | bigcode/the-stack | train |
da19721b94c15d8a0df699fe | train | class | class OrderedModuleDict(OrderedDictWrapper):
def __init__(self, module, python_dict):
super(OrderedModuleDict, self).__init__(torch._C.ModuleDict(module))
# contains _both_ script modules and non-script python-only modules
# because script modules are subclassed in python and the
# ... | class OrderedModuleDict(OrderedDictWrapper):
| def __init__(self, module, python_dict):
super(OrderedModuleDict, self).__init__(torch._C.ModuleDict(module))
# contains _both_ script modules and non-script python-only modules
# because script modules are subclassed in python and the
# C++ Module class will not hold references to ... | self._c.items()
def __setitem__(self, k, v):
if k not in self:
raise RuntimeError(
"Can't add a new parameter after ScriptModule construction."
" Tried to add '{}".format(k)
)
self._c.setattr(k, v)
def __contains__(self, k):
retu... | 120 | 120 | 403 | 9 | 111 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | OrderedModuleDict | OrderedModuleDict | 116 | 154 | 116 | 116 | 5f0ca8cc72abc7cee755dda9ab8d78227f0f3e03 | bigcode/the-stack | train |
a51dda3d44392efd0d72cd56 | train | class | class ConstMap:
def __init__(self, const_mapping):
self.const_mapping = const_mapping
def __getattr__(self, attr):
return self.const_mapping[attr]
| class ConstMap:
| def __init__(self, const_mapping):
self.const_mapping = const_mapping
def __getattr__(self, attr):
return self.const_mapping[attr]
| 2 gets us to the proper surrounding scope.
_rcb = _jit_internal.createResolutionCallbackFromFrame(frames_up=2)
ast = get_jit_def(fn, fn.__name__, self_name="ScriptModule")
return ScriptMethodStub(_rcb, ast, fn)
class ConstMap:
| 64 | 64 | 39 | 4 | 60 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | ConstMap | ConstMap | 247 | 252 | 247 | 247 | ae40518f2a5a266392a4dd9b8aa879fd867bf31e | bigcode/the-stack | train |
92cd7e4f2faa1edb17f50efb | train | class | class ScriptMeta(type):
def __init__(cls, name, bases, attrs): # noqa: B902
# Aggregate all the ScriptMethods and constants from superclasses
cls._methods = {}
cls._constants_set = set(getattr(cls, "__constants__", ()))
for base in reversed(bases):
for k, v in getattr(ba... | class ScriptMeta(type):
| def __init__(cls, name, bases, attrs): # noqa: B902
# Aggregate all the ScriptMethods and constants from superclasses
cls._methods = {}
cls._constants_set = set(getattr(cls, "__constants__", ()))
for base in reversed(bases):
for k, v in getattr(base, "_methods", {}).item... | , k):
return self._python_modules[k]
# For each user-defined class that subclasses ScriptModule, this meta-class:
# (1) finds all the methods annotated with @script_method in a ScriptModule and
# removes them from the class attributes
# (2) puts a wrapper around the class's __init__ method to recusively c... | 144 | 144 | 482 | 5 | 139 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | ScriptMeta | ScriptMeta | 165 | 215 | 165 | 165 | 5a0e325e347d8a89393bac9d0fbf81f03257b3e4 | bigcode/the-stack | train |
08876245016a69eb8c6a9bce | train | function | def script_method(fn):
if not _enabled:
return fn
# NOTE: we need to traverse two frames here because the meta-class frame
# for ScriptModule will be present, as opposed to invoking @script on a
# a function or invoking define() on a CompilationUnit.
# The stack will look like:
#
# 0... | def script_method(fn):
| if not _enabled:
return fn
# NOTE: we need to traverse two frames here because the meta-class frame
# for ScriptModule will be present, as opposed to invoking @script on a
# a function or invoking define() on a CompilationUnit.
# The stack will look like:
#
# 0. createResolutionCallb... | init__ = init_then_script
return super(ScriptMeta, cls).__init__(name, bases, attrs)
class _CachedForward(object):
def __get__(self, obj, cls):
return self.__getattr__("forward")
class ScriptWarning(Warning):
pass
def script_method(fn):
| 64 | 64 | 200 | 5 | 58 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | script_method | script_method | 227 | 244 | 227 | 227 | 22c321e9be3d5571b13c440e3318c1c93195acd8 | bigcode/the-stack | train |
21b3b3b6c9265cd832a36cc8 | train | function | def _unwrap_optional(x):
assert x is not None, "Unwrapping null optional"
return x
| def _unwrap_optional(x):
| assert x is not None, "Unwrapping null optional"
return x
| 1)
self._c.define(lang, rcb)
def __getattr__(self, attr):
r = self._c.find_function(attr)
if r is None:
raise AttributeError("'CompilationUnit' has no attribute '{}'".format(attr))
return r
def _unwrap_optional(x):
| 64 | 64 | 24 | 6 | 57 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _unwrap_optional | _unwrap_optional | 1,092 | 1,094 | 1,092 | 1,092 | b1fa88923138f2411d0de9634cf1dbcc757569c5 | bigcode/the-stack | train |
8850628e76e0dd39330043a4 | train | class | class ScriptWarning(Warning):
pass
| class ScriptWarning(Warning):
| pass
| attr(self, name)
cls.__init__ = init_then_script
return super(ScriptMeta, cls).__init__(name, bases, attrs)
class _CachedForward(object):
def __get__(self, obj, cls):
return self.__getattr__("forward")
class ScriptWarning(Warning):
| 64 | 64 | 9 | 6 | 58 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | ScriptWarning | ScriptWarning | 223 | 224 | 223 | 223 | 9fe84fcc17ff05c513038c1b9538725c988ac101 | bigcode/the-stack | train |
37af3c00f8b49ece7d4699a4 | train | function | def _is_new_style_class(cls):
if hasattr(cls, "__class__"):
return "__dict__" in dir(cls) or hasattr(cls, "__slots__")
| def _is_new_style_class(cls):
| if hasattr(cls, "__class__"):
return "__dict__" in dir(cls) or hasattr(cls, "__slots__")
| .jit")
if _enabled:
Attribute = collections.namedtuple("Attribute", ["value", "type"])
else:
def Attribute(value, type):
return value
# ScriptClasses must be new-style classes because we construct them using their
# __new__ method.
def _is_new_style_class(cls):
| 64 | 64 | 35 | 8 | 56 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _is_new_style_class | _is_new_style_class | 54 | 56 | 54 | 54 | 54a60bf41ae59999dc46f01db3ae8e17ebc82d04 | bigcode/the-stack | train |
9c5d0d40d48ba45c946456b0 | train | class | class OrderedDictWrapper(object):
def __init__(self, _c):
self._c = _c
def keys(self):
return [k for k, v in self.items()]
def values(self):
return [v for k, v in self.items()]
def __len__(self):
return len(self.values())
def __delitem__(self, k):
raise Ru... | class OrderedDictWrapper(object):
| def __init__(self, _c):
self._c = _c
def keys(self):
return [k for k, v in self.items()]
def values(self):
return [v for k, v in self.items()]
def __len__(self):
return len(self.values())
def __delitem__(self, k):
raise RuntimeError("cannot delete methods ... | in C++.
# Each OrderedDict needs to support:
# x not in view
# x in view
# view[name] = ...
# view.values()
# del view[name]
# view.items()
# view.keys()
# len(view)
class OrderedDictWrapper(object):
| 64 | 64 | 216 | 6 | 58 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | OrderedDictWrapper | OrderedDictWrapper | 80 | 113 | 80 | 80 | eef94033eaddf1dec5e86d87884ea654891eacee | bigcode/the-stack | train |
0214b1f9cbfe89dda76635e7 | train | class | class _CachedForward(object):
def __get__(self, obj, cls):
return self.__getattr__("forward")
| class _CachedForward(object):
| def __get__(self, obj, cls):
return self.__getattr__("forward")
| .get_modules():
delattr(self, name)
for name in ("_parameters", "_buffers", "_modules"):
delattr(self, name)
cls.__init__ = init_then_script
return super(ScriptMeta, cls).__init__(name, bases, attrs)
class _CachedForward(object):
| 64 | 64 | 26 | 6 | 58 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _CachedForward | _CachedForward | 218 | 220 | 218 | 218 | 5a58866290b8ff8d51bae80f8d94672c45c46ff1 | bigcode/the-stack | train |
5770427e8c34c5af65ec555d | train | function | def interface(obj):
if not inspect.isclass(obj):
raise RuntimeError("interface must be applied to a class")
if not _is_new_style_class(obj):
raise RuntimeError("TorchScript interfaces must inherit from 'object'")
# Expected MRO is:
# User module
# torch.nn.modules.module.Module
... | def interface(obj):
| if not inspect.isclass(obj):
raise RuntimeError("interface must be applied to a class")
if not _is_new_style_class(obj):
raise RuntimeError("TorchScript interfaces must inherit from 'object'")
# Expected MRO is:
# User module
# torch.nn.modules.module.Module
# object
i... | (obj)
if _jit_internal._get_fn_overloads(qual_name) or _try_get_jit_cached_overloads(obj):
raise RuntimeError(
"Function {} cannot be directly compiled because it"
" is overloaded. It must be used in a context of a function"
" where its inputs can determine which overload... | 82 | 82 | 275 | 4 | 78 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | interface | interface | 1,031 | 1,059 | 1,031 | 1,031 | 04ef8db3ff8e7a2a75db900ae6e2a4706b0df9f5 | bigcode/the-stack | train |
4fd506b7dac9d3d5f7766bdc | train | function | def script(obj, optimize=None, _frames_up=0, _rcb=None):
r"""
Scripting a function or ``nn.Module`` will inspect the source code, compile
it as TorchScript code using the TorchScript compiler, and return a :class:`ScriptModule` or
:class:`ScriptFunction`. TorchScript itself is a subset of the Python lan... | def script(obj, optimize=None, _frames_up=0, _rcb=None):
| r"""
Scripting a function or ``nn.Module`` will inspect the source code, compile
it as TorchScript code using the TorchScript compiler, and return a :class:`ScriptModule` or
:class:`ScriptFunction`. TorchScript itself is a subset of the Python language, so not all
features in Python work, but we pro... | "parameters",
"named_parameters",
"buffers",
"named_buffers",
"children",
"named_children",
"modules",
"named_modules",
"zero_grad",
"share_memory",
"_get_name",
"extra_repr",
"_slow_forward",
"_tracing_name",
... | 255 | 256 | 1,685 | 18 | 238 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | script | script | 735 | 935 | 735 | 735 | 590fbc9f34ed4fb4d46d1671b6b5b599c59d1a9a | bigcode/the-stack | train |
fee75b4f4b69e65b65d2a3c6 | train | function | def _compile_function_with_overload(overload_fn, qual_name, impl_fn):
overload_decl = get_jit_def(overload_fn, overload_fn.__name__).decl()
overload_signature = torch.jit.annotations.get_signature(
overload_fn, None, None, inspect.ismethod(overload_fn)
)
impl_ast = get_jit_def(impl_fn, impl_fn._... | def _compile_function_with_overload(overload_fn, qual_name, impl_fn):
| overload_decl = get_jit_def(overload_fn, overload_fn.__name__).decl()
overload_signature = torch.jit.annotations.get_signature(
overload_fn, None, None, inspect.ismethod(overload_fn)
)
impl_ast = get_jit_def(impl_fn, impl_fn.__name__)
overload_defaults = get_default_args(overload_fn)
imp... | (
loc,
"Default parameters on overloads do not affect the runtime so they "
"must equal to the default parameter on the implementation function. Found on "
"parameter {name}".format(name=name),
)
def _compile_function_with_overload(overload_fn,... | 64 | 64 | 185 | 17 | 47 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _compile_function_with_overload | _compile_function_with_overload | 975 | 995 | 975 | 975 | 6ee71351066d8d73d6bb3b8242b33a615a5764be | bigcode/the-stack | train |
c13a0619ba5c3a943ac9a8ab | train | function | def _compile_and_register_class(obj, rcb, qualified_name):
ast = get_jit_class_def(obj, obj.__name__)
torch._C._jit_script_class_compile(qualified_name, ast, rcb)
torch.jit._state._add_script_class(obj, qualified_name)
| def _compile_and_register_class(obj, rcb, qualified_name):
| ast = get_jit_class_def(obj, obj.__name__)
torch._C._jit_script_class_compile(qualified_name, ast, rcb)
torch.jit._state._add_script_class(obj, qualified_name)
| -style classes because we construct them using their
# __new__ method.
def _is_new_style_class(cls):
if hasattr(cls, "__class__"):
return "__dict__" in dir(cls) or hasattr(cls, "__slots__")
def _compile_and_register_class(obj, rcb, qualified_name):
| 64 | 64 | 61 | 14 | 50 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _compile_and_register_class | _compile_and_register_class | 59 | 62 | 59 | 59 | 21657e32c874c9098f6295717aa12165e211f341 | bigcode/the-stack | train |
79e9ab35fc1f2e5d4752e9e9 | train | function | def _recursive_compile_class(obj, loc):
_qual_name = _qualified_name(obj)
# We're starting a new compilation, so update the error call stack in
# case it fails
error_stack = torch._C.CallStack(_qual_name, loc)
rcb = _jit_internal.createResolutionCallbackForClassMethods(obj)
_compile_and_register... | def _recursive_compile_class(obj, loc):
| _qual_name = _qualified_name(obj)
# We're starting a new compilation, so update the error call stack in
# case it fails
error_stack = torch._C.CallStack(_qual_name, loc)
rcb = _jit_internal.createResolutionCallbackForClassMethods(obj)
_compile_and_register_class(obj, rcb, _qual_name)
| interface
ast = get_jit_class_def(obj, obj.__name__)
torch._C._jit_script_interface_compile(
qualified_name, ast, rcb, is_module_interface
)
obj.__torch_script_interface__ = True
return obj
def _recursive_compile_class(obj, loc):
| 64 | 64 | 86 | 9 | 54 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _recursive_compile_class | _recursive_compile_class | 1,062 | 1,068 | 1,062 | 1,062 | ad0b6f7aa311b7718db998a77ff7d5ff7eabdf84 | bigcode/the-stack | train |
ec66fd731833ec7f9048a96f | train | class | class CompilationUnit(object):
def __init__(self, lang=None, _frames_up=0):
self._c = torch._C.CompilationUnit()
if lang is not None:
self.define(lang, _frames_up=_frames_up + 1)
def define(self, lang, rcb=None, _frames_up=0):
if not rcb:
rcb = _jit_internal.crea... | class CompilationUnit(object):
| def __init__(self, lang=None, _frames_up=0):
self._c = torch._C.CompilationUnit()
if lang is not None:
self.define(lang, _frames_up=_frames_up + 1)
def define(self, lang, rcb=None, _frames_up=0):
if not rcb:
rcb = _jit_internal.createResolutionCallbackFromFrame(_... |
error_stack = torch._C.CallStack(_qual_name, loc)
rcb = _jit_internal.createResolutionCallbackForClassMethods(obj)
_compile_and_register_class(obj, rcb, _qual_name)
_register_builtin(is_scripting, "aten::is_scripting")
class CompilationUnit(object):
| 64 | 64 | 153 | 5 | 59 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | CompilationUnit | CompilationUnit | 1,074 | 1,089 | 1,074 | 1,074 | fd7be9b3740fa52a4e9277e8abfb297a6f8602f5 | bigcode/the-stack | train |
69b250b269d83e62c10c9af5 | train | function | def _check_directly_compile_overloaded(obj):
qual_name = _qualified_name(obj)
if _jit_internal._get_fn_overloads(qual_name) or _try_get_jit_cached_overloads(obj):
raise RuntimeError(
"Function {} cannot be directly compiled because it"
" is overloaded. It must be used in a contex... | def _check_directly_compile_overloaded(obj):
| qual_name = _qualified_name(obj)
if _jit_internal._get_fn_overloads(qual_name) or _try_get_jit_cached_overloads(obj):
raise RuntimeError(
"Function {} cannot be directly compiled because it"
" is overloaded. It must be used in a context of a function"
" where its inpu... | _compiled_fns + compiled_fns
# cache compilation, remove information stored to do compilation
_set_jit_overload_cache(obj, compiled_fns)
_jit_internal._clear_fn_overloads(qual_name)
return compiled_fns
def _check_directly_compile_overloaded(obj):
| 64 | 64 | 95 | 10 | 53 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _check_directly_compile_overloaded | _check_directly_compile_overloaded | 1,021 | 1,028 | 1,021 | 1,021 | 8148587c32e077ffd3db1433deaa87e3348c42af | bigcode/the-stack | train |
c110681c4858ceb61541b7b2 | train | function | def _get_overloads(obj):
# check for cached compiled fns
existing_compiled_fns = _try_get_jit_cached_overloads(obj)
qual_name = _qualified_name(obj)
uncompiled_overloads = _jit_internal._get_fn_overloads(qual_name)
if uncompiled_overloads is None:
return existing_compiled_fns
compiled_f... | def _get_overloads(obj):
# check for cached compiled fns
| existing_compiled_fns = _try_get_jit_cached_overloads(obj)
qual_name = _qualified_name(obj)
uncompiled_overloads = _jit_internal._get_fn_overloads(qual_name)
if uncompiled_overloads is None:
return existing_compiled_fns
compiled_fns = []
for overload_fn in uncompiled_overloads:
... | .range()
)
fn = torch._C._jit_script_compile_overload(
qual_name,
overload_decl,
impl_ast,
_rcb,
implementation_defaults,
overload_signature,
)
return fn
def _get_overloads(obj):
# check for cached compiled fns
| 64 | 64 | 185 | 16 | 47 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _get_overloads | _get_overloads | 998 | 1,018 | 998 | 999 | e7dfb740c94808b39cb1d7246dfd1af55f8a3790 | bigcode/the-stack | train |
73f79cde9dc7c8a0c894ddf6 | train | function | def _check_overload_defaults(impl_defaults, overload_defaults, loc):
for name, overload_value in overload_defaults.items():
if name not in impl_defaults or impl_defaults[name] != overload_value:
raise torch.jit.frontend.FrontendError(
loc,
"Default parameters on o... | def _check_overload_defaults(impl_defaults, overload_defaults, loc):
| for name, overload_value in overload_defaults.items():
if name not in impl_defaults or impl_defaults[name] != overload_value:
raise torch.jit.frontend.FrontendError(
loc,
"Default parameters on overloads do not affect the runtime so they "
"must eq... | )
else:
return unsupported_linear_op(x)
"""
return False
# overloads are registered in _jit_internal and compiled here so that _overload
# can be used in nn/functional.py without an import cycle
def _check_overload_defaults(impl_defaults, overload_defaults, loc):
| 64 | 64 | 100 | 15 | 48 | zhou3968322/dl-code-read | pytorch/torch/jit/_script.py | Python | _check_overload_defaults | _check_overload_defaults | 964 | 972 | 964 | 964 | 778518ae1629197adf3ede22abe61d4dec96921e | bigcode/the-stack | train |
be97e8554859292f95c52fdd | train | class | class Ply:
"""Creates an instance of Ply.
Parameters
----------
e1 : float, int
Young modulus in the 1st direction
e2 : float, int
Young modulus in the 2nd direction
v12 : float
poisson modulus 12
g12 : float, int
Shear modulus
thickness : float, int
... | class Ply:
| """Creates an instance of Ply.
Parameters
----------
e1 : float, int
Young modulus in the 1st direction
e2 : float, int
Young modulus in the 2nd direction
v12 : float
poisson modulus 12
g12 : float, int
Shear modulus
thickness : float, int
thickne... | import itertools
import numbers
import numpy as np
class Ply:
| 14 | 256 | 1,106 | 3 | 10 | IanViotti/composipy | composipy/ply_class.py | Python | Ply | Ply | 6 | 134 | 6 | 6 | d285acbc4228afc3755b56aea27e65e724ca4ace | bigcode/the-stack | train |
2fdc6b692af1b487ef255845 | train | class | @pulumi.output_type
class GetReplicationNetworkMappingResult:
"""
Network Mapping model. Ideally it should have been possible to inherit this class from prev version in InheritedModels as long as there is no difference in structure or method signature. Since there were no base Models for certain fields and meth... | @pulumi.output_type
class GetReplicationNetworkMappingResult:
| """
Network Mapping model. Ideally it should have been possible to inherit this class from prev version in InheritedModels as long as there is no difference in structure or method signature. Since there were no base Models for certain fields and methods viz NetworkMappingProperties and Load with required return... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | 124 | 148 | 495 | 13 | 111 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/recoveryservices/v20210210/get_replication_network_mapping.py | Python | GetReplicationNetworkMappingResult | GetReplicationNetworkMappingResult | 18 | 78 | 18 | 19 | 798dfb9ab36034054bf02e3801a6334f9d078705 | bigcode/the-stack | train |
b6c1dba8260e41858e393032 | train | function | def get_replication_network_mapping(fabric_name: Optional[str] = None,
network_mapping_name: Optional[str] = None,
network_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
... | def get_replication_network_mapping(fabric_name: Optional[str] = None,
network_mapping_name: Optional[str] = None,
network_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
... | """
Network Mapping model. Ideally it should have been possible to inherit this class from prev version in InheritedModels as long as there is no difference in structure or method signature. Since there were no base Models for certain fields and methods viz NetworkMappingProperties and Load with required return... | def __await__(self):
if False:
yield self
return GetReplicationNetworkMappingResult(
id=self.id,
location=self.location,
name=self.name,
properties=self.properties,
type=self.type)
def get_replication_network_mapping(fabric_name: O... | 127 | 127 | 425 | 80 | 47 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/recoveryservices/v20210210/get_replication_network_mapping.py | Python | get_replication_network_mapping | get_replication_network_mapping | 94 | 127 | 94 | 99 | 035d2eddb6966f19e59dce6bd72f9ad6cb73010f | bigcode/the-stack | train |
e4619d98b5f68a2189dbb31f | train | class | class AwaitableGetReplicationNetworkMappingResult(GetReplicationNetworkMappingResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetReplicationNetworkMappingResult(
id=self.id,
location=self.location,
na... | class AwaitableGetReplicationNetworkMappingResult(GetReplicationNetworkMappingResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetReplicationNetworkMappingResult(
id=self.id,
location=self.location,
name=self.name,
properties=self.properties,
type=self.type)
| properties")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource Type
"""
return pulumi.get(self, "type")
class AwaitableGetReplicationNetworkMappingResult(GetReplicationNetworkMappingResult):
# pylint: disable=using-constant-test
| 64 | 64 | 73 | 25 | 39 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/recoveryservices/v20210210/get_replication_network_mapping.py | Python | AwaitableGetReplicationNetworkMappingResult | AwaitableGetReplicationNetworkMappingResult | 81 | 91 | 81 | 82 | 62e6bcdc843f8c02d4890e7611c931d6231e23f1 | bigcode/the-stack | train |
cbbf34f25f5cb6a64836e180 | train | function | def read_file():
try:
in_file = open("output.txt", "r")
except OSError as e:
print("Cannot open file to read: {}", e)
return
line = in_file.readline()
while line:
print(line.rstrip('\n'))
line = in_file.readline()
in_file.close()
| def read_file():
| try:
in_file = open("output.txt", "r")
except OSError as e:
print("Cannot open file to read: {}", e)
return
line = in_file.readline()
while line:
print(line.rstrip('\n'))
line = in_file.readline()
in_file.close()
| ", "w")
except OSError as e:
print("Cannot open file: {}", e)
return
out.write("Hi! I'm a line of text in this file!\n")
out.write("Me, too!\n")
out.flush()
out.close()
def read_file():
| 64 | 64 | 73 | 5 | 59 | Ayush7-BIT/sample-programs | archive/p/python/file_io.py | Python | read_file | read_file | 16 | 29 | 16 | 17 | fbf6aa08c6c6ed3a3da054d0ecec4755d7321879 | bigcode/the-stack | train |
6d8b01d5ab547045609d2217 | train | function | def write_file():
try:
out = open("output.txt", "w")
except OSError as e:
print("Cannot open file: {}", e)
return
out.write("Hi! I'm a line of text in this file!\n")
out.write("Me, too!\n")
out.flush()
out.close()
| def write_file():
| try:
out = open("output.txt", "w")
except OSError as e:
print("Cannot open file: {}", e)
return
out.write("Hi! I'm a line of text in this file!\n")
out.write("Me, too!\n")
out.flush()
out.close()
| def write_file():
| 4 | 64 | 73 | 4 | 0 | Ayush7-BIT/sample-programs | archive/p/python/file_io.py | Python | write_file | write_file | 1 | 14 | 1 | 2 | ad846b037ef142663d8b780a62be5194972e99d6 | bigcode/the-stack | train |
10600ce9d7da7f7e069a060b | train | class | class TestCli:
"""Defines tests for usage of the archetypal Command Line Interface"""
def test_reduce(self):
"""Tests the 'reduced_model' method"""
runner = CliRunner()
base = Path("tests/input_data/umi_samples")
outname = "tests/.temp/warehouse.json"
result = runner.inv... | class TestCli:
| """Defines tests for usage of the archetypal Command Line Interface"""
def test_reduce(self):
"""Tests the 'reduced_model' method"""
runner = CliRunner()
base = Path("tests/input_data/umi_samples")
outname = "tests/.temp/warehouse.json"
result = runner.invoke(
... | import os
import pytest
from click.testing import CliRunner
from path import Path
from archetypal import settings
from archetypal.cli import cli
from archetypal.utils import log
class TestCli:
| 45 | 134 | 449 | 4 | 40 | samuelduchesne/archetypal | tests/test_cli.py | Python | TestCli | TestCli | 12 | 75 | 12 | 12 | 672b4ab47ceb06210e06a87902411235f3192418 | bigcode/the-stack | train |
f905a3bcdbbfe51a5cf14c60 | train | class | class TrieMixin:
def build_trie(self, lexicon):
"""
Build a character-trie from the plain pattern_string -> categories_list
mapping provided by `lexicon`.
Some LIWC patterns end with a `*` to indicate a wildcard match.
"""
trie = {}
for pattern, category_nam... | class TrieMixin:
| def build_trie(self, lexicon):
"""
Build a character-trie from the plain pattern_string -> categories_list
mapping provided by `lexicon`.
Some LIWC patterns end with a `*` to indicate a wildcard match.
"""
trie = {}
for pattern, category_names in lexicon.item... | class TrieMixin:
| 4 | 74 | 247 | 4 | 0 | HyanBatista/liwc-python | liwc/trie.py | Python | TrieMixin | TrieMixin | 1 | 36 | 1 | 2 | 7d071b9e2ca65fcfe40acc4703adc7653b4f9588 | bigcode/the-stack | train |
2bae63d159b2f281d18b5f7c | train | function | def test_on_test_set(model, testX, testY, sentences, verbose, threshold_factor):
test_outputs = model.predict(testX)
test_res = model.test_on_batch(testX, testY)
exact = 0
valid = 0
for i in range(len(test_outputs)):
v = output_to_vision(test_outputs[i],nb_concepts,
... | def test_on_test_set(model, testX, testY, sentences, verbose, threshold_factor):
| test_outputs = model.predict(testX)
test_res = model.test_on_batch(testX, testY)
exact = 0
valid = 0
for i in range(len(test_outputs)):
v = output_to_vision(test_outputs[i],nb_concepts,
threshold_factor, concepts_delimitations, output_id_to_concept_dict)
... | return data_set_pad
def test_with_sentences(sentences, model):
global max_seq_len
test = [one_hot_encoding_sentence(s) for s in sentences]
test_pad = padding(test, max_seq_len)
res = model.predict(test_pad)
return res
def test_on_test_set(model, testX, testY, sentences, verbose, thre... | 80 | 80 | 269 | 20 | 59 | gaetanmargueritte/ccg2esn | CSL_LSTM.py | Python | test_on_test_set | test_on_test_set | 56 | 85 | 56 | 56 | 9ab2601a78fb7a7f74643721488e091d6beb4603 | bigcode/the-stack | train |
03726d50b7455ac624ce3a23 | train | function | def get_successive_outputs(sentence, model):
words = sentence.split(" ")
prefixes = []
for i in range(len(words)+1):
prefixes.append(" ".join(words[:i]))
vect = test_with_sentences(prefixes, model)
return vect
| def get_successive_outputs(sentence, model):
| words = sentence.split(" ")
prefixes = []
for i in range(len(words)+1):
prefixes.append(" ".join(words[:i]))
vect = test_with_sentences(prefixes, model)
return vect
| .title("Performance on validation set during training")
plt.plot(self.exact_errors, color = "blue", label = "exact error")
plt.plot(self.valid_errors, color = "green", label = "valid error")
plt.legend()
plt.show()
def get_successive_outputs(sentence, model):
| 63 | 64 | 56 | 9 | 54 | gaetanmargueritte/ccg2esn | CSL_LSTM.py | Python | get_successive_outputs | get_successive_outputs | 126 | 132 | 126 | 126 | 30c5212b55bfa7760288d503990d7da71db76ab8 | bigcode/the-stack | train |
27f649e311be7bb89302fcba | train | class | class LossHistory(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.losses = []
self.val_losses = []
self.exact_errors = []
self.valid_errors = []
def on_epoch_end(self, epoch, logs=None):
global validationX_pad
global validationY
... | class LossHistory(keras.callbacks.Callback):
| def on_train_begin(self, logs={}):
self.losses = []
self.val_losses = []
self.exact_errors = []
self.valid_errors = []
def on_epoch_end(self, epoch, logs=None):
global validationX_pad
global validationY
self.losses.append(logs.get('loss'))
... | print("Exact representations : ", exact, "/", nb_sample)
print("MSE on test : ", test_res)
print("RMSE on test : ", np.sqrt(test_res))
return 1-valid/nb_sample, 1-exact/nb_sample, test_res
## to get the evolution of the loss during training
class LossHistory(keras.callbacks.Callb... | 79 | 79 | 265 | 8 | 70 | gaetanmargueritte/ccg2esn | CSL_LSTM.py | Python | LossHistory | LossHistory | 89 | 120 | 89 | 89 | e66dbb03f0c7352a99131e8de0aff787f8ade16b | bigcode/the-stack | train |
7e2cb98d0bd7284fe51ad7bf | train | function | def get_inner_states(sentences, model, only_last = False, info_obj_nb = False):
all_states = [[] for i in range(len(model.outputs))]
clause_nbs =[]
for k in range(len(sentences)):
states = get_successive_outputs(sentences[k], model)
if info_obj_nb:
words = sentences[k... | def get_inner_states(sentences, model, only_last = False, info_obj_nb = False):
| all_states = [[] for i in range(len(model.outputs))]
clause_nbs =[]
for k in range(len(sentences)):
states = get_successive_outputs(sentences[k], model)
if info_obj_nb:
words = sentences[k].split(" ")
clause_id = 0
clause_nbs.append(clause_id)... | .legend()
plt.show()
def get_successive_outputs(sentence, model):
words = sentence.split(" ")
prefixes = []
for i in range(len(words)+1):
prefixes.append(" ".join(words[:i]))
vect = test_with_sentences(prefixes, model)
return vect
def get_inner_states(sentences, mod... | 83 | 83 | 278 | 20 | 62 | gaetanmargueritte/ccg2esn | CSL_LSTM.py | Python | get_inner_states | get_inner_states | 134 | 171 | 134 | 134 | 211ac60a36b6645864eda3594aeca7b2d3b4e264 | bigcode/the-stack | train |
7b093782d3d626fd1f5cc3dd | train | function | def plot_hidden_states(sentence, model_for_test, state = 'cell', units_to_plot = 'all', plt_var = False, plt_sum = False):
activations = get_successive_outputs(sentence, model_for_test)
plot_hidden_state_activation(sentence,
activations,
st... | def plot_hidden_states(sentence, model_for_test, state = 'cell', units_to_plot = 'all', plt_var = False, plt_sum = False):
| activations = get_successive_outputs(sentence, model_for_test)
plot_hidden_state_activation(sentence,
activations,
state,
units_to_plot,
plot_variation = plt_var,
... | np.array(all_states[i])
if info_obj_nb:
return all_states, np.array(clause_nbs)
else:
return all_states
def plot_hidden_states(sentence, model_for_test, state = 'cell', units_to_plot = 'all', plt_var = False, plt_sum = False):
| 64 | 64 | 80 | 32 | 31 | gaetanmargueritte/ccg2esn | CSL_LSTM.py | Python | plot_hidden_states | plot_hidden_states | 174 | 182 | 174 | 174 | 77457629de17f0d2835efc26a3f4d9689d0d8222 | bigcode/the-stack | train |
ffc98fc2a874bf94a943295f | train | function | def test_with_sentences(sentences, model):
global max_seq_len
test = [one_hot_encoding_sentence(s) for s in sentences]
test_pad = padding(test, max_seq_len)
res = model.predict(test_pad)
return res
| def test_with_sentences(sentences, model):
| global max_seq_len
test = [one_hot_encoding_sentence(s) for s in sentences]
test_pad = padding(test, max_seq_len)
res = model.predict(test_pad)
return res
| =special_value)
for s, x in enumerate(data_set):
if x is None:
continue
seq_len = x.shape[0]
data_set_pad[s, 0:seq_len, :] = x
return data_set_pad
def test_with_sentences(sentences, model):
| 64 | 64 | 54 | 10 | 53 | gaetanmargueritte/ccg2esn | CSL_LSTM.py | Python | test_with_sentences | test_with_sentences | 50 | 55 | 50 | 50 | 6d85f2ca6a0420252c9a75bdb34d9e6565907a5b | bigcode/the-stack | train |
74123878616d21d7cbf076da | train | function | def padding(data_set, max_seq_len = None, special_value = -42):
if data_set is None:
return np.full((1, max_seq_len, nb_unique_words), fill_value=special_value)
if max_seq_len is None:
max_seq_len = max([len(s) for s in data_set])
data_set_pad = np.full((len(data_set), max_seq_len,... | def padding(data_set, max_seq_len = None, special_value = -42):
| if data_set is None:
return np.full((1, max_seq_len, nb_unique_words), fill_value=special_value)
if max_seq_len is None:
max_seq_len = max([len(s) for s in data_set])
data_set_pad = np.full((len(data_set), max_seq_len, nb_unique_words), fill_value=special_value)
for s, x in e... | , Model
from keras.layers import Dropout
from keras.layers import Dense
from keras.layers import LSTM, Masking, GRU
from keras.layers import Input
from keras.callbacks import ModelCheckpoint
##LSTM functions
def padding(data_set, max_seq_len = None, special_value = -42):
| 64 | 64 | 146 | 17 | 46 | gaetanmargueritte/ccg2esn | CSL_LSTM.py | Python | padding | padding | 32 | 46 | 32 | 32 | e838974abd376e83b079d3fdbbec34b4975c9bea | bigcode/the-stack | train |
cb81cc895c0fe925cd5b2e4a | train | function | def main(args):
attachments = {}
with open(args.csv_file) as csv_file:
for row in csv.DictReader(csv_file):
# ID,Start time,Completion time,Email,Name,Anthology ID,URL where we can download the attachment,Attachment type,"For corrections or errata, please explain in detailed prose what has c... | def main(args):
| attachments = {}
with open(args.csv_file) as csv_file:
for row in csv.DictReader(csv_file):
# ID,Start time,Completion time,Email,Name,Anthology ID,URL where we can download the attachment,Attachment type,"For corrections or errata, please explain in detailed prose what has changed.",Your na... | print(f"Paper {anthology_id} not found in the Anthology", file=sys.stderr)
# Make sure directory exists
output_dir = os.path.join(args.attachment_root, collection_id[0], collection_id)
if not os.path.exists(output_dir):
# print(f"-> Creating directory {output_dir}", file=sys.stderr)
... | 216 | 216 | 721 | 4 | 211 | KhalilMrini/acl-anthology | bin/add_bulk_attachments.py | Python | main | main | 162 | 242 | 162 | 162 | c562cc1d679065163afc138be392600c366e2008 | bigcode/the-stack | train |
707751b6e77b577cfb42f11e | train | function | def add_attachment(anthology_id, path, attach_type, overwrite=False):
"""
Adds a single attachment to the Anthology data files.
Arguments:
- The ACL ID of the paper (e.g., P17-1012)
- The path to the attachment (can be a URL)
- The attachment type (poster, presentation, note, software)
- Wh... | def add_attachment(anthology_id, path, attach_type, overwrite=False):
| """
Adds a single attachment to the Anthology data files.
Arguments:
- The ACL ID of the paper (e.g., P17-1012)
- The path to the attachment (can be a URL)
- The attachment type (poster, presentation, note, software)
- Whether to overwrite the downloaded file.
"""
collection_id, vo... | AAAAAAAAAAAAMAABqTSThUN0I2VEdZMTk4Sks3S042MVkxUEZQUVdOUS4u) we use to collect attachments, and has the following headers:
ID,Start time,Completion time,Email,Name,Anthology ID,URL where we can download the attachment,Attachment type,"For corrections or errata, please explain in detailed prose what has changed.",Yo... | 256 | 256 | 855 | 16 | 240 | KhalilMrini/acl-anthology | bin/add_bulk_attachments.py | Python | add_attachment | add_attachment | 55 | 159 | 55 | 55 | 36f2c8ffe8a4b440e6041677cf7e60fca2275ea4 | bigcode/the-stack | train |
c865ae9e423f7772fe5007c1 | train | function | @pytest.mark.parametrize('r,v,valid', (
(TimeRange(time(), time()), time(), False),
(TimeRange(time(), time(0, 0, 0, 1)), time(), True),
(TimeRange(time(), time(0, 0, 0, 1)), time(0, 0, 0, 1), False),
(TimeRange(None, None), time.min, True),
(TimeRange(None, None), time.max, True),
(TimeRange(No... | @pytest.mark.parametrize('r,v,valid', (
(TimeRange(time(), time()), time(), False),
(TimeRange(time(), time(0, 0, 0, 1)), time(), True),
(TimeRange(time(), time(0, 0, 0, 1)), time(0, 0, 0, 1), False),
(TimeRange(None, None), time.min, True),
(TimeRange(None, None), time.max, True),
(TimeRange(No... | if valid:
assert v in r
else:
assert not (v in r)
| @pytest.mark.parametrize('r,v,valid', (
(TimeRange(time(), time()), time(), False),
(TimeRange(time(), time(0, 0, 0, 1)), time(), True),
(TimeRange(time(), time(0, 0, 0, 1)), time(0, 0, 0, 1), False),
(TimeRange(None, None), time.min, True),
(TimeRange(None, None), time.max, True),
(TimeRange(No... | 259 | 84 | 280 | 259 | 0 | zakuro9715/extrange | extrange/test_timerange.py | Python | test_contains | test_contains | 27 | 46 | 27 | 42 | 6e7122b21d262bb3dc626a572e06fb335f550e6c | bigcode/the-stack | train |
c1840760bb52eae52fe3ae8c | train | function | def test_contains_invalid_value():
with pytest.raises(TypeError):
0 in TimeRange(None, None)
| def test_contains_invalid_value():
| with pytest.raises(TypeError):
0 in TimeRange(None, None)
| ),
(0, time(), False),
(time(), 0, False),
))
def test_constructor_type_check(begin, end, valid):
if valid:
TimeRange(begin, end)
else:
with pytest.raises(TypeError):
TimeRange(begin, end)
def test_contains_invalid_value():
| 64 | 64 | 23 | 6 | 58 | zakuro9715/extrange | extrange/test_timerange.py | Python | test_contains_invalid_value | test_contains_invalid_value | 23 | 25 | 23 | 23 | e0c1dbf76b58337a83cf11702a9f672dd0e132c7 | bigcode/the-stack | train |
82d507f18f1e7428251a8e2f | train | function | @pytest.mark.parametrize('begin,end,valid', (
(time(), time(), True),
(None, None, True),
(time(), None, True),
(None, time(), True),
('a', True, False),
(0, time(), False),
(time(), 0, False),
))
def test_constructor_type_check(begin, end, valid):
if valid:
TimeRange(begin, end)... | @pytest.mark.parametrize('begin,end,valid', (
(time(), time(), True),
(None, None, True),
(time(), None, True),
(None, time(), True),
('a', True, False),
(0, time(), False),
(time(), 0, False),
))
def test_constructor_type_check(begin, end, valid):
| if valid:
TimeRange(begin, end)
else:
with pytest.raises(TypeError):
TimeRange(begin, end)
| @pytest.mark.parametrize('begin,end,valid', (
(time(), time(), True),
(None, None, True),
(time(), None, True),
(None, time(), True),
('a', True, False),
(0, time(), False),
(time(), 0, False),
))
def test_constructor_type_check(begin, end, valid):
| 79 | 64 | 107 | 79 | 0 | zakuro9715/extrange | extrange/test_timerange.py | Python | test_constructor_type_check | test_constructor_type_check | 7 | 21 | 7 | 16 | 677bcadc75b6f8bcf6041260bebd42a756dda23e | bigcode/the-stack | train |
79d41cd0814dce5cfe28080c | train | function | def assert_occurrence(test_ctrl, kw_name, expected_source, expected_usage):
occ = _first_occurrence(test_ctrl, kw_name)
# print("DEBUG: assert_occurrence %s kw_name %s" % (repr(occ.location), kw_name))
assert_equal(occ.location, expected_source,
'Occurrence not in the right place')
ass... | def assert_occurrence(test_ctrl, kw_name, expected_source, expected_usage):
| occ = _first_occurrence(test_ctrl, kw_name)
# print("DEBUG: assert_occurrence %s kw_name %s" % (repr(occ.location), kw_name))
assert_equal(occ.location, expected_source,
'Occurrence not in the right place')
assert_equal(occ.usage, expected_usage, 'Usage not in the right place')
| Log', '${i}'])
for_loop.add_step(['END'])
testcase.setup.name = SETUP_KEYWORD
testcase.teardown.name = 'Teardown Kw'
testcase.template.value = TEMPLATE_KEYWORD
return testcase
def assert_occurrence(test_ctrl, kw_name, expected_source, expected_usage):
| 64 | 64 | 93 | 16 | 47 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | assert_occurrence | assert_occurrence | 81 | 86 | 81 | 81 | c1fe6fb129221f3da992a177066e17684d20e076 | bigcode/the-stack | train |
78552cf54baaf99f3330ebd2 | train | function | def check_for_variable_occurrences(test_ctrl, name, expected_occurrences):
occurrences = list(test_ctrl.execute(FindVariableOccurrences(name)))
processed_occurrences = 0
for source, usage, count in expected_occurrences:
assert_variable_occurrence(occurrences, source, usage, count)
processed_... | def check_for_variable_occurrences(test_ctrl, name, expected_occurrences):
| occurrences = list(test_ctrl.execute(FindVariableOccurrences(name)))
processed_occurrences = 0
for source, usage, count in expected_occurrences:
assert_variable_occurrence(occurrences, source, usage, count)
processed_occurrences += count
assert_equal(processed_occurrences, len(occurrence... | urrences, source, usage, count):
times_found = 0
for occ in occurrences:
if occ.location == source and occ.usage == usage:
times_found += 1
assert_equal(times_found, count)
def check_for_variable_occurrences(test_ctrl, name, expected_occurrences):
| 64 | 64 | 83 | 15 | 49 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | check_for_variable_occurrences | check_for_variable_occurrences | 97 | 103 | 97 | 97 | 9544bc80ab53e21452ba562628482ff4705f57e6 | bigcode/the-stack | train |
186f151a1bc2b9d60f5c9958 | train | class | class FindVariableOccurrencesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
project = datafilereader.construct_project(
datafilereader.FINDWHEREUSED_VARIABLES_PATH)
cls._suite1 = _get_ctrl_by_name(cls, "Suite 1", project.datafiles)
cls._suite2 = _get_ctrl_by_name... | class FindVariableOccurrencesTest(unittest.TestCase):
@classmethod
| def setUpClass(cls):
project = datafilereader.construct_project(
datafilereader.FINDWHEREUSED_VARIABLES_PATH)
cls._suite1 = _get_ctrl_by_name(cls, "Suite 1", project.datafiles)
cls._suite2 = _get_ctrl_by_name(cls, "Suite 2", project.datafiles)
cls._resource1 = _get_ctrl_b... | (self.test_ctrl, TEMPLATE_KEYWORD,
TEST1_NAME, 'Template')
def test_occurrences_in_suite_metadata(self):
assert_occurrence(self.test_ctrl, SUITE_SETUP_KEYWORD,
SUITE_NAME, 'Suite Setup')
assert_occurrence(self.test_ctrl, 'Test Setup Kw',
... | 256 | 256 | 1,078 | 13 | 243 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | FindVariableOccurrencesTest | FindVariableOccurrencesTest | 306 | 396 | 306 | 308 | 6c5c0a365a1fd809c4abab44ceaa6a0292ba9585 | bigcode/the-stack | train |
06d9241af1e171baa340f09b | train | function | def _get_ctrl_by_name(self, name, datafiles):
for file in datafiles:
if file.name == name:
return file
for test in file.tests:
if test.name == name:
return test
for kw in file.keywords:
if kw.name == name:
return kw
retu... | def _get_ctrl_by_name(self, name, datafiles):
| for file in datafiles:
if file.name == name:
return file
for test in file.tests:
if test.name == name:
return test
for kw in file.keywords:
if kw.name == name:
return kw
return None
| occurrences found for "%s"' % kw_name)
return next(occurrences)
# see https://stackoverflow.com/questions/21622193/
# python-3-2-coroutine-attributeerror-generator-object-has-no-attribute-next
def _get_ctrl_by_name(self, name, datafiles):
| 64 | 64 | 72 | 13 | 50 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | _get_ctrl_by_name | _get_ctrl_by_name | 115 | 125 | 115 | 115 | b7a725b1795f1f2048c01457d2593b912ca5a729 | bigcode/the-stack | train |
80c5148ad9a4b12e0b5e6cae | train | class | class TestFindOccurrencesWithFiles(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.project_ctrl = datafilereader.construct_project(
datafilereader.SIMPLE_TEST_SUITE_PATH)
cls.ts1 = datafilereader.get_ctrl_by_name('TestSuite1',
... | class TestFindOccurrencesWithFiles(unittest.TestCase):
@classmethod
| def setUpClass(cls):
cls.project_ctrl = datafilereader.construct_project(
datafilereader.SIMPLE_TEST_SUITE_PATH)
cls.ts1 = datafilereader.get_ctrl_by_name('TestSuite1',
cls.project_ctrl.datafiles)
cls.ts2 = datafilereader.get_ctrl... | )
def check_for_variable_occurrences(test_ctrl, name, expected_occurrences):
occurrences = list(test_ctrl.execute(FindVariableOccurrences(name)))
processed_occurrences = 0
for source, usage, count in expected_occurrences:
assert_variable_occurrence(occurrences, source, usage, count)
proces... | 256 | 256 | 1,194 | 14 | 241 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | TestFindOccurrencesWithFiles | TestFindOccurrencesWithFiles | 128 | 242 | 128 | 130 | ea27ab4b853f19a440ff1ed75257d81a210808d0 | bigcode/the-stack | train |
e2fd6d6775485d9440e71d57 | train | function | def assert_variable_occurrence(occurrences, source, usage, count):
times_found = 0
for occ in occurrences:
if occ.location == source and occ.usage == usage:
times_found += 1
assert_equal(times_found, count)
| def assert_variable_occurrence(occurrences, source, usage, count):
| times_found = 0
for occ in occurrences:
if occ.location == source and occ.usage == usage:
times_found += 1
assert_equal(times_found, count)
| " % (repr(occ.location), kw_name))
assert_equal(occ.location, expected_source,
'Occurrence not in the right place')
assert_equal(occ.usage, expected_usage, 'Usage not in the right place')
def assert_variable_occurrence(occurrences, source, usage, count):
| 64 | 64 | 56 | 15 | 49 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | assert_variable_occurrence | assert_variable_occurrence | 89 | 94 | 89 | 89 | 69878c68092bf87a789d84dc7d7d990ea89d59aa | bigcode/the-stack | train |
712a056d5efb811236b78519 | train | class | class FindOccurrencesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_ctrl, cls.namespace = TestCaseControllerWithSteps()
def test_no_occurrences(self):
find_occurrences = FindOccurrences('Keyword Name')
occurrences = self.test_ctrl.execute(find_occurrences)
... | class FindOccurrencesTest(unittest.TestCase):
@classmethod
| def setUpClass(cls):
cls.test_ctrl, cls.namespace = TestCaseControllerWithSteps()
def test_no_occurrences(self):
find_occurrences = FindOccurrences('Keyword Name')
occurrences = self.test_ctrl.execute(find_occurrences)
assert_equal([i for i in occurrences], [])
def test_occ... | _not_be_found(self):
self._assert_no_usages('testdocmatch')
def test_occurrences_in_keyword_documentation_should_not_be_found(self):
self._assert_no_usages('keyworddocmatch')
def _assert_usage(self, keyword, usage):
occ = list(self.ts2.execute(FindUsages(keyword)))
self.assertE... | 167 | 167 | 557 | 12 | 155 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | FindOccurrencesTest | FindOccurrencesTest | 245 | 303 | 245 | 247 | a43b4aa620879a5c4f2217abb23d09f94167516f | bigcode/the-stack | train |
d662a4797c96a5d629fb7304 | train | function | def TestCaseControllerWithSteps(project=None, source='some_suite.robot'):
tcf = TestCaseFile()
tcf.source = source
tcf.setting_table.suite_setup.name = 'Suite Setup Kw'
tcf.setting_table.test_setup.name = SUITE_TEST_SETUP_KEYWORD
tcf.setting_table.test_teardown.name = 'Test Teardown Kw'
tcf.sett... | def TestCaseControllerWithSteps(project=None, source='some_suite.robot'):
| tcf = TestCaseFile()
tcf.source = source
tcf.setting_table.suite_setup.name = 'Suite Setup Kw'
tcf.setting_table.test_setup.name = SUITE_TEST_SETUP_KEYWORD
tcf.setting_table.test_teardown.name = 'Test Teardown Kw'
tcf.setting_table.suite_teardown.name = 'Suite Teardown Kw'
tcf.setting_table.... | _SETUP_KEYWORD = 'Suite Setup Kw'
SUITE_TEST_SETUP_KEYWORD = 'Test Setup Kw'
SUITE_TEST_TEMPLATE_KEYWORD = 'Test Template Kw'
SUITE_NAME = 'Some Suite'
KEYWORD_IN_USERKEYWORD1 = 'Some Keyword'
EMBEDDED_ARGUMENTS_KEYWORD = "Pick '${fruit}' and '${action}' it"
def TestCaseControllerWithSteps(project=None, source='some_su... | 87 | 87 | 292 | 15 | 72 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | TestCaseControllerWithSteps | TestCaseControllerWithSteps | 38 | 62 | 38 | 38 | bc3c511621320e13c062aafb9763cada9c675bb2 | bigcode/the-stack | train |
14f3a14e70ccca04f45de71b | train | function | def _first_occurrence(test_ctrl, kw_name):
occurrences = test_ctrl.execute(FindOccurrences(kw_name))
if not occurrences:
raise AssertionError('No occurrences found for "%s"' % kw_name)
return next(occurrences)
| def _first_occurrence(test_ctrl, kw_name):
| occurrences = test_ctrl.execute(FindOccurrences(kw_name))
if not occurrences:
raise AssertionError('No occurrences found for "%s"' % kw_name)
return next(occurrences)
| _occurrences = 0
for source, usage, count in expected_occurrences:
assert_variable_occurrence(occurrences, source, usage, count)
processed_occurrences += count
assert_equal(processed_occurrences, len(occurrences))
def _first_occurrence(test_ctrl, kw_name):
| 64 | 64 | 52 | 11 | 53 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | _first_occurrence | _first_occurrence | 106 | 110 | 106 | 106 | eac3788c4dc9fae8fdcb7310542233002993207c | bigcode/the-stack | train |
c92f22fa6085b76eb4675ef3 | train | function | def _create_testcase(tcf):
testcase = tcf.testcase_table.add(TEST1_NAME)
for step in [[STEP1_KEYWORD, 'Hello'],
['Run Keyword', STEP2_ARGUMENT],
[USERKEYWORD2_NAME],
["Pick 'apple' and 'peel' it"]]:
testcase.add_step(step)
for_loop = testcase.add_fo... | def _create_testcase(tcf):
| testcase = tcf.testcase_table.add(TEST1_NAME)
for step in [[STEP1_KEYWORD, 'Hello'],
['Run Keyword', STEP2_ARGUMENT],
[USERKEYWORD2_NAME],
["Pick 'apple' and 'peel' it"]]:
testcase.add_step(step)
for_loop = testcase.add_for_loop(['FOR', '${i}', 'IN ... | = TestCaseFileController(tcf, project)
project._controller = tcf_ctrl
tctablectrl = TestCaseTableController(tcf_ctrl,
tcf.testcase_table)
return TestCaseController(tctablectrl, testcase), project._namespace
def _create_testcase(tcf):
| 64 | 64 | 146 | 8 | 55 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | _create_testcase | _create_testcase | 65 | 78 | 65 | 65 | 1766e01fda3c9d2b168811ebc0cc12c3741f8987 | bigcode/the-stack | train |
a7bc09e8d3a4f7d781799a4a | train | class | class RenameOccurrenceTest(unittest.TestCase):
def setUp(self):
self.test_ctrl, self.namespace = TestCaseControllerWithSteps()
self._steps_have_changed = False
self._testcase_settings_have_changed = False
self._name_has_changed = False
self._listeners_and_topics = [(self._st... | class RenameOccurrenceTest(unittest.TestCase):
| def setUp(self):
self.test_ctrl, self.namespace = TestCaseControllerWithSteps()
self._steps_have_changed = False
self._testcase_settings_have_changed = False
self._name_has_changed = False
self._listeners_and_topics = [(self._steps_changed,
... | , 'Steps', 1),
(self._case5.name, 'Steps', 1)))
check_for_variable_occurrences(
self._case1, "${ServerPort}", ((self._case1.name, 'Steps', 1),
(self._kw1.name, 'Steps', 1)))
def test_occurrences_builtin_varia... | 255 | 256 | 1,942 | 8 | 247 | chandrapola/RIDE | utest/controller/test_occurrences.py | Python | RenameOccurrenceTest | RenameOccurrenceTest | 399 | 597 | 399 | 400 | f9a3df4140baad3e14ac570c8199afae40f0dd87 | bigcode/the-stack | train |
55407af4616a341e346d28e9 | train | function | def physical_bounds(x, lb, ub):
'''
:param x : normalized point
:param lb: real lower bound
:param ub: real upper bound
:return: physical scale of the point
'''
x_phy = np.copy(x)
n = len(lb) # n represents dimensions
try:
m = x_phy.shape[1] # m represents the number of sam... | def physical_bounds(x, lb, ub):
| '''
:param x : normalized point
:param lb: real lower bound
:param ub: real upper bound
:return: physical scale of the point
'''
x_phy = np.copy(x)
n = len(lb) # n represents dimensions
try:
m = x_phy.shape[1] # m represents the number of sample data
except:
m =... | sample data
x = np.copy(x0)
for i in range(n):
for j in range(m):
x[i][j] = (x[i][j] - lb[i]) / (ub[i] - lb[i])
return x
def physical_bounds(x, lb, ub):
| 64 | 64 | 148 | 9 | 54 | kimukook/SDOGS | dogs/Utils.py | Python | physical_bounds | physical_bounds | 140 | 157 | 140 | 140 | 2a1dd0b7883b195a4157a389b889f2021f4f1ca5 | bigcode/the-stack | train |
434b88c53068705e7bc6ab98 | train | function | def search_bounds(xi):
n = xi.shape[0]
srch_bnd = []
for i in range(n):
rimin = np.min(xi[i, :])
rimax = np.max(xi[i, :])
temp = (rimin, rimax)
srch_bnd.append(temp)
simplex_bnds = tuple(srch_bnd)
return simplex_bnds
| def search_bounds(xi):
| n = xi.shape[0]
srch_bnd = []
for i in range(n):
rimin = np.min(xi[i, :])
rimax = np.max(xi[i, :])
temp = (rimin, rimax)
srch_bnd.append(temp)
simplex_bnds = tuple(srch_bnd)
return simplex_bnds
| - lb[i]) + lb[i]
return x_phy
def fun_eval(fun, lb, ub, x):
x = x.reshape(-1, 1)
x_phy = physical_bounds(x, lb, ub)
y = fun(x_phy)
return y
def search_bounds(xi):
| 64 | 64 | 87 | 6 | 57 | kimukook/SDOGS | dogs/Utils.py | Python | search_bounds | search_bounds | 167 | 176 | 167 | 167 | 65266116adfe458ca490b1336343e418a14b3454 | bigcode/the-stack | train |
ef5f3fcf8c4cb3c1bb6aee19 | train | function | def safe_eval_estimate(xE, y_safe, L_safe, x):
x = x.reshape(-1, 1)
val, idx, x_nn = mindis(x, xE)
safe_estimate = y_safe[:, idx] - L_safe * val
if (safe_estimate > 0).all():
return True
else:
return False
| def safe_eval_estimate(xE, y_safe, L_safe, x):
| x = x.reshape(-1, 1)
val, idx, x_nn = mindis(x, xE)
safe_estimate = y_safe[:, idx] - L_safe * val
if (safe_estimate > 0).all():
return True
else:
return False
| L_safe = 4
x0 = np.array([[0.25], [0.75]])
M = 2
return safe_fun, x0, L_safe, M, safe_fun_name
def safe_eval_estimate(xE, y_safe, L_safe, x):
| 64 | 64 | 81 | 16 | 47 | kimukook/SDOGS | dogs/Utils.py | Python | safe_eval_estimate | safe_eval_estimate | 519 | 526 | 519 | 519 | cabac969c9feb85d497cc88a10f325afea2a3995 | bigcode/the-stack | train |
d78ef3b0b1c1e67878d714a2 | train | function | def test_fun(fun_arg, n):
fun = lb = ub = xmin = y0 = fname = []
if fun_arg == 1: # 2D test function: Goldstein-price
# Notice, here I take ln(y)
lb = -2 * np.ones((2, 1))
ub = 2 * np.ones((2, 1))
fun = lambda x: np.log((1+(x[0]+x[1]+1)**2*(19-14*x[0]+3*x[0]**2-14*x[1]+6*x[0]*x[... | def test_fun(fun_arg, n):
| fun = lb = ub = xmin = y0 = fname = []
if fun_arg == 1: # 2D test function: Goldstein-price
# Notice, here I take ln(y)
lb = -2 * np.ones((2, 1))
ub = 2 * np.ones((2, 1))
fun = lambda x: np.log((1+(x[0]+x[1]+1)**2*(19-14*x[0]+3*x[0]**2-14*x[1]+6*x[0]*x[1]+3*x[1]**2))*\
... | /questions/2723294/how-to-determine-the-equation-of-the-hyperplane-that-contains-several-points
:param points: Points is an n by n square matrix. Each column represents a data point.
:return: A and b (both 2 dimensional array) that satisfy Ax = b.
'''
n, m = points.shape # n dimension of points. m sho... | 256 | 256 | 2,983 | 8 | 247 | kimukook/SDOGS | dogs/Utils.py | Python | test_fun | test_fun | 226 | 405 | 226 | 226 | 67bc1992c0014f6b3080031dcb1f19a44c73b9da | bigcode/the-stack | train |
8fdfa13c6f398d4f47acef27 | train | function | def quadrotor_desired_trajectory():
x_des = np.arctan(5 * np.linspace(0, 4, 350) - 2.5) + 1.6
# t = np.linspace(0, 5, 350)
# x1 = t[0:70] ** 2
# x2 = -(t[70:140] - 2) ** 2 + 2
# length = t.shape[0] - x1.shape[0] - x2.shape[0]
# x3 = x2[-1] * np.ones(length)
# x_des = np.hstack((x1, x2, x3))... | def quadrotor_desired_trajectory():
| x_des = np.arctan(5 * np.linspace(0, 4, 350) - 2.5) + 1.6
# t = np.linspace(0, 5, 350)
# x1 = t[0:70] ** 2
# x2 = -(t[70:140] - 2) ** 2 + 2
# length = t.shape[0] - x1.shape[0] - x2.shape[0]
# x3 = x2[-1] * np.ones(length)
# x_des = np.hstack((x1, x2, x3))
y_des = np.linspace(0, 2, 350)... | , y_des = quadrotor_desired_trajectory()
x = quadrotor_trajectory_calculator(k)
cost = np.linalg.norm(x - x_des)
safe_cost = 3.2 - np.max(x)
return cost, safe_cost
def quadrotor_desired_trajectory():
| 64 | 64 | 175 | 9 | 54 | kimukook/SDOGS | dogs/Utils.py | Python | quadrotor_desired_trajectory | quadrotor_desired_trajectory | 417 | 428 | 417 | 417 | 5aed4876862244314a64a26e9e558d793229e1f7 | bigcode/the-stack | train |
4537029af271793007559710 | train | function | def bounds(bnd1, bnd2, n):
# find vertex of domain for a box domain.
# INPUT: n: dimension, bnd1: lower bound, bnd2: upper bound.
# OUTPUT: vertex of domain. 2^n number vector of n-D.
# Example:
# n = 3
# bnd1 = np.zeros((n, 1))
# bnd2 = np.ones((n, 1))
... | def bounds(bnd1, bnd2, n):
# find vertex of domain for a box domain.
# INPUT: n: dimension, bnd1: lower bound, bnd2: upper bound.
# OUTPUT: vertex of domain. 2^n number vector of n-D.
# Example:
# n = 3
# bnd1 = np.zeros((n, 1))
# bnd2 = np.ones((n, 1))
... | assert bnd1.shape == (n, 1) and bnd2.shape == (n, 1), 'lb(bnd1) and ub(bnd2) should be 2 dimensional vector.'
bnds = np.kron(np.ones((1, 2 ** n)), bnd2)
for ii in range(n):
tt = np.mod(np.arange(2 ** n) + 1, 2 ** (n - ii)) <= 2 ** (n - ii - 1) - 1
bnds[ii, tt] = bnd1[ii]
return bnds
| def bounds(bnd1, bnd2, n):
# find vertex of domain for a box domain.
# INPUT: n: dimension, bnd1: lower bound, bnd2: upper bound.
# OUTPUT: vertex of domain. 2^n number vector of n-D.
# Example:
# n = 3
# bnd1 = np.zeros((n, 1))
# bnd2 = np.ones((n, 1))
... | 159 | 86 | 289 | 159 | 0 | kimukook/SDOGS | dogs/Utils.py | Python | bounds | bounds | 38 | 55 | 38 | 49 | 2e06fdd040860d83156091dfa5f3a730570fcbf3 | bigcode/the-stack | train |
a2f73e7e638ab9f1ee3539f3 | train | function | def unique_data(x):
"""
Outline
Find the column-wise unique elements in the given data set x
----------
Parameters
:param x: n-by-N 2d np.ndarray;
----------
Output
:return : n-by-(*) 2d np.ndarray;
"""
_x = np.ascontiguousarray(x.T)
unique_x = np.unique(_x.view([(... | def unique_data(x):
| """
Outline
Find the column-wise unique elements in the given data set x
----------
Parameters
:param x: n-by-N 2d np.ndarray;
----------
Output
:return : n-by-(*) 2d np.ndarray;
"""
_x = np.ascontiguousarray(x.T)
unique_x = np.unique(_x.view([('', _x.dtype)] * _x.... | 1, 1)
val, idx, x_nn = mindis(x, xE)
safe_estimate = y_safe[:, idx] - L_safe * val
if (safe_estimate > 0).all():
return True
else:
return False
def unique_data(x):
| 64 | 64 | 130 | 5 | 58 | kimukook/SDOGS | dogs/Utils.py | Python | unique_data | unique_data | 529 | 546 | 529 | 529 | d32610f00fca4230bd4881eafe4cd6cf71a2e5f4 | bigcode/the-stack | train |
272a4e806ce75746d4af09ef | train | function | def quadrotor_trajectory_calculator(k):
x_des, y_des = quadrotor_desired_trajectory()
n = x_des.shape[0]
xdot_des, ydot_des = reference_velocity(x_des, y_des)
x = np.zeros(n)
y = np.zeros(n)
xdot = np.zeros(xdot_des.shape[0])
ydot = np.zeros(ydot_des.shape[0])
x[0] = x_des[0]
... | def quadrotor_trajectory_calculator(k):
| x_des, y_des = quadrotor_desired_trajectory()
n = x_des.shape[0]
xdot_des, ydot_des = reference_velocity(x_des, y_des)
x = np.zeros(n)
y = np.zeros(n)
xdot = np.zeros(xdot_des.shape[0])
ydot = np.zeros(ydot_des.shape[0])
x[0] = x_des[0]
y[0] = y_des[0]
g = 9.8
dt = ... | 0:70] ** 2
# x2 = -(t[70:140] - 2) ** 2 + 2
# length = t.shape[0] - x1.shape[0] - x2.shape[0]
# x3 = x2[-1] * np.ones(length)
# x_des = np.hstack((x1, x2, x3))
y_des = np.linspace(0, 2, 350)
return x_des, y_des
def quadrotor_trajectory_calculator(k):
| 120 | 120 | 403 | 10 | 109 | kimukook/SDOGS | dogs/Utils.py | Python | quadrotor_trajectory_calculator | quadrotor_trajectory_calculator | 431 | 461 | 431 | 431 | fc25f9afad05c3a802905a24ddbf5d92a3e2316e | bigcode/the-stack | train |
03c4e6758bc20ca19e9adc21 | train | function | def normalize_bounds(x0, lb, ub):
n = len(lb) # n represents dimensions
m = x0.shape[1] # m represents the number of sample data
x = np.copy(x0)
for i in range(n):
for j in range(m):
x[i][j] = (x[i][j] - lb[i]) / (ub[i] - lb[i])
return x
| def normalize_bounds(x0, lb, ub):
| n = len(lb) # n represents dimensions
m = x0.shape[1] # m represents the number of sample data
x = np.copy(x0)
for i in range(n):
for j in range(m):
x[i][j] = (x[i][j] - lb[i]) / (ub[i] - lb[i])
return x
| # print(xC)
R2 = (np.sum(D ** 2, axis=0) - 4 * a * c) / (4.0 * a ** 2)
# print(R2)
return R2, xC
def normalize_bounds(x0, lb, ub):
| 64 | 64 | 93 | 10 | 53 | kimukook/SDOGS | dogs/Utils.py | Python | normalize_bounds | normalize_bounds | 130 | 137 | 130 | 130 | 29e3fc7cad01299ded5f70be13da690ec3163ecc | bigcode/the-stack | train |
642cac640aaee0765bd38b08 | train | function | def test_safe_fun(safe_fun_arg, n):
# ============================================================
# NOTICE: The safe initial x0 must be on the initial mesh grid!
# ============================================================
# Lower bound and upper bound of the parameter space should be controlled by
... | def test_safe_fun(safe_fun_arg, n):
# ============================================================
# NOTICE: The safe initial x0 must be on the initial mesh grid!
# ============================================================
# Lower bound and upper bound of the parameter space should be controlled by
... | safe_fun = safe_fun_name = x0 = L_safe = M = []
if safe_fun_arg == 1: # nD sinusoid safety function
# The global minimum is included in the safe region for schwefel.
# This safety function is the sin wave for each direction.
# The safe region is the union of [.1, .9] for each direction.... | + ydot[i] * dt
return x
def reference_velocity(x, y):
n = x.shape[0]
dt = 5 / n
xdot = np.zeros(n)
ydot = np.zeros(n)
for i in range(1, n):
xdot[i] = (x[i] - x[i - 1]) / dt
ydot[i] = (y[i] - y[i - 1]) / dt
return xdot, ydot
def test_safe_fun(safe_fun_arg, n):
# ======... | 168 | 168 | 562 | 59 | 108 | kimukook/SDOGS | dogs/Utils.py | Python | test_safe_fun | test_safe_fun | 475 | 516 | 475 | 480 | c7e8a35e29d1ca105fb2a50d2f1c99a4a818a87e | bigcode/the-stack | train |
f48f2951bd650b890895b649 | train | function | def modichol(A, alpha, beta):
# Modified Cholesky decomposition code for making the Hessian matrix PSD.
# Author: Shahoruz Alimohammadi
# Modified: Jan., 2017
n = A.shape[1] # size of A
L = np.identity(n)
####################
D = np.zeros((n, 1))
c = np.zeros((n, n))
#########... | def modichol(A, alpha, beta):
# Modified Cholesky decomposition code for making the Hessian matrix PSD.
# Author: Shahoruz Alimohammadi
# Modified: Jan., 2017
| n = A.shape[1] # size of A
L = np.identity(n)
####################
D = np.zeros((n, 1))
c = np.zeros((n, n))
######################
D[0] = np.max(np.abs(A[0, 0]), alpha)
c[:, 0] = A[:, 0]
L[1:n, 0] = c[1:n, 0] / D[0]
for j in range(1, n - 1):
c[j, j] = A[j, j] - (np.dot... | 1)
assert xi.shape[1] != 0, 'The set of Evaluated points has size 0!'
dis = np.linalg.norm(xi-x, axis=0)
val = np.min(dis)
idx = np.argmin(dis)
xmin = xi[:, idx].reshape(-1, 1)
return val, idx, xmin
def modichol(A, alpha, beta):
# Modified Cholesky decomposition code for making the Hessia... | 129 | 129 | 430 | 52 | 76 | kimukook/SDOGS | dogs/Utils.py | Python | modichol | modichol | 74 | 98 | 74 | 77 | 134fe63003d999b7879e4ee68fdba31aeaf4d369 | bigcode/the-stack | train |
1b2269520f83fc12028153dc | train | function | def quadrotor_cost_function(k):
k = k.reshape(-1, 1)
x_des, y_des = quadrotor_desired_trajectory()
x = quadrotor_trajectory_calculator(k)
cost = np.linalg.norm(x - x_des)
safe_cost = 3.2 - np.max(x)
return cost, safe_cost
| def quadrotor_cost_function(k):
| k = k.reshape(-1, 1)
x_des, y_des = quadrotor_desired_trajectory()
x = quadrotor_trajectory_calculator(k)
cost = np.linalg.norm(x - x_des)
safe_cost = 3.2 - np.max(x)
return cost, safe_cost
| min is defined within the safe region, the maximum position of the trajectory < 3.3
y0 = 1.2210
xmin = np.array([0, 0])
return fun, lb, ub, y0, xmin, fname
def quadrotor_cost_function(k):
| 64 | 64 | 77 | 8 | 55 | kimukook/SDOGS | dogs/Utils.py | Python | quadrotor_cost_function | quadrotor_cost_function | 408 | 414 | 408 | 408 | 0625d0b31b50a4542762e0e94f08d9811fff9f12 | bigcode/the-stack | train |
35df2d2e78f45c51281535e6 | train | function | def search_simplex_bounds(xi):
'''
Return the n+1 constraints defined by n by n+1 Delaunay simplex xi.
The optimization for finding minimizer of Sc should be within the Delaunay simplex.
:param xi: xi should be (n) by (n+1). Each column denotes a data point.
:return: Ax >= b constraints.
A: n+1 ... | def search_simplex_bounds(xi):
| '''
Return the n+1 constraints defined by n by n+1 Delaunay simplex xi.
The optimization for finding minimizer of Sc should be within the Delaunay simplex.
:param xi: xi should be (n) by (n+1). Each column denotes a data point.
:return: Ax >= b constraints.
A: n+1 by n
b: n+1 by 1
'''
... | )
y = fun(x_phy)
return y
def search_bounds(xi):
n = xi.shape[0]
srch_bnd = []
for i in range(n):
rimin = np.min(xi[i, :])
rimax = np.max(xi[i, :])
temp = (rimin, rimax)
srch_bnd.append(temp)
simplex_bnds = tuple(srch_bnd)
return simplex_bnds
def search_simp... | 107 | 107 | 359 | 8 | 98 | kimukook/SDOGS | dogs/Utils.py | Python | search_simplex_bounds | search_simplex_bounds | 179 | 201 | 179 | 179 | d09573b43a65ea253d80ae39b30ac35de9b702f5 | bigcode/the-stack | train |
bff26178b167871394ca6840 | train | function | def hyperplane_equations(points):
'''
Return the equation of n points hyperplane in n dimensional space.
Reference website:
https://math.stackexchange.com/questions/2723294/how-to-determine-the-equation-of-the-hyperplane-that-contains-several-points
:param points: Points is an n by n square matrix... | def hyperplane_equations(points):
| '''
Return the equation of n points hyperplane in n dimensional space.
Reference website:
https://math.stackexchange.com/questions/2723294/how-to-determine-the-equation-of-the-hyperplane-that-contains-several-points
:param points: Points is an n by n square matrix. Each column represents a data po... | ) < b[i, :]:
# At this point, the simplex stays at the negative side of the equation, assign minus sign to A and b.
A[i, :] = np.copy(-A[i, :].reshape(-1, 1).T)
b[i, 0] = np.copy(-b[i, :])
return A, b
def hyperplane_equations(points):
| 84 | 84 | 282 | 7 | 76 | kimukook/SDOGS | dogs/Utils.py | Python | hyperplane_equations | hyperplane_equations | 204 | 223 | 204 | 204 | 0803bf65ec4caac1dcda1f053951d2f4f8db0e3d | bigcode/the-stack | train |
a9991f953f9c98fef65aac21 | train | function | def fun_eval(fun, lb, ub, x):
x = x.reshape(-1, 1)
x_phy = physical_bounds(x, lb, ub)
y = fun(x_phy)
return y
| def fun_eval(fun, lb, ub, x):
| x = x.reshape(-1, 1)
x_phy = physical_bounds(x, lb, ub)
y = fun(x_phy)
return y
| m = x_phy.shape[0]
for i in range(n):
for j in range(m):
x_phy[i][j] = (x[i][j])*(ub[i] - lb[i]) + lb[i]
return x_phy
def fun_eval(fun, lb, ub, x):
| 64 | 64 | 45 | 11 | 52 | kimukook/SDOGS | dogs/Utils.py | Python | fun_eval | fun_eval | 160 | 164 | 160 | 160 | 789ac3a0e149f685efbc70b89d252c3da8b51d97 | bigcode/the-stack | train |
9e1b09fcb862c1580e03a800 | train | function | def reference_velocity(x, y):
n = x.shape[0]
dt = 5 / n
xdot = np.zeros(n)
ydot = np.zeros(n)
for i in range(1, n):
xdot[i] = (x[i] - x[i - 1]) / dt
ydot[i] = (y[i] - y[i - 1]) / dt
return xdot, ydot
| def reference_velocity(x, y):
| n = x.shape[0]
dt = 5 / n
xdot = np.zeros(n)
ydot = np.zeros(n)
for i in range(1, n):
xdot[i] = (x[i] - x[i - 1]) / dt
ydot[i] = (y[i] - y[i - 1]) / dt
return xdot, ydot
| ] = ydot[i-1] + yddot * dt
x[i] = x[i-1] + xdot[i] * dt
y[i] = y[i-1] + ydot[i] * dt
return x
def reference_velocity(x, y):
| 64 | 64 | 97 | 7 | 56 | kimukook/SDOGS | dogs/Utils.py | Python | reference_velocity | reference_velocity | 464 | 472 | 464 | 464 | 42bf2a6096968b5c000aeb9a3d962df5b04a1bae | bigcode/the-stack | train |
d865ea22533f79a4f05c1184 | train | function | def mindis(x, xi):
'''
calculates the minimum distance from all the existing points
:param x: x the new point
:param xi: xi all the previous points
:return: [ymin ,xmin ,index]
'''
x = x.reshape(-1, 1)
assert xi.shape[1] != 0, 'The set of Evaluated points has size 0!'
dis = np.linalg... | def mindis(x, xi):
| '''
calculates the minimum distance from all the existing points
:param x: x the new point
:param xi: xi all the previous points
:return: [ymin ,xmin ,index]
'''
x = x.reshape(-1, 1)
assert xi.shape[1] != 0, 'The set of Evaluated points has size 0!'
dis = np.linalg.norm(xi-x, axis=0)... | tt = np.mod(np.arange(2 ** n) + 1, 2 ** (n - ii)) <= 2 ** (n - ii - 1) - 1
bnds[ii, tt] = bnd1[ii]
return bnds
def mindis(x, xi):
| 64 | 64 | 140 | 7 | 56 | kimukook/SDOGS | dogs/Utils.py | Python | mindis | mindis | 58 | 71 | 58 | 58 | 77635eb02d10b3057b875a82ff08b9ecde6f04c0 | bigcode/the-stack | train |
f3d38a4d2c4345ef034b7030 | train | function | def circhyp(x, N):
# circhyp Circumhypersphere of simplex
# [xC, R2] = circhyp(x, N) calculates the coordinates of the circumcenter
# and the square of the radius of the N-dimensional hypersphere
# encircling the simplex defined by its N+1 vertices.
# Author: Shahoruz Alimohammadi
# ... | def circhyp(x, N):
# circhyp Circumhypersphere of simplex
# [xC, R2] = circhyp(x, N) calculates the coordinates of the circumcenter
# and the square of the radius of the N-dimensional hypersphere
# encircling the simplex defined by its N+1 vertices.
# Author: Shahoruz Alimohammadi
# ... | test = np.sum(np.transpose(x) ** 2, axis=1)
test = test[:, np.newaxis]
m1 = np.concatenate((np.matrix((x.T ** 2).sum(axis=1)), x))
M = np.concatenate((np.transpose(m1), np.matrix(np.ones((N + 1, 1)))), axis=1)
a = np.linalg.det(M[:, 1:N + 2])
c = (-1.0) ** (N + 1) * np.linalg.det(M[:, 0:N + 1])
... | .T)
def circhyp(x, N):
# circhyp Circumhypersphere of simplex
# [xC, R2] = circhyp(x, N) calculates the coordinates of the circumcenter
# and the square of the radius of the N-dimensional hypersphere
# encircling the simplex defined by its N+1 vertices.
# Author: Shahoruz Alimohammadi
... | 114 | 114 | 383 | 112 | 2 | kimukook/SDOGS | dogs/Utils.py | Python | circhyp | circhyp | 101 | 127 | 101 | 109 | d7c8df25966005bae691691acde9db730c128cec | bigcode/the-stack | train |
4a7e116a988386f87b8f75e5 | train | class | class Amavis(ModoExtension):
"""The Amavis extension."""
name = "modoboa_amavis"
label = ugettext_lazy("Amavis frontend")
version = __version__
description = ugettext_lazy("Simple amavis management frontend")
url = "quarantine"
available_for_topredirection = True
def load(self):
... | class Amavis(ModoExtension):
| """The Amavis extension."""
name = "modoboa_amavis"
label = ugettext_lazy("Amavis frontend")
version = __version__
description = ugettext_lazy("Simple amavis management frontend")
url = "quarantine"
available_for_topredirection = True
def load(self):
param_tools.registry.add("g... | modoboa.admin.models import Domain
from modoboa.core.extensions import ModoExtension, exts_pool
from modoboa.parameters import tools as param_tools
from . import __version__, forms
from .lib import create_user_and_policy, create_user_and_use_policy
class Amavis(ModoExtension):
| 64 | 64 | 189 | 7 | 56 | pavinjosdev/modoboa-amavis | modoboa_amavis/modo_extension.py | Python | Amavis | Amavis | 24 | 45 | 24 | 24 | 20e07c1415f88114c4c1ab15aa1dd401d794eef1 | bigcode/the-stack | train |
42db5e39d9081057524b8eae | train | function | def plot_pointing(mktable, gtitable):
time, pointing, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['ANG_DIST'], gtitable)
colornames, cmap, norm = gti_colormap()
plot.scatter(time, pointing, c = np.fmod(cc,len(colornames)), cmap = cmap,
norm=norm, marker = '+', label='Pointing Offset'... | def plot_pointing(mktable, gtitable):
| time, pointing, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['ANG_DIST'], gtitable)
colornames, cmap, norm = gti_colormap()
plot.scatter(time, pointing, c = np.fmod(cc,len(colornames)), cmap = cmap,
norm=norm, marker = '+', label='Pointing Offset')
plot.legend(loc = 2)
plot.yl... | plot.grid(True)
plot.yticks([0.0, 45.0, 90.0, 135.0, 180.0])
plot.ylabel('Angle (deg)')
return
#--------------------------POINTING---------------------------------------------
def plot_pointing(mktable, gtitable):
| 64 | 64 | 148 | 11 | 53 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_pointing | plot_pointing | 653 | 666 | 653 | 653 | e9a1a6faaacdc329b5ee411ff05d1a174c30f301 | bigcode/the-stack | train |
8e8ec55405921576fc99ed67 | train | function | def apply_gti(etable, gtitable):
mets = etable['MET']
idx = np.where(np.logical_and(mets>gtitable['START'][0],mets<gtitable['STOP'][0]))
goodlist = [ etable[idx] ]
for ii in range(1,len(gtitable['START'])):
idx = np.where(np.logical_and(mets>gtitable['START'][ii],mets<gtitable['STOP'][ii]))
... | def apply_gti(etable, gtitable):
| mets = etable['MET']
idx = np.where(np.logical_and(mets>gtitable['START'][0],mets<gtitable['STOP'][0]))
goodlist = [ etable[idx] ]
for ii in range(1,len(gtitable['START'])):
idx = np.where(np.logical_and(mets>gtitable['START'][ii],mets<gtitable['STOP'][ii]))
goodlist.append(etable[idx])
... | (args.basename),np.transpose([etable['MET'], etable['PI'],phases]))
plot.ylabel('Counts')
plot.xlabel('Pulse Phase')
plot.title('Pulse Profile')
return
#-------------------------OVERSHOOT RATE FOR RATIO------------------------------
def apply_gti(etable, gtitable):
| 64 | 64 | 118 | 10 | 54 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | apply_gti | apply_gti | 495 | 503 | 495 | 495 | 4aa4097f59257c672534114cec376b68f76217cd | bigcode/the-stack | train |
f5cc83b49f76e23b3ae86e4d | train | function | def plot_resetrate(IDS, reset_rates):
'Plots reset rates'
reset = plot.bar(IDS, reset_rates, width = .85)
plot.title('Reset Rate by Detector')
plot.ylabel('Reset Rate [Hz]')
plot.xlabel('DET_ID')
| def plot_resetrate(IDS, reset_rates):
| 'Plots reset rates'
reset = plot.bar(IDS, reset_rates, width = .85)
plot.title('Reset Rate by Detector')
plot.ylabel('Reset Rate [Hz]')
plot.xlabel('DET_ID')
| _COUNT
# given as a 7x8 matrix instead of 56 array in the mktable
for i in range(len(IDS)):
nresets[i] = MPU_ud_only[:,i].sum()
return nresets
def plot_resetrate(IDS, reset_rates):
| 64 | 64 | 58 | 11 | 52 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_resetrate | plot_resetrate | 723 | 728 | 723 | 723 | 0bd8933570b32d7a8554104d8a5b6d8ad95c4ae7 | bigcode/the-stack | train |
daaa5c0c14b87f3614cff9aa | train | function | def plot_overshoot(mktable, ovbintable, gtitable, args):
#etime, overshoot, cc = convert_to_elapsed_goodtime(hkmet, overshootrate, gtitable)
etime, overshoot, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['NUM_FPM_ON']*mktable['FPM_OVERONLY_COUNT'], gtitable)
# Delete the nan values from under... | def plot_overshoot(mktable, ovbintable, gtitable, args):
#etime, overshoot, cc = convert_to_elapsed_goodtime(hkmet, overshootrate, gtitable)
| etime, overshoot, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['NUM_FPM_ON']*mktable['FPM_OVERONLY_COUNT'], gtitable)
# Delete the nan values from undershoot and cc so they don't plot
etimeNan = np.where(np.isnan(overshoot))
ovtime=np.delete(etime,etimeNan)
overshoot=np.delete(overshoo... | _like(vals[idx],dtype=np.float)+np.float(ii))
# Returns the arrays of elapsed times, values, and an array of what segment it is in, used for setting plot colors by GTI segment
return etimes, goodvals, cc
#def plot_overshoot(etable, overshootrate, gtitable, args, hkmet, bothrate, mktable):
def plot_overshoot(m... | 125 | 125 | 418 | 44 | 81 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_overshoot | plot_overshoot | 543 | 573 | 543 | 545 | 4060a2499f567a4c073ab2d0e68be3c120367629 | bigcode/the-stack | train |
f474cd16aed3c46a24e111ca | train | function | def plot_slowfast(etable,args):
'Scatter plot of PI and fast PHA, highlighting points above ratio cut'
log.info('Counting slow and fast')
# First do some counts
nfastonly = np.count_nonzero(np.logical_and(etable['EVENT_FLAGS'][:,FLAG_FAST],
np.logical_not(etabl... | def plot_slowfast(etable,args):
| 'Scatter plot of PI and fast PHA, highlighting points above ratio cut'
log.info('Counting slow and fast')
# First do some counts
nfastonly = np.count_nonzero(np.logical_and(etable['EVENT_FLAGS'][:,FLAG_FAST],
np.logical_not(etable['EVENT_FLAGS'][:,FLAG_SLOW])))... | [0], xmax=bins[-1], linestyle='dashed', label = label)
bininfo = "bin size = {} sec".format(binsize)
plot.annotate(bininfo, xy=(0.02, 0.85), xycoords='axes fraction')
#plot.legend(loc = 4)
if lclog:
plot.yscale('log')
plot.ylim(ymin=0.1)
# Defau... | 244 | 244 | 814 | 9 | 235 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_slowfast | plot_slowfast | 212 | 269 | 212 | 212 | a4ccf8975328f44863466cdfe1fd203c829fb758 | bigcode/the-stack | train |
bcb01586aa5bfb77ed8c45b2 | train | function | def find_hot_detectors(etable):
# Compute which detectors to mask on the fly
det_events = event_counter(etable)
# Remove detector with no events
#temp_events = np.delete(det_events, np.where(det_events == 0))
stats = sigma_clipped_stats(det_events,maxiters=3,sigma_lower=3,sigma_upper=3)
bad_dets... | def find_hot_detectors(etable):
# Compute which detectors to mask on the fly
| det_events = event_counter(etable)
# Remove detector with no events
#temp_events = np.delete(det_events, np.where(det_events == 0))
stats = sigma_clipped_stats(det_events,maxiters=3,sigma_lower=3,sigma_upper=3)
bad_dets = IDS[det_events > stats[0]+3.0*stats[2]]
log.info('Detector Count Mean {0},... | = np.zeros_like(IDS)
for i, det_id in enumerate(IDS):
IDevents[i] = np.count_nonzero(etable['DET_ID'] == det_id)
return IDevents
def find_hot_detectors(etable):
# Compute which detectors to mask on the fly
| 64 | 64 | 162 | 19 | 44 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | find_hot_detectors | find_hot_detectors | 33 | 44 | 33 | 34 | d3a4eaa3624f88faf7d1cbf3552b970ee0b81bcc | bigcode/the-stack | train |
3c3853dd32fc00ce3d5e5e8b | train | function | def plot_cor(mktable, gtitable):
time, cor, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['COR_SAX'], gtitable)
#time, lon, cc2 = convert_to_elapsed_goodtime(mktable['TIME'], mktable['SAT_LON'], gtitable)
colornames, cmap, norm = gti_colormap()
plot.scatter(time, cor, c=np.fmod(cc,len(colo... | def plot_cor(mktable, gtitable):
| time, cor, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['COR_SAX'], gtitable)
#time, lon, cc2 = convert_to_elapsed_goodtime(mktable['TIME'], mktable['SAT_LON'], gtitable)
colornames, cmap, norm = gti_colormap()
plot.scatter(time, cor, c=np.fmod(cc,len(colornames)), norm=norm,
cmap... | = 'Longitude')
plot.legend(loc = 2)
plot.ylim((-60.0,60.0))
plot.xlabel('Elapsed Time (s)', labelpad = 1)
plot.grid(True)
plot.ylabel('Degrees')
return
def plot_cor(mktable, gtitable):
| 64 | 64 | 215 | 10 | 53 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_cor | plot_cor | 684 | 699 | 684 | 684 | 47c80ffd6b1a2cfaad82c0bf1ab11e19e567fe3a | bigcode/the-stack | train |
391a606ad12896c852a0382b | train | function | def pulse_profile(ax, etable, args):
if (args.orb is None) or (args.par is None):
log.warning('You did not specify orbfile or parfile')
log.info('Please input files for orb and par with --orb and --par')
return
import pint
import astropy.io.fits as pyfits
from astropy.time import... | def pulse_profile(ax, etable, args):
| if (args.orb is None) or (args.par is None):
log.warning('You did not specify orbfile or parfile')
log.info('Please input files for orb and par with --orb and --par')
return
import pint
import astropy.io.fits as pyfits
from astropy.time import TimeDelta
import pint.toa, pint.... | OGRAM------------------
def plot_deadtime(etable):
'Plot histogram of detector deadtime in microseconds.'
us = etable['DEADTIME']*1.0e6
# Bin at 1 us resolution
max = np.floor(us.max())+1
plot.hist(us,range=(0.0,max), bins=int(max),log=True)
#plot.ticklabel_format(style = 'sci', axis='x', scilim... | 232 | 232 | 776 | 10 | 222 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | pulse_profile | pulse_profile | 423 | 492 | 423 | 423 | 50edd729d7c2ec29b48678d7d70cb8a01a4b5eb3 | bigcode/the-stack | train |
d904a8aed1650b596fc02d8f | train | function | def plot_total_count_hist(etable, ax_rate, ax_counts):
'Plots event count per ID as a histogram with event count and countrate on y axes'
num_events, colors = hist_use(etable)
tc = ax_counts.bar(IDS, num_events, color = colors)
ax_rate.set_ylabel('c/s')
cntmin, cntmax = ax_counts.get_ylim()
a... | def plot_total_count_hist(etable, ax_rate, ax_counts):
| 'Plots event count per ID as a histogram with event count and countrate on y axes'
num_events, colors = hist_use(etable)
tc = ax_counts.bar(IDS, num_events, color = colors)
ax_rate.set_ylabel('c/s')
cntmin, cntmax = ax_counts.get_ylim()
ax_rate.set_ylim((cntmin/etable.meta['EXPOSURE'],cntmax/... | #diff = np.array(IDevents,dtype=np.float)-np.mean(temp)
#idx = np.where(diff>2.0*stdev)[0]
#colors[idx] = 'r'
return IDevents, colors
def plot_total_count_hist(etable, ax_rate, ax_counts):
| 64 | 64 | 195 | 14 | 49 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_total_count_hist | plot_total_count_hist | 72 | 90 | 72 | 72 | e4a643055eddd3a27ee04451b516d9ef8ab04c95 | bigcode/the-stack | train |
8ff5490435b058ad31ab813d | train | function | def pulse_profile_fixed(etable, F0):
phase = np.fmod((etable['MET']-etable['MET'][0])*F0,1.0)
plot.hist(phase,bins=32)
plot.ylabel('Counts')
plot.xlabel('Pulse Phase')
plot.title('Pulse Profile (F0={0:.6f})'.format(F0))
| def pulse_profile_fixed(etable, F0):
| phase = np.fmod((etable['MET']-etable['MET'][0])*F0,1.0)
plot.hist(phase,bins=32)
plot.ylabel('Counts')
plot.xlabel('Pulse Phase')
plot.title('Pulse Profile (F0={0:.6f})'.format(F0))
| ', axis='x', scilimits = (0,0))
plot.title('Histogram of deadtime')
plot.xlabel('Deadtime [microseconds]')
plot.ylabel('Frequency [occurrences]')
return
#-------------------------PULSE PROFILE----------------------------------
def pulse_profile_fixed(etable, F0):
| 64 | 64 | 78 | 10 | 54 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | pulse_profile_fixed | pulse_profile_fixed | 416 | 421 | 416 | 416 | 5af044c5c51f8d1ec891444dbdd6d33c5a5ed82a | bigcode/the-stack | train |
b6f3d1af8267d4086337469c | train | function | def plot_latlon(mktable, gtitable):
time, lat, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['SAT_LAT'], gtitable)
#time, lon, cc2 = convert_to_elapsed_goodtime(mktable['TIME'], mktable['SAT_LON'], gtitable)
colornames, cmap, norm = gti_colormap()
plot.scatter(time, lat, c=np.fmod(cc,len(c... | def plot_latlon(mktable, gtitable):
| time, lat, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['SAT_LAT'], gtitable)
#time, lon, cc2 = convert_to_elapsed_goodtime(mktable['TIME'], mktable['SAT_LON'], gtitable)
colornames, cmap, norm = gti_colormap()
plot.scatter(time, lat, c=np.fmod(cc,len(colornames)), norm=norm,
cmap... | deg)')
plot.yscale('log')
plot.axhline(1.0/60.0,c='r')
plot.ylim((0.0001,100.0))
return
#--------------------------LAT / LON---------------------------------------------
def plot_latlon(mktable, gtitable):
| 64 | 64 | 193 | 11 | 53 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_latlon | plot_latlon | 668 | 682 | 668 | 668 | 46c2b85abc116b1ac86bbdb2cf4a8a41de19ff93 | bigcode/the-stack | train |
6e4ca48a90fc8bd3c0b73258 | train | function | def plot_SAA(mktable, gtitable):
time, insaa, colors = convert_to_elapsed_goodtime(mktable['TIME'], mktable['NICER_SAA'], gtitable)
time = np.delete(time, np.where(insaa == 0))
insaa = np.delete(insaa, np.where(insaa == 0))
# Get Overshoot Max, just to put the SAA on the same plot
ovtime, overshoot... | def plot_SAA(mktable, gtitable):
| time, insaa, colors = convert_to_elapsed_goodtime(mktable['TIME'], mktable['NICER_SAA'], gtitable)
time = np.delete(time, np.where(insaa == 0))
insaa = np.delete(insaa, np.where(insaa == 0))
# Get Overshoot Max, just to put the SAA on the same plot
ovtime, overshoot, cc = convert_to_elapsed_goodtim... | symlog',linthreshy=10.0)
plot.legend(loc = 2)
plot.ylabel('Overshoot rate')
plot.grid(True)
return
#def plot_SAA(mktable, gtitable, overshootrate):
def plot_SAA(mktable, gtitable):
| 64 | 64 | 209 | 11 | 53 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_SAA | plot_SAA | 576 | 588 | 576 | 576 | c271af7b08d30b97f10b0a844bf03696c1499f98 | bigcode/the-stack | train |
8da024e4f0d0ad1a3fdc8739 | train | function | def convert_from_elapsed_goodtime(elapsedstarts, elapsedstops, gtitable):
'Given a set of elapsed time starts and stops will convert to MET'
startmets = np.array([])
stopmets = np.array([])
for timex in xrange(0,len(elapsedstarts)):
starttime = elapsedstarts[timex]
stoptime = elapsedstar... | def convert_from_elapsed_goodtime(elapsedstarts, elapsedstops, gtitable):
| 'Given a set of elapsed time starts and stops will convert to MET'
startmets = np.array([])
stopmets = np.array([])
for timex in xrange(0,len(elapsedstarts)):
starttime = elapsedstarts[timex]
stoptime = elapsedstarts[timex]
for idx in xrange(0,len(gtitable)):
if idx <... | (gtitable['START'])):
idx = np.where(np.logical_and(mets>gtitable['START'][ii],mets<gtitable['STOP'][ii]))
goodlist.append(etable[idx])
return vstack(goodlist,metadata_conflicts='silent')
def convert_from_elapsed_goodtime(elapsedstarts, elapsedstops, gtitable):
| 72 | 72 | 240 | 17 | 55 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | convert_from_elapsed_goodtime | convert_from_elapsed_goodtime | 505 | 523 | 505 | 505 | bb9f5ab428a94379b5dc70acbda5a7004012b960 | bigcode/the-stack | train |
bab90c9eff7868b02cc91b40 | train | function | def plot_undershoot(mktable, gtitable, args):
#etime, undershoot, cc = convert_to_elapsed_goodtime(hkmet, undershootrate, gtitable)
etime, undershoot, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['NUM_FPM_ON']*mktable['FPM_UNDERONLY_COUNT'], gtitable)
# Delete the nan values from undershoot a... | def plot_undershoot(mktable, gtitable, args):
#etime, undershoot, cc = convert_to_elapsed_goodtime(hkmet, undershootrate, gtitable)
| etime, undershoot, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['NUM_FPM_ON']*mktable['FPM_UNDERONLY_COUNT'], gtitable)
# Delete the nan values from undershoot and cc so they don't plot
etimeNan = np.where(np.isnan(undershoot))
udtime=np.delete(etime,etimeNan)
undershoot=np.delete(unde... | color = 'y', label = 'In the SAA',marker = '_')
plot.legend(loc = 2)
return
#-------------------------UNDERSHOOT RATE FOR RATIO------------------------------
#def plot_undershoot(etable, undershootrate, gtitable, args, hkmet, mktable):
def plot_undershoot(mktable, gtitable, args):
#etime, undershoot, cc ... | 105 | 105 | 351 | 39 | 66 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_undershoot | plot_undershoot | 592 | 624 | 592 | 594 | db2f14af4c1e4672883764ab7d00093eff04ffc8 | bigcode/the-stack | train |
1b3aec5e6725da4392a3de9e | train | function | def filt_ratio(etable, ratiocut):
#Filters out the points > filtratio
ratio = np.zeros_like(etable['PI'],dtype=np.float)
idx = np.where(np.logical_and(etable['PHA']>0, etable['PHA_FAST']>0))[0]
ratio[idx] = np.asarray(etable['PHA'][idx],dtype=np.float)/np.asarray(etable['PHA_FAST'][idx],dtype=np.float)
... | def filt_ratio(etable, ratiocut):
#Filters out the points > filtratio
| ratio = np.zeros_like(etable['PI'],dtype=np.float)
idx = np.where(np.logical_and(etable['PHA']>0, etable['PHA_FAST']>0))[0]
ratio[idx] = np.asarray(etable['PHA'][idx],dtype=np.float)/np.asarray(etable['PHA_FAST'][idx],dtype=np.float)
etable = etable[np.where(ratio < ratiocut)[0]]
return etable
| Rate by Detector')
plot.ylabel('Reset Rate [Hz]')
plot.xlabel('DET_ID')
#plot.ylim([0, np.max(reset_rates)+2])
#----------------------Filter Ratio Cut-----------------------------------------
def filt_ratio(etable, ratiocut):
#Filters out the points > filtratio
| 64 | 64 | 118 | 21 | 43 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | filt_ratio | filt_ratio | 732 | 738 | 732 | 733 | 53057aa1c896e5b37ff98d13c14b6fb1e4ecaec8 | bigcode/the-stack | train |
1742c547522d68c6052655ed | train | function | def structure(etable, num_events):
'Creates a grid where the xy pair corresponds to RAWX,RAWY and value at each entry is event count'
rawx = np.zeros_like(IDS,dtype=np.int)
rawy = np.zeros_like(IDS,dtype=np.int)
#getting RAWX and RAWY vals for each ID
for count, detid in enumerate(IDS):
idx... | def structure(etable, num_events):
| 'Creates a grid where the xy pair corresponds to RAWX,RAWY and value at each entry is event count'
rawx = np.zeros_like(IDS,dtype=np.int)
rawy = np.zeros_like(IDS,dtype=np.int)
#getting RAWX and RAWY vals for each ID
for count, detid in enumerate(IDS):
idx = np.where(etable['DET_ID']==detid... | of Events')
plot.locator_params(nbins = 20)
plot.title('Total (Filtered) Event Count by Detector')
#total_counts.set_ylim([np.min(num_events)-20, np.max(num_events)+20])
return num_events
#----------------------THIS MAKES THE GRAYSCALE ID/EVENT COUNT CHART---------------------
def structure(etable, n... | 79 | 79 | 266 | 8 | 71 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | structure | structure | 93 | 117 | 93 | 93 | b4de3b01b070055ca625485db623857994cd8363 | bigcode/the-stack | train |
38b31ea646c7ad05a2195ca2 | train | function | def calc_pi(etable, calfile):
'Compute PI from PHA (slow) using approximate linear calibration'
# Load calibration file
det_ids, e0s, gains = np.loadtxt(calfile,unpack=True)
det_ids = np.array(det_ids,dtype=int)
e_keV = np.zeros_like(etable['PHA'],dtype=np.float)
for d, e0, g in zip(det_ids,... | def calc_pi(etable, calfile):
| 'Compute PI from PHA (slow) using approximate linear calibration'
# Load calibration file
det_ids, e0s, gains = np.loadtxt(calfile,unpack=True)
det_ids = np.array(det_ids,dtype=int)
e_keV = np.zeros_like(etable['PHA'],dtype=np.float)
for d, e0, g in zip(det_ids,e0s,gains):
idx = np.w... | /10.0)/x + fastquart*x**3
plot.plot(x*PI_TO_KEV, cutline, 'g--', linewidth = 1.5)
return
#-------------------------------THIS PLOTS THE ENERGY SPECTRUM------------------
def calc_pi(etable, calfile):
| 64 | 64 | 155 | 9 | 55 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | calc_pi | calc_pi | 272 | 286 | 272 | 272 | b3029f994d7443d0d059e5c2efaf2d8901397cfd | bigcode/the-stack | train |
5971d77f50d82230dfffd0dc | train | function | def plot_fft_of_power(etable,nyquist, pslog, writeps):
'plots the power spectrum'
dt = 0.5/nyquist
METmin = etable['MET'].min()
T = etable['MET'].max() - etable['MET'].min()
# Choose good number of bins for efficient FFT
n = choose_N(T/float(dt))
bins = np.arange(n)*dt
log.info('{0} {1... | def plot_fft_of_power(etable,nyquist, pslog, writeps):
| 'plots the power spectrum'
dt = 0.5/nyquist
METmin = etable['MET'].min()
T = etable['MET'].max() - etable['MET'].min()
# Choose good number of bins for efficient FFT
n = choose_N(T/float(dt))
bins = np.arange(n)*dt
log.info('{0} {1}'.format(T/dt,n))
log.info('Computing FFT with {0}... | _N = factor
while new_N < orig_N:
new_N *= 10
# Finally, compare new_N to the closest power_of_two
# greater than orig_N. Take the closest.
two_N = 2
while two_N < orig_N:
two_N *= 2
if two_N < new_N: return two_N
else: return new_N
def plot_fft_of_power(etable,nyquist, pslo... | 103 | 103 | 344 | 17 | 85 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_fft_of_power | plot_fft_of_power | 365 | 399 | 365 | 365 | a97cff2c3cb0c895af4091db997ba21814540572 | bigcode/the-stack | train |
765eeac8225510ce2593c7d0 | train | function | def hist_use(etable):
'Creates array of event count per ID and colors hot detectors red'
# Make array of event counts by DET_ID
IDevents = event_counter(etable)
colors = np.array(['k']*len(IDevents))
# Color using auto identified hot detectors
bad_dets = find_hot_detectors(etable)
if bad_de... | def hist_use(etable):
| 'Creates array of event count per ID and colors hot detectors red'
# Make array of event counts by DET_ID
IDevents = event_counter(etable)
colors = np.array(['k']*len(IDevents))
# Color using auto identified hot detectors
bad_dets = find_hot_detectors(etable)
if bad_dets is not None:
... | .info('Detector Count Mean {0}, std {1}'.format(stats[0],stats[2]))
if len(bad_dets) > 0:
log.warning('!!! Found hot detectors {0}'.format(bad_dets))
return bad_dets
return None
def hist_use(etable):
| 66 | 66 | 220 | 6 | 59 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | hist_use | hist_use | 46 | 68 | 46 | 46 | 60fe9a9dbfe6240c7794050751eb241b2693fddd | bigcode/the-stack | train |
c2cf9efba31d1a30e8b12c16 | train | function | def plot_energy_spec(etable,binscale=1.0,plot_pos=None):
'plots the energy spectrum of PI'
bb = np.concatenate((np.arange(0.0,2.0,0.02*binscale),np.arange(2.0,15.0,0.1*binscale)))
hh, hh_bins = np.histogram(etable['PI']*PI_TO_KEV, bins=bb)
widths = bb[1:] - bb[:-1]
plot.step(bb[:-1],hh/widths,where=... | def plot_energy_spec(etable,binscale=1.0,plot_pos=None):
| 'plots the energy spectrum of PI'
bb = np.concatenate((np.arange(0.0,2.0,0.02*binscale),np.arange(2.0,15.0,0.1*binscale)))
hh, hh_bins = np.histogram(etable['PI']*PI_TO_KEV, bins=bb)
widths = bb[1:] - bb[:-1]
plot.step(bb[:-1],hh/widths,where='post')
# plot.hist(etable['PI']*PI_TO_KEV, bins=bb,
#... | np.zeros_like(etable['PHA'],dtype=np.float)
for d, e0, g in zip(det_ids,e0s,gains):
idx = np.where(etable['DET_ID'] == d)[0]
e_keV[idx] = e0 + g*etable['PHA'][idx]
pi = np.array(e_keV/PI_TO_KEV,dtype=np.int)
return pi
def plot_energy_spec(etable,binscale=1.0,plot_pos=None):
| 106 | 106 | 355 | 18 | 87 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_energy_spec | plot_energy_spec | 288 | 321 | 288 | 288 | 9202a9ecbd37749f47107c22ad1c39d2c190f19d | bigcode/the-stack | train |
05693809c5ee1c5f6ceedc74 | train | function | def plot_angles(mktable, gtitable):
sun = mktable['SUN_ANGLE']
earth = mktable['BR_EARTH']
moon = mktable['MOON_ANGLE']
elv = mktable['ELV']
met = mktable['TIME']
goodtime, sunangle, cc = convert_to_elapsed_goodtime(met, sun, gtitable)
goodtime, earthangle, cc = convert_to_elapsed_goodtime... | def plot_angles(mktable, gtitable):
| sun = mktable['SUN_ANGLE']
earth = mktable['BR_EARTH']
moon = mktable['MOON_ANGLE']
elv = mktable['ELV']
met = mktable['TIME']
goodtime, sunangle, cc = convert_to_elapsed_goodtime(met, sun, gtitable)
goodtime, earthangle, cc = convert_to_elapsed_goodtime(met, earth, gtitable)
goodtime,... | suny=np.delete(suny,sidx)
plot.scatter(sunt,1.1*suny*undershoot.max(), color='y', label='Sunshine',
marker = '_')
plot.legend(loc = 2)
plot.grid(True)
plot.ylabel('Undershoot rate')
if args.lclog:
plot.yscale('log')
return
#-------------------------SUN / EARTH / MOON ANGLES--... | 103 | 103 | 344 | 10 | 93 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_angles | plot_angles | 627 | 650 | 627 | 627 | 216027389b04a85ae1f133714a00302297f42ff2 | bigcode/the-stack | train |
e777d4fe46c0521bb6c8b957 | train | function | def plot_detector_chart(etable, num_events, ax_map):
'Plots the structure created in structure() above as a grayscale grid'
#WANT TO GET THE ORIGIN IN THE TOP RIGHT HAND CORNER
struct = structure(etable, num_events)
#plot.style.use('grayscale')
ax_img = plot.imshow(struct, origin = 'lower')
plo... | def plot_detector_chart(etable, num_events, ax_map):
| 'Plots the structure created in structure() above as a grayscale grid'
#WANT TO GET THE ORIGIN IN THE TOP RIGHT HAND CORNER
struct = structure(etable, num_events)
#plot.style.use('grayscale')
ax_img = plot.imshow(struct, origin = 'lower')
plot.gca().invert_yaxis()
plot.gca().invert_xaxis()
... | ,8))
for i in xrange(len(rawx)):
if rawx[i] >= 0 and rawy[i] >= 0:
structure[rawy[i]][rawx[i]] = num_events[i]
return structure
def plot_detector_chart(etable, num_events, ax_map):
| 64 | 64 | 149 | 14 | 49 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_detector_chart | plot_detector_chart | 119 | 133 | 119 | 119 | ec8bcaf77f2cadb400c7af47e4dfc610290348f9 | bigcode/the-stack | train |
fd071b8e308c757202e0e251 | train | function | def convert_to_elapsed_goodtime(mets, vals, gtitable):
'Given a set of values at METs, extract the values during the GTIs and return times that are in elapsed good time for plotting'
mets = np.asarray(mets)
vals = np.asarray(vals)
idx = np.where(np.logical_and(mets>gtitable['START'][0],mets<gtitable['ST... | def convert_to_elapsed_goodtime(mets, vals, gtitable):
| 'Given a set of values at METs, extract the values during the GTIs and return times that are in elapsed good time for plotting'
mets = np.asarray(mets)
vals = np.asarray(vals)
idx = np.where(np.logical_and(mets>gtitable['START'][0],mets<gtitable['STOP'][0]))
goodvals = vals[idx]
etimes = mets[id... | continue
else:
if starttime > gtitable['CUMTIME'][idx]:
startmets = np.append(startmets, starttime + gtitable['START'][idx])
stopmets = np.append(startmets, stoptime + gtitable['START'][idx])
return startmets, stopmets
def conve... | 80 | 80 | 267 | 14 | 65 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | convert_to_elapsed_goodtime | convert_to_elapsed_goodtime | 525 | 540 | 525 | 525 | d0381ec613fc469b0b3ac62a99ead71f3801a7c7 | bigcode/the-stack | train |
ae11e6b75cd712983c074749 | train | function | def calc_nresets(mktable, IDS):
'Count resets (detector undershoots) for each detector, from the mktable'
nresets = np.zeros_like(IDS)
# # For each DET_ID count the number of events with undershoot flag set
# for i in range(len(IDS)):
# idx = np.where(np.logical_and(etable['DET_ID'] == IDS[i],... | def calc_nresets(mktable, IDS):
| 'Count resets (detector undershoots) for each detector, from the mktable'
nresets = np.zeros_like(IDS)
# # For each DET_ID count the number of events with undershoot flag set
# for i in range(len(IDS)):
# idx = np.where(np.logical_and(etable['DET_ID'] == IDS[i],
# etabl... | ('Elapsed Time (s)', labelpad = 1)
plot.grid(True)
plot.ylabel('GeV')
return
#-------------------------THIS PLOTS USEFUL TEXT AT THE TOP OF THE SUPLOT-------
# def calc_nresets(etable, IDS):
def calc_nresets(mktable, IDS):
| 66 | 66 | 220 | 11 | 55 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | calc_nresets | calc_nresets | 703 | 721 | 703 | 703 | 53e685a2e8140aed4288520bf94451be5391cc64 | bigcode/the-stack | train |
cd6cb53b95ce11ae2a9c39fe | train | function | def filt_ratio_trumpet(etable):
#Filters out the points > filtratio
ratio = np.zeros_like(etable['PI'],dtype=np.float)
idx = np.where(np.logical_and(etable['PI']>0, etable['PI_FAST']>0))[0]
ratio[idx] = np.asarray(etable['PI'][idx],dtype=np.float)/np.asarray(etable['PI_FAST'][idx],dtype=np.float)
# ... | def filt_ratio_trumpet(etable):
#Filters out the points > filtratio
| ratio = np.zeros_like(etable['PI'],dtype=np.float)
idx = np.where(np.logical_and(etable['PI']>0, etable['PI_FAST']>0))[0]
ratio[idx] = np.asarray(etable['PI'][idx],dtype=np.float)/np.asarray(etable['PI_FAST'][idx],dtype=np.float)
# Old version
#fastconst = 1.0
#fastsig = 250.0
#fastquart = 4... | .asarray(etable['PHA'][idx],dtype=np.float)/np.asarray(etable['PHA_FAST'][idx],dtype=np.float)
etable = etable[np.where(ratio < ratiocut)[0]]
return etable
def filt_ratio_trumpet(etable):
#Filters out the points > filtratio
| 68 | 68 | 227 | 19 | 48 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | filt_ratio_trumpet | filt_ratio_trumpet | 740 | 758 | 740 | 741 | 05a997e05647d3c4b7e75f7f1a941aabcde01f4e | bigcode/the-stack | train |
bb10eee3ad0ab1d262565bc1 | train | function | def light_curve(etable, startmet, stopmet, binsize):
'Bins events as a histogram to be plotted as the light curve. returns bins and the histogram'
if startmet is None and stopmet is None:
startmet = etable['MET'][0]
t = etable['MET'] - startmet
stopmet = etable['MET'][-1]
else:
... | def light_curve(etable, startmet, stopmet, binsize):
| 'Bins events as a histogram to be plotted as the light curve. returns bins and the histogram'
if startmet is None and stopmet is None:
startmet = etable['MET'][0]
t = etable['MET'] - startmet
stopmet = etable['MET'][-1]
else:
t = etable['MET'][np.where(np.logical_and(etable['... | ('Filtered Event Count by Detector Location')
plot.xlabel('Raw X')
plot.ylabel('Raw Y')
plot.colorbar(ax_img, orientation = 'horizontal')
return
#----------------------THIS MAKES THE LIGHT CURVE---------------------------
def light_curve(etable, startmet, stopmet, binsize):
| 64 | 64 | 211 | 15 | 49 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | light_curve | light_curve | 136 | 151 | 136 | 136 | 575a65c31177d0243d0bfdaf92c780fa47cb371a | bigcode/the-stack | train |
7fa153fae80704fa4be53a5f | train | function | def plot_light_curve(etable, lclog, gtitable, binsize=1.0, noplot=False, plot_pos=None):
#'Compute binned light curve of events and return mean rate,plots light curve'
#EDGE CASE FOR FIRST INSTANCE
bins, sums = light_curve(etable, gtitable['START'][0], gtitable['STOP'][0], binsize=binsize)
cc = np.zeros_... | def plot_light_curve(etable, lclog, gtitable, binsize=1.0, noplot=False, plot_pos=None):
#'Compute binned light curve of events and return mean rate,plots light curve'
#EDGE CASE FOR FIRST INSTANCE
| bins, sums = light_curve(etable, gtitable['START'][0], gtitable['STOP'][0], binsize=binsize)
cc = np.zeros_like(bins,dtype=np.float)
cumtime = bins[-1]+binsize
#THE REST OF THE GOOD INTERVALS
for i in xrange(1,len(gtitable['START'])):
mybins, mysums = light_curve(etable, gtitable['START'][i], g... | =bins, range=(0.0,duration))
# Chop off last bin edge, which is only for computing histogram, not plotting
return bins[:-1], sums
def gti_colormap():
colornames = ['black','green','red','blue','magenta','orange','cyan','yellow','gray']
colorlevels = np.arange(len(colornames))
cmap, norm = mpl.colo... | 170 | 170 | 569 | 55 | 114 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | plot_light_curve | plot_light_curve | 159 | 209 | 159 | 161 | fdd59adff8efa78b868c419379a4239824b338ca | bigcode/the-stack | train |
50419d727b6307146c6fee13 | train | function | def gti_colormap():
colornames = ['black','green','red','blue','magenta','orange','cyan','yellow','gray']
colorlevels = np.arange(len(colornames))
cmap, norm = mpl.colors.from_levels_and_colors(levels=colorlevels, colors=colornames, extend='max')
return colornames, cmap, norm
| def gti_colormap():
| colornames = ['black','green','red','blue','magenta','orange','cyan','yellow','gray']
colorlevels = np.arange(len(colornames))
cmap, norm = mpl.colors.from_levels_and_colors(levels=colorlevels, colors=colornames, extend='max')
return colornames, cmap, norm
| 0,duration+binsize,binsize)
sums, edges = np.histogram(t, bins=bins, range=(0.0,duration))
# Chop off last bin edge, which is only for computing histogram, not plotting
return bins[:-1], sums
def gti_colormap():
| 64 | 64 | 78 | 6 | 57 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | gti_colormap | gti_colormap | 153 | 157 | 153 | 153 | a0455a4f26691390c33bd57b510b2528851ac76e | bigcode/the-stack | train |
2eec4b79139591813f55ff1d | train | function | def event_counter(etable):
'Count events by DET_ID'
IDevents = np.zeros_like(IDS)
for i, det_id in enumerate(IDS):
IDevents[i] = np.count_nonzero(etable['DET_ID'] == det_id)
return IDevents
| def event_counter(etable):
| 'Count events by DET_ID'
IDevents = np.zeros_like(IDS)
for i, det_id in enumerate(IDS):
IDevents[i] = np.count_nonzero(etable['DET_ID'] == det_id)
return IDevents
| .fits as pyfits
import astropy.units as u
# Python 2 (xrange) and Python 3 (range) compatibility
try:
xrange
except NameError:
xrange = range
#------------------------THIS MAKES THE TOTAL COUNT HISTOGRAM---------------------------
def event_counter(etable):
| 64 | 64 | 63 | 6 | 58 | juliadeneva/NICERsoft | nicer/plotutils.py | Python | event_counter | event_counter | 25 | 31 | 25 | 25 | 10ca77db40f66013cc54ecc13a28e58a8d3357e8 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.