uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
49d9d0f7ee07aa5850979825
train
function
def setAnnotations(args, syn): """Method to set annotations on an entity. Requires a JSON-formatted string that evaluates to a dict. Annotations can be updated or overwritten completely. """ try: newannots = json.loads(args.annotations) except Exception as e: sys.stderr.write...
def setAnnotations(args, syn):
"""Method to set annotations on an entity. Requires a JSON-formatted string that evaluates to a dict. Annotations can be updated or overwritten completely. """ try: newannots = json.loads(args.annotations) except Exception as e: sys.stderr.write( "Please check tha...
Provenance(args, syn): activity = syn.getProvenance(args.id, args.version) if args.output is None or args.output == 'STDOUT': print(json.dumps(activity, sort_keys=True, indent=2)) else: with open(args.output, 'w') as f: f.write(json.dumps(activity)) f.write('\n') def...
84
84
282
7
77
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
setAnnotations
setAnnotations
342
376
342
342
d79b41244246bd440e2d386c08fe725837f21a53
bigcode/the-stack
train
302dead8be1f0b5631d95876
train
function
def submit(args, syn): """ Method to allow challenge participants to submit to an evaluation queue. Examples:: synapse submit --evaluation 'ra_challenge_Q1_leaderboard' -f ~/testing/testing.txt --parentId syn2345030 \ --used syn2351967 --executed syn2351968 synapse submit --evaluation 2343117 -...
def submit(args, syn):
""" Method to allow challenge participants to submit to an evaluation queue. Examples:: synapse submit --evaluation 'ra_challenge_Q1_leaderboard' -f ~/testing/testing.txt --parentId syn2345030 \ --used syn2351967 --executed syn2351968 synapse submit --evaluation 2343117 -f ~/testing/testing.txt...
set an annotations called 'foo' to the value 1, the format should be " "'{\"foo\": 1, \"bar\":\"quux\"}'.") entity = syn.get(args.id, downloadFile=False) if args.replace: annots = newannots else: annots = syn.getAnnotations(entity) annots.update(newannots) syn.set...
187
187
625
6
181
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
submit
submit
390
436
390
390
aee77075aafd9e7836e764fbbc36a4eddbedb2ac
bigcode/the-stack
train
ad07fc0fcea935206ffe3e89
train
function
def _getIdsFromQuery(queryString, syn): """Helper function that extracts the ids out of returned query.""" if re.search('from syn\d', queryString.lower()): tbl = syn.tableQuery(queryString) check_for_id_col = filter(lambda x: x.get('id'), tbl.headers) assert check_for_id_col, ValueErro...
def _getIdsFromQuery(queryString, syn):
"""Helper function that extracts the ids out of returned query.""" if re.search('from syn\d', queryString.lower()): tbl = syn.tableQuery(queryString) check_for_id_col = filter(lambda x: x.get('id'), tbl.headers) assert check_for_id_col, ValueError("Query does not include the id column....
".join(row))) else: sys.stderr.write('Input query cannot be parsed. Please see our documentation for writing Synapse query:' ' https://docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html') def _getIdsFromQuery(queryString, syn):
64
64
154
11
53
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
_getIdsFromQuery
_getIdsFromQuery
97
110
97
97
4e94fbabf3c7ddf7a6bda1d4f8151c1292e1704e
bigcode/the-stack
train
f664628969930d7946d8926d
train
function
def move(args, syn): """Moves an entity specified by args.id to args.parentId""" entity = syn.move(args.id, args.parentid) print('Moved %s to %s' % (entity.id, entity.parentId))
def move(args, syn):
"""Moves an entity specified by args.id to args.parentId""" entity = syn.move(args.id, args.parentid) print('Moved %s to %s' % (entity.id, entity.parentId))
File_arg_check(args): """ checks that descriptionFile(if specified) is a valid file path """ if args.descriptionFile: if not os.path.isfile(args.descriptionFile): raise ValueError('The specified descriptionFile path is not a file or does not exist') def move(args, syn):
64
64
51
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
move
move
209
212
209
209
c1b0fd0e81760bac5495e69ffa147493a37be9d7
bigcode/the-stack
train
c6b4557f5461ba109b23d215
train
function
def login(args, syn): """Log in to Synapse, optionally caching credentials""" login_with_prompt(syn, args.synapseUser, args.synapsePassword, rememberMe=args.rememberMe, forced=True) profile = syn.getUserProfile() print("Logged in as: {userName} ({ownerId})".format(**profile))
def login(args, syn):
"""Log in to Synapse, optionally caching credentials""" login_with_prompt(syn, args.synapseUser, args.synapsePassword, rememberMe=args.rememberMe, forced=True) profile = syn.getUserProfile() print("Logged in as: {userName} ({ownerId})".format(**profile))
.entity, name=args.name, team=args.teamName) sys.stdout.write('Submitted (id: %s) entity: %s\t%s to Evaluation: %s\n' % (submission['id'], submission['entityId'], submission['name'], submission['evaluationId'])) def login(args, syn):
63
64
73
6
57
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
login
login
439
443
439
439
52feca603fa1668c052ed4f03618f3fbfe323249
bigcode/the-stack
train
f18fb751ec34ddf342ad7c64
train
function
def test_encoding(args, syn): import locale import platform print("python version = ", platform.python_version()) print("sys.stdout.encoding = ", sys.stdout.encoding if hasattr(sys.stdout, 'encoding') else 'no encoding attribute') print("sys.stdout.isatty() = ...
def test_encoding(args, syn):
import locale import platform print("python version = ", platform.python_version()) print("sys.stdout.encoding = ", sys.stdout.encoding if hasattr(sys.stdout, 'encoding') else 'no encoding attribute') print("sys.stdout.isatty() = ", sys.stdout.isatty()) ...
syn): """Log in to Synapse, optionally caching credentials""" login_with_prompt(syn, args.synapseUser, args.synapsePassword, rememberMe=args.rememberMe, forced=True) profile = syn.getUserProfile() print("Logged in as: {userName} ({ownerId})".format(**profile)) def test_encoding(args, syn):
76
76
256
7
69
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
test_encoding
test_encoding
446
458
446
446
c3b144cf8f7c23cc1ba83d92d8ccd689655ec050
bigcode/the-stack
train
a76be8bd4e6e23b841fd20cb
train
function
def get(args, syn): if args.recursive: if args.version is not None: raise ValueError('You cannot specify a version making a recursive download.') synapseutils.syncFromSynapse(syn, args.id, args.downloadLocation, followLink=args.followLink) elif args.queryString is not None: i...
def get(args, syn):
if args.recursive: if args.version is not None: raise ValueError('You cannot specify a version making a recursive download.') synapseutils.syncFromSynapse(syn, args.id, args.downloadLocation, followLink=args.followLink) elif args.queryString is not None: if args.version is no...
'), tbl.headers) assert check_for_id_col, ValueError("Query does not include the id column.") ids = [x['id'] for x in csv.DictReader(open(tbl.filepath))] return ids else: raise ValueError('Input query cannot be parsed. Please see our documentation for writing Synapse query:' ...
100
101
338
6
94
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
get
get
114
142
114
114
6b9069e284cfbd4523f4cdc10c9daf7f5cfbd47b
bigcode/the-stack
train
a086616248a8265da4607da3
train
function
def _descriptionFile_arg_check(args): """ checks that descriptionFile(if specified) is a valid file path """ if args.descriptionFile: if not os.path.isfile(args.descriptionFile): raise ValueError('The specified descriptionFile path is not a file or does not exist')
def _descriptionFile_arg_check(args):
""" checks that descriptionFile(if specified) is a valid file path """ if args.descriptionFile: if not os.path.isfile(args.descriptionFile): raise ValueError('The specified descriptionFile path is not a file or does not exist')
def _create_wiki_description_if_necessary(args, entity, syn): """ store the description in a Wiki """ if args.description or args.descriptionFile: syn.store(Wiki(markdown=args.description, markdownFile=args.descriptionFile, owner=entity)) def _descriptionFile_arg_check(args):
64
64
61
8
56
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
_descriptionFile_arg_check
_descriptionFile_arg_check
200
206
200
200
1d15d3d695c0d0db1e42920a9641b92207f73e9b
bigcode/the-stack
train
d3c94c841a18bd24bcd23697
train
function
def show(args, syn): """Show metadata for an entity.""" ent = syn.get(args.id, downloadFile=False) syn.printEntity(ent) sys.stdout.write('Provenance:\n') try: prov = syn.getProvenance(ent) print(prov) except SynapseHTTPError: print(' No Activity specified.\n')
def show(args, syn):
"""Show metadata for an entity.""" ent = syn.get(args.id, downloadFile=False) syn.printEntity(ent) sys.stdout.write('Provenance:\n') try: prov = syn.getProvenance(ent) print(prov) except SynapseHTTPError: print(' No Activity specified.\n')
(entity.path) as inputfile: for line in inputfile: sys.stdout.write(line) def ls(args, syn): """List entities in a Project or Folder""" syn._list(args.id, recursive=args.recursive, long_format=args.long, show_modified=args.modified) def show(args, syn):
64
64
78
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
show
show
266
276
266
266
945d2752b1585b8ad4801f6f19f82a4a7e48568b
bigcode/the-stack
train
0bee5d5d57c6a06923bb926d
train
function
def cat(args, syn): try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except (AttributeError, ValueError): # Different OS's have different signals defined. In particular, # SIGPIPE doesn't exist one Windows. The docs have this to say, # "On Windows, signal() can only be called w...
def cat(args, syn):
try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except (AttributeError, ValueError): # Different OS's have different signals defined. In particular, # SIGPIPE doesn't exist one Windows. The docs have this to say, # "On Windows, signal() can only be called with SIGABRT, SIGFPE,...
, args.destinationId, skipCopyWikiPage=args.skipCopyWiki, skipCopyAnnotations=args.skipCopyAnnotations, excludeTypes=args.excludeTypes, version=args.version, updateExisting=args.updateExis...
64
64
158
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
cat
cat
244
258
244
244
d7eab5ab2653a82f354bb41584258b31ff8ddb48
bigcode/the-stack
train
7ee429bebbe91a7bc8206586
train
function
def store(args, syn): # If we are storing a fileEntity we need to have id or parentId if args.parentid is None and args.id is None and args.file is not None: raise ValueError('synapse store requires at least either parentId or id to be specified.') # If both args.FILE and args.file specified raise e...
def store(args, syn): # If we are storing a fileEntity we need to have id or parentId
if args.parentid is None and args.id is None and args.file is not None: raise ValueError('synapse store requires at least either parentId or id to be specified.') # If both args.FILE and args.file specified raise error if args.file and args.FILE: raise ValueError('only specify one file') ...
and entity.path is not None and os.path.exists(entity.path): print("Downloaded file: %s" % os.path.basename(entity.path)) else: print('WARNING: No files associated with entity %s\n' % entity.id) print(entity) print('Creating %s' % entity.path) def ...
133
133
445
24
109
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
store
store
151
189
151
152
3d9ff796aaed4cdcb69bd3122f204277616c7896
bigcode/the-stack
train
b50635cd54a59ac6ead6313a
train
function
def login_with_prompt(syn, user, password, rememberMe=False, silent=False, forced=False): try: syn.login(user, password, silent=silent, rememberMe=rememberMe, forced=forced) except SynapseNoCredentialsError: # if there were no credentials in the cache nor provided, prompt the user and try again ...
def login_with_prompt(syn, user, password, rememberMe=False, silent=False, forced=False):
try: syn.login(user, password, silent=silent, rememberMe=rememberMe, forced=forced) except SynapseNoCredentialsError: # if there were no credentials in the cache nor provided, prompt the user and try again while not user: user = input("Synapse username: ") passwd = N...
' in args: try: args.func(args, syn) except Exception as ex: if args.debug: raise else: sys.stderr.write(utils._synapse_error_msg(ex)) def login_with_prompt(syn, user, password, rememberMe=False, silent=False, forced=False):
64
64
166
21
43
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
login_with_prompt
login_with_prompt
835
848
835
835
ae2bd69681e28e9f52d2240c3e582b8f7ae9f688
bigcode/the-stack
train
c02985b2c2403d6f69320eb7
train
function
def build_parser(): """Builds the argument parser and returns the result.""" USED_HELP = ('Synapse ID, a url, or a local file path (of a file previously' 'uploaded to Synapse) from which the specified entity is derived') EXECUTED_HELP = ('Synapse ID, a url, or a local file path (of a file ...
def build_parser():
"""Builds the argument parser and returns the result.""" USED_HELP = ('Synapse ID, a url, or a local file path (of a file previously' 'uploaded to Synapse) from which the specified entity is derived') EXECUTED_HELP = ('Synapse ID, a url, or a local file path (of a file previously' ...
, syn): import locale import platform print("python version = ", platform.python_version()) print("sys.stdout.encoding = ", sys.stdout.encoding if hasattr(sys.stdout, 'encoding') else 'no encoding attribute') print("sys.stdout.isatty() = ", sys.stdout.isatty...
256
256
4,917
4
252
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
build_parser
build_parser
461
821
461
461
fa3503e53a98936092cd5ed6143537a270b7f4f2
bigcode/the-stack
train
71d2582e1bbdd8378f210e44
train
function
def query(args, syn): try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except (AttributeError, ValueError): # Different OS's have different signals defined. In particular, # SIGPIPE doesn't exist on Windows. The docs have this to say, # "On Windows, signal() can only be called ...
def query(args, syn):
try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except (AttributeError, ValueError): # Different OS's have different signals defined. In particular, # SIGPIPE doesn't exist on Windows. The docs have this to say, # "On Windows, signal() can only be called with SIGABRT, SIGFPE, ...
few more commands (cat, create, update, associate) """ import argparse import os import sys import synapseclient import synapseutils from . import Activity import signal import json from synapseclient.core.exceptions import * from .wiki import Wiki import getpass import csv import re def query(args, syn):
73
73
245
6
66
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
query
query
73
94
73
73
5e5447ba6ea7262fc9f6e4e5befedafe237860bc
bigcode/the-stack
train
fde96dd52300045e979cac89
train
function
def getProvenance(args, syn): activity = syn.getProvenance(args.id, args.version) if args.output is None or args.output == 'STDOUT': print(json.dumps(activity, sort_keys=True, indent=2)) else: with open(args.output, 'w') as f: f.write(json.dumps(activity)) f.write('\...
def getProvenance(args, syn):
activity = syn.getProvenance(args.id, args.version) if args.output is None or args.output == 'STDOUT': print(json.dumps(activity, sort_keys=True, indent=2)) else: with open(args.output, 'w') as f: f.write(json.dumps(activity)) f.write('\n')
: with open(args.output, 'w') as f: f.write(json.dumps(activity)) f.write('\n') else: print('Set provenance record %s on entity %s\n' % (str(activity['id']), str(args.id))) def getProvenance(args, syn):
63
64
79
9
54
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
getProvenance
getProvenance
331
339
331
331
035c3dee1fc2bec43be7c70bad045a9e38135bd3
bigcode/the-stack
train
f1ef8da616ac263dc4d0047f
train
function
def delete(args, syn): if args.version: syn.delete(args.id, args.version) print('Deleted entity %s, version %s' % (args.id, args.version)) else: syn.delete(args.id) print('Deleted entity: %s' % args.id)
def delete(args, syn):
if args.version: syn.delete(args.id, args.version) print('Deleted entity %s, version %s' % (args.id, args.version)) else: syn.delete(args.id) print('Deleted entity: %s' % args.id)
.id, downloadFile=False) syn.printEntity(ent) sys.stdout.write('Provenance:\n') try: prov = syn.getProvenance(ent) print(prov) except SynapseHTTPError: print(' No Activity specified.\n') def delete(args, syn):
64
64
62
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
delete
delete
279
285
279
279
2ee124b80b54c76a93447468208165b43a410211
bigcode/the-stack
train
5be21d149490f723c9f18662
train
function
def sync(args, syn): synapseutils.syncToSynapse(syn, manifestFile=args.manifestFile, dryRun=args.dryRun, sendMessages=args.sendMessages, retries=args.retries)
def sync(args, syn):
synapseutils.syncToSynapse(syn, manifestFile=args.manifestFile, dryRun=args.dryRun, sendMessages=args.sendMessages, retries=args.retries)
os.path.exists(entity.path): print("Downloaded file: %s" % os.path.basename(entity.path)) else: print('WARNING: No files associated with entity %s\n' % entity.id) print(entity) print('Creating %s' % entity.path) def sync(args, syn):
64
64
44
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
sync
sync
145
148
145
145
48bc6d3a9032ec9996f4acd147f5be8b12fbbf94
bigcode/the-stack
train
1b584ad4b953a9a46ce3d417
train
function
def _create_wiki_description_if_necessary(args, entity, syn): """ store the description in a Wiki """ if args.description or args.descriptionFile: syn.store(Wiki(markdown=args.description, markdownFile=args.descriptionFile, owner=entity))
def _create_wiki_description_if_necessary(args, entity, syn):
""" store the description in a Wiki """ if args.description or args.descriptionFile: syn.store(Wiki(markdown=args.description, markdownFile=args.descriptionFile, owner=entity))
if there are annotations to add then # add them if args.annotations is not None: # Need to override the args id parameter setattr(args, 'id', entity['id']) setAnnotations(args, syn) def _create_wiki_description_if_necessary(args, entity, syn):
64
64
56
15
49
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
_create_wiki_description_if_necessary
_create_wiki_description_if_necessary
192
197
192
192
beda59f438f223960568a0eec664dc46839a3e68
bigcode/the-stack
train
8575b9c1a964a2657c32f54f
train
function
def copy(args, syn): mappings = synapseutils.copy(syn, args.id, args.destinationId, skipCopyWikiPage=args.skipCopyWiki, skipCopyAnnotations=args.skipCopyAnnotations, excludeTypes=args.excludeTypes, ...
def copy(args, syn):
mappings = synapseutils.copy(syn, args.id, args.destinationId, skipCopyWikiPage=args.skipCopyWiki, skipCopyAnnotations=args.skipCopyAnnotations, excludeTypes=args.excludeTypes, version...
, limitSearch=args.limitSearch) except SynapseFileNotFoundError: print('WARNING: The file %s is not available in Synapse' % fp) else: print('%s.%i\t%s' % (ent.id, ent.versionNumber, fp)) def copy(args, syn):
64
64
76
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
copy
copy
234
241
234
234
74413a9fbe77aa9eda4099f9d25330af1e0dfc08
bigcode/the-stack
train
9cd6065e1e4e25f7ee21654c
train
function
def ls(args, syn): """List entities in a Project or Folder""" syn._list(args.id, recursive=args.recursive, long_format=args.long, show_modified=args.modified)
def ls(args, syn):
"""List entities in a Project or Folder""" syn._list(args.id, recursive=args.recursive, long_format=args.long, show_modified=args.modified)
Error will be raised # in any other case." pass entity = syn.get(args.id, version=args.version) if 'path' in entity: with open(entity.path) as inputfile: for line in inputfile: sys.stdout.write(line) def ls(args, syn):
64
64
38
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
ls
ls
261
263
261
261
8fa514982e7b04d765fe2798a72ba71192653262
bigcode/the-stack
train
b5759057765bb7ea0e1557b2
train
function
def setProvenance(args, syn): """Set provenance information on a synapse entity.""" activity = Activity(name=args.name, description=args.description) if args.used: for item in syn._convertProvenanceList(args.used, args.limitSearch): activity.used(item) if args.executed: for...
def setProvenance(args, syn):
"""Set provenance information on a synapse entity.""" activity = Activity(name=args.name, description=args.description) if args.used: for item in syn._convertProvenanceList(args.used, args.limitSearch): activity.used(item) if args.executed: for item in syn._convertProvenanc...
Entity(entity) _create_wiki_description_if_necessary(args, entity, syn) print('Created entity: %s\t%s\n' % (entity['id'], entity['name'])) def onweb(args, syn): syn.onweb(args.id) def setProvenance(args, syn):
64
64
207
9
55
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
setProvenance
setProvenance
305
328
305
305
22360ada74ca55f5da584db9b5f0615641dcd2e0
bigcode/the-stack
train
38ba2a382c3d8d46078c8e28
train
function
def associate(args, syn): files = [] if args.r: files = [os.path.join(dp, f) for dp, dn, filenames in os.walk(args.path) for f in filenames] if os.path.isfile(args.path): files = [args.path] if len(files) == 0: raise Exception(("The path specified is inaccurate. ...
def associate(args, syn):
files = [] if args.r: files = [os.path.join(dp, f) for dp, dn, filenames in os.walk(args.path) for f in filenames] if os.path.isfile(args.path): files = [args.path] if len(files) == 0: raise Exception(("The path specified is inaccurate. " ...
a file or does not exist') def move(args, syn): """Moves an entity specified by args.id to args.parentId""" entity = syn.move(args.id, args.parentid) print('Moved %s to %s' % (entity.id, entity.parentId)) def associate(args, syn):
64
64
168
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
associate
associate
215
231
215
215
e5e9a5a96ada54c398a206fe0a5f5fe2f4c358ed
bigcode/the-stack
train
2ea4a1808117ef837bf58d18
train
function
def main(): args = build_parser().parse_args() synapseclient.USER_AGENT['User-Agent'] = "synapsecommandlineclient " + synapseclient.USER_AGENT['User-Agent'] syn = synapseclient.Synapse(debug=args.debug, skip_checks=args.skip_checks, configPath=args.configPath) if not ('func' in args and args.func == log...
def main():
args = build_parser().parse_args() synapseclient.USER_AGENT['User-Agent'] = "synapsecommandlineclient " + synapseclient.USER_AGENT['User-Agent'] syn = synapseclient.Synapse(debug=args.debug, skip_checks=args.skip_checks, configPath=args.configPath) if not ('func' in args and args.func == login): ...
getpass() has OS-dependent implementation and complains about unicode # on Windows python 2.7 passwd = getpass.getpass(("Password for " + user + ": ").encode('utf-8')) syn.login(user, passwd, rememberMe=rememberMe, forced=forced) def main():
64
64
124
3
61
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
main
main
851
858
851
851
5778f50493f72ae50b1bff01187ec0add0a0c3d8
bigcode/the-stack
train
15456bcc8dc405284605ccf8
train
function
def onweb(args, syn): syn.onweb(args.id)
def onweb(args, syn):
syn.onweb(args.id)
etworks.repo.model.%s' % args.type} entity = syn.createEntity(entity) _create_wiki_description_if_necessary(args, entity, syn) print('Created entity: %s\t%s\n' % (entity['id'], entity['name'])) def onweb(args, syn):
63
64
14
7
56
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
onweb
onweb
301
302
301
301
b2e0a005984828b645ae2d9e08d08bfb9fcb5157
bigcode/the-stack
train
6a133a813581e7179f90ed64
train
function
def rename_cv(x): if x=='General purpose image/video tools (PIL, cv2, skimage, etc)': return 'General purpose tools' if x=='Generative Networks (GAN, VAE, etc)': return 'Generative Networks' if x=='Image classification and other general purpose networks (VGG, Inception, ResNet, ResNeXt, NASN...
def rename_cv(x):
if x=='General purpose image/video tools (PIL, cv2, skimage, etc)': return 'General purpose tools' if x=='Generative Networks (GAN, VAE, etc)': return 'Generative Networks' if x=='Image classification and other general purpose networks (VGG, Inception, ResNet, ResNeXt, NASNet, EfficientNet, ...
x=='Recurrent Neural Networks': return 'RNN' if x=='Linear or Logistic Regression': return 'Linear/Logistic Regression' if x=='Transformer Networks (BERT, gpt-3, etc)': return 'Transformers' return x def rename_cv(x):
64
64
151
5
58
javirasu/kaggle-survey-2020
funcs.py
Python
rename_cv
rename_cv
96
107
96
96
e5154a6af9e50a62d872d9d8092dffa7ae60cfbd
bigcode/the-stack
train
c5e2b1c7e0c23e4f52b7d190
train
function
def rename_nlp(x): if x=='Contextualized embeddings (ELMo, CoVe)': return 'Contextualized embeddings' if x=='Encoder-decorder models (seq2seq, vanilla transformers)': return 'Encoder-decorder models' if x=='Transformer language models (GPT-3, BERT, XLnet, etc)': return 'Transformers'...
def rename_nlp(x):
if x=='Contextualized embeddings (ELMo, CoVe)': return 'Contextualized embeddings' if x=='Encoder-decorder models (seq2seq, vanilla transformers)': return 'Encoder-decorder models' if x=='Transformer language models (GPT-3, BERT, XLnet, etc)': return 'Transformers' if x=='Word em...
'Image classification' if x=='Image segmentation methods (U-Net, Mask R-CNN, etc)': return 'Image segmentation' if x=='Object detection methods (YOLOv3, RetinaNet, etc)': return 'Object detection' return x def rename_nlp(x):
64
64
115
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
rename_nlp
rename_nlp
109
118
109
109
70ec5c3652c32d0f0e8eb12580885efdc46a6838
bigcode/the-stack
train
d1e041dbadf20fc42c8b8077
train
function
def rename_ide(x): if x == 'Jupyter (JupyterLab, Jupyter Notebooks, etc) ': return 'Jupyter' if x == ' RStudio ': return 'RStudio' if x == 'Visual Studio': return 'Visual Studio' if x == 'Visual Studio Code (VSCode)': return 'VSCode' if x == ' PyCharm ': retur...
def rename_ide(x):
if x == 'Jupyter (JupyterLab, Jupyter Notebooks, etc) ': return 'Jupyter' if x == ' RStudio ': return 'RStudio' if x == 'Visual Studio': return 'Visual Studio' if x == 'Visual Studio Code (VSCode)': return 'VSCode' if x == ' PyCharm ': return 'PyCharm' if ...
() dat = [] for x in raw_dat: try: if not np.isnan(x): dat.append(x) except Exception: dat.append(x) if rename is not None: dat = [rename(x) for x in dat] return dat def rename_ide(x):
65
65
217
6
58
javirasu/kaggle-survey-2020
funcs.py
Python
rename_ide
rename_ide
18
43
18
18
4b919f1741cef57681cedaf55ba67fe8191bf247
bigcode/the-stack
train
5dac24a1bc5da0e1a5a32f0b
train
function
def map_yrs_prog(x): if x=='I have never written code': return 0 if x=='< 1 years': return 0.5 if x=='1-2 years': return 1.5 if x=='3-5 years': return 4 if x=='5-10 years': return 7.5 if x=='10-20 years': return 15 if x=='20+ years': re...
def map_yrs_prog(x):
if x=='I have never written code': return 0 if x=='< 1 years': return 0.5 if x=='1-2 years': return 1.5 if x=='3-5 years': return 4 if x=='5-10 years': return 7.5 if x=='10-20 years': return 15 if x=='20+ years': return 20 return np...
': return 4.5 if x=='5-10 years': return 7.5 if x=='10-20 years': return 15 if x=='20 or more years': return 20 return np.nan def map_yrs_prog(x):
64
64
116
7
56
javirasu/kaggle-survey-2020
funcs.py
Python
map_yrs_prog
map_yrs_prog
286
301
286
286
9b23e22d8aade247b17952fd5740ec14b0e4d1da
bigcode/the-stack
train
f1c9ce5fdf06e48fe5b00a4d
train
function
def rename_automl(x): if x=='Automated data augmentation (e.g. imgaug, albumentations)': return 'Auto. data augmentation' if x=='Automated feature engineering/selection (e.g. tpot, boruta_py)': return 'Auto. feature engineering/selection' if x=='Automated hyperparameter tuning (e.g. hyperopt...
def rename_automl(x):
if x=='Automated data augmentation (e.g. imgaug, albumentations)': return 'Auto. data augmentation' if x=='Automated feature engineering/selection (e.g. tpot, boruta_py)': return 'Auto. feature engineering/selection' if x=='Automated hyperparameter tuning (e.g. hyperopt, ray.tune, Vizier)': ...
stein Analytics': return 'Einstein Anal.' if x=='Google Data Studio': return 'Google Data' if x=='Microsoft Power BI': return 'Microsoft BI' if x=='SAP Analytics Cloud ': return 'SAP Anal.' return x def rename_automl(x):
64
64
195
7
56
javirasu/kaggle-survey-2020
funcs.py
Python
rename_automl
rename_automl
160
173
160
160
5f4ab32013bfdd3fdb3df4e742f8b4b425d3c0e3
bigcode/the-stack
train
d9cdf3e79e1c7adbb3ccee58
train
function
def rename_mlprod(x): if x==' Azure Machine Learning Studio ': return ' Azure ML Studio ' if x==' Google Cloud AI Platform / Google Cloud ML Engine': return 'gCloud AI Platform' if x==' Google Cloud Natural Language ': return 'gCloud NLP' if x==' Google Cloud Video AI ': ...
def rename_mlprod(x):
if x==' Azure Machine Learning Studio ': return ' Azure ML Studio ' if x==' Google Cloud AI Platform / Google Cloud ML Engine': return 'gCloud AI Platform' if x==' Google Cloud Natural Language ': return 'gCloud NLP' if x==' Google Cloud Video AI ': return 'gCloud Video' ...
return 'Word embeddings/vectors' return x def rename_cloudplat(x): if x==' Amazon Web Services (AWS) ': return 'AWS' if x==' Google Cloud Platform (GCP) ': return 'GCP' return x def rename_mlprod(x):
64
64
100
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
rename_mlprod
rename_mlprod
127
138
127
127
bc0739189cc2aa2b593300cbc48978b95c077510
bigcode/the-stack
train
f590042c8ae4893a3308c64b
train
function
def rename_courses(x): if x=='Cloud-certification programs (direct from AWS, Azure, GCP, or similar)': return 'Cloud-certification' if x=='University Courses (resulting in a university degree)': return 'University Degree' return x
def rename_courses(x):
if x=='Cloud-certification programs (direct from AWS, Azure, GCP, or similar)': return 'Cloud-certification' if x=='University Courses (resulting in a university degree)': return 'University Degree' return x
ML pipelines' return x def rename_manage(x): if x=='Domino Model Monitor': return 'Domino Monitor' return x def rename_share(x): if x=='I do not share my work publicly': return 'Not share' return x def rename_courses(x):
64
64
59
5
58
javirasu/kaggle-survey-2020
funcs.py
Python
rename_courses
rename_courses
185
190
185
185
3d4f6089138749dc9fa530467e394b900df98a44
bigcode/the-stack
train
8f5d7a39c3b3ddb015198d20
train
function
def rename_bigdata(x): if 'Google Cloud' in x: return 'gCloud '+x.split('Google Cloud')[-1] if x=='Microsoft Azure Data Lake Storage ': return 'Azure Data Lake' if x=='Microsoft SQL Server ': return 'Microsoft SQL' return x
def rename_bigdata(x):
if 'Google Cloud' in x: return 'gCloud '+x.split('Google Cloud')[-1] if x=='Microsoft Azure Data Lake Storage ': return 'Azure Data Lake' if x=='Microsoft SQL Server ': return 'Microsoft SQL' return x
AI Platform' if x==' Google Cloud Natural Language ': return 'gCloud NLP' if x==' Google Cloud Video AI ': return 'gCloud Video' if x==' Google Cloud Vision AI ': return 'gCloud Vision' return x def rename_bigdata(x):
64
64
67
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
rename_bigdata
rename_bigdata
140
147
140
140
cdcb70a6eb54569af01f56bfdb16a6f0cb18e3ed
bigcode/the-stack
train
ccdb197857f1c60fe743736c
train
function
def rename_bi(x): if x=='Einstein Analytics': return 'Einstein Anal.' if x=='Google Data Studio': return 'Google Data' if x=='Microsoft Power BI': return 'Microsoft BI' if x=='SAP Analytics Cloud ': return 'SAP Anal.' return x
def rename_bi(x):
if x=='Einstein Analytics': return 'Einstein Anal.' if x=='Google Data Studio': return 'Google Data' if x=='Microsoft Power BI': return 'Microsoft BI' if x=='SAP Analytics Cloud ': return 'SAP Anal.' return x
Google Cloud' in x: return 'gCloud '+x.split('Google Cloud')[-1] if x=='Microsoft Azure Data Lake Storage ': return 'Azure Data Lake' if x=='Microsoft SQL Server ': return 'Microsoft SQL' return x def rename_bi(x):
64
64
68
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
rename_bi
rename_bi
149
158
149
149
2173a73b6b13dccfff85e41b4f947c88b33e6bac
bigcode/the-stack
train
6666d97ddd1137f3ecd2e574
train
function
def generate_result_difference(k, res_neophytes, res_expert, experience): labels = np.unique(res_neophytes[k]+res_expert[k]) df = pd.DataFrame(np.zeros((labels.shape[0], 2)), columns=['neophytes', 'experts'], index=labels) for lang, counts in zip(*np.unique(res_neophytes[k], return_counts=True)): df...
def generate_result_difference(k, res_neophytes, res_expert, experience):
labels = np.unique(res_neophytes[k]+res_expert[k]) df = pd.DataFrame(np.zeros((labels.shape[0], 2)), columns=['neophytes', 'experts'], index=labels) for lang, counts in zip(*np.unique(res_neophytes[k], return_counts=True)): df.loc[lang, 'neophytes'] = counts/np.sum(experience['lvl'].values==0) f...
df.loc[lang, 'experts'] = counts/np.sum(experience['lvl'].values==1) fig, ax = plt.subplots(figsize=(20,8)) plt.title(k) df.plot.bar(ax=ax, rot=0) plt.tight_layout() plt.show() def generate_result_difference(k, res_neophytes, res_expert, experience):
78
78
263
17
61
javirasu/kaggle-survey-2020
funcs.py
Python
generate_result_difference
generate_result_difference
316
332
316
316
dde45e9e75ffc7e3012741c3fd61ef2253fcab61
bigcode/the-stack
train
b209e301fec776739e3330f0
train
function
def rename_manage(x): if x=='Domino Model Monitor': return 'Domino Monitor' return x
def rename_manage(x):
if x=='Domino Model Monitor': return 'Domino Monitor' return x
(e.g. auto-sklearn, xcessiv)': return 'Auto. model selection' if x=='Automation of full ML pipelines (e.g. Google AutoML, H20 Driverless AI)': return 'Auto. full ML pipelines' return x def rename_manage(x):
64
64
25
5
58
javirasu/kaggle-survey-2020
funcs.py
Python
rename_manage
rename_manage
175
178
175
175
20339f2f5ec2241584239de758fad2e47e5fbd88
bigcode/the-stack
train
530df6a9e2869b408afde159
train
function
def rename_hosted(x): if x==' Amazon EMR Notebooks ': return 'Amazon EMR Notebooks' if x==' Amazon Sagemaker Studio ': return 'Amazon Sagemaker' if x==' Binder / JupyterHub ': return 'Binder' if x==' Code Ocean ': return 'Code Ocean' if x==' Databricks Collaborative N...
def rename_hosted(x):
if x==' Amazon EMR Notebooks ': return 'Amazon EMR Notebooks' if x==' Amazon Sagemaker Studio ': return 'Amazon Sagemaker' if x==' Binder / JupyterHub ': return 'Binder' if x==' Code Ocean ': return 'Code Ocean' if x==' Databricks Collaborative Notebooks ': re...
/ Emacs ': return 'Vim / Emacs' if x == ' MATLAB ': return 'MATLAB' if x == 'None': return 'None' if x == 'Other': return 'Other' return 'nan' def rename_hosted(x):
64
64
198
6
58
javirasu/kaggle-survey-2020
funcs.py
Python
rename_hosted
rename_hosted
45
66
45
45
13b7df05cdd1b99203b26922cb8a390e95843c3d
bigcode/the-stack
train
98a5964619c4f384f1d32570
train
function
def map_company_size(x): if '0-49 employees': return 25 if '50-249 employees': return 150 if '250-999 employees': return 625 if '1000-9,999 employees': return 5500 if '10,000 or more employees': return 10000 return np.nan
def map_company_size(x):
if '0-49 employees': return 25 if '50-249 employees': return 150 if '250-999 employees': return 625 if '1000-9,999 employees': return 5500 if '10,000 or more employees': return 10000 return np.nan
5 if x=='5-9': return 7 if x=='10-14': return 12 if x=='15-19': return 17 if x=='20+': return 20 return np.nan def map_company_size(x):
64
64
83
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
map_company_size
map_company_size
252
263
252
252
0c698c430cc281bd90741617569d16221801580a
bigcode/the-stack
train
fbca73f6f3e0d70293898eef
train
function
def process_dataframe(df): res = dict() res['prog_lang'] = extract_data(cols_programming, df) res['ide'] = extract_data(cols_ide, df, rename_ide) res['hosted'] = extract_data(cols_hosted_notebook, df, rename_hosted) res['computing'] = extract_data(['What type of computing platform do you use most of...
def process_dataframe(df):
res = dict() res['prog_lang'] = extract_data(cols_programming, df) res['ide'] = extract_data(cols_ide, df, rename_ide) res['hosted'] = extract_data(cols_hosted_notebook, df, rename_hosted) res['computing'] = extract_data(['What type of computing platform do you use most often for your data science p...
'Kaggle (notebooks, forums, etc)', 'None', 'Other', 'Podcasts (Chai Time Data Science, O’Reilly Data Show, etc)', 'Reddit (r/machinelearning, etc)', 'Slack Communities (ods.ai, kagglenoobs, etc)', 'Twitter (data science influencers)', 'YouTube (Kaggle YouTube, Cloud AI Adventures, et...
119
119
398
5
114
javirasu/kaggle-survey-2020
funcs.py
Python
process_dataframe
process_dataframe
210
233
210
210
d22a2540e49d32f307137f8b6b2dd4d0107a0663
bigcode/the-stack
train
197c8b048271591a1a06ebd6
train
function
def map_yrs_ml(x): if x=='I do not use machine learning methods': return 0 if x=='Under 1 year': return 0.5 if x=='1-2 years': return 1.5 if x=='2-3 years': return 2.5 if x=='3-4 years': return 3.5 if x=='4-5 years': return 4.5 if x=='5-10 year...
def map_yrs_ml(x):
if x=='I do not use machine learning methods': return 0 if x=='Under 1 year': return 0.5 if x=='1-2 years': return 1.5 if x=='2-3 years': return 2.5 if x=='3-4 years': return 3.5 if x=='4-5 years': return 4.5 if x=='5-10 years': return ...
': return 150 if '250-999 employees': return 625 if '1000-9,999 employees': return 5500 if '10,000 or more employees': return 10000 return np.nan def map_yrs_ml(x):
64
64
153
7
56
javirasu/kaggle-survey-2020
funcs.py
Python
map_yrs_ml
map_yrs_ml
265
284
265
265
165a934ded0f5dd66ae06934d79756899514c3f1
bigcode/the-stack
train
d1556f09aa48a2d122f23038
train
function
def rename_share(x): if x=='I do not share my work publicly': return 'Not share' return x
def rename_share(x):
if x=='I do not share my work publicly': return 'Not share' return x
=='Automation of full ML pipelines (e.g. Google AutoML, H20 Driverless AI)': return 'Auto. full ML pipelines' return x def rename_manage(x): if x=='Domino Model Monitor': return 'Domino Monitor' return x def rename_share(x):
64
64
27
5
58
javirasu/kaggle-survey-2020
funcs.py
Python
rename_share
rename_share
180
183
180
180
75726a8f5aa210ae1286dc2dd7bc8ff7fd7fb603
bigcode/the-stack
train
469d572ff34a56cf52543103
train
function
def rename_computing(x): if x=='A cloud computing platform (AWS, Azure, GCP, hosted notebooks, etc)': return 'Cloud computing' if x=='A deep learning workstation (NVIDIA GTX, LambdaLabs, etc)': return 'DL workstation' if x=='A personal computer or laptop': return 'PC' return x
def rename_computing(x):
if x=='A cloud computing platform (AWS, Azure, GCP, hosted notebooks, etc)': return 'Cloud computing' if x=='A deep learning workstation (NVIDIA GTX, LambdaLabs, etc)': return 'DL workstation' if x=='A personal computer or laptop': return 'PC' return x
return 'Paperspace / Gradient' if x=='Google Cloud AI Platform Notebooks ': return 'gCloud AI Platform Notebooks ' if x=='Google Cloud Datalab Notebooks': return 'gCloud Datalab Notebooks' return x def rename_computing(x):
64
64
79
7
56
javirasu/kaggle-survey-2020
funcs.py
Python
rename_computing
rename_computing
68
75
68
68
388b0c1b0e8200e373cf8b57cd712b3fa2652d43
bigcode/the-stack
train
56849da2c8f43da1f660626c
train
function
def map_team_size(x): if x=='0': return 0 if x=='1-2': return 1.5 if x=='3-4': return 3.5 if x=='5-9': return 7 if x=='10-14': return 12 if x=='15-19': return 17 if x=='20+': return 20 return np.nan
def map_team_size(x):
if x=='0': return 0 if x=='1-2': return 1.5 if x=='3-4': return 3.5 if x=='5-9': return 7 if x=='10-14': return 12 if x=='15-19': return 17 if x=='20+': return 20 return np.nan
_manage) res['share'] = extract_data(cols_share, df, rename_share) res['courses'] = extract_data(cols_courses, df, rename_courses) res['socialplatform'] = extract_data(cols_socialplatform, df, rename_socialplatform) return res def map_team_size(x):
64
64
103
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
map_team_size
map_team_size
235
250
235
235
9d046f3aeb997e70d994f008040d22bd61ef2e69
bigcode/the-stack
train
497ee7199863d1894bb00c96
train
function
def rename_mlalgos(x): if x=='Convolutional Neural Networks': return 'CNN' if x=='Decision Trees or Random Forests': return 'CNN' if x=='Dense Neural Networks (MLPs, etc)': return 'MLP' if x=='Generative Adversarial Networks': return 'GAN' if x=='Gradient Boosting Mac...
def rename_mlalgos(x):
if x=='Convolutional Neural Networks': return 'CNN' if x=='Decision Trees or Random Forests': return 'CNN' if x=='Dense Neural Networks (MLPs, etc)': return 'MLP' if x=='Generative Adversarial Networks': return 'GAN' if x=='Gradient Boosting Machines (xgboost, lightgb...
, hosted notebooks, etc)': return 'Cloud computing' if x=='A deep learning workstation (NVIDIA GTX, LambdaLabs, etc)': return 'DL workstation' if x=='A personal computer or laptop': return 'PC' return x def rename_mlalgos(x):
64
64
161
7
56
javirasu/kaggle-survey-2020
funcs.py
Python
rename_mlalgos
rename_mlalgos
77
94
77
77
876cc3543218ae475635c998a684fc7c3f7ac843
bigcode/the-stack
train
251d5d58e949d6bffe430853
train
function
def extract_data(cols, df, rename=None): raw_dat = df[cols].values.flatten().copy() dat = [] for x in raw_dat: try: if not np.isnan(x): dat.append(x) except Exception: dat.append(x) if rename is not None: dat = [rename(x) for x in dat] ...
def extract_data(cols, df, rename=None):
raw_dat = df[cols].values.flatten().copy() dat = [] for x in raw_dat: try: if not np.isnan(x): dat.append(x) except Exception: dat.append(x) if rename is not None: dat = [rename(x) for x in dat] return dat
import numpy as np import pandas as pd from matplotlib import pyplot as plt def extract_data(cols, df, rename=None):
27
64
81
10
16
javirasu/kaggle-survey-2020
funcs.py
Python
extract_data
extract_data
5
16
5
5
61d95c5f356e8ce2ceed59d02358f32827907e2d
bigcode/the-stack
train
d392ec2ee18e2442a5b14631
train
function
def generate_result(k, res_neophytes, res_expert, experience): labels = np.unique(res_neophytes[k]+res_expert[k]) df = pd.DataFrame(np.zeros((labels.shape[0], 2)), columns=['neophytes', 'experts'], index=labels) for lang, counts in zip(*np.unique(res_neophytes[k], return_counts=True)): df.loc[lang, ...
def generate_result(k, res_neophytes, res_expert, experience):
labels = np.unique(res_neophytes[k]+res_expert[k]) df = pd.DataFrame(np.zeros((labels.shape[0], 2)), columns=['neophytes', 'experts'], index=labels) for lang, counts in zip(*np.unique(res_neophytes[k], return_counts=True)): df.loc[lang, 'neophytes'] = counts/np.sum(experience['lvl'].values==0) f...
if x=='5-10 years': return 7.5 if x=='10-20 years': return 15 if x=='20+ years': return 20 return np.nan def generate_result(k, res_neophytes, res_expert, experience):
64
64
189
16
47
javirasu/kaggle-survey-2020
funcs.py
Python
generate_result
generate_result
303
314
303
303
348a0cea7866f4bbe37c29d50cecf0953f9c5429
bigcode/the-stack
train
802a8d4596a4703519af3bc8
train
function
def rename_cloudplat(x): if x==' Amazon Web Services (AWS) ': return 'AWS' if x==' Google Cloud Platform (GCP) ': return 'GCP' return x
def rename_cloudplat(x):
if x==' Amazon Web Services (AWS) ': return 'AWS' if x==' Google Cloud Platform (GCP) ': return 'GCP' return x
x=='Transformer language models (GPT-3, BERT, XLnet, etc)': return 'Transformers' if x=='Word embeddings/vectors (GLoVe, fastText, word2vec)': return 'Word embeddings/vectors' return x def rename_cloudplat(x):
64
64
46
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
rename_cloudplat
rename_cloudplat
120
125
120
120
a71587bf2d5d374228aefe7e39b7105df06f7ab8
bigcode/the-stack
train
52071f1509f1d06740b2cd66
train
function
def rename_socialplatform(x): platforms = [ 'Blogs (Towards Data Science, Analytics Vidhya, etc)', 'Course Forums (forums.fast.ai, Coursera forums, etc)', "Email newsletters (Data Elixir, O'Reilly Data & AI, etc)", 'Journal Publications (peer-reviewed journals, conference proceedings, et...
def rename_socialplatform(x):
platforms = [ 'Blogs (Towards Data Science, Analytics Vidhya, etc)', 'Course Forums (forums.fast.ai, Coursera forums, etc)', "Email newsletters (Data Elixir, O'Reilly Data & AI, etc)", 'Journal Publications (peer-reviewed journals, conference proceedings, etc)', 'Kaggle (notebooks...
rename_courses(x): if x=='Cloud-certification programs (direct from AWS, Azure, GCP, or similar)': return 'Cloud-certification' if x=='University Courses (resulting in a university degree)': return 'University Degree' return x def rename_socialplatform(x):
64
64
187
6
57
javirasu/kaggle-survey-2020
funcs.py
Python
rename_socialplatform
rename_socialplatform
192
208
192
192
64f551ffe9e6c4e7a0d29364b6ad9bda2211f004
bigcode/the-stack
train
b9c6a4775595098d576d4cba
train
function
def _set_last_step_outputs(ctx, last_step_tensor_outputs): """Sets the last step outputs on the given context.""" # Convert replicate_outputs to the original dict structure of # last_step_outputs. last_step_tensor_outputs_dict = nest.pack_sequence_as( ctx.last_step_outputs, last_step_tensor_outputs) ...
def _set_last_step_outputs(ctx, last_step_tensor_outputs):
"""Sets the last step outputs on the given context.""" # Convert replicate_outputs to the original dict structure of # last_step_outputs. last_step_tensor_outputs_dict = nest.pack_sequence_as( ctx.last_step_outputs, last_step_tensor_outputs) for name, reduce_op in ctx._last_step_outputs_reduce_op...
Tensor` inside `tpu.replicate`. # TODO(cjfj): Return other devices when model parallelism is supported. return (tpu.core(0),) else: return (ds.extended.worker_devices[replica_id],) def _set_last_step_outputs(ctx, last_step_tensor_outputs):
68
68
229
13
55
uve/tensorflow
tensorflow/python/distribute/tpu_strategy.py
Python
_set_last_step_outputs
_set_last_step_outputs
727
744
727
727
2c5938064c9d73b077b347b9766e27557552c094
bigcode/the-stack
train
92e1bbb3c4630a148cc58c7b
train
class
class _TPUReplicaContext(distribute_lib.ReplicaContext): """Replication Context class for TPU Strategy.""" # TODO(sourabhbajaj): Call for each replica should be updating this. # TODO(b/118385803): Always properly initialize replica_id. def __init__(self, strategy, replica_id_in_sync_group=None): if r...
class _TPUReplicaContext(distribute_lib.ReplicaContext):
"""Replication Context class for TPU Strategy.""" # TODO(sourabhbajaj): Call for each replica should be updating this. # TODO(b/118385803): Always properly initialize replica_id. def __init__(self, strategy, replica_id_in_sync_group=None): if replica_id_in_sync_group is None: replica_id_in_sync...
disable=protected-access return values.regroup(device_map, replicate_outputs) if context.executing_eagerly(): tpu_function = def_function.function(tpu_function) self._tpu_function_cache[fn] = tpu_function return tpu_function class _TPUReplicaContext(distribute_lib.ReplicaContext):
72
72
240
14
57
uve/tensorflow
tensorflow/python/distribute/tpu_strategy.py
Python
_TPUReplicaContext
_TPUReplicaContext
703
724
703
703
52f2859cbfb5574e0d12d0c7a9f4fe7d67d72c03
bigcode/the-stack
train
25e48e01eae723b66d72e907
train
class
@tf_export(v1=["distribute.experimental.TPUStrategy"]) class TPUStrategyV1(distribute_lib.StrategyV1): """TPU distribution strategy implementation.""" def __init__(self, tpu_cluster_resolver=None, steps_per_run=None, device_assignment=None): """Initializes t...
@tf_export(v1=["distribute.experimental.TPUStrategy"]) class TPUStrategyV1(distribute_lib.StrategyV1):
"""TPU distribution strategy implementation.""" def __init__(self, tpu_cluster_resolver=None, steps_per_run=None, device_assignment=None): """Initializes the TPUStrategy object. Args: tpu_cluster_resolver: A tf.distribute.cluster_resolver.TPUClus...
or outfeed. def experimental_run_v2(self, fn, args=(), kwargs=None): """See base class.""" # Note: the target function is converted to graph even when in Eager mode, # so autograph is on by default here. fn = autograph.tf_convert(fn, ag_ctx.control_status_ctx()) return self.extended.tpu_run...
114
114
383
31
83
uve/tensorflow
tensorflow/python/distribute/tpu_strategy.py
Python
TPUStrategyV1
TPUStrategyV1
114
150
114
115
46002c63d70e53adfe9dbed3e05b338dedd289cb
bigcode/the-stack
train
d016117eb04c61c4b2596dfd
train
function
@contextlib.contextmanager def maybe_init_scope(): if ops.executing_eagerly_outside_functions(): yield else: with ops.init_scope(): yield
@contextlib.contextmanager def maybe_init_scope():
if ops.executing_eagerly_outside_functions(): yield else: with ops.init_scope(): yield
.as_cluster_def() if cluster_spec else None tpu_system_metadata = ( tpu_system_metadata_lib._query_tpu_system_metadata( master, cluster_def=cluster_def, query_topology=False)) return tpu_system_metadata @contextlib.contextmanager def maybe_init_scope():
64
64
38
11
52
uve/tensorflow
tensorflow/python/distribute/tpu_strategy.py
Python
maybe_init_scope
maybe_init_scope
75
81
75
76
d43c086f10b1104c2e0c919c0ac5c589dd8fdf70
bigcode/the-stack
train
f393521475e6bb7acf278cb7
train
class
@tf_export("distribute.experimental.TPUStrategy", v1=[]) class TPUStrategy(distribute_lib.Strategy): """TPU distribution strategy implementation.""" def __init__(self, tpu_cluster_resolver=None, device_assignment=None): """Initializes the TPUStrategy object. Args: ...
@tf_export("distribute.experimental.TPUStrategy", v1=[]) class TPUStrategy(distribute_lib.Strategy):
"""TPU distribution strategy implementation.""" def __init__(self, tpu_cluster_resolver=None, device_assignment=None): """Initializes the TPUStrategy object. Args: tpu_cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver, which provid...
_system_metadata( master, cluster_def=cluster_def, query_topology=False)) return tpu_system_metadata @contextlib.contextmanager def maybe_init_scope(): if ops.executing_eagerly_outside_functions(): yield else: with ops.init_scope(): yield @tf_export("di...
92
92
308
28
63
uve/tensorflow
tensorflow/python/distribute/tpu_strategy.py
Python
TPUStrategy
TPUStrategy
84
111
84
85
210b396161085ca1fd90622044ccb7eda81b7353
bigcode/the-stack
train
ce062cf7d0eaf35e244f3335
train
function
def get_tpu_system_metadata(tpu_cluster_resolver): """Retrieves TPU system metadata given a TPUClusterResolver.""" master = tpu_cluster_resolver.master() # pylint: disable=protected-access cluster_spec = tpu_cluster_resolver.cluster_spec() cluster_def = cluster_spec.as_cluster_def() if cluster_spec els...
def get_tpu_system_metadata(tpu_cluster_resolver):
"""Retrieves TPU system metadata given a TPUClusterResolver.""" master = tpu_cluster_resolver.master() # pylint: disable=protected-access cluster_spec = tpu_cluster_resolver.cluster_spec() cluster_def = cluster_spec.as_cluster_def() if cluster_spec else None tpu_system_metadata = ( tpu_system_...
.python.tpu import tpu_system_metadata as tpu_system_metadata_lib from tensorflow.python.tpu import training_loop from tensorflow.python.tpu.ops import tpu_ops from tensorflow.python.util import nest from tensorflow.python.util.tf_export import tf_export def get_tpu_system_metadata(tpu_cluster_resolver):
64
64
116
12
51
uve/tensorflow
tensorflow/python/distribute/tpu_strategy.py
Python
get_tpu_system_metadata
get_tpu_system_metadata
59
72
59
59
38654593ff2c12c22dc9995006811fd9ba1cca05
bigcode/the-stack
train
18904e133db03e7e8ad104c7
train
class
class TPUExtended(distribute_lib.StrategyExtendedV1): """Implementation of TPUStrategy.""" def __init__(self, container_strategy, tpu_cluster_resolver=None, steps_per_run=None, device_assignment=None): super(TPUExtended, self).__init__(contain...
class TPUExtended(distribute_lib.StrategyExtendedV1):
"""Implementation of TPUStrategy.""" def __init__(self, container_strategy, tpu_cluster_resolver=None, steps_per_run=None, device_assignment=None): super(TPUExtended, self).__init__(container_strategy) if tpu_cluster_resolver is None: ...
device_assignment: Optional `tf.tpu.experimental.DeviceAssignment` to specify the placement of replicas on the TPU cluster. Currently only supports the usecase of using a single core within a TPU cluster. """ super(TPUStrategyV1, self).__init__(TPUExtended( self, tpu_clust...
256
256
4,888
14
242
uve/tensorflow
tensorflow/python/distribute/tpu_strategy.py
Python
TPUExtended
TPUExtended
154
700
154
154
41765c4aa25c9def56a0a5c1e416dff8799ab746
bigcode/the-stack
train
e7719a6e88deaf9eacd76b4a
train
class
class RouteFilterRule(SubResource): """Route Filter Rule Resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param access: Required. Th...
class RouteFilterRule(SubResource):
"""Route Filter Rule Resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param access: Required. The access type of the rule. Valid val...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
93
209
697
7
85
JonathanGailliez/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/route_filter_rule_py3.py
Python
RouteFilterRule
RouteFilterRule
15
79
15
15
7928b87f6c4d547cbffb1f0f30b6667049eb7fae
bigcode/the-stack
train
e7d20741ae25d9b42bc7da55
train
class
class VirtualNetworkTapsOperations(object): """VirtualNetworkTapsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation...
class VirtualNetworkTapsOperations(object):
"""VirtualNetworkTapsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.networ...
Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # ---------------------------------------------...
256
256
5,463
8
248
rsdoherty/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_08_01/operations/_virtual_network_taps_operations.py
Python
VirtualNetworkTapsOperations
VirtualNetworkTapsOperations
28
552
28
28
1e22ae46cc2cb11c54e07fdb503264361fde21e1
bigcode/the-stack
train
376b22e7dfa6ff4d9977fc08
train
class
class PruneTest(BitcoinTestFramework): def __init__(self): self.utxo = [] self.address = ["",""] self.txouts = gen_return_txouts() def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 4) def se...
class PruneTest(BitcoinTestFramework):
def __init__(self): self.utxo = [] self.address = ["",""] self.txouts = gen_return_txouts() def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 4) def setup_network(self): self.nodes = ...
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2017 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test pruning code # ******** # WARNING: # ...
178
256
4,487
9
169
shade/BitcoinUnlimited
qa/rpc-tests/pruning.py
Python
PruneTest
PruneTest
21
385
21
22
c90ced5378cb2976dc091ed0a766b9aa2fa7a5ce
bigcode/the-stack
train
17be246efefb5362514dba8c
train
function
def calc_usage(blockdir): return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f)) / (1024. * 1024.)
def calc_usage(blockdir):
return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f)) / (1024. * 1024.)
# # Test pruning code # ******** # WARNING: # This test uses 4GB of disk space. # This test takes 30 mins or more (up to 2 hours) # ******** from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def calc_usage(blockdir):
64
64
45
6
58
shade/BitcoinUnlimited
qa/rpc-tests/pruning.py
Python
calc_usage
calc_usage
18
19
18
18
a28669db8be9ea0a973dd9cc1af78e9e464f6080
bigcode/the-stack
train
1b877960ba6bb8e3bc878682
train
function
def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127) controls = QuantumRegister(n, "ofc") oracle = QuantumCircuit(controls, name="Zf") for i in range(2 ** n): rep...
def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc") oracle = QuantumCircuit(controls, name="Zf") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.h(controls[...
import networkx as nx def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127)
64
64
197
58
5
UCLA-SEAL/QDiff
benchmark/startQiskit1262.py
Python
build_oracle
build_oracle
14
38
14
18
65ce9f82635737bf77eda8c5c06726774c01313a
bigcode/the-stack
train
cb14d6830ae905e2ffca7b78
train
function
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 pr...
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin
input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 prog.h(input_qubit[3]) # number=6 prog.h(input_qubit[0]) # numb...
ile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2,floor, sqrt, pi import numpy as np import networkx as nx def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_g...
255
255
853
17
237
UCLA-SEAL/QDiff
benchmark/startQiskit1262.py
Python
make_circuit
make_circuit
41
111
41
42
9da803db90a14f359fcc5690aaf19badf9219f9b
bigcode/the-stack
train
f866fabad182763628070c35
train
function
def get_wav_for_path_pipeline(path_names, sr): x = [] signal_length = 0 for path in path_names: # print(path) signal, _ = librosa.load(path, sr=sr) x.append(signal) signal_length += len(signal)/sr return x, signal_length
def get_wav_for_path_pipeline(path_names, sr):
x = [] signal_length = 0 for path in path_names: # print(path) signal, _ = librosa.load(path, sr=sr) x.append(signal) signal_length += len(signal)/sr return x, signal_length
_length = 0 for path in noise_path_names: signal, _ = librosa.load('../../Data' + path, sr=sr) x.append(signal) signal_length += len(signal)/sr return x, signal_length def get_wav_for_path_pipeline(path_names, sr):
64
64
70
12
51
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
get_wav_for_path_pipeline
get_wav_for_path_pipeline
55
63
55
55
af4b3edf58e8bea8e2416ba106c8d4200dc174cf
bigcode/the-stack
train
3b1b59ee783261b4fd8cf1d1
train
function
def active_BALD(out, X, n_classes): if type(X) == int: frame_cnt = X else: frame_cnt = X.shape[0] log_prob = np.zeros((out.shape[0], frame_cnt, n_classes)) score_All = np.zeros((frame_cnt, n_classes)) All_Entropy = np.zeros((frame_cnt,)) for d in range(out.shape[0]): # ...
def active_BALD(out, X, n_classes):
if type(X) == int: frame_cnt = X else: frame_cnt = X.shape[0] log_prob = np.zeros((out.shape[0], frame_cnt, n_classes)) score_All = np.zeros((frame_cnt, n_classes)) All_Entropy = np.zeros((frame_cnt,)) for d in range(out.shape[0]): # print ('Dropout Iteration', d) # ...
_prob[prob_start_idx:prob_end_idx][:,1])) + " PE: " + "{:.4f}".format(np.mean(G_X[prob_start_idx:prob_end_idx])) + " MI: " + "{:.4f}".format(np.mean(U_X[prob_start_idx:prob_end_idx]))]) sample_start = frames[index+1] ...
110
110
369
12
97
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
active_BALD
active_BALD
259
291
259
260
49ef62d9936f53bf60294cdb6588e88fe2dcf8c5
bigcode/the-stack
train
785d08bbe660a551bcc3ee6d
train
function
def detect_timestamps(preds_prob, hop_length=512, det_threshold = 0.5, sr=8000): preds = np.zeros(len(preds_prob)) for i, pred in enumerate(preds_prob): if pred[1] > det_threshold: preds[i] = 1 frames = librosa.frames_to_samples(np.arange(len(preds)), hop_length=512) sample_star...
def detect_timestamps(preds_prob, hop_length=512, det_threshold = 0.5, sr=8000):
preds = np.zeros(len(preds_prob)) for i, pred in enumerate(preds_prob): if pred[1] > det_threshold: preds[i] = 1 frames = librosa.frames_to_samples(np.arange(len(preds)), hop_length=512) sample_start = 0 prob_start_idx = 0 preds_list = [] # mozz_pred_array = [] fo...
= [] for feat in feats: if np.shape(feat)[1] < win_size: pass else: feats_windowed = skimage.util.view_as_windows(feat.T, (win_size,np.shape(feat)[0]), step=step_size) feats_windowed_array.append(feats_windowed) return np.vstack(feats_windowed_array) # R...
114
114
380
26
88
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
detect_timestamps
detect_timestamps
168
200
168
169
bc382b661ae1b12afe57f4c875b39436efa20b05
bigcode/the-stack
train
a6fce2c1402dd969b70cd606
train
function
def df_metadata(df, plot=True, filepath=None): '''Insert dataframe to calculate quantity of data per species. Expects pandas dataframe df, returns species_list, and durations, optionally plots''' durations = [] species_list = [] for species in df["species"].unique(): duration = df[df["speci...
def df_metadata(df, plot=True, filepath=None):
'''Insert dataframe to calculate quantity of data per species. Expects pandas dataframe df, returns species_list, and durations, optionally plots''' durations = [] species_list = [] for species in df["species"].unique(): duration = df[df["species"] == species]["fine_end_time"] - df[df["spec...
.shape[0]) F_X = Average_Entropy U_X = G_X - F_X # G_X = predictive entropy # U_X = MI return G_X, U_X, log_prob # Further evaluation and visualisation def df_metadata(df, plot=True, filepath=None):
64
64
163
11
52
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
df_metadata
df_metadata
298
317
298
298
c5e8080ec0c436c18bb9d12e01b1ab4dd9d744d4
bigcode/the-stack
train
36657b25a4d3635a922a900e
train
function
def get_noise_wav_for_df(df, path_strings, crop_time, sr, verbose=0): ''' Logic: If any wav file has a positive label, the unlabelled wav file is negative. This only holds true for some data in the dataset, hence we supply a list of strings to path_string, which filters the data as follows: if path_string...
def get_noise_wav_for_df(df, path_strings, crop_time, sr, verbose=0):
''' Logic: If any wav file has a positive label, the unlabelled wav file is negative. This only holds true for some data in the dataset, hence we supply a list of strings to path_string, which filters the data as follows: if path_string is a substring of path, accept this data processing scheme. crop ...
]["fine_start_time"] return x, signal_length def get_wav_for_path(noise_path_names, sr): x = [] signal_length = 0 for path in noise_path_names: signal, _ = librosa.load('../../Data' + path, sr=sr) x.append(signal) signal_length += len(signal)/sr return x, signal_length def...
174
174
580
21
152
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
get_noise_wav_for_df
get_noise_wav_for_df
65
107
65
65
901accb0ebddce1d49e1d06a4275731ece7da168
bigcode/the-stack
train
aaff4eb1441d018af0ef9413
train
function
def get_feat(x, sr, feat_type, n_feat, flatten=True, norm_per_sample=True): ''' Returns features extracted with Librosa. Currently written to support MFCCs (truncated), MFCCs, and log-mel only. flatten=True returns a continguous list of all the features from different recordings concatenated, whereas flatten=Fa...
def get_feat(x, sr, feat_type, n_feat, flatten=True, norm_per_sample=True):
''' Returns features extracted with Librosa. Currently written to support MFCCs (truncated), MFCCs, and log-mel only. flatten=True returns a continguous list of all the features from different recordings concatenated, whereas flatten=False returns a list of features, with the number of items equal to the nu...
(df_wav)): if verbose == 2: print(sample_start_time.iloc[i], sample_end_time.iloc[i]) idx_wav_array[np.arange(sample_start_time.iloc[i], sample_end_time.iloc[i]).astype('int')] = 1 x.append(wav[0][np.where(np.logical_not(idx_wav_array))]) ...
130
130
434
21
108
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
get_feat
get_feat
112
145
112
112
e8bb9dd1c405bf3d90c5038aa4497ecd51c4f855
bigcode/the-stack
train
f299b9876960618fdf095bc3
train
function
def remove_label_bug(df, verbose=0): '''Remove any entries where the label end_time is not at least 1 sample greater than the label start_time. This step can be done more efficiently when loading data into .wav files, but for readability and ease of use we will pre-process the dataframes first by removing a...
def remove_label_bug(df, verbose=0):
'''Remove any entries where the label end_time is not at least 1 sample greater than the label start_time. This step can be done more efficiently when loading data into .wav files, but for readability and ease of use we will pre-process the dataframes first by removing any entries with incorrect labels.''' ...
import matplotlib.pyplot as plt import librosa import numpy as np import skimage.util # Dataframe processing and File i/o def remove_label_bug(df, verbose=0):
39
64
214
10
28
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
remove_label_bug
remove_label_bug
9
25
9
9
c7fd54d9ab56d16eb6524ef7baef00be41715e05
bigcode/the-stack
train
b38bf3ceb04619378fd9b15e
train
function
def get_wav_for_df(df, sr): '''Extract wave files from dataframe df, at signal rate sr. Returns a list of numpy arrays in float 32, and the signal length''' # Probably memory inefficient as it loops over entire paths and loads all the corresponding wav file excerpts, may be better to open file # and perform...
def get_wav_for_df(df, sr):
'''Extract wave files from dataframe df, at signal rate sr. Returns a list of numpy arrays in float 32, and the signal length''' # Probably memory inefficient as it loops over entire paths and loads all the corresponding wav file excerpts, may be better to open file # and perform feature transform, close, s...
', i) idx_noise.append(i) df_clean = df.drop(index = df.index[idx_noise]) if verbose>=1: print('Old dataframe length:', len(df)) print('New dataframe length:', len(df_clean)) return df_clean def get_wav_for_df(df, sr):
64
64
211
10
53
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
get_wav_for_df
get_wav_for_df
28
43
28
28
662a32afc91adabae903a51feca5020664e8f9b8
bigcode/the-stack
train
118921380bb873152df495dd
train
function
def reshape_feat(feats, win_size, step_size): '''Reshaping features from get_feat to be compatible for classifiers expecting a 2D slice as input. Parameter `win_size` is given in number of feature windows. Can code to be a function of time and hop length instead in future.''' feats_windowed_array = []...
def reshape_feat(feats, win_size, step_size):
'''Reshaping features from get_feat to be compatible for classifiers expecting a 2D slice as input. Parameter `win_size` is given in number of feature windows. Can code to be a function of time and hop length instead in future.''' feats_windowed_array = [] for feat in feats: if np.shape(fe...
_idx, np.shape(signal)[1]) X_flatten[:,curr_idx:curr_idx+np.shape(signal)[1]] = signal curr_idx += np.shape(signal)[1] return X_flatten.T else: return X def reshape_feat(feats, win_size, step_size):
64
64
150
12
51
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
reshape_feat
reshape_feat
148
159
148
148
94b73e1a6971a73fbb370b02dc254a1f3e407500
bigcode/the-stack
train
3d46d41519ffa145c80d1fdf
train
function
def detect_timestamps_BNN(preds_prob, G_X, U_X, hop_length=512, det_threshold=0.5, sr=8000): ''' Outputs the mean probability per section of predicted audio: consider the case when many consecutive windows are positive, we only get to see the average output. When then thresholding the output by probability,...
def detect_timestamps_BNN(preds_prob, G_X, U_X, hop_length=512, det_threshold=0.5, sr=8000):
''' Outputs the mean probability per section of predicted audio: consider the case when many consecutive windows are positive, we only get to see the average output. When then thresholding the output by probability, it may be better to have individual windows so that we can filter out more likely events. Ho...
]))]) sample_start = frames[index+1] prob_start_idx = index+1 elif index+1 == len(frames[:-1]): sample_end = frames[index+1] prob_end_idx = index+1 # print('sample_start', sample_start, 'sample_end', sample_end, 'label', preds[index]) ...
179
179
597
33
145
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
detect_timestamps_BNN
detect_timestamps_BNN
204
246
204
204
5201826349e94e7998cabe5047c8244c30538205
bigcode/the-stack
train
18f24297ae7cc8df94abe505
train
function
def get_wav_for_path(noise_path_names, sr): x = [] signal_length = 0 for path in noise_path_names: signal, _ = librosa.load('../../Data' + path, sr=sr) x.append(signal) signal_length += len(signal)/sr return x, signal_length
def get_wav_for_path(noise_path_names, sr):
x = [] signal_length = 0 for path in noise_path_names: signal, _ = librosa.load('../../Data' + path, sr=sr) x.append(signal) signal_length += len(signal)/sr return x, signal_length
]["fine_end_time"] - df.iloc[i]["fine_start_time"], sr = sr) x.append(signal) signal_length += df.iloc[i]["fine_end_time"] - df.iloc[i]["fine_start_time"] return x, signal_length def get_wav_for_path(noise_path_names, sr):
64
64
71
13
50
seancampos/MIDS-MozzINF
Code/lib/util.py
Python
get_wav_for_path
get_wav_for_path
46
53
46
46
6fb56ab75393dc8147952fc1ffad189b46b9d607
bigcode/the-stack
train
c0b4868e9bd06dbba80d2703
train
function
def generate_agreement_data(request, tender, lot=None): data = { "items": tender.items if not lot else [i for i in tender.items if i.relatedLot == lot.id], "agreementID": "{}-{}{}".format(tender.tenderID, request.registry.server_id, len(tender.agreements) + 1), "date": get_now().isoformat(),...
def generate_agreement_data(request, tender, lot=None):
data = { "items": tender.items if not lot else [i for i in tender.items if i.relatedLot == lot.id], "agreementID": "{}-{}{}".format(tender.tenderID, request.registry.server_id, len(tender.agreements) + 1), "date": get_now().isoformat(), "contracts": [], "features": tender.fea...
to switch status tender.awardPeriod.endDate = None tender.status = "active.qualification" def all_awards_are_reviewed(request): """ checks if all tender awards are reviewed """ return all([award.status != "pending" for award in request.validated["tender"].awards]) def generate_agr...
79
79
266
12
67
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
generate_agreement_data
generate_agreement_data
459
489
459
459
9e1bc6ae0022bbc2ca91f5eb19a2c3d6ad29a9c1
bigcode/the-stack
train
9b2358f5a423ec3d3a44f3ad
train
function
def check_status(request): tender = request.validated["tender"] now = get_now() check_complaint_statuses_at_complaint_period_end(tender, now) check_cancellation_status(request, CancelTenderLot) active_lots = [ lot.id for lot in tender.lots if lot.status == "active" ] if tender....
def check_status(request):
tender = request.validated["tender"] now = get_now() check_complaint_statuses_at_complaint_period_end(tender, now) check_cancellation_status(request, CancelTenderLot) active_lots = [ lot.id for lot in tender.lots if lot.status == "active" ] if tender.lots else [None] if bl...
): LOGGER.info( "Switched tender {} to {}".format(tender.id, "unsuccessful"), extra=context_unpack(request, {"MESSAGE_ID": "switched_tender_unsuccessful"}), ) tender.status = "unsuccessful" elif not statuses.difference({"active", "unsuccessful", "cancelled"}): ...
132
132
441
5
126
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
check_status
check_status
286
341
286
286
5cb4235a015364d170069738db30aa5b95ea52e3
bigcode/the-stack
train
92dcf47e00ad939b5387883e
train
function
def all_awards_are_reviewed(request): """ checks if all tender awards are reviewed """ return all([award.status != "pending" for award in request.validated["tender"].awards])
def all_awards_are_reviewed(request):
""" checks if all tender awards are reviewed """ return all([award.status != "pending" for award in request.validated["tender"].awards])
.__parent__ = tender tender.awards.append(award) if tender.awards[-1].status == "pending": # logic for auction to switch status tender.awardPeriod.endDate = None tender.status = "active.qualification" def all_awards_are_reviewed(request):
64
64
44
9
55
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
all_awards_are_reviewed
all_awards_are_reviewed
453
456
453
453
43fc256c4de6c282dd0593503b6d468b8c6c2fb8
bigcode/the-stack
train
2d1319a25fea6b8169d305c9
train
class
class CancelTenderLot(BaseCancelTenderLot): def cancel_lot(self, request, cancellation): super(CancelTenderLot, self).cancel_lot(request, cancellation) # cancel agreements tender = request.validated["tender"] if tender.status == "active.awarded" and tender.agreements: ca...
class CancelTenderLot(BaseCancelTenderLot):
def cancel_lot(self, request, cancellation): super(CancelTenderLot, self).cancel_lot(request, cancellation) # cancel agreements tender = request.validated["tender"] if tender.status == "active.awarded" and tender.agreements: cancelled_lots = {i.id for i in tender.lots if...
factory=bid_financial_documents_factory ) bid_eligibility_documents_resource = partial( resource, error_handler=error_handler, factory=bid_eligibility_documents_factory ) bid_qualification_documents_resource = partial( resource, error_handler=error_handler, factory=bid_qualification_documents_factory ) class C...
72
72
243
9
63
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
CancelTenderLot
CancelTenderLot
52
79
52
52
d45fe8f1d657547c0ee29805c09a8fa8c040422e
bigcode/the-stack
train
444f3fc2427c709830e04caf
train
function
def prepare_qualifications(request, bids=[], lotId=None): """ creates Qualification for each Bid """ new_qualifications = [] tender = request.validated["tender"] if not bids: bids = tender.bids if tender.lots: active_lots = [lot.id for lot in tender.lots if lot.status == "active"...
def prepare_qualifications(request, bids=[], lotId=None):
""" creates Qualification for each Bid """ new_qualifications = [] tender = request.validated["tender"] if not bids: bids = tender.bids if tender.lots: active_lots = [lot.id for lot in tender.lots if lot.status == "active"] for bid in bids: if bid.status not i...
# pragma: no cover LOGGER.info( "Switched tender {} to {}".format(tender.id, "unsuccessful"), extra=context_unpack(request, {"MESSAGE_ID": "switched_tender_unsuccessful"}), ) if tender.auctionPeriod and tender.auctionPeriod.startDate: tender.auctionPeriod.st...
96
96
321
13
83
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
prepare_qualifications
prepare_qualifications
123
156
123
123
bb7c0d462990afdbe7c3d3d61e3e256220b9297f
bigcode/the-stack
train
0662a9b636923c98d7a4ad25
train
function
def check_tender_status_on_active_awarded(request): tender = request.validated["tender"] now = get_now() statuses = {agreement.status for agreement in tender.agreements} if statuses == {"cancelled"}: LOGGER.info( "Switched tender {} to {}".format(tender.id, "cancelled"), ...
def check_tender_status_on_active_awarded(request):
tender = request.validated["tender"] now = get_now() statuses = {agreement.status for agreement in tender.agreements} if statuses == {"cancelled"}: LOGGER.info( "Switched tender {} to {}".format(tender.id, "cancelled"), extra=context_unpack(request, {"MESSAGE_ID": "switch...
# pragma: no cover agreement_data = generate_agreement_data(request, tender) agreement = type(tender).agreements.model_class(agreement_data) agreement.__parent__ = tender tender.agreements.append(agreement) # Update tender status (awarded, unsuccessful) def che...
72
72
240
11
61
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
check_tender_status_on_active_awarded
check_tender_status_on_active_awarded
261
283
261
261
e34770abe3a30278d4ce30c1a00816c8f67b08c7
bigcode/the-stack
train
97284b5da740b60348c49fd9
train
function
def add_next_awards(request, reverse=False, awarding_criteria_key="amount", regenerate_all_awards=False, lot_id=None): """Adding next award. :param request: The pyramid request object. :param reverse: Is used for sorting bids to generate award. By default (reverse = False) awards ar...
def add_next_awards(request, reverse=False, awarding_criteria_key="amount", regenerate_all_awards=False, lot_id=None):
"""Adding next award. :param request: The pyramid request object. :param reverse: Is used for sorting bids to generate award. By default (reverse = False) awards are generated from lower to higher by value.amount When reverse is set to True awards are generated from higher to...
active.pre-qualification" tender.qualificationPeriod = type(tender).qualificationPeriod({"startDate": now}) remove_draft_bids(request) check_initial_bids_count(request) prepare_qualifications(request) return elif ( tender.status == "active.pre-qualification.stand-sti...
256
256
1,098
27
229
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
add_next_awards
add_next_awards
344
450
344
345
33a10330e5bbbde3e5fd40d368eb8e24b85453af
bigcode/the-stack
train
95f2dbcd0160c932dbc5956d
train
function
def all_bids_are_reviewed(request): """ checks if all tender bids are reviewed """ if request.validated["tender"].lots: active_lots = [lot.id for lot in request.validated["tender"].lots if lot.status == "active"] return all( [ lotValue.status != "pending" ...
def all_bids_are_reviewed(request):
""" checks if all tender bids are reviewed """ if request.validated["tender"].lots: active_lots = [lot.id for lot in request.validated["tender"].lots if lot.status == "active"] return all( [ lotValue.status != "pending" for bid in request.validated...
bid.status == "pending": qualification = Qualification({"bidID": bid.id, "status": "pending"}) qualification.date = get_now() tender.qualifications.append(qualification) new_qualifications.append(qualification.id) return new_qualifications def all_bid...
64
64
156
9
54
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
all_bids_are_reviewed
all_bids_are_reviewed
159
174
159
159
32f11838e631fef78342d521fc5a752ecdef8c92
bigcode/the-stack
train
f625bc9b5a66662b4ce023fa
train
function
def check_tender_status_on_active_qualification_stand_still(request): tender = request.validated["tender"] config = getAdapter(tender, IContentConfigurator) now = get_now() active_lots = [ lot.id for lot in tender.lots if lot.status == "active" ] if tender.lots else [None] if n...
def check_tender_status_on_active_qualification_stand_still(request):
tender = request.validated["tender"] config = getAdapter(tender, IContentConfigurator) now = get_now() active_lots = [ lot.id for lot in tender.lots if lot.status == "active" ] if tender.lots else [None] if not ( tender.awardPeriod and tender.awardPeriod.endDate ...
bid.status == "pending": qualification = Qualification({"bidID": bid.id, "status": "pending"}) qualification.date = get_now() tender.qualifications.append(qualification) new_qualifications.append(qualification.id) return new_qualifications def all_b...
226
226
755
15
211
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
check_tender_status_on_active_qualification_stand_still
check_tender_status_on_active_qualification_stand_still
177
256
177
178
320dbc5971ed513a50d0f707e7ea37c56d17ac55
bigcode/the-stack
train
00ebe1ff46fe78438892d5dd
train
function
def check_initial_bids_count(request): tender = request.validated["tender"] if tender.lots: [ setattr(i.auctionPeriod, "startDate", None) for i in tender.lots if i.numberOfBids < getAdapter(tender, IContentConfigurator).min_bids_number and i.auctionPeriod...
def check_initial_bids_count(request):
tender = request.validated["tender"] if tender.lots: [ setattr(i.auctionPeriod, "startDate", None) for i in tender.lots if i.numberOfBids < getAdapter(tender, IContentConfigurator).min_bids_number and i.auctionPeriod and i.auctionPeriod.startD...
): tender = request.validated["tender"] if tender.status == "active.tendering": tender.bids = [] elif tender.status in ("active.pre-qualification", "active.pre-qualification.stand-still", "active.auction"): for bid in tender.bids: if bid.status in ("pend...
126
126
423
8
118
pontostroy/api
src/openprocurement/tender/cfaua/utils.py
Python
check_initial_bids_count
check_initial_bids_count
82
120
82
82
1821b153d94f03e79c6c1b5461324c43d7b5040e
bigcode/the-stack
train
f399a3f968397d695d1899a2
train
class
class MixtureSameFamily(distribution.Distribution): """Mixture with components provided from a single batched distribution.""" equiv_tfp_cls = tfd.MixtureSameFamily def __init__(self, mixture_distribution: CategoricalLike, components_distribution: DistributionLike): """Initiali...
class MixtureSameFamily(distribution.Distribution):
"""Mixture with components provided from a single batched distribution.""" equiv_tfp_cls = tfd.MixtureSameFamily def __init__(self, mixture_distribution: CategoricalLike, components_distribution: DistributionLike): """Initializes a mixture distribution for components of a share...
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
255
256
1,186
10
244
deepmind/distrax
distrax/_src/distributions/mixture_same_family.py
Python
MixtureSameFamily
MixtureSameFamily
36
156
36
36
1374938a192917ac2644e52e0ef3164bbe5c46f2
bigcode/the-stack
train
4dfe43c7a7717960e6736ddf
train
function
def main(): log_data = {"file_names": [], "ground_truths": []} models = {} test_set = TemporalColorConstancy(mode=DATA_TYPE, split_folder=DATA_FOLDER) test_loader = DataLoader(test_set, batch_size=1, shuffle=False, num_workers=20) print('Test set size: {}'.format(len(test_set))) for model_type...
def main():
log_data = {"file_names": [], "ground_truths": []} models = {} test_set = TemporalColorConstancy(mode=DATA_TYPE, split_folder=DATA_FOLDER) test_loader = DataLoader(test_set, batch_size=1, shuffle=False, num_workers=20) print('Test set size: {}'.format(len(test_set))) for model_type, model in M...
.utils import correct, linear_to_nonlinear from classes.data.datasets.TemporalColorConstancy import TemporalColorConstancy from classes.modules.multiframe.ctccnet.ModelCTCCNet import ModelCTCCNet from classes.modules.multiframe.ctccnetc4.ModelCTCCNetC4 import ModelCTCCNetC4 from classes.modules.multiframe.tccnet.ModelT...
256
256
1,286
3
253
matteo-rizzo/cctcc
viz/correction_comparison.py
Python
main
main
32
150
32
32
45168a5210aa654bc763afbb85a229fab1bb9d61
bigcode/the-stack
train
bb20b166edb88e2d1ca4b620
train
class
class Test_chemical_potential: @classmethod def setup_class(self): """initializing parameters for tests""" self.n_e = 1e20 * u.cm ** -3 self.n_e_fail = 1e23 * u.cm ** -3 self.T = 11604 * u.K self.True1 = 1.234345958778249e-11 @pytest.mark.xfail( reason="see i...
class Test_chemical_potential: @classmethod
def setup_class(self): """initializing parameters for tests""" self.n_e = 1e20 * u.cm ** -3 self.n_e_fail = 1e23 * u.cm ** -3 self.T = 11604 * u.K self.True1 = 1.234345958778249e-11 @pytest.mark.xfail( reason="see issue https://github.com/PlasmaPy/PlasmaPy/issues...
_e = 1e23 * u.cm ** -3 radiusTrue = 1.3365046175719772e-10 * u.m radiusMeth = Wigner_Seitz_radius(n_e) testTrue = u.isclose(radiusMeth, radiusTrue, rtol=1e-5) errStr = f"Error in Wigner_Seitz_radius(), got {radiusMeth}, should be {radiusTrue}" assert testTrue, errStr class Test_chemical_potential: ...
112
112
375
11
100
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
Test_chemical_potential
Test_chemical_potential
152
188
152
153
0c6612afd7b8e6542dfdf96e1ee30c07655c7190
bigcode/the-stack
train
de8fb3c88ee4efe2661a9a22
train
function
def test_Wigner_Seitz_radius(): """ Checks Wigner-Seitz radius for a known value. """ n_e = 1e23 * u.cm ** -3 radiusTrue = 1.3365046175719772e-10 * u.m radiusMeth = Wigner_Seitz_radius(n_e) testTrue = u.isclose(radiusMeth, radiusTrue, rtol=1e-5) errStr = f"Error in Wigner_Seitz_radius(),...
def test_Wigner_Seitz_radius():
""" Checks Wigner-Seitz radius for a known value. """ n_e = 1e23 * u.cm ** -3 radiusTrue = 1.3365046175719772e-10 * u.m radiusMeth = Wigner_Seitz_radius(n_e) testTrue = u.isclose(radiusMeth, radiusTrue, rtol=1e-5) errStr = f"Error in Wigner_Seitz_radius(), got {radiusMeth}, should be {ra...
assert lambda_TF.unit == u.m # testing exceptions with pytest.raises(TypeError): Thomas_Fermi_length("Bad Input") with pytest.raises(ValueError): Thomas_Fermi_length(n_e=-1 * u.m ** -3) def test_Wigner_Seitz_radius():
64
64
128
9
55
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
test_Wigner_Seitz_radius
test_Wigner_Seitz_radius
140
149
140
140
bfb3b199ebce883e5d968fdca705e1458c9c3e4a
bigcode/the-stack
train
3caa01c2115f61dcd97e2501
train
function
def test_Thomas_Fermi_length(): r"""Test the Thomas_Fermi_length function in quantum.py.""" lambda_TF = Thomas_Fermi_length(n_e) # true value at 1e23 cm-3 lambda_TF_true = 5.379914085596706e-11 # test a simple case for expected value expectStr = ( "Thomas-Fermi length at 1e23 cm^-3 shoul...
def test_Thomas_Fermi_length():
r"""Test the Thomas_Fermi_length function in quantum.py.""" lambda_TF = Thomas_Fermi_length(n_e) # true value at 1e23 cm-3 lambda_TF_true = 5.379914085596706e-11 # test a simple case for expected value expectStr = ( "Thomas-Fermi length at 1e23 cm^-3 should be " f"{lambda_TF_true...
# testing returned units assert energy_F.unit == u.J # testing exceptions with pytest.raises(TypeError): Fermi_energy("Bad Input") with pytest.raises(ValueError): Fermi_energy(n_e=-1 * u.m ** -3) def test_Thomas_Fermi_length():
64
64
207
8
56
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
test_Thomas_Fermi_length
test_Thomas_Fermi_length
120
137
120
120
aa64eb7d101997cd97ba8241e26b7be7ec46b8f3
bigcode/the-stack
train
1382263880da89bf4c2055c8
train
function
def test_Fermi_energy(): r"""Test the Fermi_energy function in quantum.py.""" energy_F = Fermi_energy(n_e) # true value at 1e23 cm-3 energy_F_true = 1.2586761116196002e-18 # test a simple case for expected value expectStr = ( "Fermi energy at 1e23 cm^-3 should be {energy_F_true} and not ...
def test_Fermi_energy():
r"""Test the Fermi_energy function in quantum.py.""" energy_F = Fermi_energy(n_e) # true value at 1e23 cm-3 energy_F_true = 1.2586761116196002e-18 # test a simple case for expected value expectStr = ( "Fermi energy at 1e23 cm^-3 should be {energy_F_true} and not {energy_F}." ) as...
assert lambda_dbTh.unit == u.m # testing exceptions with pytest.raises(TypeError): thermal_deBroglie_wavelength("Bad Input") with pytest.raises(ValueError): thermal_deBroglie_wavelength(T_e=-1 * u.eV) def test_Fermi_energy():
64
64
192
6
58
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
test_Fermi_energy
test_Fermi_energy
101
117
101
101
83ae3d69c40b99422d9f2530a268da4139062af4
bigcode/the-stack
train
7313d45bd5a74fe277444a0e
train
function
def test_thermal_deBroglie_wavelength(): r"""Test the thermal_deBroglie_wavelength function in quantum.py.""" lambda_dbTh = thermal_deBroglie_wavelength(T_e) # true value at 1 eV lambda_dbTh_true = 6.919367518364532e-10 # test a simple case for expected value expectStr = ( "Thermal deBro...
def test_thermal_deBroglie_wavelength():
r"""Test the thermal_deBroglie_wavelength function in quantum.py.""" lambda_dbTh = thermal_deBroglie_wavelength(T_e) # true value at 1 eV lambda_dbTh_true = 6.919367518364532e-10 # test a simple case for expected value expectStr = ( "Thermal deBroglie wavelength at 1 eV should be " ...
1 * u.eV n_e = 1e23 * u.cm ** -3 # should probably change this to use unittest module # add tests for numpy arrays as inputs # add tests for different astropy units (random fuzzing method?) def test_thermal_deBroglie_wavelength():
65
66
220
11
54
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
test_thermal_deBroglie_wavelength
test_thermal_deBroglie_wavelength
79
98
79
79
0aa8f54412a6aeda473ea1508ec67a60c3d086cf
bigcode/the-stack
train
b669da9d31a2425f1a2c24fe
train
class
class Test__chemical_potential_interp: @classmethod def setup_class(self): """initializing parameters for tests""" self.n_e = 1e23 * u.cm ** -3 self.T = 11604 * u.K self.True1 = 7.741256653579105 @pytest.mark.xfail( reason="see issue https://github.com/PlasmaPy/Plasm...
class Test__chemical_potential_interp: @classmethod
def setup_class(self): """initializing parameters for tests""" self.n_e = 1e23 * u.cm ** -3 self.T = 11604 * u.K self.True1 = 7.741256653579105 @pytest.mark.xfail( reason="see issue https://github.com/PlasmaPy/PlasmaPy/issues/726" ) def test_known1(self): ...
1 = self.True1 + 1e-15 methodVal = chemical_potential(self.n_e, self.T) testTrue = not u.isclose(methodVal, fail1, rtol=1e-16, atol=0.0) errStr = ( f"Chemical potential value test gives {methodVal} and " f"should not be equal to {fail1}." ) assert testTrue...
108
108
360
12
95
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
Test__chemical_potential_interp
Test__chemical_potential_interp
191
226
191
192
ef3789275da66f423b8ea8faab5c10a1a3fbb81c
bigcode/the-stack
train
5add28285fc88f783ea7b69b
train
function
def test_deBroglie_wavelength(): dbwavelength1 = deBroglie_wavelength(2e7 * u.cm / u.s, "e") assert np.isclose(dbwavelength1.value, 3.628845222852886e-11) assert dbwavelength1.unit == u.m dbwavelength2 = deBroglie_wavelength(0 * u.m / u.s, "e") assert dbwavelength2 == np.inf * u.m V_array = n...
def test_deBroglie_wavelength():
dbwavelength1 = deBroglie_wavelength(2e7 * u.cm / u.s, "e") assert np.isclose(dbwavelength1.value, 3.628845222852886e-11) assert dbwavelength1.unit == u.m dbwavelength2 = deBroglie_wavelength(0 * u.m / u.s, "e") assert dbwavelength2 == np.inf * u.m V_array = np.array([2e5, 0]) * u.m / u.s ...
import astropy.units as u import numpy as np import pytest from astropy.constants import c, h from plasmapy.utils.exceptions import RelativityError from ..quantum import ( _chemical_potential_interp, chemical_potential, deBroglie_wavelength, Ef_, Fermi_energy, lambdaDB_, lambdaDB_th_, ...
111
168
561
9
102
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
test_deBroglie_wavelength
test_deBroglie_wavelength
23
68
23
24
eab6e59abf86a5ccc400100f850d09328b21cff4
bigcode/the-stack
train
8d055a87ececcef7e747abe2
train
function
def test_quantum_aliases(): r"""Test all aliases defined in quantum.py""" assert Ef_ is Fermi_energy assert lambdaDB_ is deBroglie_wavelength assert lambdaDB_th_ is thermal_deBroglie_wavelength
def test_quantum_aliases():
r"""Test all aliases defined in quantum.py""" assert Ef_ is Fermi_energy assert lambdaDB_ is deBroglie_wavelength assert lambdaDB_th_ is thermal_deBroglie_wavelength
, rtol=1e-16, atol=0.0) errStr = ( f"Chemical potential value test gives {methodVal} " f"and should not be equal to {fail1}." ) assert testTrue, errStr def test_quantum_aliases():
64
64
55
7
56
FinMacDov/PlasmaPy
plasmapy/formulary/tests/test_quantum.py
Python
test_quantum_aliases
test_quantum_aliases
229
234
229
229
89bf04a92878f711970e9df395ee1088421b4bfb
bigcode/the-stack
train
6be1dc36512a8851f3162244
train
class
class StdReader: def __init__( self, ) -> NoReturn: import sys self.buf = sys.stdin.buffer self.lines = ( self.async_readlines() ) self.chunks: Generator def async_readlines( self, ) -> Generator: while True: gen = self.line_chunks() yield gen def line_c...
class StdReader:
def __init__( self, ) -> NoReturn: import sys self.buf = sys.stdin.buffer self.lines = ( self.async_readlines() ) self.chunks: Generator def async_readlines( self, ) -> Generator: while True: gen = self.line_chunks() yield gen def line_chunks( self, ...
from __future__ import ( annotations, ) from typing import ( Generator, NoReturn ) class StdReader:
26
64
201
4
22
kagemeka/competitive-programming
src/atcoder/abc199/f/sol_0.py
Python
StdReader
StdReader
11
64
11
13
e6de5182d3082fd06b15898847583f149dc3659a
bigcode/the-stack
train
8d07f60b5e67cce76d814998
train
function
def main(): t = 1 # t = StdReader().int() for _ in range(t): Problem()()
def main():
t = 1 # t = StdReader().int() for _ in range(t): Problem()()
, (x, y), 1) np.add.at(g, (y, x), 1) b = pow( 2 * m, mod - 2, mod, ) g *= b g %= mod self.g = g def main():
64
64
29
3
60
kagemeka/competitive-programming
src/atcoder/abc199/f/sol_0.py
Python
main
main
254
258
254
254
fc214f9fa3cfd494acb07455a2e13bd714b769c6
bigcode/the-stack
train
cc29814c6b6c2ec05edc6a58
train
class
class NumpyModular: mod: int = None def __init__( self, mod: int, ): self.mod = mod def mat_pow( self, a: np.ndarray, n: int, ) -> np.ndarray: if n == 0: e = np.identity( a.shape[0], dtype=np.int64, ) return e x = self.mat_pow(a, n >>...
class NumpyModular:
mod: int = None def __init__( self, mod: int, ): self.mod = mod def mat_pow( self, a: np.ndarray, n: int, ) -> np.ndarray: if n == 0: e = np.identity( a.shape[0], dtype=np.int64, ) return e x = self.mat_pow(a, n >> 1) x = self.mat_d...
) chunk = self() return chunk def str( self, ) -> str: b = self() return b.decode() def int( self, ) -> int: return int(self.str()) from abc import ( ABC, abstractmethod, ) class Solver(ABC): def __init__(self): self.reader = StdReader() def __call__...
139
139
466
6
132
kagemeka/competitive-programming
src/atcoder/abc199/f/sol_0.py
Python
NumpyModular
NumpyModular
102
182
102
104
17ac8494e53961c52d386a1d8b9127626a896be3
bigcode/the-stack
train
550425ba0c814bb4785ed3aa
train
class
class Problem( Solver, ): def prepare(self): reader = self.reader n = reader.int() m = reader.int() k = reader.int() a = [ reader.int() for _ in range(n) ] a = np.array(a) xy = [ reader.int() for _ in range(2 * m) ] xy = np.array( xy, ).re...
class Problem( Solver, ):
def prepare(self): reader = self.reader n = reader.int() m = reader.int() k = reader.int() a = [ reader.int() for _ in range(n) ] a = np.array(a) xy = [ reader.int() for _ in range(2 * m) ] xy = np.array( xy, ).reshape(m, 2) - 1 self.n = n...
1 return self.cumprod(fact) def inv_factorial( self, n: int, ): fact = self.factorial(n) ifact = np.arange(1, n + 1) ifact[-1] = self.inv( fact[-1], ) return self.cumprod( ifact[::-1], )[n::-1] mod = 10 ** 9 + 7 class Problem( Solver, ):
107
107
359
8
98
kagemeka/competitive-programming
src/atcoder/abc199/f/sol_0.py
Python
Problem
Problem
188
250
188
192
be17def97b7ca70a8ba6d195b3a0fd99a0bbd568
bigcode/the-stack
train
b772f87e128244097033e8fc
train
class
class Solver(ABC): def __init__(self): self.reader = StdReader() def __call__( self, ): self.prepare() self.solve() @abstractmethod def prepare(self): ... @abstractmethod def solve(self): ...
class Solver(ABC):
def __init__(self): self.reader = StdReader() def __call__( self, ): self.prepare() self.solve() @abstractmethod def prepare(self): ... @abstractmethod def solve(self): ...
return chunk def str( self, ) -> str: b = self() return b.decode() def int( self, ) -> int: return int(self.str()) from abc import ( ABC, abstractmethod, ) class Solver(ABC):
64
64
63
6
58
kagemeka/competitive-programming
src/atcoder/abc199/f/sol_0.py
Python
Solver
Solver
74
95
74
76
7bd143ce20a35fbcec0ebc01f60e68a3319d1514
bigcode/the-stack
train
f23169d92309421d7d346650
train
function
def main(args): with mlflow.start_run(): kwargs = {'num_workers': args.workers, 'pin_memory': args.pin_memory} train_loader, valid_loader, _, _ = make_data_loader(args, **kwargs) model = LitModel(args) cb_early_stopping = EarlyStopping( monitor="val/loss", s...
def main(args):
with mlflow.start_run(): kwargs = {'num_workers': args.workers, 'pin_memory': args.pin_memory} train_loader, valid_loader, _, _ = make_data_loader(args, **kwargs) model = LitModel(args) cb_early_stopping = EarlyStopping( monitor="val/loss", stopping_threshol...
flow): if "file://" in mlflow.get_artifact_uri(): mlflow_artifact_uri = mlflow.get_artifact_uri().replace("file://","") else: mlflow_artifact_uri = mlflow.get_artifact_uri() return mlflow_artifact_uri def main(args):
64
64
206
4
59
Nvidia-Kisti-GPU-Hackathon-A-More-Opt/brain-segmentation-pytorch
train_lightning.py
Python
main
main
32
55
32
32
908b34821d1879ced7d9cb25d9132c19b7e5f335
bigcode/the-stack
train
3e387271c4081dc8cddeaab6
train
function
def get_mlflow_artifact_uri(mlflow): if "file://" in mlflow.get_artifact_uri(): mlflow_artifact_uri = mlflow.get_artifact_uri().replace("file://","") else: mlflow_artifact_uri = mlflow.get_artifact_uri() return mlflow_artifact_uri
def get_mlflow_artifact_uri(mlflow):
if "file://" in mlflow.get_artifact_uri(): mlflow_artifact_uri = mlflow.get_artifact_uri().replace("file://","") else: mlflow_artifact_uri = mlflow.get_artifact_uri() return mlflow_artifact_uri
_data_loader from models.torch_lightning import LitModel import argparse # TODOS: # 0. torch lightning metric setting # 1. tensorboard setting # 2. mlflow setting os.environ['OMP_NUM_THREADS']='1' def get_mlflow_artifact_uri(mlflow):
64
64
69
11
53
Nvidia-Kisti-GPU-Hackathon-A-More-Opt/brain-segmentation-pytorch
train_lightning.py
Python
get_mlflow_artifact_uri
get_mlflow_artifact_uri
23
29
23
23
12d08025f64e8f37f53f53a8bd113f8da25f1774
bigcode/the-stack
train
97c1ff8b63f1d262ade1d4cc
train
class
class Human(ClassicFrame): def __init__(self, size=None, color=None, clip="auto", radius_ext=None, radius_int=None, pressed=False, dark=None, light=None, thick=1, hovered=False, border_color=None): #changer border """If radius is in the range [0, 1], self.radius_value is t...
class Human(ClassicFrame):
def __init__(self, size=None, color=None, clip="auto", radius_ext=None, radius_int=None, pressed=False, dark=None, light=None, thick=1, hovered=False, border_color=None): #changer border """If radius is in the range [0, 1], self.radius_value is the fraction of radiu...
from pygame import BLEND_RGBA_MIN from pygame import Surface from thorpy._utils.colorscomputing import grow_color, normalize_color from thorpy.painting.painters.roundrect import RoundRect from thorpy.painting.painters.classicframe import ClassicFrame from thorpy.painting.graphics import linear_v_monogradation from tho...
84
189
631
6
77
YannThorimbert/PyMap2D
thorpy/painting/painters/optionnal/human.py
Python
Human
Human
11
74
11
12
3e490abc1df177123bd5a204567566da3227eb0d
bigcode/the-stack
train
caaf0dfb5d57b814f2d410ae
train
class
class main(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self) self.setWindowTitle("Main Ui") self.setFixedSize(800, 600) self.setStyleSheet(estiloFondo) self.initUi() def initUi(self): globalFont = (QtGui.QFont("Roboto", 16, QtGui.QFont.Bold)) titulofont = (QtGui.QFont("Roboto...
class main(QMainWindow):
def __init__(self, parent=None): QMainWindow.__init__(self) self.setWindowTitle("Main Ui") self.setFixedSize(800, 600) self.setStyleSheet(estiloFondo) self.initUi() def initUi(self): globalFont = (QtGui.QFont("Roboto", 16, QtGui.QFont.Bold)) titulofont = (QtGui.QFont("Roboto", 20, QtGui.QFont.Bold))...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Nombre: main.py # Autores: Cristian Cala Sierra # License: MIT License # ---------------------------------------------------------------------------- import sys from vista import * from PyQt5 import ...
109
256
1,289
6
103
CristianCala/UIDesignPyQt5
main.py
Python
main
main
15
138
15
15
4c91aabe43332a79c0203bbd159123ba8de970d6
bigcode/the-stack
train