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 _remove_temp_handler(): '\n Remove temporary handler if it exists\n ' if (TEMP_HANDLER and (TEMP_HANDLER in logging.root.handlers)): logging.root.handlers.remove(TEMP_HANDLER)
-8,479,857,811,240,753,000
Remove temporary handler if it exists
hubblestack/log.py
_remove_temp_handler
instructure/hubble
python
def _remove_temp_handler(): '\n \n ' if (TEMP_HANDLER and (TEMP_HANDLER in logging.root.handlers)): logging.root.handlers.remove(TEMP_HANDLER)
def setup_console_logger(log_level='error', log_format='%(asctime)s [%(levelname)-5s] %(message)s', date_format='%H:%M:%S'): '\n Sets up logging to STDERR, allowing for configurable level, format, and\n date format.\n ' _remove_temp_handler() rootlogger = logging.getLogger() handler = logging.S...
547,214,475,094,259,900
Sets up logging to STDERR, allowing for configurable level, format, and date format.
hubblestack/log.py
setup_console_logger
instructure/hubble
python
def setup_console_logger(log_level='error', log_format='%(asctime)s [%(levelname)-5s] %(message)s', date_format='%H:%M:%S'): '\n Sets up logging to STDERR, allowing for configurable level, format, and\n date format.\n ' _remove_temp_handler() rootlogger = logging.getLogger() handler = logging.S...
def setup_file_logger(log_file, log_level='error', log_format='%(asctime)s,%(msecs)03d [%(levelname)-5s] [%(name)s:%(lineno)d] %(message)s', date_format='%Y-%m-%d %H:%M:%S', max_bytes=100000000, backup_count=1): '\n Sets up logging to a file. By default will auto-rotate those logs every\n 100MB and keep one ...
-1,951,438,289,589,759,200
Sets up logging to a file. By default will auto-rotate those logs every 100MB and keep one backup.
hubblestack/log.py
setup_file_logger
instructure/hubble
python
def setup_file_logger(log_file, log_level='error', log_format='%(asctime)s,%(msecs)03d [%(levelname)-5s] [%(name)s:%(lineno)d] %(message)s', date_format='%Y-%m-%d %H:%M:%S', max_bytes=100000000, backup_count=1): '\n Sets up logging to a file. By default will auto-rotate those logs every\n 100MB and keep one ...
def setup_splunk_logger(): '\n Sets up logging to splunk.\n ' _remove_temp_handler() rootlogger = logging.getLogger() handler = hubblestack.splunklogging.SplunkHandler() handler.setLevel(logging.SPLUNK) rootlogger.addHandler(handler) global SPLUNK_HANDLER SPLUNK_HANDLER = handler
-5,930,119,731,152,631,000
Sets up logging to splunk.
hubblestack/log.py
setup_splunk_logger
instructure/hubble
python
def setup_splunk_logger(): '\n \n ' _remove_temp_handler() rootlogger = logging.getLogger() handler = hubblestack.splunklogging.SplunkHandler() handler.setLevel(logging.SPLUNK) rootlogger.addHandler(handler) global SPLUNK_HANDLER SPLUNK_HANDLER = handler
def emit_to_splunk(message, level, name): '\n Emit a single message to splunk\n ' if isinstance(message, (list, dict)): message = filter_logs(message, remove_dots=False) if (SPLUNK_HANDLER is None): return False handler = SPLUNK_HANDLER handler.emit(MockRecord(message, level, t...
-7,925,935,624,446,416,000
Emit a single message to splunk
hubblestack/log.py
emit_to_splunk
instructure/hubble
python
def emit_to_splunk(message, level, name): '\n \n ' if isinstance(message, (list, dict)): message = filter_logs(message, remove_dots=False) if (SPLUNK_HANDLER is None): return False handler = SPLUNK_HANDLER handler.emit(MockRecord(message, level, time.asctime(), name)) retur...
def workaround_salt_log_handler_queues(): '\n Build a fake log handler and add it to LOGGING_STORE_HANDLER and LOGGING_NULL_HANDLER\n ' class _FakeLogHandler(object): level = 10 count = 0 def handle(self, _record): ' Receive a record and increase the count ' ...
905,797,758,034,563,600
Build a fake log handler and add it to LOGGING_STORE_HANDLER and LOGGING_NULL_HANDLER
hubblestack/log.py
workaround_salt_log_handler_queues
instructure/hubble
python
def workaround_salt_log_handler_queues(): '\n \n ' class _FakeLogHandler(object): level = 10 count = 0 def handle(self, _record): ' Receive a record and increase the count ' self.count += 1 flh = _FakeLogHandler() import salt.log.setup as sls s...
def filter_logs(opts_to_log, remove_dots=True): '\n Filters out keys containing certain patterns to avoid sensitive information being sent to logs\n Works on dictionaries and lists\n This function was located at extmods/modules/conf_publisher.py previously\n ' filtered_conf = _remove_sensitive_info(...
5,361,334,341,806,947,000
Filters out keys containing certain patterns to avoid sensitive information being sent to logs Works on dictionaries and lists This function was located at extmods/modules/conf_publisher.py previously
hubblestack/log.py
filter_logs
instructure/hubble
python
def filter_logs(opts_to_log, remove_dots=True): '\n Filters out keys containing certain patterns to avoid sensitive information being sent to logs\n Works on dictionaries and lists\n This function was located at extmods/modules/conf_publisher.py previously\n ' filtered_conf = _remove_sensitive_info(...
def _remove_sensitive_info(obj, patterns_to_filter): '\n Filter known sensitive info\n ' if isinstance(obj, dict): obj = {key: _remove_sensitive_info(value, patterns_to_filter) for (key, value) in obj.items() if (not any(((patt in key) for patt in patterns_to_filter)))} elif isinstance(obj, li...
3,576,416,888,570,603,000
Filter known sensitive info
hubblestack/log.py
_remove_sensitive_info
instructure/hubble
python
def _remove_sensitive_info(obj, patterns_to_filter): '\n \n ' if isinstance(obj, dict): obj = {key: _remove_sensitive_info(value, patterns_to_filter) for (key, value) in obj.items() if (not any(((patt in key) for patt in patterns_to_filter)))} elif isinstance(obj, list): obj = [_remove...
def handle(self, _record): ' Receive a record and increase the count ' self.count += 1
3,950,741,304,086,814,000
Receive a record and increase the count
hubblestack/log.py
handle
instructure/hubble
python
def handle(self, _record): ' ' self.count += 1
@power_session(envs=ENVS, logsdir=Folders.runlogs) def tests(session: PowerSession, coverage, pkg_specs): 'Run the test suite, including test reports generation and coverage reports. ' rm_folder(Folders.site) rm_folder(Folders.reports_root) rm_file(Folders.coverage_intermediate_file) rm_file((Folder...
-4,468,099,125,579,665,400
Run the test suite, including test reports generation and coverage reports.
noxfile.py
tests
texnofobix/python-genbadge
python
@power_session(envs=ENVS, logsdir=Folders.runlogs) def tests(session: PowerSession, coverage, pkg_specs): ' ' rm_folder(Folders.site) rm_folder(Folders.reports_root) rm_file(Folders.coverage_intermediate_file) rm_file((Folders.root / 'coverage.xml')) session.install_reqs(setup=True, install=True...
@power_session(python=PY38, logsdir=Folders.runlogs) def flake8(session: PowerSession): 'Launch flake8 qualimetry.' session.install('-r', str((Folders.ci_tools / 'flake8-requirements.txt'))) session.run2('pip install -e .[flake8]') rm_folder(Folders.flake8_reports) rm_file(Folders.flake8_intermediat...
7,663,644,602,271,633,000
Launch flake8 qualimetry.
noxfile.py
flake8
texnofobix/python-genbadge
python
@power_session(python=PY38, logsdir=Folders.runlogs) def flake8(session: PowerSession): session.install('-r', str((Folders.ci_tools / 'flake8-requirements.txt'))) session.run2('pip install -e .[flake8]') rm_folder(Folders.flake8_reports) rm_file(Folders.flake8_intermediate_file) session.run('fl...
@power_session(python=[PY37]) def docs(session: PowerSession): "Generates the doc and serves it on a local http server. Pass '-- build' to build statically instead." session.install_reqs(phase='docs', phase_reqs=['mkdocs-material', 'mkdocs', 'pymdown-extensions', 'pygments']) if session.posargs: ses...
-3,700,643,923,249,329,000
Generates the doc and serves it on a local http server. Pass '-- build' to build statically instead.
noxfile.py
docs
texnofobix/python-genbadge
python
@power_session(python=[PY37]) def docs(session: PowerSession): session.install_reqs(phase='docs', phase_reqs=['mkdocs-material', 'mkdocs', 'pymdown-extensions', 'pygments']) if session.posargs: session.run2(('mkdocs -f ./docs/mkdocs.yml %s' % ' '.join(session.posargs))) else: session.ru...
@power_session(python=[PY37]) def publish(session: PowerSession): 'Deploy the docs+reports on github pages. Note: this rebuilds the docs' session.install_reqs(phase='mkdocs', phase_reqs=['mkdocs-material', 'mkdocs', 'pymdown-extensions', 'pygments']) session.run2('mkdocs build -f ./docs/mkdocs.yml') if ...
-5,760,951,214,420,701,000
Deploy the docs+reports on github pages. Note: this rebuilds the docs
noxfile.py
publish
texnofobix/python-genbadge
python
@power_session(python=[PY37]) def publish(session: PowerSession): session.install_reqs(phase='mkdocs', phase_reqs=['mkdocs-material', 'mkdocs', 'pymdown-extensions', 'pygments']) session.run2('mkdocs build -f ./docs/mkdocs.yml') if (not Folders.site_reports.exists()): raise ValueError("Test rep...
@power_session(python=[PY37]) def release(session: PowerSession): 'Create a release on github corresponding to the latest tag' from setuptools_scm import get_version from setuptools_scm.version import guess_next_dev_version version = [] def my_scheme(version_): version.append(version_) ...
3,323,425,240,592,413,000
Create a release on github corresponding to the latest tag
noxfile.py
release
texnofobix/python-genbadge
python
@power_session(python=[PY37]) def release(session: PowerSession): from setuptools_scm import get_version from setuptools_scm.version import guess_next_dev_version version = [] def my_scheme(version_): version.append(version_) return guess_next_dev_version(version_) current_tag ...
@nox.session(python=False) def gha_list(session): '(mandatory arg: <base_session_name>) Prints all sessions available for <base_session_name>, for GithubActions.' if (len(session.posargs) != 1): raise ValueError('This session has a mandatory argument: <base_session_name>') session_func = globals()[s...
4,695,728,447,206,028,000
(mandatory arg: <base_session_name>) Prints all sessions available for <base_session_name>, for GithubActions.
noxfile.py
gha_list
texnofobix/python-genbadge
python
@nox.session(python=False) def gha_list(session): if (len(session.posargs) != 1): raise ValueError('This session has a mandatory argument: <base_session_name>') session_func = globals()[session.posargs[0]] try: session_func.parametrize except AttributeError: sessions_list = ...
def _query_for_quote(symbol): '\n 返回请求某个合约的合约信息的 query_pack\n 调用次函数应该全部都是sdk的代码主动请求合约信息\n 用户请求合约信息一定是 PYSDK_api 开头的请求,因为用户请求的合约信息在回测时带有 timestamp 参数,是不应该调用此函数的\n ' symbol_list = (symbol if isinstance(symbol, list) else [symbol]) op = Operation(ins_schema.rootQuery) query = op.multi_symbol_in...
-8,257,304,933,987,689,000
返回请求某个合约的合约信息的 query_pack 调用次函数应该全部都是sdk的代码主动请求合约信息 用户请求合约信息一定是 PYSDK_api 开头的请求,因为用户请求的合约信息在回测时带有 timestamp 参数,是不应该调用此函数的
tqsdk/utils.py
_query_for_quote
Al-Wang/tqsdk-python
python
def _query_for_quote(symbol): '\n 返回请求某个合约的合约信息的 query_pack\n 调用次函数应该全部都是sdk的代码主动请求合约信息\n 用户请求合约信息一定是 PYSDK_api 开头的请求,因为用户请求的合约信息在回测时带有 timestamp 参数,是不应该调用此函数的\n ' symbol_list = (symbol if isinstance(symbol, list) else [symbol]) op = Operation(ins_schema.rootQuery) query = op.multi_symbol_in...
def _query_for_init(): '\n 返回某些类型合约的 query\n todo: 为了兼容旧版提供给用户的 api._data["quote"].items() 类似用法,应该限制交易所 ["SHFE", "DCE", "CZCE", "INE", "CFFEX", "KQ"]\n ' op = Operation(ins_schema.rootQuery) query = op.multi_symbol_info(class_=['FUTURE', 'INDEX', 'OPTION', 'COMBINE', 'CONT'], exchange_id=['SHFE', '...
-7,600,899,964,340,058,000
返回某些类型合约的 query todo: 为了兼容旧版提供给用户的 api._data["quote"].items() 类似用法,应该限制交易所 ["SHFE", "DCE", "CZCE", "INE", "CFFEX", "KQ"]
tqsdk/utils.py
_query_for_init
Al-Wang/tqsdk-python
python
def _query_for_init(): '\n 返回某些类型合约的 query\n todo: 为了兼容旧版提供给用户的 api._data["quote"].items() 类似用法,应该限制交易所 ["SHFE", "DCE", "CZCE", "INE", "CFFEX", "KQ"]\n ' op = Operation(ins_schema.rootQuery) query = op.multi_symbol_info(class_=['FUTURE', 'INDEX', 'OPTION', 'COMBINE', 'CONT'], exchange_id=['SHFE', '...
def _quotes_add_night(quotes): '为 quotes 中应该有夜盘但是市价合约文件中没有夜盘的品种,添加夜盘时间' for symbol in quotes: product_id = quotes[symbol].get('product_id') if (quotes[symbol].get('trading_time') and product_id): key = f"{quotes[symbol].get('exchange_id')}.{product_id}" if ((key in night_...
198,753,870,435,223,900
为 quotes 中应该有夜盘但是市价合约文件中没有夜盘的品种,添加夜盘时间
tqsdk/utils.py
_quotes_add_night
Al-Wang/tqsdk-python
python
def _quotes_add_night(quotes): for symbol in quotes: product_id = quotes[symbol].get('product_id') if (quotes[symbol].get('trading_time') and product_id): key = f"{quotes[symbol].get('exchange_id')}.{product_id}" if ((key in night_trading_table) and (not quotes[symbol]['...
def _bisect_value(a, x, priority='right'): '\n 返回 bisect_right() 取得下标对应的值,当插入点距离前后元素距离相等,priority 表示优先返回右边的值还是左边的值\n a: 必须是已经排序好(升序排列)的 list\n bisect_right : Return the index where to insert item x in list a, assuming a is sorted.\n ' assert (priority in ['left', 'right']) insert_index = bisect_...
-4,910,537,497,647,901,000
返回 bisect_right() 取得下标对应的值,当插入点距离前后元素距离相等,priority 表示优先返回右边的值还是左边的值 a: 必须是已经排序好(升序排列)的 list bisect_right : Return the index where to insert item x in list a, assuming a is sorted.
tqsdk/utils.py
_bisect_value
Al-Wang/tqsdk-python
python
def _bisect_value(a, x, priority='right'): '\n 返回 bisect_right() 取得下标对应的值,当插入点距离前后元素距离相等,priority 表示优先返回右边的值还是左边的值\n a: 必须是已经排序好(升序排列)的 list\n bisect_right : Return the index where to insert item x in list a, assuming a is sorted.\n ' assert (priority in ['left', 'right']) insert_index = bisect_...
def testcase_readergroup_add(self): 'tests groups=groups+[newgroups]' groupssnapshot = list(readergroups()) groups = readergroups() groups = (groups + [self.pinpadgroup]) self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups = (groups + [self.biogroup, self.pinpadgroup]) sel...
2,148,898,669,865,351,000
tests groups=groups+[newgroups]
cacreader/pyscard-2.0.2/smartcard/test/framework/testcase_readergroups.py
testcase_readergroup_add
kyletanyag/LL-Smartcard
python
def testcase_readergroup_add(self): groupssnapshot = list(readergroups()) groups = readergroups() groups = (groups + [self.pinpadgroup]) self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups = (groups + [self.biogroup, self.pinpadgroup]) self.assertEqual(groups, (groupssnap...
def testcase_readergroup_iadd(self): 'test groups+=[newgroups]' groupssnapshot = list(readergroups()) groups = readergroups() groups += [self.pinpadgroup] self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups += [self.biogroup, self.pinpadgroup] self.assertEqual(groups, (gro...
-4,554,897,509,285,952,500
test groups+=[newgroups]
cacreader/pyscard-2.0.2/smartcard/test/framework/testcase_readergroups.py
testcase_readergroup_iadd
kyletanyag/LL-Smartcard
python
def testcase_readergroup_iadd(self): groupssnapshot = list(readergroups()) groups = readergroups() groups += [self.pinpadgroup] self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups += [self.biogroup, self.pinpadgroup] self.assertEqual(groups, (groupssnapshot + [self.pinpad...
def testcase_readergroup_radd(self): 'test groups=[newgroups]+groups' groupssnapshot = list(readergroups()) groups = readergroups() zgroups = ([self.pinpadgroup] + groups) self.assertEqual(groups, groupssnapshot) self.assertEqual(zgroups, (groupssnapshot + [self.pinpadgroup])) self.assertTru...
6,720,619,275,553,248,000
test groups=[newgroups]+groups
cacreader/pyscard-2.0.2/smartcard/test/framework/testcase_readergroups.py
testcase_readergroup_radd
kyletanyag/LL-Smartcard
python
def testcase_readergroup_radd(self): groupssnapshot = list(readergroups()) groups = readergroups() zgroups = ([self.pinpadgroup] + groups) self.assertEqual(groups, groupssnapshot) self.assertEqual(zgroups, (groupssnapshot + [self.pinpadgroup])) self.assertTrue(isinstance(zgroups, type([])))...
def testcase_readergroup_append(self): 'test groups.append(newgroups)' groupssnapshot = list(readergroups()) groups = readergroups() groups.append(self.pinpadgroup) self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups.append(self.pinpadgroup) self.assertEqual(groups, (group...
8,593,865,738,370,409,000
test groups.append(newgroups)
cacreader/pyscard-2.0.2/smartcard/test/framework/testcase_readergroups.py
testcase_readergroup_append
kyletanyag/LL-Smartcard
python
def testcase_readergroup_append(self): groupssnapshot = list(readergroups()) groups = readergroups() groups.append(self.pinpadgroup) self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups.append(self.pinpadgroup) self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])...
def testcase_readergroup_insert(self): 'test groups.insert(i,newgroups)' groupssnapshot = list(readergroups()) groups = readergroups() groups.insert(0, self.pinpadgroup) self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups.insert(1, self.pinpadgroup) self.assertEqual(groups...
8,374,669,445,519,692,000
test groups.insert(i,newgroups)
cacreader/pyscard-2.0.2/smartcard/test/framework/testcase_readergroups.py
testcase_readergroup_insert
kyletanyag/LL-Smartcard
python
def testcase_readergroup_insert(self): groupssnapshot = list(readergroups()) groups = readergroups() groups.insert(0, self.pinpadgroup) self.assertEqual(groups, (groupssnapshot + [self.pinpadgroup])) groups.insert(1, self.pinpadgroup) self.assertEqual(groups, (groupssnapshot + [self.pinpadg...
def load_parallel_component(file_descr, graph: Graph, prev_layer_id): '\n Load ParallelComponent of the Kaldi model.\n ParallelComponent contains parallel nested networks.\n VariadicSplit is inserted before nested networks.\n Outputs of nested networks concatenate with layer Concat.\n\n :param file_d...
-6,662,843,149,624,463,000
Load ParallelComponent of the Kaldi model. ParallelComponent contains parallel nested networks. VariadicSplit is inserted before nested networks. Outputs of nested networks concatenate with layer Concat. :param file_descr: descriptor of the model file :param graph: graph with the topology. :param prev_layer_id: id of ...
tools/mo/openvino/tools/mo/front/kaldi/loader/loader.py
load_parallel_component
3Demonica/openvino
python
def load_parallel_component(file_descr, graph: Graph, prev_layer_id): '\n Load ParallelComponent of the Kaldi model.\n ParallelComponent contains parallel nested networks.\n VariadicSplit is inserted before nested networks.\n Outputs of nested networks concatenate with layer Concat.\n\n :param file_d...
def load_kaldi_model(graph, nnet_path): '\n Structure of the file is the following:\n magic-number(16896)<Nnet> <Next Layer Name> weights etc.\n :param nnet_path:\n :return:\n ' nnet_name = None if isinstance(nnet_path, str): file_desc = open(nnet_path, 'rb') nnet_name = get_n...
4,593,314,106,552,690,000
Structure of the file is the following: magic-number(16896)<Nnet> <Next Layer Name> weights etc. :param nnet_path: :return:
tools/mo/openvino/tools/mo/front/kaldi/loader/loader.py
load_kaldi_model
3Demonica/openvino
python
def load_kaldi_model(graph, nnet_path): '\n Structure of the file is the following:\n magic-number(16896)<Nnet> <Next Layer Name> weights etc.\n :param nnet_path:\n :return:\n ' nnet_name = None if isinstance(nnet_path, str): file_desc = open(nnet_path, 'rb') nnet_name = get_n...
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'): '\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix ...
-4,832,368,723,198,576,000
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : pos...
src/utils/console_functions.py
printProgressBar
MariusDgr/AudioMining
python
def printProgressBar(iteration, total, prefix=, suffix=, decimals=1, length=100, fill='█', printEnd='\r'): '\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - O...
def portfolio_metrics(weights, avg_xs_returns, covariance_matrix): ' Compute basic portfolio metrics: return, stdv, sharpe ratio ' portfolio_return = np.sum((weights * avg_xs_returns)) portfolio_stdv = np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix))) portfolio_sharpe = (portfolio_return / ...
-7,040,679,439,820,220,000
Compute basic portfolio metrics: return, stdv, sharpe ratio
portfolio_functions.py
portfolio_metrics
MaxGosselin/portfolio_optimizer
python
def portfolio_metrics(weights, avg_xs_returns, covariance_matrix): ' ' portfolio_return = np.sum((weights * avg_xs_returns)) portfolio_stdv = np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix))) portfolio_sharpe = (portfolio_return / portfolio_stdv) tickers = covariance_matrix.columns ...
def simulate_portfolios(iters, xs_stats, covariance_matrix): ' What we want here is to randomly generate portfolios that will sit \n inside the efficiency frontier for illustrative purposes ' simulations = [] while (iters > 1): weights = np.random.random(len(xs_stats.columns)) weights...
-4,991,181,571,714,116,000
What we want here is to randomly generate portfolios that will sit inside the efficiency frontier for illustrative purposes
portfolio_functions.py
simulate_portfolios
MaxGosselin/portfolio_optimizer
python
def simulate_portfolios(iters, xs_stats, covariance_matrix): ' What we want here is to randomly generate portfolios that will sit \n inside the efficiency frontier for illustrative purposes ' simulations = [] while (iters > 1): weights = np.random.random(len(xs_stats.columns)) weights...
def solve_minvar(xs_avg, covariance_matrix): ' Solve for the weights of the minimum variance portfolio \n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n\n Returns the weights and the jacobian used to generate the solution.\n \n ' def __minv...
-3,516,912,878,263,464,000
Solve for the weights of the minimum variance portfolio Constraints: sum of weights = 1, weights bound by [0, 0.2], Returns the weights and the jacobian used to generate the solution.
portfolio_functions.py
solve_minvar
MaxGosselin/portfolio_optimizer
python
def solve_minvar(xs_avg, covariance_matrix): ' Solve for the weights of the minimum variance portfolio \n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n\n Returns the weights and the jacobian used to generate the solution.\n \n ' def __minv...
def solve_maxsharpe(xs_avg, covariance_matrix): ' Solve for the weights of the maximum Sharpe ratio portfolio \n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n\n Returns the weights and the jacobian used to generate the solution.\n \n ' def...
-6,017,148,510,320,264,000
Solve for the weights of the maximum Sharpe ratio portfolio Constraints: sum of weights = 1, weights bound by [0, 0.2], Returns the weights and the jacobian used to generate the solution.
portfolio_functions.py
solve_maxsharpe
MaxGosselin/portfolio_optimizer
python
def solve_maxsharpe(xs_avg, covariance_matrix): ' Solve for the weights of the maximum Sharpe ratio portfolio \n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n\n Returns the weights and the jacobian used to generate the solution.\n \n ' def...
def solve_for_target_return(xs_avg, covariance_matrix, target): ' Solve for the weights of the minimum variance portfolio which has\n a specific targeted return.\n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n portfolio return = target return,\n\n...
6,640,005,835,390,372,000
Solve for the weights of the minimum variance portfolio which has a specific targeted return. Constraints: sum of weights = 1, weights bound by [0, 0.2], portfolio return = target return, Returns the weights and the jacobian used to generate the solution.
portfolio_functions.py
solve_for_target_return
MaxGosselin/portfolio_optimizer
python
def solve_for_target_return(xs_avg, covariance_matrix, target): ' Solve for the weights of the minimum variance portfolio which has\n a specific targeted return.\n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n portfolio return = target return,\n\n...
def __minvar(weights, xs_avg, covariance_matrix): ' Anonymous function to compute stdv ' return np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix)))
7,441,897,879,151,888,000
Anonymous function to compute stdv
portfolio_functions.py
__minvar
MaxGosselin/portfolio_optimizer
python
def __minvar(weights, xs_avg, covariance_matrix): ' ' return np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix)))
def __max_by_min_sharpe(weights, xs_avg, covariance_matrix): ' Anonymous function to compute sharpe ratio, note that since scipy only minimizes we go negative. ' pm = portfolio_metrics(weights, xs_avg, covariance_matrix) return ((- pm['return']) / pm['stdv'])
-6,553,485,962,850,862,000
Anonymous function to compute sharpe ratio, note that since scipy only minimizes we go negative.
portfolio_functions.py
__max_by_min_sharpe
MaxGosselin/portfolio_optimizer
python
def __max_by_min_sharpe(weights, xs_avg, covariance_matrix): ' ' pm = portfolio_metrics(weights, xs_avg, covariance_matrix) return ((- pm['return']) / pm['stdv'])
def __minvar(weights, xs_avg, covariance_matrix): ' Anonymous function to compute stdv ' return np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix)))
7,441,897,879,151,888,000
Anonymous function to compute stdv
portfolio_functions.py
__minvar
MaxGosselin/portfolio_optimizer
python
def __minvar(weights, xs_avg, covariance_matrix): ' ' return np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix)))
def __match_target(weights): ' Anonymous function to check equality with the target return ' return np.sum((weights * xs_avg))
-6,367,836,879,853,125,000
Anonymous function to check equality with the target return
portfolio_functions.py
__match_target
MaxGosselin/portfolio_optimizer
python
def __match_target(weights): ' ' return np.sum((weights * xs_avg))
def _base_parse(fh, builder, IndentationSetupF=False): 'Parses pattern definitions of the form:\n \n [ \t] => grid 4;\n [:intersection([:alpha:], [\\X064-\\X066]):] => space 1;\n\n In other words the right hand side *must* be a character set.\n\n ADAP...
-2,264,336,187,077,974,500
Parses pattern definitions of the form: [ ] => grid 4; [:intersection([:alpha:], [\X064-\X066]):] => space 1; In other words the right hand side *must* be a character set. ADAPTS: result to contain parsing information.
quex/input/files/specifier/counter.py
_base_parse
Liby99/quex
python
def _base_parse(fh, builder, IndentationSetupF=False): 'Parses pattern definitions of the form:\n \n [ \t] => grid 4;\n [:intersection([:alpha:], [\\X064-\\X066]):] => space 1;\n\n In other words the right hand side *must* be a character set.\n\n ADAP...
def _check_grid_values_integer_multiples(CaMap): "If there are no spaces and the grid is on a homogeneous scale,\n => then the grid can be transformed into 'easy-to-compute' spaces.\n " grid_value_list = [] min_info = None for (character_set, info) in CaMap: if (info.cc_type == E_Charac...
-6,188,627,997,836,072,000
If there are no spaces and the grid is on a homogeneous scale, => then the grid can be transformed into 'easy-to-compute' spaces.
quex/input/files/specifier/counter.py
_check_grid_values_integer_multiples
Liby99/quex
python
def _check_grid_values_integer_multiples(CaMap): "If there are no spaces and the grid is on a homogeneous scale,\n => then the grid can be transformed into 'easy-to-compute' spaces.\n " grid_value_list = [] min_info = None for (character_set, info) in CaMap: if (info.cc_type == E_Charac...
def check_defined(CaMap, SourceReference, CCT): 'Checks whether the character counter type has been defined in the \n map.\n \n THROWS: Error in case that is has not been defined.\n ' for (character_set, info) in CaMap: if (info.cc_type == CCT): return error.warning(("Setup d...
-7,588,525,549,289,565,000
Checks whether the character counter type has been defined in the map. THROWS: Error in case that is has not been defined.
quex/input/files/specifier/counter.py
check_defined
Liby99/quex
python
def check_defined(CaMap, SourceReference, CCT): 'Checks whether the character counter type has been defined in the \n map.\n \n THROWS: Error in case that is has not been defined.\n ' for (character_set, info) in CaMap: if (info.cc_type == CCT): return error.warning(("Setup d...
def __sm_newline_default(self): "Default newline: '(\n)|(\r\n)'\n " sm = DFA.from_character_set(NumberSet(ord('\n'))) if Setup.dos_carriage_return_newline_f: sm.add_transition_sequence(sm.init_state_index, [ord('\r'), ord('\n')]) return sm
1,336,341,528,381,798,700
Default newline: '( )|( )'
quex/input/files/specifier/counter.py
__sm_newline_default
Liby99/quex
python
def __sm_newline_default(self): "Default newline: '(\n)|(\r\n)'\n " sm = DFA.from_character_set(NumberSet(ord('\n'))) if Setup.dos_carriage_return_newline_f: sm.add_transition_sequence(sm.init_state_index, [ord('\r'), ord('\n')]) return sm
def __sm_whitespace_default(self): "Try to define default whitespace ' ' or '\t' if their positions\n are not yet occupied in the count_command_map.\n " sm_whitespace = DFA.from_character_set(NumberSet.from_integer_list([ord(' '), ord('\t')])) sm_whitespace = beautifier.do(repeat.do(sm_whitesp...
-5,222,298,472,099,206,000
Try to define default whitespace ' ' or ' ' if their positions are not yet occupied in the count_command_map.
quex/input/files/specifier/counter.py
__sm_whitespace_default
Liby99/quex
python
def __sm_whitespace_default(self): "Try to define default whitespace ' ' or '\t' if their positions\n are not yet occupied in the count_command_map.\n " sm_whitespace = DFA.from_character_set(NumberSet.from_integer_list([ord(' '), ord('\t')])) sm_whitespace = beautifier.do(repeat.do(sm_whitesp...
def _consistency_check(self): "\n Required defintions:\n -- WHITESPACE (Default done automatically) => Assert.\n -- NEWLINE (Default done automatically) => Assert.\n\n Inadmissible 'eat-into'.\n -- SUPPRESSOR shall not eat into [NEWLINE]\n -- NEWLINE shall...
-4,516,450,391,270,619,000
Required defintions: -- WHITESPACE (Default done automatically) => Assert. -- NEWLINE (Default done automatically) => Assert. Inadmissible 'eat-into'. -- SUPPRESSOR shall not eat into [NEWLINE] -- NEWLINE shall not eat into [WHITESPACE, BADSPACE, SUSPEND, SUPPRESSOR] -- WHITESPACE shall not eat in...
quex/input/files/specifier/counter.py
_consistency_check
Liby99/quex
python
def _consistency_check(self): "\n Required defintions:\n -- WHITESPACE (Default done automatically) => Assert.\n -- NEWLINE (Default done automatically) => Assert.\n\n Inadmissible 'eat-into'.\n -- SUPPRESSOR shall not eat into [NEWLINE]\n -- NEWLINE shall...
def get_enrollment_dates(course): 'Takes a course object and returns student dates of enrollment.\n Useful for handling late registrations and modified deadlines.\n\n Example:\n course.get_enrollment_date()' url_path = posixpath.join('api', 'v1', 'courses', course['course_id'], 'enrollments') api_u...
-5,592,095,403,443,192,000
Takes a course object and returns student dates of enrollment. Useful for handling late registrations and modified deadlines. Example: course.get_enrollment_date()
scripts/canvas.py
get_enrollment_dates
hsmohammed/rudaux
python
def get_enrollment_dates(course): 'Takes a course object and returns student dates of enrollment.\n Useful for handling late registrations and modified deadlines.\n\n Example:\n course.get_enrollment_date()' url_path = posixpath.join('api', 'v1', 'courses', course['course_id'], 'enrollments') api_u...
def get_assignments(course): 'Takes a course object and returns\n a Pandas data frame with all existing assignments and their attributes/data\n\n Example:\n course.get_assignments()' url_path = posixpath.join('api', 'v1', 'courses', course['course_id'], 'assignments') api_url = urllib.parse.urljoin...
2,791,318,408,290,562,000
Takes a course object and returns a Pandas data frame with all existing assignments and their attributes/data Example: course.get_assignments()
scripts/canvas.py
get_assignments
hsmohammed/rudaux
python
def get_assignments(course): 'Takes a course object and returns\n a Pandas data frame with all existing assignments and their attributes/data\n\n Example:\n course.get_assignments()' url_path = posixpath.join('api', 'v1', 'courses', course['course_id'], 'assignments') api_url = urllib.parse.urljoin...
def get_assignment_lock_date(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned.\n \n Example:\n course.get_assignment_due_date('worksheet_01')" assignments = get_assignments(course) assignments = assignment...
3,708,928,769,583,871,500
Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_due_date('worksheet_01')
scripts/canvas.py
get_assignment_lock_date
hsmohammed/rudaux
python
def get_assignment_lock_date(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned.\n \n Example:\n course.get_assignment_due_date('worksheet_01')" assignments = get_assignments(course) assignments = assignment...
def get_assignment_due_date(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned.\n \n Example:\n course.get_assignment_due_date('worksheet_01')" assignments = get_assignments(course) assignments = assignments...
5,000,143,287,905,871,000
Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_due_date('worksheet_01')
scripts/canvas.py
get_assignment_due_date
hsmohammed/rudaux
python
def get_assignment_due_date(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned.\n \n Example:\n course.get_assignment_due_date('worksheet_01')" assignments = get_assignments(course) assignments = assignments...
def get_assignment_unlock_date(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned.\n \n Example:\n course.get_assignment_unlock_date('worksheet_01')" assignments = get_assignments(course) assignments = assig...
8,767,283,540,079,634,000
Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned. Example: course.get_assignment_unlock_date('worksheet_01')
scripts/canvas.py
get_assignment_unlock_date
hsmohammed/rudaux
python
def get_assignment_unlock_date(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned.\n \n Example:\n course.get_assignment_unlock_date('worksheet_01')" assignments = get_assignments(course) assignments = assig...
def get_assignment_id(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the Canvas ID.\n \n Example:\n course.get_assignment_id('worksheet_01')" assignments = get_assignments(course) assignments = assignments[['name', 'id']].query('name == @assignment') ...
3,881,977,869,741,318,700
Takes a course object and the name of a Canvas assignment and returns the Canvas ID. Example: course.get_assignment_id('worksheet_01')
scripts/canvas.py
get_assignment_id
hsmohammed/rudaux
python
def get_assignment_id(course, assignment): "Takes a course object and the name of a Canvas assignment and returns the Canvas ID.\n \n Example:\n course.get_assignment_id('worksheet_01')" assignments = get_assignments(course) assignments = assignments[['name', 'id']].query('name == @assignment') ...
def get_grades(course, assignment): "Takes a course object, an assignment name, and get the grades for that assignment from Canvas.\n \n Example:\n course.get_grades(course, 'worksheet_01')" assignment_id = get_assignment_id(course, assignment) url_path = posixpath.join('api', 'v1', 'courses', cour...
2,481,858,038,511,870,500
Takes a course object, an assignment name, and get the grades for that assignment from Canvas. Example: course.get_grades(course, 'worksheet_01')
scripts/canvas.py
get_grades
hsmohammed/rudaux
python
def get_grades(course, assignment): "Takes a course object, an assignment name, and get the grades for that assignment from Canvas.\n \n Example:\n course.get_grades(course, 'worksheet_01')" assignment_id = get_assignment_id(course, assignment) url_path = posixpath.join('api', 'v1', 'courses', cour...
def grades_need_posting(course, assignment): "Takes a course object, an assignment name, and get the grades for that assignment from Canvas.\n \n Example:\n course.get_grades(course, 'worksheet_01')" assignment_id = get_assignment_id(course, assignment) url_path = posixpath.join('api', 'v1', 'cours...
997,278,230,784,641,700
Takes a course object, an assignment name, and get the grades for that assignment from Canvas. Example: course.get_grades(course, 'worksheet_01')
scripts/canvas.py
grades_need_posting
hsmohammed/rudaux
python
def grades_need_posting(course, assignment): "Takes a course object, an assignment name, and get the grades for that assignment from Canvas.\n \n Example:\n course.get_grades(course, 'worksheet_01')" assignment_id = get_assignment_id(course, assignment) url_path = posixpath.join('api', 'v1', 'cours...
def post_grade(course, assignment, student, score): "Takes a course object, an assignment name, student id, and score to upload. Posts to Canvas.\n\n Example:\n course.post_grades(dsci100, 'worksheet_01', '23423', 10)" assignment_id = get_assignment_id(course, assignment) url_post_path = posixpath.joi...
-5,043,899,444,181,111,000
Takes a course object, an assignment name, student id, and score to upload. Posts to Canvas. Example: course.post_grades(dsci100, 'worksheet_01', '23423', 10)
scripts/canvas.py
post_grade
hsmohammed/rudaux
python
def post_grade(course, assignment, student, score): "Takes a course object, an assignment name, student id, and score to upload. Posts to Canvas.\n\n Example:\n course.post_grades(dsci100, 'worksheet_01', '23423', 10)" assignment_id = get_assignment_id(course, assignment) url_post_path = posixpath.joi...
def make_kinetic_precond(kpointset, c0, eps=0.1, asPwCoeffs=True): '\n Preconditioner\n P = 1 / (||k|| + ε)\n\n Keyword Arguments:\n kpointset --\n ' nk = len(kpointset) nc = kpointset.ctx().num_spins() if ((nc == 1) and (nk == 1) and (not asPwCoeffs)): kp = kpointset[0] g...
1,352,622,070,274,955,300
Preconditioner P = 1 / (||k|| + ε) Keyword Arguments: kpointset --
python_module/sirius/ot/ot_precondition.py
make_kinetic_precond
electronic-structure/SIRIUS
python
def make_kinetic_precond(kpointset, c0, eps=0.1, asPwCoeffs=True): '\n Preconditioner\n P = 1 / (||k|| + ε)\n\n Keyword Arguments:\n kpointset --\n ' nk = len(kpointset) nc = kpointset.ctx().num_spins() if ((nc == 1) and (nk == 1) and (not asPwCoeffs)): kp = kpointset[0] g...
def checkpoints(self): 'runs movement to levels -- checkpoint when leaving area' return {'0': self.game, '1': self.good_ending_and_continue, 'bad': self.bad_ending, '3': self.woods_area}
-567,931,036,030,381,100
runs movement to levels -- checkpoint when leaving area
chapters/chapter2.py
checkpoints
JordanLeich/Alpha-Zombie-Survival-Game
python
def checkpoints(self): return {'0': self.game, '1': self.good_ending_and_continue, 'bad': self.bad_ending, '3': self.woods_area}
def good_ending_and_continue(self): 'Simply plays the good ending scene and then drops the player into chapter 2.' self.good_ending() Chapter3().game()
7,323,980,889,246,625,000
Simply plays the good ending scene and then drops the player into chapter 2.
chapters/chapter2.py
good_ending_and_continue
JordanLeich/Alpha-Zombie-Survival-Game
python
def good_ending_and_continue(self): self.good_ending() Chapter3().game()
def game(self): 'start of ch2' self.start() print_sleep('Upon driving the car through the broken roads area, the sun is certainly dwindling and time in the carsays 2:35 AM.\nYou continue to grow yourself tired and restless from everything that had led to this point\n', 2.5) choices = [str(x) for x in ra...
8,245,839,575,077,191,000
start of ch2
chapters/chapter2.py
game
JordanLeich/Alpha-Zombie-Survival-Game
python
def game(self): self.start() print_sleep('Upon driving the car through the broken roads area, the sun is certainly dwindling and time in the carsays 2:35 AM.\nYou continue to grow yourself tired and restless from everything that had led to this point\n', 2.5) choices = [str(x) for x in range(1, 3)] ...
def woods_area(self): 'Checkpoint save 3' player1.checkpoint_save('3') print_sleep('You have successfully gathered up some sticks and still need a source of flame to begin the campfire.\n', 2) choices = [str(x) for x in range(1, 3)] choice_options = ['You can either test your luck in creating a fire...
-3,674,613,718,898,177,000
Checkpoint save 3
chapters/chapter2.py
woods_area
JordanLeich/Alpha-Zombie-Survival-Game
python
def woods_area(self): player1.checkpoint_save('3') print_sleep('You have successfully gathered up some sticks and still need a source of flame to begin the campfire.\n', 2) choices = [str(x) for x in range(1, 3)] choice_options = ['You can either test your luck in creating a fire by (1) Creating fr...
def __init__(self, mesh): '*mesh* is the mesh Function.' self.mesh = asfunction(mesh)
-8,804,555,952,250,433,000
*mesh* is the mesh Function.
moviemaker3/math/angle.py
__init__
friedrichromstedt/moviemaker3
python
def __init__(self, mesh): self.mesh = asfunction(mesh)
def __call__(self, ps): 'Returns the arctan2. The (y, x) coordinate is in the last \n dimension.' meshT = self.mesh(ps).T return numpy.arctan2(meshT[0], meshT[1]).T
5,408,430,055,512,316,000
Returns the arctan2. The (y, x) coordinate is in the last dimension.
moviemaker3/math/angle.py
__call__
friedrichromstedt/moviemaker3
python
def __call__(self, ps): 'Returns the arctan2. The (y, x) coordinate is in the last \n dimension.' meshT = self.mesh(ps).T return numpy.arctan2(meshT[0], meshT[1]).T
def corners_nd(dims, origin=0.5): 'generate relative box corners based on length per dim and\n origin point.\n\n Args:\n dims (float array, shape=[N, ndim]): array of length per dim\n origin (list or array or float): origin point relate to smallest point.\n\n Returns:\n float array, sh...
8,539,276,352,659,929,000
generate relative box corners based on length per dim and origin point. Args: dims (float array, shape=[N, ndim]): array of length per dim origin (list or array or float): origin point relate to smallest point. Returns: float array, shape=[N, 2 ** ndim, ndim]: returned corners. point layout example: (...
det3d/core/bbox/box_np_ops.py
corners_nd
motional/polarstream
python
def corners_nd(dims, origin=0.5): 'generate relative box corners based on length per dim and\n origin point.\n\n Args:\n dims (float array, shape=[N, ndim]): array of length per dim\n origin (list or array or float): origin point relate to smallest point.\n\n Returns:\n float array, sh...
def rbbox2d_to_near_bbox(rbboxes): "convert rotated bbox to nearest 'standing' or 'lying' bbox.\n Args:\n rbboxes: [N, 5(x, y, xdim, ydim, rad)] rotated bboxes\n Returns:\n bboxes: [N, 4(xmin, ymin, xmax, ymax)] bboxes\n " rots = rbboxes[(..., (- 1))] rots_0_pi_div_2 = np.abs(limit_pe...
-1,301,025,159,006,912,300
convert rotated bbox to nearest 'standing' or 'lying' bbox. Args: rbboxes: [N, 5(x, y, xdim, ydim, rad)] rotated bboxes Returns: bboxes: [N, 4(xmin, ymin, xmax, ymax)] bboxes
det3d/core/bbox/box_np_ops.py
rbbox2d_to_near_bbox
motional/polarstream
python
def rbbox2d_to_near_bbox(rbboxes): "convert rotated bbox to nearest 'standing' or 'lying' bbox.\n Args:\n rbboxes: [N, 5(x, y, xdim, ydim, rad)] rotated bboxes\n Returns:\n bboxes: [N, 4(xmin, ymin, xmax, ymax)] bboxes\n " rots = rbboxes[(..., (- 1))] rots_0_pi_div_2 = np.abs(limit_pe...
def rotation_2d(points, angles): 'rotation 2d points based on origin point clockwise when angle positive.\n\n Args:\n points (float array, shape=[N, point_size, 2]): points to be rotated.\n angles (float array, shape=[N]): rotation angle.\n\n Returns:\n float array: same shape as points\n...
-8,212,063,425,262,677,000
rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angles (float array, shape=[N]): rotation angle. Returns: float array: same shape as points
det3d/core/bbox/box_np_ops.py
rotation_2d
motional/polarstream
python
def rotation_2d(points, angles): 'rotation 2d points based on origin point clockwise when angle positive.\n\n Args:\n points (float array, shape=[N, point_size, 2]): points to be rotated.\n angles (float array, shape=[N]): rotation angle.\n\n Returns:\n float array: same shape as points\n...
def rotation_box(box_corners, angle): 'rotation 2d points based on origin point clockwise when angle positive.\n\n Args:\n points (float array, shape=[N, point_size, 2]): points to be rotated.\n angle (float): rotation angle.\n\n Returns:\n float array: same shape as points\n ' rot...
6,605,383,920,097,669,000
rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angle (float): rotation angle. Returns: float array: same shape as points
det3d/core/bbox/box_np_ops.py
rotation_box
motional/polarstream
python
def rotation_box(box_corners, angle): 'rotation 2d points based on origin point clockwise when angle positive.\n\n Args:\n points (float array, shape=[N, point_size, 2]): points to be rotated.\n angle (float): rotation angle.\n\n Returns:\n float array: same shape as points\n ' rot...
def center_to_corner_box3d(centers, dims, angles=None, origin=(0.5, 0.5, 0.5), axis=2): 'convert kitti locations, dimensions and angles to corners\n\n Args:\n centers (float array, shape=[N, 3]): locations in kitti label file.\n dims (float array, shape=[N, 3]): dimensions in kitti label file.\n ...
4,548,306,000,528,166,000
convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 3]): locations in kitti label file. dims (float array, shape=[N, 3]): dimensions in kitti label file. angles (float array, shape=[N]): rotation_y in kitti label file. origin (list or array or float): origin ...
det3d/core/bbox/box_np_ops.py
center_to_corner_box3d
motional/polarstream
python
def center_to_corner_box3d(centers, dims, angles=None, origin=(0.5, 0.5, 0.5), axis=2): 'convert kitti locations, dimensions and angles to corners\n\n Args:\n centers (float array, shape=[N, 3]): locations in kitti label file.\n dims (float array, shape=[N, 3]): dimensions in kitti label file.\n ...
def center_to_corner_box2d(centers, dims, angles=None, origin=0.5): 'convert kitti locations, dimensions and angles to corners.\n format: center(xy), dims(xy), angles(clockwise when positive)\n\n Args:\n centers (float array, shape=[N, 2]): locations in kitti label file.\n dims (float array, sha...
7,772,419,611,600,366,000
convert kitti locations, dimensions and angles to corners. format: center(xy), dims(xy), angles(clockwise when positive) Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=[N, 2]): dimensions in kitti label file. angles (float array, shape=[N]): rotation_y in...
det3d/core/bbox/box_np_ops.py
center_to_corner_box2d
motional/polarstream
python
def center_to_corner_box2d(centers, dims, angles=None, origin=0.5): 'convert kitti locations, dimensions and angles to corners.\n format: center(xy), dims(xy), angles(clockwise when positive)\n\n Args:\n centers (float array, shape=[N, 2]): locations in kitti label file.\n dims (float array, sha...
@numba.jit(nopython=True) def iou_jit(boxes, query_boxes, eps=1.0): 'calculate box iou. note that jit version runs 2x faster than cython in\n my machine!\n Parameters\n ----------\n boxes: (N, 4) ndarray of float\n query_boxes: (K, 4) ndarray of float\n Returns\n -------\n overlaps: (N, K) n...
-7,542,823,905,533,092,000
calculate box iou. note that jit version runs 2x faster than cython in my machine! Parameters ---------- boxes: (N, 4) ndarray of float query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
det3d/core/bbox/box_np_ops.py
iou_jit
motional/polarstream
python
@numba.jit(nopython=True) def iou_jit(boxes, query_boxes, eps=1.0): 'calculate box iou. note that jit version runs 2x faster than cython in\n my machine!\n Parameters\n ----------\n boxes: (N, 4) ndarray of float\n query_boxes: (K, 4) ndarray of float\n Returns\n -------\n overlaps: (N, K) n...
@numba.jit(nopython=True) def iou_3d_jit(boxes, query_boxes, add1=True): 'calculate box iou3d,\n ----------\n boxes: (N, 6) ndarray of float\n query_boxes: (K, 6) ndarray of float\n Returns\n -------\n overlaps: (N, K) ndarray of overlap between boxes and query_boxes\n ' N = boxes.shape[0] ...
-2,774,315,039,072,902,700
calculate box iou3d, ---------- boxes: (N, 6) ndarray of float query_boxes: (K, 6) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
det3d/core/bbox/box_np_ops.py
iou_3d_jit
motional/polarstream
python
@numba.jit(nopython=True) def iou_3d_jit(boxes, query_boxes, add1=True): 'calculate box iou3d,\n ----------\n boxes: (N, 6) ndarray of float\n query_boxes: (K, 6) ndarray of float\n Returns\n -------\n overlaps: (N, K) ndarray of overlap between boxes and query_boxes\n ' N = boxes.shape[0] ...
@numba.jit(nopython=True) def iou_nd_jit(boxes, query_boxes, add1=True): 'calculate box iou nd, 2x slower than iou_jit.\n ----------\n boxes: (N, ndim * 2) ndarray of float\n query_boxes: (K, ndim * 2) ndarray of float\n Returns\n -------\n overlaps: (N, K) ndarray of overlap between boxes and que...
-5,011,801,594,874,465,000
calculate box iou nd, 2x slower than iou_jit. ---------- boxes: (N, ndim * 2) ndarray of float query_boxes: (K, ndim * 2) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
det3d/core/bbox/box_np_ops.py
iou_nd_jit
motional/polarstream
python
@numba.jit(nopython=True) def iou_nd_jit(boxes, query_boxes, add1=True): 'calculate box iou nd, 2x slower than iou_jit.\n ----------\n boxes: (N, ndim * 2) ndarray of float\n query_boxes: (K, ndim * 2) ndarray of float\n Returns\n -------\n overlaps: (N, K) ndarray of overlap between boxes and que...
def corner_to_surfaces_3d(corners): 'convert 3d box corners from corner function above\n to surfaces that normal vectors all direct to internal.\n\n Args:\n corners (float array, [N, 8, 3]): 3d box corners.\n Returns:\n surfaces (float array, [N, 6, 4, 3]):\n ' surfaces = np.array([[co...
-3,105,657,895,945,397,000
convert 3d box corners from corner function above to surfaces that normal vectors all direct to internal. Args: corners (float array, [N, 8, 3]): 3d box corners. Returns: surfaces (float array, [N, 6, 4, 3]):
det3d/core/bbox/box_np_ops.py
corner_to_surfaces_3d
motional/polarstream
python
def corner_to_surfaces_3d(corners): 'convert 3d box corners from corner function above\n to surfaces that normal vectors all direct to internal.\n\n Args:\n corners (float array, [N, 8, 3]): 3d box corners.\n Returns:\n surfaces (float array, [N, 6, 4, 3]):\n ' surfaces = np.array([[co...
@numba.jit(nopython=True) def corner_to_surfaces_3d_jit(corners): 'convert 3d box corners from corner function above\n to surfaces that normal vectors all direct to internal.\n\n Args:\n corners (float array, [N, 8, 3]): 3d box corners.\n Returns:\n surfaces (float array, [N, 6, 4, 3]):\n ...
8,323,415,292,507,754,000
convert 3d box corners from corner function above to surfaces that normal vectors all direct to internal. Args: corners (float array, [N, 8, 3]): 3d box corners. Returns: surfaces (float array, [N, 6, 4, 3]):
det3d/core/bbox/box_np_ops.py
corner_to_surfaces_3d_jit
motional/polarstream
python
@numba.jit(nopython=True) def corner_to_surfaces_3d_jit(corners): 'convert 3d box corners from corner function above\n to surfaces that normal vectors all direct to internal.\n\n Args:\n corners (float array, [N, 8, 3]): 3d box corners.\n Returns:\n surfaces (float array, [N, 6, 4, 3]):\n ...
def assign_label_to_voxel(gt_boxes, coors, voxel_size, coors_range): 'assign a 0/1 label to each voxel based on whether\n the center of voxel is in gt_box. LIDAR.\n ' voxel_size = np.array(voxel_size, dtype=gt_boxes.dtype) coors_range = np.array(coors_range, dtype=gt_boxes.dtype) shift = coors_ran...
8,134,859,055,966,454,000
assign a 0/1 label to each voxel based on whether the center of voxel is in gt_box. LIDAR.
det3d/core/bbox/box_np_ops.py
assign_label_to_voxel
motional/polarstream
python
def assign_label_to_voxel(gt_boxes, coors, voxel_size, coors_range): 'assign a 0/1 label to each voxel based on whether\n the center of voxel is in gt_box. LIDAR.\n ' voxel_size = np.array(voxel_size, dtype=gt_boxes.dtype) coors_range = np.array(coors_range, dtype=gt_boxes.dtype) shift = coors_ran...
def assign_label_to_voxel_v3(gt_boxes, coors, voxel_size, coors_range): 'assign a 0/1 label to each voxel based on whether\n the center of voxel is in gt_box. LIDAR.\n ' voxel_size = np.array(voxel_size, dtype=gt_boxes.dtype) coors_range = np.array(coors_range, dtype=gt_boxes.dtype) shift = coors_...
4,818,000,534,278,983,000
assign a 0/1 label to each voxel based on whether the center of voxel is in gt_box. LIDAR.
det3d/core/bbox/box_np_ops.py
assign_label_to_voxel_v3
motional/polarstream
python
def assign_label_to_voxel_v3(gt_boxes, coors, voxel_size, coors_range): 'assign a 0/1 label to each voxel based on whether\n the center of voxel is in gt_box. LIDAR.\n ' voxel_size = np.array(voxel_size, dtype=gt_boxes.dtype) coors_range = np.array(coors_range, dtype=gt_boxes.dtype) shift = coors_...
def image_box_region_area(img_cumsum, bbox): 'check a 2d voxel is contained by a box. used to filter empty\n anchors.\n Summed-area table algorithm:\n ==> W\n ------------------\n | | |\n |------A---------B\n | | |\n | | |\n |----- C---------D\n I...
5,212,201,778,767,590,000
check a 2d voxel is contained by a box. used to filter empty anchors. Summed-area table algorithm: ==> W ------------------ | | | |------A---------B | | | | | | |----- C---------D Iabcd = ID-IB-IC+IA Args: img_cumsum: [M, H, W](yx) cumsumed image. bbox: [N, 4](xyxy) boundi...
det3d/core/bbox/box_np_ops.py
image_box_region_area
motional/polarstream
python
def image_box_region_area(img_cumsum, bbox): 'check a 2d voxel is contained by a box. used to filter empty\n anchors.\n Summed-area table algorithm:\n ==> W\n ------------------\n | | |\n |------A---------B\n | | |\n | | |\n |----- C---------D\n I...
def __init__(self): '\n\t\tCreates the himesis graph representing the AToM3 model HContractUnitR03_ConnectedLHS\n\t\t' self.is_compiled = True super(HContractUnitR03_ConnectedLHS, self).__init__(name='HContractUnitR03_ConnectedLHS', num_nodes=0, edges=[]) self.add_edges([]) self['mm__'] = ['MT_pre__...
-8,516,995,704,198,999,000
Creates the himesis graph representing the AToM3 model HContractUnitR03_ConnectedLHS
UML2ER/contracts/unit/HContractUnitR03_ConnectedLHS.py
__init__
levilucio/SyVOLT
python
def __init__(self): '\n\t\t\n\t\t' self.is_compiled = True super(HContractUnitR03_ConnectedLHS, self).__init__(name='HContractUnitR03_ConnectedLHS', num_nodes=0, edges=[]) self.add_edges([]) self['mm__'] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self['MT_constraint__'] = 'return True' s...
def rand_permute_adj_matrix(matrix): 'Randomly permute the order of vertices in the adjacency matrix, while maintaining the connectivity\n between them.' num_vertices = matrix.shape[0] rand_order = np.arange(num_vertices) np.random.shuffle(rand_order) matrix_permuted = rearrange_adj_matrix(matrix...
2,072,083,524,283,573,000
Randomly permute the order of vertices in the adjacency matrix, while maintaining the connectivity between them.
utils/graph_utils.py
rand_permute_adj_matrix
BrunoKM/rhoana_graph_tools
python
def rand_permute_adj_matrix(matrix): 'Randomly permute the order of vertices in the adjacency matrix, while maintaining the connectivity\n between them.' num_vertices = matrix.shape[0] rand_order = np.arange(num_vertices) np.random.shuffle(rand_order) matrix_permuted = rearrange_adj_matrix(matrix...
def ged_from_adj(adj_mat_1, adj_mat_2, directed=False, ged_function=graph_edit_dist.compare): 'Calculate the graph edit distance between two graphs' if directed: create_using = nx.DiGraph else: create_using = nx.Graph g1 = nx.from_numpy_matrix(adj_mat_1, create_using=create_using()) ...
-1,019,193,061,419,621,200
Calculate the graph edit distance between two graphs
utils/graph_utils.py
ged_from_adj
BrunoKM/rhoana_graph_tools
python
def ged_from_adj(adj_mat_1, adj_mat_2, directed=False, ged_function=graph_edit_dist.compare): if directed: create_using = nx.DiGraph else: create_using = nx.Graph g1 = nx.from_numpy_matrix(adj_mat_1, create_using=create_using()) g2 = nx.from_numpy_matrix(adj_mat_2, create_using=crea...
def ged_from_adj_nx(adj_mat_1, adj_mat_2, directed=False): 'Calculate the graph edit distance between two graphs using the networkx implementation' return ged_from_adj(adj_mat_1, adj_mat_2, directed=directed, ged_function=nx.graph_edit_distance)
-6,871,451,744,190,802,000
Calculate the graph edit distance between two graphs using the networkx implementation
utils/graph_utils.py
ged_from_adj_nx
BrunoKM/rhoana_graph_tools
python
def ged_from_adj_nx(adj_mat_1, adj_mat_2, directed=False): return ged_from_adj(adj_mat_1, adj_mat_2, directed=directed, ged_function=nx.graph_edit_distance)
def ged_from_adj_ged4py(adj_mat_1, adj_mat_2, directed=False): 'Calculate the graph edit distance between two graphs using the ged4py implementation' return ged_from_adj(adj_mat_1, adj_mat_2, directed=directed, ged_function=graph_edit_dist.compare)
-2,015,968,644,657,250,800
Calculate the graph edit distance between two graphs using the ged4py implementation
utils/graph_utils.py
ged_from_adj_ged4py
BrunoKM/rhoana_graph_tools
python
def ged_from_adj_ged4py(adj_mat_1, adj_mat_2, directed=False): return ged_from_adj(adj_mat_1, adj_mat_2, directed=directed, ged_function=graph_edit_dist.compare)
def is_isomorphic_from_adj(adj_mat_1, adj_mat_2): 'Checks whether two graphs are isomorphic taking adjacency matrices as inputs' g1 = nx.from_numpy_matrix(adj_mat_1, create_using=nx.DiGraph()) g2 = nx.from_numpy_matrix(adj_mat_2, create_using=nx.DiGraph()) return nx.is_isomorphic(g1, g2)
5,955,937,699,591,090,000
Checks whether two graphs are isomorphic taking adjacency matrices as inputs
utils/graph_utils.py
is_isomorphic_from_adj
BrunoKM/rhoana_graph_tools
python
def is_isomorphic_from_adj(adj_mat_1, adj_mat_2): g1 = nx.from_numpy_matrix(adj_mat_1, create_using=nx.DiGraph()) g2 = nx.from_numpy_matrix(adj_mat_2, create_using=nx.DiGraph()) return nx.is_isomorphic(g1, g2)
def train(self, epoch: int) -> None: '\n Train an epoch\n\n Parameters\n ----------\n epoch : int\n Current number of epoch\n ' self.decoder.train() self.encoder.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter(tag...
6,085,474,841,145,883,000
Train an epoch Parameters ---------- epoch : int Current number of epoch
trainer/trainer.py
train
Renovamen/Image-Caption
python
def train(self, epoch: int) -> None: '\n Train an epoch\n\n Parameters\n ----------\n epoch : int\n Current number of epoch\n ' self.decoder.train() self.encoder.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter(tag...
def validate(self) -> float: '\n Validate an epoch.\n\n Returns\n -------\n bleu4 : float\n BLEU-4 score\n ' self.decoder.eval() if (self.encoder is not None): self.encoder.eval() batch_time = AverageMeter() losses = AverageMeter() top5accs =...
3,469,363,881,887,474,700
Validate an epoch. Returns ------- bleu4 : float BLEU-4 score
trainer/trainer.py
validate
Renovamen/Image-Caption
python
def validate(self) -> float: '\n Validate an epoch.\n\n Returns\n -------\n bleu4 : float\n BLEU-4 score\n ' self.decoder.eval() if (self.encoder is not None): self.encoder.eval() batch_time = AverageMeter() losses = AverageMeter() top5accs =...
def _get_all_query_string(self, changelist): "\n If there's a default value set the all parameter needs to be provided\n however, if a default is not set the all parameter is not required.\n " if self.default_filter_value: return changelist.get_query_string({self.parameter_name: sel...
7,343,347,246,114,303,000
If there's a default value set the all parameter needs to be provided however, if a default is not set the all parameter is not required.
djangocms_content_expiry/filters.py
_get_all_query_string
Aiky30/djangocms-content-expiry
python
def _get_all_query_string(self, changelist): "\n If there's a default value set the all parameter needs to be provided\n however, if a default is not set the all parameter is not required.\n " if self.default_filter_value: return changelist.get_query_string({self.parameter_name: sel...
@core.flake8ext def hacking_no_locals(logical_line, physical_line, tokens, noqa): 'Do not use locals() or self.__dict__ for string formatting.\n\n Okay: \'locals()\'\n Okay: \'locals\'\n Okay: locals()\n Okay: print(locals())\n H501: print("%(something)" % locals())\n H501: LOG.info(_("%(something...
7,383,045,247,385,087,000
Do not use locals() or self.__dict__ for string formatting. Okay: 'locals()' Okay: 'locals' Okay: locals() Okay: print(locals()) H501: print("%(something)" % locals()) H501: LOG.info(_("%(something)") % self.__dict__) Okay: print("%(something)" % locals()) # noqa
hacking/checks/dictlist.py
hacking_no_locals
UbuntuEvangelist/hacking
python
@core.flake8ext def hacking_no_locals(logical_line, physical_line, tokens, noqa): 'Do not use locals() or self.__dict__ for string formatting.\n\n Okay: \'locals()\'\n Okay: \'locals\'\n Okay: locals()\n Okay: print(locals())\n H501: print("%(something)" % locals())\n H501: LOG.info(_("%(something...
def deal_card(): 'Return random card' cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] card = random.choice(cards) return card
-3,847,650,605,205,713,000
Return random card
Programs/day_11_blackjack.py
deal_card
Yunram/python_training
python
def deal_card(): cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] card = random.choice(cards) return card
def calculate_score(cards): 'Take a list of cards and return the score' if ((sum(cards) == 21) and (len(cards) == 2)): return 0 if ((11 in cards) and (sum(cards) > 21)): cards.remove(11) cards.append(1) return sum(cards)
6,349,374,628,700,159,000
Take a list of cards and return the score
Programs/day_11_blackjack.py
calculate_score
Yunram/python_training
python
def calculate_score(cards): if ((sum(cards) == 21) and (len(cards) == 2)): return 0 if ((11 in cards) and (sum(cards) > 21)): cards.remove(11) cards.append(1) return sum(cards)
def jupyterbook(): '\n Create content and TOC for building a jupyter-book version 0.8: https://jupyterbook.org/intro\n\n This function is called directly from bin/doconce\n ' if (len(sys.argv) < 2): doconce_version() print(docstring_jupyterbook) print("Try 'doconce jupyterbook -...
5,549,780,974,407,250,000
Create content and TOC for building a jupyter-book version 0.8: https://jupyterbook.org/intro This function is called directly from bin/doconce
lib/doconce/jupyterbook.py
jupyterbook
aless80/doconce
python
def jupyterbook(): '\n Create content and TOC for building a jupyter-book version 0.8: https://jupyterbook.org/intro\n\n This function is called directly from bin/doconce\n ' if (len(sys.argv) < 2): doconce_version() print(docstring_jupyterbook) print("Try 'doconce jupyterbook -...
def split_file(filestr, separator): "Split the text of a doconce file by a regex string.\n\n Split the text of a doconce file by a separator regex (e.g. the values of\n the INLINE_TAGS dictionary from common.py) and return the chunks of text.\n Note that the first chunk contains any text before the first s...
-3,129,595,768,777,523,700
Split the text of a doconce file by a regex string. Split the text of a doconce file by a separator regex (e.g. the values of the INLINE_TAGS dictionary from common.py) and return the chunks of text. Note that the first chunk contains any text before the first separator. :param str filestr: text string :param str sepa...
lib/doconce/jupyterbook.py
split_file
aless80/doconce
python
def split_file(filestr, separator): "Split the text of a doconce file by a regex string.\n\n Split the text of a doconce file by a separator regex (e.g. the values of\n the INLINE_TAGS dictionary from common.py) and return the chunks of text.\n Note that the first chunk contains any text before the first s...
def split_ipynb(ipynb_text, filenames): 'Split a Jupyter notebook based on filenames present in its blocks\n\n Given the text of a Jupyter notebook marked with the output filename\n in comments (e.g. <!-- jupyter-book 02_mybook.ipynb -->), return a list of\n Jupyter notebooks separated accordingly.\n :p...
985,091,436,715,346,400
Split a Jupyter notebook based on filenames present in its blocks Given the text of a Jupyter notebook marked with the output filename in comments (e.g. <!-- jupyter-book 02_mybook.ipynb -->), return a list of Jupyter notebooks separated accordingly. :param str ipynb_text: ipynb code marked with individual filenames i...
lib/doconce/jupyterbook.py
split_ipynb
aless80/doconce
python
def split_ipynb(ipynb_text, filenames): 'Split a Jupyter notebook based on filenames present in its blocks\n\n Given the text of a Jupyter notebook marked with the output filename\n in comments (e.g. <!-- jupyter-book 02_mybook.ipynb -->), return a list of\n Jupyter notebooks separated accordingly.\n :p...
def read_title_file(titles_opt, chapters, sec_list): "Helper function to read and process a file with titles\n\n Read the file containing titles and process them according to the number of jupyter-book chapters and sections.\n len(sec_list) should be the same as len(chapters), and its elements can be empty li...
1,563,216,286,263,243,000
Helper function to read and process a file with titles Read the file containing titles and process them according to the number of jupyter-book chapters and sections. len(sec_list) should be the same as len(chapters), and its elements can be empty lists :param str titles_opt: 'auto' or file containing titles :param li...
lib/doconce/jupyterbook.py
read_title_file
aless80/doconce
python
def read_title_file(titles_opt, chapters, sec_list): "Helper function to read and process a file with titles\n\n Read the file containing titles and process them according to the number of jupyter-book chapters and sections.\n len(sec_list) should be the same as len(chapters), and its elements can be empty li...
def titles_to_chunks(chunks, title_list, sep, sep2=None, chapter_formatter='%02d_', tags=INLINE_TAGS): 'Helper function to extract assign titles to jupyter-book chapters/sections (here called chunks)\n\n Jupyter-book files must have a # header with the title (see doc jupyter-book >\n Types of content source f...
-4,218,107,978,038,146,000
Helper function to extract assign titles to jupyter-book chapters/sections (here called chunks) Jupyter-book files must have a # header with the title (see doc jupyter-book > Types of content source files > Rules for all content types). This function extracts title from the title file or from the headers given by the ...
lib/doconce/jupyterbook.py
titles_to_chunks
aless80/doconce
python
def titles_to_chunks(chunks, title_list, sep, sep2=None, chapter_formatter='%02d_', tags=INLINE_TAGS): 'Helper function to extract assign titles to jupyter-book chapters/sections (here called chunks)\n\n Jupyter-book files must have a # header with the title (see doc jupyter-book >\n Types of content source f...
def create_title(chunk, sep, tags): "Helper function to allow doconce jupyterbook to automatically assign titles in the TOC\n\n If a chunk of text starts with the section specified in sep, lift it up\n to a chapter section. This allows doconce jupyterbook to automatically use the\n section's text as title ...
746,731,705,735,869,800
Helper function to allow doconce jupyterbook to automatically assign titles in the TOC If a chunk of text starts with the section specified in sep, lift it up to a chapter section. This allows doconce jupyterbook to automatically use the section's text as title in the TOC on the left :param str chunk: text string :pa...
lib/doconce/jupyterbook.py
create_title
aless80/doconce
python
def create_title(chunk, sep, tags): "Helper function to allow doconce jupyterbook to automatically assign titles in the TOC\n\n If a chunk of text starts with the section specified in sep, lift it up\n to a chapter section. This allows doconce jupyterbook to automatically use the\n section's text as title ...
def identify_format(text_list): "Identify the appropriate formats to convert a list of DocOnce texts.\n\n Given a list of DocOnce texts, check if they contain code. If so, return the suffix\n '.ipynb' (for the Jupyter Notebook ipynb format), otherwise return '.md' (for\n the pandoc markdown format).\n :...
-6,315,886,050,878,515,000
Identify the appropriate formats to convert a list of DocOnce texts. Given a list of DocOnce texts, check if they contain code. If so, return the suffix '.ipynb' (for the Jupyter Notebook ipynb format), otherwise return '.md' (for the pandoc markdown format). :param list[str] text_list: list of strings using DocOnce s...
lib/doconce/jupyterbook.py
identify_format
aless80/doconce
python
def identify_format(text_list): "Identify the appropriate formats to convert a list of DocOnce texts.\n\n Given a list of DocOnce texts, check if they contain code. If so, return the suffix\n '.ipynb' (for the Jupyter Notebook ipynb format), otherwise return '.md' (for\n the pandoc markdown format).\n :...
def create_toc_yml(basenames, nesting_levels, titles, dest='./', dest_toc='./', section_paths=None, section_titles=None): 'Create the content of a _toc.yml file\n\n Give the lists of paths, titles, and nesting levels, return the content of a _toc.yml file\n :param list[str] basenames: list of file bas...
-2,230,910,722,808,470,300
Create the content of a _toc.yml file Give the lists of paths, titles, and nesting levels, return the content of a _toc.yml file :param list[str] basenames: list of file basenames for jupyter-book chapters or sections, i.e. strings that can be used after the `file:` section in a _toc.yml :param list[str] titles: list ...
lib/doconce/jupyterbook.py
create_toc_yml
aless80/doconce
python
def create_toc_yml(basenames, nesting_levels, titles, dest='./', dest_toc='./', section_paths=None, section_titles=None): 'Create the content of a _toc.yml file\n\n Give the lists of paths, titles, and nesting levels, return the content of a _toc.yml file\n :param list[str] basenames: list of file bas...
def print_help_jupyterbook(): 'Pretty print help string and command line options\n\n Help function to print help and formatted command line options for doconce jupyterbook\n ' print(docstring_jupyterbook) print('Options:') help_print_options(cmdline_opts=_registered_cmdline_opts_jupyterbook)
-513,857,317,894,164,030
Pretty print help string and command line options Help function to print help and formatted command line options for doconce jupyterbook
lib/doconce/jupyterbook.py
print_help_jupyterbook
aless80/doconce
python
def print_help_jupyterbook(): 'Pretty print help string and command line options\n\n Help function to print help and formatted command line options for doconce jupyterbook\n ' print(docstring_jupyterbook) print('Options:') help_print_options(cmdline_opts=_registered_cmdline_opts_jupyterbook)
def read_to_list(file): 'Read the content of a file to list\n\n Verify the existence of a file, then read it to a list by\n stripping newlines. The function aborts the program if the file does not exist.\n\n :param str file: Path to an existing file\n :return: list of strings\n :rtype: list[str]\n ...
-1,171,378,323,079,902,700
Read the content of a file to list Verify the existence of a file, then read it to a list by stripping newlines. The function aborts the program if the file does not exist. :param str file: Path to an existing file :return: list of strings :rtype: list[str]
lib/doconce/jupyterbook.py
read_to_list
aless80/doconce
python
def read_to_list(file): 'Read the content of a file to list\n\n Verify the existence of a file, then read it to a list by\n stripping newlines. The function aborts the program if the file does not exist.\n\n :param str file: Path to an existing file\n :return: list of strings\n :rtype: list[str]\n ...
def get_link_destinations(chunk): 'Find any target of a link in HTML code\n\n Use regex to find tags with the id or name attribute, which makes them a possible target of a link\n :param str chunk: text string\n :return: destinations, destination_tags\n :rtype: Tuple[list[str], list[str]]\n ' (des...
6,399,748,933,904,265,000
Find any target of a link in HTML code Use regex to find tags with the id or name attribute, which makes them a possible target of a link :param str chunk: text string :return: destinations, destination_tags :rtype: Tuple[list[str], list[str]]
lib/doconce/jupyterbook.py
get_link_destinations
aless80/doconce
python
def get_link_destinations(chunk): 'Find any target of a link in HTML code\n\n Use regex to find tags with the id or name attribute, which makes them a possible target of a link\n :param str chunk: text string\n :return: destinations, destination_tags\n :rtype: Tuple[list[str], list[str]]\n ' (des...
def fix_links(chunk, tag2file): 'Find and fix the the destinations of hyperlinks using HTML or markdown syntax\n\n Fix any link in a string text so that they can target a different html document.\n First use regex on a HTML text to find any HTML or markdown hyperlinks\n (e.g. <a href="#sec1"> or [sec1](#se...
9,217,471,721,488,170,000
Find and fix the the destinations of hyperlinks using HTML or markdown syntax Fix any link in a string text so that they can target a different html document. First use regex on a HTML text to find any HTML or markdown hyperlinks (e.g. <a href="#sec1"> or [sec1](#sec1) ). Then use a dictionary to prepend the filename ...
lib/doconce/jupyterbook.py
fix_links
aless80/doconce
python
def fix_links(chunk, tag2file): 'Find and fix the the destinations of hyperlinks using HTML or markdown syntax\n\n Fix any link in a string text so that they can target a different html document.\n First use regex on a HTML text to find any HTML or markdown hyperlinks\n (e.g. <a href="#sec1"> or [sec1](#se...
def resolve_links_destinations(chunks, chunk_basenames): 'Fix links in jupyter-book chapters/sections so that they can target destinations in other files\n\n Prepend a filename to all links\' destinations e.g. <a href="#Langtangen_2012"> becomes\n <a href="02_jupyterbook.html#Langtangen_2012">\n :param lis...
5,405,938,629,762,071,000
Fix links in jupyter-book chapters/sections so that they can target destinations in other files Prepend a filename to all links' destinations e.g. <a href="#Langtangen_2012"> becomes <a href="02_jupyterbook.html#Langtangen_2012"> :param list[str] chunks: DocOnce texts consisting in Jupyter-book chapters/sections :para...
lib/doconce/jupyterbook.py
resolve_links_destinations
aless80/doconce
python
def resolve_links_destinations(chunks, chunk_basenames): 'Fix links in jupyter-book chapters/sections so that they can target destinations in other files\n\n Prepend a filename to all links\' destinations e.g. <a href="#Langtangen_2012"> becomes\n <a href="02_jupyterbook.html#Langtangen_2012">\n :param lis...
def fix_media_src(filestr, dirname, dest): 'Fix the (relative) path to any figure and movie in the DocOnce file.\n\n The generated .md and .ipynb files will be created in the path passed to `--dest`.\n This method fixes the paths of the image and movie files so that they can be found\n in generated .md and...
358,296,290,649,753,860
Fix the (relative) path to any figure and movie in the DocOnce file. The generated .md and .ipynb files will be created in the path passed to `--dest`. This method fixes the paths of the image and movie files so that they can be found in generated .md and .ipynb files. :param str filestr: text string :param str dirnam...
lib/doconce/jupyterbook.py
fix_media_src
aless80/doconce
python
def fix_media_src(filestr, dirname, dest): 'Fix the (relative) path to any figure and movie in the DocOnce file.\n\n The generated .md and .ipynb files will be created in the path passed to `--dest`.\n This method fixes the paths of the image and movie files so that they can be found\n in generated .md and...
def escape_chars(title): 'Wrap title in quotes if it contains colons, asterisks, bacticks' if (re.search(':', title) or re.search('\\*', title) or re.search('\\`', title)): title = title.replace('"', '\\"') title = (('"' + title) + '"') return title
-4,069,678,415,874,223,600
Wrap title in quotes if it contains colons, asterisks, bacticks
lib/doconce/jupyterbook.py
escape_chars
aless80/doconce
python
def escape_chars(title): if (re.search(':', title) or re.search('\\*', title) or re.search('\\`', title)): title = title.replace('"', '\\"') title = (('"' + title) + '"') return title
def mae(y_true, y_pred): ' Implementation of Mean average error\n ' return K.mean(K.abs((y_true - y_pred)))
8,321,551,904,465,290,000
Implementation of Mean average error
raynet/models.py
mae
paschalidoud/raynet
python
def mae(y_true, y_pred): ' \n ' return K.mean(K.abs((y_true - y_pred)))