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 |
|---|---|---|---|---|---|---|---|
@classmethod
def trade_message_from_db(cls, record: RowProxy, metadata: Optional[Dict]=None):
'\n *used for backtesting\n Convert a row of trade data into standard OrderBookMessage format\n :param record: a row of trade data from the database\n :return: BinarzOrderBookMessage\n '
... | -5,456,147,756,478,211,000 | *used for backtesting
Convert a row of trade data into standard OrderBookMessage format
:param record: a row of trade data from the database
:return: BinarzOrderBookMessage | hummingbot/connector/exchange/binarz/binarz_order_book.py | trade_message_from_db | amirhosein-fasihi/hummingbot | python | @classmethod
def trade_message_from_db(cls, record: RowProxy, metadata: Optional[Dict]=None):
'\n *used for backtesting\n Convert a row of trade data into standard OrderBookMessage format\n :param record: a row of trade data from the database\n :return: BinarzOrderBookMessage\n '
... |
def index():
'\n Module Home Page\n - provide the list of currently-Active Problems\n '
redirect(URL(f='problem'))
module_name = settings.modules[module].name_nice
table = s3db.delphi_group
groups = db((table.active == True)).select()
result = []
for group in groups:
... | 1,710,652,710,227,107,600 | Module Home Page
- provide the list of currently-Active Problems | controllers/delphi.py | index | Code4SierraLeone/shdms | python | def index():
'\n Module Home Page\n - provide the list of currently-Active Problems\n '
redirect(URL(f='problem'))
module_name = settings.modules[module].name_nice
table = s3db.delphi_group
groups = db((table.active == True)).select()
result = []
for group in groups:
... |
def group_rheader(r, tabs=[]):
' Group rheader '
if (r.representation == 'html'):
if (r.record is None):
return None
tabs = [(T('Basic Details'), None), (T('Problems'), 'problem')]
group = r.record
duser = s3db.delphi_DelphiUser(group.id)
if duser.authorised:
... | 2,477,566,475,082,201,000 | Group rheader | controllers/delphi.py | group_rheader | Code4SierraLeone/shdms | python | def group_rheader(r, tabs=[]):
' '
if (r.representation == 'html'):
if (r.record is None):
return None
tabs = [(T('Basic Details'), None), (T('Problems'), 'problem')]
group = r.record
duser = s3db.delphi_DelphiUser(group.id)
if duser.authorised:
t... |
def group():
' Problem Group REST Controller '
if (not s3_has_role('DelphiAdmin')):
s3db.configure('delphi_group', deletable=False)
def prep(r):
if r.interactive:
if r.component:
tablename = r.component.tablename
list_fields = s3db.get_config(tabl... | -3,236,655,830,655,958,000 | Problem Group REST Controller | controllers/delphi.py | group | Code4SierraLeone/shdms | python | def group():
' '
if (not s3_has_role('DelphiAdmin')):
s3db.configure('delphi_group', deletable=False)
def prep(r):
if r.interactive:
if r.component:
tablename = r.component.tablename
list_fields = s3db.get_config(tablename, 'list_fields')
... |
def problem_rheader(r, tabs=[]):
' Problem rheader '
if (r.representation == 'html'):
if (r.record is None):
return None
problem = r.record
tabs = [(T('Problems'), 'problems'), (T('Solutions'), 'solution'), (T('Discuss'), 'discuss'), (T('Vote'), 'vote'), (T('Scale of Results'... | 6,364,680,731,863,635,000 | Problem rheader | controllers/delphi.py | problem_rheader | Code4SierraLeone/shdms | python | def problem_rheader(r, tabs=[]):
' '
if (r.representation == 'html'):
if (r.record is None):
return None
problem = r.record
tabs = [(T('Problems'), 'problems'), (T('Solutions'), 'solution'), (T('Discuss'), 'discuss'), (T('Vote'), 'vote'), (T('Scale of Results'), 'results')]
... |
def problem():
' Problem REST Controller '
tablename = ('%s_%s' % (module, resourcename))
table = s3db[tablename]
set_method = s3db.set_method
set_method(module, resourcename, method='problems', action=problems)
set_method(module, resourcename, method='discuss', action=discuss)
set_method(mo... | -7,876,399,767,762,272,000 | Problem REST Controller | controllers/delphi.py | problem | Code4SierraLeone/shdms | python | def problem():
' '
tablename = ('%s_%s' % (module, resourcename))
table = s3db[tablename]
set_method = s3db.set_method
set_method(module, resourcename, method='problems', action=problems)
set_method(module, resourcename, method='discuss', action=discuss)
set_method(module, resourcename, com... |
def problems(r, **attr):
'\n Redirect to the list of Problems for the Group\n - used for a Tab\n '
try:
group_id = r.record.group_id
except:
raise HTTP(400)
else:
redirect(URL(f='group', args=[group_id, 'problem'])) | -3,807,189,094,633,276,400 | Redirect to the list of Problems for the Group
- used for a Tab | controllers/delphi.py | problems | Code4SierraLeone/shdms | python | def problems(r, **attr):
'\n Redirect to the list of Problems for the Group\n - used for a Tab\n '
try:
group_id = r.record.group_id
except:
raise HTTP(400)
else:
redirect(URL(f='group', args=[group_id, 'problem'])) |
def solution():
'\n Used for Imports\n '
return s3_rest_controller() | -6,854,097,583,476,038,000 | Used for Imports | controllers/delphi.py | solution | Code4SierraLeone/shdms | python | def solution():
'\n \n '
return s3_rest_controller() |
def vote(r, **attr):
'\n Custom Method to allow Voting on Solutions to a Problem\n '
problem = r.record
duser = s3db.delphi_DelphiUser(problem.group_id)
rheader = problem_rheader(r)
stable = s3db.delphi_solution
query = (stable.problem_id == problem.id)
rows = db(query).select(stab... | 2,324,606,337,618,013,000 | Custom Method to allow Voting on Solutions to a Problem | controllers/delphi.py | vote | Code4SierraLeone/shdms | python | def vote(r, **attr):
'\n \n '
problem = r.record
duser = s3db.delphi_DelphiUser(problem.group_id)
rheader = problem_rheader(r)
stable = s3db.delphi_solution
query = (stable.problem_id == problem.id)
rows = db(query).select(stable.id, stable.name)
options = Storage()
for row... |
def save_vote():
'\n Function accessed by AJAX from vote() to save the results of a Vote\n '
try:
problem_id = request.args[0]
except:
raise HTTP(400)
ptable = s3db.delphi_problem
query = (ptable.id == problem_id)
problem = db(query).select(ptable.group_id, limitby=(0, ... | -8,974,777,343,455,827,000 | Function accessed by AJAX from vote() to save the results of a Vote | controllers/delphi.py | save_vote | Code4SierraLeone/shdms | python | def save_vote():
'\n \n '
try:
problem_id = request.args[0]
except:
raise HTTP(400)
ptable = s3db.delphi_problem
query = (ptable.id == problem_id)
problem = db(query).select(ptable.group_id, limitby=(0, 1)).first()
if (not problem):
raise HTTP(404)
duser... |
def _getUnitNormalDeviation(zscore):
'\n Utility function used by Scale of Results\n\n Looks up the Unit Normal Deviation based on the Z-Score (Proportion/Probability)\n http://en.wikipedia.org/wiki/Standard_normal_table\n\n @ToDo: Move to S3Statistics module\n '
UNIT_NORMAL = ((0... | -5,715,348,252,954,635,000 | Utility function used by Scale of Results
Looks up the Unit Normal Deviation based on the Z-Score (Proportion/Probability)
http://en.wikipedia.org/wiki/Standard_normal_table
@ToDo: Move to S3Statistics module | controllers/delphi.py | _getUnitNormalDeviation | Code4SierraLeone/shdms | python | def _getUnitNormalDeviation(zscore):
'\n Utility function used by Scale of Results\n\n Looks up the Unit Normal Deviation based on the Z-Score (Proportion/Probability)\n http://en.wikipedia.org/wiki/Standard_normal_table\n\n @ToDo: Move to S3Statistics module\n '
UNIT_NORMAL = ((0... |
def online_variance(data):
'\n A numerically stable algorithm for calculating variance\n http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm\n '
n = 0
mean = 0
M2 = 0
for x in data:
n = (n + 1)
delta = (x - mean)
mean = (mean + ... | -8,880,010,815,469,903,000 | A numerically stable algorithm for calculating variance
http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm | controllers/delphi.py | online_variance | Code4SierraLeone/shdms | python | def online_variance(data):
'\n A numerically stable algorithm for calculating variance\n http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm\n '
n = 0
mean = 0
M2 = 0
for x in data:
n = (n + 1)
delta = (x - mean)
mean = (mean + ... |
def results(r, **attr):
'\n Custom Method to show the Scale of Results\n '
def NBSP():
return XML(' ')
rheader = problem_rheader(r)
response.view = 'delphi/results.html'
empty = dict(rheader=rheader, num_voted=0, chart='', table_color='', grids='', summary='')
problem = r... | 7,627,450,511,142,660,000 | Custom Method to show the Scale of Results | controllers/delphi.py | results | Code4SierraLeone/shdms | python | def results(r, **attr):
'\n \n '
def NBSP():
return XML(' ')
rheader = problem_rheader(r)
response.view = 'delphi/results.html'
empty = dict(rheader=rheader, num_voted=0, chart=, table_color=, grids=, summary=)
problem = r.record
if problem:
vtable = s3db.delp... |
def discuss(r, **attr):
' Custom Method to manage the discussion of a Problem or Solution '
if r.component:
resourcename = 'solution'
id = r.component_id
else:
resourcename = 'problem'
id = r.id
rheader = problem_rheader(r)
ckeditor = URL(c='static', f='ckeditor', arg... | 8,840,206,016,214,611,000 | Custom Method to manage the discussion of a Problem or Solution | controllers/delphi.py | discuss | Code4SierraLeone/shdms | python | def discuss(r, **attr):
' '
if r.component:
resourcename = 'solution'
id = r.component_id
else:
resourcename = 'problem'
id = r.id
rheader = problem_rheader(r)
ckeditor = URL(c='static', f='ckeditor', args='ckeditor.js')
s3.scripts.append(ckeditor)
adapter = ... |
def comment_parse(comment, comments, solution_id=None):
'\n Parse a Comment\n\n @param: comment - a gluon.sql.Row: the current comment\n @param: comments - a gluon.sql.Rows: full list of comments\n @param: solution_id - a reference ID: optional solution commented on\n '
author = B... | -1,991,871,730,518,547,000 | Parse a Comment
@param: comment - a gluon.sql.Row: the current comment
@param: comments - a gluon.sql.Rows: full list of comments
@param: solution_id - a reference ID: optional solution commented on | controllers/delphi.py | comment_parse | Code4SierraLeone/shdms | python | def comment_parse(comment, comments, solution_id=None):
'\n Parse a Comment\n\n @param: comment - a gluon.sql.Row: the current comment\n @param: comments - a gluon.sql.Rows: full list of comments\n @param: solution_id - a reference ID: optional solution commented on\n '
author = B... |
def comments():
' Function accessed by AJAX from discuss() to handle Comments '
try:
resourcename = request.args[0]
except:
raise HTTP(400)
try:
id = request.args[1]
except:
raise HTTP(400)
if (resourcename == 'problem'):
problem_id = id
solution_i... | -7,195,253,218,591,263,000 | Function accessed by AJAX from discuss() to handle Comments | controllers/delphi.py | comments | Code4SierraLeone/shdms | python | def comments():
' '
try:
resourcename = request.args[0]
except:
raise HTTP(400)
try:
id = request.args[1]
except:
raise HTTP(400)
if (resourcename == 'problem'):
problem_id = id
solution_id = None
elif (resourcename == 'solution'):
sta... |
def get_type(x):
' Return the most specific type in the type hierarchy that applies to x\n and a boolean indicating whether x is an AST. If the type cannot be\n determined, return TYPE_OBJECT as the type. '
if isinstance(x, (int, long)):
return (TYPE_INT, False)
elif isinstance(x, float):
... | -453,047,719,814,319,000 | Return the most specific type in the type hierarchy that applies to x
and a boolean indicating whether x is an AST. If the type cannot be
determined, return TYPE_OBJECT as the type. | TurtleArt/tatype.py | get_type | sugar-activities/4742-activity | python | def get_type(x):
' Return the most specific type in the type hierarchy that applies to x\n and a boolean indicating whether x is an AST. If the type cannot be\n determined, return TYPE_OBJECT as the type. '
if isinstance(x, (int, long)):
return (TYPE_INT, False)
elif isinstance(x, float):
... |
def get_converter(old_type, new_type):
' If there is a converter old_type -> new_type, return it. Else return\n None. If a chain of converters is necessary, return it as a tuple or\n list (starting with the innermost, first-to-apply converter). '
if (new_type == TYPE_OBJECT):
return identity
i... | -7,958,143,292,103,566,000 | If there is a converter old_type -> new_type, return it. Else return
None. If a chain of converters is necessary, return it as a tuple or
list (starting with the innermost, first-to-apply converter). | TurtleArt/tatype.py | get_converter | sugar-activities/4742-activity | python | def get_converter(old_type, new_type):
' If there is a converter old_type -> new_type, return it. Else return\n None. If a chain of converters is necessary, return it as a tuple or\n list (starting with the innermost, first-to-apply converter). '
if (new_type == TYPE_OBJECT):
return identity
i... |
def convert(x, new_type, old_type=None, converter=None):
' Convert x to the new type if possible.\n old_type -- the type of x. If not given, it is computed. '
if (not isinstance(new_type, Type)):
raise ValueError(('%s is not a type in the type hierarchy' % repr(new_type)))
if (new_type == TYPE_OB... | -7,584,842,374,124,464,000 | Convert x to the new type if possible.
old_type -- the type of x. If not given, it is computed. | TurtleArt/tatype.py | convert | sugar-activities/4742-activity | python | def convert(x, new_type, old_type=None, converter=None):
' Convert x to the new type if possible.\n old_type -- the type of x. If not given, it is computed. '
if (not isinstance(new_type, Type)):
raise ValueError(('%s is not a type in the type hierarchy' % repr(new_type)))
if (new_type == TYPE_OB... |
def get_call_ast(func_name, args=None, kwargs=None, return_type=None):
' Return an AST representing the call to a function with the name\n func_name, passing it the arguments args (given as a list) and the\n keyword arguments kwargs (given as a dictionary).\n func_name -- either the name of a callable as a... | 7,071,092,608,266,613,000 | Return an AST representing the call to a function with the name
func_name, passing it the arguments args (given as a list) and the
keyword arguments kwargs (given as a dictionary).
func_name -- either the name of a callable as a string, or an AST
representing a callable expression
return_type -- if this is not None... | TurtleArt/tatype.py | get_call_ast | sugar-activities/4742-activity | python | def get_call_ast(func_name, args=None, kwargs=None, return_type=None):
' Return an AST representing the call to a function with the name\n func_name, passing it the arguments args (given as a list) and the\n keyword arguments kwargs (given as a dictionary).\n func_name -- either the name of a callable as a... |
def __init__(self, constant_name, value):
" constant_name -- the name of the constant that points to this Type\n object\n value -- an arbitrary integer that is different from the values of\n all other Types. The order of the integers doesn't matter. "
self.constant_name = constant_n... | -7,065,363,459,867,630,000 | constant_name -- the name of the constant that points to this Type
object
value -- an arbitrary integer that is different from the values of
all other Types. The order of the integers doesn't matter. | TurtleArt/tatype.py | __init__ | sugar-activities/4742-activity | python | def __init__(self, constant_name, value):
" constant_name -- the name of the constant that points to this Type\n object\n value -- an arbitrary integer that is different from the values of\n all other Types. The order of the integers doesn't matter. "
self.constant_name = constant_n... |
def __init__(self, bad_value, bad_type=None, req_type=None, message=''):
' bad_value -- the mis-typed value that caused the error\n bad_type -- the type of the bad_value\n req_type -- the type that the value was expected to have\n message -- short statement about the cause of the error. It is\n... | -8,337,545,677,568,987,000 | bad_value -- the mis-typed value that caused the error
bad_type -- the type of the bad_value
req_type -- the type that the value was expected to have
message -- short statement about the cause of the error. It is
not shown to the user, but may appear in debugging output. | TurtleArt/tatype.py | __init__ | sugar-activities/4742-activity | python | def __init__(self, bad_value, bad_type=None, req_type=None, message=):
' bad_value -- the mis-typed value that caused the error\n bad_type -- the type of the bad_value\n req_type -- the type that the value was expected to have\n message -- short statement about the cause of the error. It is\n ... |
def poke_mode_only(cls):
"\n Class Decorator for child classes of BaseSensorOperator to indicate\n that instances of this class are only safe to use poke mode.\n\n Will decorate all methods in the class to assert they did not change\n the mode from 'poke'.\n\n :param cls: BaseSensor class to enforce ... | 1,229,829,944,032,250,400 | Class Decorator for child classes of BaseSensorOperator to indicate
that instances of this class are only safe to use poke mode.
Will decorate all methods in the class to assert they did not change
the mode from 'poke'.
:param cls: BaseSensor class to enforce methods only use 'poke' mode.
:type cls: type | airflow/sensors/base_sensor_operator.py | poke_mode_only | CoverGenius/airflow | python | def poke_mode_only(cls):
"\n Class Decorator for child classes of BaseSensorOperator to indicate\n that instances of this class are only safe to use poke mode.\n\n Will decorate all methods in the class to assert they did not change\n the mode from 'poke'.\n\n :param cls: BaseSensor class to enforce ... |
def poke(self, context: Dict) -> bool:
'\n Function that the sensors defined while deriving this class should\n override.\n '
raise AirflowException('Override me.') | -3,133,657,140,022,421,500 | Function that the sensors defined while deriving this class should
override. | airflow/sensors/base_sensor_operator.py | poke | CoverGenius/airflow | python | def poke(self, context: Dict) -> bool:
'\n Function that the sensors defined while deriving this class should\n override.\n '
raise AirflowException('Override me.') |
def _get_next_poke_interval(self, started_at, try_number):
'\n Using the similar logic which is used for exponential backoff retry delay for operators.\n '
if self.exponential_backoff:
min_backoff = int((self.poke_interval * (2 ** (try_number - 2))))
current_time = timezone.utcnow(... | 3,211,719,983,406,018,000 | Using the similar logic which is used for exponential backoff retry delay for operators. | airflow/sensors/base_sensor_operator.py | _get_next_poke_interval | CoverGenius/airflow | python | def _get_next_poke_interval(self, started_at, try_number):
'\n \n '
if self.exponential_backoff:
min_backoff = int((self.poke_interval * (2 ** (try_number - 2))))
current_time = timezone.utcnow()
run_hash = int(hashlib.sha1('{}#{}#{}#{}'.format(self.dag_id, self.task_id, st... |
@property
def reschedule(self):
'Define mode rescheduled sensors.'
return (self.mode == 'reschedule') | -7,624,722,879,257,717,000 | Define mode rescheduled sensors. | airflow/sensors/base_sensor_operator.py | reschedule | CoverGenius/airflow | python | @property
def reschedule(self):
return (self.mode == 'reschedule') |
@property
def deps(self):
'\n Adds one additional dependency for all sensor operators that\n checks if a sensor task instance can be rescheduled.\n '
if self.reschedule:
return (BaseOperator.deps.fget(self) | {ReadyToRescheduleDep()})
return BaseOperator.deps.fget(self) | -7,659,577,540,815,607,000 | Adds one additional dependency for all sensor operators that
checks if a sensor task instance can be rescheduled. | airflow/sensors/base_sensor_operator.py | deps | CoverGenius/airflow | python | @property
def deps(self):
'\n Adds one additional dependency for all sensor operators that\n checks if a sensor task instance can be rescheduled.\n '
if self.reschedule:
return (BaseOperator.deps.fget(self) | {ReadyToRescheduleDep()})
return BaseOperator.deps.fget(self) |
def add_source(self, name, similar=None):
"Adds a new source of absorption to the sightline.\n\n The purpose of a source is to hold multiple line models\n together, sometiimes with similar parameters\n\n Args:\n name (str): The name of the absorption source\n similar (... | -5,067,733,584,439,722,000 | Adds a new source of absorption to the sightline.
The purpose of a source is to hold multiple line models
together, sometiimes with similar parameters
Args:
name (str): The name of the absorption source
similar (dict): A dict of parameters that change with the source,
not the specific line, defaul... | edibles/sightline.py | add_source | jancami/edibles | python | def add_source(self, name, similar=None):
"Adds a new source of absorption to the sightline.\n\n The purpose of a source is to hold multiple line models\n together, sometiimes with similar parameters\n\n Args:\n name (str): The name of the absorption source\n similar (... |
def add_line(self, name, source=None, pars=None, guess_data=None):
'Adds a new line to a given absorption source.\n If no source is given, a new one will be created.\n\n Args:\n name (str): The name of the line\n source (str): the name of the source this line will belong to\n ... | -8,732,481,608,611,323,000 | Adds a new line to a given absorption source.
If no source is given, a new one will be created.
Args:
name (str): The name of the line
source (str): the name of the source this line will belong to
pars (dict): user input parameters
guess_data (1darray): flux data to guess with | edibles/sightline.py | add_line | jancami/edibles | python | def add_line(self, name, source=None, pars=None, guess_data=None):
'Adds a new line to a given absorption source.\n If no source is given, a new one will be created.\n\n Args:\n name (str): The name of the line\n source (str): the name of the source this line will belong to\n ... |
def fit(self, data=None, old=False, x=None, report=False, plot=False, weights=None, method='leastsq', **kwargs):
'Fits a model to the sightline data given by the EdiblesSpectrum object.\n\n Args:\n data (1darray): Flux data to fit\n params (lmfit.parameter.Parameters): Initial parameter... | 3,280,400,313,545,762,000 | Fits a model to the sightline data given by the EdiblesSpectrum object.
Args:
data (1darray): Flux data to fit
params (lmfit.parameter.Parameters): Initial parameters to fit
model (lmfit.model.CompositeModel): The model to fit, default: self.complete_model
x (1darray): Wavelength data to fit
report... | edibles/sightline.py | fit | jancami/edibles | python | def fit(self, data=None, old=False, x=None, report=False, plot=False, weights=None, method='leastsq', **kwargs):
'Fits a model to the sightline data given by the EdiblesSpectrum object.\n\n Args:\n data (1darray): Flux data to fit\n params (lmfit.parameter.Parameters): Initial parameter... |
def freeze(self, pars=None, prefix=None, freeze_cont=True, unfreeze=False):
"Freezes the current params, so you can still add to the\n model but the 'old' parameters will not change\n\n Args:\n prefix (str): Prefix of parameters to freeze, default: None, example: 'Telluric'\n ... | -3,010,078,550,005,135,000 | Freezes the current params, so you can still add to the
model but the 'old' parameters will not change
Args:
prefix (str): Prefix of parameters to freeze, default: None, example: 'Telluric'
freeze_cont (bool): Freeze the continuum or not, default: True
unfreeze (bool): unfreezes all parameters except x... | edibles/sightline.py | freeze | jancami/edibles | python | def freeze(self, pars=None, prefix=None, freeze_cont=True, unfreeze=False):
"Freezes the current params, so you can still add to the\n model but the 'old' parameters will not change\n\n Args:\n prefix (str): Prefix of parameters to freeze, default: None, example: 'Telluric'\n ... |
def separate(self, data, x, old=False, plot=True):
'Separate the sources that were added to Sightline.\n\n Args:\n data (1darray): FLux data to use for separation\n x (1darray): Wavelength array to use\n old (bool): If true, uses the older, second-most recent model and parame... | -8,686,016,170,199,200,000 | Separate the sources that were added to Sightline.
Args:
data (1darray): FLux data to use for separation
x (1darray): Wavelength array to use
old (bool): If true, uses the older, second-most recent model and parameters
plot (bool): If true, plots separted spectrum | edibles/sightline.py | separate | jancami/edibles | python | def separate(self, data, x, old=False, plot=True):
'Separate the sources that were added to Sightline.\n\n Args:\n data (1darray): FLux data to use for separation\n x (1darray): Wavelength array to use\n old (bool): If true, uses the older, second-most recent model and parame... |
def Battery_Func(t, SV, SV_dot, sw):
'================================================================='
'==========================INITIALIZE============================='
'================================================================='
print(t)
nSV = len(SV)
res = np.zeros([nSV])
offset... | 3,328,596,747,109,749,000 | ================================================================= | li_ion_battery_p2d_functions.py | Battery_Func | coresresearch/p2d_li_ion_battery | python | def Battery_Func(t, SV, SV_dot, sw):
'==========================INITIALIZE============================='
print(t)
nSV = len(SV)
res = np.zeros([nSV])
offset_vec = sep.offsets
" anode = an.obj['electrode']\n anode_s = an.obj['surf']\n elyte = an.obj['elyte']\n ... |
def _update_learning_rate(self):
' Learning rate scheduling per step '
self.current_step += 1
lr = (self.init_lr * self._get_lr_scale())
for param_group in self._optimizer.param_groups:
param_group['lr'] = lr | 5,636,199,922,058,562,000 | Learning rate scheduling per step | FastSpeech2/model/optimizer.py | _update_learning_rate | ARBML/klaam | python | def _update_learning_rate(self):
' '
self.current_step += 1
lr = (self.init_lr * self._get_lr_scale())
for param_group in self._optimizer.param_groups:
param_group['lr'] = lr |
def validate_one(func_name):
'\n Validate the docstring for the given func_name\n\n Parameters\n ----------\n func_name : function\n Function whose docstring will be evaluated\n\n Returns\n -------\n int\n The number of errors found in the `func_name` docstring\n '
func_obj... | 1,290,854,573,790,395,100 | Validate the docstring for the given func_name
Parameters
----------
func_name : function
Function whose docstring will be evaluated
Returns
-------
int
The number of errors found in the `func_name` docstring | scripts/validate_docstrings.py | validate_one | Anjali2019/pandas | python | def validate_one(func_name):
'\n Validate the docstring for the given func_name\n\n Parameters\n ----------\n func_name : function\n Function whose docstring will be evaluated\n\n Returns\n -------\n int\n The number of errors found in the `func_name` docstring\n '
func_obj... |
def print_list_views(ctx):
'Read list view by title example'
list_object = ctx.web.lists.get_by_title(list_title)
views = list_object.views
ctx.load(views)
ctx.execute_query()
for view in views:
cur_view_title = view.properties['Title']
cur_view = views.get_by_title(cur_view_titl... | -8,704,608,048,394,303,000 | Read list view by title example | examples/sharepoint/view_operations.py | print_list_views | Aisbergg/Office365-REST-Python-Client | python | def print_list_views(ctx):
list_object = ctx.web.lists.get_by_title(list_title)
views = list_object.views
ctx.load(views)
ctx.execute_query()
for view in views:
cur_view_title = view.properties['Title']
cur_view = views.get_by_title(cur_view_title)
ctx.load(cur_view)
... |
def print_view_items(ctx):
'Example demonstrates how to retrieve View items'
list_object = ctx.web.lists.get_by_title(list_title)
view = list_object.views.get_by_title(view_title)
ctx.load(view, ['ViewQuery'])
ctx.execute_query()
view_fields = view.view_fields
ctx.load(view_fields)
ctx.e... | -7,885,829,279,766,085,000 | Example demonstrates how to retrieve View items | examples/sharepoint/view_operations.py | print_view_items | Aisbergg/Office365-REST-Python-Client | python | def print_view_items(ctx):
list_object = ctx.web.lists.get_by_title(list_title)
view = list_object.views.get_by_title(view_title)
ctx.load(view, ['ViewQuery'])
ctx.execute_query()
view_fields = view.view_fields
ctx.load(view_fields)
ctx.execute_query()
qry = CamlQuery()
qry.View... |
def test_dead_default():
'\n\t\tYou may now omit a transition, or even an entire state, from the map. This\n\t\taffects every usage of `fsm.map`.\n\t'
blockquote = fsm(alphabet={'/', '*', anything_else}, states={0, 1, 2, 3, 4, 5}, initial=0, finals={4}, map={0: {'/': 1}, 1: {'*': 2}, 2: {'/': 2, anything_else: ... | -8,301,654,867,052,381,000 | You may now omit a transition, or even an entire state, from the map. This
affects every usage of `fsm.map`. | greenery/fsm_test.py | test_dead_default | doni69/greenery | python | def test_dead_default():
'\n\t\tYou may now omit a transition, or even an entire state, from the map. This\n\t\taffects every usage of `fsm.map`.\n\t'
blockquote = fsm(alphabet={'/', '*', anything_else}, states={0, 1, 2, 3, 4, 5}, initial=0, finals={4}, map={0: {'/': 1}, 1: {'*': 2}, 2: {'/': 2, anything_else: ... |
def _construct_simple(coeffs, opt):
'Handle simple domains, e.g.: ZZ, QQ, RR and algebraic domains. '
rationals = floats = complexes = algebraics = False
float_numbers = []
if (opt.extension is True):
is_algebraic = (lambda coeff: (coeff.is_number and coeff.is_algebraic))
else:
is_al... | 2,315,593,106,988,361,700 | Handle simple domains, e.g.: ZZ, QQ, RR and algebraic domains. | sympy/polys/constructor.py | _construct_simple | ABKor752/sympy | python | def _construct_simple(coeffs, opt):
' '
rationals = floats = complexes = algebraics = False
float_numbers = []
if (opt.extension is True):
is_algebraic = (lambda coeff: (coeff.is_number and coeff.is_algebraic))
else:
is_algebraic = (lambda coeff: False)
for coeff in coeffs:
... |
def _construct_algebraic(coeffs, opt):
'We know that coefficients are algebraic so construct the extension. '
from sympy.polys.numberfields import primitive_element
(result, exts) = ([], set())
for coeff in coeffs:
if coeff.is_Rational:
coeff = (None, 0, QQ.from_sympy(coeff))
... | 2,948,707,779,347,088,000 | We know that coefficients are algebraic so construct the extension. | sympy/polys/constructor.py | _construct_algebraic | ABKor752/sympy | python | def _construct_algebraic(coeffs, opt):
' '
from sympy.polys.numberfields import primitive_element
(result, exts) = ([], set())
for coeff in coeffs:
if coeff.is_Rational:
coeff = (None, 0, QQ.from_sympy(coeff))
else:
a = coeff.as_coeff_add()[0]
coeff -=... |
def _construct_composite(coeffs, opt):
'Handle composite domains, e.g.: ZZ[X], QQ[X], ZZ(X), QQ(X). '
(numers, denoms) = ([], [])
for coeff in coeffs:
(numer, denom) = coeff.as_numer_denom()
numers.append(numer)
denoms.append(denom)
(polys, gens) = parallel_dict_from_basic((numer... | -2,506,318,975,181,357,000 | Handle composite domains, e.g.: ZZ[X], QQ[X], ZZ(X), QQ(X). | sympy/polys/constructor.py | _construct_composite | ABKor752/sympy | python | def _construct_composite(coeffs, opt):
' '
(numers, denoms) = ([], [])
for coeff in coeffs:
(numer, denom) = coeff.as_numer_denom()
numers.append(numer)
denoms.append(denom)
(polys, gens) = parallel_dict_from_basic((numers + denoms))
if (not gens):
return None
if ... |
def _construct_expression(coeffs, opt):
'The last resort case, i.e. use the expression domain. '
(domain, result) = (EX, [])
for coeff in coeffs:
result.append(domain.from_sympy(coeff))
return (domain, result) | 8,277,807,598,530,472,000 | The last resort case, i.e. use the expression domain. | sympy/polys/constructor.py | _construct_expression | ABKor752/sympy | python | def _construct_expression(coeffs, opt):
' '
(domain, result) = (EX, [])
for coeff in coeffs:
result.append(domain.from_sympy(coeff))
return (domain, result) |
@public
def construct_domain(obj, **args):
'Construct a minimal domain for the list of coefficients. '
opt = build_options(args)
if hasattr(obj, '__iter__'):
if isinstance(obj, dict):
if (not obj):
(monoms, coeffs) = ([], [])
else:
(monoms, coe... | 5,775,620,295,657,424,000 | Construct a minimal domain for the list of coefficients. | sympy/polys/constructor.py | construct_domain | ABKor752/sympy | python | @public
def construct_domain(obj, **args):
' '
opt = build_options(args)
if hasattr(obj, '__iter__'):
if isinstance(obj, dict):
if (not obj):
(monoms, coeffs) = ([], [])
else:
(monoms, coeffs) = list(zip(*list(obj.items())))
else:
... |
def __init__(self, images_dir, clustering_dir, classfication_dir, output_dir=None):
'\n thie function initializes the network class\n :param images_dir: \n :param clustering_dir: \n :param classfication_dir: \n '
self.images_dir = images_dir
self.clustering_dir = clusterin... | 3,227,855,410,215,280,600 | thie function initializes the network class
:param images_dir:
:param clustering_dir:
:param classfication_dir: | src/models/final_model.py | __init__ | dsp-uga/rope | python | def __init__(self, images_dir, clustering_dir, classfication_dir, output_dir=None):
'\n thie function initializes the network class\n :param images_dir: \n :param clustering_dir: \n :param classfication_dir: \n '
self.images_dir = images_dir
self.clustering_dir = clusterin... |
def load_model(self):
'\n this function loads model from file\n '
if os.path.isfile(self.model_file_name):
self.model = keras.models.load_model(self.model_file_name) | 1,793,141,196,649,369,000 | this function loads model from file | src/models/final_model.py | load_model | dsp-uga/rope | python | def load_model(self):
'\n \n '
if os.path.isfile(self.model_file_name):
self.model = keras.models.load_model(self.model_file_name) |
def train(self):
'\n this function trains the final network\n :return: \n '
self.load_model()
if (self.model is None):
self.model = self.UNet(input_shape=(64, 64, 3))
print(self.model.summary())
for k in range(0, 4):
for i in range(0, 14):
print(i)
... | 6,425,991,241,974,136,000 | this function trains the final network
:return: | src/models/final_model.py | train | dsp-uga/rope | python | def train(self):
'\n this function trains the final network\n :return: \n '
self.load_model()
if (self.model is None):
self.model = self.UNet(input_shape=(64, 64, 3))
print(self.model.summary())
for k in range(0, 4):
for i in range(0, 14):
print(i)
... |
def predict(self):
'\n this function runs the prediction over the sets\n :return: \n '
if (self.model is None):
self.load_model()
if (self.model is None):
return None
i = 0
X_train = np.load(os.path.join(self.images_dir, (('X_' + str(i)) + '.npy')))
X1_train ... | -5,065,718,216,160,854,000 | this function runs the prediction over the sets
:return: | src/models/final_model.py | predict | dsp-uga/rope | python | def predict(self):
'\n this function runs the prediction over the sets\n :return: \n '
if (self.model is None):
self.load_model()
if (self.model is None):
return None
i = 0
X_train = np.load(os.path.join(self.images_dir, (('X_' + str(i)) + '.npy')))
X1_train ... |
def plot_et(self, LAXIS, xbl, xbr, ybu, ybd, ilg):
'Plot mean total energy stratification in the model'
grd1 = self.xzn0
plt1 = self.fht_et
plt.figure(figsize=(7, 6))
plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))
to_plot = [plt1]
self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, t... | -8,758,915,946,996,778,000 | Plot mean total energy stratification in the model | CANUTO1997/LuminosityEquation.py | plot_et | mmicromegas/ransX | python | def plot_et(self, LAXIS, xbl, xbr, ybu, ybd, ilg):
grd1 = self.xzn0
plt1 = self.fht_et
plt.figure(figsize=(7, 6))
plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))
to_plot = [plt1]
self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot)
plt.title('total energy')
plt.plot(g... |
def plot_luminosity_equation_exact(self, LAXIS, xbl, xbr, ybu, ybd, ilg):
'Plot luminosity equation in the model'
grd1 = self.xzn0
rhs0 = self.minus_cp_rho_dTdt
rhs1 = self.plus_delta_dPdt
rhs2 = self.minus_dd_div_eiui
rhs3 = self.plus_tke_diss
res = self.minus_resLumExactEquation
plt.fi... | -119,366,724,537,761,120 | Plot luminosity equation in the model | CANUTO1997/LuminosityEquation.py | plot_luminosity_equation_exact | mmicromegas/ransX | python | def plot_luminosity_equation_exact(self, LAXIS, xbl, xbr, ybu, ybd, ilg):
grd1 = self.xzn0
rhs0 = self.minus_cp_rho_dTdt
rhs1 = self.plus_delta_dPdt
rhs2 = self.minus_dd_div_eiui
rhs3 = self.plus_tke_diss
res = self.minus_resLumExactEquation
plt.figure(figsize=(7, 6))
plt.gca().yaxi... |
def setup_vertex_buffer(gl, data, shader, shader_variable):
'Setup a vertex buffer with `data` vertices as `shader_variable` on shader'
vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)
vbo.create()
with bind(vbo):
vertices = np.array(data, np.float32)
(count, dim_vertex) = vertices.shape
... | 3,822,176,870,625,612,000 | Setup a vertex buffer with `data` vertices as `shader_variable` on shader | caimageviewer/gl_util.py | setup_vertex_buffer | klauer/caproto-image-viewer | python | def setup_vertex_buffer(gl, data, shader, shader_variable):
vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)
vbo.create()
with bind(vbo):
vertices = np.array(data, np.float32)
(count, dim_vertex) = vertices.shape
vbo.allocate(vertices.flatten(), vertices.nbytes)
attr_loc ... |
def update_vertex_buffer(vbo, data):
'Update a vertex buffer with `data` vertices'
vertices = np.asarray(data, np.float32)
(count, dim_vertex) = vertices.shape
with bind(vbo):
vbo.allocate(vertices.flatten(), vertices.nbytes) | 4,712,907,263,101,164,000 | Update a vertex buffer with `data` vertices | caimageviewer/gl_util.py | update_vertex_buffer | klauer/caproto-image-viewer | python | def update_vertex_buffer(vbo, data):
vertices = np.asarray(data, np.float32)
(count, dim_vertex) = vertices.shape
with bind(vbo):
vbo.allocate(vertices.flatten(), vertices.nbytes) |
def copy_data_to_pbo(pbo, data, *, mapped_array=None):
'Allocate or update data stored in a pixel buffer object'
(width, height) = data.shape
with bind(pbo):
if (pbo.isCreated() and (mapped_array is not None)):
mapped_array[:] = data.reshape((width, height))
return mapped_arr... | 5,597,396,672,997,456,000 | Allocate or update data stored in a pixel buffer object | caimageviewer/gl_util.py | copy_data_to_pbo | klauer/caproto-image-viewer | python | def copy_data_to_pbo(pbo, data, *, mapped_array=None):
(width, height) = data.shape
with bind(pbo):
if (pbo.isCreated() and (mapped_array is not None)):
mapped_array[:] = data.reshape((width, height))
return mapped_array
full_size = data.nbytes
pointer_type = np.ctyp... |
def update_pbo_texture(gl, pbo, texture, *, array_data, texture_format, source_format, source_type):
'Update a texture associated with a PBO'
(width, height) = array_data.shape[:2]
if (source_format == gl.GL_RGB):
height //= 3
with bind(pbo, texture):
gl.glPixelStorei(gl.GL_UNPACK_ALIGNM... | 3,789,928,796,293,781,500 | Update a texture associated with a PBO | caimageviewer/gl_util.py | update_pbo_texture | klauer/caproto-image-viewer | python | def update_pbo_texture(gl, pbo, texture, *, array_data, texture_format, source_format, source_type):
(width, height) = array_data.shape[:2]
if (source_format == gl.GL_RGB):
height //= 3
with bind(pbo, texture):
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
gl.glTexParameteri(gl.GL... |
@contextmanager
def bind(*objs, args=None):
'Bind all objs (optionally with positional arguments); releases at cleanup'
if (args is None):
args = (None for obj in objs)
for (obj, arg) in zip(objs, args):
if (arg is not None):
obj.bind(arg)
else:
obj.bind()
... | 1,272,922,605,012,459,800 | Bind all objs (optionally with positional arguments); releases at cleanup | caimageviewer/gl_util.py | bind | klauer/caproto-image-viewer | python | @contextmanager
def bind(*objs, args=None):
if (args is None):
args = (None for obj in objs)
for (obj, arg) in zip(objs, args):
if (arg is not None):
obj.bind(arg)
else:
obj.bind()
(yield)
for obj in objs[::(- 1)]:
obj.release() |
def _generate_code_verifier():
"\n Generates a 'code_verifier' as described in https://tools.ietf.org/html/rfc7636#section-4.1\n Adapted from https://github.com/openstack/deb-python-oauth2client/blob/master/oauth2client/_pkce.py.\n :return str:\n "
code_verifier = _base64.urlsafe_b64encode(_os.urand... | -140,427,470,149,594,020 | Generates a 'code_verifier' as described in https://tools.ietf.org/html/rfc7636#section-4.1
Adapted from https://github.com/openstack/deb-python-oauth2client/blob/master/oauth2client/_pkce.py.
:return str: | flytekit/clis/auth/auth.py | _generate_code_verifier | AdrianoKF/flytekit | python | def _generate_code_verifier():
"\n Generates a 'code_verifier' as described in https://tools.ietf.org/html/rfc7636#section-4.1\n Adapted from https://github.com/openstack/deb-python-oauth2client/blob/master/oauth2client/_pkce.py.\n :return str:\n "
code_verifier = _base64.urlsafe_b64encode(_os.urand... |
def _create_code_challenge(code_verifier):
'\n Adapted from https://github.com/openstack/deb-python-oauth2client/blob/master/oauth2client/_pkce.py.\n :param str code_verifier: represents a code verifier generated by generate_code_verifier()\n :return str: urlsafe base64-encoded sha256 hash digest\n '
... | 4,351,893,662,429,492,700 | Adapted from https://github.com/openstack/deb-python-oauth2client/blob/master/oauth2client/_pkce.py.
:param str code_verifier: represents a code verifier generated by generate_code_verifier()
:return str: urlsafe base64-encoded sha256 hash digest | flytekit/clis/auth/auth.py | _create_code_challenge | AdrianoKF/flytekit | python | def _create_code_challenge(code_verifier):
'\n Adapted from https://github.com/openstack/deb-python-oauth2client/blob/master/oauth2client/_pkce.py.\n :param str code_verifier: represents a code verifier generated by generate_code_verifier()\n :return str: urlsafe base64-encoded sha256 hash digest\n '
... |
def _initialize_credentials(self, auth_token_resp):
'\n The auth_token_resp body is of the form:\n {\n "access_token": "foo",\n "refresh_token": "bar",\n "token_type": "Bearer"\n }\n '
response_body = auth_token_resp.json()
if ('access_token' not in res... | 3,593,339,050,330,529,000 | The auth_token_resp body is of the form:
{
"access_token": "foo",
"refresh_token": "bar",
"token_type": "Bearer"
} | flytekit/clis/auth/auth.py | _initialize_credentials | AdrianoKF/flytekit | python | def _initialize_credentials(self, auth_token_resp):
'\n The auth_token_resp body is of the form:\n {\n "access_token": "foo",\n "refresh_token": "bar",\n "token_type": "Bearer"\n }\n '
response_body = auth_token_resp.json()
if ('access_token' not in res... |
@property
def credentials(self):
'\n :return flytekit.clis.auth.auth.Credentials:\n '
return self._credentials | -7,460,607,824,305,833,000 | :return flytekit.clis.auth.auth.Credentials: | flytekit/clis/auth/auth.py | credentials | AdrianoKF/flytekit | python | @property
def credentials(self):
'\n \n '
return self._credentials |
@property
def expired(self):
'\n :return bool:\n '
return self._expired | 5,468,941,397,680,082,000 | :return bool: | flytekit/clis/auth/auth.py | expired | AdrianoKF/flytekit | python | @property
def expired(self):
'\n \n '
return self._expired |
def get(self, request, group_id, format=None):
' List all group members\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
group_id = ... | 716,541,368,521,144,400 | List all group members
Permission checking:
1. only admin can perform this action. | seahub/api2/endpoints/admin/group_members.py | get | DMKun/seahub | python | def get(self, request, group_id, format=None):
' List all group members\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
group_id = ... |
def post(self, request, group_id):
'\n Bulk add group members.\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
group_id = in... | 4,027,174,524,807,285,000 | Bulk add group members.
Permission checking:
1. only admin can perform this action. | seahub/api2/endpoints/admin/group_members.py | post | DMKun/seahub | python | def post(self, request, group_id):
'\n Bulk add group members.\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
group_id = in... |
def put(self, request, group_id, email, format=None):
' update role of a group member\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
... | 7,298,239,316,915,039,000 | update role of a group member
Permission checking:
1. only admin can perform this action. | seahub/api2/endpoints/admin/group_members.py | put | DMKun/seahub | python | def put(self, request, group_id, email, format=None):
' update role of a group member\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
... |
def delete(self, request, group_id, email, format=None):
' Delete an user from group\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
... | -1,522,323,534,279,099,600 | Delete an user from group
Permission checking:
1. only admin can perform this action. | seahub/api2/endpoints/admin/group_members.py | delete | DMKun/seahub | python | def delete(self, request, group_id, email, format=None):
' Delete an user from group\n\n Permission checking:\n 1. only admin can perform this action.\n '
if (not request.user.admin_permissions.can_manage_group()):
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
... |
def _get_databases(self, context):
'Returns the initial databases for this instance.'
databases = None
if context.get('databases'):
dbs = context['databases']
databases = [{'name': d.strip()} for d in dbs.split(',')]
return databases | 6,399,540,008,223,094,000 | Returns the initial databases for this instance. | openstack_dashboard/contrib/trove/content/databases/workflows/create_instance.py | _get_databases | ChinaMassClouds/horizon | python | def _get_databases(self, context):
databases = None
if context.get('databases'):
dbs = context['databases']
databases = [{'name': d.strip()} for d in dbs.split(',')]
return databases |
def test_init(self, event_loop):
'Test that creating an instance of Purge calls init of FoglampProcess and creates loggers'
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.object(FoglampProcess, '__init__') as mock_process:
with patch... | 5,284,015,934,107,695,000 | Test that creating an instance of Purge calls init of FoglampProcess and creates loggers | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_init | ThyagOSI/FogLAMP | python | def test_init(self, event_loop):
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.object(FoglampProcess, '__init__') as mock_process:
with patch.object(logger, 'setup') as log:
with patch.object(mockAuditLogger, '__init__'... |
def test_write_statistics(self, event_loop):
'Test that write_statistics calls update statistics with defined keys and value increments'
@asyncio.coroutine
def mock_s_update():
return ''
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
w... | 1,872,808,031,474,282,500 | Test that write_statistics calls update statistics with defined keys and value increments | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_write_statistics | ThyagOSI/FogLAMP | python | def test_write_statistics(self, event_loop):
@asyncio.coroutine
def mock_s_update():
return
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.object(FoglampProcess, '__init__'):
with patch.object(Statistics, 'update',... |
def test_set_configuration(self, event_loop):
"Test that purge's set_configuration returns configuration item with key 'PURGE_READ' "
@asyncio.coroutine
def mock_cm_return():
return ''
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
wit... | -5,957,796,145,405,066,000 | Test that purge's set_configuration returns configuration item with key 'PURGE_READ' | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_set_configuration | ThyagOSI/FogLAMP | python | def test_set_configuration(self, event_loop):
" "
@asyncio.coroutine
def mock_cm_return():
return
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.object(FoglampProcess, '__init__'):
with patch.object(mockAuditLogger,... |
@pytest.mark.parametrize('conf, expected_return, expected_calls', [(config['purgeAgeSize'], (2, 4), {'sent_id': 0, 'size': '20', 'flag': 'purge'}), (config['purgeAge'], (1, 2), {'sent_id': 0, 'age': '72', 'flag': 'purge'}), (config['purgeSize'], (1, 2), {'sent_id': 0, 'size': '100', 'flag': 'purge'}), (config['retainAg... | -469,366,175,127,310,850 | Test that purge_data calls Storage's purge with defined configuration | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_purge_data | ThyagOSI/FogLAMP | python | @pytest.mark.parametrize('conf, expected_return, expected_calls', [(config['purgeAgeSize'], (2, 4), {'sent_id': 0, 'size': '20', 'flag': 'purge'}), (config['purgeAge'], (1, 2), {'sent_id': 0, 'age': '72', 'flag': 'purge'}), (config['purgeSize'], (1, 2), {'sent_id': 0, 'size': '100', 'flag': 'purge'}), (config['retainAg... |
@pytest.mark.parametrize('conf, expected_return', [({'retainUnsent': {'value': 'False'}, 'age': {'value': '0'}, 'size': {'value': '0'}}, (0, 0)), ({'retainUnsent': {'value': 'True'}, 'age': {'value': '0'}, 'size': {'value': '0'}}, (0, 0))])
def test_purge_data_no_data_purged(self, event_loop, conf, expected_return):
... | 8,077,367,409,494,260,000 | Test that purge_data logs message when no data was purged | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_purge_data_no_data_purged | ThyagOSI/FogLAMP | python | @pytest.mark.parametrize('conf, expected_return', [({'retainUnsent': {'value': 'False'}, 'age': {'value': '0'}, 'size': {'value': '0'}}, (0, 0)), ({'retainUnsent': {'value': 'True'}, 'age': {'value': '0'}, 'size': {'value': '0'}}, (0, 0))])
def test_purge_data_no_data_purged(self, event_loop, conf, expected_return):
... |
@pytest.mark.parametrize('conf, expected_return', [({'retainUnsent': {'value': 'True'}, 'age': {'value': '-1'}, 'size': {'value': '-1'}}, (0, 0))])
def test_purge_error_storage_response(self, event_loop, conf, expected_return):
'Test that purge_data logs error when storage purge returns an error response'
@asy... | -4,718,137,762,322,573,000 | Test that purge_data logs error when storage purge returns an error response | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_purge_error_storage_response | ThyagOSI/FogLAMP | python | @pytest.mark.parametrize('conf, expected_return', [({'retainUnsent': {'value': 'True'}, 'age': {'value': '-1'}, 'size': {'value': '-1'}}, (0, 0))])
def test_purge_error_storage_response(self, event_loop, conf, expected_return):
@asyncio.coroutine
def mock_audit_info():
return
mockStorageClien... |
@pytest.mark.parametrize('conf, expected_error_key', [({'retainUnsent': {'value': 'True'}, 'age': {'value': 'bla'}, 'size': {'value': '0'}}, 'age'), ({'retainUnsent': {'value': 'True'}, 'age': {'value': '0'}, 'size': {'value': 'bla'}}, 'size')])
def test_purge_data_invalid_conf(self, event_loop, conf, expected_error_ke... | -9,136,429,344,613,736,000 | Test that purge_data raises exception when called with invalid configuration | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_purge_data_invalid_conf | ThyagOSI/FogLAMP | python | @pytest.mark.parametrize('conf, expected_error_key', [({'retainUnsent': {'value': 'True'}, 'age': {'value': 'bla'}, 'size': {'value': '0'}}, 'age'), ({'retainUnsent': {'value': 'True'}, 'age': {'value': '0'}, 'size': {'value': 'bla'}}, 'size')])
def test_purge_data_invalid_conf(self, event_loop, conf, expected_error_ke... |
def test_run(self, event_loop):
'Test that run calls all units of purge process'
@asyncio.coroutine
def mock_audit_info():
return ''
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.object(FoglampProcess, '__init__'):
... | 346,495,409,171,678,200 | Test that run calls all units of purge process | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_run | ThyagOSI/FogLAMP | python | def test_run(self, event_loop):
@asyncio.coroutine
def mock_audit_info():
return
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.object(FoglampProcess, '__init__'):
with patch.object(mockAuditLogger, '__init__', ret... |
def test_run_exception(self, event_loop):
'Test that run calls all units of purge process and checks the exception handling'
@asyncio.coroutine
def mock_audit_info():
return ''
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.... | -5,734,047,374,759,279,000 | Test that run calls all units of purge process and checks the exception handling | tests/unit/python/foglamp/tasks/purge/test_purge.py | test_run_exception | ThyagOSI/FogLAMP | python | def test_run_exception(self, event_loop):
@asyncio.coroutine
def mock_audit_info():
return
mockStorageClient = MagicMock(spec=StorageClient)
mockAuditLogger = AuditLogger(mockStorageClient)
with patch.object(FoglampProcess, '__init__'):
with patch.object(mockAuditLogger, '__in... |
def updates_configured():
'Returns True if update checking have been configured.'
return (prepare_updater() is not None) | 1,418,974,148,192,326,000 | Returns True if update checking have been configured. | core/update.py | updates_configured | McArcady/python-lnp | python | def updates_configured():
return (prepare_updater() is not None) |
def check_update():
'Checks for updates using the URL specified in PyLNP.json.'
if (not updates_configured()):
return
if (not lnp.userconfig.has_value('updateDays')):
interval = lnp.config.get_value('updates/defaultInterval', (- 1))
if ((interval != (- 1)) and lnp.ui.on_request_updat... | -8,196,296,363,672,645,000 | Checks for updates using the URL specified in PyLNP.json. | core/update.py | check_update | McArcady/python-lnp | python | def check_update():
if (not updates_configured()):
return
if (not lnp.userconfig.has_value('updateDays')):
interval = lnp.config.get_value('updates/defaultInterval', (- 1))
if ((interval != (- 1)) and lnp.ui.on_request_update_permission(interval)):
next_update(interval)
... |
def perform_update_check():
'Performs the actual update check. Runs in a thread.'
prepare_updater()
if lnp.updater.update_needed():
lnp.new_version = lnp.updater.get_version()
lnp.ui.on_update_available() | -2,845,390,626,586,245,600 | Performs the actual update check. Runs in a thread. | core/update.py | perform_update_check | McArcady/python-lnp | python | def perform_update_check():
prepare_updater()
if lnp.updater.update_needed():
lnp.new_version = lnp.updater.get_version()
lnp.ui.on_update_available() |
def prepare_updater():
'Returns an Updater object for the configured updater.'
if lnp.updater:
return lnp.updater
updaters = {'regex': RegexUpdater, 'json': JSONUpdater, 'dffd': DFFDUpdater}
updater_id = lnp.config.get('updates/updateMethod', None)
if (updater_id is None):
log.w('Upd... | -3,500,684,316,671,097,300 | Returns an Updater object for the configured updater. | core/update.py | prepare_updater | McArcady/python-lnp | python | def prepare_updater():
if lnp.updater:
return lnp.updater
updaters = {'regex': RegexUpdater, 'json': JSONUpdater, 'dffd': DFFDUpdater}
updater_id = lnp.config.get('updates/updateMethod', None)
if (updater_id is None):
log.w('Update method not configured in PyLNP.json! Will attempt t... |
def next_update(days):
'Sets the next update check to occur in <days> days.'
lnp.userconfig['nextUpdate'] = (time.time() + (((days * 24) * 60) * 60))
lnp.userconfig['updateDays'] = days
lnp.save_config() | 6,134,476,219,030,161,000 | Sets the next update check to occur in <days> days. | core/update.py | next_update | McArcady/python-lnp | python | def next_update(days):
lnp.userconfig['nextUpdate'] = (time.time() + (((days * 24) * 60) * 60))
lnp.userconfig['updateDays'] = days
lnp.save_config() |
def start_update():
'Launches a webbrowser to the specified update URL.'
launcher.open_url(lnp.updater.get_download_url()) | 3,976,281,430,918,038,000 | Launches a webbrowser to the specified update URL. | core/update.py | start_update | McArcady/python-lnp | python | def start_update():
launcher.open_url(lnp.updater.get_download_url()) |
def download_df_baseline(immediate=False):
'Download the current version of DF from Bay12 Games to serve as a\n baseline, in LNP/Baselines/'
filename = lnp.df_info.get_archive_name()
url = ('http://www.bay12games.com/dwarves/' + filename)
target = os.path.join(paths.get('baselines'), filename)
qu... | 2,693,516,806,954,899,000 | Download the current version of DF from Bay12 Games to serve as a
baseline, in LNP/Baselines/ | core/update.py | download_df_baseline | McArcady/python-lnp | python | def download_df_baseline(immediate=False):
'Download the current version of DF from Bay12 Games to serve as a\n baseline, in LNP/Baselines/'
filename = lnp.df_info.get_archive_name()
url = ('http://www.bay12games.com/dwarves/' + filename)
target = os.path.join(paths.get('baselines'), filename)
qu... |
def direct_download_pack():
'Directly download a new version of the pack to the current BASEDIR'
url = lnp.updater.get_direct_url()
fname = lnp.updater.get_direct_filename()
target = os.path.join(lnp.BASEDIR, fname)
download.download('updates', url, target, end_callback=extract_new_pack) | -514,763,240,004,540,100 | Directly download a new version of the pack to the current BASEDIR | core/update.py | direct_download_pack | McArcady/python-lnp | python | def direct_download_pack():
url = lnp.updater.get_direct_url()
fname = lnp.updater.get_direct_filename()
target = os.path.join(lnp.BASEDIR, fname)
download.download('updates', url, target, end_callback=extract_new_pack) |
def extract_new_pack(_, fname, bool_val):
'Extract a downloaded new pack to a sibling dir of the current pack.'
exts = ('.zip', '.bz2', '.gz', '.7z', '.xz')
if ((not bool_val) or (not any((fname.endswith(ext) for ext in exts)))):
return None
archive = os.path.join(lnp.BASEDIR, os.path.basename(f... | 929,262,011,020,408,300 | Extract a downloaded new pack to a sibling dir of the current pack. | core/update.py | extract_new_pack | McArcady/python-lnp | python | def extract_new_pack(_, fname, bool_val):
exts = ('.zip', '.bz2', '.gz', '.7z', '.xz')
if ((not bool_val) or (not any((fname.endswith(ext) for ext in exts)))):
return None
archive = os.path.join(lnp.BASEDIR, os.path.basename(fname))
return extract_archive(archive, os.path.join(lnp.BASEDIR, ... |
def extract_archive(fname, target):
'Extract the archive fname to dir target, avoiding explosions.'
if zipfile.is_zipfile(fname):
zf = zipfile.ZipFile(fname)
namelist = zf.namelist()
topdir = namelist[0].split(os.path.sep)[0]
if (not all((f.startswith(topdir) for f in namelist)))... | -4,466,180,850,622,522,400 | Extract the archive fname to dir target, avoiding explosions. | core/update.py | extract_archive | McArcady/python-lnp | python | def extract_archive(fname, target):
if zipfile.is_zipfile(fname):
zf = zipfile.ZipFile(fname)
namelist = zf.namelist()
topdir = namelist[0].split(os.path.sep)[0]
if (not all((f.startswith(topdir) for f in namelist))):
target = os.path.join(target, os.path.basename(fn... |
def update_needed(self):
'Checks if an update is necessary.'
self.text = download.download_str(self.get_check_url())
if (self.text is None):
log.e('Error checking for updates, could not download text')
curr_version = lnp.config.get_string('updates/packVersion')
if (not curr_version):
... | -603,070,208,608,805,800 | Checks if an update is necessary. | core/update.py | update_needed | McArcady/python-lnp | python | def update_needed(self):
self.text = download.download_str(self.get_check_url())
if (self.text is None):
log.e('Error checking for updates, could not download text')
curr_version = lnp.config.get_string('updates/packVersion')
if (not curr_version):
log.e('Current pack version is not... |
def get_check_url(self):
'Returns the URL used to check for updates.'
return lnp.config.get_string('updates/checkURL') | -2,481,073,543,452,999,000 | Returns the URL used to check for updates. | core/update.py | get_check_url | McArcady/python-lnp | python | def get_check_url(self):
return lnp.config.get_string('updates/checkURL') |
def get_version(self):
'Returns the version listed at the update URL. Must be overridden by\n subclasses.'
pass | 6,166,192,657,965,314,000 | Returns the version listed at the update URL. Must be overridden by
subclasses. | core/update.py | get_version | McArcady/python-lnp | python | def get_version(self):
'Returns the version listed at the update URL. Must be overridden by\n subclasses.'
pass |
def get_download_url(self):
'Returns a URL from which the user can download the update.'
return lnp.config.get_string('updates/downloadURL') | 6,181,411,547,175,209,000 | Returns a URL from which the user can download the update. | core/update.py | get_download_url | McArcady/python-lnp | python | def get_download_url(self):
return lnp.config.get_string('updates/downloadURL') |
def get_direct_url(self):
'Returns a URL pointing directly to the update, for download by the\n program.'
return lnp.config.get_string('updates/directURL') | 4,640,743,652,360,267,000 | Returns a URL pointing directly to the update, for download by the
program. | core/update.py | get_direct_url | McArcady/python-lnp | python | def get_direct_url(self):
'Returns a URL pointing directly to the update, for download by the\n program.'
return lnp.config.get_string('updates/directURL') |
def get_direct_filename(self):
'Returns the filename that should be used for direct downloads.'
directFilename = lnp.config.get_string('updates/directFilename')
if directFilename:
return directFilename
url_fragments = urlparse(self.get_direct_url())
return os.path.basename(unquote(url_fragme... | 471,715,325,318,947,500 | Returns the filename that should be used for direct downloads. | core/update.py | get_direct_filename | McArcady/python-lnp | python | def get_direct_filename(self):
directFilename = lnp.config.get_string('updates/directFilename')
if directFilename:
return directFilename
url_fragments = urlparse(self.get_direct_url())
return os.path.basename(unquote(url_fragments.path)) |
def compile_model(network):
'\n :param network dict: dictionary with network parameters\n :return: compiled model\n '
model = lgb.LGBMRegressor(num_leaves=network.get('num_leaves', 31), learning_rate=network.get('learning_rate', 0.1), n_estimators=network.get('n_estimators', 20), max_bin=network.get('m... | -3,924,933,480,687,173,600 | :param network dict: dictionary with network parameters
:return: compiled model | gb_rf_evolution/gb_train.py | compile_model | EvanBagis/gb_rf_evolution | python | def compile_model(network):
'\n :param network dict: dictionary with network parameters\n :return: compiled model\n '
model = lgb.LGBMRegressor(num_leaves=network.get('num_leaves', 31), learning_rate=network.get('learning_rate', 0.1), n_estimators=network.get('n_estimators', 20), max_bin=network.get('m... |
def train_and_score(network, x_train, y_train, x_test, y_test):
'\n\n :param network dict: dictionary with network parameters\n :param x_train array: numpy array with features for traning\n :param y_train array: numpy array with labels for traning\n :param x_test array: numpy array with labels for test\... | 1,104,790,927,388,677,900 | :param network dict: dictionary with network parameters
:param x_train array: numpy array with features for traning
:param y_train array: numpy array with labels for traning
:param x_test array: numpy array with labels for test
:param y_test array: numpy array with labels for test
:return float: score | gb_rf_evolution/gb_train.py | train_and_score | EvanBagis/gb_rf_evolution | python | def train_and_score(network, x_train, y_train, x_test, y_test):
'\n\n :param network dict: dictionary with network parameters\n :param x_train array: numpy array with features for traning\n :param y_train array: numpy array with labels for traning\n :param x_test array: numpy array with labels for test\... |
@cached_property
def additional_properties_type():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n '
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type) | 1,702,168,743,392,494,600 | This must be a method because a model may have properties that are
of type self, this must run after the class is loaded | code/python/QuotesAPIforDigitalPortals/v2/fds/sdk/QuotesAPIforDigitalPortals/model/prices_trading_schedule_event_list_data.py | additional_properties_type | factset/enterprise-sdk | python | @cached_property
def additional_properties_type():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n '
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type) |
@cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ... | 6,639,963,327,444,114,000 | This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. | code/python/QuotesAPIforDigitalPortals/v2/fds/sdk/QuotesAPIforDigitalPortals/model/prices_trading_schedule_event_list_data.py | openapi_types | factset/enterprise-sdk | python | @cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ... |
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, id, *args, **kwargs):
'PricesTradingScheduleEventListData - a model defined in OpenAPI\n\n Args:\n id (str): Identifier of the notation.\n\n Keyword Args:\n _check_type (bool): if True, values for parameters... | 3,884,444,163,335,825,000 | PricesTradingScheduleEventListData - a model defined in OpenAPI
Args:
id (str): Identifier of the notation.
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is... | code/python/QuotesAPIforDigitalPortals/v2/fds/sdk/QuotesAPIforDigitalPortals/model/prices_trading_schedule_event_list_data.py | _from_openapi_data | factset/enterprise-sdk | python | @classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, id, *args, **kwargs):
'PricesTradingScheduleEventListData - a model defined in OpenAPI\n\n Args:\n id (str): Identifier of the notation.\n\n Keyword Args:\n _check_type (bool): if True, values for parameters... |
@convert_js_args_to_python_args
def __init__(self, id, *args, **kwargs):
'PricesTradingScheduleEventListData - a model defined in OpenAPI\n\n Args:\n id (str): Identifier of the notation.\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n ... | 3,673,162,969,030,290,000 | PricesTradingScheduleEventListData - a model defined in OpenAPI
Args:
id (str): Identifier of the notation.
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is... | code/python/QuotesAPIforDigitalPortals/v2/fds/sdk/QuotesAPIforDigitalPortals/model/prices_trading_schedule_event_list_data.py | __init__ | factset/enterprise-sdk | python | @convert_js_args_to_python_args
def __init__(self, id, *args, **kwargs):
'PricesTradingScheduleEventListData - a model defined in OpenAPI\n\n Args:\n id (str): Identifier of the notation.\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n ... |
def __init__(self, error):
'Instantiate super class with passed message.'
self.message = 'No domains were passed!'
super().__init__(self.message) | -5,821,761,965,115,697,000 | Instantiate super class with passed message. | src/findcdn/findcdn_err.py | __init__ | Pascal-0x90/findCDN | python | def __init__(self, error):
self.message = 'No domains were passed!'
super().__init__(self.message) |
def __init__(self, outFile):
'Instantiate super class with passed message with passed in filename.'
self.message = (('A file with the name ' + outFile) + ' already exists!')
super().__init__(self.message) | -103,428,230,241,982,430 | Instantiate super class with passed message with passed in filename. | src/findcdn/findcdn_err.py | __init__ | Pascal-0x90/findCDN | python | def __init__(self, outFile):
self.message = (('A file with the name ' + outFile) + ' already exists!')
super().__init__(self.message) |
def __init__(self, item):
'Instantiate super class with passed message with passed in item.'
self.message = (item + ' is not a valid domain in findcdn.main()')
super().__init__(self.message) | -3,419,750,793,731,725,300 | Instantiate super class with passed message with passed in item. | src/findcdn/findcdn_err.py | __init__ | Pascal-0x90/findCDN | python | def __init__(self, item):
self.message = (item + ' is not a valid domain in findcdn.main()')
super().__init__(self.message) |
def __init__(self, error):
'Instantiate super class with passed message using passed in error.'
self.message = ('The following error occurred in findcdn while file writing:\n' + repr(error))
super().__init__(self.message) | -4,781,970,469,078,838,000 | Instantiate super class with passed message using passed in error. | src/findcdn/findcdn_err.py | __init__ | Pascal-0x90/findCDN | python | def __init__(self, error):
self.message = ('The following error occurred in findcdn while file writing:\n' + repr(error))
super().__init__(self.message) |
def match_target_amplitude(aChunk, target_dBFS):
' Normalize given audio chunk '
change_in_dBFS = (target_dBFS - aChunk.dBFS)
return aChunk.apply_gain(change_in_dBFS) | 5,784,923,878,507,612,000 | Normalize given audio chunk | src/subtitle.py | match_target_amplitude | whilemind/subtitle | python | def match_target_amplitude(aChunk, target_dBFS):
' '
change_in_dBFS = (target_dBFS - aChunk.dBFS)
return aChunk.apply_gain(change_in_dBFS) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.