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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e6ddfbc05e8bb7294021d125 | train | function | def notmasked_edges(a, axis=None):
"""
Find the indices of the first and last unmasked values along an axis.
If all values are masked, return None. Otherwise, return a list
of two tuples, corresponding to the indices of the first and last
unmasked values respectively.
Parameters
---------... | def notmasked_edges(a, axis=None):
| """
Find the indices of the first and last unmasked values along an axis.
If all values are masked, return None. Otherwise, return a list
of two tuples, corresponding to the indices of the first and last
unmasked values respectively.
Parameters
----------
a : array_like
The in... | np.ma.flatnotmasked_edges(a)
array([3, 8])
>>> a[:] = np.ma.masked
>>> print(np.ma.flatnotmasked_edges(a))
None
"""
m = getmask(a)
if m is nomask or not np.any(m):
return np.array([0, a.size - 1])
unmasked = np.flatnonzero(~m)
if len(unmasked) > 0:
return unmasked[... | 121 | 121 | 405 | 9 | 111 | waritthap/numpy | numpy/ma/extras.py | Python | notmasked_edges | notmasked_edges | 1,574 | 1,622 | 1,574 | 1,574 | a01454f8ad592f81e3bbebd587148f392d36bc5f | bigcode/the-stack | train |
ed623af1f54c90f2af79ee27 | train | function | def mask_cols(a, axis=None):
"""
Mask columns of a 2D array that contain masked values.
This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.
See Also
--------
mask_rowcols : Mask rows and/or columns of a 2D array.
masked_where : Mask where a condition is met.
Exampl... | def mask_cols(a, axis=None):
| """
Mask columns of a 2D array that contain masked values.
This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.
See Also
--------
mask_rowcols : Mask rows and/or columns of a 2D array.
masked_where : Mask where a condition is met.
Examples
--------
>>> impor... | _value=1)
>>> ma.mask_rows(a)
masked_array(
data=[[0, 0, 0],
[--, --, --],
[0, 0, 0]],
mask=[[False, False, False],
[ True, True, True],
[False, False, False]],
fill_value=1)
"""
return mask_rowcols(a, 0)
def mask_cols(a, axis=None):
| 97 | 97 | 325 | 8 | 89 | waritthap/numpy | numpy/ma/extras.py | Python | mask_cols | mask_cols | 984 | 1,025 | 984 | 984 | e7101d9d2ae3d9d7791f2f86012e36713bf79821 | bigcode/the-stack | train |
e695e89a301dc07577f103cf | train | class | class _fromnxfunction_allargs(_fromnxfunction):
"""
A version of `_fromnxfunction` that is called with multiple array
arguments. Similar to `_fromnxfunction_args` except that all args
are converted to arrays even if they are not so already. This makes
it possible to process scalars as 1-D arrays. On... | class _fromnxfunction_allargs(_fromnxfunction):
| """
A version of `_fromnxfunction` that is called with multiple array
arguments. Similar to `_fromnxfunction_args` except that all args
are converted to arrays even if they are not so already. This makes
it possible to process scalars as 1-D arrays. Only keyword arguments
are passed through verb... | *args, **params)
_m = func(getmaskarray(x), *args, **params)
res.append(masked_array(_d, mask=_m))
if len(arrays) == 1:
return res[0]
return res
class _fromnxfunction_allargs(_fromnxfunction):
| 67 | 67 | 224 | 12 | 54 | waritthap/numpy | numpy/ma/extras.py | Python | _fromnxfunction_allargs | _fromnxfunction_allargs | 328 | 348 | 328 | 328 | 2d860440fcfd5ee33182e6c373d495562facfc4b | bigcode/the-stack | train |
c11e13552099e1000d6f4acd | train | function | def compress_nd(x, axis=None):
"""Suppress slices from multiple dimensions which contain masked values.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked, `x` is interpreted as a MaskedArray with ... | def compress_nd(x, axis=None):
| """Suppress slices from multiple dimensions which contain masked values.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked, `x` is interpreted as a MaskedArray with `mask`
set to `nomask`.... | , np.inexact):
# avoid inf / x = masked
s = np.ma.sum(low_high, axis=axis, out=out)
np.true_divide(s.data, 2., casting='unsafe', out=s.data)
s = np.lib.utils._median_nancheck(asorted, s, axis, out)
else:
s = np.ma.mean(low_high, axis=axis, out=out)
return s
def compress... | 101 | 101 | 338 | 8 | 92 | waritthap/numpy | numpy/ma/extras.py | Python | compress_nd | compress_nd | 809 | 849 | 809 | 809 | 17d0af1d612c19376771aa1581063d0e39f29fcb | bigcode/the-stack | train |
46081a2c5825e143184ab5ce | train | function | def compress_rowcols(x, axis=None):
"""
Suppress the rows and/or columns of a 2-D array that contain
masked values.
The suppression behavior is selected with the `axis` parameter.
- If axis is None, both rows and columns are suppressed.
- If axis is 0, only rows are suppressed.
- If axis i... | def compress_rowcols(x, axis=None):
| """
Suppress the rows and/or columns of a 2-D array that contain
masked values.
The suppression behavior is selected with the `axis` parameter.
- If axis is None, both rows and columns are suppressed.
- If axis is 0, only rows are suppressed.
- If axis is 1 or -1, only columns are suppress... | else:
axis = normalize_axis_tuple(axis, x.ndim)
# Nothing is masked: return x
if m is nomask or not m.any():
return x._data
# All is masked: return empty
if m.all():
return nxarray([])
# Filter elements through boolean indexing
data = x._data
for ax in axis:
... | 132 | 132 | 440 | 9 | 122 | waritthap/numpy | numpy/ma/extras.py | Python | compress_rowcols | compress_rowcols | 851 | 903 | 851 | 851 | 1946ea85e432acfb1fcf324e7780caa1f0651d96 | bigcode/the-stack | train |
869b24b93f66a7f0791a7a3e | train | class | class _fromnxfunction_seq(_fromnxfunction):
"""
A version of `_fromnxfunction` that is called with a single sequence
of arrays followed by auxiliary args that are passed verbatim for
both the data and mask calls.
"""
def __call__(self, x, *args, **params):
func = getattr(np, self.__name_... | class _fromnxfunction_seq(_fromnxfunction):
| """
A version of `_fromnxfunction` that is called with a single sequence
of arrays followed by auxiliary args that are passed verbatim for
both the data and mask calls.
"""
def __call__(self, x, *args, **params):
func = getattr(np, self.__name__)
_d = func(tuple([np.asarray(a) fo... | _array(_d, mask=_m)
else:
_d = func(np.asarray(x), *args, **params)
_m = func(getmaskarray(x), *args, **params)
return masked_array(_d, mask=_m)
class _fromnxfunction_seq(_fromnxfunction):
| 64 | 64 | 135 | 11 | 53 | waritthap/numpy | numpy/ma/extras.py | Python | _fromnxfunction_seq | _fromnxfunction_seq | 290 | 300 | 290 | 290 | 0571dc956752a0bf7a21702cd26cf6fc7c52246c | bigcode/the-stack | train |
a260a17c62715aac17779945 | train | function | def ediff1d(arr, to_end=None, to_begin=None):
"""
Compute the differences between consecutive elements of an array.
This function is the equivalent of `numpy.ediff1d` that takes masked
values into account, see `numpy.ediff1d` for details.
See Also
--------
numpy.ediff1d : Equivalent functi... | def ediff1d(arr, to_end=None, to_begin=None):
| """
Compute the differences between consecutive elements of an array.
This function is the equivalent of `numpy.ediff1d` that takes masked
values into account, see `numpy.ediff1d` for details.
See Also
--------
numpy.ediff1d : Equivalent function for ndarrays.
"""
arr = ma.asanyar... | ],
[False, True, False],
[False, True, False]],
fill_value=1)
"""
return mask_rowcols(a, 1)
#####--------------------------------------------------------------------------
#---- --- arraysetops ---
#####--------------------------------------------------------------------------... | 63 | 64 | 201 | 15 | 49 | waritthap/numpy | numpy/ma/extras.py | Python | ediff1d | ediff1d | 1,032 | 1,058 | 1,032 | 1,032 | 52c731cb7d7e846ded6874db900295bc2fbda2c8 | bigcode/the-stack | train |
e0ef7942b9b037546bf241dd | train | function | def unique(ar1, return_index=False, return_inverse=False):
"""
Finds the unique elements of an array.
Masked values are considered the same element (masked). The output array
is always a masked array. See `numpy.unique` for more details.
See Also
--------
numpy.unique : Equivalent function... | def unique(ar1, return_index=False, return_inverse=False):
| """
Finds the unique elements of an array.
Masked values are considered the same element (masked). The output array
is always a masked array. See `numpy.unique` for more details.
See Also
--------
numpy.unique : Equivalent function for ndarrays.
"""
output = np.unique(ar1,
... | len(arrays) != 1:
# We'll save ourselves a copy of a potentially large array in the common
# case where neither to_begin or to_end was given.
ed = hstack(arrays)
#
return ed
def unique(ar1, return_index=False, return_inverse=False):
| 64 | 64 | 147 | 13 | 50 | waritthap/numpy | numpy/ma/extras.py | Python | unique | unique | 1,061 | 1,082 | 1,061 | 1,061 | a8407ffa653ee90cf04366dcb59b68679dc5dc80 | bigcode/the-stack | train |
7f84e5bd51f028eb457db3a4 | train | function | def compress_cols(a):
"""
Suppress whole columns of a 2-D array that contain masked values.
This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see
`extras.compress_rowcols` for details.
See Also
--------
extras.compress_rowcols
"""
a = asarray(a)
if a.ndim != 2:
r... | def compress_cols(a):
| """
Suppress whole columns of a 2-D array that contain masked values.
This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see
`extras.compress_rowcols` for details.
See Also
--------
extras.compress_rowcols
"""
a = asarray(a)
if a.ndim != 2:
raise NotImplementedErr... | details.
See Also
--------
extras.compress_rowcols
"""
a = asarray(a)
if a.ndim != 2:
raise NotImplementedError("compress_rows works for 2D arrays only.")
return compress_rowcols(a, 0)
def compress_cols(a):
| 64 | 64 | 109 | 5 | 59 | waritthap/numpy | numpy/ma/extras.py | Python | compress_cols | compress_cols | 923 | 938 | 923 | 923 | 5ef5c12172249d0bfbd096cf1baf51ae4e206b8a | bigcode/the-stack | train |
e0065495d4042b471ceb1b4a | train | function | def isin(element, test_elements, assume_unique=False, invert=False):
"""
Calculates `element in test_elements`, broadcasting over
`element` only.
The output is always a masked array of the same shape as `element`.
See `numpy.isin` for more details.
See Also
--------
in1d : Flatte... | def isin(element, test_elements, assume_unique=False, invert=False):
| """
Calculates `element in test_elements`, broadcasting over
`element` only.
The output is always a masked array of the same shape as `element`.
See `numpy.isin` for more details.
See Also
--------
in1d : Flattened version of this function.
numpy.isin : Equivalent function fo... | = ma.concatenate((bool_ar, [invert]))
indx = order.argsort(kind='mergesort')[:len(ar1)]
if assume_unique:
return flag[indx]
else:
return flag[indx][rev_idx]
def isin(element, test_elements, assume_unique=False, invert=False):
| 64 | 64 | 144 | 14 | 50 | waritthap/numpy | numpy/ma/extras.py | Python | isin | isin | 1,186 | 1,206 | 1,186 | 1,186 | a08d7a43cde6fff75e16c0feda862c1c9dfc3697 | bigcode/the-stack | train |
a96d49564c02ea476bbe41a3 | train | class | class TestMechanismDriver(api.MechanismDriver):
"""Test mechanism driver for testing mechanism driver api."""
def initialize(self):
self.bound_ports = set()
def _check_network_context(self, context, original_expected):
assert(isinstance(context, api.NetworkContext))
assert(isinstan... | class TestMechanismDriver(api.MechanismDriver):
| """Test mechanism driver for testing mechanism driver api."""
def initialize(self):
self.bound_ports = set()
def _check_network_context(self, context, original_expected):
assert(isinstance(context, api.NetworkContext))
assert(isinstance(context.current, dict))
assert(contex... | # Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | 186 | 256 | 1,795 | 11 | 174 | osic-neutron/neutron-ipcapacity | neutron/tests/unit/plugins/ml2/drivers/mechanism_test.py | Python | TestMechanismDriver | TestMechanismDriver | 21 | 236 | 21 | 21 | 5a49491a2ef571690c039e81ae69ddaaa1f62439 | bigcode/the-stack | train |
0a49b2257ffa494668d81e7f | train | class | class NoDefault:
pass
| class NoDefault:
| pass
| import List, Dict, Callable
from .cast_handlers import bool_cast_handler
from .exceptions import CastHandlerMissingError
from .exceptions import SecretMissingError
from .exceptions import SecretSourceMissing
from .secret_sources import BaseSecretSource
from .secret_sources import EnvironmentVariableSecretSource
class... | 64 | 64 | 7 | 4 | 59 | trym-inc/top-secret | top_secret/_vault.py | Python | NoDefault | NoDefault | 11 | 12 | 11 | 11 | bed94e550b8c5af5f7e13cc99acf53732fb4af10 | bigcode/the-stack | train |
c42421cc68d9161bf8b4b0b5 | train | class | class Vault:
_cache = {}
cast_handlers: 'Dict[Callable]' = {}
secret_sources: 'List[BaseSecretSource]' = []
preprocessors: 'List[Callable[str, str]]' = []
def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None):
if cast_handlers is None:
cast_handlers = {... | class Vault:
| _cache = {}
cast_handlers: 'Dict[Callable]' = {}
secret_sources: 'List[BaseSecretSource]' = []
preprocessors: 'List[Callable[str, str]]' = []
def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None):
if cast_handlers is None:
cast_handlers = {}
if ... | from typing import List, Dict, Callable
from .cast_handlers import bool_cast_handler
from .exceptions import CastHandlerMissingError
from .exceptions import SecretMissingError
from .exceptions import SecretSourceMissing
from .secret_sources import BaseSecretSource
from .secret_sources import EnvironmentVariableSecretS... | 100 | 210 | 701 | 3 | 97 | trym-inc/top-secret | top_secret/_vault.py | Python | Vault | Vault | 24 | 150 | 24 | 24 | 8996c362a5356b4f47a10056a775bace9ec01411 | bigcode/the-stack | train |
1ad8e47fd7c38de7c6f5c1a8 | train | class | class Mailboxes(Composite):
def __init__(self):
Composite.__init__(self)
self.tree = Tree()
root = TreeItem(self.imageItemHTML("home.gif", "foo@example.com"))
self.tree.addItem(root)
inboxItem = self.addImageItem(root, "Inbox")
self.addImageItem(root, "Drafts")
... | class Mailboxes(Composite):
| def __init__(self):
Composite.__init__(self)
self.tree = Tree()
root = TreeItem(self.imageItemHTML("home.gif", "foo@example.com"))
self.tree.addItem(root)
inboxItem = self.addImageItem(root, "Inbox")
self.addImageItem(root, "Drafts")
self.addImageItem(root, "... | from pyjamas.ui.Composite import Composite
from pyjamas.ui.Tree import Tree
from pyjamas.ui.TreeItem import TreeItem
class Mailboxes(Composite):
| 35 | 64 | 211 | 6 | 28 | takipsizad/pyjs | examples/mail/Mailboxes.py | Python | Mailboxes | Mailboxes | 6 | 31 | 6 | 6 | 633bc1911f73b75ad9338c7482262102103a1910 | bigcode/the-stack | train |
ea52c66c29420865f346bef7 | train | function | def get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
global _dbs
if reconnect:
disconnect(alias)
if alias not in _dbs:
conn = get_connection(alias)
conn_settings = _connection_settings[alias]
db = conn[conn_settings['name']]
# Authenticate if necessary
... | def get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
| global _dbs
if reconnect:
disconnect(alias)
if alias not in _dbs:
conn = get_connection(alias)
conn_settings = _connection_settings[alias]
db = conn[conn_settings['name']]
# Authenticate if necessary
if conn_settings['username'] and conn_settings['password']:... | _connections[alias] = connection if connection else connection_class(**conn_settings)
except Exception as e:
raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e))
return _connections[alias]
def get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
| 64 | 64 | 122 | 12 | 52 | HiroIshikawa/21playground | thumblelog/myproject/lib/python3.5/site-packages/mongoengine/connection.py | Python | get_db | get_db | 139 | 154 | 139 | 139 | a856b75caa920a547322e7aea772fa4cdcd7f81d | bigcode/the-stack | train |
95d8f056e51cc571e983fbf3 | train | function | def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
global _connections
# Connect to the database if not already connected
if reconnect:
disconnect(alias)
if alias not in _connections:
if alias not in _connection_settings:
msg = 'Connection with alias "%s" ha... | def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
| global _connections
# Connect to the database if not already connected
if reconnect:
disconnect(alias)
if alias not in _connections:
if alias not in _connection_settings:
msg = 'Connection with alias "%s" has not been defined' % alias
if alias == DEFAULT_CONNECTI... | _source'] = uri_options['authsource']
# Deprecated parameters that should not be passed on
kwargs.pop('slaves', None)
kwargs.pop('is_slave', None)
conn_settings.update(kwargs)
_connection_settings[alias] = conn_settings
def disconnect(alias=DEFAULT_CONNECTION_NAME):
global _connections
g... | 125 | 125 | 419 | 12 | 113 | HiroIshikawa/21playground | thumblelog/myproject/lib/python3.5/site-packages/mongoengine/connection.py | Python | get_connection | get_connection | 90 | 136 | 90 | 90 | fb871bda9de1093109c2320863d580ff428a1410 | bigcode/the-stack | train |
e7a02d985b0cacaeb8a08442 | train | function | def register_connection(alias, name=None, host=None, port=None,
read_preference=READ_PREFERENCE,
username=None, password=None, authentication_source=None,
**kwargs):
"""Add a connection.
:param alias: the name that will be used to refer to... | def register_connection(alias, name=None, host=None, port=None,
read_preference=READ_PREFERENCE,
username=None, password=None, authentication_source=None,
**kwargs):
| """Add a connection.
:param alias: the name that will be used to refer to this connection
throughout MongoEngine
:param name: the name of the specific database to use
:param host: the host name of the :program:`mongod` instance to connect to
:param port: the port that the :program:`mongod` ... | engine.python_support import IS_PYMONGO_3
__all__ = ['ConnectionError', 'connect', 'register_connection',
'DEFAULT_CONNECTION_NAME']
DEFAULT_CONNECTION_NAME = 'default'
if IS_PYMONGO_3:
READ_PREFERENCE = ReadPreference.PRIMARY
else:
from pymongo import MongoReplicaSetClient
READ_PREFERENCE = F... | 133 | 134 | 449 | 38 | 95 | HiroIshikawa/21playground | thumblelog/myproject/lib/python3.5/site-packages/mongoengine/connection.py | Python | register_connection | register_connection | 25 | 76 | 25 | 28 | 5c0e9459e4bf228d0b500bf9a558e52aec4a23be | bigcode/the-stack | train |
36a5d2eceda8e83f363da5c7 | train | function | def disconnect(alias=DEFAULT_CONNECTION_NAME):
global _connections
global _dbs
if alias in _connections:
get_connection(alias=alias).close()
del _connections[alias]
if alias in _dbs:
del _dbs[alias]
| def disconnect(alias=DEFAULT_CONNECTION_NAME):
| global _connections
global _dbs
if alias in _connections:
get_connection(alias=alias).close()
del _connections[alias]
if alias in _dbs:
del _dbs[alias]
| authentication_source'] = uri_options['authsource']
# Deprecated parameters that should not be passed on
kwargs.pop('slaves', None)
kwargs.pop('is_slave', None)
conn_settings.update(kwargs)
_connection_settings[alias] = conn_settings
def disconnect(alias=DEFAULT_CONNECTION_NAME):
| 64 | 64 | 58 | 8 | 55 | HiroIshikawa/21playground | thumblelog/myproject/lib/python3.5/site-packages/mongoengine/connection.py | Python | disconnect | disconnect | 79 | 87 | 79 | 79 | 19060d68308a7201ac479a1789144cc137e8b1e3 | bigcode/the-stack | train |
fa1ffbcfbe02cef6feea0387 | train | function | def connect(db=None, alias=DEFAULT_CONNECTION_NAME, **kwargs):
"""Connect to the database specified by the 'db' argument.
Connection settings may be provided here as well if the database is not
running on the default port on localhost. If authentication is needed,
provide username and password argument... | def connect(db=None, alias=DEFAULT_CONNECTION_NAME, **kwargs):
| """Connect to the database specified by the 'db' argument.
Connection settings may be provided here as well if the database is not
running on the default port on localhost. If authentication is needed,
provide username and password arguments as well.
Multiple databases are supported by using alias... | ['username'] and conn_settings['password']:
db.authenticate(conn_settings['username'],
conn_settings['password'],
source=conn_settings['authentication_source'])
_dbs[alias] = db
return _dbs[alias]
def connect(db=None, alias=DEFAULT_CONNECTI... | 64 | 64 | 143 | 14 | 50 | HiroIshikawa/21playground | thumblelog/myproject/lib/python3.5/site-packages/mongoengine/connection.py | Python | connect | connect | 157 | 173 | 157 | 157 | ebae4c87e69d558836ea2fde08ed5f4450b592bb | bigcode/the-stack | train |
16c4bbbf19e5a03d0bc1cd2c | train | class | class ConnectionError(Exception):
pass
| class ConnectionError(Exception):
| pass
| Error', 'connect', 'register_connection',
'DEFAULT_CONNECTION_NAME']
DEFAULT_CONNECTION_NAME = 'default'
if IS_PYMONGO_3:
READ_PREFERENCE = ReadPreference.PRIMARY
else:
from pymongo import MongoReplicaSetClient
READ_PREFERENCE = False
class ConnectionError(Exception):
| 64 | 64 | 8 | 5 | 58 | HiroIshikawa/21playground | thumblelog/myproject/lib/python3.5/site-packages/mongoengine/connection.py | Python | ConnectionError | ConnectionError | 16 | 17 | 16 | 16 | a05fec4f6e0fecea502e64c522fc09578bca1e08 | bigcode/the-stack | train |
3e835e401f0d51fc12dec4b3 | train | class | class EnchantConan(ConanFile):
name = "enchant"
description = (
"Enchant aims to provide a simple but comprehensive abstraction for "
"dealing with different spell checking libraries in a consistent way"
)
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://abi... | class EnchantConan(ConanFile):
| name = "enchant"
description = (
"Enchant aims to provide a simple but comprehensive abstraction for "
"dealing with different spell checking libraries in a consistent way"
)
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://abiword.github.io/enchant/"
to... | import functools
from conans import ConanFile, CMake, tools
required_conan_version = ">=1.43.0"
class EnchantConan(ConanFile):
| 38 | 131 | 437 | 10 | 28 | dyndrite/conan-center-index | recipes/enchant/all/conanfile.py | Python | EnchantConan | EnchantConan | 8 | 57 | 8 | 8 | 1edf7b94af2ce9f182b761b0a274edeca829f147 | bigcode/the-stack | train |
cd519c95d61f364084d14256 | train | function | def optimization_objective(dynamic_config, checkpoint_dir=None):
train_loader, valid_loader, test_loader = create_dataloaders(dynamic_config)
early_stopping_patience = dynamic_config['early_stopping_patience']
model = dynamic_config['model'](dynamic_config).to(device)
optimizer = dynamic_config['optimiz... | def optimization_objective(dynamic_config, checkpoint_dir=None):
| train_loader, valid_loader, test_loader = create_dataloaders(dynamic_config)
early_stopping_patience = dynamic_config['early_stopping_patience']
model = dynamic_config['model'](dynamic_config).to(device)
optimizer = dynamic_config['optimizer'](model.parameters(),
... | from src.data_management.data_manager import create_dataloaders
from src.model_management.train_test import evaluate, train
from ray import tune
import numpy as np
import torch
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
def optimization_objective(dynamic_config, checkpoint_dir=None):
| 65 | 135 | 452 | 11 | 54 | Amir-Mehrpanah/RRFLab | windows-mlps-lrsignal/src/model_management/hyperparameter_optimization.py | Python | optimization_objective | optimization_objective | 10 | 50 | 10 | 10 | 79a3e606d3b4aef5a6d3109675715f34a3cce6ce | bigcode/the-stack | train |
96b8a3246e2f39abc8383951 | train | class | class BaseSystem(abc.ABC):
"""Abstract system object."""
@abc.abstractmethod
def design(self) -> SimpleNamespace:
"""System design specifying the list of components to use.
Returns:
system callback components
"""
@abc.abstractmethod
def update(self, component: ... | class BaseSystem(abc.ABC):
| """Abstract system object."""
@abc.abstractmethod
def design(self) -> SimpleNamespace:
"""System design specifying the list of components to use.
Returns:
system callback components
"""
@abc.abstractmethod
def update(self, component: Any) -> None:
"""Up... | software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Core Mava interfaces for Jax systems."""
import abc
from t... | 83 | 83 | 279 | 8 | 74 | 1998x-stack/Mava | mava/core_jax.py | Python | BaseSystem | BaseSystem | 24 | 71 | 24 | 24 | e01d1228ffddb2a477b953e890d96c4792f8fb6f | bigcode/the-stack | train |
744b93ec8ab786e88cc7b3d4 | train | function | def main():
#
parser = argparse.ArgumentParser()
parser.add_argument('template')
parser.add_argument('entries', metavar='entry', nargs='*', type=entry)
args = parser.parse_args()
#
context = {key: value for key, value in args.entries}
with open(args.template) as fin:
template =... | def main():
#
| parser = argparse.ArgumentParser()
parser.add_argument('template')
parser.add_argument('entries', metavar='entry', nargs='*', type=entry)
args = parser.parse_args()
#
context = {key: value for key, value in args.entries}
with open(args.template) as fin:
template = jinja2.Template(f... | ocoder developers
#
# This file is part of biocoder,
# released under Apache License Version 2.0 (http://www.apache.org/licenses/LICENCE).
#
import argparse
import sys
import jinja2
def entry(text):
return text.split('=', 1)
def main():
#
| 64 | 64 | 89 | 5 | 59 | east301/biocoder-server | tools/scripts/render-template.py | Python | main | main | 19 | 31 | 19 | 20 | e9e79b0d83a06dff820c72e081650f0b13a632aa | bigcode/the-stack | train |
3cdf2f42df0bb3a2e303ddc3 | train | function | def entry(text):
return text.split('=', 1)
| def entry(text):
| return text.split('=', 1)
| /bin/env python3
#
# (c) 2016 biocoder developers
#
# This file is part of biocoder,
# released under Apache License Version 2.0 (http://www.apache.org/licenses/LICENCE).
#
import argparse
import sys
import jinja2
def entry(text):
| 64 | 64 | 13 | 4 | 59 | east301/biocoder-server | tools/scripts/render-template.py | Python | entry | entry | 15 | 16 | 15 | 15 | b674b064f2f165f1faec0ed8dd38d60cc36b03ea | bigcode/the-stack | train |
bff7dcf94d496d01212dfde5 | train | class | class LikedByListResource(Resource):
@jwt_refresh_required
def get(self):
current_user = get_jwt_identity()
return Match.get_liked_by(self, user_id=current_user["id"])
| class LikedByListResource(Resource):
@jwt_refresh_required
| def get(self):
current_user = get_jwt_identity()
return Match.get_liked_by(self, user_id=current_user["id"])
|
def get(self, user_id):
user = get_jwt_identity()
match = Match.check_match(user["id"], user_id)
return match or {"matched" : False, "liked" : False}, 200
class LikedByListResource(Resource):
@jwt_refresh_required
| 64 | 64 | 46 | 15 | 48 | gwasserfall/matcha | resources/matches.py | Python | LikedByListResource | LikedByListResource | 83 | 88 | 83 | 84 | df605d32522f1a05d96f0bc98cce285a45ae8f5c | bigcode/the-stack | train |
bc4fc8544c15c718b3092350 | train | class | class LikesListResource(Resource):
@jwt_refresh_required
def get(self):
current_user = get_jwt_identity()
return Match.get_likes(self, user_id=current_user["id"])
| class LikesListResource(Resource):
@jwt_refresh_required
| def get(self):
current_user = get_jwt_identity()
return Match.get_likes(self, user_id=current_user["id"])
| False}, 200
class LikedByListResource(Resource):
@jwt_refresh_required
def get(self):
current_user = get_jwt_identity()
return Match.get_liked_by(self, user_id=current_user["id"])
class LikesListResource(Resource):
@jwt_refresh_required
| 64 | 64 | 42 | 13 | 51 | gwasserfall/matcha | resources/matches.py | Python | LikesListResource | LikesListResource | 90 | 95 | 90 | 91 | b516a0e1ab309f5f699eac2ebaa5656e1d034399 | bigcode/the-stack | train |
b61061256b89e1740f6a25b7 | train | class | class UnmatchResource(Resource):
@jwt_refresh_required
def delete(self, user_id):
current_user = get_jwt_identity()
match = Match.check_match(current_user["id"], user_id)
if match["liked"] or match["matched"]:
my_like = Match.get(matcher_id=current_user["id"], matchee_id=u... | class UnmatchResource(Resource):
@jwt_refresh_required
| def delete(self, user_id):
current_user = get_jwt_identity()
match = Match.check_match(current_user["id"], user_id)
if match["liked"] or match["matched"]:
my_like = Match.get(matcher_id=current_user["id"], matchee_id=user_id)
their_like = Match.get(matcher_id=user_id... | : False, "liked" : False}, 200
class LikedByListResource(Resource):
@jwt_refresh_required
def get(self):
current_user = get_jwt_identity()
return Match.get_liked_by(self, user_id=current_user["id"])
class LikesListResource(Resource):
@jwt_refresh_required
def get(self):
... | 113 | 113 | 379 | 13 | 100 | gwasserfall/matcha | resources/matches.py | Python | UnmatchResource | UnmatchResource | 97 | 130 | 97 | 98 | c1ce1bcefb9937d5dd35acccc439ce2f84afdd1e | bigcode/the-stack | train |
a4ea844691e17e5390ba4714 | train | class | class MatchResource(Resource):
@jwt_refresh_required
def get(self, user_id):
user = get_jwt_identity()
match = Match.check_match(user["id"], user_id)
return match or {"matched" : False, "liked" : False}, 200
| class MatchResource(Resource):
@jwt_refresh_required
| def get(self, user_id):
user = get_jwt_identity()
match = Match.check_match(user["id"], user_id)
return match or {"matched" : False, "liked" : False}, 200
| ", (current_user["id"], current_user["id"]))
for m in c.fetchall():
user = User.get(id=m["id"])
user.get_primary_image()
matches.append(user)
temp.pool.release(connection)
return matches, 200
class MatchResource(Resource):
@jwt_refresh_req... | 64 | 64 | 59 | 11 | 52 | gwasserfall/matcha | resources/matches.py | Python | MatchResource | MatchResource | 75 | 81 | 75 | 76 | 67f5d5a13e328c5304d52cac76fce8eb4d5a2c01 | bigcode/the-stack | train |
c758152727dfdddc48cfc343 | train | class | class MatchListResource(Resource):
@jwt_refresh_required
def post(self):
"""
Doc string to describe function
"""
args = Arguments(request.json)
args.string("matchee_id", required=True)
args.validate()
user = get_jwt_identity()
images = Image.... | class MatchListResource(Resource):
@jwt_refresh_required
| def post(self):
"""
Doc string to describe function
"""
args = Arguments(request.json)
args.string("matchee_id", required=True)
args.validate()
user = get_jwt_identity()
images = Image.check_images(user_id=user["id"])
if not images["has_... | from flask import request
from flask_restful import Resource
from models.matches import Match
from models.user import User
from models.images import Image
from models.block_request import BlockRequest
from twisted.python import log
from flask_jwt_extended import get_jwt_identity
from helpers import Arguments, is_e... | 79 | 113 | 377 | 12 | 66 | gwasserfall/matcha | resources/matches.py | Python | MatchListResource | MatchListResource | 16 | 72 | 16 | 17 | b6689fe46c9f01b0e294a7e76a225480fcb82875 | bigcode/the-stack | train |
2c81b5e44c14a877658c5204 | train | class | class ApplicationError(Error):
"""Raised by APIProxy in the event of an application-level error."""
def __init__(self, application_error, error_detail=''):
self.application_error = application_error
self.error_detail = error_detail
Error.__init__(self, application_error)
def __str__(self):
return... | class ApplicationError(Error):
| """Raised by APIProxy in the event of an application-level error."""
def __init__(self, application_error, error_detail=''):
self.application_error = application_error
self.error_detail = error_detail
Error.__init__(self, application_error)
def __str__(self):
return 'ApplicationError: %d %s' % (s... | parsing the arguments."""
class DeadlineExceededError(Error):
"""Raised by APIProxy calls if the call took too long to respond."""
class CancelledError(Error):
"""Raised by APIProxy calls if the call was cancelled, such as when
the user's request is exiting."""
class ApplicationError(Error):
| 63 | 64 | 89 | 5 | 58 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | ApplicationError | ApplicationError | 47 | 56 | 47 | 47 | 6965781d45cbcf88dd7ffc797b5e3f885a3f0589 | bigcode/the-stack | train |
5e790940f770ed8ecbe86f0b | train | class | class ResponseTooLargeError(Error):
"""Raised by APIProxy calls if the response was too large."""
| class ResponseTooLargeError(Error):
| """Raised by APIProxy calls if the response was too large."""
| .application_error,
self.error_detail)
class OverQuotaError(Error):
"""Raised by APIProxy calls when they have been blocked due to a lack of
available quota."""
class RequestTooLargeError(Error):
"""Raised by APIProxy calls if the request was too large."""
class ResponseT... | 64 | 64 | 21 | 7 | 57 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | ResponseTooLargeError | ResponseTooLargeError | 65 | 66 | 65 | 65 | 8de3e27c08b9bee6a1b2603e20d232470e0d0332 | bigcode/the-stack | train |
8fbddfe06133e2aaee3d6158 | train | class | class InterruptedError(Error):
"""Raised by APIProxy.Wait() when the wait is interrupted by an uncaught
exception from some callback, not necessarily associated with the RPC in
question."""
def __init__(self, exception, rpc):
self.args = ("The Wait() request was interrupted by an exception from "
... | class InterruptedError(Error):
| """Raised by APIProxy.Wait() when the wait is interrupted by an uncaught
exception from some callback, not necessarily associated with the RPC in
question."""
def __init__(self, exception, rpc):
self.args = ("The Wait() request was interrupted by an exception from "
"another callback:", exc... | ):
"""Raised by APIProxy calls if the response was too large."""
class CapabilityDisabledError(Error):
"""Raised by APIProxy when API calls are temporarily disabled."""
class FeatureNotEnabledError(Error):
"""Raised by APIProxy when the app must enable a feature to use this call."""
class InterruptedError(Error... | 64 | 64 | 118 | 5 | 59 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | InterruptedError | InterruptedError | 74 | 90 | 74 | 74 | 74f03dff66484299194d715a9978652a9206fbc3 | bigcode/the-stack | train |
1196effbda0e193000da2b1c | train | class | class CapabilityDisabledError(Error):
"""Raised by APIProxy when API calls are temporarily disabled."""
| class CapabilityDisabledError(Error):
| """Raised by APIProxy when API calls are temporarily disabled."""
| calls when they have been blocked due to a lack of
available quota."""
class RequestTooLargeError(Error):
"""Raised by APIProxy calls if the request was too large."""
class ResponseTooLargeError(Error):
"""Raised by APIProxy calls if the response was too large."""
class CapabilityDisabledError(Error):
| 64 | 64 | 19 | 6 | 58 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | CapabilityDisabledError | CapabilityDisabledError | 68 | 69 | 68 | 68 | 9c7a5a1f5aecf1966821876831753ad82bb0e7eb | bigcode/the-stack | train |
b3e87fbf51c493fa41242352 | train | class | class ArgumentError(Error):
"""Raised by APIProxy calls if there is an error parsing the arguments."""
| class ArgumentError(Error):
| """Raised by APIProxy calls if there is an error parsing the arguments."""
| class Error(Exception):
"""Base APIProxy error type."""
class RPCFailedError(Error):
"""Raised by APIProxy calls when the RPC to the application server fails."""
class CallNotFoundError(Error):
"""Raised by APIProxy calls when the requested method cannot be found."""
class ArgumentError(Error):
| 63 | 64 | 21 | 5 | 58 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | ArgumentError | ArgumentError | 34 | 35 | 34 | 34 | 21f71c2f6fd730ad1cf4a9314e913af6344b1e7c | bigcode/the-stack | train |
590a812d238046e5d34bcbb2 | train | class | class RequestTooLargeError(Error):
"""Raised by APIProxy calls if the request was too large."""
| class RequestTooLargeError(Error):
| """Raised by APIProxy calls if the request was too large."""
| def __str__(self):
return 'ApplicationError: %d %s' % (self.application_error,
self.error_detail)
class OverQuotaError(Error):
"""Raised by APIProxy calls when they have been blocked due to a lack of
available quota."""
class RequestTooLargeError(Error):
| 64 | 64 | 21 | 7 | 57 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | RequestTooLargeError | RequestTooLargeError | 62 | 63 | 62 | 62 | f44465930b4a6fb1b528ac28c0d1f85e64911c09 | bigcode/the-stack | train |
18acb15fa81c9ead9c9d6189 | train | class | class OverQuotaError(Error):
"""Raised by APIProxy calls when they have been blocked due to a lack of
available quota."""
| class OverQuotaError(Error):
| """Raised by APIProxy calls when they have been blocked due to a lack of
available quota."""
| _detail=''):
self.application_error = application_error
self.error_detail = error_detail
Error.__init__(self, application_error)
def __str__(self):
return 'ApplicationError: %d %s' % (self.application_error,
self.error_detail)
class OverQuotaError(Error):
| 64 | 64 | 28 | 6 | 58 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | OverQuotaError | OverQuotaError | 58 | 60 | 58 | 58 | 5c4f969bd204fa871ca90022c47bada02aabc6aa | bigcode/the-stack | train |
28542f1b756cd594af5a96bc | train | class | class DeadlineExceededError(Error):
"""Raised by APIProxy calls if the call took too long to respond."""
| class DeadlineExceededError(Error):
| """Raised by APIProxy calls if the call took too long to respond."""
| APIProxy calls when the RPC to the application server fails."""
class CallNotFoundError(Error):
"""Raised by APIProxy calls when the requested method cannot be found."""
class ArgumentError(Error):
"""Raised by APIProxy calls if there is an error parsing the arguments."""
class DeadlineExceededError(Error):
| 63 | 64 | 22 | 6 | 57 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | DeadlineExceededError | DeadlineExceededError | 38 | 39 | 38 | 38 | fa618db801d0f7c9051bad710aaeee07ac29513d | bigcode/the-stack | train |
04b31de0dd9ab001e7350a7c | train | class | class FeatureNotEnabledError(Error):
"""Raised by APIProxy when the app must enable a feature to use this call."""
| class FeatureNotEnabledError(Error):
| """Raised by APIProxy when the app must enable a feature to use this call."""
| Error(Error):
"""Raised by APIProxy calls if the request was too large."""
class ResponseTooLargeError(Error):
"""Raised by APIProxy calls if the response was too large."""
class CapabilityDisabledError(Error):
"""Raised by APIProxy when API calls are temporarily disabled."""
class FeatureNotEnabledError(Error)... | 64 | 64 | 25 | 7 | 57 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | FeatureNotEnabledError | FeatureNotEnabledError | 71 | 72 | 71 | 71 | 0b335d856ddd6822ffd67692f43ea3dc7af41eea | bigcode/the-stack | train |
284c21c8d7a372d6af5d9b61 | train | class | class CallNotFoundError(Error):
"""Raised by APIProxy calls when the requested method cannot be found."""
| class CallNotFoundError(Error):
| """Raised by APIProxy calls when the requested method cannot be found."""
| and
# limitations under the License.
#
"""Errors thrown by apiproxy.MakeSyncCall.
"""
class Error(Exception):
"""Base APIProxy error type."""
class RPCFailedError(Error):
"""Raised by APIProxy calls when the RPC to the application server fails."""
class CallNotFoundError(Error):
| 63 | 64 | 22 | 7 | 56 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | CallNotFoundError | CallNotFoundError | 30 | 31 | 30 | 30 | 5168c77efa9dbb831da71eac9423114bb66e885b | bigcode/the-stack | train |
9a7825384260b43520d03b1e | train | class | class RPCFailedError(Error):
"""Raised by APIProxy calls when the RPC to the application server fails."""
| class RPCFailedError(Error):
| """Raised by APIProxy calls when the RPC to the application server fails."""
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Errors thrown by apiproxy.MakeSyncCall.
"""
class Error(Exception):
"""Base APIProxy error type."""
class RPCFailedError(Error):
| 63 | 64 | 22 | 6 | 57 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | RPCFailedError | RPCFailedError | 26 | 27 | 26 | 26 | 4e24c748733584a13c05c1588f6a3cef07d1452a | bigcode/the-stack | train |
7138c11568228ac81e12a9b4 | train | class | class CancelledError(Error):
"""Raised by APIProxy calls if the call was cancelled, such as when
the user's request is exiting."""
| class CancelledError(Error):
| """Raised by APIProxy calls if the call was cancelled, such as when
the user's request is exiting."""
| by APIProxy calls when the requested method cannot be found."""
class ArgumentError(Error):
"""Raised by APIProxy calls if there is an error parsing the arguments."""
class DeadlineExceededError(Error):
"""Raised by APIProxy calls if the call took too long to respond."""
class CancelledError(Error):
| 63 | 64 | 30 | 6 | 57 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | CancelledError | CancelledError | 42 | 44 | 42 | 42 | 7f1935681e65768693ae35c568dd2992ff49e06c | bigcode/the-stack | train |
5bedcb2f2a8c171e0fbca9c9 | train | class | class Error(Exception):
"""Base APIProxy error type."""
| class Error(Exception):
| """Base APIProxy error type."""
| # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Errors thrown by apiproxy.MakeSyncCall.
"""
class Error(Exception):
| 64 | 64 | 12 | 4 | 60 | qsnake/google_appengine | google/appengine/runtime/apiproxy_errors.py | Python | Error | Error | 22 | 23 | 22 | 22 | 411ee309eb742dffaca595fa396390a3268864a5 | bigcode/the-stack | train |
49e0c35def6ca72fc913e2da | train | class | class Convert2DTo3DTransform(AbstractTransform):
def __init__(self):
pass
def __call__(self, **data_dict):
return convert_2d_to_3d_generator(data_dict)
| class Convert2DTo3DTransform(AbstractTransform):
| def __init__(self):
pass
def __call__(self, **data_dict):
return convert_2d_to_3d_generator(data_dict)
| _shape_seg[-1]))
return data_dict
class Convert3DTo2DTransform(AbstractTransform):
def __init__(self):
pass
def __call__(self, **data_dict):
return convert_3d_to_2d_generator(data_dict)
class Convert2DTo3DTransform(AbstractTransform):
| 64 | 64 | 44 | 11 | 53 | anxingle/nnUNet_simple | nnunet/training/data_augmentation/custom_transforms.py | Python | Convert2DTo3DTransform | Convert2DTo3DTransform | 88 | 93 | 88 | 88 | e53329921f70d00d61225969f25fd653f00d41f6 | bigcode/the-stack | train |
5b91d79d45e2cd90c24e5151 | train | class | class MaskTransform(AbstractTransform):
def __init__(self, dct_for_where_it_was_used, mask_idx_in_seg=1, set_outside_to=0, data_key="data", seg_key="seg"):
"""
data[mask < 0] = 0
Sets everything outside the mask to 0. CAREFUL! outside is defined as < 0, not =0 (in the Mask)!!!
:param dct_for_where_it_was_used... | class MaskTransform(AbstractTransform):
| def __init__(self, dct_for_where_it_was_used, mask_idx_in_seg=1, set_outside_to=0, data_key="data", seg_key="seg"):
"""
data[mask < 0] = 0
Sets everything outside the mask to 0. CAREFUL! outside is defined as < 0, not =0 (in the Mask)!!!
:param dct_for_where_it_was_used:
:param mask_idx_in_seg:
:param set... | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from batchgenerators.transforms import AbstractTransform
class RemoveKeyTransform(AbstractTransform):
def __init__(self, key_to_remove):
self.key_to_remove = ... | 103 | 103 | 345 | 6 | 96 | anxingle/nnUNet_simple | nnunet/training/data_augmentation/custom_transforms.py | Python | MaskTransform | MaskTransform | 28 | 57 | 28 | 28 | 0241197229cc30b9aa731f283dce73d18176a83b | bigcode/the-stack | train |
7d5afc0bc1dc864d4661fa2b | train | class | class ConvertSegmentationToRegionsTransform(AbstractTransform):
def __init__(self, regions, seg_key="seg", output_key="seg", seg_channel=0):
"""
regions are tuple of tuples where each inner tuple holds the class indices that are merged into one region, example:
regions= ((1, 2), (2, )) will result in 2 regions: ... | class ConvertSegmentationToRegionsTransform(AbstractTransform):
| def __init__(self, regions, seg_key="seg", output_key="seg", seg_channel=0):
"""
regions are tuple of tuples where each inner tuple holds the class indices that are merged into one region, example:
regions= ((1, 2), (2, )) will result in 2 regions: one covering the region of labels 1&2 and the other just 2
:pa... | ):
def __init__(self):
pass
def __call__(self, **data_dict):
return convert_3d_to_2d_generator(data_dict)
class Convert2DTo3DTransform(AbstractTransform):
def __init__(self):
pass
def __call__(self, **data_dict):
return convert_2d_to_3d_generator(data_dict)
class ConvertSegmentationToRegionsTransform(Ab... | 88 | 88 | 295 | 10 | 78 | anxingle/nnUNet_simple | nnunet/training/data_augmentation/custom_transforms.py | Python | ConvertSegmentationToRegionsTransform | ConvertSegmentationToRegionsTransform | 96 | 123 | 96 | 96 | d07eb0a396dcf3c56a31a0dd139178847e856af2 | bigcode/the-stack | train |
fd751a845c736e07d4a7defe | train | function | def convert_2d_to_3d_generator(data_dict):
shp = data_dict['orig_shape_data']
current_shape = data_dict['data'].shape
data_dict['data'] = data_dict['data'].reshape((shp[0], shp[1], shp[2], current_shape[-2], current_shape[-1]))
shp = data_dict['orig_shape_seg']
current_shape_seg = data_dict['seg'].shape
data_dict... | def convert_2d_to_3d_generator(data_dict):
| shp = data_dict['orig_shape_data']
current_shape = data_dict['data'].shape
data_dict['data'] = data_dict['data'].reshape((shp[0], shp[1], shp[2], current_shape[-2], current_shape[-1]))
shp = data_dict['orig_shape_seg']
current_shape_seg = data_dict['seg'].shape
data_dict['seg'] = data_dict['seg'].reshape((shp[0],... | shape
data_dict['seg'] = data_dict['seg'].reshape((shp[0], shp[1] * shp[2], shp[3], shp[4]))
data_dict['orig_shape_seg'] = shp
return data_dict
def convert_2d_to_3d_generator(data_dict):
| 64 | 64 | 132 | 13 | 50 | anxingle/nnUNet_simple | nnunet/training/data_augmentation/custom_transforms.py | Python | convert_2d_to_3d_generator | convert_2d_to_3d_generator | 70 | 77 | 70 | 70 | 6334b034e71ec87756662085306df505a13c6ed4 | bigcode/the-stack | train |
461fa9d71d6b634dea657b9d | train | class | class RemoveKeyTransform(AbstractTransform):
def __init__(self, key_to_remove):
self.key_to_remove = key_to_remove
def __call__(self, **data_dict):
_ = data_dict.pop(self.key_to_remove, None)
return data_dict
| class RemoveKeyTransform(AbstractTransform):
| def __init__(self, key_to_remove):
self.key_to_remove = key_to_remove
def __call__(self, **data_dict):
_ = data_dict.pop(self.key_to_remove, None)
return data_dict
| an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from batchgenerators.transforms import AbstractTransform
class RemoveKeyTransform(AbstractTransform):
| 64 | 64 | 56 | 7 | 56 | anxingle/nnUNet_simple | nnunet/training/data_augmentation/custom_transforms.py | Python | RemoveKeyTransform | RemoveKeyTransform | 19 | 25 | 19 | 19 | 9039ef8f98c17e26132e39c0809e4de115c28b2d | bigcode/the-stack | train |
0f4a5d030eeffa496f8d1ee8 | train | function | def convert_3d_to_2d_generator(data_dict):
shp = data_dict['data'].shape
data_dict['data'] = data_dict['data'].reshape((shp[0], shp[1] * shp[2], shp[3], shp[4]))
data_dict['orig_shape_data'] = shp
shp = data_dict['seg'].shape
data_dict['seg'] = data_dict['seg'].reshape((shp[0], shp[1] * shp[2], shp[3], shp[4]))
d... | def convert_3d_to_2d_generator(data_dict):
| shp = data_dict['data'].shape
data_dict['data'] = data_dict['data'].reshape((shp[0], shp[1] * shp[2], shp[3], shp[4]))
data_dict['orig_shape_data'] = shp
shp = data_dict['seg'].shape
data_dict['seg'] = data_dict['seg'].reshape((shp[0], shp[1] * shp[2], shp[3], shp[4]))
data_dict['orig_shape_seg'] = shp
return da... | (data.shape[1]):
if self.dct_for_where_it_was_used[c]:
data[b, c][mask < 0] = self.set_outside_to
data_dict[self.data_key] = data
return data_dict
def convert_3d_to_2d_generator(data_dict):
| 64 | 64 | 127 | 13 | 50 | anxingle/nnUNet_simple | nnunet/training/data_augmentation/custom_transforms.py | Python | convert_3d_to_2d_generator | convert_3d_to_2d_generator | 60 | 67 | 60 | 60 | 0bd4abc98c44fa06d0c1579a6192da838ea8ebb6 | bigcode/the-stack | train |
e89b227ccd934a5a550d730f | train | class | class Convert3DTo2DTransform(AbstractTransform):
def __init__(self):
pass
def __call__(self, **data_dict):
return convert_3d_to_2d_generator(data_dict)
| class Convert3DTo2DTransform(AbstractTransform):
| def __init__(self):
pass
def __call__(self, **data_dict):
return convert_3d_to_2d_generator(data_dict)
| current_shape_seg = data_dict['seg'].shape
data_dict['seg'] = data_dict['seg'].reshape((shp[0], shp[1], shp[2], current_shape_seg[-2], current_shape_seg[-1]))
return data_dict
class Convert3DTo2DTransform(AbstractTransform):
| 64 | 64 | 44 | 11 | 52 | anxingle/nnUNet_simple | nnunet/training/data_augmentation/custom_transforms.py | Python | Convert3DTo2DTransform | Convert3DTo2DTransform | 80 | 85 | 80 | 80 | f5cdc008c1b80e111ab9cdf7db0889538f590976 | bigcode/the-stack | train |
fccffdf96a6ad201ba75a85e | train | class | class Animal(object):
def __init__(self, nome):
self.nome = nome
| class Animal(object):
| def __init__(self, nome):
self.nome = nome
|
import random
class Animal(object):
| 8 | 64 | 19 | 4 | 3 | nnsdtr/OOP-Python | Hereditariedade_e_Polimorfismo/20-Inheriting-the-Superclass_Constructor.py | Python | Animal | Animal | 5 | 7 | 5 | 5 | 10733935e9ac47718ba4fd809d0c5b660a6b2804 | bigcode/the-stack | train |
748ad6fdca70ade311251e78 | train | class | class Cachorro(Animal):
def __init__(self, nome):
"""Superclass constructor:
- super(Classe, instância_self).método(valor)
Pegue a superclasse de 'Cachorro' - ou seja, 'Animal' - e passe a
instância de 'Cachorro' para qualquer método, como por exemplo
o construtor... | class Cachorro(Animal):
| def __init__(self, nome):
"""Superclass constructor:
- super(Classe, instância_self).método(valor)
Pegue a superclasse de 'Cachorro' - ou seja, 'Animal' - e passe a
instância de 'Cachorro' para qualquer método, como por exemplo
o construtor __init__"""
pr... |
import random
class Animal(object):
def __init__(self, nome):
self.nome = nome
class Cachorro(Animal):
| 29 | 64 | 154 | 6 | 22 | nnsdtr/OOP-Python | Hereditariedade_e_Polimorfismo/20-Inheriting-the-Superclass_Constructor.py | Python | Cachorro | Cachorro | 10 | 23 | 10 | 10 | 0b59857266dd85f84721bfa5d0729d5d934a578e | bigcode/the-stack | train |
9bfbb4687e575565cb0e97f0 | train | class | class Connection(Thread):
def __init__(
self,
connector: Callable[[], sqlite3.Connection],
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:
super().__init__()
self._running = True
self._connection: Optional[sqlite3.Connection] = None
self._conn... | class Connection(Thread):
| def __init__(
self,
connector: Callable[[], sqlite3.Connection],
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:
super().__init__()
self._running = True
self._connection: Optional[sqlite3.Connection] = None
self._connector = connector
... | # Copyright 2018 John Reese
# Licensed under the MIT license
"""
Core implementation of aiosqlite proxies
"""
import asyncio
import logging
import sqlite3
import warnings
import sys
from functools import partial
from pathlib import Path
from queue import Empty, Queue
from threading import Thread
from typing import (
... | 182 | 256 | 2,157 | 4 | 177 | zsoltm/aiosqlite | aiosqlite/core.py | Python | Connection | Connection | 44 | 350 | 44 | 44 | 494c11551962a9d10b181eb8fb648e0c0a84ff66 | bigcode/the-stack | train |
76e6f272bea378bb0ed3a6cf | train | function | def connect(
database: Union[str, Path],
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Any
) -> Connection:
"""Create and return a connection proxy to the sqlite database."""
if loop is not None:
warn(
"aiosqlite.connect() no longer uses the `loop` parameter... | def connect(
database: Union[str, Path],
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Any
) -> Connection:
| """Create and return a connection proxy to the sqlite database."""
if loop is not None:
warn(
"aiosqlite.connect() no longer uses the `loop` parameter",
DeprecationWarning,
)
def connector() -> sqlite3.Connection:
if isinstance(database, str):
lo... | .backup,
target,
pages=pages,
progress=progress,
name=name,
sleep=sleep,
)
def connect(
database: Union[str, Path],
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Any
) -> Connection:
| 64 | 64 | 148 | 37 | 27 | zsoltm/aiosqlite | aiosqlite/core.py | Python | connect | connect | 353 | 377 | 353 | 358 | 0f1f51206af7ecf057668728e1c27e4570d2e12a | bigcode/the-stack | train |
c90ae5da71c217caf3d3dd9f | train | function | def get_loop(future: asyncio.Future) -> asyncio.AbstractEventLoop:
if sys.version_info >= (3, 7):
return future.get_loop()
else:
return future._loop
| def get_loop(future: asyncio.Future) -> asyncio.AbstractEventLoop:
| if sys.version_info >= (3, 7):
return future.get_loop()
else:
return future._loop
| Type,
Union,
)
from warnings import warn
from .context import contextmanager
from .cursor import Cursor
__all__ = ["connect", "Connection", "Cursor"]
LOG = logging.getLogger("aiosqlite")
def get_loop(future: asyncio.Future) -> asyncio.AbstractEventLoop:
| 64 | 64 | 42 | 15 | 49 | zsoltm/aiosqlite | aiosqlite/core.py | Python | get_loop | get_loop | 37 | 41 | 37 | 37 | 98db5b5027a3fa94f9f4325ce8188046fc3c2d97 | bigcode/the-stack | train |
44937736c41ee053374fda85 | train | function | def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
"""
Randomly split given sample to a training- and testing sample
Parameters
----------
X : DataFrame of shape (n_samples, n_features)
Dat... | def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
| """
Randomly split given sample to a training- and testing sample
Parameters
----------
X : DataFrame of shape (n_samples, n_features)
Data frame of samples and feature values.
y : Series of shape (n_samples, )
Responses corresponding samples in data frame.
train_proportio... | from typing import Tuple
import numpy as np
import pandas as pd
def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
| 58 | 89 | 299 | 43 | 14 | OmerLif/IML.HUJI | IMLearn/utils/utils.py | Python | split_train_test | split_train_test | 6 | 40 | 6 | 7 | 104d2768fd7388223e22fc84f3aa5138c5fec2b4 | bigcode/the-stack | train |
ba814b2260abaa864fa11999 | train | function | def confusion_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Compute a confusion matrix between two sets of integer vectors
Parameters
----------
a: ndarray of shape (n_samples,)
First vector of integers
b: ndarray of shape (n_samples,)
Second vector of integers
R... | def confusion_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
| """
Compute a confusion matrix between two sets of integer vectors
Parameters
----------
a: ndarray of shape (n_samples,)
First vector of integers
b: ndarray of shape (n_samples,)
Second vector of integers
Returns
-------
confusion_matrix: ndarray of shape (a_uniqu... | train = X.sample(frac=train_proportion)
test = X.loc[X.index.difference(train.index)]
return np.array(train), np.array(y.loc[train.index]), np.array(test), np.array(y.loc[test.index])
def confusion_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
| 64 | 64 | 138 | 17 | 47 | OmerLif/IML.HUJI | IMLearn/utils/utils.py | Python | confusion_matrix | confusion_matrix | 43 | 61 | 43 | 43 | 55a9f25e267fc76fb5d06f16dd1920aafc1617e9 | bigcode/the-stack | train |
4ae5607c80c2c2dd0862a57f | train | class | @pulumi.input_type
class MyInputType:
first_value: pulumi.Input[str] = pulumi.property("firstValue")
second_value: Optional[pulumi.Input[float]] = pulumi.property("secondValue")
def __init__(self,
first_value: pulumi.Input[str],
second_value: Optional[pulumi.Input[float]] ... | @pulumi.input_type
class MyInputType:
| first_value: pulumi.Input[str] = pulumi.property("firstValue")
second_value: Optional[pulumi.Input[float]] = pulumi.property("secondValue")
def __init__(self,
first_value: pulumi.Input[str],
second_value: Optional[pulumi.Input[float]] = None):
pulumi.set(self, "fir... |
@pulumi.input_type
class MySimpleInputType:
first_value: pulumi.Input[str] = pulumi.property("firstValue")
second_value: Optional[pulumi.Input[float]] = pulumi.property("secondValue", default=None)
@pulumi.input_type
class MyInputType:
| 64 | 64 | 105 | 11 | 53 | sticha/pulumi | sdk/python/lib/test/test_types_input_type.py | Python | MyInputType | MyInputType | 28 | 37 | 28 | 29 | 3ebc4f0b853cdc780f0ac27ccceabb5e391b3282 | bigcode/the-stack | train |
61d6018683ee689d78ac6877 | train | class | @pulumi.input_type
class DefaultArgs:
a: pulumi.Input[str] = pulumi.property("a", default="foo")
b: pulumi.Input[str] = pulumi.property("b", default="bar")
c: Optional[pulumi.Input[str]] = pulumi.property("c", default=None)
| @pulumi.input_type
class DefaultArgs:
| a: pulumi.Input[str] = pulumi.property("a", default="foo")
b: pulumi.Input[str] = pulumi.property("b", default="bar")
c: Optional[pulumi.Input[str]] = pulumi.property("c", default=None)
| ]]:
"""Second value docstring."""
return pulumi.get(self, "second_value")
@second_value.setter
def second_value(self, value: Optional[pulumi.Input[float]]):
pulumi.set(self, "second_value", value)
@pulumi.input_type
class DefaultArgs:
| 64 | 64 | 68 | 10 | 54 | sticha/pulumi | sdk/python/lib/test/test_types_input_type.py | Python | DefaultArgs | DefaultArgs | 71 | 75 | 71 | 72 | d387501a9cbd05de69d46d82f50628940a6fe9c6 | bigcode/the-stack | train |
48b3f935a94d859999f92dc0 | train | class | @pulumi.input_type
class MySimpleInputType:
first_value: pulumi.Input[str] = pulumi.property("firstValue")
second_value: Optional[pulumi.Input[float]] = pulumi.property("secondValue", default=None)
| @pulumi.input_type
class MySimpleInputType:
| first_value: pulumi.Input[str] = pulumi.property("firstValue")
second_value: Optional[pulumi.Input[float]] = pulumi.property("secondValue", default=None)
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from typing import Optional
import pulumi
import pulumi._types as _types
@pulumi.input_type
class MySimpleInputType:
| 64 | 64 | 52 | 12 | 51 | sticha/pulumi | sdk/python/lib/test/test_types_input_type.py | Python | MySimpleInputType | MySimpleInputType | 22 | 25 | 22 | 23 | c58b36a5eb6ae207a51dea629789f58d6bb393c6 | bigcode/the-stack | train |
0e790584626492dac9c5dda9 | train | class | class InputTypeTests(unittest.TestCase):
def test_decorator_raises(self):
with self.assertRaises(AssertionError) as cm:
@pulumi.input_type
@pulumi.input_type
class Foo:
pass
with self.assertRaises(AssertionError) as cm:
@pulumi.input_t... | class InputTypeTests(unittest.TestCase):
| def test_decorator_raises(self):
with self.assertRaises(AssertionError) as cm:
@pulumi.input_type
@pulumi.input_type
class Foo:
pass
with self.assertRaises(AssertionError) as cm:
@pulumi.input_type
@pulumi.output_type
... | pulumi.set(self, "second_value", second_value)
# Property with empty getter/setter bodies.
@property
@pulumi.getter(name="firstValue")
def first_value(self) -> pulumi.Input[str]:
"""First value docstring."""
...
@first_value.setter
def first_value(self, value: pulumi.In... | 245 | 245 | 819 | 8 | 237 | sticha/pulumi | sdk/python/lib/test/test_types_input_type.py | Python | InputTypeTests | InputTypeTests | 78 | 175 | 78 | 78 | 5e3887799f3f0a0480e77671a8c42992df7d2e9c | bigcode/the-stack | train |
8fa416b05bfd19d1dd9d0ae1 | train | class | @pulumi.input_type
class MyDeclaredPropertiesInputType:
def __init__(self,
first_value: pulumi.Input[str],
second_value: Optional[pulumi.Input[float]] = None):
pulumi.set(self, "first_value", first_value)
pulumi.set(self, "second_value", second_value)
# Propert... | @pulumi.input_type
class MyDeclaredPropertiesInputType:
| def __init__(self,
first_value: pulumi.Input[str],
second_value: Optional[pulumi.Input[float]] = None):
pulumi.set(self, "first_value", first_value)
pulumi.set(self, "second_value", second_value)
# Property with empty getter/setter bodies.
@property
@pu... | init__(self,
first_value: pulumi.Input[str],
second_value: Optional[pulumi.Input[float]] = None):
pulumi.set(self, "first_value", first_value)
pulumi.set(self, "second_value", second_value)
@pulumi.input_type
class MyDeclaredPropertiesInputType:
| 67 | 67 | 226 | 13 | 54 | sticha/pulumi | sdk/python/lib/test/test_types_input_type.py | Python | MyDeclaredPropertiesInputType | MyDeclaredPropertiesInputType | 40 | 68 | 40 | 41 | 915a8975031a04294f23acae3c62c3de5c784f7a | bigcode/the-stack | train |
c28270d75680f1eaf6aa7ddd | train | function | @contextmanager
def capture(command, *args, **kwargs):
out = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), 'utf-8')
try:
command(*args, **kwargs)
sys.stdout.seek(0)
yield sys.stdout.read()
finally:
sys.stdout = out
| @contextmanager
def capture(command, *args, **kwargs):
| out = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), 'utf-8')
try:
command(*args, **kwargs)
sys.stdout.seek(0)
yield sys.stdout.read()
finally:
sys.stdout = out
| import sys
from io import TextIOWrapper, BytesIO
from contextlib import contextmanager
@contextmanager
def capture(command, *args, **kwargs):
| 34 | 64 | 68 | 14 | 19 | OSM-es/CatAtom2Osm | test/tools.py | Python | capture | capture | 5 | 14 | 5 | 6 | 2e20f2494062fcbd60bf90d3d9ddfa7ae849c2f4 | bigcode/the-stack | train |
659d3a0895e057ccb09e0794 | train | function | @pivot.register(ProcessEvent, ["create"], FileEvent, ["create"], abstract=True)
def cmd_copy(process_event, ctx):
"""
:param Process process_event: The input event to pivot on
:param DataModelQueryLayer ctx: Search context to query over
"""
window = {'start': process_event.time - datetime.timedelta(... | @pivot.register(ProcessEvent, ["create"], FileEvent, ["create"], abstract=True)
def cmd_copy(process_event, ctx):
| """
:param Process process_event: The input event to pivot on
:param DataModelQueryLayer ctx: Search context to query over
"""
window = {'start': process_event.time - datetime.timedelta(minutes=1)}
if process_event.duration is not None:
window['end'] = process_event.time + process_event.... | _ip)
criteria['hostname'] = network_event.state.hostname
# Ignore thread creations into the kernel
query = ctx.query(NetworkEvent.search('start', **criteria), **window)
for result in query:
pivot_flow = NetworkEvent.update_existing('start', **result)
if int(piv... | 170 | 170 | 567 | 26 | 143 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | cmd_copy | cmd_copy | 414 | 464 | 414 | 415 | 26c2cb00cef54a6c81af49ff0b69487cabe84f2b | bigcode/the-stack | train |
6f4970d93d6f106589ccbfbb | train | function | @pivot.register(NetworkEvent, ['message'], FileEvent, ['create', 'modify'], abstract=True)
def smb_file_write(network_event, ctx):
""" Given a flow event that has protocol information, pivot from host information into the file event on the
host. If it doesn't exist, then add
"""
if network_event.state.... | @pivot.register(NetworkEvent, ['message'], FileEvent, ['create', 'modify'], abstract=True)
def smb_file_write(network_event, ctx):
| """ Given a flow event that has protocol information, pivot from host information into the file event on the
host. If it doesn't exist, then add
"""
if network_event.state.proto_info is None:
return
if network_event.state.proto_info.startswith('SMB2 Write Request') and 'File: ' in network_... | in ProcessEvent.fields:
thread_field = 'target_' + field
if thread_field in thread_event.state:
process_info[field] = thread_event.state[thread_field]
inject_time = thread_event.time
fake_injected = ProcessEvent.update_existing(action='inject', metadata={'synthe... | 125 | 125 | 419 | 30 | 94 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | smb_file_write | smb_file_write | 155 | 195 | 155 | 156 | 6dab6ee111399c0fe63ff522fa7f891c12ccb40a | bigcode/the-stack | train |
07ca2d285efbb260ddf5d220 | train | function | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def wmic_process_create(process_event, ctx):
"""
:param Process process_event: The input event to pivot on
:param DataModelQueryLayer ctx: Search context to query over
"""
if process_event.state.exe.lower() == "wmic.... | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def wmic_process_create(process_event, ctx):
| """
:param Process process_event: The input event to pivot on
:param DataModelQueryLayer ctx: Search context to query over
"""
if process_event.state.exe.lower() == "wmic.exe":
args = command_to_argv(process_event.state.command_line)
lower_args = [_.lower() for _ in args]
i... | (FieldQuery("parent_image_path") == "C:\\Windows\\system32\\taskeng.exe") |
(FieldQuery("parent_image_path") == "C:\\Windows\\system32\\svchost.exe")
)
for process_event in ctx.query(query, start=process_event.time):
task_process = ProcessEvent.update_existing('creat... | 111 | 111 | 373 | 28 | 82 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | wmic_process_create | wmic_process_create | 318 | 357 | 318 | 319 | ed2ffd4242342c1bfab5a7dcf94864367a3289a0 | bigcode/the-stack | train |
e62dbe5807dc8ccc6202c813 | train | function | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def at(process_event, ctx):
""" :type process_event: Process """
if process_event.state.exe.lower() == "at.exe" and "/?" not in str(process_event.state.command_line):
args = command_to_argv(process_event.state.command_li... | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def at(process_event, ctx):
| """ :type process_event: Process """
if process_event.state.exe.lower() == "at.exe" and "/?" not in str(process_event.state.command_line):
args = command_to_argv(process_event.state.command_line)
lower_args = [_.lower() for _ in args]
if len(args) == 1:
return
crite... | (
(FieldQuery("parent_image_path") == "C:\\Windows\\System32\\taskeng.exe") |
(FieldQuery("parent_image_path") == "C:\\Windows\\System32\\svchost.exe")
)
for process_event in ctx.query(query, start=process_event.time):
task_process = ProcessEvent.update_existing('cr... | 109 | 109 | 364 | 25 | 83 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | at | at | 279 | 315 | 279 | 280 | e12a8a920b44a0d1d2c8a2ea1780312fcd041481 | bigcode/the-stack | train |
9696d536bb10b0e1b4c940a2 | train | function | @pivot.register(NetworkEvent, ["start"], NetworkEvent, ["start"], abstract=True)
def mapped_rpc(network_event, ctx):
if network_event.state.dest_port == '135' and 'pid' in network_event.state:
window = {'start': network_event.time - datetime.timedelta(seconds=1), 'end': network_event.time + datetime.timedel... | @pivot.register(NetworkEvent, ["start"], NetworkEvent, ["start"], abstract=True)
def mapped_rpc(network_event, ctx):
| if network_event.state.dest_port == '135' and 'pid' in network_event.state:
window = {'start': network_event.time - datetime.timedelta(seconds=1), 'end': network_event.time + datetime.timedelta(seconds=10)}
criteria = Criteria(pid=network_event.state.pid, src_ip=network_event.state.src_ip, dest_ip=n... | .replace("'", '"')
for process_event in ctx.query(ProcessEvent.search('create', **criteria), start=process_event.time):
task_process = ProcessEvent.update_existing('create', **process_event)
yield task_process
@pivot.register(NetworkEvent, ["start"], NetworkEvent, ["start"], abstract=Tr... | 73 | 73 | 246 | 26 | 46 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | mapped_rpc | mapped_rpc | 391 | 411 | 391 | 392 | f6b05d6c75c42d3cc434ddd4d04168c4d346b8c5 | bigcode/the-stack | train |
eaf169ecb13f17a1edad661a | train | function | @pivot.register(ProcessEvent, ['create', 'inject'], ThreadEvent, ['remote_create'], depends=['process_end'])
def thread_inject(process_event, ctx=None):
""" Given a suspicious process, detects all processes that it injected into.
A more complex pivot, because the destination may also act legitimately
if the... | @pivot.register(ProcessEvent, ['create', 'inject'], ThreadEvent, ['remote_create'], depends=['process_end'])
def thread_inject(process_event, ctx=None):
| """ Given a suspicious process, detects all processes that it injected into.
A more complex pivot, because the destination may also act legitimately
if the prior threads were not tampered with. Thus, this may require
greater granularity (thread level) in order to better resolve its pivots
to ignore ... | 4:
host_info['ip_address'] = host_string
except ValueError:
host_info['fqdn'] = host_string
host_info['hostname'] = host_string.split(".")[0]
else:
host_info['hostname'] = host_string.split(".")[0]
return host_info
@pivot.register(ProcessEvent, ['create',... | 100 | 100 | 336 | 34 | 65 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | thread_inject | thread_inject | 41 | 70 | 41 | 42 | 6e8df19c8778c413e33d072208544de8bd75c10c | bigcode/the-stack | train |
cf9a67d7c9f5b1eb14a7338d | train | function | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def sc(process_event, ctx):
""" :type process_event: Process """
if process_event.state.exe.lower() == "sc.exe" and "binpath=" in str(process_event.state.command_line.lower()):
args = command_to_argv(process_event.state.... | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def sc(process_event, ctx):
| """ :type process_event: Process """
if process_event.state.exe.lower() == "sc.exe" and "binpath=" in str(process_event.state.command_line.lower()):
args = command_to_argv(process_event.state.command_line)
criteria = Criteria(parent_image_path="C:\\windows\\system32\\services.exe")
if ... | _event in ctx.query(ProcessEvent.search('create', **criteria),
start=process_event.time - datetime.timedelta(seconds=10),
end=process_event.time + datetime.timedelta(minutes=1)):
task_process = ProcessEvent.update_existing('create... | 84 | 84 | 283 | 25 | 58 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | sc | sc | 360 | 388 | 360 | 361 | 8db5e6b47820ef94cc059295b81a9b72db11af93 | bigcode/the-stack | train |
c10f4b01b0aa4639575aed5c | train | function | @pivot.register(FileEvent, ['create', 'modify'], FileEvent, ['create', 'modify'], abstract=True)
def remote_file_modify(file_event, ctx):
""" Detect file writes to a network share by looking for file events that look similar to
\\host\share\relative\path\to\file.extension
Pivot onto the other host to find ... | @pivot.register(FileEvent, ['create', 'modify'], FileEvent, ['create', 'modify'], abstract=True)
def remote_file_modify(file_event, ctx):
| """ Detect file writes to a network share by looking for file events that look similar to
\\host\share\relative\path\to\file.extension
Pivot onto the other host to find the corresponding file event. If ony can't be found, fabricate this event
"""
file_path = file_event.state.file_path
if file_p... |
# Create a fake one if none can be found
if len(files) == 0:
file_fields = dict(file_path=wildcard_path, file_name=wildcard_path.split('\\').pop())
for field in ('fqdn', 'hostname'):
if network_event.state[field]:
file_fields[field] = networ... | 139 | 139 | 466 | 33 | 106 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | remote_file_modify | remote_file_modify | 198 | 239 | 198 | 199 | f3caff794778a29ca9707b958980b8f4352c01a1 | bigcode/the-stack | train |
5b965cbb3d6b0711a274a71e | train | function | def extract_host(host_string):
prefix = '\\\\'
host_info = {}
if host_string.startswith(prefix):
host_string = host_string[len(prefix):]
if "." in host_string:
try:
ip_list = [int(_) for _ in host_string.split('.')]
if len(ip_list) == 4:
host_info[... | def extract_host(host_string):
| prefix = '\\\\'
host_info = {}
if host_string.startswith(prefix):
host_string = host_string[len(prefix):]
if "." in host_string:
try:
ip_list = [int(_) for _ in host_string.split('.')]
if len(ip_list) == 4:
host_info['ip_address'] = host_string
... | ThreadEvent, RegistryEvent
from app.cascade.data_model.query import FieldQuery
from app.cascade.data_model import pivot
from app.cascade.data_model.pivots import Criteria
from app.utils import command_to_argv, next_arg
logger = logging.getLogger(__name__)
def extract_host(host_string):
| 64 | 64 | 132 | 6 | 58 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | extract_host | extract_host | 23 | 38 | 23 | 23 | 557dbd618c43c9ae31e4aa3e3c58f7d623aaa689 | bigcode/the-stack | train |
6caec4121c8c42e2a79ba641 | train | function | @pivot.register(ThreadEvent, ['remote_create'], ProcessEvent, ['inject'], abstract=True)
def tainted_process(thread_event, ctx):
""" Given a thread injection event, taint the process from that point forward.
:type thread_event: Thread
"""
# The process must have existed by the time the remote thread was... | @pivot.register(ThreadEvent, ['remote_create'], ProcessEvent, ['inject'], abstract=True)
def tainted_process(thread_event, ctx):
| """ Given a thread injection event, taint the process from that point forward.
:type thread_event: Thread
"""
# The process must have existed by the time the remote thread was created
window = {'end': thread_event.time + datetime.timedelta(minutes=1), 'last': 1}
criteria = Criteria(pid=thread_ev... | .state.to_mongo().items() if k.startswith("src_")}
criteria.coalesce(src_fields, 'image_path', 'exe', force=False)
criteria.coalesce(src_fields, 'parent_image_path', 'parent_exe', force=False)
criteria.coalesce(src_fields, 'ppid', force=False)
parent_query = ProcessEvent.search(action='... | 152 | 152 | 509 | 28 | 123 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | tainted_process | tainted_process | 101 | 152 | 101 | 102 | c4b117bd5737481f361255c7a79fad88a2eeecb7 | bigcode/the-stack | train |
22f51448738ea98266d535c3 | train | function | @pivot.register(ThreadEvent, ['remote_create'], ProcessEvent, ["create"], reverse=True, inverse='thread_inject')
def injection_source(thread_event, ctx=None):
""" Given a suspicious thread, determine the process(es) on each endpoint
of the connection. This will resolve the processes, but will not look for
c... | @pivot.register(ThreadEvent, ['remote_create'], ProcessEvent, ["create"], reverse=True, inverse='thread_inject')
def injection_source(thread_event, ctx=None):
| """ Given a suspicious thread, determine the process(es) on each endpoint
of the connection. This will resolve the processes, but will not look for
creation or termination events. As a result, it will not pivot onto the
launched child processes of the other endpoints. This would avoid investigating
... | None:
thread_field = 'src_' + process_field
if thread_field in ThreadEvent.fields and thread_field not in remote_thread.state:
remote_thread.state[thread_field] = process_event.state[process_field]
remote_thread.save()
yield remote_thread
@pivot.regi... | 90 | 90 | 303 | 34 | 55 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | injection_source | injection_source | 73 | 98 | 73 | 74 | ea573b7e02d6f961d0855517af6239ca377f29c1 | bigcode/the-stack | train |
ed68c40fec138c4315d6d838 | train | function | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def schtasks(process_event, ctx):
""" :type process_event: Process """
if process_event.state.exe.lower() == "schtasks.exe" and "/tr" in str(process_event.state.command_line).lower():
args = command_to_argv(process_event.... | @pivot.register(ProcessEvent, ['create'], ProcessEvent, ['create'], abstract=True)
def schtasks(process_event, ctx):
| """ :type process_event: Process """
if process_event.state.exe.lower() == "schtasks.exe" and "/tr" in str(process_event.state.command_line).lower():
args = command_to_argv(process_event.state.command_line)
lower_args = [_.lower() for _ in args]
criteria = Criteria()
# if schedu... | Event.update_existing(file_event.action, **remote_file_event)
yield remote_file
break
else:
# if no file events can be found, then make one up
file_time = file_event.time + datetime.timedelta(seconds=3)
remote_file = FileEvent.update_existing(file_eve... | 109 | 109 | 366 | 26 | 82 | inmadria/cascade-server | app/cascade/windows_pivots.py | Python | schtasks | schtasks | 242 | 276 | 242 | 243 | b9e46861bdfbd9f9958d00f0d18ecd2ceaa6bbb3 | bigcode/the-stack | train |
d4b69630a8969b33cf492068 | train | class | class Test_SimpleConfig(SequentialTestCase):
def setUp(self):
super(Test_SimpleConfig, self).setUp()
# make sure "read_user_config" and "user_dir" return a temporary directory.
self.electrum_dir = tempfile.mkdtemp()
# Do the same for the user dir to avoid overwriting the real config... | class Test_SimpleConfig(SequentialTestCase):
| def setUp(self):
super(Test_SimpleConfig, self).setUp()
# make sure "read_user_config" and "user_dir" return a temporary directory.
self.electrum_dir = tempfile.mkdtemp()
# Do the same for the user dir to avoid overwriting the real configuration
# for development machines wit... | import ast
import sys
import os
import tempfile
import shutil
from io import StringIO
from electrum_audax.simple_config import (SimpleConfig, read_user_config)
from . import SequentialTestCase
class Test_SimpleConfig(SequentialTestCase):
| 55 | 256 | 1,668 | 10 | 44 | enkrypter/audax-polaris | electrum_audax/tests/test_simple_config.py | Python | Test_SimpleConfig | Test_SimpleConfig | 13 | 147 | 13 | 14 | 4b194bb4cad3ede87e92b8cad0e26b45458a14c8 | bigcode/the-stack | train |
b037b4834813bc894b1bcdbe | train | class | class TestUserConfig(SequentialTestCase):
def setUp(self):
super(TestUserConfig, self).setUp()
self._saved_stdout = sys.stdout
self._stdout_buffer = StringIO()
sys.stdout = self._stdout_buffer
self.user_dir = tempfile.mkdtemp()
def tearDown(self):
super(TestUse... | class TestUserConfig(SequentialTestCase):
| def setUp(self):
super(TestUserConfig, self).setUp()
self._saved_stdout = sys.stdout
self._stdout_buffer = StringIO()
sys.stdout = self._stdout_buffer
self.user_dir = tempfile.mkdtemp()
def tearDown(self):
super(TestUserConfig, self).tearDown()
shutil.rm... | .fee_to_depth(6.5))
self.assertEqual(370000, config.fee_to_depth(6))
self.assertEqual(495000, config.fee_to_depth(5.5))
self.assertEqual(36495000, config.fee_to_depth(0.5))
class TestUserConfig(SequentialTestCase):
| 71 | 71 | 239 | 9 | 62 | enkrypter/audax-polaris | electrum_audax/tests/test_simple_config.py | Python | TestUserConfig | TestUserConfig | 150 | 185 | 150 | 151 | 65231ce6010ef192bd45bffa659c46b91c3d5795 | bigcode/the-stack | train |
05d9a9e6d3df8c339303608a | train | class | class AccountTests(ApiTestBase):
"""Tests for AccountsEndpointsMixin."""
@staticmethod
def init_all(api):
return [
{'name': 'test_login', 'test': AccountTests('test_login', api)},
{'name': 'test_login_mock', 'test': AccountTests('test_login_mock', api)},
{
... | class AccountTests(ApiTestBase):
| """Tests for AccountsEndpointsMixin."""
@staticmethod
def init_all(api):
return [
{'name': 'test_login', 'test': AccountTests('test_login', api)},
{'name': 'test_login_mock', 'test': AccountTests('test_login_mock', api)},
{
'name': 'test_login_fai... | import unittest
import json
from urllib.request import urlopen
from io import BytesIO
from .common import (
Client,
ClientError,
ClientLoginError,
ApiTestBase,
compat_mock,
compat_urllib_error,
MockResponse,
)
class AccountTests(ApiTestBase):
| 63 | 256 | 3,590 | 7 | 56 | zmike808/instagram_private_api_old | api_tests/private/accounts.py | Python | AccountTests | AccountTests | 17 | 493 | 17 | 17 | eb00dd35b888f4d6c6c9642c26fc6fb7bb39d55a | bigcode/the-stack | train |
8e6e6075cfb3890f8ae7b024 | train | function | def piecewise_distribution(num_knots: int, ceiling: bool = False) -> Type[Piecewise]:
if ceiling:
return type("CeilingPiecewise{}".format(num_knots), (CeilingPiecewise,), {'_num_knots': num_knots})
else:
return type("Piecewise{}".format(num_knots), (Piecewise,), {'_num_knots': num_knots})
| def piecewise_distribution(num_knots: int, ceiling: bool = False) -> Type[Piecewise]:
| if ceiling:
return type("CeilingPiecewise{}".format(num_knots), (CeilingPiecewise,), {'_num_knots': num_knots})
else:
return type("Piecewise{}".format(num_knots), (Piecewise,), {'_num_knots': num_knots})
| ):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if cls.arg_constraints:
cls.arg_constraints.update(ceiling=constraints.unit_interval)
def piecewise_distribution(num_knots: int, ceiling: bool = False) -> Type[Piecewise]:
| 64 | 64 | 85 | 22 | 42 | strongio/strong-glm | strong_glm/distributions/piecewise.py | Python | piecewise_distribution | piecewise_distribution | 162 | 166 | 162 | 162 | 41b06e834396ab1f369adfe4888b197f2ffae6a3 | bigcode/the-stack | train |
03ea6c111f9eb81a20eea6c6 | train | class | class Piecewise(torch.distributions.ExponentialFamily):
support = constraints.positive
arg_constraints = None
_num_knots = None
def __init_subclass__(cls, **kwargs):
if cls._num_knots is not None:
# if subclass defines the _num_knots, then constraints can be a class-attribute (other... | class Piecewise(torch.distributions.ExponentialFamily):
| support = constraints.positive
arg_constraints = None
_num_knots = None
def __init_subclass__(cls, **kwargs):
if cls._num_knots is not None:
# if subclass defines the _num_knots, then constraints can be a class-attribute (otherwise only
# instance-attr, defined in __init... | from collections import OrderedDict
from typing import Sequence, Optional, Tuple, Type
from numbers import Number
import torch
from torch.distributions import constraints
from torch.distributions.utils import broadcast_all
from strong_glm.distributions.ceiling import CeilingMixin
class Piecewise(torch.distributions.... | 63 | 256 | 1,346 | 10 | 52 | strongio/strong-glm | strong_glm/distributions/piecewise.py | Python | Piecewise | Piecewise | 13 | 152 | 13 | 13 | cb9e1220548595a672a2ba22a2a1eb01b83df119 | bigcode/the-stack | train |
e7d89cb5446c38f6939bef90 | train | class | class CeilingPiecewise(CeilingMixin, Piecewise):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if cls.arg_constraints:
cls.arg_constraints.update(ceiling=constraints.unit_interval)
| class CeilingPiecewise(CeilingMixin, Piecewise):
| def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if cls.arg_constraints:
cls.arg_constraints.update(ceiling=constraints.unit_interval)
| Error
def rsample(self, sample_shape: torch.Size = torch.Size()):
raise NotImplementedError
def icdf(self, value):
raise NotImplementedError
def enumerate_support(self, expand=True):
raise NotImplementedError
class CeilingPiecewise(CeilingMixin, Piecewise):
| 64 | 64 | 53 | 12 | 51 | strongio/strong-glm | strong_glm/distributions/piecewise.py | Python | CeilingPiecewise | CeilingPiecewise | 155 | 159 | 155 | 155 | 5208ff9a12dcf07ce9b7b45fa31e37305fdd66e4 | bigcode/the-stack | train |
42bec990f8577f83fbc8b890 | train | function | @posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, author=current_user)
db.session.add(post)
db.session.commit()
flash(u"Your post has bee... | @posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
| form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, author=current_user)
db.session.add(post)
db.session.commit()
flash(u"Your post has been created!", "success")
return redirect(url_for("main.home"))
return re... | abort
from flaskblog import db
from flask_login import current_user, login_required
from flaskblog.models import Post
from flaskblog.posts.forms import PostForm
posts = Blueprint('posts', __name__)
@posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
| 64 | 64 | 107 | 21 | 43 | nguyenthieu95/first_flask_blog | flaskblog/posts/routes.py | Python | new_post | new_post | 9 | 19 | 9 | 11 | 8ddba1adf5ad1bb614dc2656ce6df054b908109e | bigcode/the-stack | train |
cbab96e3226b0aed3051e4cb | train | function | @posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content... | @posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
| post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash(u"Your post has been updated!", "success")
... | >")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template("post.html", title=post.title, post=post)
@posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
| 64 | 64 | 162 | 29 | 35 | nguyenthieu95/first_flask_blog | flaskblog/posts/routes.py | Python | update_post | update_post | 28 | 44 | 28 | 30 | b63353870b178fe03ee7690640fb880d606c4594 | bigcode/the-stack | train |
ab4cceeea7a54fe979c81b48 | train | function | @posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash(u"Your post has been deleted!", "success")
return redi... | @posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
| post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash(u"Your post has been deleted!", "success")
return redirect(url_for("main.home"))
| form.title.data = post.title
form.content.data = post.content
return render_template("create_post.html", title="Update Post", form=form, legend="Update Post")
@posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
| 64 | 64 | 84 | 26 | 38 | nguyenthieu95/first_flask_blog | flaskblog/posts/routes.py | Python | delete_post | delete_post | 47 | 56 | 47 | 49 | ef636e9c611968626ad4b40727099abe85ef9647 | bigcode/the-stack | train |
06bb042600595cab6e4ce86b | train | function | @posts.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template("post.html", title=post.title, post=post)
| @posts.route("/post/<int:post_id>")
def post(post_id):
| post = Post.query.get_or_404(post_id)
return render_template("post.html", title=post.title, post=post)
| db.session.commit()
flash(u"Your post has been created!", "success")
return redirect(url_for("main.home"))
return render_template("create_post.html", title="New Post", form=form, legend="New Post")
@posts.route("/post/<int:post_id>")
def post(post_id):
| 64 | 64 | 45 | 16 | 48 | nguyenthieu95/first_flask_blog | flaskblog/posts/routes.py | Python | post | post | 22 | 25 | 22 | 23 | 68525d04766ebe827045dbb9e830acca1dd9a6a6 | bigcode/the-stack | train |
1e5b92368130e869f6c4465b | train | class | class SedDepEroder(Component):
"""
This module implements sediment flux dependent channel incision
following::
E = f(Qs, Qc) * ([a stream power-like term] - [an optional threshold]),
where E is the bed erosion rate, Qs is the volumetric sediment flux
into a node, and Qc is the volumetric s... | class SedDepEroder(Component):
| """
This module implements sediment flux dependent channel incision
following::
E = f(Qs, Qc) * ([a stream power-like term] - [an optional threshold]),
where E is the bed erosion rate, Qs is the volumetric sediment flux
into a node, and Qc is the volumetric sediment transport capacity at
... | from __future__ import print_function
import warnings
from six.moves import range
import numpy as np
from time import sleep
from landlab import ModelParameterDictionary, CLOSED_BOUNDARY, Component
from landlab.core.model_parameter_dictionary import MissingKeyError
from landlab.field.scalar_data_fields import FieldE... | 94 | 256 | 9,930 | 8 | 85 | awickert/landlab | landlab/components/stream_power/sed_flux_dep_incision.py | Python | SedDepEroder | SedDepEroder | 17 | 977 | 17 | 17 | 56728208f0a4246634369ca449584f436a00504d | bigcode/the-stack | train |
7ba5eb5fda8099cbdd8e34f9 | train | function | def mask_csv_func():
return 'completed masking'
| def mask_csv_func():
| return 'completed masking'
| civil_stand","number"]
df.to_csv("/usr/local/input/singhealth_dataset1.csv")
df.to_parquet("/usr/local/input/singhealth_dataset1.parquet")
return 'completed csv fixup'
def tokenize_csv_func():
return 'completed masking'
def mask_csv_func():
| 64 | 64 | 12 | 6 | 58 | ozzyathome/docker-airflow | dags/SingHealthDemo1.py | Python | mask_csv_func | mask_csv_func | 21 | 22 | 21 | 21 | 3f4e538cbec6115cca2ac42de7dbdf6d02baa30f | bigcode/the-stack | train |
c0e0b32f894d158d02c1c232 | train | function | def export_csv_func():
return 'completed export'
| def export_csv_func():
| return 'completed export'
| /local/input/singhealth_dataset1.csv")
df.to_parquet("/usr/local/input/singhealth_dataset1.parquet")
return 'completed csv fixup'
def tokenize_csv_func():
return 'completed masking'
def mask_csv_func():
return 'completed masking'
def export_csv_func():
| 64 | 64 | 12 | 6 | 58 | ozzyathome/docker-airflow | dags/SingHealthDemo1.py | Python | export_csv_func | export_csv_func | 24 | 25 | 24 | 24 | 54d6b94a71cec9bf52e592b7c520766a62d56eca | bigcode/the-stack | train |
d257af2d2ffcac344503e113 | train | function | def convert_csv_func():
print('Fixup CSV to parquet')
import pandas
df=pandas.read_csv("/usr/local/input/singhealth_dataset.csv",header=None)
df.columns=["first_name","last_name","email","dob","id","gender","colour","religion","civil_stand","number"]
df.to_csv("/usr/local/input/singhealth_dataset1.... | def convert_csv_func():
| print('Fixup CSV to parquet')
import pandas
df=pandas.read_csv("/usr/local/input/singhealth_dataset.csv",header=None)
df.columns=["first_name","last_name","email","dob","id","gender","colour","religion","civil_stand","number"]
df.to_csv("/usr/local/input/singhealth_dataset1.csv")
df.to_parquet("... | from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.bash_operator import BashOperator
from airflow.operators.docker_operator import DockerOperator
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
def convert_csv... | 61 | 64 | 107 | 6 | 54 | ozzyathome/docker-airflow | dags/SingHealthDemo1.py | Python | convert_csv_func | convert_csv_func | 9 | 16 | 9 | 9 | 6ab8aff491aa0b5f3cf2625d9d1b40e8bc81351d | bigcode/the-stack | train |
5745a87f0fc11e989e19869a | train | function | def tokenize_csv_func():
return 'completed masking'
| def tokenize_csv_func():
| return 'completed masking'
| ","dob","id","gender","colour","religion","civil_stand","number"]
df.to_csv("/usr/local/input/singhealth_dataset1.csv")
df.to_parquet("/usr/local/input/singhealth_dataset1.parquet")
return 'completed csv fixup'
def tokenize_csv_func():
| 64 | 64 | 12 | 6 | 58 | ozzyathome/docker-airflow | dags/SingHealthDemo1.py | Python | tokenize_csv_func | tokenize_csv_func | 18 | 19 | 18 | 18 | d069b9b1d066ff625da00cef146f3151875babb9 | bigcode/the-stack | train |
56c4f6fe89821dcd045cd148 | train | function | def search(request):
queryset_list = Listing.objects.order_by('-list_date')
# Keywords
if 'keywords' in request.GET:
keywords = request.GET['keywords']
if keywords:
queryset_list = queryset_list.filter(
description__icontains=keywords)
# City
if 'city' i... | def search(request):
| queryset_list = Listing.objects.order_by('-list_date')
# Keywords
if 'keywords' in request.GET:
keywords = request.GET['keywords']
if keywords:
queryset_list = queryset_list.filter(
description__icontains=keywords)
# City
if 'city' in request.GET:
... | context = {
'listings': paged_listings
}
return render(request, 'listings/listings.html', context)
def listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
context = {
'listing': listing
}
return render(request, 'listings/listing.html', context)... | 82 | 82 | 275 | 4 | 78 | mposh/BT-Real-Estate | listings/views.py | Python | search | search | 32 | 73 | 32 | 32 | 1848530eb9a129fc87ccd81edd9d6d59ff1cf15b | bigcode/the-stack | train |
9e603fcdddd614a4ea8bd405 | train | function | def listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
context = {
'listing': listing
}
return render(request, 'listings/listing.html', context)
| def listing(request, listing_id):
| listing = get_object_or_404(Listing, pk=listing_id)
context = {
'listing': listing
}
return render(request, 'listings/listing.html', context)
| aginator(listings, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'listings': paged_listings
}
return render(request, 'listings/listings.html', context)
def listing(request, listing_id):
| 64 | 64 | 49 | 7 | 57 | mposh/BT-Real-Estate | listings/views.py | Python | listing | listing | 22 | 29 | 22 | 22 | 3289aa814fb62f862dd53b9448494ab304da7b55 | bigcode/the-stack | train |
d16acd791eb4f4f5a5a595ac | train | function | def index(request):
listings = Listing.objects.order_by('-list_date').filter(is_published=True)
paginator = Paginator(listings, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'listings': paged_listings
}
return render(request, 'listings/lis... | def index(request):
| listings = Listing.objects.order_by('-list_date').filter(is_published=True)
paginator = Paginator(listings, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'listings': paged_listings
}
return render(request, 'listings/listings.html', context... | from django.shortcuts import get_object_or_404, render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from .choices import price_choices, bedroom_choices, state_choices
from .models import Listing
def index(request):
| 52 | 64 | 82 | 4 | 47 | mposh/BT-Real-Estate | listings/views.py | Python | index | index | 8 | 19 | 8 | 8 | 39e958c02064fc87817439bb12690be50e75473e | bigcode/the-stack | train |
096745615fc4c61c53074f3c | train | class | @pulumi.output_type
class MachinePropertiesResponseOsProfile(dict):
"""
Specifies the operating system settings for the hybrid machine.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "computerName":
suggest = "computer_name"
if suggest:
... | @pulumi.output_type
class MachinePropertiesResponseOsProfile(dict):
| """
Specifies the operating system settings for the hybrid machine.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "computerName":
suggest = "computer_name"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in MachinePropert... | Specifies the version of the script handler.
"""
return pulumi.get(self, "type_handler_version")
@property
@pulumi.getter
def status(self) -> Optional['outputs.MachineExtensionInstanceViewResponseStatus']:
"""
Instance view status.
"""
return pulumi.get(self... | 83 | 83 | 278 | 14 | 69 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/hybridcompute/v20200802/outputs.py | Python | MachinePropertiesResponseOsProfile | MachinePropertiesResponseOsProfile | 379 | 415 | 379 | 380 | 4a7463dbcd2d9b6c3aacb8062add904de0e205d4 | bigcode/the-stack | train |
a20cc00bea0c2e7d9d54ead6 | train | class | @pulumi.output_type
class LocationDataResponse(dict):
"""
Metadata pertaining to the geographic location of the resource.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "countryOrRegion":
suggest = "country_or_region"
if suggest:
... | @pulumi.output_type
class LocationDataResponse(dict):
| """
Metadata pertaining to the geographic location of the resource.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "countryOrRegion":
suggest = "country_or_region"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in Locatio... | :
"""
The error's code.
"""
return pulumi.get(self, "code")
@property
@pulumi.getter
def message(self) -> str:
"""
A human readable error message.
"""
return pulumi.get(self, "message")
@property
@pulumi.getter
def details(self) -... | 166 | 166 | 554 | 12 | 154 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/hybridcompute/v20200802/outputs.py | Python | LocationDataResponse | LocationDataResponse | 75 | 147 | 75 | 76 | 47789bab9e1d6871e013d726459c8e077a242fd0 | bigcode/the-stack | train |
3d93798c5262dc134f09daeb | train | class | @pulumi.output_type
class MachineResponseIdentity(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "principalId":
suggest = "principal_id"
elif key == "tenantId":
suggest = "tenant_id"
if suggest:
pulumi.log.warn(f"Ke... | @pulumi.output_type
class MachineResponseIdentity(dict):
@staticmethod
| def __key_warning(key: str):
suggest = None
if key == "principalId":
suggest = "principal_id"
elif key == "tenantId":
suggest = "tenant_id"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in MachineResponseIdentity. Access the value via the '{... | __self__, *,
computer_name: str):
"""
Specifies the operating system settings for the hybrid machine.
:param str computer_name: Specifies the host OS name of the hybrid machine.
"""
pulumi.set(__self__, "computer_name", computer_name)
@property
@pulumi.g... | 122 | 122 | 407 | 16 | 106 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/hybridcompute/v20200802/outputs.py | Python | MachineResponseIdentity | MachineResponseIdentity | 418 | 475 | 418 | 420 | 1b82e9ee3fdc9b859f5834754c31fdf73398e943 | bigcode/the-stack | train |
bbe01bd33b72304f73ffea40 | train | class | @pulumi.output_type
class ErrorDetailResponse(dict):
def __init__(__self__, *,
code: str,
message: str,
details: Optional[Sequence['outputs.ErrorDetailResponse']] = None,
target: Optional[str] = None):
"""
:param str code: The error... | @pulumi.output_type
class ErrorDetailResponse(dict):
| def __init__(__self__, *,
code: str,
message: str,
details: Optional[Sequence['outputs.ErrorDetailResponse']] = None,
target: Optional[str] = None):
"""
:param str code: The error's code.
:param str message: A human readable... | pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'ErrorDetailResponse',
'LocationDataResponse',
'MachineExtensionInstanceViewResponse',
'MachineExtensionInstanceViewResponseStatus',
'Machi... | 104 | 104 | 349 | 12 | 92 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/hybridcompute/v20200802/outputs.py | Python | ErrorDetailResponse | ErrorDetailResponse | 22 | 72 | 22 | 23 | e5fbc249f7de61d3def3ddfd02cc109fb3a5fce0 | bigcode/the-stack | train |
d7763048d5d8103e1e99b79d | train | class | @pulumi.output_type
class MachineExtensionInstanceViewResponse(dict):
"""
Describes the Machine Extension Instance View.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "typeHandlerVersion":
suggest = "type_handler_version"
if suggest:
... | @pulumi.output_type
class MachineExtensionInstanceViewResponse(dict):
| """
Describes the Machine Extension Instance View.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "typeHandlerVersion":
suggest = "type_handler_version"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in MachineExtensionIn... | property
@pulumi.getter
def city(self) -> Optional[str]:
"""
The city or locality where the resource is located.
"""
return pulumi.get(self, "city")
@property
@pulumi.getter(name="countryOrRegion")
def country_or_region(self) -> Optional[str]:
"""
The... | 159 | 159 | 533 | 14 | 145 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/hybridcompute/v20200802/outputs.py | Python | MachineExtensionInstanceViewResponse | MachineExtensionInstanceViewResponse | 150 | 220 | 150 | 151 | d1b865ade908cfcf47f16ef081b70d2de3542202 | bigcode/the-stack | train |
5aa412d9ec704e276a187954 | train | class | @pulumi.output_type
class MachineExtensionPropertiesResponseInstanceView(dict):
"""
The machine extension instance view.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "typeHandlerVersion":
suggest = "type_handler_version"
if suggest:
... | @pulumi.output_type
class MachineExtensionPropertiesResponseInstanceView(dict):
| """
The machine extension instance view.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "typeHandlerVersion":
suggest = "type_handler_version"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in MachineExtensionPropertiesRe... | localizable label for the status.
"""
return pulumi.get(self, "display_status")
@property
@pulumi.getter
def level(self) -> str:
"""
The level code.
"""
return pulumi.get(self, "level")
@property
@pulumi.getter
def message(self) -> str:
... | 159 | 159 | 533 | 15 | 144 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/hybridcompute/v20200802/outputs.py | Python | MachineExtensionPropertiesResponseInstanceView | MachineExtensionPropertiesResponseInstanceView | 306 | 376 | 306 | 307 | 5ac2ba8191f892f27c0429f4b4526c1337f07107 | bigcode/the-stack | train |
72ae575a3d15a920b0c9e350 | train | class | @pulumi.output_type
class MachineExtensionInstanceViewResponseStatus(dict):
"""
Instance view status.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "displayStatus":
suggest = "display_status"
if suggest:
pulumi.log.warn(f"Key... | @pulumi.output_type
class MachineExtensionInstanceViewResponseStatus(dict):
| """
Instance view status.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "displayStatus":
suggest = "display_status"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in MachineExtensionInstanceViewResponseStatus. Access the... | name")
@property
@pulumi.getter
def type(self) -> str:
"""
Specifies the type of the extension; an example is "CustomScriptExtension".
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="typeHandlerVersion")
def type_handler_version(self) -> str:
... | 164 | 164 | 548 | 15 | 149 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/hybridcompute/v20200802/outputs.py | Python | MachineExtensionInstanceViewResponseStatus | MachineExtensionInstanceViewResponseStatus | 223 | 303 | 223 | 224 | a8da86b932e9a83a47920b03eed8591b080ea8f2 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.