body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
f4ea1b1b9ec17424450a9ea6da24343b0da873334048e7e158e9f0943afcef39 | def simFN(a, b, t, disp, I):
'\n Integrates the FHN ODEs\n\n Input:\n a: the shape of the cubic parabola\n b: describes the kinetics of the recovery variable w\n c: describes the kinetics of the recovery variable\n t: time to integrate over\n disp: (True/False) plot data\n I: input current\n... | Integrates the FHN ODEs
Input:
a: the shape of the cubic parabola
b: describes the kinetics of the recovery variable w
c: describes the kinetics of the recovery variable
t: time to integrate over
disp: (True/False) plot data
I: input current
Output
V - membrane voltage
w - recovery variable that mimics activation of ... | simulateFHN.py | simFN | thq80/auxiliary-particle-filter | 1 | python | def simFN(a, b, t, disp, I):
'\n Integrates the FHN ODEs\n\n Input:\n a: the shape of the cubic parabola\n b: describes the kinetics of the recovery variable w\n c: describes the kinetics of the recovery variable\n t: time to integrate over\n disp: (True/False) plot data\n I: input current\n... | def simFN(a, b, t, disp, I):
'\n Integrates the FHN ODEs\n\n Input:\n a: the shape of the cubic parabola\n b: describes the kinetics of the recovery variable w\n c: describes the kinetics of the recovery variable\n t: time to integrate over\n disp: (True/False) plot data\n I: input current\n... |
c44e783b92300b7d79c47a1787ff587e502683d41cb86765b262992844d25fae | def test_reinforceio_homepage(self):
'\n Code example from the homepage and README.md.\n '
from tensorforce.agents import TRPOAgent
agent = TRPOAgent(states=dict(shape=(10,), type='float'), actions=dict(type='int', num_actions=2), network=[dict(type='dense', size=50), dict(type='dense', size=5... | Code example from the homepage and README.md. | tensorforce/tests/test_tutorial_code.py | test_reinforceio_homepage | Jonathan-Livingston-Seagull/tensorforce | 2 | python | def test_reinforceio_homepage(self):
'\n \n '
from tensorforce.agents import TRPOAgent
agent = TRPOAgent(states=dict(shape=(10,), type='float'), actions=dict(type='int', num_actions=2), network=[dict(type='dense', size=50), dict(type='dense', size=50)], update_mode=dict(unit='episodes', batch_... | def test_reinforceio_homepage(self):
'\n \n '
from tensorforce.agents import TRPOAgent
agent = TRPOAgent(states=dict(shape=(10,), type='float'), actions=dict(type='int', num_actions=2), network=[dict(type='dense', size=50), dict(type='dense', size=50)], update_mode=dict(unit='episodes', batch_... |
efc4c8636b3e187a77d15cb0d258779e8414d04db02cc4f81329b7d44daa10e3 | def test_blogpost_introduction(self):
'\n Test of introduction blog post examples.\n '
import tensorflow as tf
from tensorforce.agents import DQNAgent
network_spec = [dict(type='dense', size=32), dict(type='dense', size=32)]
states = dict(shape=(10,), type='float')
actions = dict(t... | Test of introduction blog post examples. | tensorforce/tests/test_tutorial_code.py | test_blogpost_introduction | Jonathan-Livingston-Seagull/tensorforce | 2 | python | def test_blogpost_introduction(self):
'\n \n '
import tensorflow as tf
from tensorforce.agents import DQNAgent
network_spec = [dict(type='dense', size=32), dict(type='dense', size=32)]
states = dict(shape=(10,), type='float')
actions = dict(type='int', num_actions=5)
agent = DQ... | def test_blogpost_introduction(self):
'\n \n '
import tensorflow as tf
from tensorforce.agents import DQNAgent
network_spec = [dict(type='dense', size=32), dict(type='dense', size=32)]
states = dict(shape=(10,), type='float')
actions = dict(type='int', num_actions=5)
agent = DQ... |
0223b196a61405d32e9809415093d55e6c56d6249c6a9e27cbf5651077436d76 | @property
def id(self):
'The ID of the entity.'
return self.data[self.id_field] | The ID of the entity. | cartoframes/data/observatory/catalog/entity.py | id | CartoDB/cartoframes | 236 | python | @property
def id(self):
return self.data[self.id_field] | @property
def id(self):
return self.data[self.id_field]<|docstring|>The ID of the entity.<|endoftext|> |
37963d69424da678bdd5b774a6a4e99271d0f0ccc9938d1312b15b26d315b385 | @property
def slug(self):
'The slug (short ID) of the entity.'
try:
return self.data['slug']
except KeyError:
return None | The slug (short ID) of the entity. | cartoframes/data/observatory/catalog/entity.py | slug | CartoDB/cartoframes | 236 | python | @property
def slug(self):
try:
return self.data['slug']
except KeyError:
return None | @property
def slug(self):
try:
return self.data['slug']
except KeyError:
return None<|docstring|>The slug (short ID) of the entity.<|endoftext|> |
37af31659259b9b8f399c0ca120bad0dd6165da59b54390637c282950d94534f | @classmethod
def get(cls, id_):
"Get an instance of an entity by ID or slug.\n\n Args:\n id_ (str):\n ID or slug of a catalog entity.\n\n Raises:\n CatalogError: if there's a problem when connecting to the catalog or no entities are found.\n\n "
return c... | Get an instance of an entity by ID or slug.
Args:
id_ (str):
ID or slug of a catalog entity.
Raises:
CatalogError: if there's a problem when connecting to the catalog or no entities are found. | cartoframes/data/observatory/catalog/entity.py | get | CartoDB/cartoframes | 236 | python | @classmethod
def get(cls, id_):
"Get an instance of an entity by ID or slug.\n\n Args:\n id_ (str):\n ID or slug of a catalog entity.\n\n Raises:\n CatalogError: if there's a problem when connecting to the catalog or no entities are found.\n\n "
return c... | @classmethod
def get(cls, id_):
"Get an instance of an entity by ID or slug.\n\n Args:\n id_ (str):\n ID or slug of a catalog entity.\n\n Raises:\n CatalogError: if there's a problem when connecting to the catalog or no entities are found.\n\n "
return c... |
62228648d26fa6702751cb3da955493424fd84d15b9d9a44440396af99d68c3f | @classmethod
def get_all(cls, filters=None):
'List all instances of an entity.\n\n Args:\n filters (dict, optional):\n Dict containing pairs of entity properties and its value to be used as filters to query the available\n entities. If none is provided, no filters wil... | List all instances of an entity.
Args:
filters (dict, optional):
Dict containing pairs of entity properties and its value to be used as filters to query the available
entities. If none is provided, no filters will be applied to the query. | cartoframes/data/observatory/catalog/entity.py | get_all | CartoDB/cartoframes | 236 | python | @classmethod
def get_all(cls, filters=None):
'List all instances of an entity.\n\n Args:\n filters (dict, optional):\n Dict containing pairs of entity properties and its value to be used as filters to query the available\n entities. If none is provided, no filters wil... | @classmethod
def get_all(cls, filters=None):
'List all instances of an entity.\n\n Args:\n filters (dict, optional):\n Dict containing pairs of entity properties and its value to be used as filters to query the available\n entities. If none is provided, no filters wil... |
6a37c32b5bb404286096bb81301df57fa6cfa87a3d645a8063eaa03be4098a32 | @classmethod
def get_list(cls, id_list):
"Get a list of instance of an entity by a list of IDs or slugs.\n\n Args:\n id_list (list):\n List of ID or slugs of entities in the catalog to retrieve instances.\n\n Raises:\n CatalogError: if there's a problem when connec... | Get a list of instance of an entity by a list of IDs or slugs.
Args:
id_list (list):
List of ID or slugs of entities in the catalog to retrieve instances.
Raises:
CatalogError: if there's a problem when connecting to the catalog or no entities are found. | cartoframes/data/observatory/catalog/entity.py | get_list | CartoDB/cartoframes | 236 | python | @classmethod
def get_list(cls, id_list):
"Get a list of instance of an entity by a list of IDs or slugs.\n\n Args:\n id_list (list):\n List of ID or slugs of entities in the catalog to retrieve instances.\n\n Raises:\n CatalogError: if there's a problem when connec... | @classmethod
def get_list(cls, id_list):
"Get a list of instance of an entity by a list of IDs or slugs.\n\n Args:\n id_list (list):\n List of ID or slugs of entities in the catalog to retrieve instances.\n\n Raises:\n CatalogError: if there's a problem when connec... |
7f793df3f847d450bfee289c0c03c7e7281c83f14bdf6d5f7e786307467682eb | def to_series(self):
'Converts the entity instance to a pandas Series.'
return pd.Series(self.data) | Converts the entity instance to a pandas Series. | cartoframes/data/observatory/catalog/entity.py | to_series | CartoDB/cartoframes | 236 | python | def to_series(self):
return pd.Series(self.data) | def to_series(self):
return pd.Series(self.data)<|docstring|>Converts the entity instance to a pandas Series.<|endoftext|> |
78627af9dc0cfaed43e2c3cbdc43967a0409402283c0b533c1e7632dae0ec3f4 | def to_dict(self):
'Converts the entity instance to a Python dict.'
return {key: value for (key, value) in self.data.items() if (key not in self.export_excluded_fields)} | Converts the entity instance to a Python dict. | cartoframes/data/observatory/catalog/entity.py | to_dict | CartoDB/cartoframes | 236 | python | def to_dict(self):
return {key: value for (key, value) in self.data.items() if (key not in self.export_excluded_fields)} | def to_dict(self):
return {key: value for (key, value) in self.data.items() if (key not in self.export_excluded_fields)}<|docstring|>Converts the entity instance to a Python dict.<|endoftext|> |
6b8ea859c42427502a4c07fea30fed1a0ae0664648ab821d6b8662ebc75d8efa | def is_subscribed(self, credentials, entity_type):
'Check if the entity is subscribed'
return (self.is_public_data or (self.id in subscriptions.get_subscription_ids(credentials, entity_type))) | Check if the entity is subscribed | cartoframes/data/observatory/catalog/entity.py | is_subscribed | CartoDB/cartoframes | 236 | python | def is_subscribed(self, credentials, entity_type):
return (self.is_public_data or (self.id in subscriptions.get_subscription_ids(credentials, entity_type))) | def is_subscribed(self, credentials, entity_type):
return (self.is_public_data or (self.id in subscriptions.get_subscription_ids(credentials, entity_type)))<|docstring|>Check if the entity is subscribed<|endoftext|> |
647feb966a8e04af493170dc2c01865d60caabf3500aaea4ef63ff0b8f6abe4b | def to_dataframe(self):
'Converts a list to a pandas DataFrame.\n\n Examples:\n >>> catalog = Catalog()\n >>> catalog.categories.to_dataframe()\n\n '
df = pd.DataFrame([item.data for item in self])
if ('summary_json' in df):
del df['summary_json']
return df | Converts a list to a pandas DataFrame.
Examples:
>>> catalog = Catalog()
>>> catalog.categories.to_dataframe() | cartoframes/data/observatory/catalog/entity.py | to_dataframe | CartoDB/cartoframes | 236 | python | def to_dataframe(self):
'Converts a list to a pandas DataFrame.\n\n Examples:\n >>> catalog = Catalog()\n >>> catalog.categories.to_dataframe()\n\n '
df = pd.DataFrame([item.data for item in self])
if ('summary_json' in df):
del df['summary_json']
return df | def to_dataframe(self):
'Converts a list to a pandas DataFrame.\n\n Examples:\n >>> catalog = Catalog()\n >>> catalog.categories.to_dataframe()\n\n '
df = pd.DataFrame([item.data for item in self])
if ('summary_json' in df):
del df['summary_json']
return df<|d... |
8c8d15f8582fa415657be605cbfab67f5517a83598def7d11bfeacd67801697f | @classmethod
def load_viz(cls, viz_name: str, *args, **kwargs) -> Viz:
'Loads built in visualization class.\n Currently supports: "lorenz", "cylinder", "grayscott"\n\n Args:\n viz_name (str): Keyword/name of visualization class\n\n Raises:\n KeyError: If viz_name is not a ... | Loads built in visualization class.
Currently supports: "lorenz", "cylinder", "grayscott"
Args:
viz_name (str): Keyword/name of visualization class
Raises:
KeyError: If viz_name is not a supported visualization type
Returns:
(Viz): Initialized viz class | trphysx/viz/viz_auto.py | load_viz | zabaras/transformer-physx | 33 | python | @classmethod
def load_viz(cls, viz_name: str, *args, **kwargs) -> Viz:
'Loads built in visualization class.\n Currently supports: "lorenz", "cylinder", "grayscott"\n\n Args:\n viz_name (str): Keyword/name of visualization class\n\n Raises:\n KeyError: If viz_name is not a ... | @classmethod
def load_viz(cls, viz_name: str, *args, **kwargs) -> Viz:
'Loads built in visualization class.\n Currently supports: "lorenz", "cylinder", "grayscott"\n\n Args:\n viz_name (str): Keyword/name of visualization class\n\n Raises:\n KeyError: If viz_name is not a ... |
42d942fc8535b6ae0a0e532b373e4941b29e4946c6c9001bae97ba06f56a37df | def get_label(self):
'Gets the label of a traffic light color.\n\n Returns:\n :obj:`str`: The label string.\n '
if (self.value == 1):
return 'red traffic light'
elif (self.value == 2):
return 'yellow traffic light'
elif (self.value == 3):
return 'green tr... | Gets the label of a traffic light color.
Returns:
:obj:`str`: The label string. | pylot/perception/detection/traffic_light.py | get_label | chirpyjh/pylot | 231 | python | def get_label(self):
'Gets the label of a traffic light color.\n\n Returns:\n :obj:`str`: The label string.\n '
if (self.value == 1):
return 'red traffic light'
elif (self.value == 2):
return 'yellow traffic light'
elif (self.value == 3):
return 'green tr... | def get_label(self):
'Gets the label of a traffic light color.\n\n Returns:\n :obj:`str`: The label string.\n '
if (self.value == 1):
return 'red traffic light'
elif (self.value == 2):
return 'yellow traffic light'
elif (self.value == 3):
return 'green tr... |
061c6baa52d67ae1e3cf926dab52de841d26fef1f0718de1306316a406bd402c | @classmethod
def from_simulator_actor(cls, traffic_light):
' Creates a TrafficLight from a simulator traffic light actor.\n\n Args:\n traffic_light: A simulator traffic light actor.\n\n Returns:\n :py:class:`.TrafficLight`: A traffic light.\n '
from carla import Traffi... | Creates a TrafficLight from a simulator traffic light actor.
Args:
traffic_light: A simulator traffic light actor.
Returns:
:py:class:`.TrafficLight`: A traffic light. | pylot/perception/detection/traffic_light.py | from_simulator_actor | chirpyjh/pylot | 231 | python | @classmethod
def from_simulator_actor(cls, traffic_light):
' Creates a TrafficLight from a simulator traffic light actor.\n\n Args:\n traffic_light: A simulator traffic light actor.\n\n Returns:\n :py:class:`.TrafficLight`: A traffic light.\n '
from carla import Traffi... | @classmethod
def from_simulator_actor(cls, traffic_light):
' Creates a TrafficLight from a simulator traffic light actor.\n\n Args:\n traffic_light: A simulator traffic light actor.\n\n Returns:\n :py:class:`.TrafficLight`: A traffic light.\n '
from carla import Traffi... |
77e32acdd65b4ea2feca86bf784186f1fea7706836b8b4dbcc0b7314ba56ad95 | def is_traffic_light_visible(self, camera_transform: pylot.utils.Transform, town_name: str=None, distance_threshold: int=70):
'Checks if the traffic light is visible from the camera transform.\n\n Args:\n transform (:py:class:`~pylot.utils.Transform`): Transform of the\n camera in t... | Checks if the traffic light is visible from the camera transform.
Args:
transform (:py:class:`~pylot.utils.Transform`): Transform of the
camera in the world frame of reference.
distance_threshold (:obj:`int`): Maximum distance to the camera
(in m).
Returns:
bool: True if the traffic light ... | pylot/perception/detection/traffic_light.py | is_traffic_light_visible | chirpyjh/pylot | 231 | python | def is_traffic_light_visible(self, camera_transform: pylot.utils.Transform, town_name: str=None, distance_threshold: int=70):
'Checks if the traffic light is visible from the camera transform.\n\n Args:\n transform (:py:class:`~pylot.utils.Transform`): Transform of the\n camera in t... | def is_traffic_light_visible(self, camera_transform: pylot.utils.Transform, town_name: str=None, distance_threshold: int=70):
'Checks if the traffic light is visible from the camera transform.\n\n Args:\n transform (:py:class:`~pylot.utils.Transform`): Transform of the\n camera in t... |
b6e7172f69555e0261bd1b37f670263288ce77e6c5743fa4b991e7e33d88c97e | def get_all_detected_traffic_light_boxes(self, town_name: str, depth_frame, segmented_image):
' Returns traffic lights for all boxes of a simulator traffic light.\n\n Note:\n All the traffic lights returned will have the same id and\n transform.\n\n Args:\n town_name (... | Returns traffic lights for all boxes of a simulator traffic light.
Note:
All the traffic lights returned will have the same id and
transform.
Args:
town_name (:obj:`str`): Name of the town in which the traffic light
is.
depth_frame (:py:class:`~pylot.perception.depth_frame.DepthFrame`):
... | pylot/perception/detection/traffic_light.py | get_all_detected_traffic_light_boxes | chirpyjh/pylot | 231 | python | def get_all_detected_traffic_light_boxes(self, town_name: str, depth_frame, segmented_image):
' Returns traffic lights for all boxes of a simulator traffic light.\n\n Note:\n All the traffic lights returned will have the same id and\n transform.\n\n Args:\n town_name (... | def get_all_detected_traffic_light_boxes(self, town_name: str, depth_frame, segmented_image):
' Returns traffic lights for all boxes of a simulator traffic light.\n\n Note:\n All the traffic lights returned will have the same id and\n transform.\n\n Args:\n town_name (... |
1d3b90f9e3fa7600e5950a657dff1c0d5fd259a304cfd3370880dec13e35e876 | def _relative_to_traffic_light(self, points):
'Transforms the bounding box specified in the points relative to the\n light.\n\n Args:\n points: An array of length 4 representing the 4 points of the\n rectangle.\n '
def rotate(yaw, location):
' Rotate a giv... | Transforms the bounding box specified in the points relative to the
light.
Args:
points: An array of length 4 representing the 4 points of the
rectangle. | pylot/perception/detection/traffic_light.py | _relative_to_traffic_light | chirpyjh/pylot | 231 | python | def _relative_to_traffic_light(self, points):
'Transforms the bounding box specified in the points relative to the\n light.\n\n Args:\n points: An array of length 4 representing the 4 points of the\n rectangle.\n '
def rotate(yaw, location):
' Rotate a giv... | def _relative_to_traffic_light(self, points):
'Transforms the bounding box specified in the points relative to the\n light.\n\n Args:\n points: An array of length 4 representing the 4 points of the\n rectangle.\n '
def rotate(yaw, location):
' Rotate a giv... |
64b234550ab2734a5cf9407ba6e40b417006e92b4bbb19d781e6da33bc4f5a00 | def rotate(yaw, location):
' Rotate a given 3D vector around the Z-axis. '
rotation_matrix = np.identity(3)
rotation_matrix[(0, 0)] = np.cos(yaw)
rotation_matrix[(0, 1)] = (- np.sin(yaw))
rotation_matrix[(1, 0)] = np.sin(yaw)
rotation_matrix[(1, 1)] = np.cos(yaw)
location_vector = np.array([... | Rotate a given 3D vector around the Z-axis. | pylot/perception/detection/traffic_light.py | rotate | chirpyjh/pylot | 231 | python | def rotate(yaw, location):
' '
rotation_matrix = np.identity(3)
rotation_matrix[(0, 0)] = np.cos(yaw)
rotation_matrix[(0, 1)] = (- np.sin(yaw))
rotation_matrix[(1, 0)] = np.sin(yaw)
rotation_matrix[(1, 1)] = np.cos(yaw)
location_vector = np.array([[location.x], [location.y], [location.z]])
... | def rotate(yaw, location):
' '
rotation_matrix = np.identity(3)
rotation_matrix[(0, 0)] = np.cos(yaw)
rotation_matrix[(0, 1)] = (- np.sin(yaw))
rotation_matrix[(1, 0)] = np.sin(yaw)
rotation_matrix[(1, 1)] = np.cos(yaw)
location_vector = np.array([[location.x], [location.y], [location.z]])
... |
b351e0c3e2f0932c0d9e92e3ab46f629f0c847755e20a5bae5e69e3b2e4eb5fe | def size_term(land_use, destination_choice_coeffs):
'\n This method takes the land use data and multiplies various columns of the\n land use data by coefficients from the spec table in order\n to yield a size term (a linear combination of land use variables).\n\n Parameters\n ----------\n land_use... | This method takes the land use data and multiplies various columns of the
land use data by coefficients from the spec table in order
to yield a size term (a linear combination of land use variables).
Parameters
----------
land_use : DataFrame
A dataframe of land use attributes - the column names should match
t... | activitysim/abm/tables/size_terms.py | size_term | mattwigway/activitysim | 2 | python | def size_term(land_use, destination_choice_coeffs):
'\n This method takes the land use data and multiplies various columns of the\n land use data by coefficients from the spec table in order\n to yield a size term (a linear combination of land use variables).\n\n Parameters\n ----------\n land_use... | def size_term(land_use, destination_choice_coeffs):
'\n This method takes the land use data and multiplies various columns of the\n land use data by coefficients from the spec table in order\n to yield a size term (a linear combination of land use variables).\n\n Parameters\n ----------\n land_use... |
f79c3395c77515b1fe339a1298971b96f9062310cad990b8b9e6bfa72b5fab43 | def tour_destination_size_terms(land_use, size_terms, model_selector):
"\n\n Parameters\n ----------\n land_use - pipeline table\n size_terms - pipeline table\n model_selector - str\n\n Returns\n -------\n\n ::\n\n pandas.dataframe\n one column per model_selector segment with index... | Parameters
----------
land_use - pipeline table
size_terms - pipeline table
model_selector - str
Returns
-------
::
pandas.dataframe
one column per model_selector segment with index of land_use
e.g. for model_selector 'workplace', columns will be work_low, work_med, ...
and for model_selector ... | activitysim/abm/tables/size_terms.py | tour_destination_size_terms | mattwigway/activitysim | 2 | python | def tour_destination_size_terms(land_use, size_terms, model_selector):
"\n\n Parameters\n ----------\n land_use - pipeline table\n size_terms - pipeline table\n model_selector - str\n\n Returns\n -------\n\n ::\n\n pandas.dataframe\n one column per model_selector segment with index... | def tour_destination_size_terms(land_use, size_terms, model_selector):
"\n\n Parameters\n ----------\n land_use - pipeline table\n size_terms - pipeline table\n model_selector - str\n\n Returns\n -------\n\n ::\n\n pandas.dataframe\n one column per model_selector segment with index... |
d8f5698568976df605536b2f1935033bf690fc17ee4c067be0571933c449ded6 | def __init__(__self__, resource_name, opts=None, curve=None, key_opts=None, key_size=None, key_type=None, key_vault_id=None, name=None, tags=None, vault_uri=None, __name__=None, __opts__=None):
'\n Manages a Key Vault Key.\n \n :param str resource_name: The name of the resource.\n :param... | Manages a Key Vault Key.
:param str resource_name: The name of the resource.
:param kulado.ResourceOptions opts: Options for the resource.
:param kulado.Input[str] curve: Specifies the curve to use when creating an `EC` key. Possible values are `P-256`, `P-384`, `P-521`, and `SECP256K1`. This field will be required in... | sdk/python/kulado_azure/keyvault/key.py | __init__ | kulado/kulado-azure | 0 | python | def __init__(__self__, resource_name, opts=None, curve=None, key_opts=None, key_size=None, key_type=None, key_vault_id=None, name=None, tags=None, vault_uri=None, __name__=None, __opts__=None):
'\n Manages a Key Vault Key.\n \n :param str resource_name: The name of the resource.\n :param... | def __init__(__self__, resource_name, opts=None, curve=None, key_opts=None, key_size=None, key_type=None, key_vault_id=None, name=None, tags=None, vault_uri=None, __name__=None, __opts__=None):
'\n Manages a Key Vault Key.\n \n :param str resource_name: The name of the resource.\n :param... |
dc88598542b233430eba10a2d3802bef6e9b92a189ee25d600a8484d19bfaa2f | def apply_weights(values: Sequence[float], weights: Sequence[float]):
'\n Returns values[0] * weights[0] + values[1] * weights[1] + ... + values[n] * weights[n]\n '
return sum([(v[0] * v[1]) for v in zip(values, weights)]) | Returns values[0] * weights[0] + values[1] * weights[1] + ... + values[n] * weights[n] | src/math_utils.py | apply_weights | gcardozo123/cg_playground | 1 | python | def apply_weights(values: Sequence[float], weights: Sequence[float]):
'\n \n '
return sum([(v[0] * v[1]) for v in zip(values, weights)]) | def apply_weights(values: Sequence[float], weights: Sequence[float]):
'\n \n '
return sum([(v[0] * v[1]) for v in zip(values, weights)])<|docstring|>Returns values[0] * weights[0] + values[1] * weights[1] + ... + values[n] * weights[n]<|endoftext|> |
5fc30c832a576ee5b57c9a0fb957f97bab78ddde39118072ba56f941cae2dc4e | def angle_to(self, other):
'\n Returns the radian angles to other Vec2\n '
dot_prod = self.dot(other)
mag = self.magnitude()
other_mag = other.magnitude()
return acos((dot_prod / (mag * other_mag))) | Returns the radian angles to other Vec2 | src/math_utils.py | angle_to | gcardozo123/cg_playground | 1 | python | def angle_to(self, other):
'\n \n '
dot_prod = self.dot(other)
mag = self.magnitude()
other_mag = other.magnitude()
return acos((dot_prod / (mag * other_mag))) | def angle_to(self, other):
'\n \n '
dot_prod = self.dot(other)
mag = self.magnitude()
other_mag = other.magnitude()
return acos((dot_prod / (mag * other_mag)))<|docstring|>Returns the radian angles to other Vec2<|endoftext|> |
ba69a62875edda163efe215901dce5355574e5c85aff31c3c9344c2f997805f5 | @classmethod
def obtain_barycentric_weights(cls, p, v0, v1, v2):
'\n Returns the barycentric weights (reference: https://codeplea.com/triangular-interpolation)\n for a given point `p` inside a triangle (v0, v1, v2).\n '
denominator = (((v1.y - v2.y) * (v0.x - v2.x)) + ((v2.x - v1.x) * (v0.y... | Returns the barycentric weights (reference: https://codeplea.com/triangular-interpolation)
for a given point `p` inside a triangle (v0, v1, v2). | src/math_utils.py | obtain_barycentric_weights | gcardozo123/cg_playground | 1 | python | @classmethod
def obtain_barycentric_weights(cls, p, v0, v1, v2):
'\n Returns the barycentric weights (reference: https://codeplea.com/triangular-interpolation)\n for a given point `p` inside a triangle (v0, v1, v2).\n '
denominator = (((v1.y - v2.y) * (v0.x - v2.x)) + ((v2.x - v1.x) * (v0.y... | @classmethod
def obtain_barycentric_weights(cls, p, v0, v1, v2):
'\n Returns the barycentric weights (reference: https://codeplea.com/triangular-interpolation)\n for a given point `p` inside a triangle (v0, v1, v2).\n '
denominator = (((v1.y - v2.y) * (v0.x - v2.x)) + ((v2.x - v1.x) * (v0.y... |
5fc30c832a576ee5b57c9a0fb957f97bab78ddde39118072ba56f941cae2dc4e | def angle_to(self, other):
'\n Returns the radian angles to other Vec2\n '
dot_prod = self.dot(other)
mag = self.magnitude()
other_mag = other.magnitude()
return acos((dot_prod / (mag * other_mag))) | Returns the radian angles to other Vec2 | src/math_utils.py | angle_to | gcardozo123/cg_playground | 1 | python | def angle_to(self, other):
'\n \n '
dot_prod = self.dot(other)
mag = self.magnitude()
other_mag = other.magnitude()
return acos((dot_prod / (mag * other_mag))) | def angle_to(self, other):
'\n \n '
dot_prod = self.dot(other)
mag = self.magnitude()
other_mag = other.magnitude()
return acos((dot_prod / (mag * other_mag)))<|docstring|>Returns the radian angles to other Vec2<|endoftext|> |
d20763c908a214eab9ced2eb49f7b097e6acfa0adc76e15148f2b63c729509ea | @classmethod
def triangle_area(cls, p0, p1, p2):
'\n Returns twice the area - just to avoid division - of the oriented triangle (p0, p1, p2).\n The area is positive if the triangle is oriented counterclockwise.\n '
return (((p1.x - p0.x) * (p2.y - p0.y)) - ((p1.y - p0.y) * (p2.x - p0.x))) | Returns twice the area - just to avoid division - of the oriented triangle (p0, p1, p2).
The area is positive if the triangle is oriented counterclockwise. | src/math_utils.py | triangle_area | gcardozo123/cg_playground | 1 | python | @classmethod
def triangle_area(cls, p0, p1, p2):
'\n Returns twice the area - just to avoid division - of the oriented triangle (p0, p1, p2).\n The area is positive if the triangle is oriented counterclockwise.\n '
return (((p1.x - p0.x) * (p2.y - p0.y)) - ((p1.y - p0.y) * (p2.x - p0.x))) | @classmethod
def triangle_area(cls, p0, p1, p2):
'\n Returns twice the area - just to avoid division - of the oriented triangle (p0, p1, p2).\n The area is positive if the triangle is oriented counterclockwise.\n '
return (((p1.x - p0.x) * (p2.y - p0.y)) - ((p1.y - p0.y) * (p2.x - p0.x)))<|... |
a690e77913a64f0776cbfe9b6b71bfd8b8d9d40235841956466ba2bb88f8c1a8 | @classmethod
def is_counterclockwise(cls, p0, p1, p2):
'\n Returns true if the Vec2s p0, p1, p2 are in a counterclockwise order\n '
return (Vec3.triangle_area(p0, p1, p2) > 0) | Returns true if the Vec2s p0, p1, p2 are in a counterclockwise order | src/math_utils.py | is_counterclockwise | gcardozo123/cg_playground | 1 | python | @classmethod
def is_counterclockwise(cls, p0, p1, p2):
'\n \n '
return (Vec3.triangle_area(p0, p1, p2) > 0) | @classmethod
def is_counterclockwise(cls, p0, p1, p2):
'\n \n '
return (Vec3.triangle_area(p0, p1, p2) > 0)<|docstring|>Returns true if the Vec2s p0, p1, p2 are in a counterclockwise order<|endoftext|> |
baf920a1674cc2e3f190f180a5d4568fca804354230959e45c16d3ee5f1de82d | @classmethod
def _build_dependencies(cls, analyzer_names):
'Build a dependency list of analyzers.\n\n Args:\n analyzer_names (list): List of analyzer names.\n\n Returns:\n A list of sets of analyzer names. Each set represents\n one dependency group.\n\n Raises:\... | Build a dependency list of analyzers.
Args:
analyzer_names (list): List of analyzer names.
Returns:
A list of sets of analyzer names. Each set represents
one dependency group.
Raises:
KeyError: if class introduces circular dependencies. | timesketch/lib/analyzers/manager.py | _build_dependencies | tomchop/timesketch | 1,810 | python | @classmethod
def _build_dependencies(cls, analyzer_names):
'Build a dependency list of analyzers.\n\n Args:\n analyzer_names (list): List of analyzer names.\n\n Returns:\n A list of sets of analyzer names. Each set represents\n one dependency group.\n\n Raises:\... | @classmethod
def _build_dependencies(cls, analyzer_names):
'Build a dependency list of analyzers.\n\n Args:\n analyzer_names (list): List of analyzer names.\n\n Returns:\n A list of sets of analyzer names. Each set represents\n one dependency group.\n\n Raises:\... |
1c850c85424f349ef7955691fcd7de484986f3bdff5c293a382bad737d77ddcf | @classmethod
def clear_registration(cls):
'Clears all analyzer registration.'
cls._class_ordering = []
cls._class_registry = {} | Clears all analyzer registration. | timesketch/lib/analyzers/manager.py | clear_registration | tomchop/timesketch | 1,810 | python | @classmethod
def clear_registration(cls):
cls._class_ordering = []
cls._class_registry = {} | @classmethod
def clear_registration(cls):
cls._class_ordering = []
cls._class_registry = {}<|docstring|>Clears all analyzer registration.<|endoftext|> |
39632ef98512edcb1dc1303486552a1862523ebda5c31944755bd072a3ea629f | @classmethod
def get_analyzers(cls, analyzer_names=None):
'Retrieves the registered analyzers.\n\n Args:\n analyzer_names (list): List of analyzer names.\n\n Yields:\n tuple: containing:\n str: the uniquely identifying name of the analyzer\n type: th... | Retrieves the registered analyzers.
Args:
analyzer_names (list): List of analyzer names.
Yields:
tuple: containing:
str: the uniquely identifying name of the analyzer
type: the analyzer class. | timesketch/lib/analyzers/manager.py | get_analyzers | tomchop/timesketch | 1,810 | python | @classmethod
def get_analyzers(cls, analyzer_names=None):
'Retrieves the registered analyzers.\n\n Args:\n analyzer_names (list): List of analyzer names.\n\n Yields:\n tuple: containing:\n str: the uniquely identifying name of the analyzer\n type: th... | @classmethod
def get_analyzers(cls, analyzer_names=None):
'Retrieves the registered analyzers.\n\n Args:\n analyzer_names (list): List of analyzer names.\n\n Yields:\n tuple: containing:\n str: the uniquely identifying name of the analyzer\n type: th... |
862ae692c5106e3e05232a8939985c98df5dad946859bff200b2d7dcaa81fd33 | @classmethod
def get_analyzer(cls, analyzer_name):
'Retrieves a class object of a specific analyzer.\n\n Args:\n analyzer_name (str): name of the analyzer to retrieve.\n\n Returns:\n Analyzer class object.\n '
return cls._class_registry[analyzer_name.lower()] | Retrieves a class object of a specific analyzer.
Args:
analyzer_name (str): name of the analyzer to retrieve.
Returns:
Analyzer class object. | timesketch/lib/analyzers/manager.py | get_analyzer | tomchop/timesketch | 1,810 | python | @classmethod
def get_analyzer(cls, analyzer_name):
'Retrieves a class object of a specific analyzer.\n\n Args:\n analyzer_name (str): name of the analyzer to retrieve.\n\n Returns:\n Analyzer class object.\n '
return cls._class_registry[analyzer_name.lower()] | @classmethod
def get_analyzer(cls, analyzer_name):
'Retrieves a class object of a specific analyzer.\n\n Args:\n analyzer_name (str): name of the analyzer to retrieve.\n\n Returns:\n Analyzer class object.\n '
return cls._class_registry[analyzer_name.lower()]<|docstrin... |
47eb791fe2b72c00d0331d55dbb71052be1c632e4242fe8c1068d665d6ff471f | @classmethod
def register_analyzer(cls, analyzer_class):
'Registers an analyzer class.\n\n The analyzer classes are identified by their lower case name.\n\n Args:\n analyzer_class (type): the analyzer class to register.\n\n Raises:\n KeyError: if class is already set for t... | Registers an analyzer class.
The analyzer classes are identified by their lower case name.
Args:
analyzer_class (type): the analyzer class to register.
Raises:
KeyError: if class is already set for the corresponding name. | timesketch/lib/analyzers/manager.py | register_analyzer | tomchop/timesketch | 1,810 | python | @classmethod
def register_analyzer(cls, analyzer_class):
'Registers an analyzer class.\n\n The analyzer classes are identified by their lower case name.\n\n Args:\n analyzer_class (type): the analyzer class to register.\n\n Raises:\n KeyError: if class is already set for t... | @classmethod
def register_analyzer(cls, analyzer_class):
'Registers an analyzer class.\n\n The analyzer classes are identified by their lower case name.\n\n Args:\n analyzer_class (type): the analyzer class to register.\n\n Raises:\n KeyError: if class is already set for t... |
0870b5e1c3e3bf2d1338759dd87e6ead1efa383a771cad1ace87fef13c9cf866 | def __init__(self, **kwargs):
'\n Parameters\n -----------------------------------------------------------------------\n xL_0 Local plane x-value of the origin point\n xL Local plane x-value of the destination point\n yL_0 Local plane y-value of the origin p... | Parameters
-----------------------------------------------------------------------
xL_0 Local plane x-value of the origin point
xL Local plane x-value of the destination point
yL_0 Local plane y-value of the origin point
yL Local plane y-value of the destination point
zL_0 Local p... | local_polar.py | __init__ | stannielson/c3m_3d | 0 | python | def __init__(self, **kwargs):
'\n Parameters\n -----------------------------------------------------------------------\n xL_0 Local plane x-value of the origin point\n xL Local plane x-value of the destination point\n yL_0 Local plane y-value of the origin p... | def __init__(self, **kwargs):
'\n Parameters\n -----------------------------------------------------------------------\n xL_0 Local plane x-value of the origin point\n xL Local plane x-value of the destination point\n yL_0 Local plane y-value of the origin p... |
271d9e1c948a103d33769e5a4d78f0865253ab531170d304b2338382087ad3ef | def get_init_state(self, user_id):
'Get init state'
state = {'length': InitValues.LENGTH, 'width': InitValues.WIDTH, 'id': user_id}
message = dict()
for entities in self.get_entities():
for entity in entities:
if (entity.get_name() in message):
message[entity.get_name... | Get init state | game_board.py | get_init_state | Exocen/Bomberman | 2 | python | def get_init_state(self, user_id):
state = {'length': InitValues.LENGTH, 'width': InitValues.WIDTH, 'id': user_id}
message = dict()
for entities in self.get_entities():
for entity in entities:
if (entity.get_name() in message):
message[entity.get_name()].append(entit... | def get_init_state(self, user_id):
state = {'length': InitValues.LENGTH, 'width': InitValues.WIDTH, 'id': user_id}
message = dict()
for entities in self.get_entities():
for entity in entities:
if (entity.get_name() in message):
message[entity.get_name()].append(entit... |
23927ebcdf2e8f9b3f38883a3693500181a7b256b12ef5b052fa73bbbe923d8c | def create_message(self):
'Create message to notify users about map update\n\n Returns:\n dict : {{"type": "map"}{ updated : entities }} OR None\n '
message = dict()
new_game_map = self.create_map()
def _update_message(entity):
if (entity.get_name() in message):
... | Create message to notify users about map update
Returns:
dict : {{"type": "map"}{ updated : entities }} OR None | game_board.py | create_message | Exocen/Bomberman | 2 | python | def create_message(self):
'Create message to notify users about map update\n\n Returns:\n dict : {{"type": "map"}{ updated : entities }} OR None\n '
message = dict()
new_game_map = self.create_map()
def _update_message(entity):
if (entity.get_name() in message):
... | def create_message(self):
'Create message to notify users about map update\n\n Returns:\n dict : {{"type": "map"}{ updated : entities }} OR None\n '
message = dict()
new_game_map = self.create_map()
def _update_message(entity):
if (entity.get_name() in message):
... |
3e95d4ac900fa47f1b938770fc399c7b8733c7939607a63138cc86b14a148153 | async def notify(self, message):
'\n Notify all users about game updates\n '
try:
(await asyncio.gather(*[user.ws.send(message) for user in self.users]))
except websockets.exceptions.ConnectionClosed:
logging.debug('Connection lost')
except Exception:
logging.except... | Notify all users about game updates | game_board.py | notify | Exocen/Bomberman | 2 | python | async def notify(self, message):
'\n \n '
try:
(await asyncio.gather(*[user.ws.send(message) for user in self.users]))
except websockets.exceptions.ConnectionClosed:
logging.debug('Connection lost')
except Exception:
logging.exception('Connection lost for unexpected... | async def notify(self, message):
'\n \n '
try:
(await asyncio.gather(*[user.ws.send(message) for user in self.users]))
except websockets.exceptions.ConnectionClosed:
logging.debug('Connection lost')
except Exception:
logging.exception('Connection lost for unexpected... |
65d5533a6041a1555b9ea534993d08ce93201173bc660bfa02c62adaf8b25a19 | def is_position_free(self, position):
"Check if position doesn't contain a blockable entity"
for entities in self.get_entities():
if (entities and next(iter(entities)).BLOCKABLE):
for entity in entities:
if (entity.get_position() == position):
return False... | Check if position doesn't contain a blockable entity | game_board.py | is_position_free | Exocen/Bomberman | 2 | python | def is_position_free(self, position):
for entities in self.get_entities():
if (entities and next(iter(entities)).BLOCKABLE):
for entity in entities:
if (entity.get_position() == position):
return False
return True | def is_position_free(self, position):
for entities in self.get_entities():
if (entities and next(iter(entities)).BLOCKABLE):
for entity in entities:
if (entity.get_position() == position):
return False
return True<|docstring|>Check if position doesn't... |
b3f799d80349a3b50650e7a9841a0271018cb143cf96ab4c7dd100940e4ccfcc | def random_spawn(self, nb=1):
'Return nb available positions\n\n Args:\n nb (int, optional): nb positions. Defaults to 1.\n\n Returns:\n [Position]: positions list\n '
x_choices = range(InitValues.LENGTH)
y_choices = range(InitValues.WIDTH)
pos_choices = set()
... | Return nb available positions
Args:
nb (int, optional): nb positions. Defaults to 1.
Returns:
[Position]: positions list | game_board.py | random_spawn | Exocen/Bomberman | 2 | python | def random_spawn(self, nb=1):
'Return nb available positions\n\n Args:\n nb (int, optional): nb positions. Defaults to 1.\n\n Returns:\n [Position]: positions list\n '
x_choices = range(InitValues.LENGTH)
y_choices = range(InitValues.WIDTH)
pos_choices = set()
... | def random_spawn(self, nb=1):
'Return nb available positions\n\n Args:\n nb (int, optional): nb positions. Defaults to 1.\n\n Returns:\n [Position]: positions list\n '
x_choices = range(InitValues.LENGTH)
y_choices = range(InitValues.WIDTH)
pos_choices = set()
... |
4805944dd867e42c3e50dc16b9ed711b36059876894087aca6ec9ebf8d8371c1 | async def game_loop(self):
'\n Update and clean all entities and notify users\n '
while True:
(await asyncio.sleep(InitValues.TICKS))
if self.users:
self.mailbox.drop_key(EntitiesNames.BOARD)
message_queue = self.mailbox.get(EntitiesNames.BOARD)
... | Update and clean all entities and notify users | game_board.py | game_loop | Exocen/Bomberman | 2 | python | async def game_loop(self):
'\n \n '
while True:
(await asyncio.sleep(InitValues.TICKS))
if self.users:
self.mailbox.drop_key(EntitiesNames.BOARD)
message_queue = self.mailbox.get(EntitiesNames.BOARD)
if message_queue:
tasks = []
... | async def game_loop(self):
'\n \n '
while True:
(await asyncio.sleep(InitValues.TICKS))
if self.users:
self.mailbox.drop_key(EntitiesNames.BOARD)
message_queue = self.mailbox.get(EntitiesNames.BOARD)
if message_queue:
tasks = []
... |
8ae1316097767ebc9cf746808d54d06c86e452db3aba4c1998aab45ea0249114 | @staticmethod
async def clean_entity_list(entity_set, lock):
'Remove dead entities\n\n Args:\n entity_set (set): entity list to clean\n lock (async lock): entity lock\n '
async with lock:
entity_set -= {e for e in entity_set if e.is_dead()} | Remove dead entities
Args:
entity_set (set): entity list to clean
lock (async lock): entity lock | game_board.py | clean_entity_list | Exocen/Bomberman | 2 | python | @staticmethod
async def clean_entity_list(entity_set, lock):
'Remove dead entities\n\n Args:\n entity_set (set): entity list to clean\n lock (async lock): entity lock\n '
async with lock:
entity_set -= {e for e in entity_set if e.is_dead()} | @staticmethod
async def clean_entity_list(entity_set, lock):
'Remove dead entities\n\n Args:\n entity_set (set): entity list to clean\n lock (async lock): entity lock\n '
async with lock:
entity_set -= {e for e in entity_set if e.is_dead()}<|docstring|>Remove dead ent... |
ab2bb79c243f7f82afe36b861190cc2258a504abe620d9a8005a65aa15e2fdb4 | def _identity(self):
'Identity element.'
raise NotImplemented('Not yet implemented') | Identity element. | sympy/microlie/se3.py | _identity | evbernardes/sympy | 0 | python | def _identity(self):
raise NotImplemented('Not yet implemented') | def _identity(self):
raise NotImplemented('Not yet implemented')<|docstring|>Identity element.<|endoftext|> |
df0a41e109ec080056945bba32765224d01311cdef058f151b182fdcbed19458 | def _inverse(self):
' .'
return SE3(((- self.rot.T) * self.pos), self.rot.T) | . | sympy/microlie/se3.py | _inverse | evbernardes/sympy | 0 | python | def _inverse(self):
' '
return SE3(((- selfrotT) * selfpos), selfrotT) | def _inverse(self):
' '
return SE3(((- selfrotT) * selfpos), selfrotT)<|docstring|>.<|endoftext|> |
6123ef61b4eb4aa00c01478878855d6355d330db6f59c16500819151d1aa975f | def _compose(self, Elem):
'With another Group element.'
if (not isinstance(Elem, SE3)):
raise NotImplemented
R1 = self.rot
R2 = Elem.rot
p1 = self.pos
p2 = Elem.pos
return SE3((p1 + (R1 * p2)), (R1 * R2)) | With another Group element. | sympy/microlie/se3.py | _compose | evbernardes/sympy | 0 | python | def _compose(self, Elem):
if (not isinstance(Elem, SE3)):
raise NotImplemented
R1 = self.rot
R2 = Elem.rot
p1 = self.pos
p2 = Elem.pos
return SE3((p1 + (R1 * p2)), (R1 * R2)) | def _compose(self, Elem):
if (not isinstance(Elem, SE3)):
raise NotImplemented
R1 = self.rot
R2 = Elem.rot
p1 = self.pos
p2 = Elem.pos
return SE3((p1 + (R1 * p2)), (R1 * R2))<|docstring|>With another Group element.<|endoftext|> |
d80cc29b9665022e4d71059d15b9aecab3532031b494a60db19e64677934e994 | def _act(self, v):
'Act on a vector.'
if (v.shape == (1, 3)):
return (self.pos + (self.rot * v.T))
elif (v.shape == (3, 1)):
return (self.pos + (self.rot * v))
else:
raise ValueError('Vector must have length == 3') | Act on a vector. | sympy/microlie/se3.py | _act | evbernardes/sympy | 0 | python | def _act(self, v):
if (v.shape == (1, 3)):
return (self.pos + (self.rot * v.T))
elif (v.shape == (3, 1)):
return (self.pos + (self.rot * v))
else:
raise ValueError('Vector must have length == 3') | def _act(self, v):
if (v.shape == (1, 3)):
return (self.pos + (self.rot * v.T))
elif (v.shape == (3, 1)):
return (self.pos + (self.rot * v))
else:
raise ValueError('Vector must have length == 3')<|docstring|>Act on a vector.<|endoftext|> |
1b6a690215b91d79e2fce8e0f90075b316bb9a04ee1a639a15ec5ac5b91cffac | def _log(self):
'Lift to tangent space.'
ang = vee(ln(self.rot))
lin = (Vinv(ang) * self.pos)
return TgSE3(lin, ang) | Lift to tangent space. | sympy/microlie/se3.py | _log | evbernardes/sympy | 0 | python | def _log(self):
ang = vee(ln(self.rot))
lin = (Vinv(ang) * self.pos)
return TgSE3(lin, ang) | def _log(self):
ang = vee(ln(self.rot))
lin = (Vinv(ang) * self.pos)
return TgSE3(lin, ang)<|docstring|>Lift to tangent space.<|endoftext|> |
752aeb21b3dca81a9a55d3246f70a3bb1247b81bea8a6a3fd1f4d93bc7ee9eb2 | def _hat(self):
'Lie Algebra isomorphism.'
if self.is_symbolic:
return BlockMatrix([[self.ang.hat(), self.lin], [ZeroMatrix(1, 3), ZeroMatrix(1, 1)]])
else:
return Matrix([[self.ang.hat(), self.lin], [0, 0, 0, 0]]) | Lie Algebra isomorphism. | sympy/microlie/se3.py | _hat | evbernardes/sympy | 0 | python | def _hat(self):
if self.is_symbolic:
return BlockMatrix([[self.ang.hat(), self.lin], [ZeroMatrix(1, 3), ZeroMatrix(1, 1)]])
else:
return Matrix([[self.ang.hat(), self.lin], [0, 0, 0, 0]]) | def _hat(self):
if self.is_symbolic:
return BlockMatrix([[self.ang.hat(), self.lin], [ZeroMatrix(1, 3), ZeroMatrix(1, 1)]])
else:
return Matrix([[self.ang.hat(), self.lin], [0, 0, 0, 0]])<|docstring|>Lie Algebra isomorphism.<|endoftext|> |
eac315601c6d43bf291f8a95c61df13ce0f426aaa4dbed8ae5859c2dd39c6d1b | def _exp(self):
'Retract to group element.'
theta = self.ang
pos = (V(theta) * self.lin)
rot = exp(theta.hat())
return SE3(pos, rot) | Retract to group element. | sympy/microlie/se3.py | _exp | evbernardes/sympy | 0 | python | def _exp(self):
theta = self.ang
pos = (V(theta) * self.lin)
rot = exp(theta.hat())
return SE3(pos, rot) | def _exp(self):
theta = self.ang
pos = (V(theta) * self.lin)
rot = exp(theta.hat())
return SE3(pos, rot)<|docstring|>Retract to group element.<|endoftext|> |
3d7f74b2e025059bf531dd37950c7f1d1db5db9ca70a05edf693284cc67cce9d | def test_init():
'Test Initialization method.'
arps = AdjustingRPSAgent()
assert (arps.weight == 1)
assert (arps.original_strategy == arps.strategy)
assert (arps.counts == [(1 / 3), (1 / 3), (1 / 3)])
arps_int = AdjustingRPSAgent(weight=6)
assert (arps_int.weight == 6)
assert (arps_int.c... | Test Initialization method. | tests/agent_tests/adjusting_rps_agent_test.py | test_init | aturfah/cmplxsys530-final | 4 | python | def test_init():
arps = AdjustingRPSAgent()
assert (arps.weight == 1)
assert (arps.original_strategy == arps.strategy)
assert (arps.counts == [(1 / 3), (1 / 3), (1 / 3)])
arps_int = AdjustingRPSAgent(weight=6)
assert (arps_int.weight == 6)
assert (arps_int.counts == [2, 2, 2])
arps_... | def test_init():
arps = AdjustingRPSAgent()
assert (arps.weight == 1)
assert (arps.original_strategy == arps.strategy)
assert (arps.counts == [(1 / 3), (1 / 3), (1 / 3)])
arps_int = AdjustingRPSAgent(weight=6)
assert (arps_int.weight == 6)
assert (arps_int.counts == [2, 2, 2])
arps_... |
ada993843cb136dbda7681b6069f41e2df33a1b59b51c1bef51d52525482a6bb | def test_update_info():
'Test that update_info works properly.'
arps = AdjustingRPSAgent()
assert (arps.strategy == [(1 / 3), (1 / 3), (1 / 3)])
arps.update_info(opp_move=0)
assert (arps.counts == [(1 / 3), (4 / 3), (1 / 3)])
assert (arps.original_strategy == [(1 / 3), (1 / 3), (1 / 3)])
ass... | Test that update_info works properly. | tests/agent_tests/adjusting_rps_agent_test.py | test_update_info | aturfah/cmplxsys530-final | 4 | python | def test_update_info():
arps = AdjustingRPSAgent()
assert (arps.strategy == [(1 / 3), (1 / 3), (1 / 3)])
arps.update_info(opp_move=0)
assert (arps.counts == [(1 / 3), (4 / 3), (1 / 3)])
assert (arps.original_strategy == [(1 / 3), (1 / 3), (1 / 3)])
assert ([round(prob, 4) for prob in arps.s... | def test_update_info():
arps = AdjustingRPSAgent()
assert (arps.strategy == [(1 / 3), (1 / 3), (1 / 3)])
arps.update_info(opp_move=0)
assert (arps.counts == [(1 / 3), (4 / 3), (1 / 3)])
assert (arps.original_strategy == [(1 / 3), (1 / 3), (1 / 3)])
assert ([round(prob, 4) for prob in arps.s... |
4bcdbc8e7ca4ef6e2b28a5c59b543cc62f881266e1141c26955775405afd5c76 | def test_reset_state():
'Test that reset_state resets state.'
arps = AdjustingRPSAgent()
arps.update_info(opp_move=0)
arps.reset_state()
assert (arps.strategy == [(1 / 3), (1 / 3), (1 / 3)])
assert (arps.counts == [(1 / 3), (1 / 3), (1 / 3)])
arps_weight = AdjustingRPSAgent(weight=9)
arp... | Test that reset_state resets state. | tests/agent_tests/adjusting_rps_agent_test.py | test_reset_state | aturfah/cmplxsys530-final | 4 | python | def test_reset_state():
arps = AdjustingRPSAgent()
arps.update_info(opp_move=0)
arps.reset_state()
assert (arps.strategy == [(1 / 3), (1 / 3), (1 / 3)])
assert (arps.counts == [(1 / 3), (1 / 3), (1 / 3)])
arps_weight = AdjustingRPSAgent(weight=9)
arps_weight.update_info(opp_move=0)
... | def test_reset_state():
arps = AdjustingRPSAgent()
arps.update_info(opp_move=0)
arps.reset_state()
assert (arps.strategy == [(1 / 3), (1 / 3), (1 / 3)])
assert (arps.counts == [(1 / 3), (1 / 3), (1 / 3)])
arps_weight = AdjustingRPSAgent(weight=9)
arps_weight.update_info(opp_move=0)
... |
29610dce9921ba1ed72443e4bca880273cbb4ef5dcfb808fbe962015679d4557 | @bp.route('/send', methods=['POST'])
def send():
'Send message to telegram bot.\n\n :returns: bot response\n '
data = request.get_json()
try:
message = data['message']
chat = data['chat']
except KeyError:
abort(404)
(response, status) = telegram_bot.send(chat, message)
... | Send message to telegram bot.
:returns: bot response | app/telegram.py | send | plyq/plyq-binance-telegram-connector | 0 | python | @bp.route('/send', methods=['POST'])
def send():
'Send message to telegram bot.\n\n :returns: bot response\n '
data = request.get_json()
try:
message = data['message']
chat = data['chat']
except KeyError:
abort(404)
(response, status) = telegram_bot.send(chat, message)
... | @bp.route('/send', methods=['POST'])
def send():
'Send message to telegram bot.\n\n :returns: bot response\n '
data = request.get_json()
try:
message = data['message']
chat = data['chat']
except KeyError:
abort(404)
(response, status) = telegram_bot.send(chat, message)
... |
890568673183e7c244ac7d6f959efe1e488a1ed426077b97670b1a8a6dcac96b | @bp.route('/check', methods=['GET'])
def check():
'Get telegram bot info.\n\n :returns: bot response\n '
(response, status) = telegram_bot.check()
return (response, status) | Get telegram bot info.
:returns: bot response | app/telegram.py | check | plyq/plyq-binance-telegram-connector | 0 | python | @bp.route('/check', methods=['GET'])
def check():
'Get telegram bot info.\n\n :returns: bot response\n '
(response, status) = telegram_bot.check()
return (response, status) | @bp.route('/check', methods=['GET'])
def check():
'Get telegram bot info.\n\n :returns: bot response\n '
(response, status) = telegram_bot.check()
return (response, status)<|docstring|>Get telegram bot info.
:returns: bot response<|endoftext|> |
144a2069cebab3f25106121423a9d275d4737eadff0c02a4f4c15a8a1d42b953 | def is_process_running(pid):
'\n Check if the provided pid is running\n '
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True | Check if the provided pid is running | src/catcher/utils.py | is_process_running | gavin-anders/callback-catcher | 2 | python | def is_process_running(pid):
'\n \n '
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True | def is_process_running(pid):
'\n \n '
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True<|docstring|>Check if the provided pid is running<|endoftext|> |
ef947fe51e03e935db8ac4ec1e04f4332f24f031848f4c87d8f4685ad0da2c05 | @API.public
def factory(f: Optional[T]=None, *, singleton: Optional[bool]=None, scope: Optional[Scope]=Scope.sentinel(), wiring: Optional[Wiring]=Wiring()) -> Union[(Callable[([T], T)], T)]:
"\n .. deprecated:: 1.4\n Use :py:func:`.lazy` instead for external classes or :py:func:`.injectable` with\n ... | .. deprecated:: 1.4
Use :py:func:`.lazy` instead for external classes or :py:func:`.injectable` with
the :code:`factory_method` argument for classes you own.
.. admonition:: MIGRATION
For classes you own you should use :py:func:`.injectable`:
.. doctest:: factory_migration
>>> from antidote ... | src/antidote/factory.py | factory | Finistere/dependency_manager | 0 | python | @API.public
def factory(f: Optional[T]=None, *, singleton: Optional[bool]=None, scope: Optional[Scope]=Scope.sentinel(), wiring: Optional[Wiring]=Wiring()) -> Union[(Callable[([T], T)], T)]:
"\n .. deprecated:: 1.4\n Use :py:func:`.lazy` instead for external classes or :py:func:`.injectable` with\n ... | @API.public
def factory(f: Optional[T]=None, *, singleton: Optional[bool]=None, scope: Optional[Scope]=Scope.sentinel(), wiring: Optional[Wiring]=Wiring()) -> Union[(Callable[([T], T)], T)]:
"\n .. deprecated:: 1.4\n Use :py:func:`.lazy` instead for external classes or :py:func:`.injectable` with\n ... |
ce7cdea14653a714bcd0c8a053a565da5c37586d96848101d23db8ad32dd650c | def __init__(self, *, wiring: Optional[Wiring]=Wiring(), singleton: Optional[bool]=None, scope: Optional[Scope]=Scope.sentinel(), parameters: Optional[Iterable[str]]=None):
'\n\n Args:\n wiring: Wiring to be applied on the factory. By default only\n :code:`__init__()` an... | Args:
wiring: Wiring to be applied on the factory. By default only
:code:`__init__()` and :code:`__call__()` will be wired. To deactivate
any wiring at all use :py:obj:`None`.
singleton: Whether the returned dependency is a singleton or not. If yes,
the factory will be called at most on... | src/antidote/factory.py | __init__ | Finistere/dependency_manager | 0 | python | def __init__(self, *, wiring: Optional[Wiring]=Wiring(), singleton: Optional[bool]=None, scope: Optional[Scope]=Scope.sentinel(), parameters: Optional[Iterable[str]]=None):
'\n\n Args:\n wiring: Wiring to be applied on the factory. By default only\n :code:`__init__()` an... | def __init__(self, *, wiring: Optional[Wiring]=Wiring(), singleton: Optional[bool]=None, scope: Optional[Scope]=Scope.sentinel(), parameters: Optional[Iterable[str]]=None):
'\n\n Args:\n wiring: Wiring to be applied on the factory. By default only\n :code:`__init__()` an... |
b0eeb35272bacb8b942c66c801656f1b2042c172973ba2eecfabb2af52a31408 | def copy(self, *, wiring: Union[(Optional[Wiring], Copy)]=Copy.IDENTICAL, singleton: Union[(bool, Copy)]=Copy.IDENTICAL, scope: Union[(Optional[Scope], Copy)]=Copy.IDENTICAL, parameters: Union[(Optional[Iterable[str]], Copy)]=Copy.IDENTICAL) -> Factory.Conf:
'\n .. deprecated:: 1.1\n\n Copies ... | .. deprecated:: 1.1
Copies current configuration and overrides only specified arguments.
Accepts the same arguments as :code:`__init__` | src/antidote/factory.py | copy | Finistere/dependency_manager | 0 | python | def copy(self, *, wiring: Union[(Optional[Wiring], Copy)]=Copy.IDENTICAL, singleton: Union[(bool, Copy)]=Copy.IDENTICAL, scope: Union[(Optional[Scope], Copy)]=Copy.IDENTICAL, parameters: Union[(Optional[Iterable[str]], Copy)]=Copy.IDENTICAL) -> Factory.Conf:
'\n .. deprecated:: 1.1\n\n Copies ... | def copy(self, *, wiring: Union[(Optional[Wiring], Copy)]=Copy.IDENTICAL, singleton: Union[(bool, Copy)]=Copy.IDENTICAL, scope: Union[(Optional[Scope], Copy)]=Copy.IDENTICAL, parameters: Union[(Optional[Iterable[str]], Copy)]=Copy.IDENTICAL) -> Factory.Conf:
'\n .. deprecated:: 1.1\n\n Copies ... |
10c530f7d5e98d6810c6e958534ee5ba67c189e384232271e484e1898d6dc740 | def lbeta(x, name='lbeta'):
'Computes `ln(|Beta(x)|)`, reducing along the last dimension.\n\n Given one-dimensional `z = [z_0,...,z_{K-1}]`, we define\n\n ```Beta(z) = \\prod_j Gamma(z_j) / Gamma(\\sum_j z_j)```\n\n And for `n + 1` dimensional `x` with shape `[N1, ..., Nn, K]`, we define\n `lbeta(x)[i1, ..., in... | Computes `ln(|Beta(x)|)`, reducing along the last dimension.
Given one-dimensional `z = [z_0,...,z_{K-1}]`, we define
```Beta(z) = \prod_j Gamma(z_j) / Gamma(\sum_j z_j)```
And for `n + 1` dimensional `x` with shape `[N1, ..., Nn, K]`, we define
`lbeta(x)[i1, ..., in] = Log(|Beta(x[i1, ..., in, :])|)`. In other wor... | tensorflow/python/ops/special_math_ops.py | lbeta | ssameerr/tensorflow | 2 | python | def lbeta(x, name='lbeta'):
'Computes `ln(|Beta(x)|)`, reducing along the last dimension.\n\n Given one-dimensional `z = [z_0,...,z_{K-1}]`, we define\n\n ```Beta(z) = \\prod_j Gamma(z_j) / Gamma(\\sum_j z_j)```\n\n And for `n + 1` dimensional `x` with shape `[N1, ..., Nn, K]`, we define\n `lbeta(x)[i1, ..., in... | def lbeta(x, name='lbeta'):
'Computes `ln(|Beta(x)|)`, reducing along the last dimension.\n\n Given one-dimensional `z = [z_0,...,z_{K-1}]`, we define\n\n ```Beta(z) = \\prod_j Gamma(z_j) / Gamma(\\sum_j z_j)```\n\n And for `n + 1` dimensional `x` with shape `[N1, ..., Nn, K]`, we define\n `lbeta(x)[i1, ..., in... |
18169c53cfba38bb838dbc7f3135516ec1898acde056685f05f47f228dabb2d9 | def einsum(axes, *inputs):
'\n A generalized contraction between tensors of arbitrary dimension.\n\n Like numpy.einsum.\n '
match = re.match('([a-z,]+)->([a-z]+)', axes)
assert match, ('Indices have incorrect format: %s' % axes)
inputs = list(inputs)
idx_in = match.group(1).split(',')
idx_out... | A generalized contraction between tensors of arbitrary dimension.
Like numpy.einsum. | tensorflow/python/ops/special_math_ops.py | einsum | ssameerr/tensorflow | 2 | python | def einsum(axes, *inputs):
'\n A generalized contraction between tensors of arbitrary dimension.\n\n Like numpy.einsum.\n '
match = re.match('([a-z,]+)->([a-z]+)', axes)
assert match, ('Indices have incorrect format: %s' % axes)
inputs = list(inputs)
idx_in = match.group(1).split(',')
idx_out... | def einsum(axes, *inputs):
'\n A generalized contraction between tensors of arbitrary dimension.\n\n Like numpy.einsum.\n '
match = re.match('([a-z,]+)->([a-z]+)', axes)
assert match, ('Indices have incorrect format: %s' % axes)
inputs = list(inputs)
idx_in = match.group(1).split(',')
idx_out... |
d89a8c858d196172029e6fdb089c8760aeddd2988e674ea7eba0080d1246231e | def timestamp2date(timestamp):
'\n 时间戳转换为日期\n Parameters\n ----------\n timestamp: int or str\n 用户账号\n\n Returns\n -------\n datetime:\n 转换好的日期:年-月-日 时:分:秒\n '
time_array = time.localtime(int(timestamp))
datetime = time.strftime('%Y-%m-%d %H:%M:%S', time_array)
retu... | 时间戳转换为日期
Parameters
----------
timestamp: int or str
用户账号
Returns
-------
datetime:
转换好的日期:年-月-日 时:分:秒 | wechatarticles/tools.py | timestamp2date | pengziliu/wechat_articles_spider | 1 | python | def timestamp2date(timestamp):
'\n 时间戳转换为日期\n Parameters\n ----------\n timestamp: int or str\n 用户账号\n\n Returns\n -------\n datetime:\n 转换好的日期:年-月-日 时:分:秒\n '
time_array = time.localtime(int(timestamp))
datetime = time.strftime('%Y-%m-%d %H:%M:%S', time_array)
retu... | def timestamp2date(timestamp):
'\n 时间戳转换为日期\n Parameters\n ----------\n timestamp: int or str\n 用户账号\n\n Returns\n -------\n datetime:\n 转换好的日期:年-月-日 时:分:秒\n '
time_array = time.localtime(int(timestamp))
datetime = time.strftime('%Y-%m-%d %H:%M:%S', time_array)
retu... |
ba02547884dce9cee98e1282a2c025f5d3566564e34ed8a8f0d03e9c0baab020 | def save_mongo(data, host=None, port=None, name=None, password='', dbname=None, collname=None):
'\n 存储数据到mongo\n Parameters\n ----------\n data: list\n 需要插入的数据\n host: str\n 主机名(默认为本机数据库)\n port: int\n mongo所在主机开放的端口,默认为27017\n username: str\n 用户名\n password: str\... | 存储数据到mongo
Parameters
----------
data: list
需要插入的数据
host: str
主机名(默认为本机数据库)
port: int
mongo所在主机开放的端口,默认为27017
username: str
用户名
password: str
用户密码
dbname: str
远程连接的数据库名
collname: str
需要插入的集合名(collection)
Returns
-------
None | wechatarticles/tools.py | save_mongo | pengziliu/wechat_articles_spider | 1 | python | def save_mongo(data, host=None, port=None, name=None, password=, dbname=None, collname=None):
'\n 存储数据到mongo\n Parameters\n ----------\n data: list\n 需要插入的数据\n host: str\n 主机名(默认为本机数据库)\n port: int\n mongo所在主机开放的端口,默认为27017\n username: str\n 用户名\n password: str\n ... | def save_mongo(data, host=None, port=None, name=None, password=, dbname=None, collname=None):
'\n 存储数据到mongo\n Parameters\n ----------\n data: list\n 需要插入的数据\n host: str\n 主机名(默认为本机数据库)\n port: int\n mongo所在主机开放的端口,默认为27017\n username: str\n 用户名\n password: str\n ... |
9fa0dc134cc1b10afc8de93e63f9823ea98404dd1a813db592f5342ca75ed322 | def save_json(fname, data):
'\n 保存数据为txt格式\n Parameters\n ----------\n fname: str\n 保存为txt文件名\n data: list\n 爬取到的数据\n Returns\n -------\n None\n '
assert isinstance(fname, str)
if ('.json' not in fname):
raise IOError('fname must be json', fname)
with ope... | 保存数据为txt格式
Parameters
----------
fname: str
保存为txt文件名
data: list
爬取到的数据
Returns
-------
None | wechatarticles/tools.py | save_json | pengziliu/wechat_articles_spider | 1 | python | def save_json(fname, data):
'\n 保存数据为txt格式\n Parameters\n ----------\n fname: str\n 保存为txt文件名\n data: list\n 爬取到的数据\n Returns\n -------\n None\n '
assert isinstance(fname, str)
if ('.json' not in fname):
raise IOError('fname must be json', fname)
with ope... | def save_json(fname, data):
'\n 保存数据为txt格式\n Parameters\n ----------\n fname: str\n 保存为txt文件名\n data: list\n 爬取到的数据\n Returns\n -------\n None\n '
assert isinstance(fname, str)
if ('.json' not in fname):
raise IOError('fname must be json', fname)
with ope... |
5edbcf12464cc48461a45909b8a2084678b2151007a92a06457bd5b1595e888a | def process(self, text: str, verbose=False) -> str:
'\n String-to-string coreference resolution through textual replacements.\n '
doc = self.nlp(text)
if (not doc._.has_coref):
return text
processed_text = []
if verbose:
print('Coreferencing replacements:')
for toke... | String-to-string coreference resolution through textual replacements. | src/extractor_service/coref.py | process | ansonmiu0214/aspect-based-sentiment-analysis | 4 | python | def process(self, text: str, verbose=False) -> str:
'\n \n '
doc = self.nlp(text)
if (not doc._.has_coref):
return text
processed_text = []
if verbose:
print('Coreferencing replacements:')
for token in doc:
if token._.in_coref:
main_subj_token = ... | def process(self, text: str, verbose=False) -> str:
'\n \n '
doc = self.nlp(text)
if (not doc._.has_coref):
return text
processed_text = []
if verbose:
print('Coreferencing replacements:')
for token in doc:
if token._.in_coref:
main_subj_token = ... |
c3d64cd5947152e7285956425cdddb42c2ff655473e88c7f5b0c24f3300582a1 | def get_globals():
'Context variables that are available for every template rendered by\n OSFWebRenderer.\n '
user = _get_current_user()
set_status_message(user)
user_institutions = ([{'id': inst._id, 'name': inst.name, 'logo_path': inst.logo_path_rounded_corners} for inst in user.affiliated_insti... | Context variables that are available for every template rendered by
OSFWebRenderer. | website/routes.py | get_globals | felliott/osf.io | 628 | python | def get_globals():
'Context variables that are available for every template rendered by\n OSFWebRenderer.\n '
user = _get_current_user()
set_status_message(user)
user_institutions = ([{'id': inst._id, 'name': inst.name, 'logo_path': inst.logo_path_rounded_corners} for inst in user.affiliated_insti... | def get_globals():
'Context variables that are available for every template rendered by\n OSFWebRenderer.\n '
user = _get_current_user()
set_status_message(user)
user_institutions = ([{'id': inst._id, 'name': inst.name, 'logo_path': inst.logo_path_rounded_corners} for inst in user.affiliated_insti... |
c49c64b3fe19377588c9171e31e6c99e22cf9114881e20638faf685ead89b5fd | def robots():
'Serves the robots.txt file.'
if os.path.exists(os.path.join(settings.STATIC_FOLDER, 'robots.local.txt')):
robots_file = 'robots.local.txt'
else:
robots_file = 'robots.txt'
return send_from_directory(settings.STATIC_FOLDER, robots_file, mimetype='html') | Serves the robots.txt file. | website/routes.py | robots | felliott/osf.io | 628 | python | def robots():
if os.path.exists(os.path.join(settings.STATIC_FOLDER, 'robots.local.txt')):
robots_file = 'robots.local.txt'
else:
robots_file = 'robots.txt'
return send_from_directory(settings.STATIC_FOLDER, robots_file, mimetype='html') | def robots():
if os.path.exists(os.path.join(settings.STATIC_FOLDER, 'robots.local.txt')):
robots_file = 'robots.local.txt'
else:
robots_file = 'robots.txt'
return send_from_directory(settings.STATIC_FOLDER, robots_file, mimetype='html')<|docstring|>Serves the robots.txt file.<|endoftex... |
cd230d9ba6c8418165658e847a3dc3642c9995e34ecc8347fa9846295f092123 | def sitemap_file(path):
'Serves the sitemap/* files.'
if path.endswith('.xml.gz'):
mime = 'application/x-gzip'
elif path.endswith('.xml'):
mime = 'text/xml'
else:
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
return send_from_directory((settings.STATIC_FOLDER + '/sitemaps/'... | Serves the sitemap/* files. | website/routes.py | sitemap_file | felliott/osf.io | 628 | python | def sitemap_file(path):
if path.endswith('.xml.gz'):
mime = 'application/x-gzip'
elif path.endswith('.xml'):
mime = 'text/xml'
else:
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
return send_from_directory((settings.STATIC_FOLDER + '/sitemaps/'), path, mimetype=mime) | def sitemap_file(path):
if path.endswith('.xml.gz'):
mime = 'application/x-gzip'
elif path.endswith('.xml'):
mime = 'text/xml'
else:
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
return send_from_directory((settings.STATIC_FOLDER + '/sitemaps/'), path, mimetype=mime)<|docs... |
3047a3abf48ca8e4cab749bdad5191703fba9652159429ada71af24a9a931b25 | def ember_app(path=None):
'Serve the contents of the ember application'
ember_app_folder = None
fp = (path or 'index.html')
ember_app = None
for k in EXTERNAL_EMBER_APPS.keys():
if request.path.strip('/').startswith(k):
ember_app = EXTERNAL_EMBER_APPS[k]
break
if ... | Serve the contents of the ember application | website/routes.py | ember_app | felliott/osf.io | 628 | python | def ember_app(path=None):
ember_app_folder = None
fp = (path or 'index.html')
ember_app = None
for k in EXTERNAL_EMBER_APPS.keys():
if request.path.strip('/').startswith(k):
ember_app = EXTERNAL_EMBER_APPS[k]
break
if (not ember_app):
raise HTTPError(http... | def ember_app(path=None):
ember_app_folder = None
fp = (path or 'index.html')
ember_app = None
for k in EXTERNAL_EMBER_APPS.keys():
if request.path.strip('/').startswith(k):
ember_app = EXTERNAL_EMBER_APPS[k]
break
if (not ember_app):
raise HTTPError(http... |
26f7a9e1cdfbba7e6fdf85c5264947ad3d627e6c5ccb027ca9489185b6498bb0 | def make_url_map(app):
'Set up all the routes for the OSF app.\n\n :param app: A Flask/Werkzeug app to bind the rules to.\n '
process_rules(app, [Rule('/<path:_>', ['get', 'post'], HTTPError(http_status.HTTP_404_NOT_FOUND), OsfWebRenderer('', render_mako_string, trust=False)), Rule('/api/v1/<path:_>', ['g... | Set up all the routes for the OSF app.
:param app: A Flask/Werkzeug app to bind the rules to. | website/routes.py | make_url_map | felliott/osf.io | 628 | python | def make_url_map(app):
'Set up all the routes for the OSF app.\n\n :param app: A Flask/Werkzeug app to bind the rules to.\n '
process_rules(app, [Rule('/<path:_>', ['get', 'post'], HTTPError(http_status.HTTP_404_NOT_FOUND), OsfWebRenderer(, render_mako_string, trust=False)), Rule('/api/v1/<path:_>', ['get... | def make_url_map(app):
'Set up all the routes for the OSF app.\n\n :param app: A Flask/Werkzeug app to bind the rules to.\n '
process_rules(app, [Rule('/<path:_>', ['get', 'post'], HTTPError(http_status.HTTP_404_NOT_FOUND), OsfWebRenderer(, render_mako_string, trust=False)), Rule('/api/v1/<path:_>', ['get... |
e1f1885d50d0fb7dcee2381642c41a56265dc0faf5a674328070bcc48612b5db | def __call__(self, data, *args, **kwargs):
"\n This function has been added to keep our Flask requests compatible with django-waffle, it's been adapted from\n waffle's own middleware code at https://github.com/django-waffle/django-waffle/blob/master/waffle/middleware.py\n "
resp = super(Osf... | This function has been added to keep our Flask requests compatible with django-waffle, it's been adapted from
waffle's own middleware code at https://github.com/django-waffle/django-waffle/blob/master/waffle/middleware.py | website/routes.py | __call__ | felliott/osf.io | 628 | python | def __call__(self, data, *args, **kwargs):
"\n This function has been added to keep our Flask requests compatible with django-waffle, it's been adapted from\n waffle's own middleware code at https://github.com/django-waffle/django-waffle/blob/master/waffle/middleware.py\n "
resp = super(Osf... | def __call__(self, data, *args, **kwargs):
"\n This function has been added to keep our Flask requests compatible with django-waffle, it's been adapted from\n waffle's own middleware code at https://github.com/django-waffle/django-waffle/blob/master/waffle/middleware.py\n "
resp = super(Osf... |
de68bea1f47838a47bf6a4485710d7780b1dcfb2bf956470ad2d9b521f106966 | def discover_single_file_for_basin(data_dir: str, basin: str) -> str:
"\n Discovers a single dataset file for the specified basin. Discovery will be performed using the pattern\n '{data_dir}/*{basin}*', i.e. the basin ID has to be present in any file name within the directory. Note, that\n basin id '123' e... | Discovers a single dataset file for the specified basin. Discovery will be performed using the pattern
'{data_dir}/*{basin}*', i.e. the basin ID has to be present in any file name within the directory. Note, that
basin id '123' e.g. will match the following file names: 123_streamflow.txt, 123.nc, 00123456_daymet_v4_dai... | libs/ioutils.py | discover_single_file_for_basin | SebaDro/st-deep-hydro | 0 | python | def discover_single_file_for_basin(data_dir: str, basin: str) -> str:
"\n Discovers a single dataset file for the specified basin. Discovery will be performed using the pattern\n '{data_dir}/*{basin}*', i.e. the basin ID has to be present in any file name within the directory. Note, that\n basin id '123' e... | def discover_single_file_for_basin(data_dir: str, basin: str) -> str:
"\n Discovers a single dataset file for the specified basin. Discovery will be performed using the pattern\n '{data_dir}/*{basin}*', i.e. the basin ID has to be present in any file name within the directory. Note, that\n basin id '123' e... |
5bae12ef5bde30ebf9f8b6ddeb34522423a6cebe5b6876c594b4f55353f38801 | def discover_files_for_basins(data_dir: str, basins: list) -> dict:
'\n\n Parameters\n ----------\n data_dir: str\n The data directory used for discovering dataset files related to the specified basins\n basins: list\n List of basin IDs\n\n Returns\n -------\n dict\n Dict t... | Parameters
----------
data_dir: str
The data directory used for discovering dataset files related to the specified basins
basins: list
List of basin IDs
Returns
-------
dict
Dict that holds the dataset path to each basin | libs/ioutils.py | discover_files_for_basins | SebaDro/st-deep-hydro | 0 | python | def discover_files_for_basins(data_dir: str, basins: list) -> dict:
'\n\n Parameters\n ----------\n data_dir: str\n The data directory used for discovering dataset files related to the specified basins\n basins: list\n List of basin IDs\n\n Returns\n -------\n dict\n Dict t... | def discover_files_for_basins(data_dir: str, basins: list) -> dict:
'\n\n Parameters\n ----------\n data_dir: str\n The data directory used for discovering dataset files related to the specified basins\n basins: list\n List of basin IDs\n\n Returns\n -------\n dict\n Dict t... |
fe44185e1716e43cd797df396b29e645476c38b01746a0a5e3979455ccf0deb3 | def discover_single_camels_us_forcings_file(data_dir: str, forcings_type: str, basin: str):
"\n Discovers a single CAMELS-US forcing file by using the pattern '{data_dir}/**/{basin}_lump_{forcings_type}_forcing_leap.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US data di... | Discovers a single CAMELS-US forcing file by using the pattern '{data_dir}/**/{basin}_lump_{forcings_type}_forcing_leap.txt'.
Parameters
----------
data_dir: str
Path to the CAMELS-US data directory for forcings.
forcings_type: str
Type of the forcings timeseries, i.e. one of 'daymet', 'maurer', or 'nldas'
bas... | libs/ioutils.py | discover_single_camels_us_forcings_file | SebaDro/st-deep-hydro | 0 | python | def discover_single_camels_us_forcings_file(data_dir: str, forcings_type: str, basin: str):
"\n Discovers a single CAMELS-US forcing file by using the pattern '{data_dir}/**/{basin}_lump_{forcings_type}_forcing_leap.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US data di... | def discover_single_camels_us_forcings_file(data_dir: str, forcings_type: str, basin: str):
"\n Discovers a single CAMELS-US forcing file by using the pattern '{data_dir}/**/{basin}_lump_{forcings_type}_forcing_leap.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US data di... |
d487b295edf02afa2676fdb526f1439ec750266cfaa74598b28ad7bdd3e9305a | def discover_single_camels_us_streamflow_file(data_dir: str, basin: str):
"\n Discovers a single CAMELS-US streamflow file by using the pattern '{data_dir}/**/{basin}_streamflow_qc.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US data directory for streamflow.\n basin:... | Discovers a single CAMELS-US streamflow file by using the pattern '{data_dir}/**/{basin}_streamflow_qc.txt'.
Parameters
----------
data_dir: str
Path to the CAMELS-US data directory for streamflow.
basin: str
ID of the basin, the streamflow file will be discovered for.
Returns
-------
str
Path to the disc... | libs/ioutils.py | discover_single_camels_us_streamflow_file | SebaDro/st-deep-hydro | 0 | python | def discover_single_camels_us_streamflow_file(data_dir: str, basin: str):
"\n Discovers a single CAMELS-US streamflow file by using the pattern '{data_dir}/**/{basin}_streamflow_qc.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US data directory for streamflow.\n basin:... | def discover_single_camels_us_streamflow_file(data_dir: str, basin: str):
"\n Discovers a single CAMELS-US streamflow file by using the pattern '{data_dir}/**/{basin}_streamflow_qc.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US data directory for streamflow.\n basin:... |
52e7966a21901e369812d9f83fde628d59cd80a416afecb782e20c5231b17f83 | def discover_multiple_camels_us_forcings_files(data_dir: str, forcings_type: str, basins: list=None):
"\n Discovers multiple CAMELS-US forcing files. All files will be considered that follow the pattern\n '{data_dir}/**/*_lump_{forcings_type}_forcing_leap.txt'.\n\n Parameters\n ----------\n data_dir:... | Discovers multiple CAMELS-US forcing files. All files will be considered that follow the pattern
'{data_dir}/**/*_lump_{forcings_type}_forcing_leap.txt'.
Parameters
----------
data_dir: str
Path to the CAMELS-US data directory for forcings.
forcings_type: str
Type of the forcing timeseries, i.e. one of 'daymet... | libs/ioutils.py | discover_multiple_camels_us_forcings_files | SebaDro/st-deep-hydro | 0 | python | def discover_multiple_camels_us_forcings_files(data_dir: str, forcings_type: str, basins: list=None):
"\n Discovers multiple CAMELS-US forcing files. All files will be considered that follow the pattern\n '{data_dir}/**/*_lump_{forcings_type}_forcing_leap.txt'.\n\n Parameters\n ----------\n data_dir:... | def discover_multiple_camels_us_forcings_files(data_dir: str, forcings_type: str, basins: list=None):
"\n Discovers multiple CAMELS-US forcing files. All files will be considered that follow the pattern\n '{data_dir}/**/*_lump_{forcings_type}_forcing_leap.txt'.\n\n Parameters\n ----------\n data_dir:... |
17e6dc814e1201cfb5e6d72cf36f4c1b61db2d191f4cb2a1a580934a104b2ea6 | def discover_multiple_camels_us_streamflow_files(data_dir: str, basins: list=None):
"\n Discovers multiple CAMELS-US streamflow files. All files will be considered that follow the pattern\n '{data_dir}/**/*_streamflow_qc.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US... | Discovers multiple CAMELS-US streamflow files. All files will be considered that follow the pattern
'{data_dir}/**/*_streamflow_qc.txt'.
Parameters
----------
data_dir: str
Path to the CAMELS-US data directory for streamflow
basins: list
List of basins, the streamflow files will be discovered for. If 'None', a... | libs/ioutils.py | discover_multiple_camels_us_streamflow_files | SebaDro/st-deep-hydro | 0 | python | def discover_multiple_camels_us_streamflow_files(data_dir: str, basins: list=None):
"\n Discovers multiple CAMELS-US streamflow files. All files will be considered that follow the pattern\n '{data_dir}/**/*_streamflow_qc.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US... | def discover_multiple_camels_us_streamflow_files(data_dir: str, basins: list=None):
"\n Discovers multiple CAMELS-US streamflow files. All files will be considered that follow the pattern\n '{data_dir}/**/*_streamflow_qc.txt'.\n\n Parameters\n ----------\n data_dir: str\n Path to the CAMELS-US... |
caba2bd0b51382239cbbad1f6edb401c25d3d42f90d654f95ba9553e51eeaab1 | def load_forcings(path: str, ds_type: str):
'\n Load a dataset that contains forcing data\n\n Parameters\n ----------\n path: str\n Path to the forcings dataset\n ds_type: str\n Type of dataset. One of {camels-us, daymet-2d}\n\n Returns\n -------\n Dataset contating forcings ti... | Load a dataset that contains forcing data
Parameters
----------
path: str
Path to the forcings dataset
ds_type: str
Type of dataset. One of {camels-us, daymet-2d}
Returns
-------
Dataset contating forcings timeseries data | libs/ioutils.py | load_forcings | SebaDro/st-deep-hydro | 0 | python | def load_forcings(path: str, ds_type: str):
'\n Load a dataset that contains forcing data\n\n Parameters\n ----------\n path: str\n Path to the forcings dataset\n ds_type: str\n Type of dataset. One of {camels-us, daymet-2d}\n\n Returns\n -------\n Dataset contating forcings ti... | def load_forcings(path: str, ds_type: str):
'\n Load a dataset that contains forcing data\n\n Parameters\n ----------\n path: str\n Path to the forcings dataset\n ds_type: str\n Type of dataset. One of {camels-us, daymet-2d}\n\n Returns\n -------\n Dataset contating forcings ti... |
c36278516b842111d233eebd68b4c1aee665d1f75bf8690cdac1d5df3f52b27f | def load_forcings_camels_us(path: str) -> pd.DataFrame:
'\n Loads CAMELS forcing data from raw text files\n\n Parameters\n ----------\n path: str\n Path to the raw text file containing forcing data for a certain basin\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing Dat... | Loads CAMELS forcing data from raw text files
Parameters
----------
path: str
Path to the raw text file containing forcing data for a certain basin
Returns
-------
pd.DataFrame
DataFrame containing DateTime indexed forcing data for a basin | libs/ioutils.py | load_forcings_camels_us | SebaDro/st-deep-hydro | 0 | python | def load_forcings_camels_us(path: str) -> pd.DataFrame:
'\n Loads CAMELS forcing data from raw text files\n\n Parameters\n ----------\n path: str\n Path to the raw text file containing forcing data for a certain basin\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing Dat... | def load_forcings_camels_us(path: str) -> pd.DataFrame:
'\n Loads CAMELS forcing data from raw text files\n\n Parameters\n ----------\n path: str\n Path to the raw text file containing forcing data for a certain basin\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing Dat... |
32a6e32d457fabfa804972fd983df3f4c090ad47b34561359cb4d00acc88fe15 | def load_forcings_gauge_metadata(path: str) -> Tuple[(float, float, float)]:
'\n Loads gauge metadata from the header of a CAMELS-USE forcings file.\n\n Parameters\n ----------\n path: str\n Path to the forcings file.\n\n Returns\n -------\n tuple\n (gauge latitude, gauge elevatio... | Loads gauge metadata from the header of a CAMELS-USE forcings file.
Parameters
----------
path: str
Path to the forcings file.
Returns
-------
tuple
(gauge latitude, gauge elevation, basin area [m²]) | libs/ioutils.py | load_forcings_gauge_metadata | SebaDro/st-deep-hydro | 0 | python | def load_forcings_gauge_metadata(path: str) -> Tuple[(float, float, float)]:
'\n Loads gauge metadata from the header of a CAMELS-USE forcings file.\n\n Parameters\n ----------\n path: str\n Path to the forcings file.\n\n Returns\n -------\n tuple\n (gauge latitude, gauge elevatio... | def load_forcings_gauge_metadata(path: str) -> Tuple[(float, float, float)]:
'\n Loads gauge metadata from the header of a CAMELS-USE forcings file.\n\n Parameters\n ----------\n path: str\n Path to the forcings file.\n\n Returns\n -------\n tuple\n (gauge latitude, gauge elevatio... |
c3c268efdeb85d65c008e45582ad9f6e4bbfe2333a298ef06368fb29bcf1e264 | def load_forcings_daymet_2d(path: str) -> xr.Dataset:
'\n\n Parameters\n ----------\n path: str\n Path to a Daymet NetCDF dataset\n\n Returns\n -------\n xarray.Dataset\n Dataset hat contains two dimensional Daymet forcings data\n\n '
with xr.open_dataset(path) as ds:
... | Parameters
----------
path: str
Path to a Daymet NetCDF dataset
Returns
-------
xarray.Dataset
Dataset hat contains two dimensional Daymet forcings data | libs/ioutils.py | load_forcings_daymet_2d | SebaDro/st-deep-hydro | 0 | python | def load_forcings_daymet_2d(path: str) -> xr.Dataset:
'\n\n Parameters\n ----------\n path: str\n Path to a Daymet NetCDF dataset\n\n Returns\n -------\n xarray.Dataset\n Dataset hat contains two dimensional Daymet forcings data\n\n '
with xr.open_dataset(path) as ds:
... | def load_forcings_daymet_2d(path: str) -> xr.Dataset:
'\n\n Parameters\n ----------\n path: str\n Path to a Daymet NetCDF dataset\n\n Returns\n -------\n xarray.Dataset\n Dataset hat contains two dimensional Daymet forcings data\n\n '
with xr.open_dataset(path) as ds:
... |
0b114c455bd7f3aa13bd449ef7c14a79e70f676913e887deebec28e0d90b6d71 | def load_streamflow(path: str, ds_type: str):
'\n Load streamflow data\n\n Parameters\n ----------\n path: str\n Path to a streamflow dataset\n ds_type: str\n Type of the streamflow dataset. One of {camels-us}\n\n Returns\n -------\n Dataset containing streamflow timeseries dat... | Load streamflow data
Parameters
----------
path: str
Path to a streamflow dataset
ds_type: str
Type of the streamflow dataset. One of {camels-us}
Returns
-------
Dataset containing streamflow timeseries data | libs/ioutils.py | load_streamflow | SebaDro/st-deep-hydro | 0 | python | def load_streamflow(path: str, ds_type: str):
'\n Load streamflow data\n\n Parameters\n ----------\n path: str\n Path to a streamflow dataset\n ds_type: str\n Type of the streamflow dataset. One of {camels-us}\n\n Returns\n -------\n Dataset containing streamflow timeseries dat... | def load_streamflow(path: str, ds_type: str):
'\n Load streamflow data\n\n Parameters\n ----------\n path: str\n Path to a streamflow dataset\n ds_type: str\n Type of the streamflow dataset. One of {camels-us}\n\n Returns\n -------\n Dataset containing streamflow timeseries dat... |
5fb146d712298dc8b92d7af1798fa3f33097a59d0b06ec9fc6157556ed75957b | def load_streamflow_camels_us(path: str) -> pd.DataFrame:
'\n Loads CAMELS streamflow data from raw text files\n\n Parameters\n ----------\n path: str\n Path to the raw text file containing streamflow data for a certain basin\n\n Returns\n -------\n pd.DataFrame\n DataFrame contai... | Loads CAMELS streamflow data from raw text files
Parameters
----------
path: str
Path to the raw text file containing streamflow data for a certain basin
Returns
-------
pd.DataFrame
DataFrame containing DateTime indexed streamflow data for a basin | libs/ioutils.py | load_streamflow_camels_us | SebaDro/st-deep-hydro | 0 | python | def load_streamflow_camels_us(path: str) -> pd.DataFrame:
'\n Loads CAMELS streamflow data from raw text files\n\n Parameters\n ----------\n path: str\n Path to the raw text file containing streamflow data for a certain basin\n\n Returns\n -------\n pd.DataFrame\n DataFrame contai... | def load_streamflow_camels_us(path: str) -> pd.DataFrame:
'\n Loads CAMELS streamflow data from raw text files\n\n Parameters\n ----------\n path: str\n Path to the raw text file containing streamflow data for a certain basin\n\n Returns\n -------\n pd.DataFrame\n DataFrame contai... |
e8feb66cabfa5bda2d54bbdb3c2b6087609aca61ca51f2def5dc050ad840f770 | def load_camels_us_basin_physical_characteristics(path: str) -> pd.DataFrame:
'\n Loads physical characteristics for CAMEL-US basins\n\n Parameters\n ----------\n path: str\n Path to the metadata file\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing physical characteris... | Loads physical characteristics for CAMEL-US basins
Parameters
----------
path: str
Path to the metadata file
Returns
-------
pd.DataFrame
DataFrame containing physical characteristics for CAMEL-US basins | libs/ioutils.py | load_camels_us_basin_physical_characteristics | SebaDro/st-deep-hydro | 0 | python | def load_camels_us_basin_physical_characteristics(path: str) -> pd.DataFrame:
'\n Loads physical characteristics for CAMEL-US basins\n\n Parameters\n ----------\n path: str\n Path to the metadata file\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing physical characteris... | def load_camels_us_basin_physical_characteristics(path: str) -> pd.DataFrame:
'\n Loads physical characteristics for CAMEL-US basins\n\n Parameters\n ----------\n path: str\n Path to the metadata file\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing physical characteris... |
50a67429d39e26fd9b9059d3b51236a9b603f5d1c3290aeda8032f48ccc1f941 | def load_camels_us_gauge_information(path: str) -> pd.DataFrame:
'\n Loads gauge information metadata for CAMEL-US basins\n\n Parameters\n ----------\n path: str\n Path to the metadata file\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing physical characteristics for CA... | Loads gauge information metadata for CAMEL-US basins
Parameters
----------
path: str
Path to the metadata file
Returns
-------
pd.DataFrame
DataFrame containing physical characteristics for CAMEL-US basins | libs/ioutils.py | load_camels_us_gauge_information | SebaDro/st-deep-hydro | 0 | python | def load_camels_us_gauge_information(path: str) -> pd.DataFrame:
'\n Loads gauge information metadata for CAMEL-US basins\n\n Parameters\n ----------\n path: str\n Path to the metadata file\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing physical characteristics for CA... | def load_camels_us_gauge_information(path: str) -> pd.DataFrame:
'\n Loads gauge information metadata for CAMEL-US basins\n\n Parameters\n ----------\n path: str\n Path to the metadata file\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing physical characteristics for CA... |
2f69fb6a275a63089a9d5a9e70d5a73c4738095b09be17b2ddaf664c4736a3db | def create_out_dir(output: str, name: str) -> str:
'\n Creates a directory in the given output folder for a given name and the current timestamp that can be used for\n storing outputs such as logs, monitoring metrics or saved models\n\n Parameters\n ----------\n output: str\n Output directory\... | Creates a directory in the given output folder for a given name and the current timestamp that can be used for
storing outputs such as logs, monitoring metrics or saved models
Parameters
----------
output: str
Output directory
name: str
Name of the current run
Returns
-------
str
Path of the created direc... | libs/ioutils.py | create_out_dir | SebaDro/st-deep-hydro | 0 | python | def create_out_dir(output: str, name: str) -> str:
'\n Creates a directory in the given output folder for a given name and the current timestamp that can be used for\n storing outputs such as logs, monitoring metrics or saved models\n\n Parameters\n ----------\n output: str\n Output directory\... | def create_out_dir(output: str, name: str) -> str:
'\n Creates a directory in the given output folder for a given name and the current timestamp that can be used for\n storing outputs such as logs, monitoring metrics or saved models\n\n Parameters\n ----------\n output: str\n Output directory\... |
3da4ec8a0121e6263396b68c2474dc10a9abe0e35d4a03f77277147e340fbd4e | def load_tracker(self, path, tracker_names=None, store=True):
'\n Args:\n path(str): path to result\n tracker_name(list): name of tracker\n '
if (not tracker_names):
tracker_names = [x.split('/')[(- 1)] for x in glob(path) if os.path.isdir(x)]
if isinstance(tracke... | Args:
path(str): path to result
tracker_name(list): name of tracker | toolkit/datasets/video.py | load_tracker | qilei123/pysot | 4,318 | python | def load_tracker(self, path, tracker_names=None, store=True):
'\n Args:\n path(str): path to result\n tracker_name(list): name of tracker\n '
if (not tracker_names):
tracker_names = [x.split('/')[(- 1)] for x in glob(path) if os.path.isdir(x)]
if isinstance(tracke... | def load_tracker(self, path, tracker_names=None, store=True):
'\n Args:\n path(str): path to result\n tracker_name(list): name of tracker\n '
if (not tracker_names):
tracker_names = [x.split('/')[(- 1)] for x in glob(path) if os.path.isdir(x)]
if isinstance(tracke... |
a744034928daf69d239c8e00e6d7e633ba193205555dccd927e4b6d7a7c52304 | def draw_box(self, roi, img, linewidth, color, name=None):
'\n roi: rectangle or polygon\n img: numpy array img\n linewith: line width of the bbox\n '
if ((len(roi) > 6) and ((len(roi) % 2) == 0)):
pts = np.array(roi, np.int32).reshape((- 1), 1, 2)
color =... | roi: rectangle or polygon
img: numpy array img
linewith: line width of the bbox | toolkit/datasets/video.py | draw_box | qilei123/pysot | 4,318 | python | def draw_box(self, roi, img, linewidth, color, name=None):
'\n roi: rectangle or polygon\n img: numpy array img\n linewith: line width of the bbox\n '
if ((len(roi) > 6) and ((len(roi) % 2) == 0)):
pts = np.array(roi, np.int32).reshape((- 1), 1, 2)
color =... | def draw_box(self, roi, img, linewidth, color, name=None):
'\n roi: rectangle or polygon\n img: numpy array img\n linewith: line width of the bbox\n '
if ((len(roi) > 6) and ((len(roi) % 2) == 0)):
pts = np.array(roi, np.int32).reshape((- 1), 1, 2)
color =... |
2c272c49d0722d3e64eb4059d615ade9c1665b5cd21c61815224c1ee006e2834 | def show(self, pred_trajs={}, linewidth=2, show_name=False):
"\n pred_trajs: dict of pred_traj, {'tracker_name': list of traj}\n pred_traj should contain polygon or rectangle(x, y, width, height)\n linewith: line width of the bbox\n "
assert (self.imgs is not ... | pred_trajs: dict of pred_traj, {'tracker_name': list of traj}
pred_traj should contain polygon or rectangle(x, y, width, height)
linewith: line width of the bbox | toolkit/datasets/video.py | show | qilei123/pysot | 4,318 | python | def show(self, pred_trajs={}, linewidth=2, show_name=False):
"\n pred_trajs: dict of pred_traj, {'tracker_name': list of traj}\n pred_traj should contain polygon or rectangle(x, y, width, height)\n linewith: line width of the bbox\n "
assert (self.imgs is not ... | def show(self, pred_trajs={}, linewidth=2, show_name=False):
"\n pred_trajs: dict of pred_traj, {'tracker_name': list of traj}\n pred_traj should contain polygon or rectangle(x, y, width, height)\n linewith: line width of the bbox\n "
assert (self.imgs is not ... |
6e0d2a9ed76393fe36605f14f250a7f09d0a54956242491556f10d468c7717b0 | def read_tooltips(gui_name):
'Read and format tooltips, return a dict.'
dirname = os.path.dirname(__file__)
help_path = os.path.join(dirname, 'help', (gui_name + '.json'))
with open(help_path) as fid:
raw_tooltips = json.load(fid)
format_ = TextWrapper(width=60, fix_sentence_endings=True).fi... | Read and format tooltips, return a dict. | mne/gui/_help.py | read_tooltips | hofaflo/mne-python | 1,953 | python | def read_tooltips(gui_name):
dirname = os.path.dirname(__file__)
help_path = os.path.join(dirname, 'help', (gui_name + '.json'))
with open(help_path) as fid:
raw_tooltips = json.load(fid)
format_ = TextWrapper(width=60, fix_sentence_endings=True).fill
return {key: format_(text) for (key... | def read_tooltips(gui_name):
dirname = os.path.dirname(__file__)
help_path = os.path.join(dirname, 'help', (gui_name + '.json'))
with open(help_path) as fid:
raw_tooltips = json.load(fid)
format_ = TextWrapper(width=60, fix_sentence_endings=True).fill
return {key: format_(text) for (key... |
864c9cdd85f94e511ff2cf9ddbba0f537b9127abeef30813f495531b6ba38035 | def test_no_args(capsys, monkeypatch):
'With no arguments, awsudo exits with usage.'
monkeypatch.setattr(sys, 'argv', ['awsudo'])
with pytest.raises(SystemExit):
main.main()
(out, err) = capsys.readouterr()
assert ('Usage:' in err) | With no arguments, awsudo exits with usage. | awsudo/test/test_main.py | test_no_args | outersystems/awsudo | 1 | python | def test_no_args(capsys, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['awsudo'])
with pytest.raises(SystemExit):
main.main()
(out, err) = capsys.readouterr()
assert ('Usage:' in err) | def test_no_args(capsys, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['awsudo'])
with pytest.raises(SystemExit):
main.main()
(out, err) = capsys.readouterr()
assert ('Usage:' in err)<|docstring|>With no arguments, awsudo exits with usage.<|endoftext|> |
9e7a4ad343238d597582c3bbf5f1ff0e8ee279548e98578bb921479e17d2df8a | def test_only_option(capsys, monkeypatch):
'With only options, awsudo exits with usage.'
monkeypatch.setattr(sys, 'argv', ['awsudo', '-u', 'default'])
with pytest.raises(SystemExit):
main.main()
(out, err) = capsys.readouterr()
assert ('Usage:' in err) | With only options, awsudo exits with usage. | awsudo/test/test_main.py | test_only_option | outersystems/awsudo | 1 | python | def test_only_option(capsys, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['awsudo', '-u', 'default'])
with pytest.raises(SystemExit):
main.main()
(out, err) = capsys.readouterr()
assert ('Usage:' in err) | def test_only_option(capsys, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['awsudo', '-u', 'default'])
with pytest.raises(SystemExit):
main.main()
(out, err) = capsys.readouterr()
assert ('Usage:' in err)<|docstring|>With only options, awsudo exits with usage.<|endoftext|> |
3b9be94fb3264a4b1dcbb2ec8d7cdc4cc157678ddf7a2dd3c18787784067823a | def test_parseArgs_env_profile(monkeypatch):
'Env vars is taken if no option are given.'
environ = {'AWS_PROFILE': 'profile'}
monkeypatch.setattr(os, 'environ', environ)
monkeypatch.setattr(sys, 'argv', ['awsudo', 'command'])
(profile, args) = main.parseArgs()
assert (profile == 'profile')
a... | Env vars is taken if no option are given. | awsudo/test/test_main.py | test_parseArgs_env_profile | outersystems/awsudo | 1 | python | def test_parseArgs_env_profile(monkeypatch):
environ = {'AWS_PROFILE': 'profile'}
monkeypatch.setattr(os, 'environ', environ)
monkeypatch.setattr(sys, 'argv', ['awsudo', 'command'])
(profile, args) = main.parseArgs()
assert (profile == 'profile')
assert (args == ['command']) | def test_parseArgs_env_profile(monkeypatch):
environ = {'AWS_PROFILE': 'profile'}
monkeypatch.setattr(os, 'environ', environ)
monkeypatch.setattr(sys, 'argv', ['awsudo', 'command'])
(profile, args) = main.parseArgs()
assert (profile == 'profile')
assert (args == ['command'])<|docstring|>Env... |
99a619f87c8a2aacbd0f27129685a50cdc57b8511e96da6e0d412bc37764f38e | def test_parseArgs_option_over_environ(monkeypatch):
'Options values are taken even if environment variables are set.'
environ = {'AWS_PROFILE': 'profile-environ'}
monkeypatch.setattr(os, 'environ', environ)
monkeypatch.setattr(sys, 'argv', ['awsudo', '-u', 'profile-option', 'command'])
(profile, ar... | Options values are taken even if environment variables are set. | awsudo/test/test_main.py | test_parseArgs_option_over_environ | outersystems/awsudo | 1 | python | def test_parseArgs_option_over_environ(monkeypatch):
environ = {'AWS_PROFILE': 'profile-environ'}
monkeypatch.setattr(os, 'environ', environ)
monkeypatch.setattr(sys, 'argv', ['awsudo', '-u', 'profile-option', 'command'])
(profile, args) = main.parseArgs()
assert (profile == 'profile-option')
... | def test_parseArgs_option_over_environ(monkeypatch):
environ = {'AWS_PROFILE': 'profile-environ'}
monkeypatch.setattr(os, 'environ', environ)
monkeypatch.setattr(sys, 'argv', ['awsudo', '-u', 'profile-option', 'command'])
(profile, args) = main.parseArgs()
assert (profile == 'profile-option')
... |
4f70c342c2e1a765df11b8bc76432cd0c2498cd9dfbef0f80fe235dcbbdff5cd | def test_cleanEnvironment(monkeypatch):
'cleanEnvironment strips AWS and boto configuration.'
environ = {'AWS_SECRET': 'password1', 'BOTO_CONFIG': 'please work', 'HOME': 'ward bound'}
monkeypatch.setattr(os, 'environ', environ)
main.cleanEnvironment()
assert ('AWS_SECRET' not in environ)
assert ... | cleanEnvironment strips AWS and boto configuration. | awsudo/test/test_main.py | test_cleanEnvironment | outersystems/awsudo | 1 | python | def test_cleanEnvironment(monkeypatch):
environ = {'AWS_SECRET': 'password1', 'BOTO_CONFIG': 'please work', 'HOME': 'ward bound'}
monkeypatch.setattr(os, 'environ', environ)
main.cleanEnvironment()
assert ('AWS_SECRET' not in environ)
assert ('BOTO_CONFIG' not in environ)
assert (environ['H... | def test_cleanEnvironment(monkeypatch):
environ = {'AWS_SECRET': 'password1', 'BOTO_CONFIG': 'please work', 'HOME': 'ward bound'}
monkeypatch.setattr(os, 'environ', environ)
main.cleanEnvironment()
assert ('AWS_SECRET' not in environ)
assert ('BOTO_CONFIG' not in environ)
assert (environ['H... |
f00f0a7b22ed1aa4dadea8c6f218da3c53add0716bf454ebb45dd06a17143331 | def format_date(data_json) -> List[Dict[(str, Union[(str, int, datetime.datetime)])]]:
' Formats the date from a json object. '
for row in data_json:
row_date = row['product_url__created_at']
row_date_formatted = eval(row_date)
row['product_url__created_at'] = row_date_formatted
retu... | Formats the date from a json object. | utils/utils.py | format_date | yagomichalak/django-test | 0 | python | def format_date(data_json) -> List[Dict[(str, Union[(str, int, datetime.datetime)])]]:
' '
for row in data_json:
row_date = row['product_url__created_at']
row_date_formatted = eval(row_date)
row['product_url__created_at'] = row_date_formatted
return data_json | def format_date(data_json) -> List[Dict[(str, Union[(str, int, datetime.datetime)])]]:
' '
for row in data_json:
row_date = row['product_url__created_at']
row_date_formatted = eval(row_date)
row['product_url__created_at'] = row_date_formatted
return data_json<|docstring|>Formats the... |
f5efd6170ad467276d974dfca159c444a3db6c84c559240b1bf6bf0d91ca5866 | def group_products(data_json) -> Dict[(str, Union[(str, int, datetime.datetime)])]:
' Group duplicate products. '
new_data_list: List[List[Dict[(str, Union[(str, int, datetime.datetime)])]]] = []
products: Dict[(str, List[Any])] = {}
for row in data_json:
if (row['product_url'] in products):
... | Group duplicate products. | utils/utils.py | group_products | yagomichalak/django-test | 0 | python | def group_products(data_json) -> Dict[(str, Union[(str, int, datetime.datetime)])]:
' '
new_data_list: List[List[Dict[(str, Union[(str, int, datetime.datetime)])]]] = []
products: Dict[(str, List[Any])] = {}
for row in data_json:
if (row['product_url'] in products):
products[row['pr... | def group_products(data_json) -> Dict[(str, Union[(str, int, datetime.datetime)])]:
' '
new_data_list: List[List[Dict[(str, Union[(str, int, datetime.datetime)])]]] = []
products: Dict[(str, List[Any])] = {}
for row in data_json:
if (row['product_url'] in products):
products[row['pr... |
5080d6357d423828944d682d71977d4ad03d0df35f12c76cea91011b8b68b968 | def setup(bot: commands.Bot):
'Setup the discipline cog'
bot.add_cog(Discipline(bot)) | Setup the discipline cog | bot/cogs/discipline.py | setup | Things-N-Stuff/Turt | 0 | python | def setup(bot: commands.Bot):
bot.add_cog(Discipline(bot)) | def setup(bot: commands.Bot):
bot.add_cog(Discipline(bot))<|docstring|>Setup the discipline cog<|endoftext|> |
32f29117ad1b32aac7db7dc59c7209521b07808f51e5dd1339d7b31fbac5eddf | @commands.Command
@server_only()
@whitelist_only()
async def warn(self, ctx, user: discord.User, severity: int, reason: str):
"\n Permissions Requirement: \n Warning Whitelisted Users: Server Owner\n Warning Non-Whitelisted Users: Server Whitelisted\n Parameters:\n use... | Permissions Requirement:
Warning Whitelisted Users: Server Owner
Warning Non-Whitelisted Users: Server Whitelisted
Parameters:
user - An @ mention or the userid of the user to be warned.
severity - How severe the offense was. This number is added to the user's account for this server.
reason - The ... | bot/cogs/discipline.py | warn | Things-N-Stuff/Turt | 0 | python | @commands.Command
@server_only()
@whitelist_only()
async def warn(self, ctx, user: discord.User, severity: int, reason: str):
"\n Permissions Requirement: \n Warning Whitelisted Users: Server Owner\n Warning Non-Whitelisted Users: Server Whitelisted\n Parameters:\n use... | @commands.Command
@server_only()
@whitelist_only()
async def warn(self, ctx, user: discord.User, severity: int, reason: str):
"\n Permissions Requirement: \n Warning Whitelisted Users: Server Owner\n Warning Non-Whitelisted Users: Server Whitelisted\n Parameters:\n use... |
999a79186a76f31002c39fcd72a38d04f3c35c37087b04580df77b6c8a799422 | def test_valid_http():
'Test building a UnstructuredData.'
validator = RecordValidator(True)
ud = UnstructuredData('http://example.com', FileType.TEXT)
assert (ud.record is None)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'OK') | Test building a UnstructuredData. | tests/zeffTestSuite/record/test_unstructureddata.py | test_valid_http | ziff/ZeffClient | 1 | python | def test_valid_http():
validator = RecordValidator(True)
ud = UnstructuredData('http://example.com', FileType.TEXT)
assert (ud.record is None)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'OK') | def test_valid_http():
validator = RecordValidator(True)
ud = UnstructuredData('http://example.com', FileType.TEXT)
assert (ud.record is None)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'OK')<|docstring|>Test building a UnstructuredData.<|endoftext|> |
f93155fe10d4af289a2afc49cf9a006d6bf45e356098856046ade6c07d98a866 | def test_valid_file():
'Test building a UnstructuredData with file.'
validator = RecordValidator(True)
ud = UnstructuredData(f'file://{__file__}', FileType.TEXT)
assert (ud.record is None)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'OK') | Test building a UnstructuredData with file. | tests/zeffTestSuite/record/test_unstructureddata.py | test_valid_file | ziff/ZeffClient | 1 | python | def test_valid_file():
validator = RecordValidator(True)
ud = UnstructuredData(f'file://{__file__}', FileType.TEXT)
assert (ud.record is None)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'OK') | def test_valid_file():
validator = RecordValidator(True)
ud = UnstructuredData(f'file://{__file__}', FileType.TEXT)
assert (ud.record is None)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'OK')<|docstring|>Test building a UnstructuredData with file.<|endoftext|> |
202cbedc1382a3ce183d1a6c4ed5045a5af7e9f11ac50dc669774a5428ce0a13 | def test_missing_file():
'Test building a UnstructuredData with missing file.'
validator = RecordValidator(True)
ud = UnstructuredData('file:///spam', FileType.TEXT)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'file missing') | Test building a UnstructuredData with missing file. | tests/zeffTestSuite/record/test_unstructureddata.py | test_missing_file | ziff/ZeffClient | 1 | python | def test_missing_file():
validator = RecordValidator(True)
ud = UnstructuredData('file:///spam', FileType.TEXT)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'file missing') | def test_missing_file():
validator = RecordValidator(True)
ud = UnstructuredData('file:///spam', FileType.TEXT)
validator.validate_unstructured_data(ud)
assert (ud.accessible == 'file missing')<|docstring|>Test building a UnstructuredData with missing file.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.