body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def scope_name():
'Returns the name of current scope as a string, e.g. deepq/q_func'
return tf.compat.v1.get_variable_scope().name | 4,613,101,357,403,974,000 | Returns the name of current scope as a string, e.g. deepq/q_func | baselines/deepq/build_graph.py | scope_name | rwill128/baselines | python | def scope_name():
return tf.compat.v1.get_variable_scope().name |
def absolute_scope_name(relative_scope_name):
'Appends parent scope name to `relative_scope_name`'
return ((scope_name() + '/') + relative_scope_name) | 7,051,420,257,098,793,000 | Appends parent scope name to `relative_scope_name` | baselines/deepq/build_graph.py | absolute_scope_name | rwill128/baselines | python | def absolute_scope_name(relative_scope_name):
return ((scope_name() + '/') + relative_scope_name) |
def build_act(make_obs_ph, q_func, num_actions, scope='deepq', reuse=None):
'Creates the act function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.compat.v1.placeholder or TfInput\n a function that take a name and creates a placeholder of input with that name\n q_func: (tf.Variable, int,... | 2,112,412,584,453,471,000 | Creates the act function:
Parameters
----------
make_obs_ph: str -> tf.compat.v1.placeholder or TfInput
a function that take a name and creates a placeholder of input with that name
q_func: (tf.Variable, int, str, bool) -> tf.Variable
the model that takes the following inputs:
... | baselines/deepq/build_graph.py | build_act | rwill128/baselines | python | def build_act(make_obs_ph, q_func, num_actions, scope='deepq', reuse=None):
'Creates the act function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.compat.v1.placeholder or TfInput\n a function that take a name and creates a placeholder of input with that name\n q_func: (tf.Variable, int,... |
def build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope='deepq', reuse=None, param_noise_filter_func=None):
'Creates the act function with support for parameter space noise exploration (https://arxiv.org/abs/1706.01905):\n\n Parameters\n ----------\n make_obs_ph: str -> tf.compat.v1.placehol... | -6,425,649,312,369,713,000 | Creates the act function with support for parameter space noise exploration (https://arxiv.org/abs/1706.01905):
Parameters
----------
make_obs_ph: str -> tf.compat.v1.placeholder or TfInput
a function that take a name and creates a placeholder of input with that name
q_func: (tf.Variable, int, ... | baselines/deepq/build_graph.py | build_act_with_param_noise | rwill128/baselines | python | def build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope='deepq', reuse=None, param_noise_filter_func=None):
'Creates the act function with support for parameter space noise exploration (https://arxiv.org/abs/1706.01905):\n\n Parameters\n ----------\n make_obs_ph: str -> tf.compat.v1.placehol... |
def build_train(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, double_q=True, scope='deepq', reuse=None, param_noise=False, param_noise_filter_func=None):
"Creates the train function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.compat.v1.placeholder or TfInput\n ... | 7,110,669,786,864,565,000 | Creates the train function:
Parameters
----------
make_obs_ph: str -> tf.compat.v1.placeholder or TfInput
a function that takes a name and creates a placeholder of input with that name
q_func: (tf.Variable, int, str, bool) -> tf.Variable
the model that takes the following inputs:
... | baselines/deepq/build_graph.py | build_train | rwill128/baselines | python | def build_train(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, double_q=True, scope='deepq', reuse=None, param_noise=False, param_noise_filter_func=None):
"Creates the train function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.compat.v1.placeholder or TfInput\n ... |
def hash_password(mapper, connect, target):
'\n Helper function that is a listener and hashes passwords before\n insertion into the database.\n\n :param mapper:\n :param connect:\n :param target:\n '
target.hash_password() | -4,729,170,507,548,841,000 | Helper function that is a listener and hashes passwords before
insertion into the database.
:param mapper:
:param connect:
:param target: | lemur/users/models.py | hash_password | Brett-Wood/lemur | python | def hash_password(mapper, connect, target):
'\n Helper function that is a listener and hashes passwords before\n insertion into the database.\n\n :param mapper:\n :param connect:\n :param target:\n '
target.hash_password() |
def check_password(self, password):
"\n Hash a given password and check it against the stored value\n to determine it's validity.\n\n :param password:\n :return:\n "
if self.password:
return bcrypt.check_password_hash(self.password, password) | -8,769,349,069,280,813,000 | Hash a given password and check it against the stored value
to determine it's validity.
:param password:
:return: | lemur/users/models.py | check_password | Brett-Wood/lemur | python | def check_password(self, password):
"\n Hash a given password and check it against the stored value\n to determine it's validity.\n\n :param password:\n :return:\n "
if self.password:
return bcrypt.check_password_hash(self.password, password) |
def hash_password(self):
'\n Generate the secure hash for the password.\n\n :return:\n '
if self.password:
self.password = bcrypt.generate_password_hash(self.password).decode('utf-8') | -2,520,262,000,120,174,600 | Generate the secure hash for the password.
:return: | lemur/users/models.py | hash_password | Brett-Wood/lemur | python | def hash_password(self):
'\n Generate the secure hash for the password.\n\n :return:\n '
if self.password:
self.password = bcrypt.generate_password_hash(self.password).decode('utf-8') |
@property
def is_admin(self):
"\n Determine if the current user has the 'admin' role associated\n with it.\n\n :return:\n "
for role in self.roles:
if (role.name == 'admin'):
return True | 6,724,741,202,377,436,000 | Determine if the current user has the 'admin' role associated
with it.
:return: | lemur/users/models.py | is_admin | Brett-Wood/lemur | python | @property
def is_admin(self):
"\n Determine if the current user has the 'admin' role associated\n with it.\n\n :return:\n "
for role in self.roles:
if (role.name == 'admin'):
return True |
def ceiling_thresh(progress, maximum):
'Creates a progress object\n Ensures that 0 < progress < maximum'
effective_progress = max(0, progress)
if (maximum > 0):
return Progress(min(effective_progress, maximum), maximum)
else:
return Progress(effective_progress, maximum) | -8,003,298,595,079,599,000 | Creates a progress object
Ensures that 0 < progress < maximum | requirements/progress.py | ceiling_thresh | georgiashay/fireroad-server2 | python | def ceiling_thresh(progress, maximum):
'Creates a progress object\n Ensures that 0 < progress < maximum'
effective_progress = max(0, progress)
if (maximum > 0):
return Progress(min(effective_progress, maximum), maximum)
else:
return Progress(effective_progress, maximum) |
def total_units(courses):
'Finds the total units in a list of Course objects'
total = 0
for course in courses:
total += course.total_units
return total | 4,904,410,876,397,925,000 | Finds the total units in a list of Course objects | requirements/progress.py | total_units | georgiashay/fireroad-server2 | python | def total_units(courses):
total = 0
for course in courses:
total += course.total_units
return total |
def sum_progresses(progresses, criterion_type, maxFunc):
'Adds together a list of Progress objects by combining them one by one\n criterion_type: either subjects or units\n maxFunc: describes how to combine the maximums of the Progress objects'
if (criterion_type == CRITERION_SUBJECTS):
mapfunc = ... | -5,932,178,459,262,459,000 | Adds together a list of Progress objects by combining them one by one
criterion_type: either subjects or units
maxFunc: describes how to combine the maximums of the Progress objects | requirements/progress.py | sum_progresses | georgiashay/fireroad-server2 | python | def sum_progresses(progresses, criterion_type, maxFunc):
'Adds together a list of Progress objects by combining them one by one\n criterion_type: either subjects or units\n maxFunc: describes how to combine the maximums of the Progress objects'
if (criterion_type == CRITERION_SUBJECTS):
mapfunc = ... |
def force_unfill_progresses(satisfied_by_category, current_distinct_threshold, current_threshold):
'Adjusts the fulfillment and progress of RequirementsProgress object with both distinct thresholds and thresholds\n These requirements follow the form "X subjects/units from at least N categories"\n satisfied_by... | 3,881,115,969,647,407,600 | Adjusts the fulfillment and progress of RequirementsProgress object with both distinct thresholds and thresholds
These requirements follow the form "X subjects/units from at least N categories"
satisfied_by_category: list of lists of Courses for each category
current_distinct_threshold: threshold object for distinct th... | requirements/progress.py | force_unfill_progresses | georgiashay/fireroad-server2 | python | def force_unfill_progresses(satisfied_by_category, current_distinct_threshold, current_threshold):
'Adjusts the fulfillment and progress of RequirementsProgress object with both distinct thresholds and thresholds\n These requirements follow the form "X subjects/units from at least N categories"\n satisfied_by... |
def __init__(self, statement, list_path):
'Initializes a progress object with the given requirements statement.'
self.statement = statement
self.threshold = self.statement.get_threshold()
self.distinct_threshold = self.statement.get_distinct_threshold()
self.list_path = list_path
self.children =... | 7,988,293,559,431,877,000 | Initializes a progress object with the given requirements statement. | requirements/progress.py | __init__ | georgiashay/fireroad-server2 | python | def __init__(self, statement, list_path):
self.statement = statement
self.threshold = self.statement.get_threshold()
self.distinct_threshold = self.statement.get_distinct_threshold()
self.list_path = list_path
self.children = []
if (self.statement.requirement is None):
for (index, c... |
def courses_satisfying_req(self, courses):
'\n Returns the whole courses and the half courses satisfying this requirement\n separately.\n '
if (self.statement.requirement is not None):
req = self.statement.requirement
if (('GIR:' in req) or ('HASS' in req) or ('CI-' in req))... | -7,514,238,843,185,547,000 | Returns the whole courses and the half courses satisfying this requirement
separately. | requirements/progress.py | courses_satisfying_req | georgiashay/fireroad-server2 | python | def courses_satisfying_req(self, courses):
'\n Returns the whole courses and the half courses satisfying this requirement\n separately.\n '
if (self.statement.requirement is not None):
req = self.statement.requirement
if (('GIR:' in req) or ('HASS' in req) or ('CI-' in req))... |
def override_requirement(self, manual_progress):
"\n Sets the progress fulfillment variables based on a manual progress value, which is\n expressed in either units or subjects depending on the requirement's threshold.\n "
self.is_fulfilled = (manual_progress >= self.threshold.get_actual_cut... | -7,453,064,142,810,164,000 | Sets the progress fulfillment variables based on a manual progress value, which is
expressed in either units or subjects depending on the requirement's threshold. | requirements/progress.py | override_requirement | georgiashay/fireroad-server2 | python | def override_requirement(self, manual_progress):
"\n Sets the progress fulfillment variables based on a manual progress value, which is\n expressed in either units or subjects depending on the requirement's threshold.\n "
self.is_fulfilled = (manual_progress >= self.threshold.get_actual_cut... |
def compute_assertions(self, courses, progress_assertions):
'\n Computes the fulfillment of this requirement based on progress assertions, and returns\n True if the requirement has an assertion available or False otherwise.\n\n Assertions are in the format of a dictionary keyed by requirements ... | 998,024,915,000,721,000 | Computes the fulfillment of this requirement based on progress assertions, and returns
True if the requirement has an assertion available or False otherwise.
Assertions are in the format of a dictionary keyed by requirements list paths, where the
values are dictionaries containing three possible keys: "substitutions",... | requirements/progress.py | compute_assertions | georgiashay/fireroad-server2 | python | def compute_assertions(self, courses, progress_assertions):
'\n Computes the fulfillment of this requirement based on progress assertions, and returns\n True if the requirement has an assertion available or False otherwise.\n\n Assertions are in the format of a dictionary keyed by requirements ... |
def bypass_children(self):
'Sets the is_bypassed flag of the recursive children of this progress object to True.'
for child in self.children:
child.is_bypassed = True
child.is_fulfilled = False
child.subject_fulfillment = Progress(0, 0)
child.subject_progress = 0
child.su... | -4,900,640,971,778,047,000 | Sets the is_bypassed flag of the recursive children of this progress object to True. | requirements/progress.py | bypass_children | georgiashay/fireroad-server2 | python | def bypass_children(self):
for child in self.children:
child.is_bypassed = True
child.is_fulfilled = False
child.subject_fulfillment = Progress(0, 0)
child.subject_progress = 0
child.subject_max = 0
child.unit_fulfillment = Progress(0, 0)
child.unit_progr... |
def compute(self, courses, progress_overrides, progress_assertions):
'Computes and stores the status of the requirements statement using the\n given list of Course objects.'
satisfied_courses = set()
if self.compute_assertions(courses, progress_assertions):
self.bypass_children()
retu... | 8,909,662,200,190,154,000 | Computes and stores the status of the requirements statement using the
given list of Course objects. | requirements/progress.py | compute | georgiashay/fireroad-server2 | python | def compute(self, courses, progress_overrides, progress_assertions):
'Computes and stores the status of the requirements statement using the\n given list of Course objects.'
satisfied_courses = set()
if self.compute_assertions(courses, progress_assertions):
self.bypass_children()
retu... |
def to_json_object(self, full=True, child_fn=None):
'Returns a JSON dictionary containing the dictionary representation of\n the enclosed requirements statement, as well as progress information.'
stmt_json = self.statement.to_json_object(full=False)
stmt_json[JSONProgressConstants.is_fulfilled] = sel... | -2,686,563,129,011,772,000 | Returns a JSON dictionary containing the dictionary representation of
the enclosed requirements statement, as well as progress information. | requirements/progress.py | to_json_object | georgiashay/fireroad-server2 | python | def to_json_object(self, full=True, child_fn=None):
'Returns a JSON dictionary containing the dictionary representation of\n the enclosed requirements statement, as well as progress information.'
stmt_json = self.statement.to_json_object(full=False)
stmt_json[JSONProgressConstants.is_fulfilled] = sel... |
def test_create_user_with_lowercase_email(self):
' Test creating a new user with an lowercase email words '
payload = {'email': 'example@example.com', 'password': '1111qqqq='}
user = get_user_model().objects.create_user(email=payload['email'], password=payload['password'])
self.assertEqual(user.email, p... | -5,877,496,336,141,041,000 | Test creating a new user with an lowercase email words | app/core/tests/test_models.py | test_create_user_with_lowercase_email | pudka/recipe-app-api | python | def test_create_user_with_lowercase_email(self):
' '
payload = {'email': 'example@example.com', 'password': '1111qqqq='}
user = get_user_model().objects.create_user(email=payload['email'], password=payload['password'])
self.assertEqual(user.email, payload['email'].lower()) |
def test_create_user_with_invalid_email(self):
' Test creating a new user with an invalid email address '
with self.assertRaises(ValueError):
get_user_model().objects.create_user(None, '1234325') | -6,157,888,896,015,371,000 | Test creating a new user with an invalid email address | app/core/tests/test_models.py | test_create_user_with_invalid_email | pudka/recipe-app-api | python | def test_create_user_with_invalid_email(self):
' '
with self.assertRaises(ValueError):
get_user_model().objects.create_user(None, '1234325') |
def test_create_superuser_is_successful(self):
' Test that create a new superuser '
user = get_user_model().objects.create_superuser('example@example.com', '1234')
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff) | -7,088,548,888,936,505,000 | Test that create a new superuser | app/core/tests/test_models.py | test_create_superuser_is_successful | pudka/recipe-app-api | python | def test_create_superuser_is_successful(self):
' '
user = get_user_model().objects.create_superuser('example@example.com', '1234')
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff) |
@staticmethod
def getSubtableClass(format):
'Return the subtable class for a format.'
return cmap_classes.get(format, cmap_format_unknown) | 6,981,419,533,710,048,000 | Return the subtable class for a format. | FontTools/fontTools/ttLib/tables/_c_m_a_p.py | getSubtableClass | johanoren/IncrementalNumbers | python | @staticmethod
def getSubtableClass(format):
return cmap_classes.get(format, cmap_format_unknown) |
@staticmethod
def newSubtable(format):
'Return a new instance of a subtable for format.'
subtableClass = CmapSubtable.getSubtableClass(format)
return subtableClass(format) | -8,252,059,341,019,018,000 | Return a new instance of a subtable for format. | FontTools/fontTools/ttLib/tables/_c_m_a_p.py | newSubtable | johanoren/IncrementalNumbers | python | @staticmethod
def newSubtable(format):
subtableClass = CmapSubtable.getSubtableClass(format)
return subtableClass(format) |
def getEncoding(self, default=None):
'Returns the Python encoding name for this cmap subtable based on its platformID,\n\t\tplatEncID, and language. If encoding for these values is not known, by default\n\t\tNone is returned. That can be overriden by passing a value to the default\n\t\targument.\n\n\t\tNote that ... | -8,219,492,945,941,369,000 | Returns the Python encoding name for this cmap subtable based on its platformID,
platEncID, and language. If encoding for these values is not known, by default
None is returned. That can be overriden by passing a value to the default
argument.
Note that if you want to choose a "preferred" cmap subtable, most of the ... | FontTools/fontTools/ttLib/tables/_c_m_a_p.py | getEncoding | johanoren/IncrementalNumbers | python | def getEncoding(self, default=None):
'Returns the Python encoding name for this cmap subtable based on its platformID,\n\t\tplatEncID, and language. If encoding for these values is not known, by default\n\t\tNone is returned. That can be overriden by passing a value to the default\n\t\targument.\n\n\t\tNote that ... |
def __init__(self, rate, validate_args=False, allow_nan_stats=True, name='Exponential'):
'Construct Exponential distribution with parameter `rate`.\n\n Args:\n rate: Floating point tensor, equivalent to `1 / mean`. Must contain only\n positive values.\n validate_args: Python `bool`, default `Fal... | 6,270,380,275,110,105,000 | Construct Exponential distribution with parameter `rate`.
Args:
rate: Floating point tensor, equivalent to `1 / mean`. Must contain only
positive values.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
perfor... | venv1/Lib/site-packages/tensorflow/python/ops/distributions/exponential.py | __init__ | Soum-Soum/Tensorflow_Face_Finder | python | def __init__(self, rate, validate_args=False, allow_nan_stats=True, name='Exponential'):
'Construct Exponential distribution with parameter `rate`.\n\n Args:\n rate: Floating point tensor, equivalent to `1 / mean`. Must contain only\n positive values.\n validate_args: Python `bool`, default `Fal... |
def set_model_constants(xx=50000.0, nx=100, va=10.0, tmax=(((60 * 360) * 24) * 3600.0), avep=(24 * 3600.0), dt=3600.0, period=(((3600 * 24) * 360) * 1), B=2.0, T0=(273.15 + 6), dT=2.0, Cs=0.001, Cp=1030.0, ra=1.5, ro=1030.0, ri=900.0, Cpo=4000.0, Cpi=2900.0, H=200.0, vo=0.2, Hb=1000.0, Li=3300000.0, Tf=(273.15 - 1.8), ... | 2,590,239,401,571,567,600 | Setup model constants. All of the constants have fixed values, but one can pass in own values or even some arbitrary values via **args. | coupled_channel/cutils.py | set_model_constants | AleksiNummelin/coupled_channel | python | def set_model_constants(xx=50000.0, nx=100, va=10.0, tmax=(((60 * 360) * 24) * 3600.0), avep=(24 * 3600.0), dt=3600.0, period=(((3600 * 24) * 360) * 1), B=2.0, T0=(273.15 + 6), dT=2.0, Cs=0.001, Cp=1030.0, ra=1.5, ro=1030.0, ri=900.0, Cpo=4000.0, Cpi=2900.0, H=200.0, vo=0.2, Hb=1000.0, Li=3300000.0, Tf=(273.15 - 1.8), ... |
def CoupledChannel(C, forcing, T_boundary=None, dt_f=((30 * 24) * 3600), restoring=False, ice_model=True, atm_adv=True, spatial_pattern=None, atm_DA_tendencies=None, ocn_DA_tendencies=None, return_coupled_fluxes=False, random_amp=0.1):
'\n This is the main function for the coupled ocean--atm channel model.\n ... | 6,091,658,717,478,800,000 | This is the main function for the coupled ocean--atm channel model.
## INPUT VARIABLES ##
tmax: running time in seconds
avep: averaging period for the ouput
T0: initial temperature
forcing: dimensionless scaling for the heat flux forcing - default strength is 5 W/m2
dt_f: timestep of the forcing
atm_adv: boolean, adv... | coupled_channel/cutils.py | CoupledChannel | AleksiNummelin/coupled_channel | python | def CoupledChannel(C, forcing, T_boundary=None, dt_f=((30 * 24) * 3600), restoring=False, ice_model=True, atm_adv=True, spatial_pattern=None, atm_DA_tendencies=None, ocn_DA_tendencies=None, return_coupled_fluxes=False, random_amp=0.1):
'\n This is the main function for the coupled ocean--atm channel model.\n ... |
def CoupledChannel_time(nt, nx, xx, dt, avep, sst, tas, hice, sst_boundary, sst_out, tas_out, hice_out, sflx_f_out, sflx_out, forcing, spatial_pattern, ra, Cp, va, vo, Da, Do, Cs, T0, Tf, emissivity, SW0, SW_anom, H, Hb, Cpo, ro, tau_entrainment, Li, ri, use_ocn_tendencies, use_atm_tendencies, atm_DA_tendencies, ocn_DA... | -8,831,610,648,961,246,000 | Separate time loop to enable numba | coupled_channel/cutils.py | CoupledChannel_time | AleksiNummelin/coupled_channel | python | def CoupledChannel_time(nt, nx, xx, dt, avep, sst, tas, hice, sst_boundary, sst_out, tas_out, hice_out, sflx_f_out, sflx_out, forcing, spatial_pattern, ra, Cp, va, vo, Da, Do, Cs, T0, Tf, emissivity, SW0, SW_anom, H, Hb, Cpo, ro, tau_entrainment, Li, ri, use_ocn_tendencies, use_atm_tendencies, atm_DA_tendencies, ocn_DA... |
def CoupledChannel2(C, forcing, dt_f=((30 * 24) * 3600), ocn_mixing_ratio=0, restoring=False, ice_model=True, atm_adv=True, spatial_pattern=None, atm_DA_tendencies=None, ocn_DA_tendencies=None, return_coupled_fluxes=False, random_amp=0.1):
'\n This is the main function for the coupled ocean--atm channel model.\n... | 149,027,019,511,530,000 | This is the main function for the coupled ocean--atm channel model.
## INPUT VARIABLES ##
tmax: running time in seconds
avep: averaging period for the ouput
T0: initial temperature
forcing: dimensionless scaling for the heat flux forcing - default strength is 5 W/m2
dt_f: timestep of the forcing
atm_adv: boolean, adv... | coupled_channel/cutils.py | CoupledChannel2 | AleksiNummelin/coupled_channel | python | def CoupledChannel2(C, forcing, dt_f=((30 * 24) * 3600), ocn_mixing_ratio=0, restoring=False, ice_model=True, atm_adv=True, spatial_pattern=None, atm_DA_tendencies=None, ocn_DA_tendencies=None, return_coupled_fluxes=False, random_amp=0.1):
'\n This is the main function for the coupled ocean--atm channel model.\n... |
def RaisedCosinePulse(t, Freq, Amplitude):
'\n\tRaised-Cosine Pulse\n\t\n\t@param t time vector\n\t@param Freq Frequency in Hz\n\t@param Amplitude Real Value of Amplitude\n\t\t\n\t@return Output signal vector\n\t@retval P vector of length equals to the time vector t\n\t\n\t'
N = np.size(t, 0)
P = np.z... | 3,912,961,718,534,332,000 | Raised-Cosine Pulse
@param t time vector
@param Freq Frequency in Hz
@param Amplitude Real Value of Amplitude
@return Output signal vector
@retval P vector of length equals to the time vector t | EFIT2D_Classes.py | RaisedCosinePulse | guillaumedavidphd/efit2d-pyopencl | python | def RaisedCosinePulse(t, Freq, Amplitude):
'\n\tRaised-Cosine Pulse\n\t\n\t@param t time vector\n\t@param Freq Frequency in Hz\n\t@param Amplitude Real Value of Amplitude\n\t\t\n\t@return Output signal vector\n\t@retval P vector of length equals to the time vector t\n\t\n\t'
N = np.size(t, 0)
P = np.z... |
def ricker(t, ts, fsavg):
'\n\tRicker Pulse\n\n\t@param t time vector\n\t@param ts temporal delay\n\t@param fsavg pulse width parameter\n\n\t@return Output signal vector\n\t'
a = ((fsavg * pi) * (t - ts))
a2 = (a * a)
return ((1.0 - (2.0 * a2)) * np.exp((- a2))) | 2,047,324,342,537,119,700 | Ricker Pulse
@param t time vector
@param ts temporal delay
@param fsavg pulse width parameter
@return Output signal vector | EFIT2D_Classes.py | ricker | guillaumedavidphd/efit2d-pyopencl | python | def ricker(t, ts, fsavg):
'\n\tRicker Pulse\n\n\t@param t time vector\n\t@param ts temporal delay\n\t@param fsavg pulse width parameter\n\n\t@return Output signal vector\n\t'
a = ((fsavg * pi) * (t - ts))
a2 = (a * a)
return ((1.0 - (2.0 * a2)) * np.exp((- a2))) |
def __init__(self, Width=40, Height=40, Pixel_mm=10, label=0, SPML=False):
'\n\t\tConstructor of the Class NewImage\n\n\t\t@param Width Width of the Scenario\n\t\t@param Height Height of the Scenario\n\t\t@param Pixel_mm Ratio Pixel per mm\n\t\t@param label Label\n\t\t@param SPML Flag used to ... | 1,345,557,265,963,583,500 | Constructor of the Class NewImage
@param Width Width of the Scenario
@param Height Height of the Scenario
@param Pixel_mm Ratio Pixel per mm
@param label Label
@param SPML Flag used to indicate the boundary conditions | EFIT2D_Classes.py | __init__ | guillaumedavidphd/efit2d-pyopencl | python | def __init__(self, Width=40, Height=40, Pixel_mm=10, label=0, SPML=False):
'\n\t\tConstructor of the Class NewImage\n\n\t\t@param Width Width of the Scenario\n\t\t@param Height Height of the Scenario\n\t\t@param Pixel_mm Ratio Pixel per mm\n\t\t@param label Label\n\t\t@param SPML Flag used to ... |
def createLayer(self, centerW, centerH, Width, Height, label, Theta=0):
'\n\t\tCreate a Layer\n\n\t\t@param centerW center in width-axis of the Layer\n\t\t@param centerH center in height-axis of the Layer\n\t\t@param Width Width of the Layer\n\t\t@param Height Height of the Layer\n\t\t@param label ... | -2,616,156,985,373,886,500 | Create a Layer
@param centerW center in width-axis of the Layer
@param centerH center in height-axis of the Layer
@param Width Width of the Layer
@param Height Height of the Layer
@param label Label of the layer
@param Theta Rotation Angle | EFIT2D_Classes.py | createLayer | guillaumedavidphd/efit2d-pyopencl | python | def createLayer(self, centerW, centerH, Width, Height, label, Theta=0):
'\n\t\tCreate a Layer\n\n\t\t@param centerW center in width-axis of the Layer\n\t\t@param centerH center in height-axis of the Layer\n\t\t@param Width Width of the Layer\n\t\t@param Height Height of the Layer\n\t\t@param label ... |
def createABS(self, Tap):
'\n\t\tCreate the boundary layers depending on the boundary conditions required\n\n\t\t@param Tap Layer Size\n\n\n\t\t'
self.Tap = Tap
self.SPML = True
self.AirBoundary = False
(self.M, self.N) = np.shape(self.I)
TP = round((Tap * self.Pixel_mm))
M_pml = int((self.... | 548,004,113,053,188,300 | Create the boundary layers depending on the boundary conditions required
@param Tap Layer Size | EFIT2D_Classes.py | createABS | guillaumedavidphd/efit2d-pyopencl | python | def createABS(self, Tap):
'\n\t\tCreate the boundary layers depending on the boundary conditions required\n\n\t\t@param Tap Layer Size\n\n\n\t\t'
self.Tap = Tap
self.SPML = True
self.AirBoundary = False
(self.M, self.N) = np.shape(self.I)
TP = round((Tap * self.Pixel_mm))
M_pml = int((self.... |
def __init__(self, name='Water', rho=1000, c11=2190000000.0, c12=0.0, c22=0.0, c44=0.0, eta_v=0, eta_s=0, label=0):
'\n\t\tConstructor of the Material object\n\t\t'
self.name = name
self.rho = rho
self.c11 = c11
self.c12 = c12
self.c22 = c22
self.c44 = c44
self.VL = sqrt((c11 / rho))
... | -3,500,076,890,244,242,400 | Constructor of the Material object | EFIT2D_Classes.py | __init__ | guillaumedavidphd/efit2d-pyopencl | python | def __init__(self, name='Water', rho=1000, c11=2190000000.0, c12=0.0, c22=0.0, c44=0.0, eta_v=0, eta_s=0, label=0):
'\n\t\t\n\t\t'
self.name = name
self.rho = rho
self.c11 = c11
self.c12 = c12
self.c22 = c22
self.c44 = c44
self.VL = sqrt((c11 / rho))
self.VT = sqrt((c44 / rho))
s... |
def pulseEcho(self):
'\n\t\tDefine Theta for PulseEcho Inspection. PulseEcho Inspection uses the same transducer acting as emitter and as receiver\n\t\t'
self.Theta = [((270 * pi) / 180), ((270 * pi) / 180)] | 7,562,510,623,405,474,000 | Define Theta for PulseEcho Inspection. PulseEcho Inspection uses the same transducer acting as emitter and as receiver | EFIT2D_Classes.py | pulseEcho | guillaumedavidphd/efit2d-pyopencl | python | def pulseEcho(self):
'\n\t\t\n\t\t'
self.Theta = [((270 * pi) / 180), ((270 * pi) / 180)] |
def transmission(self):
'\n\t\tDefine Theta for Transmission Inspection. Transmision uses two transducers, one used as emitter and another as receiver\n\t\t'
self.Theta = [((270 * pi) / 180), ((90 * pi) / 180)] | 1,775,700,811,088,977,200 | Define Theta for Transmission Inspection. Transmision uses two transducers, one used as emitter and another as receiver | EFIT2D_Classes.py | transmission | guillaumedavidphd/efit2d-pyopencl | python | def transmission(self):
'\n\t\t\n\t\t'
self.Theta = [((270 * pi) / 180), ((90 * pi) / 180)] |
def __init__(self, Size=10, Offset=0, BorderOffset=0, Location=0, name='emisor'):
'\n\t\tConstructor of the Class Transducer\n\t\t'
self.Size = Size
self.Offset = Offset
self.BorderOffset = BorderOffset
self.SizePixel = 0
self.Location = Location
self.name = name | 3,218,654,689,680,988,700 | Constructor of the Class Transducer | EFIT2D_Classes.py | __init__ | guillaumedavidphd/efit2d-pyopencl | python | def __init__(self, Size=10, Offset=0, BorderOffset=0, Location=0, name='emisor'):
'\n\t\t\n\t\t'
self.Size = Size
self.Offset = Offset
self.BorderOffset = BorderOffset
self.SizePixel = 0
self.Location = Location
self.name = name |
def generate(self, t):
'\n\t\tGenerate the signal waveform\n\n\t\t@param t vector time\n\t\t@return signal vector with the same length as the vector time\n\n\t\t'
if (self.name == 'RaisedCosinePulse'):
return RaisedCosinePulse(t, self.Frequency, self.Amplitude)
elif (self.name == 'RickerPulse'):
... | 7,699,083,209,038,406,000 | Generate the signal waveform
@param t vector time
@return signal vector with the same length as the vector time | EFIT2D_Classes.py | generate | guillaumedavidphd/efit2d-pyopencl | python | def generate(self, t):
'\n\t\tGenerate the signal waveform\n\n\t\t@param t vector time\n\t\t@return signal vector with the same length as the vector time\n\n\t\t'
if (self.name == 'RaisedCosinePulse'):
return RaisedCosinePulse(t, self.Frequency, self.Amplitude)
elif (self.name == 'RickerPulse'):
... |
def saveSignal(self, t):
'\n\t\tSave the signal waveform into the object\n\t\t@param t vector time\n\n\t\t'
self.time_signal = self.generate(t) | 5,772,529,140,745,431,000 | Save the signal waveform into the object
@param t vector time | EFIT2D_Classes.py | saveSignal | guillaumedavidphd/efit2d-pyopencl | python | def saveSignal(self, t):
'\n\t\tSave the signal waveform into the object\n\t\t@param t vector time\n\n\t\t'
self.time_signal = self.generate(t) |
def __init__(self):
'\n\t\tConstructor of the Class Inspection\n\t\t'
self.Theta = 0
self.XL = 0
self.YL = 0
self.IR = 0 | -5,232,118,787,041,142,000 | Constructor of the Class Inspection | EFIT2D_Classes.py | __init__ | guillaumedavidphd/efit2d-pyopencl | python | def __init__(self):
'\n\t\t\n\t\t'
self.Theta = 0
self.XL = 0
self.YL = 0
self.IR = 0 |
def addOffset(self, image, transducer, NRI):
'\n\t\tHandle Offset\n\n\t\t'
NXL = np.size(self.XL, 0)
Ntheta = np.size(self.Theta, 0)
(M_pml, N_pml) = np.shape(image.Itemp)
self.YL += np.around((((transducer.Offset * image.Pixel_mm) * NRI) / float(N_pml)))
self.IR = np.zeros((Ntheta, Ntheta), dty... | 8,526,326,461,510,447,000 | Handle Offset | EFIT2D_Classes.py | addOffset | guillaumedavidphd/efit2d-pyopencl | python | def addOffset(self, image, transducer, NRI):
'\n\t\t\n\n\t\t'
NXL = np.size(self.XL, 0)
Ntheta = np.size(self.Theta, 0)
(M_pml, N_pml) = np.shape(image.Itemp)
self.YL += np.around((((transducer.Offset * image.Pixel_mm) * NRI) / float(N_pml)))
self.IR = np.zeros((Ntheta, Ntheta), dtype=np.float32... |
def addBorderOffset(self, image, transducer, MRI):
'\n\t\tHandle Border Offset\n\n\t\t'
(M_pml, N_pml) = np.shape(image.Itemp)
ratio = (float(MRI) / float(M_pml))
self.XL[:, 0] += np.around(((transducer.BorderOffset * image.Pixel_mm) * ratio))
self.XL[:, 1] -= np.around(((transducer.BorderOffset * ... | 4,878,553,628,047,036,000 | Handle Border Offset | EFIT2D_Classes.py | addBorderOffset | guillaumedavidphd/efit2d-pyopencl | python | def addBorderOffset(self, image, transducer, MRI):
'\n\t\t\n\n\t\t'
(M_pml, N_pml) = np.shape(image.Itemp)
ratio = (float(MRI) / float(M_pml))
self.XL[:, 0] += np.around(((transducer.BorderOffset * image.Pixel_mm) * ratio))
self.XL[:, 1] -= np.around(((transducer.BorderOffset * image.Pixel_mm) * rat... |
def jobParameters(self, materiales):
'\n\t\tDefine Main Simulation Parameters\n\n\t\t@parm materiales Materials List\n\n\t\t\n\t\t'
indVL = [mat.VL for mat in materiales if (mat.VL > 400)]
indVT = [mat.VT for mat in materiales if (mat.VT > 400)]
VL = np.array(indVL)
VT = np.array(indVT)
V = np.... | -244,765,449,709,255,680 | Define Main Simulation Parameters
@parm materiales Materials List | EFIT2D_Classes.py | jobParameters | guillaumedavidphd/efit2d-pyopencl | python | def jobParameters(self, materiales):
'\n\t\tDefine Main Simulation Parameters\n\n\t\t@parm materiales Materials List\n\n\t\t\n\t\t'
indVL = [mat.VL for mat in materiales if (mat.VL > 400)]
indVT = [mat.VT for mat in materiales if (mat.VT > 400)]
VL = np.array(indVL)
VT = np.array(indVT)
V = np.... |
def createNumericalModel(self, image):
'\n\t\tCreate the Numerical Model\n\n\t\t@param image The Scenario Object\n\t\t'
Mp = (((np.shape(image.Itemp)[0] * self.SpatialScale) / image.Pixel_mm) / self.dx)
self.Rgrid = (Mp / np.shape(image.Itemp)[0])
self.TapG = np.around(((image.Tap * self.Rgrid) * image... | 7,753,574,737,775,600,000 | Create the Numerical Model
@param image The Scenario Object | EFIT2D_Classes.py | createNumericalModel | guillaumedavidphd/efit2d-pyopencl | python | def createNumericalModel(self, image):
'\n\t\tCreate the Numerical Model\n\n\t\t@param image The Scenario Object\n\t\t'
Mp = (((np.shape(image.Itemp)[0] * self.SpatialScale) / image.Pixel_mm) / self.dx)
self.Rgrid = (Mp / np.shape(image.Itemp)[0])
self.TapG = np.around(((image.Tap * self.Rgrid) * image... |
def initReceivers(self):
'\n\t\tInitialize the receivers\n\n\t\t'
self.receiver_signals = 0 | 6,697,424,247,738,574,000 | Initialize the receivers | EFIT2D_Classes.py | initReceivers | guillaumedavidphd/efit2d-pyopencl | python | def initReceivers(self):
'\n\t\t\n\n\t\t'
self.receiver_signals = 0 |
def setDevice(self, Device):
'\n\t\tSet the Computation Device\n\n\t\t@param Device Device to be used\n\n\t\tDefine the device used to compute the simulations:\n\t\t\t - "CPU" : uses the global memory in th CPU\n\t\t\t - "GPU_Global" : uses the global memory in the GPU\n\t\t\t - "GPU_Local" : uses the local... | -3,548,639,641,303,364,000 | Set the Computation Device
@param Device Device to be used
Define the device used to compute the simulations:
- "CPU" : uses the global memory in th CPU
- "GPU_Global" : uses the global memory in the GPU
- "GPU_Local" : uses the local memory in the GPU | EFIT2D_Classes.py | setDevice | guillaumedavidphd/efit2d-pyopencl | python | def setDevice(self, Device):
'\n\t\tSet the Computation Device\n\n\t\t@param Device Device to be used\n\n\t\tDefine the device used to compute the simulations:\n\t\t\t - "CPU" : uses the global memory in th CPU\n\t\t\t - "GPU_Global" : uses the global memory in the GPU\n\t\t\t - "GPU_Local" : uses the local... |
def parse_methods(csv_file, errors_dict):
'\n Parses the input CSV file with columns (method, usability, errors)\n and yields `MethodInfo` instances as a result.\n '
with csv_file.open(newline='') as f:
f = csv.reader(f)
next(f, None)
for (line, (method, usability, errors)) in e... | 5,726,738,502,827,109,000 | Parses the input CSV file with columns (method, usability, errors)
and yields `MethodInfo` instances as a result. | telethon_generator/parsers/methods.py | parse_methods | Thorbijoern/Telethon | python | def parse_methods(csv_file, errors_dict):
'\n Parses the input CSV file with columns (method, usability, errors)\n and yields `MethodInfo` instances as a result.\n '
with csv_file.open(newline=) as f:
f = csv.reader(f)
next(f, None)
for (line, (method, usability, errors)) in enu... |
def define_nav_elements(self):
'Return list of initialized pages or tabs accordingly.\n\n Should return, list: each item is an initialized app (ex `[AppBase(self.app)]` in the order each tab is rendered\n\n Raises:\n NotImplementedError: Child class must implement this method\n\n '
... | -9,071,551,403,152,067,000 | Return list of initialized pages or tabs accordingly.
Should return, list: each item is an initialized app (ex `[AppBase(self.app)]` in the order each tab is rendered
Raises:
NotImplementedError: Child class must implement this method | dash_charts/utils_app_with_navigation.py | define_nav_elements | KyleKing/dash_charts | python | def define_nav_elements(self):
'Return list of initialized pages or tabs accordingly.\n\n Should return, list: each item is an initialized app (ex `[AppBase(self.app)]` in the order each tab is rendered\n\n Raises:\n NotImplementedError: Child class must implement this method\n\n '
... |
def create(self, **kwargs):
'Create each navigation componet, storing the layout. Then parent class to create application.\n\n Args:\n kwargs: keyword arguments passed to `self.create`\n\n '
self.nav_lookup = OrderedDict([(tab.name, tab) for tab in self.define_nav_elements()])
self.... | 1,415,531,660,317,778,000 | Create each navigation componet, storing the layout. Then parent class to create application.
Args:
kwargs: keyword arguments passed to `self.create` | dash_charts/utils_app_with_navigation.py | create | KyleKing/dash_charts | python | def create(self, **kwargs):
'Create each navigation componet, storing the layout. Then parent class to create application.\n\n Args:\n kwargs: keyword arguments passed to `self.create`\n\n '
self.nav_lookup = OrderedDict([(tab.name, tab) for tab in self.define_nav_elements()])
self.... |
def initialization(self) -> None:
'Initialize ids with `self.register_uniq_ids([...])` and other one-time actions.'
super().initialization()
self.register_uniq_ids(self.app_ids) | -6,014,535,785,036,283,000 | Initialize ids with `self.register_uniq_ids([...])` and other one-time actions. | dash_charts/utils_app_with_navigation.py | initialization | KyleKing/dash_charts | python | def initialization(self) -> None:
super().initialization()
self.register_uniq_ids(self.app_ids) |
def create_elements(self) -> None:
'Override method as not needed at navigation-level.'
... | -7,928,977,626,787,852,000 | Override method as not needed at navigation-level. | dash_charts/utils_app_with_navigation.py | create_elements | KyleKing/dash_charts | python | def create_elements(self) -> None:
... |
def create_callbacks(self) -> None:
'Override method as not needed at navigation-level.'
... | 728,964,613,210,143,400 | Override method as not needed at navigation-level. | dash_charts/utils_app_with_navigation.py | create_callbacks | KyleKing/dash_charts | python | def create_callbacks(self) -> None:
... |
def initialization(self) -> None:
'Initialize ids with `self.register_uniq_ids([...])` and other one-time actions.'
super().initialization()
self.register_uniq_ids(['N/A']) | 4,057,255,263,994,259,000 | Initialize ids with `self.register_uniq_ids([...])` and other one-time actions. | dash_charts/utils_app_with_navigation.py | initialization | KyleKing/dash_charts | python | def initialization(self) -> None:
super().initialization()
self.register_uniq_ids(['N/A']) |
def create_elements(self) -> None:
'Initialize the charts, tables, and other Dash elements..'
... | 4,531,074,656,994,668,500 | Initialize the charts, tables, and other Dash elements.. | dash_charts/utils_app_with_navigation.py | create_elements | KyleKing/dash_charts | python | def create_elements(self) -> None:
... |
def create_callbacks(self) -> None:
'Register callbacks necessary for this tab.'
... | -9,179,829,243,889,156,000 | Register callbacks necessary for this tab. | dash_charts/utils_app_with_navigation.py | create_callbacks | KyleKing/dash_charts | python | def create_callbacks(self) -> None:
... |
def return_layout(self) -> dict:
'Return Dash application layout.\n\n Returns:\n dict: Dash HTML object\n\n '
tabs = [dcc.Tab(label=name, value=name) for (name, tab) in self.nav_lookup.items()]
return html.Div(children=[dcc.Tabs(id=self._il[self.id_tabs_select], value=list(self.nav_... | -2,062,648,213,333,622,800 | Return Dash application layout.
Returns:
dict: Dash HTML object | dash_charts/utils_app_with_navigation.py | return_layout | KyleKing/dash_charts | python | def return_layout(self) -> dict:
'Return Dash application layout.\n\n Returns:\n dict: Dash HTML object\n\n '
tabs = [dcc.Tab(label=name, value=name) for (name, tab) in self.nav_lookup.items()]
return html.Div(children=[dcc.Tabs(id=self._il[self.id_tabs_select], value=list(self.nav_... |
def create_callbacks(self) -> None:
'Register the navigation callback.'
outputs = [(self.id_tabs_content, 'children')]
inputs = [(self.id_tabs_select, 'value')]
@self.callback(outputs, inputs, [])
def render_tab(tab_name):
return [self.nav_layouts[tab_name]] | -152,575,347,912,989,060 | Register the navigation callback. | dash_charts/utils_app_with_navigation.py | create_callbacks | KyleKing/dash_charts | python | def create_callbacks(self) -> None:
outputs = [(self.id_tabs_content, 'children')]
inputs = [(self.id_tabs_select, 'value')]
@self.callback(outputs, inputs, [])
def render_tab(tab_name):
return [self.nav_layouts[tab_name]] |
def verify_app_initialization(self):
'Check that the app was properly initialized.\n\n Raises:\n RuntimeError: if child class has not called `self.register_uniq_ids`\n\n '
super().verify_app_initialization()
allowed_locations = ('left', 'top', 'bottom', 'right')
if (self.tabs_lo... | 8,322,259,039,936,427,000 | Check that the app was properly initialized.
Raises:
RuntimeError: if child class has not called `self.register_uniq_ids` | dash_charts/utils_app_with_navigation.py | verify_app_initialization | KyleKing/dash_charts | python | def verify_app_initialization(self):
'Check that the app was properly initialized.\n\n Raises:\n RuntimeError: if child class has not called `self.register_uniq_ids`\n\n '
super().verify_app_initialization()
allowed_locations = ('left', 'top', 'bottom', 'right')
if (self.tabs_lo... |
def return_layout(self) -> dict:
'Return Dash application layout.\n\n Returns:\n dict: Dash HTML object\n\n '
return html.Div(children=[self.tab_menu(), html.Div(style={f'margin-{self.tabs_location}': self.tabs_margin}, children=[html.Div(id=self._il[self.id_tabs_content])])]) | -6,400,689,786,300,438,000 | Return Dash application layout.
Returns:
dict: Dash HTML object | dash_charts/utils_app_with_navigation.py | return_layout | KyleKing/dash_charts | python | def return_layout(self) -> dict:
'Return Dash application layout.\n\n Returns:\n dict: Dash HTML object\n\n '
return html.Div(children=[self.tab_menu(), html.Div(style={f'margin-{self.tabs_location}': self.tabs_margin}, children=[html.Div(id=self._il[self.id_tabs_content])])]) |
def generate_tab_kwargs(self):
'Create the tab keyword arguments. Intended to be modified through inheritance.\n\n Returns:\n tuple: keyword arguments and styling for the dcc.Tab elements\n\n - tab_kwargs: with at minimum keys `(style, selected_style)` for dcc.Tab\n -... | -7,499,227,051,544,763,000 | Create the tab keyword arguments. Intended to be modified through inheritance.
Returns:
tuple: keyword arguments and styling for the dcc.Tab elements
- tab_kwargs: with at minimum keys `(style, selected_style)` for dcc.Tab
- tabs_kwargs: to be passed to dcc.Tabs
- tabs_style: style for the... | dash_charts/utils_app_with_navigation.py | generate_tab_kwargs | KyleKing/dash_charts | python | def generate_tab_kwargs(self):
'Create the tab keyword arguments. Intended to be modified through inheritance.\n\n Returns:\n tuple: keyword arguments and styling for the dcc.Tab elements\n\n - tab_kwargs: with at minimum keys `(style, selected_style)` for dcc.Tab\n -... |
def tab_menu(self):
'Return the HTML elements for the tab menu.\n\n Returns:\n dict: Dash HTML object\n\n '
(tab_kwargs, tabs_kwargs, tabs_style) = self.generate_tab_kwargs()
tabs = [dcc.Tab(label=name, value=name, **tab_kwargs) for (name, tab) in self.nav_lookup.items()]
return... | -3,407,844,848,752,143,400 | Return the HTML elements for the tab menu.
Returns:
dict: Dash HTML object | dash_charts/utils_app_with_navigation.py | tab_menu | KyleKing/dash_charts | python | def tab_menu(self):
'Return the HTML elements for the tab menu.\n\n Returns:\n dict: Dash HTML object\n\n '
(tab_kwargs, tabs_kwargs, tabs_style) = self.generate_tab_kwargs()
tabs = [dcc.Tab(label=name, value=name, **tab_kwargs) for (name, tab) in self.nav_lookup.items()]
return... |
def return_layout(self) -> dict:
'Return Dash application layout.\n\n Returns:\n dict: Dash HTML object\n\n '
return html.Div(children=[dcc.Location(id=self._il[self.id_url], refresh=False), self.nav_bar(), html.Div(id=self._il[self.id_pages_content])]) | -3,280,295,393,280,241,700 | Return Dash application layout.
Returns:
dict: Dash HTML object | dash_charts/utils_app_with_navigation.py | return_layout | KyleKing/dash_charts | python | def return_layout(self) -> dict:
'Return Dash application layout.\n\n Returns:\n dict: Dash HTML object\n\n '
return html.Div(children=[dcc.Location(id=self._il[self.id_url], refresh=False), self.nav_bar(), html.Div(id=self._il[self.id_pages_content])]) |
def nav_bar(self):
'Return the HTML elements for the navigation menu.\n\n Returns:\n dict: Dash HTML object\n\n '
brand = []
if self.logo:
brand.append(dbc.Col(html.Img(src=self.logo, height='25px')))
brand.append(dbc.Col(dbc.NavbarBrand(self.name, className='ml-2')))
... | -4,144,133,806,008,334,300 | Return the HTML elements for the navigation menu.
Returns:
dict: Dash HTML object | dash_charts/utils_app_with_navigation.py | nav_bar | KyleKing/dash_charts | python | def nav_bar(self):
'Return the HTML elements for the navigation menu.\n\n Returns:\n dict: Dash HTML object\n\n '
brand = []
if self.logo:
brand.append(dbc.Col(html.Img(src=self.logo, height='25px')))
brand.append(dbc.Col(dbc.NavbarBrand(self.name, className='ml-2')))
... |
def create_callbacks(self) -> None:
'Register the navigation callback.'
outputs = [(self.id_pages_content, 'children')]
inputs = [(self.id_url, 'pathname')]
@self.callback(outputs, inputs, [])
def render_page(pathname):
try:
return [self.nav_layouts[self.select_page_name(pathnam... | 4,695,464,808,721,864,000 | Register the navigation callback. | dash_charts/utils_app_with_navigation.py | create_callbacks | KyleKing/dash_charts | python | def create_callbacks(self) -> None:
outputs = [(self.id_pages_content, 'children')]
inputs = [(self.id_url, 'pathname')]
@self.callback(outputs, inputs, [])
def render_page(pathname):
try:
return [self.nav_layouts[self.select_page_name(pathname)]]
except Exception as er... |
def select_page_name(self, pathname):
'Return the page name determined based on the pathname.\n\n Should return str: page name\n\n Args:\n pathname: relative pathname from URL\n\n Raises:\n NotImplementedError: Child class must implement this method\n\n '
raise ... | 4,873,284,732,234,408,000 | Return the page name determined based on the pathname.
Should return str: page name
Args:
pathname: relative pathname from URL
Raises:
NotImplementedError: Child class must implement this method | dash_charts/utils_app_with_navigation.py | select_page_name | KyleKing/dash_charts | python | def select_page_name(self, pathname):
'Return the page name determined based on the pathname.\n\n Should return str: page name\n\n Args:\n pathname: relative pathname from URL\n\n Raises:\n NotImplementedError: Child class must implement this method\n\n '
raise ... |
def test_run(self):
'A dummy test just to run configured workloads'
pass | -5,225,681,682,568,962,000 | A dummy test just to run configured workloads | tests/eas/rfc.py | test_run | ADVAN-ELAA-8QM-PRC1/platform-external-lisa | python | def test_run(self):
pass |
def main() -> None:
'\n Entry point of this test project.\n '
ap.Stage(background_color='#333', stage_width=1000, stage_height=500)
sprite: ap.Sprite = ap.Sprite()
sprite.graphics.line_style(color='#0af', round_dot_setting=ap.LineRoundDotSetting(round_size=10, space_size=10))
sprite.graphics.m... | 3,645,435,936,439,092,700 | Entry point of this test project. | test_projects/line_round_dot_setting/main.py | main | simon-ritchie/action-py-script | python | def main() -> None:
'\n \n '
ap.Stage(background_color='#333', stage_width=1000, stage_height=500)
sprite: ap.Sprite = ap.Sprite()
sprite.graphics.line_style(color='#0af', round_dot_setting=ap.LineRoundDotSetting(round_size=10, space_size=10))
sprite.graphics.move_to(x=50, y=30)
sprite.gra... |
def on_polyline_click(e: ap.MouseEvent[ap.Polyline], options: dict) -> None:
'\n Handler that called when polyline is clicked.\n\n Parameters\n ----------\n e : MouseEvent\n Created MouseEvent instance.\n options : dict\n Optional parameters.\n '
polyline: ap.Polyline = e.this
... | -1,806,673,741,255,246,000 | Handler that called when polyline is clicked.
Parameters
----------
e : MouseEvent
Created MouseEvent instance.
options : dict
Optional parameters. | test_projects/line_round_dot_setting/main.py | on_polyline_click | simon-ritchie/action-py-script | python | def on_polyline_click(e: ap.MouseEvent[ap.Polyline], options: dict) -> None:
'\n Handler that called when polyline is clicked.\n\n Parameters\n ----------\n e : MouseEvent\n Created MouseEvent instance.\n options : dict\n Optional parameters.\n '
polyline: ap.Polyline = e.this
... |
def test_01_set_body_pagelink(self):
'Test the get_body_pagelink_ids and set_body_pagelink functions.'
self.set_setting('PAGE_LINK_FILTER', True)
page1 = self.create_new_page()
page2 = self.create_new_page()
content_string = 'test <a href="%s" class="page_%d">hello</a>'
content = Content(page=pa... | -6,059,341,719,195,447,000 | Test the get_body_pagelink_ids and set_body_pagelink functions. | pages/tests/test_pages_link.py | test_01_set_body_pagelink | redsolution/django-page-cms | python | def test_01_set_body_pagelink(self):
self.set_setting('PAGE_LINK_FILTER', True)
page1 = self.create_new_page()
page2 = self.create_new_page()
content_string = 'test <a href="%s" class="page_%d">hello</a>'
content = Content(page=page2, language='en-us', type='body', body=(content_string % ('#', ... |
def log(self, message):
'\n Logs a message for analysis of model training.\n '
self._logger.log(message) | -2,225,675,124,089,114,000 | Logs a message for analysis of model training. | rafiki/model/log.py | log | Yirui-Wang/rafiki | python | def log(self, message):
'\n \n '
self._logger.log(message) |
def define_loss_plot(self):
'\n Convenience method of defining a plot of ``loss`` against ``epoch``.\n To be used with ``log_loss_metric()``.\n '
self.define_plot('Loss Over Epochs', ['loss'], x_axis='epoch') | 7,711,925,971,221,801,000 | Convenience method of defining a plot of ``loss`` against ``epoch``.
To be used with ``log_loss_metric()``. | rafiki/model/log.py | define_loss_plot | Yirui-Wang/rafiki | python | def define_loss_plot(self):
'\n Convenience method of defining a plot of ``loss`` against ``epoch``.\n To be used with ``log_loss_metric()``.\n '
self.define_plot('Loss Over Epochs', ['loss'], x_axis='epoch') |
def log_loss_metric(self, loss, epoch):
'\n Convenience method for logging `loss` against `epoch`.\n To be used with ``define_loss_plot()``.\n '
self.log_metrics(loss=loss, epoch=epoch) | -2,649,884,738,541,751,000 | Convenience method for logging `loss` against `epoch`.
To be used with ``define_loss_plot()``. | rafiki/model/log.py | log_loss_metric | Yirui-Wang/rafiki | python | def log_loss_metric(self, loss, epoch):
'\n Convenience method for logging `loss` against `epoch`.\n To be used with ``define_loss_plot()``.\n '
self.log_metrics(loss=loss, epoch=epoch) |
def define_plot(self, title, metrics, x_axis=None):
'\n Defines a plot for a set of metrics for analysis of model training.\n By default, metrics will be plotted against time.\n '
self._logger.define_plot(title, metrics, x_axis) | 309,463,364,877,846,700 | Defines a plot for a set of metrics for analysis of model training.
By default, metrics will be plotted against time. | rafiki/model/log.py | define_plot | Yirui-Wang/rafiki | python | def define_plot(self, title, metrics, x_axis=None):
'\n Defines a plot for a set of metrics for analysis of model training.\n By default, metrics will be plotted against time.\n '
self._logger.define_plot(title, metrics, x_axis) |
def log_metrics(self, **kwargs):
'\n Logs metrics for a single point in time { <metric>: <value> }.\n <value> should be a number.\n '
self._logger.log_metrics(**kwargs) | 2,631,083,698,204,591,000 | Logs metrics for a single point in time { <metric>: <value> }.
<value> should be a number. | rafiki/model/log.py | log_metrics | Yirui-Wang/rafiki | python | def log_metrics(self, **kwargs):
'\n Logs metrics for a single point in time { <metric>: <value> }.\n <value> should be a number.\n '
self._logger.log_metrics(**kwargs) |
def config(settings):
'\n Template for WA-COP + CAD Cloud Integration\n '
T = current.T
settings.base.system_name = T('Sahana: Washington Common Operating Picture (WA-COP)')
settings.base.system_name_short = T('Sahana')
settings.base.prepopulate_options = {'mandatory': 'CAD', 'default': ('... | -1,311,257,314,297,650,200 | Template for WA-COP + CAD Cloud Integration | modules/templates/CAD/config.py | config | anurag-ks/eden | python | def config(settings):
'\n \n '
T = current.T
settings.base.system_name = T('Sahana: Washington Common Operating Picture (WA-COP)')
settings.base.system_name_short = T('Sahana')
settings.base.prepopulate_options = {'mandatory': 'CAD', 'default': ('default/users', 'CAD/Demo')}
settings.b... |
def __init__(self):
'\n Evaluates ground truth constructor\n ' | 7,175,434,617,803,589,000 | Evaluates ground truth constructor | art/defences/detector/poison/ground_truth_evaluator.py | __init__ | SecantZhang/adversarial-robustness-toolbox | python | def __init__(self):
'\n \n ' |
def analyze_correctness(self, assigned_clean_by_class: Union[(np.ndarray, List[np.ndarray])], is_clean_by_class: list) -> Tuple[(np.ndarray, str)]:
'\n For each training sample, determine whether the activation clustering method was correct.\n\n :param assigned_clean_by_class: Result of clustering.\n ... | 2,196,615,981,718,381,000 | For each training sample, determine whether the activation clustering method was correct.
:param assigned_clean_by_class: Result of clustering.
:param is_clean_by_class: is clean separated by class.
:return: Two variables are returned:
1) all_errors_by_class[i]: an array indicating the correctness of each ass... | art/defences/detector/poison/ground_truth_evaluator.py | analyze_correctness | SecantZhang/adversarial-robustness-toolbox | python | def analyze_correctness(self, assigned_clean_by_class: Union[(np.ndarray, List[np.ndarray])], is_clean_by_class: list) -> Tuple[(np.ndarray, str)]:
'\n For each training sample, determine whether the activation clustering method was correct.\n\n :param assigned_clean_by_class: Result of clustering.\n ... |
def get_confusion_matrix(self, values: np.ndarray) -> dict:
'\n Computes and returns a json object that contains the confusion matrix for each class.\n\n :param values: Array indicating the correctness of each assignment in the ith class.\n :return: Json object with confusion matrix per-class.\... | -1,183,738,427,082,292,700 | Computes and returns a json object that contains the confusion matrix for each class.
:param values: Array indicating the correctness of each assignment in the ith class.
:return: Json object with confusion matrix per-class. | art/defences/detector/poison/ground_truth_evaluator.py | get_confusion_matrix | SecantZhang/adversarial-robustness-toolbox | python | def get_confusion_matrix(self, values: np.ndarray) -> dict:
'\n Computes and returns a json object that contains the confusion matrix for each class.\n\n :param values: Array indicating the correctness of each assignment in the ith class.\n :return: Json object with confusion matrix per-class.\... |
@staticmethod
def calculate_and_print(numerator: int, denominator: int, name: str) -> float:
'\n Computes and prints the rates based on the denominator provided.\n\n :param numerator: number used to compute the rate.\n :param denominator: number used to compute the rate.\n :param name: R... | -2,129,083,346,196,205,600 | Computes and prints the rates based on the denominator provided.
:param numerator: number used to compute the rate.
:param denominator: number used to compute the rate.
:param name: Rate name being computed e.g., false-positive rate.
:return: Computed rate | art/defences/detector/poison/ground_truth_evaluator.py | calculate_and_print | SecantZhang/adversarial-robustness-toolbox | python | @staticmethod
def calculate_and_print(numerator: int, denominator: int, name: str) -> float:
'\n Computes and prints the rates based on the denominator provided.\n\n :param numerator: number used to compute the rate.\n :param denominator: number used to compute the rate.\n :param name: R... |
def basedir_def(*args):
'Return an uninterpolated path relative to $pybasedir.'
return os.path.join('$pybasedir', *args) | -7,844,244,356,446,634,000 | Return an uninterpolated path relative to $pybasedir. | shadowfiend/common/paths.py | basedir_def | RogerYuQian/shadowfiend | python | def basedir_def(*args):
return os.path.join('$pybasedir', *args) |
def bindir_def(*args):
'Return an uninterpolated path relative to $bindir.'
return os.path.join('$bindir', *args) | 3,999,146,093,527,564,300 | Return an uninterpolated path relative to $bindir. | shadowfiend/common/paths.py | bindir_def | RogerYuQian/shadowfiend | python | def bindir_def(*args):
return os.path.join('$bindir', *args) |
def state_path_def(*args):
'Return an uninterpolated path relative to $state_path.'
return os.path.join('$state_path', *args) | 2,190,866,738,796,461,000 | Return an uninterpolated path relative to $state_path. | shadowfiend/common/paths.py | state_path_def | RogerYuQian/shadowfiend | python | def state_path_def(*args):
return os.path.join('$state_path', *args) |
def basedir_rel(*args):
'Return a path relative to $pybasedir.'
return os.path.join(CONF.pybasedir, *args) | -4,652,185,622,669,104,000 | Return a path relative to $pybasedir. | shadowfiend/common/paths.py | basedir_rel | RogerYuQian/shadowfiend | python | def basedir_rel(*args):
return os.path.join(CONF.pybasedir, *args) |
def bindir_rel(*args):
'Return a path relative to $bindir.'
return os.path.join(CONF.bindir, *args) | -9,031,136,238,445,476,000 | Return a path relative to $bindir. | shadowfiend/common/paths.py | bindir_rel | RogerYuQian/shadowfiend | python | def bindir_rel(*args):
return os.path.join(CONF.bindir, *args) |
def state_path_rel(*args):
'Return a path relative to $state_path.'
return os.path.join(CONF.state_path, *args) | 6,254,008,708,169,499,000 | Return a path relative to $state_path. | shadowfiend/common/paths.py | state_path_rel | RogerYuQian/shadowfiend | python | def state_path_rel(*args):
return os.path.join(CONF.state_path, *args) |
def save2csv(dst_fh, row):
'\n Appends a list with data to a dst_fh csv\n args:\n dst_fh: str, output file\n row: list, list of values to write in a row\n '
with open(dst_fh, 'a', encoding='utf-8') as csvfile:
out = csv.writer(csvfile, delimiter=',', lineterminator='\n', quotechar... | -3,922,397,457,484,646,000 | Appends a list with data to a dst_fh csv
args:
dst_fh: str, output file
row: list, list of values to write in a row | src/utils.py | save2csv | BookOps-CAT/CBH-migration | python | def save2csv(dst_fh, row):
'\n Appends a list with data to a dst_fh csv\n args:\n dst_fh: str, output file\n row: list, list of values to write in a row\n '
with open(dst_fh, 'a', encoding='utf-8') as csvfile:
out = csv.writer(csvfile, delimiter=',', lineterminator='\n', quotechar... |
def test_admin_index(self):
' test index because customdashboard with MenuModule is may used'
adminindex = reverse('admin:index')
response = self.client.get(adminindex, follow=True, extra={'app_label': 'admin'})
self.assertIn(response.status_code, (200, 302)) | 8,092,868,403,751,705,000 | test index because customdashboard with MenuModule is may used | pagetools/menus/tests/test_admin.py | test_admin_index | theithec/django-pagetools | python | def test_admin_index(self):
' '
adminindex = reverse('admin:index')
response = self.client.get(adminindex, follow=True, extra={'app_label': 'admin'})
self.assertIn(response.status_code, (200, 302)) |
def test_allow_inheritance_from_interface(f, s):
'Allow inheritance from interface.'
user_class = f(s.User)
user = user_class(last_login=datetime(1999, 12, 31))
assert (not user.is_active()) | -2,168,000,348,716,013,800 | Allow inheritance from interface. | tests/test_subtyping.py | test_allow_inheritance_from_interface | proofit404/generics | python | def test_allow_inheritance_from_interface(f, s):
user_class = f(s.User)
user = user_class(last_login=datetime(1999, 12, 31))
assert (not user.is_active()) |
def histogram(x: np.ndarray, bins: int=10, range: Tuple[(float, float)]=(0, 10), weights: Optional[np.ndarray]=None, flow: bool=False) -> Tuple[(np.ndarray, Optional[np.ndarray], np.ndarray)]:
'Calculate the histogram for the data ``x``.\n\n Parameters\n ----------\n x : :obj:`numpy.ndarray`\n data ... | 8,530,521,508,059,037,000 | Calculate the histogram for the data ``x``.
Parameters
----------
x : :obj:`numpy.ndarray`
data to histogram
bins : int
number of bins
range : (float, float)
axis range
weights : :obj:`numpy.ndarray`, optional
array of weights for ``x``
flow : bool
include over and underflow content in first and la... | humba/core.py | histogram | douglasdavis/humba | python | def histogram(x: np.ndarray, bins: int=10, range: Tuple[(float, float)]=(0, 10), weights: Optional[np.ndarray]=None, flow: bool=False) -> Tuple[(np.ndarray, Optional[np.ndarray], np.ndarray)]:
'Calculate the histogram for the data ``x``.\n\n Parameters\n ----------\n x : :obj:`numpy.ndarray`\n data ... |
def mwv_histogram(x: np.ndarray, weights: np.ndarray, bins: int=10, range: Tuple[(float, float)]=(0, 10), flow: bool=False) -> Tuple[(np.ndarray, np.ndarray, np.ndarray)]:
'Histogram the same data but with multiple weight variations.\n\n Parameters\n ----------\n x : :obj:`numpy.ndarray`\n data to h... | -6,720,209,729,624,591,000 | Histogram the same data but with multiple weight variations.
Parameters
----------
x : :obj:`numpy.ndarray`
data to histogram
weights : :obj:`numpy.ndarray`, optional
multidimensional array of weights for ``x`` the first element
of the ``shape`` attribute must be equal to the length of ``x``.
bins : int
... | humba/core.py | mwv_histogram | douglasdavis/humba | python | def mwv_histogram(x: np.ndarray, weights: np.ndarray, bins: int=10, range: Tuple[(float, float)]=(0, 10), flow: bool=False) -> Tuple[(np.ndarray, np.ndarray, np.ndarray)]:
'Histogram the same data but with multiple weight variations.\n\n Parameters\n ----------\n x : :obj:`numpy.ndarray`\n data to h... |
def template_2a_1():
'\n Returns:\n QuantumCircuit: template as a quantum circuit.\n '
qc = QuantumCircuit(1)
qc.x(0)
qc.x(0)
return qc | 2,524,713,596,045,054,500 | Returns:
QuantumCircuit: template as a quantum circuit. | qiskit/circuit/library/template_circuits/toffoli/template_2a_1.py | template_2a_1 | AustinGilliam/qiskit-terra | python | def template_2a_1():
'\n Returns:\n QuantumCircuit: template as a quantum circuit.\n '
qc = QuantumCircuit(1)
qc.x(0)
qc.x(0)
return qc |
@classmethod
def setUpClass(cls):
' Set up class-wide resources (test data) '
super(ErrorWarningTests, cls).setUpClass()
logging.getLogger('dataactcore').setLevel(logging.ERROR)
logging.getLogger('dataactvalidator').setLevel(logging.ERROR)
with create_app().app_context():
cls.monkeypatch = M... | -1,095,766,638,879,940,900 | Set up class-wide resources (test data) | tests/integration/error_warning_file_tests.py | setUpClass | RonSherfey/data-act-broker-backend | python | @classmethod
def setUpClass(cls):
' '
super(ErrorWarningTests, cls).setUpClass()
logging.getLogger('dataactcore').setLevel(logging.ERROR)
logging.getLogger('dataactvalidator').setLevel(logging.ERROR)
with create_app().app_context():
cls.monkeypatch = MonkeyPatch()
sess = GlobalDB.db... |
def setUp(self):
'Test set-up.'
super(ErrorWarningTests, self).setUp() | 4,622,662,541,926,604,000 | Test set-up. | tests/integration/error_warning_file_tests.py | setUp | RonSherfey/data-act-broker-backend | python | def setUp(self):
super(ErrorWarningTests, self).setUp() |
def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.List = channel.unary_unary('/api.OrganizationService/List', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_organization__pb2.ListOrganizationRequest.SerializeToString, respon... | -7,631,543,553,442,211,000 | Constructor.
Args:
channel: A grpc.Channel. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | __init__ | GaiaFL/chirpstack-api | python | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.List = channel.unary_unary('/api.OrganizationService/List', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_organization__pb2.ListOrganizationRequest.SerializeToString, respon... |
def List(self, request, context):
'Get organization list.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | -4,753,088,458,980,007,000 | Get organization list. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | List | GaiaFL/chirpstack-api | python | def List(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def Get(self, request, context):
'Get data for a particular organization.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | 4,950,086,142,057,745,000 | Get data for a particular organization. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | Get | GaiaFL/chirpstack-api | python | def Get(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def Create(self, request, context):
'Create a new organization.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | -730,394,343,294,820,000 | Create a new organization. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | Create | GaiaFL/chirpstack-api | python | def Create(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.