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
90accf14c63735e7e8b770c1
train
class
@pulumi.output_type class GetServiceEndpointPolicyResult: """ Service End point policy resource. """ def __init__(__self__, etag=None, id=None, kind=None, location=None, name=None, provisioning_state=None, resource_guid=None, service_endpoint_policy_definitions=None, subnets=None, tags=None, type=None):...
@pulumi.output_type class GetServiceEndpointPolicyResult:
""" Service End point policy resource. """ def __init__(__self__, etag=None, id=None, kind=None, location=None, name=None, provisioning_state=None, resource_guid=None, service_endpoint_policy_definitions=None, subnets=None, tags=None, type=None): if etag and not isinstance(etag, str): ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
123
256
1,039
13
110
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/network/v20201101/get_service_endpoint_policy.py
Python
GetServiceEndpointPolicyResult
GetServiceEndpointPolicyResult
18
144
18
19
e43eeb04cd05649d8cfcc292dfb872475b75b34a
bigcode/the-stack
train
10abbd59d24b2f2ac6dca699
train
function
def get_service_endpoint_policy(expand: Optional[str] = None, resource_group_name: Optional[str] = None, service_endpoint_policy_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetService...
def get_service_endpoint_policy(expand: Optional[str] = None, resource_group_name: Optional[str] = None, service_endpoint_policy_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetService...
""" Service End point policy resource. :param str expand: Expands referenced resources. :param str resource_group_name: The name of the resource group. :param str service_endpoint_policy_name: The name of the service endpoint policy. """ __args__ = dict() __args__['expand'] = expand ...
_state=self.provisioning_state, resource_guid=self.resource_guid, service_endpoint_policy_definitions=self.service_endpoint_policy_definitions, subnets=self.subnets, tags=self.tags, type=self.type) def get_service_endpoint_policy(expand: Optional[str] = None, ...
103
103
345
59
44
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/network/v20201101/get_service_endpoint_policy.py
Python
get_service_endpoint_policy
get_service_endpoint_policy
166
199
166
169
039f80083d7a880bcb7f2e3972179332cda63fd6
bigcode/the-stack
train
a6f70cd4063770c1abdc08c0
train
class
class AwaitableGetServiceEndpointPolicyResult(GetServiceEndpointPolicyResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetServiceEndpointPolicyResult( etag=self.etag, id=self.id, kind=self.kind, ...
class AwaitableGetServiceEndpointPolicyResult(GetServiceEndpointPolicyResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetServiceEndpointPolicyResult( etag=self.etag, id=self.id, kind=self.kind, location=self.location, name=self.name, provisioning_state=self.provisioning_state, ...
tags") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") class AwaitableGetServiceEndpointPolicyResult(GetServiceEndpointPolicyResult): # pylint: disable=using-constant-test
64
64
121
25
39
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/network/v20201101/get_service_endpoint_policy.py
Python
AwaitableGetServiceEndpointPolicyResult
AwaitableGetServiceEndpointPolicyResult
147
163
147
148
75e32331c4722deaaaba4075e75fdc7f4c869de8
bigcode/the-stack
train
f0456cc9ced41ab40c2710a5
train
function
def run(ctx: protocol_api.ProtocolContext): source_plate = ctx.load_labware( 'nest_96_wellplate_100ul_pcr_full_skirt', '1', 'RNA elution plate from station B') pcr_plate = ctx.load_labware( 'nest_96_wellplate_100ul_pcr_full_skirt', '2', 'PCR plate') tuberack = ctx.load_labware( ...
def run(ctx: protocol_api.ProtocolContext):
source_plate = ctx.load_labware( 'nest_96_wellplate_100ul_pcr_full_skirt', '1', 'RNA elution plate from station B') pcr_plate = ctx.load_labware( 'nest_96_wellplate_100ul_pcr_full_skirt', '2', 'PCR plate') tuberack = ctx.load_labware( 'opentrons_24_tuberack_eppendorf_2ml_safe...
from opentrons import protocol_api # metadata metadata = { 'protocolName': 'S3 Station C Version 1', 'author': 'Nick <protocols@opentrons.com>', 'source': 'Custom Protocol Request', 'apiLevel': '2.0' } """ REAGENT SETUP: - slot 5 2ml tuberack: - mastermixes: tubes A1-A3 - positive control: tu...
127
202
674
9
117
emilyjunkins/covid19
protocols/S3/v1_station_c_S3.ot2.apiv2.py
Python
run
run
23
87
23
23
94ec8cbf0978639340619244e4ae88286cd4d13f
bigcode/the-stack
train
1338b28e38da56a2045ab6cb
train
function
def get_shelf(request): """Gets a shelf using the location. Args: request: shelf_messages.ShelfRequest, the request message for a shelf. Returns: Shelf object. Raises: endpoints.NotFoundException when a shelf can not be found. """ if request.urlsafe_key: shelf = api_utils.get_ndb_key(requ...
def get_shelf(request):
"""Gets a shelf using the location. Args: request: shelf_messages.ShelfRequest, the request message for a shelf. Returns: Shelf object. Raises: endpoints.NotFoundException when a shelf can not be found. """ if request.urlsafe_key: shelf = api_utils.get_ndb_key(request.urlsafe_key).get() ...
devices_on_shelf: api_utils.get_ndb_key(device.doc_id).get().remove_from_shelf( shelf=shelf, user_email=user_email) shelf.audit(user_email=user_email, num_of_devices=len(devices_on_shelf)) return message_types.VoidMessage() def get_shelf(request):
64
64
127
6
58
gng-demo/GrabnGo
loaner/web_app/backend/api/shelf_api.py
Python
get_shelf
get_shelf
205
224
205
205
f3a020dbfecab6255ba93cf1a1c42133dd9f2324
bigcode/the-stack
train
0fac09fd3b1a81073838254f
train
class
@root_api.ROOT_API.api_class(resource_name='shelf', path='shelf') class ShelfApi(root_api.Service): """This class is for the Shelf API.""" @auth.method( shelf_messages.EnrollShelfRequest, message_types.VoidMessage, name='enroll', path='enroll', http_method='POST', permission=per...
@root_api.ROOT_API.api_class(resource_name='shelf', path='shelf') class ShelfApi(root_api.Service):
"""This class is for the Shelf API.""" @auth.method( shelf_messages.EnrollShelfRequest, message_types.VoidMessage, name='enroll', path='enroll', http_method='POST', permission=permissions.Permissions.MODIFY_SHELF) def enroll(self, request): """Enrolls a shelf in the progra...
governing permissions and # limitations under the License. """The entry point for the Shelf methods.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from protorpc import message_types from google.appengine.api import datastor...
255
256
1,255
26
229
gng-demo/GrabnGo
loaner/web_app/backend/api/shelf_api.py
Python
ShelfApi
ShelfApi
47
202
47
48
a31aa2bb1fb43bcea7a102ec45afddda6780fa0f
bigcode/the-stack
train
bfcbdf289d162b1d76c5604c
train
function
def make_scipy_linear_constraints( shapeX: torch.Size, inequality_constraints: Optional[List[Tuple[Tensor, Tensor, float]]] = None, equality_constraints: Optional[List[Tuple[Tensor, Tensor, float]]] = None, ) -> List[ScipyConstraintDict]: r"""Generate scipy constraints from torch representation. Ar...
def make_scipy_linear_constraints( shapeX: torch.Size, inequality_constraints: Optional[List[Tuple[Tensor, Tensor, float]]] = None, equality_constraints: Optional[List[Tuple[Tensor, Tensor, float]]] = None, ) -> List[ScipyConstraintDict]:
r"""Generate scipy constraints from torch representation. Args: shapeX: The shape of the torch.Tensor to optimize over (i.e. `b x q x d`) inequality constraints: A list of tuples (indices, coefficients, rhs), with each tuple encoding an inequality constraint of the form ...
1, 0.8) """ if lower_bounds is None and upper_bounds is None: return None def _expand(bounds: Union[float, Tensor], X: Tensor, lower: bool) -> Tensor: if bounds is None: ebounds = torch.full_like(X, float("-inf" if lower else "inf")) else: if not torch.is_ten...
219
219
732
60
159
talesa/botorch
botorch/optim/parameter_constraints.py
Python
make_scipy_linear_constraints
make_scipy_linear_constraints
68
128
68
72
11c79308cc8e64f76a5de4da351486f22275b16b
bigcode/the-stack
train
7717941c7a04ae565f76a03d
train
function
def _make_linear_constraints( indices: Tensor, coefficients: Tensor, rhs: float, shapeX: torch.Size, eq: bool = False, ) -> List[ScipyConstraintDict]: r"""Create linear constraints to be used by `scipy.minimize`. Encodes constraints of the form `\sum_i (coefficients[i] * X[..., indices[...
def _make_linear_constraints( indices: Tensor, coefficients: Tensor, rhs: float, shapeX: torch.Size, eq: bool = False, ) -> List[ScipyConstraintDict]:
r"""Create linear constraints to be used by `scipy.minimize`. Encodes constraints of the form `\sum_i (coefficients[i] * X[..., indices[i]]) ? rhs` where `?` can be designated either as `>=` by setting `eq=False`, or as `=` by setting `eq=True`. If indices is one-dimensional, the constraints a...
.ndarray, flat_idxr: List[int], coeffs: np.ndarray, n: int ) -> np.ndarray: r"""Return the Jacobian associated with a linear constraint. Args: x: The input array. flat_idxr: The indices for the elements of x that appear in the constraint. coeffs: The coefficients corresponding to the in...
256
256
1,085
44
212
talesa/botorch
botorch/optim/parameter_constraints.py
Python
_make_linear_constraints
_make_linear_constraints
180
270
180
186
cb565a27450d069d4abf821e6e7d1c9d69896def
bigcode/the-stack
train
f804dda8e7b0b55effd0bed0
train
function
def lin_constraint_jac( x: np.ndarray, flat_idxr: List[int], coeffs: np.ndarray, n: int ) -> np.ndarray: r"""Return the Jacobian associated with a linear constraint. Args: x: The input array. flat_idxr: The indices for the elements of x that appear in the constraint. coeffs: The coe...
def lin_constraint_jac( x: np.ndarray, flat_idxr: List[int], coeffs: np.ndarray, n: int ) -> np.ndarray:
r"""Return the Jacobian associated with a linear constraint. Args: x: The input array. flat_idxr: The indices for the elements of x that appear in the constraint. coeffs: The coefficients corresponding to the indices. n: number of elements Returns: The Jacobian. ...
] * x[i]) - rhs` """ return np.sum(x[flat_idxr] * coeffs, -1) - rhs def lin_constraint_jac( x: np.ndarray, flat_idxr: List[int], coeffs: np.ndarray, n: int ) -> np.ndarray:
64
64
141
34
29
talesa/botorch
botorch/optim/parameter_constraints.py
Python
lin_constraint_jac
lin_constraint_jac
148
165
148
150
446a48008d1a940e06f0bb3d9a1f7b6a3eda0c14
bigcode/the-stack
train
bc21d24a3f04ec5b4b1053f5
train
function
def _arrayify(X: Tensor) -> np.ndarray: r"""Convert a torch.Tensor (any dtype or device) to a numpy (double) array. Args: X: The input tensor. Returns: A numpy array of double dtype with the same shape and data as `X`. """ return X.cpu().detach().contiguous().double().clone().numpy...
def _arrayify(X: Tensor) -> np.ndarray:
r"""Convert a torch.Tensor (any dtype or device) to a numpy (double) array. Args: X: The input tensor. Returns: A numpy array of double dtype with the same shape and data as `X`. """ return X.cpu().detach().contiguous().double().clone().numpy()
number of elements Returns: The Jacobian. """ # TODO: Use sparse representation (not sure if scipy optim supports that) jac = np.zeros(n) jac[flat_idxr] = coeffs return jac def _arrayify(X: Tensor) -> np.ndarray:
64
64
81
12
51
talesa/botorch
botorch/optim/parameter_constraints.py
Python
_arrayify
_arrayify
168
177
168
168
57998aee6b822ba90a073d4bc8a1d76a8147ad4b
bigcode/the-stack
train
6590c4bcf89fb010a1d6476d
train
function
def make_scipy_bounds( X: Tensor, lower_bounds: Optional[Union[float, Tensor]] = None, upper_bounds: Optional[Union[float, Tensor]] = None, ) -> Optional[Bounds]: r"""Creates a scipy Bounds object for optimziation Args: X: `... x d` tensor lower_bounds: Lower bounds on each column (...
def make_scipy_bounds( X: Tensor, lower_bounds: Optional[Union[float, Tensor]] = None, upper_bounds: Optional[Union[float, Tensor]] = None, ) -> Optional[Bounds]:
r"""Creates a scipy Bounds object for optimziation Args: X: `... x d` tensor lower_bounds: Lower bounds on each column (last dimension) of `X`. If this is a single float, then all columns have the same bound. upper_bounds: Lower bounds on each column (last dimension) of `X`....
import CandidateGenerationError, UnsupportedError from scipy.optimize import Bounds from torch import Tensor ScipyConstraintDict = Dict[ str, Union[str, Callable[[np.ndarray], float], Callable[[np.ndarray], np.ndarray]] ] NLC_TOL = -1e-6 def make_scipy_bounds( X: Tensor, lower_bounds: Optional[Union[floa...
107
107
358
48
58
talesa/botorch
botorch/optim/parameter_constraints.py
Python
make_scipy_bounds
make_scipy_bounds
29
65
29
33
7d744280f1ca343f97a1e2b9c7d3881a82576c6d
bigcode/the-stack
train
491ba8f9594c17d166488672
train
function
def _make_f_and_grad_nonlinear_inequality_constraints( f_np_wrapper: Callable, nlc: Callable ) -> Tuple[Callable[[Tensor], Tensor], Callable[[Tensor], Tensor]]: """ Create callables for objective + grad for the nonlinear inequality constraints. The Scipy interface requires specifying separate callables ...
def _make_f_and_grad_nonlinear_inequality_constraints( f_np_wrapper: Callable, nlc: Callable ) -> Tuple[Callable[[Tensor], Tensor], Callable[[Tensor], Tensor]]:
""" Create callables for objective + grad for the nonlinear inequality constraints. The Scipy interface requires specifying separate callables and we use caching to avoid evaluating the same input twice. This caching onlh works if the returned functions are evaluated on the same input in immediate ...
) is a no-op if dim -1 is not singleton new_indices.squeeze_(-1) # convert new_coefficients to Tensor new_coefficients = torch.stack(new_coefficients) new_constraints.append((new_indices, new_coefficients, new_rhs)) return new_constraints def _make_f_and_grad_nonlinea...
103
103
345
42
60
talesa/botorch
botorch/optim/parameter_constraints.py
Python
_make_f_and_grad_nonlinear_inequality_constraints
_make_f_and_grad_nonlinear_inequality_constraints
336
369
336
338
89324748397cf277bd930ad8e53951684e0dca66
bigcode/the-stack
train
e1f543f011444227552193ab
train
function
def _generate_unfixed_lin_constraints( constraints: Optional[List[Tuple[Tensor, Tensor, float]]], fixed_features: Dict[int, float], dimension: int, eq: bool, ) -> Optional[List[Tuple[Tensor, Tensor, float]]]: # If constraints is None or an empty list, then return itself if not constraints: ...
def _generate_unfixed_lin_constraints( constraints: Optional[List[Tuple[Tensor, Tensor, float]]], fixed_features: Dict[int, float], dimension: int, eq: bool, ) -> Optional[List[Tuple[Tensor, Tensor, float]]]: # If constraints is None or an empty list, then return itself
if not constraints: return constraints # replace_index generates the new indices for the unfixed dimensions # after eliminating the fixed dimensions. # Example: dimension = 5, ff.keys() = [1, 3], replace_index = {0: 0, 2: 1, 4: 2} unfixed_keys = sorted(set(range(dimension)) - set(fixed_feat...
]): for j in range(shapeX[1]): idxr = (i * offsets[0] + j * offsets[1] + indices).tolist() fun = partial( eval_lin_constraint, flat_idxr=idxr, coeffs=coeffs, rhs=float(rhs) ) jac = partial(lin_constraint_jac, flat_idxr=idxr,...
201
201
672
71
129
talesa/botorch
botorch/optim/parameter_constraints.py
Python
_generate_unfixed_lin_constraints
_generate_unfixed_lin_constraints
273
333
273
280
8c6d85332e5775d37ce4bff38514018a65e50d84
bigcode/the-stack
train
132b92fa8107a8ac9ca2cc65
train
function
def eval_lin_constraint( x: np.ndarray, flat_idxr: List[int], coeffs: np.ndarray, rhs: float ) -> np.float64: r"""Evaluate a single linear constraint. Args: x: The input array. flat_idxr: The indices in `x` to consider. coeffs: The coefficients corresponding to the indices. ...
def eval_lin_constraint( x: np.ndarray, flat_idxr: List[int], coeffs: np.ndarray, rhs: float ) -> np.float64:
r"""Evaluate a single linear constraint. Args: x: The input array. flat_idxr: The indices in `x` to consider. coeffs: The coefficients corresponding to the indices. rhs: The right-hand-side of the constraint. Returns: The evaluted constraint: `\sum_i (coeffs[i] * x[...
indices=indcs, coefficients=coeffs, rhs=rhs, shapeX=shapeX, eq=True ) return constraints def eval_lin_constraint( x: np.ndarray, flat_idxr: List[int], coeffs: np.ndarray, rhs: float ) -> np.float64:
64
64
136
34
29
talesa/botorch
botorch/optim/parameter_constraints.py
Python
eval_lin_constraint
eval_lin_constraint
131
145
131
133
aee49b4da5f8710921801b5992690dbfc00a1b19
bigcode/the-stack
train
0898b63812d3b9fa23a42f29
train
function
def make_scipy_nonlinear_inequality_constraints( nonlinear_inequality_constraints: List[Callable], f_np_wrapper: Callable, x0: Tensor, ) -> List[Dict]: r"""Generate Scipy nonlinear inequality constraints from callables. Args: nonlinear_inequality_constraints: List of callables for the nonli...
def make_scipy_nonlinear_inequality_constraints( nonlinear_inequality_constraints: List[Callable], f_np_wrapper: Callable, x0: Tensor, ) -> List[Dict]:
r"""Generate Scipy nonlinear inequality constraints from callables. Args: nonlinear_inequality_constraints: List of callables for the nonlinear inequality constraints. Each callable represents a constraint of the form >= 0 and takes a torch tensor of size (p x q x dim) and retur...
cache["obj"], cache["grad"] = f_obj_and_grad(X) return cache["obj"] def f_grad(X): X_c = cache["X"] if X_c is None or not np.array_equal(X_c, X): cache["X"] = X.copy() cache["obj"], cache["grad"] = f_obj_and_grad(X) return cache["grad"] return f_obj, f_...
133
133
444
43
89
talesa/botorch
botorch/optim/parameter_constraints.py
Python
make_scipy_nonlinear_inequality_constraints
make_scipy_nonlinear_inequality_constraints
372
418
372
376
9bd83c96fe876407ee07229c235735f776e3cfab
bigcode/the-stack
train
fd91c31d0e4e2043fbbd9203
train
class
class Migration(migrations.Migration): operations = []
class Migration(migrations.Migration):
operations = []
from django.db import migrations class Migration(migrations.Migration):
13
64
11
7
5
jpmallarino/django
tests/migrations/test_migrations_backwards_deps_1/0001_initial.py
Python
Migration
Migration
4
5
4
4
70acd3981a8062eea4bf1792a083756bdc7ce319
bigcode/the-stack
train
f627d535cec135f16a008c9e
train
function
@pytest.mark.parametrize( ("name", "expected"), [ ("Jeanette", "Hello Jeanette!"), ("Raven", "Hello Raven!"), ("Maxine", "Hello Maxine!"), ("Matteo", "Hello Matteo!"), ("Destinee", "Hello Destinee!"), ("Alden", "Hello Alden!"), ("Mariah", "Hello Mariah!"),...
@pytest.mark.parametrize( ("name", "expected"), [ ("Jeanette", "Hello Jeanette!"), ("Raven", "Hello Raven!"), ("Maxine", "Hello Maxine!"), ("Matteo", "Hello Matteo!"), ("Destinee", "Hello Destinee!"), ("Alden", "Hello Alden!"), ("Mariah", "Hello Mariah!"),...
"""Example test with parametrization.""" assert hello(name) == expected
@pytest.mark.parametrize( ("name", "expected"), [ ("Jeanette", "Hello Jeanette!"), ("Raven", "Hello Raven!"), ("Maxine", "Hello Maxine!"), ("Matteo", "Hello Matteo!"), ("Destinee", "Hello Destinee!"), ("Alden", "Hello Alden!"), ("Mariah", "Hello Mariah!"),...
121
64
137
121
0
davidmarcos98/Datawrapper
tests/test_example/test_hello.py
Python
test_hello
test_hello
6
22
6
20
0327026171e824883236db89e8a2f32d291bddb3
bigcode/the-stack
train
132c7e8eab95f81ae0ee8820
train
function
def _override_info(http_msg, http_attr, secret_field): if ( secret_field in getattr(http_msg, http_attr) and http_attr in ALLOWED_ATTRS_TO_HIDE ): getattr(http_msg, http_attr)[secret_field] = "<sensitive_information>"
def _override_info(http_msg, http_attr, secret_field):
if ( secret_field in getattr(http_msg, http_attr) and http_attr in ALLOWED_ATTRS_TO_HIDE ): getattr(http_msg, http_attr)[secret_field] = "<sensitive_information>"
issing_keys, scope) def _hide(http_msg, hide_settings): for http_attr in hide_settings: secret_fields = hide_settings[http_attr] for field in secret_fields: _override_info(http_msg, http_attr, field) def _override_info(http_msg, http_attr, secret_field):
64
64
58
13
51
rcmachado/scanapi
scanapi/utils.py
Python
_override_info
_override_info
54
59
54
54
87a91123f7b3d4943debcb6826eaeaa08ff43b6b
bigcode/the-stack
train
cb16d97c49ac17660d75ab1f
train
function
def hide_sensitive_info(response): report_settings = settings.get("report", {}) request = response.request request_settings = report_settings.get("hide-request", {}) response_settings = report_settings.get("hide-response", {}) _hide(request, request_settings) _hide(response, response_settings)
def hide_sensitive_info(response):
report_settings = settings.get("report", {}) request = response.request request_settings = report_settings.get("hide-request", {}) response_settings = report_settings.get("hide-response", {}) _hide(request, request_settings) _hide(response, response_settings)
second_url = second_url.lstrip("/") return "/".join([first_url, second_url]) def validate_keys(keys, available_keys, required_keys, scope): _validate_allowed_keys(keys, available_keys, scope) _validate_required_keys(keys, required_keys, scope) def hide_sensitive_info(response):
64
64
63
6
58
rcmachado/scanapi
scanapi/utils.py
Python
hide_sensitive_info
hide_sensitive_info
25
32
25
25
5c23d198c8301337d818f845751f39f0c3be8a1e
bigcode/the-stack
train
dec3a6c4c185c79132e911a9
train
function
def _validate_required_keys(keys, required_keys, scope): if not set(required_keys) <= set(keys): missing_keys = set(required_keys) - set(keys) raise MissingMandatoryKeyError(missing_keys, scope)
def _validate_required_keys(keys, required_keys, scope):
if not set(required_keys) <= set(keys): missing_keys = set(required_keys) - set(keys) raise MissingMandatoryKeyError(missing_keys, scope)
hide(request, request_settings) _hide(response, response_settings) def _validate_allowed_keys(keys, available_keys, scope): for key in keys: if not key in available_keys: raise InvalidKeyError(key, scope, available_keys) def _validate_required_keys(keys, required_keys, scope):
64
64
47
12
52
rcmachado/scanapi
scanapi/utils.py
Python
_validate_required_keys
_validate_required_keys
41
44
41
41
eb808e654f3a793843669133d4094619f682bf13
bigcode/the-stack
train
3efaadb9f38a02978bbf542c
train
function
def _validate_allowed_keys(keys, available_keys, scope): for key in keys: if not key in available_keys: raise InvalidKeyError(key, scope, available_keys)
def _validate_allowed_keys(keys, available_keys, scope):
for key in keys: if not key in available_keys: raise InvalidKeyError(key, scope, available_keys)
.get("report", {}) request = response.request request_settings = report_settings.get("hide-request", {}) response_settings = report_settings.get("hide-response", {}) _hide(request, request_settings) _hide(response, response_settings) def _validate_allowed_keys(keys, available_keys, scope):
64
64
38
12
52
rcmachado/scanapi
scanapi/utils.py
Python
_validate_allowed_keys
_validate_allowed_keys
35
38
35
35
10a5b11357568b5049de2e0834ab17664639a5dc
bigcode/the-stack
train
617bb1d2c47971f64f5fd382
train
function
def join_urls(first_url, second_url): if not first_url: return second_url if not second_url: return first_url first_url = first_url.strip("/") second_url = second_url.lstrip("/") return "/".join([first_url, second_url])
def join_urls(first_url, second_url):
if not first_url: return second_url if not second_url: return first_url first_url = first_url.strip("/") second_url = second_url.lstrip("/") return "/".join([first_url, second_url])
from scanapi.errors import InvalidKeyError, MissingMandatoryKeyError from scanapi.settings import settings ALLOWED_ATTRS_TO_HIDE = ("headers body").split() def join_urls(first_url, second_url):
43
64
61
9
34
rcmachado/scanapi
scanapi/utils.py
Python
join_urls
join_urls
7
17
7
7
77497d2e06026fece8090cd4b75d7b8c404bdf80
bigcode/the-stack
train
d71df095dc758f9b97c19255
train
function
def _hide(http_msg, hide_settings): for http_attr in hide_settings: secret_fields = hide_settings[http_attr] for field in secret_fields: _override_info(http_msg, http_attr, field)
def _hide(http_msg, hide_settings):
for http_attr in hide_settings: secret_fields = hide_settings[http_attr] for field in secret_fields: _override_info(http_msg, http_attr, field)
Error(key, scope, available_keys) def _validate_required_keys(keys, required_keys, scope): if not set(required_keys) <= set(keys): missing_keys = set(required_keys) - set(keys) raise MissingMandatoryKeyError(missing_keys, scope) def _hide(http_msg, hide_settings):
64
64
46
9
55
rcmachado/scanapi
scanapi/utils.py
Python
_hide
_hide
47
51
47
47
d9c5c6c88bae8ddb5c324e56f1bac45230e15007
bigcode/the-stack
train
d838ea5770349e93275ecfbe
train
function
def validate_keys(keys, available_keys, required_keys, scope): _validate_allowed_keys(keys, available_keys, scope) _validate_required_keys(keys, required_keys, scope)
def validate_keys(keys, available_keys, required_keys, scope):
_validate_allowed_keys(keys, available_keys, scope) _validate_required_keys(keys, required_keys, scope)
if not first_url: return second_url if not second_url: return first_url first_url = first_url.strip("/") second_url = second_url.lstrip("/") return "/".join([first_url, second_url]) def validate_keys(keys, available_keys, required_keys, scope):
64
64
37
13
51
rcmachado/scanapi
scanapi/utils.py
Python
validate_keys
validate_keys
20
22
20
20
1a505b559667fa27b4d3864525de3160ec346d5d
bigcode/the-stack
train
bdcdf8bbe2333a34e35aa175
train
function
def fp32_to_fp16(val): """Convert fp32 `val` to fp16""" def half_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, FLOAT_TYPES): val = val.half() return val r...
def fp32_to_fp16(val):
"""Convert fp32 `val` to fp16""" def half_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, FLOAT_TYPES): val = val.half() return val return conversion_helper...
a nested tuple/list structure.""" if not isinstance(val, (tuple, list)): return conversion(val) rtn = [conversion_helper(v, conversion) for v in val] if isinstance(val, tuple): rtn = tuple(rtn) return rtn def fp32_to_fp16(val):
64
64
83
8
55
botmatic/tacotron2
tacotron/fp16_optimizer.py
Python
fp32_to_fp16
fp32_to_fp16
21
30
21
21
e78bb9e5ddb270fd74a635de214dd410471b80a1
bigcode/the-stack
train
deb4ad11924e7b905bf13993
train
class
class FP16_Module(nn.Module): def __init__(self, module): super(FP16_Module, self).__init__() self.add_module('module', module.half()) def forward(self, *inputs, **kwargs): return fp16_to_fp32(self.module(*(fp32_to_fp16(inputs)), **kwargs))
class FP16_Module(nn.Module):
def __init__(self, module): super(FP16_Module, self).__init__() self.add_module('module', module.half()) def forward(self, *inputs, **kwargs): return fp16_to_fp32(self.module(*(fp32_to_fp16(inputs)), **kwargs))
): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, HALF_TYPES): val = val.float() return val return conversion_helper(val, float_conversion) class FP16_Module(nn.Module):
64
64
69
7
57
botmatic/tacotron2
tacotron/fp16_optimizer.py
Python
FP16_Module
FP16_Module
43
49
43
43
920100cddf6204fc0c3dc84505160805e827bac1
bigcode/the-stack
train
3abdbbecdadbd157f7fe6640
train
function
def conversion_helper(val, conversion): """Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure.""" if not isinstance(val, (tuple, list)): return conversion(val) rtn = [conversion_helper(v, conversion) for v in val] if isinstance(val, tuple): r...
def conversion_helper(val, conversion):
"""Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure.""" if not isinstance(val, (tuple, list)): return conversion(val) rtn = [conversion_helper(v, conversion) for v in val] if isinstance(val, tuple): rtn = tuple(rtn) return rtn
._utils import _flatten_dense_tensors, _unflatten_dense_tensors from loss_scaler import DynamicLossScaler, LossScaler FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor) HALF_TYPES = (torch.HalfTensor, torch.cuda.HalfTensor) def conversion_helper(val, conversion):
64
64
79
7
57
botmatic/tacotron2
tacotron/fp16_optimizer.py
Python
conversion_helper
conversion_helper
12
19
12
12
0067f10f668c78ca8fd669b9959400b24fee23b6
bigcode/the-stack
train
2dcc460079aec03b1d7f423e
train
class
class FP16_Optimizer(object): """ FP16_Optimizer is designed to wrap an existing PyTorch optimizer, and enable an fp16 model to be trained using a master copy of fp32 weights. Args: optimizer (torch.optim.optimizer): Existing optimizer containing initialized fp16 parameters. Internally, FP16_...
class FP16_Optimizer(object):
""" FP16_Optimizer is designed to wrap an existing PyTorch optimizer, and enable an fp16 model to be trained using a master copy of fp32 weights. Args: optimizer (torch.optim.optimizer): Existing optimizer containing initialized fp16 parameters. Internally, FP16_Optimizer replaces the passed ...
(val, tuple): rtn = tuple(rtn) return rtn def fp32_to_fp16(val): """Convert fp32 `val` to fp16""" def half_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, FLOAT_TYPES)...
256
256
3,147
7
249
botmatic/tacotron2
tacotron/fp16_optimizer.py
Python
FP16_Optimizer
FP16_Optimizer
51
381
51
51
3b7eed754fff8d0a1cf8651be0e1bfb9d65231b6
bigcode/the-stack
train
c687a8e6b7bcfe6321b8cd98
train
function
def fp16_to_fp32(val): """Convert fp16 `val` to fp32""" def float_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, HALF_TYPES): val = val.float() return val ...
def fp16_to_fp32(val):
"""Convert fp16 `val` to fp32""" def float_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, HALF_TYPES): val = val.float() return val return conversion_helpe...
val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, FLOAT_TYPES): val = val.half() return val return conversion_helper(val, half_conversion) def fp16_to_fp32(val):
64
64
82
8
56
botmatic/tacotron2
tacotron/fp16_optimizer.py
Python
fp16_to_fp32
fp16_to_fp32
32
41
32
32
e230b1cef63d3b3d6cecb9648de4d7dc2492e926
bigcode/the-stack
train
6ff76c9e32dab7bb961dc99f
train
class
class RecPredictor(Predictor): def __init__(self, config): super().__init__(config["Global"], config["Global"]["rec_inference_model_dir"]) self.preprocess_ops = create_operators(config["RecPreProcess"][ "transform_ops"]) self.postprocess = build_postproce...
class RecPredictor(Predictor):
def __init__(self, config): super().__init__(config["Global"], config["Global"]["rec_inference_model_dir"]) self.preprocess_ops = create_operators(config["RecPreProcess"][ "transform_ops"]) self.postprocess = build_postprocess(config["RecPostProcess"]) ...
.dirname(os.path.abspath(__file__)) sys.path.append(os.path.abspath(os.path.join(__dir__, '../'))) import cv2 import numpy as np from utils import logger from utils import config from utils.predictor import Predictor from utils.get_image_list import get_image_list from preprocess import create_operators from postproc...
81
81
270
8
72
TxT1212/PaddleClas
deploy/python/predict_rec.py
Python
RecPredictor
RecPredictor
31
63
31
31
2efcef6f878200c63c42a715d1098f9fc9b66249
bigcode/the-stack
train
98319ea47a7e2fbd93b3c87e
train
function
def main(config): rec_predictor = RecPredictor(config) image_list = get_image_list(config["Global"]["infer_imgs"]) assert config["Global"]["batch_size"] == 1 for idx, image_file in enumerate(image_list): batch_input = [] img = cv2.imread(image_file)[:, :, ::-1] output = rec_pred...
def main(config):
rec_predictor = RecPredictor(config) image_list = get_image_list(config["Global"]["infer_imgs"]) assert config["Global"]["batch_size"] == 1 for idx, image_file in enumerate(image_list): batch_input = [] img = cv2.imread(image_file)[:, :, ::-1] output = rec_predictor.predict(img)...
.run() batch_output = output_tensor.copy_to_cpu() if feature_normalize: feas_norm = np.sqrt( np.sum(np.square(batch_output), axis=1, keepdims=True)) batch_output = np.divide(batch_output, feas_norm) return batch_output def main(config...
64
64
109
4
59
TxT1212/PaddleClas
deploy/python/predict_rec.py
Python
main
main
66
78
66
66
4ce51e4f368bf2b02f6622f1d418b307e9707f36
bigcode/the-stack
train
b17df444a874ff73a5c06a4f
train
class
class Detector: def __init__(self, frequency=100): import pickle self.frequency = frequency; self.model = pickle.load(open("log_reg1.sav", 'rb')) def divide_by_windows_std(self, X, y, window_len=60): """ Parameters: window_len - len...
class Detector:
def __init__(self, frequency=100): import pickle self.frequency = frequency; self.model = pickle.load(open("log_reg1.sav", 'rb')) def divide_by_windows_std(self, X, y, window_len=60): """ Parameters: window_len - length of each window in...
class Detector:
4
129
430
4
0
Vitalinsh/Sleep-Analysis-with-accelerometer
final_model/sleep_awake_detector.py
Python
Detector
Detector
1
56
1
2
0010fd76c57d9d7a2f0532243a1f6e554ed838a0
bigcode/the-stack
train
3f91688f3600b356179aba7c
train
class
class TestTransformerGenerator(unittest.TestCase): """ Checks that the generative transformer can learn basic tasks. """ def _overfit_train(self, **args): args = dict( task='integration_tests:overfit', model='transformer/generator', optimizer='sgd', ...
class TestTransformerGenerator(unittest.TestCase):
""" Checks that the generative transformer can learn basic tasks. """ def _overfit_train(self, **args): args = dict( task='integration_tests:overfit', model='transformer/generator', optimizer='sgd', learningrate=1, momentum=0.9, ...
self.assertGreaterEqual(test['hits@1'], 0.90) @testing_utils.retry(ntries=3) def test_prelayernorm(self): """ Test --variant prelayernorm with history_add_global_end_token option. """ valid, test = self._overfit_train( task='integration_tests:overfit', ...
256
256
3,386
8
248
mikejqzhang/ParlAI
tests/test_transformers.py
Python
TestTransformerGenerator
TestTransformerGenerator
202
604
202
202
4eb32525dab8d65e2738bbbdd70249487b0823be
bigcode/the-stack
train
22bc8104f61252b66a3e4afe
train
class
@testing_utils.skipUnlessVision class TestImagePolyencoder(unittest.TestCase): """ Unit tests for the ImagePolyencoderAgent. Test that the model is able to handle simple train tasks. """ base_args = { 'log_every_n_secs': 5, 'model': 'transformer/image_polyencoder', 'embeddi...
@testing_utils.skipUnlessVision class TestImagePolyencoder(unittest.TestCase):
""" Unit tests for the ImagePolyencoderAgent. Test that the model is able to handle simple train tasks. """ base_args = { 'log_every_n_secs': 5, 'model': 'transformer/image_polyencoder', 'embedding_size': 32, 'n_heads': 1, 'n_layers': 1, 'n_positions...
=1, n_heads=1, embedding_size=4, ffn_size=8, skip_generation=True, validation_max_exs=1, short_final_eval=True, ) args['num_epochs'] = 9 / 500 args['validation_every_n_epochs'] = 9 / 500 valid1, test1 = testing_util...
245
245
817
16
229
mikejqzhang/ParlAI
tests/test_transformers.py
Python
TestImagePolyencoder
TestImagePolyencoder
766
861
766
767
4c9ba8e5eae4050c4763386ad589460a27593ac1
bigcode/the-stack
train
e687121662eeb6a325fd2926
train
class
class TestClassifier(unittest.TestCase): """ Test transformer/classifier. """ @testing_utils.retry() def test_simple(self): valid, test = testing_utils.train_model( dict( task='integration_tests:classifier', model='transformer/classifier', ...
class TestClassifier(unittest.TestCase):
""" Test transformer/classifier. """ @testing_utils.retry() def test_simple(self): valid, test = testing_utils.train_model( dict( task='integration_tests:classifier', model='transformer/classifier', classes=['one', 'zero'], ...
) opt = parser.parse_args([]) agent = create_agent(opt) # assert that the embeddings were resized assert agent.resized_embeddings # assert model has special tokens self.assertEqual(agent.special_toks, ['PARTY', 'PARROT']) class TestClassifier(unit...
63
64
151
7
56
mikejqzhang/ParlAI
tests/test_transformers.py
Python
TestClassifier
TestClassifier
607
631
607
607
fc5a0d9dfaeae5d23fad0c9e9122027b473d1ef2
bigcode/the-stack
train
21085409b592ff940e15c617
train
class
class TestLearningRateScheduler(unittest.TestCase): """ Test learning rate scheduler for both generative and ranking transformers. """ def _test_learning_rate_resuming(self, user_args): """ Test learning rate resumes correctly. """ args = dict( task='integrat...
class TestLearningRateScheduler(unittest.TestCase):
""" Test learning rate scheduler for both generative and ranking transformers. """ def _test_learning_rate_resuming(self, user_args): """ Test learning rate resumes correctly. """ args = dict( task='integration_tests:overfit', lr_scheduler='invsqr...
LEVEL_BPE_MERGE, bpe_add_prefix_space=False, model_file=model_file, save_after_valid=True, special_tok_lst='PARTY,PARROT', ) opt = parser.parse_args([]) agent = create_agent(opt) # assert that the embeddings ...
256
256
982
9
246
mikejqzhang/ParlAI
tests/test_transformers.py
Python
TestLearningRateScheduler
TestLearningRateScheduler
634
763
634
634
5454aa5c7f4e008c51b7fd90b3a3d71d12b2e60c
bigcode/the-stack
train
355e0fbec5987dacf4986986
train
class
class TestTransformerRanker(unittest.TestCase): """ Checks that transformer_ranker can learn some very basic tasks. """ def _overfit_train(self, **args): opt = dict( task='integration_tests:overfit', model='transformer/ranker', optimizer='adam', l...
class TestTransformerRanker(unittest.TestCase):
""" Checks that transformer_ranker can learn some very basic tasks. """ def _overfit_train(self, **args): opt = dict( task='integration_tests:overfit', model='transformer/ranker', optimizer='adam', learningrate=0.01, batchsize=4, ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Test many variants of transformers. """ import os import unittest import pytest import parlai.utils.testing as test...
145
256
1,279
9
135
mikejqzhang/ParlAI
tests/test_transformers.py
Python
TestTransformerRanker
TestTransformerRanker
22
199
22
22
709628e89293789fecb9c531d2d46eeb2f123f1d
bigcode/the-stack
train
f3a2c86c5e67d30fb80678d0
train
function
def test_execute(capsys): cmd = DeclareCommand('declare alias "machin"') facade = new_facade() cmd.execute(facade) try: unit = facade.parser.get_definition("machin", UnitType.alias) assert len(unit.variations) == 0 assert len(unit.rules) == 0 except (KeyError, ValueError): ...
def test_execute(capsys):
cmd = DeclareCommand('declare alias "machin"') facade = new_facade() cmd.execute(facade) try: unit = facade.parser.get_definition("machin", UnitType.alias) assert len(unit.variations) == 0 assert len(unit.rules) == 0 except (KeyError, ValueError): pytest.fail("Unexpec...
"') cmd.execute(facade) captured = capsys.readouterr() assert "[ERROR]\tVariation name detected, " + \ "while units cannot be declared with a variation. " + \ "Did you mean to escape some hashtags '#'?" in captured.out cmd = DeclareCommand('declare alias "var"') cmd.execute(fa...
106
106
355
7
99
fanfanfeng/Chatette
tests/unit-testing/cli/interactive_commands/test_declare_command.py
Python
test_execute
test_execute
60
98
60
60
66f7bef04b51ebe6563887b56c5d636b77620e71
bigcode/the-stack
train
280d53fa9531cec760d1e05f
train
function
def test_err(capsys): facade = new_facade() cmd = DeclareCommand("declare") cmd.execute(facade) captured = capsys.readouterr() assert "[ERROR]\tMissing some arguments\n\tUsage: " + \ 'declare <unit-type> "<unit-name>"' in captured.out cmd = DeclareCommand("declare nothing /a/") ...
def test_err(capsys):
facade = new_facade() cmd = DeclareCommand("declare") cmd.execute(facade) captured = capsys.readouterr() assert "[ERROR]\tMissing some arguments\n\tUsage: " + \ 'declare <unit-type> "<unit-name>"' in captured.out cmd = DeclareCommand("declare nothing /a/") cmd.execute(facade) ...
clare_command import DeclareCommand from chatette_qiu.parsing.parser_utils import UnitType def test_obj(): cmd = DeclareCommand("") assert cmd.command_tokens == [] assert isinstance(cmd, CommandStrategy) cmd = DeclareCommand("declare alias /a/") assert cmd.command_tokens == ["declare", "alias", ...
86
86
287
7
79
fanfanfeng/Chatette
tests/unit-testing/cli/interactive_commands/test_declare_command.py
Python
test_err
test_err
27
57
27
27
e5fba3600c2c2a26a259a38d438c93c8c4023a28
bigcode/the-stack
train
33986193c28a4c6187257822
train
function
def test_obj(): cmd = DeclareCommand("") assert cmd.command_tokens == [] assert isinstance(cmd, CommandStrategy) cmd = DeclareCommand("declare alias /a/") assert cmd.command_tokens == ["declare", "alias", "/a/"] assert isinstance(cmd, CommandStrategy)
def test_obj():
cmd = DeclareCommand("") assert cmd.command_tokens == [] assert isinstance(cmd, CommandStrategy) cmd = DeclareCommand("declare alias /a/") assert cmd.command_tokens == ["declare", "alias", "/a/"] assert isinstance(cmd, CommandStrategy)
re_command`. """ import pytest from test_command_strategy import new_facade from chatette_qiu.cli.interactive_commands.command_strategy import CommandStrategy from chatette_qiu.cli.interactive_commands.declare_command import DeclareCommand from chatette_qiu.parsing.parser_utils import UnitType def test_obj():
64
64
60
4
59
fanfanfeng/Chatette
tests/unit-testing/cli/interactive_commands/test_declare_command.py
Python
test_obj
test_obj
17
24
17
17
54846ff385ab508c1f05d013dcf68a339f345752
bigcode/the-stack
train
f64dd84a88fda7e620742fd9
train
function
def test_abstract_methods(): cmd = DeclareCommand('declare alias "a"') with pytest.raises(NotImplementedError): cmd.execute_on_unit(None, None, None) with pytest.raises(NotImplementedError): cmd.finish_execution(None)
def test_abstract_methods():
cmd = DeclareCommand('declare alias "a"') with pytest.raises(NotImplementedError): cmd.execute_on_unit(None, None, None) with pytest.raises(NotImplementedError): cmd.finish_execution(None)
assert len(unit.rules) == 0 except (KeyError, ValueError): pytest.fail("Unexpected error, 'declare' command didn't work.") captured = capsys.readouterr() assert "Intent 'machin' was successfully declared." in captured.out def test_abstract_methods():
64
64
51
6
57
fanfanfeng/Chatette
tests/unit-testing/cli/interactive_commands/test_declare_command.py
Python
test_abstract_methods
test_abstract_methods
101
106
101
101
63102587333b1814aafbb2e15f336ae1e22ce255
bigcode/the-stack
train
ca14ed7c71229aee866910d3
train
class
class BasePortalPlugin(BaseAdminPlugin): # Media def get_media(self, media): return media + self.vendor('xadmin.plugin.portal.js')
class BasePortalPlugin(BaseAdminPlugin): # Media
def get_media(self, media): return media + self.vendor('xadmin.plugin.portal.js')
#coding:utf-8 from xadmin.sites import site from xadmin.models import UserSettings from xadmin.views import BaseAdminPlugin, ModelFormAdminView, DetailAdminView from xadmin.layout import Fieldset, Column class BasePortalPlugin(BaseAdminPlugin): # Media
62
64
33
12
49
charles820/django-xadmin
xadmin/plugins/portal.py
Python
BasePortalPlugin
BasePortalPlugin
8
12
8
10
3ba25b3a087dcf05522ee73702127d1c13a66da9
bigcode/the-stack
train
1100a7a653dafeace7284f04
train
class
class ModelDetailPlugin(ModelFormPlugin): def _portal_key(self): return '%s_%s_detail_portal' % (self.opts.app_label, self.opts.module_name) def block_after_fieldsets(self, context, node): # put portal key and submit url to page return "<input type='hidden' id='_portal_key' value='%s' ...
class ModelDetailPlugin(ModelFormPlugin):
def _portal_key(self): return '%s_%s_detail_portal' % (self.opts.app_label, self.opts.module_name) def block_after_fieldsets(self, context, node): # put portal key and submit url to page return "<input type='hidden' id='_portal_key' value='%s' />" % self._portal_key()
Exception: pass return helper def block_form_top(self, context, node): # put portal key and submit url to page return "<input type='hidden' id='_portal_key' value='%s' />" % self._portal_key() class ModelDetailPlugin(ModelFormPlugin):
64
64
85
8
56
charles820/django-xadmin
xadmin/plugins/portal.py
Python
ModelDetailPlugin
ModelDetailPlugin
64
71
64
65
89b847850f87e7bf145dff0d56d1cd187187ae43
bigcode/the-stack
train
74170fea11b9505b76b8bc1a
train
class
class ModelFormPlugin(BasePortalPlugin): def _portal_key(self): return '%s_%s_editform_portal' % (self.opts.app_label, self.opts.module_name) def get_form_helper(self, helper): cs = [] layout = helper.layout get_layout_objects(layout, Column, cs) for i, c in enumerate(c...
class ModelFormPlugin(BasePortalPlugin):
def _portal_key(self): return '%s_%s_editform_portal' % (self.opts.app_label, self.opts.module_name) def get_form_helper(self, helper): cs = [] layout = helper.layout get_layout_objects(layout, Column, cs) for i, c in enumerate(cs): if not getattr(c, 'css_id'...
(self, media): return media + self.vendor('xadmin.plugin.portal.js') def get_layout_objects(layout, clz, objects): for i, layout_object in enumerate(layout.fields): if layout_object.__class__ is clz or issubclass(layout_object.__class__, clz): objects.append(layout_object) elif...
98
98
328
8
90
charles820/django-xadmin
xadmin/plugins/portal.py
Python
ModelFormPlugin
ModelFormPlugin
23
61
23
24
7393a68be73176533bc7db146b1d41364ab461da
bigcode/the-stack
train
44f80ce06a073616ba2d0a26
train
function
def get_layout_objects(layout, clz, objects): for i, layout_object in enumerate(layout.fields): if layout_object.__class__ is clz or issubclass(layout_object.__class__, clz): objects.append(layout_object) elif hasattr(layout_object, 'get_field_names'): get_layout_objects(layo...
def get_layout_objects(layout, clz, objects):
for i, layout_object in enumerate(layout.fields): if layout_object.__class__ is clz or issubclass(layout_object.__class__, clz): objects.append(layout_object) elif hasattr(layout_object, 'get_field_names'): get_layout_objects(layout_object, clz, objects)
, ModelFormAdminView, DetailAdminView from xadmin.layout import Fieldset, Column class BasePortalPlugin(BaseAdminPlugin): # Media def get_media(self, media): return media + self.vendor('xadmin.plugin.portal.js') def get_layout_objects(layout, clz, objects):
64
64
73
11
53
charles820/django-xadmin
xadmin/plugins/portal.py
Python
get_layout_objects
get_layout_objects
15
20
15
15
7b2e9c6ef8e86568b9febf9e956f94c3951c8622
bigcode/the-stack
train
77a286af9c7caf6f87cede2d
train
function
def eval_one_epoch(model, dataloader, epoch_id, result_dir, logger): if cfg.RPN.ENABLED and not cfg.RCNN.ENABLED: ret_dict = eval_one_epoch_rpn(model, dataloader, epoch_id, result_dir, logger) elif not cfg.RPN.ENABLED and cfg.RCNN.ENABLED: ret_dict = eval_one_epoch_rcnn(model, dataloader, epoch_...
def eval_one_epoch(model, dataloader, epoch_id, result_dir, logger):
if cfg.RPN.ENABLED and not cfg.RCNN.ENABLED: ret_dict = eval_one_epoch_rpn(model, dataloader, epoch_id, result_dir, logger) elif not cfg.RPN.ENABLED and cfg.RCNN.ENABLED: ret_dict = eval_one_epoch_rcnn(model, dataloader, epoch_id, result_dir, logger) elif cfg.RPN.ENABLED and cfg.RCNN.ENABLED...
_class = name_to_class[cfg.CLASSES]) logger.info(ap_result_str) ret_dict.update(ap_dict) logger.info('result is saved to: %s' % result_dir) return ret_dict def eval_one_epoch(model, dataloader, epoch_id, result_dir, logger):
64
64
144
18
45
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
eval_one_epoch
eval_one_epoch
751
760
751
751
888d630b049fc8b0e14ac7982c286ae03e133639
bigcode/the-stack
train
6f5b11a33cf240972512dde8
train
function
def eval_one_epoch_rpn(model, dataloader, epoch_id, result_dir, logger): np.random.seed(1024) mode = 'TEST' if args.test else 'EVAL' if args.save_rpn_feature: kitti_features_dir = os.path.join(result_dir, 'features') os.makedirs(kitti_features_dir, exist_ok = True) if args.save_result ...
def eval_one_epoch_rpn(model, dataloader, epoch_id, result_dir, logger):
np.random.seed(1024) mode = 'TEST' if args.test else 'EVAL' if args.save_rpn_feature: kitti_features_dir = os.path.join(result_dir, 'features') os.makedirs(kitti_features_dir, exist_ok = True) if args.save_result or args.save_rpn_feature: kitti_output_dir = os.path.join(result_...
1], bbox3d[k, 2], bbox3d[k, 6], scores[k]), file = f) def save_rpn_features(seg_result, rpn_scores_raw, pts_features, backbone_xyz, backbone_features, kitti_features_dir, sample_id): pts_intensity = pts_features[:, 0] output_file = os.path.join(kitti_features_dir, '%...
256
256
1,855
20
236
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
eval_one_epoch_rpn
eval_one_epoch_rpn
121
276
121
121
f49be7974312b853a8c3172708fa97ad48b5d776
bigcode/the-stack
train
42f3f19fbf72529863397b48
train
function
def create_dataloader(logger): mode = 'TEST' if args.test else 'EVAL' DATA_PATH = os.path.join('../', 'data') # create dataloader test_set = KittiRCNNDataset(root_dir = DATA_PATH, npoints = cfg.RPN.NUM_POINTS, split = cfg.TEST.SPLIT, mode = mode, random_select = args.ran...
def create_dataloader(logger):
mode = 'TEST' if args.test else 'EVAL' DATA_PATH = os.path.join('../', 'data') # create dataloader test_set = KittiRCNNDataset(root_dir = DATA_PATH, npoints = cfg.RPN.NUM_POINTS, split = cfg.TEST.SPLIT, mode = mode, random_select = args.random_select, ...
, step) # record this epoch which has been evaluated with open(ckpt_record_file, 'a') as f: print('%s' % cur_epoch_id, file = f) logger.info('Epoch %s has been evaluated' % cur_epoch_id) def create_dataloader(logger):
64
64
173
6
58
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
create_dataloader
create_dataloader
928
943
928
928
21c15834fd50bd1c8b052258ebb2f8d52cfea4b8
bigcode/the-stack
train
9f71e0d784df32253d6a9d53
train
function
def save_rpn_features(seg_result, rpn_scores_raw, pts_features, backbone_xyz, backbone_features, kitti_features_dir, sample_id): pts_intensity = pts_features[:, 0] output_file = os.path.join(kitti_features_dir, '%06d.npy' % sample_id) xyz_file = os.path.join(kitti_features_dir, '%06d_...
def save_rpn_features(seg_result, rpn_scores_raw, pts_features, backbone_xyz, backbone_features, kitti_features_dir, sample_id):
pts_intensity = pts_features[:, 0] output_file = os.path.join(kitti_features_dir, '%06d.npy' % sample_id) xyz_file = os.path.join(kitti_features_dir, '%06d_xyz.npy' % sample_id) seg_file = os.path.join(kitti_features_dir, '%06d_seg.npy' % sample_id) intensity_file = os.path.join(kitti_features_dir,...
], bbox3d[k, 1], bbox3d[k, 2], bbox3d[k, 6], scores[k]), file = f) def save_rpn_features(seg_result, rpn_scores_raw, pts_features, backbone_xyz, backbone_features, kitti_features_dir, sample_id):
64
64
209
31
33
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
save_rpn_features
save_rpn_features
105
118
105
106
565fff08d0bb9cef21dca058a88287051dc17944
bigcode/the-stack
train
c3446df36c1c25af00dff9ee
train
function
def save_kitti_format(sample_id, calib, bbox3d, kitti_output_dir, scores, img_shape): corners3d = kitti_utils.boxes3d_to_corners3d(bbox3d) img_boxes, _ = calib.corners3d_to_img_boxes(corners3d) img_boxes[:, 0] = np.clip(img_boxes[:, 0], 0, img_shape[1] - 1) img_boxes[:, 1] = np.clip(img_boxes[:, 1], 0,...
def save_kitti_format(sample_id, calib, bbox3d, kitti_output_dir, scores, img_shape):
corners3d = kitti_utils.boxes3d_to_corners3d(bbox3d) img_boxes, _ = calib.corners3d_to_img_boxes(corners3d) img_boxes[:, 0] = np.clip(img_boxes[:, 0], 0, img_shape[1] - 1) img_boxes[:, 1] = np.clip(img_boxes[:, 1], 0, img_shape[0] - 1) img_boxes[:, 2] = np.clip(img_boxes[:, 2], 0, img_shape[1] - 1)...
= argparse.REMAINDER, help = 'set extra config keys if needed') parser.add_argument('--model_type', type = str, default = 'base', help = 'model type') args = parser.parse_args() def create_logger(log_file): log_format = '%(asctime)s %(levelname)5s %(message)s' logging.basicConfig(leve...
158
158
528
24
134
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
save_kitti_format
save_kitti_format
77
102
77
77
0ad8916d745c22421731486fec1366f664123e34
bigcode/the-stack
train
9349adb1f2a9b90a98d4bd7f
train
function
def eval_one_epoch_rcnn(model, dataloader, epoch_id, result_dir, logger): np.random.seed(1024) MEAN_SIZE = torch.from_numpy(cfg.CLS_MEAN_SIZE[0]).cuda() mode = 'TEST' if args.test else 'EVAL' final_output_dir = os.path.join(result_dir, 'final_result', 'data') os.makedirs(final_output_dir, exist_ok ...
def eval_one_epoch_rcnn(model, dataloader, epoch_id, result_dir, logger):
np.random.seed(1024) MEAN_SIZE = torch.from_numpy(cfg.CLS_MEAN_SIZE[0]).cuda() mode = 'TEST' if args.test else 'EVAL' final_output_dir = os.path.join(result_dir, 'final_result', 'data') os.makedirs(final_output_dir, exist_ok = True) if args.save_result: roi_output_dir = os.path.join(re...
.set_postfix(disp_dict) progress_bar.update() progress_bar.close() logger.info(str(datetime.now())) logger.info('-------------------performance of epoch %s---------------------' % epoch_id) logger.info('max number of objects: %d' % max_num) logger.info('rpn iou avg: %f' % (rpn_iou_avg / ma...
256
256
2,529
20
235
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
eval_one_epoch_rcnn
eval_one_epoch_rcnn
279
495
279
279
50dcac3773f47d32c398ee4d65fabca19f38f1c3
bigcode/the-stack
train
6f64c35cbb80dcff1160b86e
train
function
def get_no_evaluated_ckpt(ckpt_dir, ckpt_record_file): ckpt_list = glob.glob(os.path.join(ckpt_dir, '*checkpoint_epoch_*.pth')) ckpt_list.sort(key = os.path.getmtime) evaluated_ckpt_list = [float(x.strip()) for x in open(ckpt_record_file, 'r').readlines()] for cur_ckpt in ckpt_list: num_list = ...
def get_no_evaluated_ckpt(ckpt_dir, ckpt_record_file):
ckpt_list = glob.glob(os.path.join(ckpt_dir, '*checkpoint_epoch_*.pth')) ckpt_list.sort(key = os.path.getmtime) evaluated_ckpt_list = [float(x.strip()) for x in open(ckpt_record_file, 'r').readlines()] for cur_ckpt in ckpt_list: num_list = re.findall('checkpoint_epoch_(.*).pth', cur_ckpt) ...
%s/' % backup_dir) # load checkpoint load_ckpt_based_on_args(model, logger) # start evaluation eval_one_epoch(model, test_loader, epoch_id, root_result_dir, logger) def get_no_evaluated_ckpt(ckpt_dir, ckpt_record_file):
64
64
171
18
46
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
get_no_evaluated_ckpt
get_no_evaluated_ckpt
838
851
838
838
60b4c4c256126c53d150d6750624b6323527e5ef
bigcode/the-stack
train
98ead0ed1e8b9e97a5246158
train
function
def eval_one_epoch_joint(model, dataloader, epoch_id, result_dir, logger):#True np.random.seed(666) MEAN_SIZE = torch.from_numpy(cfg.CLS_MEAN_SIZE[0]).cuda() mode = 'TEST' if args.test else 'EVAL' final_output_dir = os.path.join(result_dir, 'final_result', 'data') os.makedirs(final_output_dir, exis...
def eval_one_epoch_joint(model, dataloader, epoch_id, result_dir, logger):#True
np.random.seed(666) MEAN_SIZE = torch.from_numpy(cfg.CLS_MEAN_SIZE[0]).cuda() mode = 'TEST' if args.test else 'EVAL' final_output_dir = os.path.join(result_dir, 'final_result', 'data') os.makedirs(final_output_dir, exist_ok = True) if args.save_result: roi_output_dir = os.path.join(res...
2f)' % thresh] = cur_roi_recall for idx, thresh in enumerate(thresh_list): cur_recall = total_recalled_bbox_list[idx] / max(total_gt_bbox, 1.0) logger.info('total bbox recall(thresh=%.3f): %d / %d = %f' % (thresh, total_recalled_bbox_list[idx], ...
256
256
3,213
22
233
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
eval_one_epoch_joint
eval_one_epoch_joint
498
748
498
498
8ad17cd55fda8e5c009da7842f7906a5d274aab1
bigcode/the-stack
train
a91bdccce8740105517b5296
train
function
def create_logger(log_file): log_format = '%(asctime)s %(levelname)5s %(message)s' logging.basicConfig(level = logging.INFO, format = log_format, filename = log_file) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(logging.Formatter(log_format)) logging.ge...
def create_logger(log_file):
log_format = '%(asctime)s %(levelname)5s %(message)s' logging.basicConfig(level = logging.INFO, format = log_format, filename = log_file) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(logging.Formatter(log_format)) logging.getLogger(__name__).addHandler(...
', dest = 'set_cfgs', default = None, nargs = argparse.REMAINDER, help = 'set extra config keys if needed') parser.add_argument('--model_type', type = str, default = 'base', help = 'model type') args = parser.parse_args() def create_logger(log_file):
64
64
89
6
58
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
create_logger
create_logger
67
74
67
67
385278151a284e222b8e7f0968a506a81e48f4c1
bigcode/the-stack
train
2271d210e61cf097f64a3ec7
train
function
def load_ckpt_based_on_args(model, logger): if args.ckpt is not None: train_utils.load_checkpoint(model, filename = args.ckpt, logger = logger) total_keys = model.state_dict().keys().__len__() if cfg.RPN.ENABLED and args.rpn_ckpt is not None: load_part_ckpt(model, filename = args.rpn_ckpt, ...
def load_ckpt_based_on_args(model, logger):
if args.ckpt is not None: train_utils.load_checkpoint(model, filename = args.ckpt, logger = logger) total_keys = model.state_dict().keys().__len__() if cfg.RPN.ENABLED and args.rpn_ckpt is not None: load_part_ckpt(model, filename = args.rpn_ckpt, logger = logger, total_keys = total_keys) ...
= update_model_state.keys().__len__() if update_keys == 0: raise RuntimeError logger.info("==> Done (loaded %d/%d)" % (update_keys, total_keys)) else: raise FileNotFoundError def load_ckpt_based_on_args(model, logger):
64
64
133
11
52
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
load_ckpt_based_on_args
load_ckpt_based_on_args
782
791
782
782
9e96fb7ff2b0eb8eca1c032d048340cae259a29c
bigcode/the-stack
train
a8d778886eb6cf40f0dce88d
train
function
def repeat_eval_ckpt(root_result_dir, ckpt_dir): root_result_dir = os.path.join(root_result_dir, 'eval', 'eval_all_' + args.extra_tag) os.makedirs(root_result_dir, exist_ok = True) log_file = os.path.join(root_result_dir, 'log_eval_all_%s.txt' % cfg.TEST.SPLIT) logger = create_logger(log_file) logg...
def repeat_eval_ckpt(root_result_dir, ckpt_dir):
root_result_dir = os.path.join(root_result_dir, 'eval', 'eval_all_' + args.extra_tag) os.makedirs(root_result_dir, exist_ok = True) log_file = os.path.join(root_result_dir, 'log_eval_all_%s.txt' % cfg.TEST.SPLIT) logger = create_logger(log_file) logger.info('**********************Start logging*****...
% backup_dir) # load checkpoint load_ckpt_based_on_args(model, logger) # start evaluation eval_one_epoch(model, test_loader, epoch_id, root_result_dir, logger) def get_no_evaluated_ckpt(ckpt_dir, ckpt_record_file): ckpt_list = glob.glob(os.path.join(ckpt_dir, '*checkpoint_epoch_*.pth')) ckp...
227
227
757
13
213
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
repeat_eval_ckpt
repeat_eval_ckpt
854
925
854
854
bcc6b3c926128d8e327b90845366d853af496955
bigcode/the-stack
train
edefebfed826d3ce9e61acbf
train
function
def eval_single_ckpt(root_result_dir): root_result_dir = os.path.join(root_result_dir, 'eval') # set epoch_id and output dir num_list = re.findall(r'\d+', args.ckpt) if args.ckpt is not None else [] epoch_id = num_list[-1] if num_list.__len__() > 0 else 'no_number' root_result_dir = os.path.join(roo...
def eval_single_ckpt(root_result_dir):
root_result_dir = os.path.join(root_result_dir, 'eval') # set epoch_id and output dir num_list = re.findall(r'\d+', args.ckpt) if args.ckpt is not None else [] epoch_id = num_list[-1] if num_list.__len__() > 0 else 'no_number' root_result_dir = os.path.join(root_result_dir, 'epoch_%s' % epoch_id, cf...
FoundError def load_ckpt_based_on_args(model, logger): if args.ckpt is not None: train_utils.load_checkpoint(model, filename = args.ckpt, logger = logger) total_keys = model.state_dict().keys().__len__() if cfg.RPN.ENABLED and args.rpn_ckpt is not None: load_part_ckpt(model, filename = ar...
145
145
484
9
136
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
eval_single_ckpt
eval_single_ckpt
794
835
794
794
4514a3e24f45e829cd04b5aabf472ed5524bfbb1
bigcode/the-stack
train
5683b606d5317811f5107bf5
train
function
def load_part_ckpt(model, filename, logger, total_keys = -1): if os.path.isfile(filename): logger.info("==> Loading part model from checkpoint '{}'".format(filename)) checkpoint = torch.load(filename) model_state = checkpoint['model_state'] update_model_state = { key: val for key, v...
def load_part_ckpt(model, filename, logger, total_keys = -1):
if os.path.isfile(filename): logger.info("==> Loading part model from checkpoint '{}'".format(filename)) checkpoint = torch.load(filename) model_state = checkpoint['model_state'] update_model_state = { key: val for key, val in model_state.items() if key in model.state_dict() } ...
.RPN.ENABLED and cfg.RCNN.ENABLED: ret_dict = eval_one_epoch_joint(model, dataloader, epoch_id, result_dir, logger) else: raise NotImplementedError return ret_dict def load_part_ckpt(model, filename, logger, total_keys = -1):
64
64
162
17
46
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
tools/eval_rcnn.py
Python
load_part_ckpt
load_part_ckpt
763
779
763
763
8202c8d800d8ccd07542b3a67c8aa575e39fce68
bigcode/the-stack
train
5c51761d69e5d878e7bfc4e2
train
function
def left_eye(colour): eyes[1] = colour
def left_eye(colour):
eyes[1] = colour
0, duty_cycle=0) tail_outer = pulseio.PWMOut(board.TAIL2, frequency=2000, duty_cycle=0) touch_right_ear = touchio.TouchIn(board.EAR_R) touch_left_ear = touchio.TouchIn(board.EAR_L) def left_eye(colour):
64
64
14
6
58
owainkenwayucl/Catacorn
kittylib.py
Python
left_eye
left_eye
27
28
27
27
e26ad8ca9d89d52cbf76e81133a8df6f2e6575dc
bigcode/the-stack
train
0a5e6e4e70f4ab3e120ba47f
train
function
def right_eye(colour): eyes[0] = colour
def right_eye(colour):
eyes[0] = colour
Out(board.TAIL2, frequency=2000, duty_cycle=0) touch_right_ear = touchio.TouchIn(board.EAR_R) touch_left_ear = touchio.TouchIn(board.EAR_L) def left_eye(colour): eyes[1] = colour def right_eye(colour):
64
64
14
6
57
owainkenwayucl/Catacorn
kittylib.py
Python
right_eye
right_eye
30
31
30
30
e8902c3bfafc8bda2ef15d5bac2534f7932acbc2
bigcode/the-stack
train
0bdf3dc54d321134ab8ade60
train
function
def auto_app_url_patterns(): from .models import ThingType items = [] things = ThingType.objects.all() for t in things: thing = t.get_class() label = thing._meta.verbose_name.lower() label_p = thing._meta.verbose_name_plural.lower() listname = '%s_list' % label de...
def auto_app_url_patterns():
from .models import ThingType items = [] things = ThingType.objects.all() for t in things: thing = t.get_class() label = thing._meta.verbose_name.lower() label_p = thing._meta.verbose_name_plural.lower() listname = '%s_list' % label detailname = '%s_detail' % labe...
url(r'^sitemap\.xml$', cache_page(3600)(sitemaps_views.sitemap), {'sitemaps': {'things': ThingSitemap}}), url(r'^export/(?P<ct_id>\d+)/$', thing_export, name='things_export'), ) def auto_app_url_patterns():
64
64
157
6
58
jmoswalt/django-things
things/urls.py
Python
auto_app_url_patterns
auto_app_url_patterns
29
42
29
29
5b0eacaabcb9e6e002270afb7de881f53c8870d3
bigcode/the-stack
train
07ea0028e8ed1de3811b0a3a
train
class
class RedisCache(Cache): def __init__(self, maxsize, client=None, host=None, port=None, password=None, db=None, ttl=15 * 60, clear_on_exit=False, key_prefix='RedisCache'): Cache.__init__(self, maxsize, None) self.client_ = client self.host = host or redis_co...
class RedisCache(Cache):
def __init__(self, maxsize, client=None, host=None, port=None, password=None, db=None, ttl=15 * 60, clear_on_exit=False, key_prefix='RedisCache'): Cache.__init__(self, maxsize, None) self.client_ = client self.host = host or redis_config.HOST self.po...
from cachetools import Cache from redis import StrictRedis import pickle import atexit import time from mlchain.config import redis_config class RedisCache(Cache):
36
150
500
5
30
Nguyen-ATrung/mlchain-public-dev
mlchain/cache/remote.py
Python
RedisCache
RedisCache
9
82
9
9
d3e290b747b49434b79fa3ff567ddd3bf163653e
bigcode/the-stack
train
ecdd58c8731573a600b7d87d
train
class
class MultiObjectPermissionsMixin(object): ''' API Mixin that compares ``n`` objects and their permissions and returns if both are valid. Objects can be referred to by key afterwards in self.object_dict. permission dict should be: {'obj1': {'obj_class': class_model, 'lookup_url_kwarg', 'object_perm...
class MultiObjectPermissionsMixin(object):
''' API Mixin that compares ``n`` objects and their permissions and returns if both are valid. Objects can be referred to by key afterwards in self.object_dict. permission dict should be: {'obj1': {'obj_class': class_model, 'lookup_url_kwarg', 'object_permission_required': 'your rules perm here'}, ...
import logging from django.db import transaction from django.utils.translation import gettext_lazy as _ from django.http import Http404 from treebeard.exceptions import InvalidPosition, InvalidMoveToDescendant, PathOverflow from rest_framework.generics import get_object_or_404 from rest_framework.exceptions import Vali...
157
175
586
7
150
maceoutliner/django-fiction-outlines-api
fiction_outlines_api/mixins.py
Python
MultiObjectPermissionsMixin
MultiObjectPermissionsMixin
20
91
20
20
37bf8726a000331cf2c1e0692fd2455ab8480a0e
bigcode/the-stack
train
db19de9b1d6a10eb583fb6ae
train
class
class NodeMoveMixin(object): ''' API mixin for move method for nodes. ''' source_node = None target_node = None target_node_type_fieldname = None # fieldname to send to tree_manipulation signal. pos = None related_key = None # Specify in subclass def get_object(self, pkval): ...
class NodeMoveMixin(object):
''' API mixin for move method for nodes. ''' source_node = None target_node = None target_node_type_fieldname = None # fieldname to send to tree_manipulation signal. pos = None related_key = None # Specify in subclass def get_object(self, pkval): ''' Fetches an ind...
data submitted is invalid or violates the structure of the tree. :returns: A serializer representing the created object. ''' kwarg_dict = {} for field in self.fields_required_for_add: kwarg_dict[field] = serializer.validated_data[field] if self.pos: ...
256
256
905
6
249
maceoutliner/django-fiction-outlines-api
fiction_outlines_api/mixins.py
Python
NodeMoveMixin
NodeMoveMixin
175
258
175
175
48fd966328b6f38532a204bbf53b5cfa78e0f08a
bigcode/the-stack
train
038b603395ad4e99da7ba46e
train
class
class NodeAddMixin(object): ''' API Mixin for add_sibling and add_child commands. :attribute fields_required_for_add: A tuple of fields that should be required in the submitted serializer in order to create the object. ''' fields_required_for_add = ('description',) # Declare in more detail...
class NodeAddMixin(object):
''' API Mixin for add_sibling and add_child commands. :attribute fields_required_for_add: A tuple of fields that should be required in the submitted serializer in order to create the object. ''' fields_required_for_add = ('description',) # Declare in more detail in subclass. def post(...
perm, obj): raise PermissionDenied return super().check_object_permissions(request, obj) def post(self, request, *args, **kwargs): self.permission_object_dict = {} for obj, attrs in self.object_class_permission_dict.items(): try: self.permission_objec...
221
221
739
6
215
maceoutliner/django-fiction-outlines-api
fiction_outlines_api/mixins.py
Python
NodeAddMixin
NodeAddMixin
94
172
94
94
30e97a46000bca17c43a553ef2e14979139d943c
bigcode/the-stack
train
96b14bdfe5cbecb03a2560ed
train
class
class Capture(object): def __init__(self, schema, database='projetocurio' ): self.schema = schema self.database = database self.engine = self.connect_to_db() self.meta = self.load_db_schema() self.url ...
class Capture(object):
def __init__(self, schema, database='projetocurio' ): self.schema = schema self.database = database self.engine = self.connect_to_db() self.meta = self.load_db_schema() self.url = None self.data = N...
import requests import sqlalchemy import xmltodict from sqlalchemy import create_engine, MetaData from collections import defaultdict import datetime from pathlib import Path from utils import * class Capture(object):
42
124
415
5
37
projeto-curio/bigua
bigua/API/capture.py
Python
Capture
Capture
10
79
10
11
a131a75ac1838c09a75d3c9c70ad1f160908f044
bigcode/the-stack
train
5615677f8b8b23feaa6ddca9
train
class
class OrganizationsFunds(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, amount=None): """ OrganizationsFunds - a model defined in Swagger :param dict swaggerTypes: The key is attri...
class OrganizationsFunds(object):
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, amount=None): """ OrganizationsFunds - a model defined in Swagger :param dict swaggerTypes: The key is attribute name ...
SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so...
154
154
515
5
148
jiji-online/neptune-cli
neptune/generated/swagger_client/models/organizations_funds.py
Python
OrganizationsFunds
OrganizationsFunds
26
121
26
26
351ba525ea82be8f2f703e6da4450e6fbbdb03ea
bigcode/the-stack
train
496349f6492bc0d18a8c5d2e
train
function
def dict_merge(source, target): if not isinstance(source, dict) or not isinstance(target, dict): return source src = deepcopy(source) dst = deepcopy(target) for key, val in src.items(): if key in dst and is_list_of_dict(val) and is_list_of_dict(dst[key]): for dst_elem in dst...
def dict_merge(source, target):
if not isinstance(source, dict) or not isinstance(target, dict): return source src = deepcopy(source) dst = deepcopy(target) for key, val in src.items(): if key in dst and is_list_of_dict(val) and is_list_of_dict(dst[key]): for dst_elem in dst[key]: for each_...
.extend([elem for elem in haystack if elem.lower() == needle.lower()]) # Otherwise, there are more stuff, so go recursive else: for value in haystack: findings.extend(seek_value_in_dict(needle, value)) return findings def dict_merge(source, target):
64
64
107
7
56
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
dict_merge
dict_merge
275
288
275
275
4054cd15404380d9e68ca50a71bf6f758c7587fd
bigcode/the-stack
train
0dc9f97ca47da94dbb88bf87
train
function
def are_networks_same(first_network, network_list): for second_network in network_list: if check_if_cidr(first_network) and check_if_cidr(second_network) and \ IPNetwork(first_network) == IPNetwork(second_network): return True return False
def are_networks_same(first_network, network_list):
for second_network in network_list: if check_if_cidr(first_network) and check_if_cidr(second_network) and \ IPNetwork(first_network) == IPNetwork(second_network): return True return False
_cidr, cidr): for ip_network in cidr: if check_if_cidr(ip_cidr) and check_if_cidr(ip_network) and IPNetwork(ip_cidr) in IPNetwork(ip_network): return True return False def are_networks_same(first_network, network_list):
64
64
58
11
52
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
are_networks_same
are_networks_same
56
62
56
56
e1b7022b4c05c0e068b7b2c856057c490cc1453d
bigcode/the-stack
train
234c467f4e0de8a80f6e9bad
train
function
def find_root_by_key(haystack, needle, return_key=None, _inherited_key=None, _depth=0, _return_value=None): ''' Searches needle in haystack ( could be dict, list, list of dicts, nested dicts, etc. ) and returns the root key that has this needle somewhere within it's children. :param haystack: dict, lis...
def find_root_by_key(haystack, needle, return_key=None, _inherited_key=None, _depth=0, _return_value=None):
''' Searches needle in haystack ( could be dict, list, list of dicts, nested dicts, etc. ) and returns the root key that has this needle somewhere within it's children. :param haystack: dict, list :param needle: search key :param return_key: if this is given, then the result will be the root_ke...
True)) else: found.extend(seek_regex_key_in_dict_values(value, key_name, needle, key_matched)) elif isinstance(haystack, list): for value in haystack: found.extend(seek_regex_key_in_dict_values(value, key_name, needle, key_matched)) else: return [] ...
104
104
348
31
72
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
find_root_by_key
find_root_by_key
153
185
153
153
e4b8d6c28084707a790b9e79916788ec0723bf8a
bigcode/the-stack
train
e4d8ec618a36ac8c51d722c5
train
function
def get_resource_address_list_from_stash(resource_list): address_list = [] for resource in resource_list: if 'address' in resource and resource['address'] not in address_list: address_list.append(resource['address']) return address_list
def get_resource_address_list_from_stash(resource_list):
address_list = [] for resource in resource_list: if 'address' in resource and resource['address'] not in address_list: address_list.append(resource['address']) return address_list
]['address'].replace('[0]','')} else: return {'address': stash[0]} else: if 'address' in alternative_stash: return alternative_stash else: return {'address': alternative_stash} def get_resource_address_list_from_stash(resource_...
64
64
53
11
53
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
get_resource_address_list_from_stash
get_resource_address_list_from_stash
218
224
218
218
a8a364fe212ee68fb4019872805da5908bf1ffa9
bigcode/the-stack
train
2743938a37e78db87f1fe5ad
train
function
def flatten_list(input): return list(flatten(input))
def flatten_list(input):
return list(flatten(input))
import re from netaddr import IPNetwork from terraform_compliance.steps import resource_name from collections.abc import Iterable import json from copy import deepcopy class EmptyStash(object): pass class Null(object): pass def flatten_list(input):
55
64
12
5
49
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
flatten_list
flatten_list
17
18
17
17
87bdf32b7c06c1bae8fa8fc12abd8da07ccf97dd
bigcode/the-stack
train
920abb9243a0fe6509b985c9
train
function
def seek_regex_key_in_dict_values(haystack, key_name, needle, key_matched=None): ''' Searches needle in haystack ( could be dict, list, list of dicts, nested dicts, etc. ) and returns all findings as a list. The only difference from seek_key_in_dict is, we are assuming needle is in regex format here and we ...
def seek_regex_key_in_dict_values(haystack, key_name, needle, key_matched=None):
''' Searches needle in haystack ( could be dict, list, list of dicts, nested dicts, etc. ) and returns all findings as a list. The only difference from seek_key_in_dict is, we are assuming needle is in regex format here and we are searching for values instead. :param haystack: dict, list :param...
& values ''' found = list() if isinstance(haystack, dict): for key, value in haystack.items(): if key.lower() == needle.lower(): found.append({key: value}) else: found.extend(seek_key_in_dict(value, needle)) elif isinstance(haystack, list...
120
120
402
21
98
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
seek_regex_key_in_dict_values
seek_regex_key_in_dict_values
105
150
105
105
688ad760353625068784bc91562d6375cd4047d8
bigcode/the-stack
train
4f50621e28a18acb83d62d5b
train
class
class Null(object): pass
class Null(object):
pass
import re from netaddr import IPNetwork from terraform_compliance.steps import resource_name from collections.abc import Iterable import json from copy import deepcopy class EmptyStash(object): pass class Null(object):
47
64
7
4
42
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
Null
Null
13
14
13
13
5ef6097a059007caae27bc669c8ab15848eff89f
bigcode/the-stack
train
cbb8b72c5055da77ee273c8e
train
function
def seek_value_in_dict(needle, haystack, address=None): findings = [] if isinstance(haystack, (str, int, bool, float)) and needle in haystack: findings.append(dict(values=needle, address=None)) elif isinstance(haystack, dict): address = haystack.get('address') if address is None else addres...
def seek_value_in_dict(needle, haystack, address=None):
findings = [] if isinstance(haystack, (str, int, bool, float)) and needle in haystack: findings.append(dict(values=needle, address=None)) elif isinstance(haystack, dict): address = haystack.get('address') if address is None else address for key, value in haystack.items(): ...
resource['values']: del resource['values'][mounted_resource_type] return resources def search_regex_in_list(regex, target_list): if isinstance(target_list, list): return list(filter(re.compile(r'{}'.format(regex)).match, target_list)) return False def seek_value_in_dict(need...
71
71
239
14
56
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
seek_value_in_dict
seek_value_in_dict
248
272
248
248
a1db06ab5db1a40bac141871f69df4fdf3573d75
bigcode/the-stack
train
89ddb0e39efdc4829c5275c5
train
function
def seek_key_in_dict(haystack, needle): ''' Searches needle in haystack ( could be dict, list, list of dicts, nested dicts, etc. ) and returns all findings as a list :param haystack: dict, list :param needle: search key :return: list of found keys & values ''' found = list() if isin...
def seek_key_in_dict(haystack, needle):
''' Searches needle in haystack ( could be dict, list, list of dicts, nested dicts, etc. ) and returns all findings as a list :param haystack: dict, list :param needle: search key :return: list of found keys & values ''' found = list() if isinstance(haystack, dict): for key,...
value if it is found :param resource_type: String of resource_type :return: converted or original resource_type ''' if resource_type in resource_name.keys(): resource_type = resource_name[resource_type] return resource_type def seek_key_in_dict(haystack, needle):
64
64
173
11
52
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
seek_key_in_dict
seek_key_in_dict
78
102
78
78
668683acb33c738273b54318cb840e3b322ec98f
bigcode/the-stack
train
e3b5467367df09151a696b13
train
function
def is_ip_in_cidr(ip_cidr, cidr): for ip_network in cidr: if check_if_cidr(ip_cidr) and check_if_cidr(ip_network) and IPNetwork(ip_cidr) in IPNetwork(ip_network): return True return False
def is_ip_in_cidr(ip_cidr, cidr):
for ip_network in cidr: if check_if_cidr(ip_cidr) and check_if_cidr(ip_network) and IPNetwork(ip_cidr) in IPNetwork(ip_network): return True return False
r'(3[0-2]|2[0-9]|1[0-9]|[0-9])' matches = re.match(regex, value) if matches is not None: return True return False def is_ip_in_cidr(ip_cidr, cidr):
64
64
60
13
50
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
is_ip_in_cidr
is_ip_in_cidr
48
53
48
48
bd6a9de4a64727b220c27334c61eb105568e6fcb
bigcode/the-stack
train
3056809617134534916e9a00
train
class
class EmptyStash(object): pass
class EmptyStash(object):
pass
import re from netaddr import IPNetwork from terraform_compliance.steps import resource_name from collections.abc import Iterable import json from copy import deepcopy class EmptyStash(object):
40
64
9
6
33
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
EmptyStash
EmptyStash
9
10
9
9
18b375b277f2b7288a6bebcb2bdfae5e61f9e6a0
bigcode/the-stack
train
8184701129b0909f056acb09
train
function
def flatten(items): for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): for sub_x in flatten(x): yield sub_x else: yield x
def flatten(items):
for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): for sub_x in flatten(x): yield sub_x else: yield x
from netaddr import IPNetwork from terraform_compliance.steps import resource_name from collections.abc import Iterable import json from copy import deepcopy class EmptyStash(object): pass class Null(object): pass def flatten_list(input): return list(flatten(input)) def flatten(items):
64
64
47
4
60
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
flatten
flatten
21
27
21
21
b4a9f4e7a9fb2cb1ee798f27a8fbcbeb46c890ac
bigcode/the-stack
train
7f3f45fc46eb18b70b5a6a59
train
function
def convert_resource_type(resource_type): ''' Searchs given resource_type within resource_name array and returns the value if it is found :param resource_type: String of resource_type :return: converted or original resource_type ''' if resource_type in resource_name.keys(): resource_typ...
def convert_resource_type(resource_type):
''' Searchs given resource_type within resource_name array and returns the value if it is found :param resource_type: String of resource_type :return: converted or original resource_type ''' if resource_type in resource_name.keys(): resource_type = resource_name[resource_type] retu...
are_networks_same(first_network, network_list): for second_network in network_list: if check_if_cidr(first_network) and check_if_cidr(second_network) and \ IPNetwork(first_network) == IPNetwork(second_network): return True return False def convert_resource_type(resource_typ...
64
64
75
7
56
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
convert_resource_type
convert_resource_type
65
75
65
65
2a20a17a6626cfeb944838676c4410e8f8af2398
bigcode/the-stack
train
3dffc784d7191b438d58de59
train
function
def is_key_exist(key, target_list_of_dict): for each in target_list_of_dict: if isinstance(each, dict) and key in each.keys(): return True return False
def is_key_exist(key, target_list_of_dict):
for each in target_list_of_dict: if isinstance(each, dict) and key in each.keys(): return True return False
if not is_key_exist(each_key, val): src[key].append(dst_elem) return src def is_list_of_dict(target_list): return isinstance(target_list, list) and len(target_list) and isinstance(target_list[0], dict) def is_key_exist(key, target_list_of_dict):
64
64
41
11
53
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
is_key_exist
is_key_exist
295
300
295
295
be02684a5673f3593754c5e3faa8e6fb25e6668f
bigcode/the-stack
train
d3f6f31dbb4090a57ece0d17
train
function
def is_list_of_dict(target_list): return isinstance(target_list, list) and len(target_list) and isinstance(target_list[0], dict)
def is_list_of_dict(target_list):
return isinstance(target_list, list) and len(target_list) and isinstance(target_list[0], dict)
dst and is_list_of_dict(val) and is_list_of_dict(dst[key]): for dst_elem in dst[key]: for each_key in dst_elem.keys(): if not is_key_exist(each_key, val): src[key].append(dst_elem) return src def is_list_of_dict(target_list):
64
64
30
8
55
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
is_list_of_dict
is_list_of_dict
291
292
291
291
f5b1e3d035f440b6871424f5813f7b42c13ba889
bigcode/the-stack
train
6cbe008aa09c685b0784448e
train
function
def search_regex_in_list(regex, target_list): if isinstance(target_list, list): return list(filter(re.compile(r'{}'.format(regex)).match, target_list)) return False
def search_regex_in_list(regex, target_list):
if isinstance(target_list, list): return list(filter(re.compile(r'{}'.format(regex)).match, target_list)) return False
resources: if 'terraform-compliance.mounted_resources' in resource: for mounted_resource_type in resource['terraform-compliance.mounted_resources']: if mounted_resource_type in resource['values']: del resource['values'][mounted_resource_type] return resource...
64
64
39
10
53
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
search_regex_in_list
search_regex_in_list
241
245
241
241
4be941e02a615948cbefafb5218edcfd2e64be58
bigcode/the-stack
train
a53fd573be85b773f989f539
train
function
def get_resource_name_from_stash(stash, alternative_stash=None, address=None): if address is not None: return {'address': address} if isinstance(alternative_stash, (str, bool)) or alternative_stash is None: if isinstance(stash, list): # Get the first number, since this is usually d...
def get_resource_name_from_stash(stash, alternative_stash=None, address=None):
if address is not None: return {'address': address} if isinstance(alternative_stash, (str, bool)) or alternative_stash is None: if isinstance(stash, list): # Get the first number, since this is usually due to `count` usage in terraform if 'address' in stash[0] and stash...
return [] return list(set(found)) def jsonify(string): if not isinstance(string, str): return string try: return json.loads(string) except json.decoder.JSONDecodeError: return string def get_resource_name_from_stash(stash, alternative_stash=None, address=None):
64
64
162
18
45
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
get_resource_name_from_stash
get_resource_name_from_stash
198
215
198
198
cff2961a5ab03db9c8ec70405cda2b888fba6600
bigcode/the-stack
train
a1aa1197c50c6fce54a4198a
train
function
def remove_mounted_resources(resource_list): if not isinstance(resource_list, list): return resource_list resources = deepcopy(resource_list) for resource in resources: if 'terraform-compliance.mounted_resources' in resource: for mounted_resource_type in resource['terraform-comp...
def remove_mounted_resources(resource_list):
if not isinstance(resource_list, list): return resource_list resources = deepcopy(resource_list) for resource in resources: if 'terraform-compliance.mounted_resources' in resource: for mounted_resource_type in resource['terraform-compliance.mounted_resources']: i...
_stash} def get_resource_address_list_from_stash(resource_list): address_list = [] for resource in resource_list: if 'address' in resource and resource['address'] not in address_list: address_list.append(resource['address']) return address_list def remove_mounted_resources(resource_li...
64
64
87
8
55
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
remove_mounted_resources
remove_mounted_resources
227
238
227
227
aeebd98ab5074b3a13260ad5539d7dae1d548aa8
bigcode/the-stack
train
536beeed00996bdf6abc4576
train
function
def jsonify(string): if not isinstance(string, str): return string try: return json.loads(string) except json.decoder.JSONDecodeError: return string
def jsonify(string):
if not isinstance(string, str): return string try: return json.loads(string) except json.decoder.JSONDecodeError: return string
stack, list) and _inherited_key is not None: for value in haystack: found.extend(find_root_by_key(value, needle, return_key, _inherited_key, _depth+1, _return_value)) else: return [] return list(set(found)) def jsonify(string):
64
64
37
4
60
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
jsonify
jsonify
188
195
188
188
2a6d72981eb1d0c067a74d5f8a1d92b475ae5692
bigcode/the-stack
train
90afd6f265593d5896118f3e
train
function
def check_if_cidr(value): regex = r'(1[0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])' \ r'\.' \ r'(1[0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])' \ r'\.' \ r'(1[0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])' \ r'\.' \ r'(1[0-9][0-9]|2[0...
def check_if_cidr(value):
regex = r'(1[0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])' \ r'\.' \ r'(1[0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])' \ r'\.' \ r'(1[0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])' \ r'\.' \ r'(1[0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9...
(object): pass class Null(object): pass def flatten_list(input): return list(flatten(input)) def flatten(items): for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): for sub_x in flatten(x): yield sub_x else: yield ...
78
78
261
7
70
ptiredknees/terraform-compliance
terraform_compliance/common/helper.py
Python
check_if_cidr
check_if_cidr
30
45
30
30
062ba32b2e44f386382ef0ce1b25e4413bacaea1
bigcode/the-stack
train
a68a33c160f903567d118cb1
train
function
def find_people_to_vaccinate( receives_vaccine, # noqa: U100 states, params, seed, # noqa: U100 vaccination_shares, init_start, ): """Find people that have to be vaccinated on a given day. On the init_start date all individuals that should have been vaccinated until that day get v...
def find_people_to_vaccinate( receives_vaccine, # noqa: U100 states, params, seed, # noqa: U100 vaccination_shares, init_start, ):
"""Find people that have to be vaccinated on a given day. On the init_start date all individuals that should have been vaccinated until that day get vaccinated. Since vaccinations take effect within three weeks and the burn in period is four weeks this does not lead to jumps in the simulation perio...
import warnings import pandas as pd from sid import get_date def find_people_to_vaccinate( receives_vaccine, # noqa: U100 states, params, seed, # noqa: U100 vaccination_shares, init_start, ):
60
158
527
46
13
covid-19-impact-lab/sid-germany
src/policies/find_people_to_vaccinate.py
Python
find_people_to_vaccinate
find_people_to_vaccinate
7
64
7
14
38010ea02020852b885154336f4afae0fdbf15fd
bigcode/the-stack
train
9bd35a3b05f55155763647f1
train
class
class Migration(migrations.Migration): dependencies = [ ('streamers', '0001_initial'), ] operations = [ migrations.AlterField( model_name='streamer', name='created', field=models.DateTimeField(auto_now_add=True), ), ]
class Migration(migrations.Migration):
dependencies = [ ('streamers', '0001_initial'), ] operations = [ migrations.AlterField( model_name='streamer', name='created', field=models.DateTimeField(auto_now_add=True), ), ]
# Generated by Django 3.1.7 on 2021-04-09 01:10 from django.db import migrations, models class Migration(migrations.Migration):
38
64
59
7
30
wwsean08/tau
tau/streamers/migrations/0002_auto_20210409_0110.py
Python
Migration
Migration
6
18
6
7
553191c190e292ebaf05f75718284a91306fe256
bigcode/the-stack
train
ba305cc5d0cdd364268febf2
train
function
def mk_github(name, source): return { "name": name, "git": "https://" + source + ".git", "http": "https://" + source, "dir": "https://" + source + "/tree/master{/dir}", "file": "https://" + source + "/blob/master{/dir}/{file}#L{line}", }
def mk_github(name, source):
return { "name": name, "git": "https://" + source + ".git", "http": "https://" + source, "dir": "https://" + source + "/tree/master{/dir}", "file": "https://" + source + "/blob/master{/dir}/{file}#L{line}", }
go-source" content="{name} {http} {dir} {file}"> <meta http-equiv="refresh" content="0; url={http}"> </head> <body> Nothing to see here; <a href="{http}">move along</a>. </body> """ def mk_github(name, source):
64
64
83
8
56
sour-is/go-toolbox
mkweb.py
Python
mk_github
mk_github
20
27
20
20
1128dda682c539ca8c9c7417b2bc912f19497c94
bigcode/the-stack
train
cbdf83eec107c78a7b4a4324
train
class
class MealPal: def __init__(self): self.session = requests.Session() def login(self, user, password): data = { 'username': user, 'password': password, } headers = { 'Host': BASE_DOMAIN, 'Origin': BASE_URL, 'Referer': ...
class MealPal:
def __init__(self): self.session = requests.Session() def login(self, user, password): data = { 'username': user, 'password': password, } headers = { 'Host': BASE_DOMAIN, 'Origin': BASE_URL, 'Referer': f'{BASE_URL}/log...
import requests BASE_DOMAIN = 'secure.mealpal.com' BASE_URL = f'https://{BASE_DOMAIN}' LOGIN_URL = f'{BASE_URL}/1/login' CITIES_URL = f'{BASE_URL}/1/functions/getCitiesWithNeighborhoods' MENU_URL = f'{BASE_URL}/api/v1/cities/{{}}/product_offerings/lunch/menu' RESERVATION_URL = f'{BASE_URL}/api/v2/reservations' KITCHE...
111
160
536
4
107
ipwnponies/mealpy
mealpy/mealpy.py
Python
MealPal
MealPal
13
100
13
14
ac4ae66af0bdd607635f334e7eea9380c14e06c3
bigcode/the-stack
train
6909283794cec09e1e55cc49
train
class
class EventListBox(urwid.ListBox): """Container for list of U_Events""" def __init__( self, *args, parent, conf, delete_status, toggle_delete_instance, toggle_delete_all, set_focus_date_callback=None, **kwargs): self._init = True self.parent = par...
class EventListBox(urwid.ListBox):
"""Container for list of U_Events""" def __init__( self, *args, parent, conf, delete_status, toggle_delete_instance, toggle_delete_all, set_focus_date_callback=None, **kwargs): self._init = True self.parent = parent self.delete_status = de...
binds = self._conf['keybindings'] if key in binds['left']: key = 'left' elif key in binds['up']: key = 'up' elif key in binds['right']: key = 'right' elif key in binds['down']: key = 'down' return key class EventListBox(urwid.ListB...
79
79
264
10
68
PsychicNoodles/khal
khal/ui/__init__.py
Python
EventListBox
EventListBox
237
274
237
237
b307dcb9e27637313da514e17dfb47631ef29bdb
bigcode/the-stack
train
5aa559d598fc4338c4b06e89
train
class
class DayWalker(urwid.SimpleFocusListWalker): """A list Walker that contains a list of DateListBox objects, each representing one day and associated events""" def __init__(self, this_date, eventcolumn, conf, collection, delete_status): self.eventcolumn = eventcolumn self._conf = conf ...
class DayWalker(urwid.SimpleFocusListWalker):
"""A list Walker that contains a list of DateListBox objects, each representing one day and associated events""" def __init__(self, this_date, eventcolumn, conf, collection, delete_status): self.eventcolumn = eventcolumn self._conf = conf self.delete_status = delete_status s...
self._conf['keybindings']['today']: self.parent.calendar.base_widget.set_focus_date(dt.date.today()) rval = super().keypress(size, key) self.clean() if key in ['up', 'down']: try: self._old_focus = self.focus_position except IndexError: ...
256
256
1,222
11
245
PsychicNoodles/khal
khal/ui/__init__.py
Python
DayWalker
DayWalker
350
504
350
350
fd8d788846b13b66d7de601fc989fae95d15277d
bigcode/the-stack
train
cd1c2935be365225911c23ec
train
class
class SearchDialog(urwid.WidgetWrap): """A Search Dialog Widget""" def __init__(self, search_func, abort_func): class Search(Edit): def keypress(self, size, key): if key == 'enter': search_func(self.text) else: return...
class SearchDialog(urwid.WidgetWrap):
"""A Search Dialog Widget""" def __init__(self, search_func, abort_func): class Search(Edit): def keypress(self, size, key): if key == 'enter': search_func(self.text) else: return super().keypress(size, key) ...
.calendar)) lines.append(divider) if event.description != '': lines.append(urwid.Text(event.description)) pile = urwid.Pile(lines) urwid.WidgetWrap.__init__(self, urwid.Filler(pile, valign='top')) class SearchDialog(urwid.WidgetWrap):
63
64
181
9
54
PsychicNoodles/khal
khal/ui/__init__.py
Python
SearchDialog
SearchDialog
1,001
1,026
1,001
1,001
2ead39a54415818e29acedf114a5bd60497e2374
bigcode/the-stack
train
f14cf3c3ac1836c3f45247d1
train
class
class DateListBox(urwid.ListBox): """A ListBox container for a SimpleFocusListWalker, that contains one day worth of events""" selected_date = None def __init__(self, content, date): self.date = date super().__init__(content) def __repr__(self): return f'<DateListBox {self...
class DateListBox(urwid.ListBox):
"""A ListBox container for a SimpleFocusListWalker, that contains one day worth of events""" selected_date = None def __init__(self, content, date): self.date = date super().__init__(content) def __repr__(self): return f'<DateListBox {self.date}>' __str__ = __repr__ ...
type end: datetime.date """ start = start.date() if isinstance(start, dt.datetime) else start end = end.date() if isinstance(end, dt.datetime) else end update = everything for one in self: if (start <= one.date <= end): update = True if update...
120
120
401
10
110
PsychicNoodles/khal
khal/ui/__init__.py
Python
DateListBox
DateListBox
561
615
561
561
91d2c3b2e36759c7af104b7888f8afaef31b6666
bigcode/the-stack
train
ea33224ffa6f38294697833e
train
class
class DateHeader(SelectableText): def __init__(self, day, dateformat, conf): """ :type day: datetime.date :type dateformat: format to print `day` in :type dateformat: str """ self._day = day self._dateformat = dateformat self._conf = conf super...
class DateHeader(SelectableText):
def __init__(self, day, dateformat, conf): """ :type day: datetime.date :type dateformat: format to print `day` in :type dateformat: str """ self._day = day self._dateformat = dateformat self._conf = conf super().__init__('') self.updat...
| # +----------------------------------------------------------+ ALL = 1 INSTANCES = 2 class DateConversionError(Exception): pass class SelectableText(urwid.Text): def selectable(self): return True def keypress(self, size, key): return key def get_cursor_coords(self, size): ...
131
131
438
7
123
PsychicNoodles/khal
khal/ui/__init__.py
Python
DateHeader
DateHeader
101
158
101
101
d3eb5e3c33c6c5e81de47acfb9b969b5734770e1
bigcode/the-stack
train
bd0aee39ab984a76f37ad848
train
class
class ClassicView(Pane): """default Pane for khal showing a CalendarWalker on the left and the eventList + eventviewer/editor on the right """ def __init__(self, collection, conf=None, title='', description=''): self.init = True # Will be set when opening the view inside a Window ...
class ClassicView(Pane):
"""default Pane for khal showing a CalendarWalker on the left and the eventList + eventviewer/editor on the right """ def __init__(self, collection, conf=None, title='', description=''): self.init = True # Will be set when opening the view inside a Window self.window = None...
)) lines.append(urwid.Text('Calendar: ' + event.calendar)) lines.append(divider) if event.description != '': lines.append(urwid.Text(event.description)) pile = urwid.Pile(lines) urwid.WidgetWrap.__init__(self, urwid.Filler(pile, valign='top')) class SearchDialog(...
256
256
1,235
6
250
PsychicNoodles/khal
khal/ui/__init__.py
Python
ClassicView
ClassicView
1,029
1,176
1,029
1,029
76d76fe2fee01c2ba4e34bd74f0e80c273ec5534
bigcode/the-stack
train
91a4c6a360574030b585dfee
train
class
class EventColumn(urwid.WidgetWrap): """Container for list of events Handles modifying events, showing events' details and editing them """ def __init__(self, elistbox, pane): self.pane = pane self._conf = pane._conf self.divider = urwid.Divider('─') self.editor = False...
class EventColumn(urwid.WidgetWrap):
"""Container for list of events Handles modifying events, showing events' details and editing them """ def __init__(self, elistbox, pane): self.pane = pane self._conf = pane._conf self.divider = urwid.Divider('─') self.editor = False self._current_date = None ...
_style() return super().render(size, focus) def reset_style(self): self.body[0].set_attr_map({None: 'date header'}) def set_selected_date(self, day): """Mark `day` as selected :param day: day to mark as selected :type day: datetime.date """ DateListBox....
256
256
2,595
9
247
PsychicNoodles/khal
khal/ui/__init__.py
Python
EventColumn
EventColumn
618
941
618
618
d7cb0e5ce188b62eff99c5d4add6ca985e2f8722
bigcode/the-stack
train
9385da9c796e1d1362539708
train
function
def start_pane(pane, callback, program_info='', quit_keys=None): """Open the user interface with the given initial pane.""" quit_keys = quit_keys or ['q'] frame = Window( footer=program_info + f' | {quit_keys[0]}: quit, ?: help', quit_keys=quit_keys, ) class LogPaneFormatter(loggin...
def start_pane(pane, callback, program_info='', quit_keys=None):
"""Open the user interface with the given initial pane.""" quit_keys = quit_keys or ['q'] frame = Window( footer=program_info + f' | {quit_keys[0]}: quit, ?: help', quit_keys=quit_keys, ) class LogPaneFormatter(logging.Formatter): def get_prefix(self, level): if...
'foreground']: return (name, '', '', '', color, '') else: return (name, '', '', '', '', color) def _add_calendar_colors(palette, collection): """Add the colors for the defined calendars to the palette. :param palette: the base palette :type palette: list :param collection: :t...
230
230
768
16
213
PsychicNoodles/khal
khal/ui/__init__.py
Python
start_pane
start_pane
1,272
1,371
1,272
1,272
824b9bd859fa0c004d6691f1fcc1b7ccf42aefed
bigcode/the-stack
train
ab4c8f5924350af9f06f8f29
train
function
def _add_calendar_colors(palette, collection): """Add the colors for the defined calendars to the palette. :param palette: the base palette :type palette: list :param collection: :type collection: CalendarCollection :returns: the modified palette :rtype: list """ for cal in collecti...
def _add_calendar_colors(palette, collection):
"""Add the colors for the defined calendars to the palette. :param palette: the base palette :type palette: list :param collection: :type collection: CalendarCollection :returns: the modified palette :rtype: list """ for cal in collection.calendars: if cal['color'] == '': ...
high color slot. It seems to work # in lower color terminals as well. if hmethod in ['fg', 'foreground']: return (name, '', '', '', color, '') else: return (name, '', '', '', '', color) def _add_calendar_colors(palette, collection):
64
64
186
10
54
PsychicNoodles/khal
khal/ui/__init__.py
Python
_add_calendar_colors
_add_calendar_colors
1,247
1,269
1,247
1,247
25253ac2a1d36d002a95566b5c77e22db3a42569
bigcode/the-stack
train