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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c6c3724fdadfb1341756ca4a | train | function | def parse_args(): # pylint: disable=I0011,R0915
""" Command line parsing code"""
class LoadFromJson(argparse.Action): # pylint: disable=I0011,R0903
""" argparse action to support reading options from a json dictionary. """
def __call__(self, parser, namespace, values, o... | def parse_args(): # pylint: disable=I0011,R0915
| """ Command line parsing code"""
class LoadFromJson(argparse.Action): # pylint: disable=I0011,R0903
""" argparse action to support reading options from a json dictionary. """
def __call__(self, parser, namespace, values, option_string=None):
for key, value in values.iteritems():
... | create the page, but we also need to create any pages between the
# last page and this one, and ensure that we end on an even page.
# Spreads are also an issue - if the page we are looking for is not there
# because the page before was a double-spread, then something has gone wrong and we
# should fail... | 256 | 256 | 2,100 | 17 | 239 | richardkchapman/BlurbFlow | flowblurb.py | Python | parse_args | parse_args | 432 | 592 | 432 | 432 | ade3ca63dc5be364a6ed13431180f518510bcc59 | bigcode/the-stack | train |
4b40421156501bc00367048f | train | function | def create_backup(extracted):
""" Create a backup of the bbf2.xml in old_bbfs/bbf2_000000000<n>.xml """
backup_path = extracted + "/old_bbfs"
if not os.path.exists(backup_path):
os.makedirs(backup_path)
next_file = 1
while True:
backup_file = "%s/bbf2_%.10d.xml" % (backup_path, next_... | def create_backup(extracted):
| """ Create a backup of the bbf2.xml in old_bbfs/bbf2_000000000<n>.xml """
backup_path = extracted + "/old_bbfs"
if not os.path.exists(backup_path):
os.makedirs(backup_path)
next_file = 1
while True:
backup_file = "%s/bbf2_%.10d.xml" % (backup_path, next_file)
if not os.path.e... | % \
(name, ppi, width, height))
elif ppi > args.max_ppi:
print ('Resolution too high for %s (%d ppi) - ideal size (%d,%d)' % \
(name, ppi, width, height))
def create_backup(extracted):
| 64 | 64 | 129 | 6 | 58 | richardkchapman/BlurbFlow | flowblurb.py | Python | create_backup | create_backup | 686 | 697 | 686 | 686 | f7c9eabb90eeb641c362cd250db84364d1d8faf6 | bigcode/the-stack | train |
96a86899edc2c985525b4f59 | train | function | def add_title_page(doc, args, pageno):
""" Add a section title page. """
page = find_page(doc, pageno)
title = args.section_title
container = ET.SubElement(page, 'container', {
"transform": "1 0 0 1", "type": "text",
"x": str(args.right if pageno%2 == 0 else args.left),
"y": str(... | def add_title_page(doc, args, pageno):
| """ Add a section title page. """
page = find_page(doc, pageno)
title = args.section_title
container = ET.SubElement(page, 'container', {
"transform": "1 0 0 1", "type": "text",
"x": str(args.right if pageno%2 == 0 else args.left),
"y": str(args.top),
"width": str(args.pa... | for image in images:
this_section = exiftool.get_tag(image.src, args.section_field)
if this_section in sections:
sections[this_section].append(image)
else:
sections[this_section] = [image]
return sections
def add_title_page(doc, args, pagen... | 64 | 64 | 210 | 11 | 52 | richardkchapman/BlurbFlow | flowblurb.py | Python | add_title_page | add_title_page | 868 | 883 | 868 | 868 | 03996d124e1f6021213e31a05053f68795738cfc | bigcode/the-stack | train |
cc9dc4909d254dcfc1ae3f10 | train | function | def find_sections(args, images):
""" Map images to sections using specified exif field. """
sections = {}
with ExifTool(executable=args.exiftool) as exiftool:
for image in images:
this_section = exiftool.get_tag(image.src, args.section_field)
if this_section in sections:
... | def find_sections(args, images):
| """ Map images to sections using specified exif field. """
sections = {}
with ExifTool(executable=args.exiftool) as exiftool:
for image in images:
this_section = exiftool.get_tag(image.src, args.section_field)
if this_section in sections:
sections[this_section... | _dir = tempfile.mkdtemp()
istemp = True
if args.input:
extractBlurbFiles.extract(args.input, args.output_dir)
create_backup(args.output_dir)
else:
initialize_blurb_directory(args.output_dir, args)
return istemp
def find_sections(args, images):
| 64 | 64 | 94 | 7 | 56 | richardkchapman/BlurbFlow | flowblurb.py | Python | find_sections | find_sections | 856 | 866 | 856 | 856 | 64fae5a4c46f1f8cfbef29c4089722d09fffd284 | bigcode/the-stack | train |
abe8248a4197b07abb0ba3b0 | train | function | def fuzzy_sort_coarse(image, pano_threshold):
""" A very fuzzy sort by aspect ratio - portrait then square then landscape then pano"""
if image.width > image.height*pano_threshold:
return 2
elif image.width > image.height:
return 1
elif image.width < image.height:
return -1
e... | def fuzzy_sort_coarse(image, pano_threshold):
| """ A very fuzzy sort by aspect ratio - portrait then square then landscape then pano"""
if image.width > image.height*pano_threshold:
return 2
elif image.width > image.height:
return 1
elif image.width < image.height:
return -1
else:
return 0
| and an indication
of whether last row is complete.
Note that this is destructive in that the builder is not usable afterwards. """
pages = self.get_pages(pagenos[:])
return (sum(1 for _ in pages), self.incomplete)
def fuzzy_sort_coarse(image, pano_threshold):
| 64 | 64 | 78 | 10 | 54 | richardkchapman/BlurbFlow | flowblurb.py | Python | fuzzy_sort_coarse | fuzzy_sort_coarse | 234 | 243 | 234 | 234 | 8848f25126004973f2a8d2b67fe6e99a0649f2b6 | bigcode/the-stack | train |
6c6e2931e4623abdacbfacf0 | train | class | class PageBuilder(object):
""" Populate images onto pages. """
def __init__(self, args, images):
self.args = args
self.images = images[::-1] # reverses the list, not in-place
self.page_height = args.page_height-(args.top+args.bottom)
self.incomplete = True
def _row_width(sel... | class PageBuilder(object):
| """ Populate images onto pages. """
def __init__(self, args, images):
self.args = args
self.images = images[::-1] # reverses the list, not in-place
self.page_height = args.page_height-(args.top+args.bottom)
self.incomplete = True
def _row_width(self, row):
num_deltas... | #!/usr/bin/env python
from __future__ import print_function
""" Populate a blurb book automatically using a 500px-like algorithm"""
import argparse
import glob
import os
import sys
import math
import uuid
import collections
import json
import tempfile
import shutil
import subprocess
import random
import threading
from ... | 167 | 256 | 2,030 | 5 | 162 | richardkchapman/BlurbFlow | flowblurb.py | Python | PageBuilder | PageBuilder | 29 | 232 | 29 | 29 | 478e01b412d0d27194a335ad30be816c0be2bc0d | bigcode/the-stack | train |
3401642acf7fc524d2a87e0d | train | function | def initialize_blurb_directory(path, args):
""" Create a blank blurb directory."""
width, height, name = PRESETS.get(args.format)
if not os.path.exists(path):
os.makedirs(path)
with open(path+'/.version', 'w') as version_file:
version_file.write('4\n')
project_image = Image.new('RGB'... | def initialize_blurb_directory(path, args):
| """ Create a blank blurb directory."""
width, height, name = PRESETS.get(args.format)
if not os.path.exists(path):
os.makedirs(path)
with open(path+'/.version', 'w') as version_file:
version_file.write('4\n')
project_image = Image.new('RGB', (139, 120), "white") # Size not critical
... | : exif tag %s not found in %d of %d images' % \
(args.sort, exiftool.missing_tags, len(images)))
return images
else:
return images
PRESETS = {
'small-square': (495, 495, 'square'),
'standard-landscape': (693, 594, 'landscape'),
'standard-portrait': (585... | 180 | 180 | 602 | 9 | 171 | richardkchapman/BlurbFlow | flowblurb.py | Python | initialize_blurb_directory | initialize_blurb_directory | 786 | 834 | 786 | 786 | 9cd22d9470492554d0acac02ed082fa6db4c77cd | bigcode/the-stack | train |
8de3f0ee4a09bb2713d1f3bc | train | function | def fuzzy_sort_fine(image):
""" A slightly less fuzzy sort by aspect ratio"""
return round(float(image.width)/image.height)
| def fuzzy_sort_fine(image):
| """ A slightly less fuzzy sort by aspect ratio"""
return round(float(image.width)/image.height)
| then square then landscape then pano"""
if image.width > image.height*pano_threshold:
return 2
elif image.width > image.height:
return 1
elif image.width < image.height:
return -1
else:
return 0
def fuzzy_sort_fine(image):
| 64 | 64 | 28 | 7 | 56 | richardkchapman/BlurbFlow | flowblurb.py | Python | fuzzy_sort_fine | fuzzy_sort_fine | 245 | 247 | 245 | 245 | ed2ac851817d5f4b5118cfcd9d9f39e1a3c68a3b | bigcode/the-stack | train |
2a3ce0dfa98786b37393cb8a | train | function | def empty_pages(doc):
""" Returns all empty pages in the original Blurb doc. """
for page in doc.findall('.//section/page'):
if not page.findall('container'):
yield page
| def empty_pages(doc):
| """ Returns all empty pages in the original Blurb doc. """
for page in doc.findall('.//section/page'):
if not page.findall('container'):
yield page
| Unexpected page number')
for page in range(last+1, (pageno+1)/2 * 2 + 1):
ET.SubElement(section, 'page', {'color':'#00000000', 'number': str(page)})
return find_page(doc, pageno)
def empty_pages(doc):
| 64 | 64 | 42 | 5 | 59 | richardkchapman/BlurbFlow | flowblurb.py | Python | empty_pages | empty_pages | 421 | 425 | 421 | 421 | 48b7841316213e1dc4ab490b4bc88eea85810016 | bigcode/the-stack | train |
1882992835d184e0e996e608 | train | class | class ExifTool(object):
""" Read exif data using exiftool.
Derived from a suggestion at
http://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script.
"""
sentinel = "{ready}\n"
def __init__(self, executable="exiftool"):
self.executable = executable
sel... | class ExifTool(object):
| """ Read exif data using exiftool.
Derived from a suggestion at
http://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script.
"""
sentinel = "{ready}\n"
def __init__(self, executable="exiftool"):
self.executable = executable
self.process = None
... | if self.all_rows:
for row in self.all_rows:
self._unget_all_row(row)
self._unget_all_row(self.last_row)
for row in self.next_row:
self._unget_all_row(row)
self.all_rows = None
self.last_row = None
... | 105 | 105 | 351 | 6 | 99 | richardkchapman/BlurbFlow | flowblurb.py | Python | ExifTool | ExifTool | 357 | 401 | 357 | 357 | 0270fc81d432e877a02687a1c8d74c2d700a23d2 | bigcode/the-stack | train |
9cf03884cfba375cf7ce7398 | train | function | def populate_section(doc, args, pagenos, images, previews):
""" Populate all images for a single section. """
images = sort_images(images, args)
if args.section_start == 'even' or args.section_start == 'full':
while pagenos and (pagenos[0] % 2 == 1):
pagenos.pop(0)
if args.section_st... | def populate_section(doc, args, pagenos, images, previews):
| """ Populate all images for a single section. """
images = sort_images(images, args)
if args.section_start == 'even' or args.section_start == 'full':
while pagenos and (pagenos[0] % 2 == 1):
pagenos.pop(0)
if args.section_start == 'odd' or args.section_start == 'full':
while ... | else:
break
print ('Optimized image height is %d' % (args.image_height))
if args.random:
print ('Optimized seed %s' % (args.random))
print ('Optimization incomplete: %d' % (incomplete))
return populate_pages(args, images, pagenos)
def populate_section(doc, args, pagenos, imag... | 83 | 83 | 279 | 15 | 68 | richardkchapman/BlurbFlow | flowblurb.py | Python | populate_section | populate_section | 944 | 969 | 944 | 944 | 971b9a3a51e7c2cd37021162e06f7a1a3c843d81 | bigcode/the-stack | train |
f0d1f43d2febef2957134a9b | train | function | def load_media(project_dir, image_list):
""" Load and/or populate blurb media registry. """
if os.path.isfile(project_dir+'/media_registry.xml'):
media = ET.parse(project_dir+'/media_registry.xml')
else:
root = ET.Element('medialist')
for elem in ['images', 'video', 'audio', 'text']:... | def load_media(project_dir, image_list):
| """ Load and/or populate blurb media registry. """
if os.path.isfile(project_dir+'/media_registry.xml'):
media = ET.parse(project_dir+'/media_registry.xml')
else:
root = ET.Element('medialist')
for elem in ['images', 'video', 'audio', 'text']:
ET.SubElement(root, elem)
... | os.makedirs("%s/images" % (project_dir))
link_or_copy(image_name, "%s/images/%s.%s" % (project_dir, guid, ext))
# creation of the thumbnails deferred until merge time
changed = True
return changed
def load_media(project_dir, image_list):
| 64 | 64 | 122 | 9 | 54 | richardkchapman/BlurbFlow | flowblurb.py | Python | load_media | load_media | 736 | 747 | 736 | 736 | 7f78ba2f13496e170c31fd4e72b9e9b0a8b28284 | bigcode/the-stack | train |
3060d112abb41034f9b3c363 | train | function | def populate_single_page(args, count, images, pagenos):
""" Return a generator that scales all supplied images to fit on fixed number of pages."""
def _try_it():
builder = make_builder(args, images)
page_count, incomplete = builder.get_page_count(pagenos)
return (page_count, incomplete)
... | def populate_single_page(args, count, images, pagenos):
| """ Return a generator that scales all supplied images to fit on fixed number of pages."""
def _try_it():
builder = make_builder(args, images)
page_count, incomplete = builder.get_page_count(pagenos)
return (page_count, incomplete)
while True:
page_count, incomplete = _try_i... | title)
def make_builder(args, images):
""" Return a PageBuilder object appropriate for given args."""
if args.smart:
return SmartPageBuilder(args, images)
else:
if args.reverse:
images = images[::-1]
return PageBuilder(args, images)
def populate_pages(args, images, pag... | 108 | 108 | 361 | 14 | 94 | richardkchapman/BlurbFlow | flowblurb.py | Python | populate_single_page | populate_single_page | 898 | 942 | 898 | 898 | e38bd48c84bc1b0b602c04129948e9fef5db4050 | bigcode/the-stack | train |
51ed1e099569a4ce2af43d02 | train | class | class SmartPageBuilder(PageBuilder):
""" Populate images onto pages, trying to do so intelligently.
Smart algorithm mk 2:
Sort by aspect ratio
Generate rows that attempt to scale equally (based on aspect ratio of first image in row)
(note that average might be better but harder as we... | class SmartPageBuilder(PageBuilder):
| """ Populate images onto pages, trying to do so intelligently.
Smart algorithm mk 2:
Sort by aspect ratio
Generate rows that attempt to scale equally (based on aspect ratio of first image in row)
(note that average might be better but harder as we don't know what images are in the ro... | .args.odd_only or self.args.even_only):
populated = self.next_page(page_width, pageno, first)
first = False
if populated:
del pagenos[0:i]
i = 0
yield (populated, pageno, double)
... | 256 | 256 | 1,047 | 7 | 249 | richardkchapman/BlurbFlow | flowblurb.py | Python | SmartPageBuilder | SmartPageBuilder | 249 | 355 | 249 | 249 | d417f2e53a5df39bea29cc4d7486e6b24269cbf9 | bigcode/the-stack | train |
6191dff638c297d8cb532f82 | train | function | def link_or_copy(source, dest):
""" Symlink a file if we can, else copy it."""
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, dest)
else:
shutil.copyfile(source, dest)
| def link_or_copy(source, dest):
| """ Symlink a file if we can, else copy it."""
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, dest)
else:
shutil.copyfile(source, dest)
| _file = "%s/bbf2_%.10d.xml" % (backup_path, next_file)
if not os.path.exists(backup_file):
shutil.copyfile(extracted+"/bbf2.xml", backup_file)
break
next_file += 1
def link_or_copy(source, dest):
| 64 | 64 | 62 | 8 | 55 | richardkchapman/BlurbFlow | flowblurb.py | Python | link_or_copy | link_or_copy | 699 | 705 | 699 | 699 | 8c65e27070fba1fdc61e8b294eeb9c0d63c1c590 | bigcode/the-stack | train |
bfb87a3138a85ff99541d0d2 | train | function | def main():
""" Main code. """
args = parse_args()
istemp = initialize_output_directory(args)
xml_parser = ET.XMLParser(remove_blank_text=True)
doc = ET.parse(args.output_dir+'/bbf2.xml', xml_parser)
if args.page_width == -1:
args.page_width = float(doc.getroot().get('width'))
if arg... | def main():
| """ Main code. """
args = parse_args()
istemp = initialize_output_directory(args)
xml_parser = ET.XMLParser(remove_blank_text=True)
doc = ET.parse(args.output_dir+'/bbf2.xml', xml_parser)
if args.page_width == -1:
args.page_width = float(doc.getroot().get('width'))
if args.page_heigh... | all images for multiple sections. """
sections_map = find_sections(args, images)
if not args.sections:
args.sections = sorted(sections_map.keys())
for section in args.sections:
section_args = argparse.Namespace(**vars(args))
setattr(section_args, 'section_title', section)
if... | 141 | 141 | 470 | 3 | 138 | richardkchapman/BlurbFlow | flowblurb.py | Python | main | main | 987 | 1,031 | 987 | 987 | 5c2d003e3f46063507de00dae5ca1a15a3cda59b | bigcode/the-stack | train |
7aeb7ecd29875da900f7d374 | train | function | def sort_images(images, args):
""" Sort images according to requested order. """
if args.random:
random.seed(args.random)
random.shuffle(images)
if args.sort:
if args.sort == 'name':
return sorted(images, key=lambda image: image.src)
elif args.sort == 'date':
... | def sort_images(images, args):
| """ Sort images according to requested order. """
if args.random:
random.seed(args.random)
random.shuffle(images)
if args.sort:
if args.sort == 'name':
return sorted(images, key=lambda image: image.src)
elif args.sort == 'date':
return sorted(images, k... | elem in ['images', 'video', 'audio', 'text']:
ET.SubElement(root, elem)
media = ET.ElementTree(root)
if image_list and populate_media(project_dir, media, image_list):
media.write(project_dir+'/media_registry.xml', pretty_print=True)
return media
def sort_images(images, args):
| 70 | 70 | 236 | 7 | 62 | richardkchapman/BlurbFlow | flowblurb.py | Python | sort_images | sort_images | 749 | 773 | 749 | 749 | d2174c6727b0696b6b83317db63499c6935ad4c1 | bigcode/the-stack | train |
6dc1d96db441805f86d3d056 | train | function | def populate_media(project_dir, media, images):
""" Add listed images to the media_registry xml. """
(parent,) = media.xpath('./images')
changed = False
for image_name in images:
image_name = os.path.abspath(image_name)
if not media.xpath('.//images/media[@src=\'%s\']' % image_name):
... | def populate_media(project_dir, media, images):
| """ Add listed images to the media_registry xml. """
(parent,) = media.xpath('./images')
changed = False
for image_name in images:
image_name = os.path.abspath(image_name)
if not media.xpath('.//images/media[@src=\'%s\']' % image_name):
img = Image.open(image_name)
... | next_file += 1
def link_or_copy(source, dest):
""" Symlink a file if we can, else copy it."""
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, dest)
else:
shutil.copyfile(source, dest)
def populate_media(project_dir, media, images):
| 79 | 79 | 266 | 10 | 69 | richardkchapman/BlurbFlow | flowblurb.py | Python | populate_media | populate_media | 707 | 734 | 707 | 707 | 021de27af5babc60506374f9b6d4c89e158a2b6a | bigcode/the-stack | train |
ee02519f0464f1e5da226174 | train | class | class ReadIOInfoOnNFS(object):
def __init__(
self,
mount_point,
yaml_fname=IO_INFO_FNAME,
):
self.yaml_fname = yaml_fname
self.file_op = FileOps(self.yaml_fname, type="yaml")
self.mount_point = mount_point
self.base_dirs = []
self.files = []
d... | class ReadIOInfoOnNFS(object):
| def __init__(
self,
mount_point,
yaml_fname=IO_INFO_FNAME,
):
self.yaml_fname = yaml_fname
self.file_op = FileOps(self.yaml_fname, type="yaml")
self.mount_point = mount_point
self.base_dirs = []
self.files = []
def initialize_verify_io(self):
... | import logging
import os
import sys
sys.path.append(os.path.abspath(os.path.join(__file__, "../../../")))
import v2.utils.utils as utils
from v2.lib.exceptions import TestExecError
from v2.utils.utils import FileOps
IO_INFO_FNAME = "io_info.yaml"
log = logging.getLogger()
class ReadIOInfoOnNFS(object):
| 76 | 177 | 591 | 9 | 67 | viduship/ceph-qe-scripts | rgw/v2/tests/nfs_ganesha/verify_on_nfs.py | Python | ReadIOInfoOnNFS | ReadIOInfoOnNFS | 16 | 84 | 16 | 16 | 8ffece3030c9da24add493fc317868a7d5b8a686 | bigcode/the-stack | train |
c5a3ba2cb320e5dc867ecae8 | train | function | def voice_toggle(request):
if 'voice_toggle' in request.session:
return request.session['voice_toggle']=='true'
else:
return False
| def voice_toggle(request):
| if 'voice_toggle' in request.session:
return request.session['voice_toggle']=='true'
else:
return False
| from .models import Odai
def common(request):
context = {
"odais": Odai.objects.all().order_by("-id"),
"voice_toggle": voice_toggle(request)
}
return context
def voice_toggle(request):
| 50 | 64 | 32 | 5 | 44 | agajo/oogiridojo_app_on_django | context_processors.py | Python | voice_toggle | voice_toggle | 10 | 14 | 10 | 10 | 94a0442d15270df396127596209518d02675e273 | bigcode/the-stack | train |
74689ead7ab5b5efd6d69dc9 | train | function | def common(request):
context = {
"odais": Odai.objects.all().order_by("-id"),
"voice_toggle": voice_toggle(request)
}
return context
| def common(request):
| context = {
"odais": Odai.objects.all().order_by("-id"),
"voice_toggle": voice_toggle(request)
}
return context
| from .models import Odai
def common(request):
| 11 | 64 | 38 | 4 | 6 | agajo/oogiridojo_app_on_django | context_processors.py | Python | common | common | 3 | 8 | 3 | 3 | c6f7e4084c9f80f1fbe8936ad8c9fdb9b92ad746 | bigcode/the-stack | train |
ff688d10217a6e82f4ec51b3 | train | function | def get_drugs():
json_data = json.load(urlopen(rest_api))
return json_data
| def get_drugs():
| json_data = json.load(urlopen(rest_api))
return json_data
| import json
from urllib.request import urlopen
from django.conf import settings
# get rest endpoint from settings
rest_api = settings.DJANGOPHARMA_REST_URL
# get all data from rest service
def get_drugs():
| 50 | 64 | 21 | 5 | 44 | thodoris/djangoPharma | djangoPharma/drugs/restService.py | Python | get_drugs | get_drugs | 9 | 11 | 9 | 9 | e3fcaf23fc0c983abf72d663cfc16935dd694c7f | bigcode/the-stack | train |
717f2769bce29135cba83704 | train | function | def get_drug_by_id(drug_id):
urlpath = rest_api + '/' + drug_id
rest_result = urlopen(urlpath)
resp = json.load(rest_result)
return resp
| def get_drug_by_id(drug_id):
| urlpath = rest_api + '/' + drug_id
rest_result = urlopen(urlpath)
resp = json.load(rest_result)
return resp
| _drugs()
for drug in json_data:
del drug['barcode']
del drug['producer']
del drug['price_wholesale']
del drug['price_retail']
return json_data
# get a drug by id (from REST API)
def get_drug_by_id(drug_id):
| 64 | 64 | 43 | 10 | 54 | thodoris/djangoPharma | djangoPharma/drugs/restService.py | Python | get_drug_by_id | get_drug_by_id | 27 | 31 | 27 | 27 | 800442317e6838a432abeaa4a907ab41d042d307 | bigcode/the-stack | train |
b5c9d04ab733a5635cf7d58b | train | function | def get_drugs_index():
json_data = get_drugs()
for drug in json_data:
del drug['barcode']
del drug['producer']
del drug['price_wholesale']
del drug['price_retail']
return json_data
| def get_drugs_index():
| json_data = get_drugs()
for drug in json_data:
del drug['barcode']
del drug['producer']
del drug['price_wholesale']
del drug['price_retail']
return json_data
| .DJANGOPHARMA_REST_URL
# get all data from rest service
def get_drugs():
json_data = json.load(urlopen(rest_api))
return json_data
# returns a drug dict (drug id , drug , name)
# by removing unwanted fields
def get_drugs_index():
| 64 | 64 | 54 | 6 | 57 | thodoris/djangoPharma | djangoPharma/drugs/restService.py | Python | get_drugs_index | get_drugs_index | 16 | 23 | 16 | 16 | 189f835bba25c23fa6907026d90ff283712ff937 | bigcode/the-stack | train |
595c70bac50ec1efdf955d22 | train | class | class Kubernetes(AgentCheck):
""" Collect metrics and events from Kubernetes """
pod_names_by_container = {}
def __init__(self, name, init_config, agentConfig, instances=None):
if instances is not None and len(instances) > 1:
raise Exception('Kubernetes check only supports one configur... | class Kubernetes(AgentCheck):
| """ Collect metrics and events from Kubernetes """
pod_names_by_container = {}
def __init__(self, name, init_config, agentConfig, instances=None):
if instances is not None and len(instances) > 1:
raise Exception('Kubernetes check only supports one configured instance.')
AgentC... | # seconds
NET_ERRORS = ['rx_errors', 'tx_errors', 'rx_dropped', 'tx_dropped']
DEFAULT_ENABLED_GAUGES = [
'memory.usage',
'filesystem.usage']
GAUGE = AgentCheck.gauge
RATE = AgentCheck.rate
HISTORATE = AgentCheck.generate_historate_func(["container_name"])
HISTO = AgentCheck.generate_histogram_func(["contai... | 256 | 256 | 4,892 | 6 | 250 | chotiwat/integrations-core | kubernetes/datadog_checks/kubernetes/kubernetes.py | Python | Kubernetes | Kubernetes | 68 | 563 | 68 | 68 | 83ef7fa86799f431691e6af64451ac38f885cc86 | bigcode/the-stack | train |
97f107b47ad4a74ce73340f9 | train | function | def get(grid):
visited = set()
min_size = float("inf")
for r in range(len(grid)):
for c in range(len(grid[0])):
size = explore_size(grid, r, c, visited)
if size > 0 and size < min_size:
min_size = size
return min_size
| def get(grid):
| visited = set()
min_size = float("inf")
for r in range(len(grid)):
for c in range(len(grid[0])):
size = explore_size(grid, r, c, visited)
if size > 0 and size < min_size:
min_size = size
return min_size
| return the size of the smallest island.
An island is a vertically or horizontally connected region of land.
You may assume that the grid contains at least one island.
- r = number of rows
- c = number of columns
- Time: O(rc)
- Space: O(rc)
"""
def get(grid):
| 64 | 64 | 71 | 4 | 60 | vitormeriat/basic_graph_algorithms | graph_algorithms/minimum_island.py | Python | get | get | 17 | 25 | 17 | 17 | 82423cea04d81d5ddc9c52e24a52e3347d0359f9 | bigcode/the-stack | train |
3e91083c5002419509e41e2f | train | function | def explore_size(grid, r, c, visited):
row_inbounds = 0 <= r < len(grid)
col_inbounds = 0 <= c < len(grid[0])
if not row_inbounds or not col_inbounds:
return 0
if grid[r][c] == 'W':
return 0
pos = (r, c)
if pos in visited:
return 0
visited.add(pos)
size = 1
... | def explore_size(grid, r, c, visited):
| row_inbounds = 0 <= r < len(grid)
col_inbounds = 0 <= c < len(grid[0])
if not row_inbounds or not col_inbounds:
return 0
if grid[r][c] == 'W':
return 0
pos = (r, c)
if pos in visited:
return 0
visited.add(pos)
size = 1
size += explore_size(grid, r - 1, c, v... | for r in range(len(grid)):
for c in range(len(grid[0])):
size = explore_size(grid, r, c, visited)
if size > 0 and size < min_size:
min_size = size
return min_size
def explore_size(grid, r, c, visited):
| 64 | 64 | 170 | 11 | 52 | vitormeriat/basic_graph_algorithms | graph_algorithms/minimum_island.py | Python | explore_size | explore_size | 28 | 47 | 28 | 28 | 098ff6854c93ffb470dd1ece5917e03b5a9cd9c8 | bigcode/the-stack | train |
7a5fb47c6049d961cbdfcca1 | train | class | @attr.s(auto_attribs=True, on_setattr=DENON_ATTR_SETATTR)
class DenonAVR(DenonAVRFoundation):
"""
Representing a Denon AVR Device.
Initialize MainZone of DenonAVR.
:param host: IP or HOSTNAME.
:type host: str
:param name: Device name, if None FriendlyName of device is used.
:type name: st... | @attr.s(auto_attribs=True, on_setattr=DENON_ATTR_SETATTR)
class DenonAVR(DenonAVRFoundation):
| """
Representing a Denon AVR Device.
Initialize MainZone of DenonAVR.
:param host: IP or HOSTNAME.
:type host: str
:param name: Device name, if None FriendlyName of device is used.
:type name: str or None
:param show_all_inputs: If True deleted input functions are also shown
:typ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module implements the interface to Denon AVR receivers.
:copyright: (c) 2016 by Oliver Goetz.
:license: MIT, see LICENSE for more details.
"""
import logging
import time
from typing import Dict, List, Optional
import attr
from .decorators import run_async_syn... | 232 | 256 | 4,670 | 31 | 201 | elad-bar/denonavr | denonavr/denonavr.py | Python | DenonAVR | DenonAVR | 32 | 671 | 32 | 33 | 34b091d74773c02ee7e6ede8f65eb28fedea6f56 | bigcode/the-stack | train |
c785ff89fab8b48b9572292e | train | function | def PeterPan():
webbrowser.open(PP, new=new)
| def PeterPan():
| webbrowser.open(PP, new=new)
| from tkinter import *
import webbrowser
from subprocess import call
def LittlePrincess():
webbrowser.open(LP, new=new)
def PeterPan():
| 31 | 64 | 14 | 4 | 27 | UAEU-IRI/std_googleAssistant | GUI/ReemCodes/BabyG/AudioBooksBabyG.py | Python | PeterPan | PeterPan | 8 | 9 | 8 | 8 | dd2fd44d8381d81ba3571694e3b063bfc7fd78e9 | bigcode/the-stack | train |
409bc5abb14f1d254c57e6ca | train | function | def LittlePrincess():
webbrowser.open(LP, new=new)
| def LittlePrincess():
| webbrowser.open(LP, new=new)
| from tkinter import *
import webbrowser
from subprocess import call
def LittlePrincess():
| 17 | 64 | 14 | 4 | 12 | UAEU-IRI/std_googleAssistant | GUI/ReemCodes/BabyG/AudioBooksBabyG.py | Python | LittlePrincess | LittlePrincess | 5 | 6 | 5 | 5 | 26a98745e317f2c3449d388836a07c60b1ff8273 | bigcode/the-stack | train |
493c3ff975a45a3b05c15628 | train | class | class GUI:
def __init__(self, master):
frame = Frame(master)
frame.pack()
frame.configure(background='white')
self.button1 = Button(frame, bg="white", command=PeterPan)
self.button1.config(image=photo1)
self.button2 = Button(frame, bg="white", command=LittlePrincess)
... | class GUI:
| def __init__(self, master):
frame = Frame(master)
frame.pack()
frame.configure(background='white')
self.button1 = Button(frame, bg="white", command=PeterPan)
self.button1.config(image=photo1)
self.button2 = Button(frame, bg="white", command=LittlePrincess)
sel... | webbrowser.open(LP, new=new)
def PeterPan():
webbrowser.open(PP, new=new)
def Back():
root.destroy()
call(['python', 'C:/Users/Reemy/Documents/GitHub/std_googleAssistant/GUI/Codes/BabyG/AppsBabyG.py'])
class GUI:
| 64 | 64 | 109 | 3 | 61 | UAEU-IRI/std_googleAssistant | GUI/ReemCodes/BabyG/AudioBooksBabyG.py | Python | GUI | GUI | 15 | 25 | 15 | 15 | f95c52033dd3851ad09d1a85654641858b127018 | bigcode/the-stack | train |
8f8f4094df4143ce97380550 | train | function | def Back():
root.destroy()
call(['python', 'C:/Users/Reemy/Documents/GitHub/std_googleAssistant/GUI/Codes/BabyG/AppsBabyG.py'])
| def Back():
| root.destroy()
call(['python', 'C:/Users/Reemy/Documents/GitHub/std_googleAssistant/GUI/Codes/BabyG/AppsBabyG.py'])
| from tkinter import *
import webbrowser
from subprocess import call
def LittlePrincess():
webbrowser.open(LP, new=new)
def PeterPan():
webbrowser.open(PP, new=new)
def Back():
| 44 | 64 | 38 | 3 | 41 | UAEU-IRI/std_googleAssistant | GUI/ReemCodes/BabyG/AudioBooksBabyG.py | Python | Back | Back | 11 | 13 | 11 | 11 | 8dd28b075e9e37b00f25e754cbb58f204f35c147 | bigcode/the-stack | train |
def4fb8f82813c85c2163720 | train | function | def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
email = req.params.get('email')
if not email:
try:
req_body = req.get_json()
except ValueError:
pass
else:
email = req_body.get... | def main(req: func.HttpRequest) -> func.HttpResponse:
| logging.info('Python HTTP trigger function processed a request.')
email = req.params.get('email')
if not email:
try:
req_body = req.get_json()
except ValueError:
pass
else:
email = req_body.get('email')
if email:
steve_table = SteveTa... | import logging
import datetime
import azure.functions as func
from steve_constants import TEST_MODE, ACCOUNT_KEY
from steve_email import SteveSingleEmail
from steve_table import SteveTable
from steve_templates import generate_func_response
def main(req: func.HttpRequest) -> func.HttpResponse:
| 62 | 133 | 446 | 13 | 48 | Ssloto/SteveEmail | Unsubscribe/__init__.py | Python | main | main | 11 | 58 | 11 | 11 | 97f12ec66cb6c7a0f0ae3ad06fbdd62614ab1a5b | bigcode/the-stack | train |
f5303c9d930bad100103d494 | train | class | class CryptoMKTHMACAuth(HMACAuth):
api_key_header = "X-MKT-APIKEY"
nonce_header = "X-MKT-TIMESTAMP"
signature_header = "X-MKT-SIGNATURE"
signature_delimiter = ""
algorithm = "sha384"
def _nonce(self):
return self.timestamp.seconds()
def build_message(self, r: P, nonce: str):
... | class CryptoMKTHMACAuth(HMACAuth):
| api_key_header = "X-MKT-APIKEY"
nonce_header = "X-MKT-TIMESTAMP"
signature_header = "X-MKT-SIGNATURE"
signature_delimiter = ""
algorithm = "sha384"
def _nonce(self):
return self.timestamp.seconds()
def build_message(self, r: P, nonce: str):
path = urlsplit(r.path_url).path
... | .parse import urlsplit
from requests import PreparedRequest as P
from . import constants as _c
from . import models as _m
from .client_public import CryptoMKTPublic
from ..auth import HMACAuth
from ..base import AuthMixin
class CryptoMKTHMACAuth(HMACAuth):
| 64 | 64 | 153 | 10 | 53 | delta575/trading-api-wrappers | trading_api_wrappers/cryptomkt/client_auth.py | Python | CryptoMKTHMACAuth | CryptoMKTHMACAuth | 13 | 32 | 13 | 14 | e2e5b9421e65c1f32d404d092d8b1f7a8b241259 | bigcode/the-stack | train |
a869a9d9fc574b2a20001f89 | train | class | class CryptoMKTAuth(CryptoMKTPublic, AuthMixin):
auth_cls = CryptoMKTHMACAuth
def __init__(self, key: str, secret: str, timeout: int = None, **kwargs):
super().__init__(timeout, **kwargs)
self.add_auth(key, secret)
# BALANCE------------------------------------------------------------------... | class CryptoMKTAuth(CryptoMKTPublic, AuthMixin):
| auth_cls = CryptoMKTHMACAuth
def __init__(self, key: str, secret: str, timeout: int = None, **kwargs):
super().__init__(timeout, **kwargs)
self.add_auth(key, secret)
# BALANCE------------------------------------------------------------------
def balance(self):
data = self.get("... | import json
from urllib.parse import urlsplit
from requests import PreparedRequest as P
from . import constants as _c
from . import models as _m
from .client_public import CryptoMKTPublic
from ..auth import HMACAuth
from ..base import AuthMixin
class CryptoMKTHMACAuth(HMACAuth):
api_key_header = "X-MKT-APIKEY"... | 226 | 232 | 774 | 14 | 211 | delta575/trading-api-wrappers | trading_api_wrappers/cryptomkt/client_auth.py | Python | CryptoMKTAuth | CryptoMKTAuth | 35 | 160 | 35 | 35 | 6b0bebcfa23f3e6785888f1a6a61942c72aa8676 | bigcode/the-stack | train |
1f396dbe543bca18cd32d01f | train | function | def ReadCombiInfo(fileName) :
infil = open(fileName, 'r')
lines = infil.readlines()
infil.close()
infos = []
for lin in lines:
tlst = lin.strip().split()
info = float(tlst[1])
infos.append(info)
return infos
| def ReadCombiInfo(fileName) :
| infil = open(fileName, 'r')
lines = infil.readlines()
infil.close()
infos = []
for lin in lines:
tlst = lin.strip().split()
info = float(tlst[1])
infos.append(info)
return infos
|
def getNameAct(conn):
data = conn.GetData(table='raw_data', fields='mol_name,activity_class')
nameAct = {}
for dat in data :
nameAct[dat[0]] = dat[1]
return nameAct
def ReadCombiInfo(fileName) :
| 64 | 64 | 66 | 9 | 54 | Ivy286/cluster_basedfps | third_party_package/RDKit_2015_03_1/rdkit/ML/InfoTheory/testBitRanker.py | Python | ReadCombiInfo | ReadCombiInfo | 31 | 40 | 31 | 31 | ac4c8cddd84e95f309726e81daa9ea54ddb9398d | bigcode/the-stack | train |
7492ed2c70713294af5e299a | train | function | def getNameAct(conn):
data = conn.GetData(table='raw_data', fields='mol_name,activity_class')
nameAct = {}
for dat in data :
nameAct[dat[0]] = dat[1]
return nameAct
| def getNameAct(conn):
| data = conn.GetData(table='raw_data', fields='mol_name,activity_class')
nameAct = {}
for dat in data :
nameAct[dat[0]] = dat[1]
return nameAct
| (table='signatures', fields='mol_name,fingerprint')
fpMap = {}
for dat in data :
pkl = str(dat[1])
sbv = pickle.loads(pkl)
fpMap[dat[0]] = sbv
return fpMap
def getNameAct(conn):
| 64 | 64 | 54 | 6 | 57 | Ivy286/cluster_basedfps | third_party_package/RDKit_2015_03_1/rdkit/ML/InfoTheory/testBitRanker.py | Python | getNameAct | getNameAct | 23 | 29 | 23 | 23 | 6b3855babf1648fc32fb3c3a6c3a32a3b42d6634 | bigcode/the-stack | train |
d09ba177ecc6a6125ac33818 | train | class | class TestCase(unittest.TestCase):
def setUp(self) :
pass
def test0Ranker(self) :
nbits = 5000
dbName = os.path.join('../','test_data', 'FEW_CDK2.GDB')
conn = DbConnect(dbName)
fps = getFingerprints(conn)
nameAct = getNameAct(conn)
sl = len(fps.values()[0... | class TestCase(unittest.TestCase):
| def setUp(self) :
pass
def test0Ranker(self) :
nbits = 5000
dbName = os.path.join('../','test_data', 'FEW_CDK2.GDB')
conn = DbConnect(dbName)
fps = getFingerprints(conn)
nameAct = getNameAct(conn)
sl = len(fps.values()[0])
rnkr = InfoTheory.InfoBi... | DataStructs
from rdkit.Dbase.DbConnection import DbConnect
import os
from rdkit.six.moves import cPickle as pickle
def feq(v1,v2,tol2=1e-4):
return abs(v1-v2)<=tol2
def getFingerprints(conn) :
data = conn.GetData(table='signatures', fields='mol_name,fingerprint')
fpMap = {}
for dat in data :
... | 256 | 256 | 917 | 7 | 248 | Ivy286/cluster_basedfps | third_party_package/RDKit_2015_03_1/rdkit/ML/InfoTheory/testBitRanker.py | Python | TestCase | TestCase | 42 | 131 | 42 | 42 | 84cbe76f69ca074015d389e7f879f8cdadeb19d9 | bigcode/the-stack | train |
8a6afd96d9078f857f05866d | train | function | def feq(v1,v2,tol2=1e-4):
return abs(v1-v2)<=tol2
| def feq(v1,v2,tol2=1e-4):
| return abs(v1-v2)<=tol2
|
import unittest
from rdkit.ML import InfoTheory
from rdkit import DataStructs
from rdkit.Dbase.DbConnection import DbConnect
import os
from rdkit.six.moves import cPickle as pickle
def feq(v1,v2,tol2=1e-4):
| 64 | 64 | 27 | 16 | 47 | Ivy286/cluster_basedfps | third_party_package/RDKit_2015_03_1/rdkit/ML/InfoTheory/testBitRanker.py | Python | feq | feq | 11 | 12 | 11 | 11 | 5043cb60db0552209207b516ec6d669e80d0ce8d | bigcode/the-stack | train |
9d497acc36d61f932b12b964 | train | function | def getFingerprints(conn) :
data = conn.GetData(table='signatures', fields='mol_name,fingerprint')
fpMap = {}
for dat in data :
pkl = str(dat[1])
sbv = pickle.loads(pkl)
fpMap[dat[0]] = sbv
return fpMap
| def getFingerprints(conn) :
| data = conn.GetData(table='signatures', fields='mol_name,fingerprint')
fpMap = {}
for dat in data :
pkl = str(dat[1])
sbv = pickle.loads(pkl)
fpMap[dat[0]] = sbv
return fpMap
| Structs
from rdkit.Dbase.DbConnection import DbConnect
import os
from rdkit.six.moves import cPickle as pickle
def feq(v1,v2,tol2=1e-4):
return abs(v1-v2)<=tol2
def getFingerprints(conn) :
| 64 | 64 | 71 | 7 | 56 | Ivy286/cluster_basedfps | third_party_package/RDKit_2015_03_1/rdkit/ML/InfoTheory/testBitRanker.py | Python | getFingerprints | getFingerprints | 14 | 21 | 14 | 14 | d2231aad4cb3efeea84d904c4fec5e3a16ad336f | bigcode/the-stack | train |
80c992d4107b6f35ff2f897b | train | class | @pulumi.input_type
class MeshArgs:
def __init__(__self__, *,
name: Optional[pulumi.Input[str]] = None,
spec: Optional[pulumi.Input['MeshSpecArgs']] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of argumen... | @pulumi.input_type
class MeshArgs:
| def __init__(__self__, *,
name: Optional[pulumi.Input[str]] = None,
spec: Optional[pulumi.Input['MeshSpecArgs']] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of arguments for constructing a Mesh resource... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | 111 | 147 | 490 | 10 | 101 | aamir-locus/pulumi-aws | sdk/python/pulumi_aws/appmesh/mesh.py | Python | MeshArgs | MeshArgs | 15 | 68 | 15 | 16 | b63e9385fab26da6e492e93ae43764e1d99e0109 | bigcode/the-stack | train |
579b111070824b1c115efd54 | train | class | @pulumi.input_type
class _MeshState:
def __init__(__self__, *,
arn: Optional[pulumi.Input[str]] = None,
created_date: Optional[pulumi.Input[str]] = None,
last_updated_date: Optional[pulumi.Input[str]] = None,
mesh_owner: Optional[pulumi.Input[str]]... | @pulumi.input_type
class _MeshState:
| def __init__(__self__, *,
arn: Optional[pulumi.Input[str]] = None,
created_date: Optional[pulumi.Input[str]] = None,
last_updated_date: Optional[pulumi.Input[str]] = None,
mesh_owner: Optional[pulumi.Input[str]] = None,
name: Optio... | The name to use for the service mesh. Must be between 1 and 255 characters in length.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def spec(self) -> Opti... | 256 | 256 | 1,203 | 11 | 245 | aamir-locus/pulumi-aws | sdk/python/pulumi_aws/appmesh/mesh.py | Python | _MeshState | _MeshState | 71 | 204 | 71 | 72 | 79ab8eaafadf56b3231f0d349260b037bba9aeb6 | bigcode/the-stack | train |
bca8bab35233e6984c8e859d | train | class | class Mesh(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
name: Optional[pulumi.Input[str]] = None,
spec: Optional[pulumi.Input[pulumi.InputType['MeshSpecArgs']]] = No... | class Mesh(pulumi.CustomResource):
@overload
| def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
name: Optional[pulumi.Input[str]] = None,
spec: Optional[pulumi.Input[pulumi.InputType['MeshSpecArgs']]] = None,
tags: Optional[pulumi.Input[... | [pulumi.Input[str]]:
"""
The resource owner's AWS account ID.
"""
return pulumi.get(self, "resource_owner")
@resource_owner.setter
def resource_owner(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "resource_owner", value)
@property
@pulumi.getter
... | 256 | 256 | 2,044 | 13 | 243 | aamir-locus/pulumi-aws | sdk/python/pulumi_aws/appmesh/mesh.py | Python | Mesh | Mesh | 207 | 442 | 207 | 208 | 28eaf8a622dc175a36a476efe1acf04bc9685498 | bigcode/the-stack | train |
ac6d1425f6dea68313736361 | train | class | class MagicConfig(AppConfig):
name = 'magic'
| class MagicConfig(AppConfig):
| name = 'magic'
| from django.apps import AppConfig
class MagicConfig(AppConfig):
| 13 | 64 | 12 | 6 | 6 | Angoreher/xcero | magic/apps.py | Python | MagicConfig | MagicConfig | 4 | 5 | 4 | 4 | 6444c0eb19edf060bc18a6a3a9d137f5e08c9317 | bigcode/the-stack | train |
c15a6fecfa4b26d962cb89e3 | train | function | def _relocate_spliced_links(links, orig_prefix, new_prefix):
"""Re-linking function which differs from `relocate.relocate_links` by
reading the old link rather than the new link, since the latter wasn't moved
in our case. This still needs to be called after the copy to destination
because it expects the... | def _relocate_spliced_links(links, orig_prefix, new_prefix):
| """Re-linking function which differs from `relocate.relocate_links` by
reading the old link rather than the new link, since the latter wasn't moved
in our case. This still needs to be called after the copy to destination
because it expects the new directory structure to be in place."""
for link in l... | import symlink
import spack.binary_distribution as bindist
import spack.error
import spack.hooks
import spack.paths
import spack.relocate as relocate
import spack.stage
import spack.store
def _relocate_spliced_links(links, orig_prefix, new_prefix):
| 64 | 64 | 152 | 16 | 47 | Loewe2/spack | lib/spack/spack/rewiring.py | Python | _relocate_spliced_links | _relocate_spliced_links | 23 | 33 | 23 | 23 | fd1b6e77f2d5908da40c2361b0b36454c53b47a9 | bigcode/the-stack | train |
883e570941bfd18e0a991dd4 | train | class | class PackageNotInstalledError(RewireError):
"""Raised when the build_spec for a splice was not installed."""
def __init__(self, spliced_spec, build_spec, dep):
super(PackageNotInstalledError, self).__init__(
"""Rewire of {0}
failed due to missing install of build spec {1}
... | class PackageNotInstalledError(RewireError):
| """Raised when the build_spec for a splice was not installed."""
def __init__(self, spliced_spec, build_spec, dep):
super(PackageNotInstalledError, self).__init__(
"""Rewire of {0}
failed due to missing install of build spec {1}
for spec {2}""".format(spliced_spec, bu... | ooks.post_install(spec)
class RewireError(spack.error.SpackError):
"""Raised when something goes wrong with rewiring."""
def __init__(self, message, long_msg=None):
super(RewireError, self).__init__(message, long_msg)
class PackageNotInstalledError(RewireError):
| 64 | 64 | 89 | 9 | 55 | Loewe2/spack | lib/spack/spack/rewiring.py | Python | PackageNotInstalledError | PackageNotInstalledError | 122 | 128 | 122 | 122 | 9a09052ec8bcfa3b97480ef357e045737df15c17 | bigcode/the-stack | train |
b950eb9c9c7950e6e21905af | train | function | def rewire(spliced_spec):
"""Given a spliced spec, this function conducts all the rewiring on all
nodes in the DAG of that spec."""
assert spliced_spec.spliced
for spec in spliced_spec.traverse(order='post', root=True):
if not spec.build_spec.package.installed:
# TODO: May want to ch... | def rewire(spliced_spec):
| """Given a spliced spec, this function conducts all the rewiring on all
nodes in the DAG of that spec."""
assert spliced_spec.spliced
for spec in spliced_spec.traverse(order='post', root=True):
if not spec.build_spec.package.installed:
# TODO: May want to change this at least for the... | (os.path.join(orig_prefix, link))
link_target = re.sub('^' + orig_prefix, new_prefix, link_target)
new_link_path = os.path.join(new_prefix, link)
os.unlink(new_link_path)
symlink(link_target, new_link_path)
def rewire(spliced_spec):
| 64 | 64 | 145 | 7 | 57 | Loewe2/spack | lib/spack/spack/rewiring.py | Python | rewire | rewire | 36 | 49 | 36 | 36 | 0760d79e2430b4f400bcfa4b8133612f7448f048 | bigcode/the-stack | train |
19f6eb1d747462d204615485 | train | function | def rewire_node(spec, explicit):
"""This function rewires a single node, worrying only about references to
its subgraph. Binaries, text, and links are all changed in accordance with
the splice. The resulting package is then 'installed.'"""
tempdir = tempfile.mkdtemp()
# copy anything installed to a ... | def rewire_node(spec, explicit):
| """This function rewires a single node, worrying only about references to
its subgraph. Binaries, text, and links are all changed in accordance with
the splice. The resulting package is then 'installed.'"""
tempdir = tempfile.mkdtemp()
# copy anything installed to a temporary directory
shutil.co... | _prefix, link_target)
new_link_path = os.path.join(new_prefix, link)
os.unlink(new_link_path)
symlink(link_target, new_link_path)
def rewire(spliced_spec):
"""Given a spliced spec, this function conducts all the rewiring on all
nodes in the DAG of that spec."""
assert spliced_spec.... | 188 | 188 | 627 | 8 | 180 | Loewe2/spack | lib/spack/spack/rewiring.py | Python | rewire_node | rewire_node | 52 | 113 | 52 | 52 | 1204faaef03ddc9ee1d6a4bfadd0ed1e96bfa84c | bigcode/the-stack | train |
0ce00d290021dd957771894a | train | class | class RewireError(spack.error.SpackError):
"""Raised when something goes wrong with rewiring."""
def __init__(self, message, long_msg=None):
super(RewireError, self).__init__(message, long_msg)
| class RewireError(spack.error.SpackError):
| """Raised when something goes wrong with rewiring."""
def __init__(self, message, long_msg=None):
super(RewireError, self).__init__(message, long_msg)
| spack.store.layout.spec_file_path(spec))
# add to database, not sure about explicit
spack.store.db.add(spec, spack.store.layout, explicit=explicit)
# run post install hooks
spack.hooks.post_install(spec)
class RewireError(spack.error.SpackError):
| 64 | 64 | 50 | 11 | 53 | Loewe2/spack | lib/spack/spack/rewiring.py | Python | RewireError | RewireError | 116 | 119 | 116 | 116 | 3ce5749e2fdf8ca55df64b147fbbbd4be26cb7c1 | bigcode/the-stack | train |
a54de89aa81ea1fe578e07c9 | train | function | def lazy_import():
from gooddata_afm_client.model.measure_result_header import MeasureResultHeader
globals()['MeasureResultHeader'] = MeasureResultHeader
| def lazy_import():
| from gooddata_afm_client.model.measure_result_header import MeasureResultHeader
globals()['MeasureResultHeader'] = MeasureResultHeader
| Simple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
OpenApiModel
)
from gooddata_afm_client.exceptions import ApiAttributeError
def lazy_import():
| 64 | 64 | 32 | 4 | 59 | hkad98/gooddata-python-sdk | gooddata-afm-client/gooddata_afm_client/model/measure_execution_result_header.py | Python | lazy_import | lazy_import | 33 | 35 | 33 | 33 | e14f72e3d8085c5b7e3627c189d9c9b4a2bb1b88 | bigcode/the-stack | train |
8f7e950db48856b767ff304c | train | class | class MeasureExecutionResultHeader(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (v... | class MeasureExecutionResultHeader(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | """
OpenAPI definition
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v0
Contact: support@gooddata.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sy... | 218 | 256 | 1,987 | 8 | 209 | hkad98/gooddata-python-sdk | gooddata-afm-client/gooddata_afm_client/model/measure_execution_result_header.py | Python | MeasureExecutionResultHeader | MeasureExecutionResultHeader | 38 | 276 | 38 | 38 | 063dcaf569f135782ea0437a57bd7b4ad1b8519d | bigcode/the-stack | train |
fc51672a8efd0bd1e3565597 | train | function | def setup(client) -> None:
""" Cog's setup function. """
client.add_cog(Games(client))
| def setup(client) -> None:
| """ Cog's setup function. """
client.add_cog(Games(client))
| ["emoji"] == slot2["emoji"] or slot2["emoji"] == slot3["emoji"]:
return await msg.edit(embed=be)
else:
await SlothCurrency.update_user_money(ctx.author.id, -bet)
return await msg.edit(embed=lost)
def setup(client) -> None:
| 64 | 64 | 24 | 7 | 57 | GNovaisLongue/sloth-bot | cogs/games.py | Python | setup | setup | 513 | 516 | 513 | 513 | 2742eedc45b187eaa02d63a835ad511f9d97e452 | bigcode/the-stack | train |
9ef3352ec13eb2a28cf8fa31 | train | class | class Games(*minigames_cogs):
""" A category for a minigames. """
def __init__(self, client) -> None:
""" Class init method. """
# Initiates all inherited cogs
for minigame_cog in minigames_cogs:
minigame_cog.__init__(self, client)
self.client = client
@command... | class Games(*minigames_cogs):
| """ A category for a minigames. """
def __init__(self, client) -> None:
""" Class init method. """
# Initiates all inherited cogs
for minigame_cog in minigames_cogs:
minigame_cog.__init__(self, client)
self.client = client
@commands.Cog.listener()
async def... | import discord
from discord.ext import commands
from random import randint, sample, shuffle, choice
import os
import json
from typing import List, Dict, Optional, Any, Union
import asyncio
from extra import utils
from extra.slothclasses.player import Player
from extra.minigames.connect_four import ConnectFour
from ex... | 132 | 256 | 5,052 | 9 | 123 | GNovaisLongue/sloth-bot | cogs/games.py | Python | Games | Games | 20 | 510 | 20 | 20 | f5d2fa833ef23c8baa8d3d65363ad3cc8c487959 | bigcode/the-stack | train |
05741628b3ccaa5d502e236a | train | class | class MockPerpConnector(BacktestMarket, PerpetualTrading):
def __init__(self):
BacktestMarket.__init__(self)
PerpetualTrading.__init__(self)
self._funding_payment_span = [0, 10]
def supported_position_modes(self):
return [PositionMode.ONEWAY, PositionMode.HEDGE]
| class MockPerpConnector(BacktestMarket, PerpetualTrading):
| def __init__(self):
BacktestMarket.__init__(self)
PerpetualTrading.__init__(self)
self._funding_payment_span = [0, 10]
def supported_position_modes(self):
return [PositionMode.ONEWAY, PositionMode.HEDGE]
| from hummingsim.backtest.backtest_market import BacktestMarket
from hummingbot.connector.perpetual_trading import PerpetualTrading
from hummingbot.core.event.events import PositionMode
class MockPerpConnector(BacktestMarket, PerpetualTrading):
| 54 | 64 | 75 | 15 | 38 | coreydemarse/hummingbot | test/mock/mock_perp_connector.py | Python | MockPerpConnector | MockPerpConnector | 6 | 13 | 6 | 6 | d9f01cb0c76c03e309472314f9ad8b377f3830be | bigcode/the-stack | train |
0d12451a5d42695802cd00f7 | train | function | @app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
return item_dict
| @app.post("/items/")
async def create_item(item: Item):
| item_dict = item.dict()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
return item_dict
| typing import Optional
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
| 64 | 64 | 54 | 13 | 51 | kaopanboonyuen/2110446_DataScience_2021s2 | code/week11_airflow/fastapi/post.py | Python | create_item | create_item | 17 | 23 | 17 | 18 | 502629d21cada9af9862a5a33ee3b0b895c125e5 | bigcode/the-stack | train |
a9ffa3fdf96765cfbf02de91 | train | class | class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
| class Item(BaseModel):
| name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
| # post example
import uvicorn
from fastapi import FastAPI
from typing import Optional
from pydantic import BaseModel
class Item(BaseModel):
| 33 | 64 | 34 | 5 | 27 | kaopanboonyuen/2110446_DataScience_2021s2 | code/week11_airflow/fastapi/post.py | Python | Item | Item | 9 | 13 | 9 | 9 | e2b372a6ff508532593a8ced0cbe11e1c0180ec9 | bigcode/the-stack | train |
bb2aa43cbae5eb72d69b00e7 | train | function | @app.get('/items/{item_id}')
async def read_item(item_id: int):
return { 'item_id': item_id }
| @app.get('/items/{item_id}')
async def read_item(item_id: int):
| return { 'item_id': item_id }
| create_item(item: Item):
item_dict = item.dict()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
return item_dict
@app.get('/items/{item_id}')
async def read_item(item_id: int):
| 64 | 64 | 27 | 17 | 46 | kaopanboonyuen/2110446_DataScience_2021s2 | code/week11_airflow/fastapi/post.py | Python | read_item | read_item | 25 | 27 | 25 | 26 | fa809b8d88bae6e9e6ed1118a283129d96d6c3d2 | bigcode/the-stack | train |
f2cd0ce63bc64146e337f260 | train | function | @pytest.mark.xfail # Update once ogr mocking problems are resolved
def test_copr_pr_handle(pr_event, dump_http_com):
config = dump_http_com(f"{Path(__file__).name}/pr_handle.yaml")
flexmock(jobs.SteveJobs, config=config)
# it would make sense to make LocalProject offline
flexmock(PackitAPI).should_rec... | @pytest.mark.xfail # Update once ogr mocking problems are resolved
def test_copr_pr_handle(pr_event, dump_http_com):
| config = dump_http_com(f"{Path(__file__).name}/pr_handle.yaml")
flexmock(jobs.SteveJobs, config=config)
# it would make sense to make LocalProject offline
flexmock(PackitAPI).should_receive("run_copr_build").with_args(
owner="packit",
project="packit-service-packit-342",
chroots... | "github_pr_event.json").read_text())
@pytest.fixture()
def release_event():
return json.loads((DATA_DIR / "webhooks" / "release_event.json").read_text())
@pytest.mark.xfail # Update once ogr mocking problems are resolved
def test_copr_pr_handle(pr_event, dump_http_com):
| 64 | 64 | 185 | 27 | 37 | phracek/packit-service | tests/integration/test_copr.py | Python | test_copr_pr_handle | test_copr_pr_handle | 30 | 43 | 30 | 31 | 824540c395f05df50cf09ccf14a9d7d59e708a26 | bigcode/the-stack | train |
0631d69d1e5246573249c60f | train | function | @pytest.fixture()
def release_event():
return json.loads((DATA_DIR / "webhooks" / "release_event.json").read_text())
| @pytest.fixture()
def release_event():
| return json.loads((DATA_DIR / "webhooks" / "release_event.json").read_text())
| it_service.worker.jobs import SteveJobs
from packit_service.worker.whitelist import Whitelist
from tests.spellbook import DATA_DIR
@pytest.fixture()
def pr_event():
return json.loads((DATA_DIR / "webhooks" / "github_pr_event.json").read_text())
@pytest.fixture()
def release_event():
| 64 | 64 | 28 | 7 | 57 | phracek/packit-service | tests/integration/test_copr.py | Python | release_event | release_event | 25 | 27 | 25 | 26 | e17518639e4a3441035d4f40aaa78e14aaf83ec6 | bigcode/the-stack | train |
339312785fb77208d73dfb92 | train | function | @pytest.fixture()
def pr_event():
return json.loads((DATA_DIR / "webhooks" / "github_pr_event.json").read_text())
| @pytest.fixture()
def pr_event():
| return json.loads((DATA_DIR / "webhooks" / "github_pr_event.json").read_text())
| packit_service.service.models import Model
from packit_service.worker import jobs
from packit_service.worker.handler import BuildStatusReporter
from packit_service.worker.jobs import SteveJobs
from packit_service.worker.whitelist import Whitelist
from tests.spellbook import DATA_DIR
@pytest.fixture()
def pr_event():
| 64 | 64 | 29 | 7 | 56 | phracek/packit-service | tests/integration/test_copr.py | Python | pr_event | pr_event | 20 | 22 | 20 | 21 | ceaf3f1fba1423c6ba7f34dba6c0ddd6c09e0142 | bigcode/the-stack | train |
631d273336d93f4b61fd4938 | train | function | def test_wrong_collaborator(pr_event):
packit_yaml = (
"{'specfile_path': '', 'synced_files': []"
", jobs: [{trigger: pull_request, job: copr_build, metadata: {targets:[]}}]}"
)
copr_dict = {
"login": "stevejobs",
"username": "stevejobs",
"token": "apple",
"co... | def test_wrong_collaborator(pr_event):
| packit_yaml = (
"{'specfile_path': '', 'synced_files': []"
", jobs: [{trigger: pull_request, job: copr_build, metadata: {targets:[]}}]}"
)
copr_dict = {
"login": "stevejobs",
"username": "stevejobs",
"token": "apple",
"copr_url": "https://copr.fedorainfracloud... | owner="packit",
project="packit-service-packit-342",
chroots=["fedora-29-x86_64", "fedora-rawhide-x86_64", "fedora-30-x86_64"],
).and_return("1", "asd").once()
flexmock(PackitAPI).should_receive("watch_copr_build").and_return("failed").once()
jobs.SteveJobs().process_message(pr_event)
def ... | 105 | 105 | 352 | 9 | 96 | phracek/packit-service | tests/integration/test_copr.py | Python | test_wrong_collaborator | test_wrong_collaborator | 46 | 84 | 46 | 46 | 519885920b8c61fb5c6dd25702c3c2ccc49c4f31 | bigcode/the-stack | train |
0b69953c162c933c9adc5b59 | train | class | class Projectile(object):
def __init__(self,mass,velocity):
self.mass = mass
self.velocity = velocity
| class Projectile(object):
| def __init__(self,mass,velocity):
self.mass = mass
self.velocity = velocity
| __all__ =['Projectile']
class Projectile(object):
| 12 | 64 | 26 | 4 | 8 | xiaomiwujiecao/effectivePythonNote | 50/mypackage/models.py | Python | Projectile | Projectile | 3 | 6 | 3 | 3 | 4e237274e4d4fae59f0122f40545777a09e25047 | bigcode/the-stack | train |
ad5459038ecdabc0779c0451 | train | function | def gen_encoded_password(formated_date):
encoded = keys.businessShortCode + keys.lipaNaMpesaPassKey + formated_date
encoded_string = base64.b64encode(encoded.encode())
passwrd = encoded_string.decode('utf-8')
return passwrd
| def gen_encoded_password(formated_date):
| encoded = keys.businessShortCode + keys.lipaNaMpesaPassKey + formated_date
encoded_string = base64.b64encode(encoded.encode())
passwrd = encoded_string.decode('utf-8')
return passwrd
| import requests
import keys
from datetime import datetime
import base64
def gen_formated_timestamp():
unformatted_date = datetime.now()
formated_date = unformatted_date.strftime('%Y%m%d%H%M%S')
return formated_date
def gen_encoded_password(formated_date):
| 63 | 64 | 60 | 8 | 54 | karisayaa/DarajaApiBwa | lipanampesa.py | Python | gen_encoded_password | gen_encoded_password | 14 | 18 | 14 | 14 | 0967d806433a4644370fb8793064a4e5bdeff953 | bigcode/the-stack | train |
47688b53ea80ab6c6cf5e8fe | train | function | def lipa_na_mpesa():
access_token = gen_access_token()
api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
headers = { "Authorization": "Bearer %s" % access_token }
request = {
"BusinessShortCode": keys.businessShortCode,
"Password": passwd,
"Timestamp": t... | def lipa_na_mpesa():
| access_token = gen_access_token()
api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
headers = { "Authorization": "Bearer %s" % access_token }
request = {
"BusinessShortCode": keys.businessShortCode,
"Password": passwd,
"Timestamp": time_stp,
"Tra... | ://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))
myaccess_token = r.json()['access_token']
return myaccess_token
def lipa_na_mpesa():
| 64 | 64 | 192 | 7 | 56 | karisayaa/DarajaApiBwa | lipanampesa.py | Python | lipa_na_mpesa | lipa_na_mpesa | 37 | 57 | 37 | 37 | df9e7e72e454d085a60290790f1d473cbe56b9e7 | bigcode/the-stack | train |
385d4154bab3d99869f7b65e | train | function | def gen_access_token():
consumer_key = keys.consumerKey
consumer_secret = keys.consumerSecret
api_URL = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))
myaccess_token = r.json()['acc... | def gen_access_token():
| consumer_key = keys.consumerKey
consumer_secret = keys.consumerSecret
api_URL = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))
myaccess_token = r.json()['access_token']
return my... | _string = base64.b64encode(encoded.encode())
passwrd = encoded_string.decode('utf-8')
return passwrd
time_stp = gen_formated_timestamp()
passwd = gen_encoded_password(time_stp)
import requests
from requests.auth import HTTPBasicAuth
def gen_access_token():
| 64 | 64 | 85 | 6 | 57 | karisayaa/DarajaApiBwa | lipanampesa.py | Python | gen_access_token | gen_access_token | 27 | 35 | 27 | 27 | fdbe18ddb73da4b018bdc7b651963c50a0a32c14 | bigcode/the-stack | train |
a2cd592122cd65bc280415d7 | train | function | def gen_formated_timestamp():
unformatted_date = datetime.now()
formated_date = unformatted_date.strftime('%Y%m%d%H%M%S')
return formated_date
| def gen_formated_timestamp():
| unformatted_date = datetime.now()
formated_date = unformatted_date.strftime('%Y%m%d%H%M%S')
return formated_date
| import requests
import keys
from datetime import datetime
import base64
def gen_formated_timestamp():
| 21 | 64 | 40 | 6 | 14 | karisayaa/DarajaApiBwa | lipanampesa.py | Python | gen_formated_timestamp | gen_formated_timestamp | 8 | 11 | 8 | 8 | 1f7bf085cd960eb34aef231446dd384fe8790dcd | bigcode/the-stack | train |
80404ad172fec4a542af23c4 | train | class | class Gaussian(Distribution):
"""
Gaussian distribution, for unbounded continuous actions (specification key: `gaussian`).
Args:
name (string): Distribution name
(<span style="color:#0000C0"><b>internal use</b></span>).
action_spec (specification): Action specification
... | class Gaussian(Distribution):
| """
Gaussian distribution, for unbounded continuous actions (specification key: `gaussian`).
Args:
name (string): Distribution name
(<span style="color:#0000C0"><b>internal use</b></span>).
action_spec (specification): Action specification
(<span style="color:#0000C0... | # Copyright 2018 Tensorforce Team. 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 applicable la... | 179 | 256 | 1,536 | 5 | 173 | JNC96/tensorforce | tensorforce/core/distributions/gaussian.py | Python | Gaussian | Gaussian | 25 | 174 | 25 | 25 | f22cb14b0ada04a3b008d49cdf17a706adba9060 | bigcode/the-stack | train |
5a523a243129f466e237cffd | train | class | class JSONEncoder(flask.json.JSONEncoder):
def __init__(self, *args, **kwargs):
kwargs['use_decimal'] = False
super(JSONEncoder, self).__init__(*args, **kwargs)
def _getAttrName(self, attr):
if isinstance(attr, basestring):
return attr
else:
return attr.... | class JSONEncoder(flask.json.JSONEncoder):
| def __init__(self, *args, **kwargs):
kwargs['use_decimal'] = False
super(JSONEncoder, self).__init__(*args, **kwargs)
def _getAttrName(self, attr):
if isinstance(attr, basestring):
return attr
else:
return attr.name
def default(self, obj):
if... | cg in cgs:
qry.pushDict(cg)
return qry
elif cls == 'TO':
import blm
toc = blm.getTocByFullname(dic['toc'])
toi = toc._create(objectid.ObjectId(dic['id']))
return toi
elif cls == 'DiffTOI':
import blm
toc = blm.getTocByFullname(dic['toc'])
... | 175 | 175 | 586 | 9 | 165 | jacob22/accounting | accounting/jsonserialization.py | Python | JSONEncoder | JSONEncoder | 113 | 183 | 113 | 114 | 1a888f4aa67e083d69c41d70bf57d16409bff0b3 | bigcode/the-stack | train |
16e5623aeb5807a279c9f5d5 | train | function | def objectDecode(dic):
if '_cls_' not in dic:
return dic
cls = dic['_cls_']
import blm
Query = pytransact.query
if cls in opValueKind:
kind = opValueKind[cls]
claz = getattr(Query, cls)
if kind is None:
return claz()
value = dic['value']
... | def objectDecode(dic):
| if '_cls_' not in dic:
return dic
cls = dic['_cls_']
import blm
Query = pytransact.query
if cls in opValueKind:
kind = opValueKind[cls]
claz = getattr(Query, cls)
if kind is None:
return claz()
value = dic['value']
if kind == 'between':
... | ': 'single',
'Between': 'between'
# map stuff: 'HasKey', 'LacksKey', 'NotIlikeMap', 'InMap',
# 'LikeMap', 'NotLikeMap', 'IlikeMap', 'NoneOfMap'
# 'Readable'
}
class JSONDecoder(flask.json.JSONDecoder):
def __init__(self, **kw):
kw['object_hook'] = objectDecode
... | 111 | 111 | 373 | 5 | 106 | jacob22/accounting | accounting/jsonserialization.py | Python | objectDecode | objectDecode | 56 | 110 | 56 | 56 | 98bf0088bfc5857d435b35bf3a2ca551704d3ebf | bigcode/the-stack | train |
0eb5b845a66eb5b57189c272 | train | class | class JSONDecoder(flask.json.JSONDecoder):
def __init__(self, **kw):
kw['object_hook'] = objectDecode
super(JSONDecoder, self).__init__(**kw)
| class JSONDecoder(flask.json.JSONDecoder):
| def __init__(self, **kw):
kw['object_hook'] = objectDecode
super(JSONDecoder, self).__init__(**kw)
| '
# map stuff: 'HasKey', 'LacksKey', 'NotIlikeMap', 'InMap',
# 'LikeMap', 'NotLikeMap', 'IlikeMap', 'NoneOfMap'
# 'Readable'
}
class JSONDecoder(flask.json.JSONDecoder):
| 64 | 64 | 41 | 9 | 55 | jacob22/accounting | accounting/jsonserialization.py | Python | JSONDecoder | JSONDecoder | 49 | 53 | 49 | 50 | 5a0ce7173772adbfc389b039063724f19632822c | bigcode/the-stack | train |
b2e11ea48f30ade884304d1a | train | function | def get_save_folder(hyps):
"""
Creates the save name for the model.
hyps: dict
keys:
main_path: str
the leading path to the save_folder
exp_name: str
the root experiment name
exp_num: int
the experiment id number
... | def get_save_folder(hyps):
| """
Creates the save name for the model.
hyps: dict
keys:
main_path: str
the leading path to the save_folder
exp_name: str
the root experiment name
exp_num: int
the experiment id number
search_keys: str
... | t[0]
if name == exp_name and num is not None:
exp_nums.add(num)
for i in range(len(exp_nums)):
if i+offset not in exp_nums:
return i+offset
return len(exp_nums) + offset
def get_save_folder(hyps):
| 64 | 64 | 130 | 8 | 55 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | get_save_folder | get_save_folder | 114 | 133 | 114 | 114 | 92d02fc638ef07214954b42978fc794f806945e5 | bigcode/the-stack | train |
0a0dc7223e044de85a6581b1 | train | function | def make_hyper_range(low, high, range_len, method="log"):
"""
Creates a list of length range_len that is a range between two
values. The method dictates the spacing between the values.
low: float
the lowest value in the range
"""
if method.lower() == "random":
param_vals = np.r... | def make_hyper_range(low, high, range_len, method="log"):
| """
Creates a list of length range_len that is a range between two
values. The method dictates the spacing between the values.
low: float
the lowest value in the range
"""
if method.lower() == "random":
param_vals = np.random.random(low, high+1e-5, size=range_len)
elif meth... | 1)
else:
for param in hyp_ranges[key]:
hyps[key] = param
hyper_q = fill_hyper_q(hyps, hyp_ranges, keys, hyper_q,
idx+1)
return hyper_q
def make_hyper_range(low, high, range_len, method="log"):
| 67 | 67 | 225 | 16 | 50 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | make_hyper_range | make_hyper_range | 220 | 241 | 220 | 220 | 9334d6fe4aa716602ae1a08c686614f7870b9ab7 | bigcode/the-stack | train |
ea2816a6fafadb3913e5772a | train | function | def get_exp_num(exp_folder, exp_name, offset=0):
"""
Finds the next open experiment id number by searching through the
existing experiment numbers in the folder.
If an offset is argued, it is impossible to have an exp_num that is
less than the value of the offset. The returned exp_num will be
t... | def get_exp_num(exp_folder, exp_name, offset=0):
| """
Finds the next open experiment id number by searching through the
existing experiment numbers in the folder.
If an offset is argued, it is impossible to have an exp_num that is
less than the value of the offset. The returned exp_num will be
the next available experiment number starting with... | not in ignore_keys:
hyps[k] = v
hyps['seed'] += 1 # For fresh data
s = " Restarted training from epoch "+str(checkpt['epoch'])
hyps['description'] = utils.try_key(hyps,
"description",
... | 112 | 112 | 374 | 14 | 97 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | get_exp_num | get_exp_num | 64 | 112 | 64 | 64 | 502443f2200fe040dcbb6798e7c4ac3fc93f384b | bigcode/the-stack | train |
e6c2e3c6a5d28071d594c16d | train | function | def hyper_search(hyps, hyp_ranges, train_fxn):
"""
The top level function to create hyperparameter combinations and
perform trainings.
hyps: dict
the initial hyperparameter dict
keys: str
vals: values for the hyperparameters specified by the keys
hyp_ranges: dict
the... | def hyper_search(hyps, hyp_ranges, train_fxn):
| """
The top level function to create hyperparameter combinations and
perform trainings.
hyps: dict
the initial hyperparameter dict
keys: str
vals: values for the hyperparameters specified by the keys
hyp_ranges: dict
these are the ranges that will change the hyperpar... | "):
"""
Creates a list of length range_len that is a range between two
values. The method dictates the spacing between the values.
low: float
the lowest value in the range
"""
if method.lower() == "random":
param_vals = np.random.random(low, high+1e-5, size=range_len)
elif ... | 224 | 224 | 749 | 14 | 209 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | hyper_search | hyper_search | 243 | 321 | 243 | 243 | 83a608df7acae98188075f1665dc1d69f95f87d7 | bigcode/the-stack | train |
09f1dba0e548b4f13efd618d | train | function | def run_training(train_fxn):
"""
This function extracts the hyperparams and hyperranges from the
command line arguments and asks the user if they would like to
proceed with the training and/or overwrite the previous save
folder.
train_fxn: function
this the training function that will c... | def run_training(train_fxn):
| """
This function extracts the hyperparams and hyperranges from the
command line arguments and asks the user if they would like to
proceed with the training and/or overwrite the previous save
folder.
train_fxn: function
this the training function that will carry out the training
... | ']\n'
f.write(s)
f.write('\n')
hyper_q = Queue()
hyper_q = fill_hyper_q(hyps, hyp_ranges, list(hyp_ranges.keys()),
hyper_q, idx=0)
total_searches = hyper_q.qsize()
print("n_searches:", total_searches)
result_count = 0
pr... | 189 | 189 | 632 | 7 | 182 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | run_training | run_training | 323 | 387 | 323 | 323 | a204072490aee8b603cb6692ebaab003807f2b5b | bigcode/the-stack | train |
879c17783b170a1d016642c2 | train | function | def get_resume_checkpt(hyps, verbose=True):
"""
This function cleans up the code to resume from a particular
checkpoint or folder.
Be careful, this does change the hyps dict in place!!!!
hyps: dict
dictionary of hyperparameters
keys: str
"resume_folder": str
... | def get_resume_checkpt(hyps, verbose=True):
| """
This function cleans up the code to resume from a particular
checkpoint or folder.
Be careful, this does change the hyps dict in place!!!!
hyps: dict
dictionary of hyperparameters
keys: str
"resume_folder": str
must be a key present in hyps for ... | .nn.functional as F
from torch.optim.lr_scheduler import ReduceLROnPlateau,StepLR,MultiStepLR
import time
from tqdm import tqdm
import math
from queue import Queue
from collections import deque
import psutil
import json
import supervised_gym.utils.save_io as io
import supervised_gym.utils.utils as utils
import select
i... | 106 | 106 | 356 | 12 | 93 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | get_resume_checkpt | get_resume_checkpt | 24 | 62 | 24 | 24 | 3743ddcf83dcdf90d3ad77e17ea772ddcca6fcaa | bigcode/the-stack | train |
5449b6fd25b33742fac176c4 | train | function | def fill_hyper_q(hyps, hyp_ranges, keys, hyper_q, idx=0):
"""
Recursive function to load each of the hyperparameter combinations
onto a queue.
hyps - dict of hyperparameters created by a HyperParameters object
type: dict
keys: name of hyperparameter
values: value of hyperparamet... | def fill_hyper_q(hyps, hyp_ranges, keys, hyper_q, idx=0):
| """
Recursive function to load each of the hyperparameter combinations
onto a queue.
hyps - dict of hyperparameters created by a HyperParameters object
type: dict
keys: name of hyperparameter
values: value of hyperparameter
hyp_ranges - dict of lists
these are the ra... | n"+str(model)+'\n')
for k in sorted(hyps.keys()):
f.write(str(k) + ": " + str(hyps[k]) + "\n")
temp_hyps = dict()
keys = list(hyps.keys())
temp_hyps = {k:v for k,v in hyps.items()}
for k in keys:
if type(hyps[k]) == type(np.array([])):
del temp_hyps[k]
with op... | 148 | 148 | 496 | 21 | 127 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | fill_hyper_q | fill_hyper_q | 166 | 218 | 166 | 166 | 677cf00d4b9960671b79fe95f5e6932d728625a4 | bigcode/the-stack | train |
b6dbb8bec7b600cef0820971 | train | function | def record_session(hyps, model):
"""
Writes important parameters to file. If 'resume_folder' is an entry
in the hyps dict, then the txt file is appended to instead of being
overwritten.
hyps: dict
dict of relevant hyperparameters
model: torch nn.Module
the model to be trained
... | def record_session(hyps, model):
| """
Writes important parameters to file. If 'resume_folder' is an entry
in the hyps dict, then the txt file is appended to instead of being
overwritten.
hyps: dict
dict of relevant hyperparameters
model: torch nn.Module
the model to be trained
"""
sf = hyps['save_folder'... | the root experiment name
exp_num: int
the experiment id number
search_keys: str
the identifying keys for this hyperparameter search
"""
save_folder = "{}/{}_{}".format(hyps['main_path'],
hyps['exp_name'],
... | 89 | 89 | 298 | 9 | 79 | grantsrb/supervised_gym | supervised_gym/utils/training.py | Python | record_session | record_session | 135 | 164 | 135 | 135 | 8359b28c0ca1fd6a45f913e5610505be156f3cdc | bigcode/the-stack | train |
075733593189e1a5cc1eec4d | train | class | class HindsightReplayBuffer(SimpleReplayBuffer):
def __init__(self,
max_replay_buffer_size,
env,
random_seed=1995,
relabel_type='future',
her_ratio=0.8,
observation_key="observation",
desired_goal_key="desired_goal",
achieved_goal_key="achieved_goal"):
"""
:para... | class HindsightReplayBuffer(SimpleReplayBuffer):
| def __init__(self,
max_replay_buffer_size,
env,
random_seed=1995,
relabel_type='future',
her_ratio=0.8,
observation_key="observation",
desired_goal_key="desired_goal",
achieved_goal_key="achieved_goal"):
"""
:param max_replay_buffer_size:
:param env:
... | from inspect import Attribute
import numpy as np
from rlkit.data_management.simple_replay_buffer import (
SimpleReplayBuffer
)
from rlkit.data_management.env_replay_buffer import get_dim
from rlkit.envs.goal_env_utils import compute_reward, compute_distance
from gym.spaces import Box, Discrete, Tuple, Dict
import ... | 84 | 256 | 1,333 | 9 | 74 | Ericonaldo/ILSwiss | rlkit/data_management/relabel_replay_buffer.py | Python | HindsightReplayBuffer | HindsightReplayBuffer | 13 | 140 | 13 | 13 | dd7865f69fe3215672435951f8221e3662783466 | bigcode/the-stack | train |
69549942c791f144bfb345c1 | train | function | def analyze_o2_level(value):
print("{} - Analyze Oxygen Level".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = None
if value >= 95:
response = {
"message": "NORMAL"
}
else:
response = {
"message": "Your blood oxyg... | def analyze_o2_level(value):
| print("{} - Analyze Oxygen Level".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = None
if value >= 95:
response = {
"message": "NORMAL"
}
else:
response = {
"message": "Your blood oxygen level is not normal"
... | > 123:
response = {
"message": "Your heart Rate is not normal"
}
else:
response = {
"message": "NORMAL"
}
print("{} - Heart Rate: {}".format(LOGPREFIX, response))
return response
def analyze_o2_level(value):
| 64 | 64 | 98 | 7 | 56 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_o2_level | analyze_o2_level | 403 | 419 | 403 | 403 | 3ab5c20c8756e80cf80de67b99b2c232f73ab3ca | bigcode/the-stack | train |
15e8da3964d594153e64dc5c | train | function | def analyze_respiratory_rate(value):
print("{} - Analyze Respiratory Rate".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = None
if value >= 12 and value <= 20:
response = {
"message": "NORMAL"
}
else:
response = {
... | def analyze_respiratory_rate(value):
| print("{} - Analyze Respiratory Rate".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = None
if value >= 12 and value <= 20:
response = {
"message": "NORMAL"
}
else:
response = {
"message": "Your respiratory rat... | 95:
response = {
"message": "NORMAL"
}
else:
response = {
"message": "Your blood oxygen level is not normal"
}
print("{} - Oxygen: {}".format(LOGPREFIX, response))
return response
def analyze_respiratory_rate(value):
| 64 | 64 | 106 | 8 | 55 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_respiratory_rate | analyze_respiratory_rate | 421 | 437 | 421 | 421 | e3b399b5b704b259f8ef10c88abbdc9229a83046 | bigcode/the-stack | train |
ddfeaa4b7b326af853e15cd6 | train | function | def get_age(userId):
print("{} - Get Age".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, userId))
age = 0
mssql_url = get_parameter_value('serverless-mssql-url')
engine = create_engine(mssql_url)
with Session(engine) as session:
query= """
SE... | def get_age(userId):
| print("{} - Get Age".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, userId))
age = 0
mssql_url = get_parameter_value('serverless-mssql-url')
engine = create_engine(mssql_url)
with Session(engine) as session:
query= """
SELECT DATEDIFF(YEAR,BI... | <= 20:
response = {
"message": "NORMAL"
}
else:
response = {
"message": "Your respiratory rate is not normal"
}
print("{} - Respiratory Rate: {}".format(LOGPREFIX, response))
return response
def get_age(userId):
| 64 | 64 | 163 | 6 | 57 | jfdaniel77/myHealth-consultation | recommendation.py | Python | get_age | get_age | 439 | 462 | 439 | 439 | 09eef1634840823d9f75baa0cb6526f3d0792a3f | bigcode/the-stack | train |
71f65cf3fcf8e15fc61822ea | train | function | def get_recommendation_graphdb(list_medical):
print("{} - Get Recommendation from GraphDB".format(LOGPREFIX))
list_recommendation = []
query = """
MATCH (disease:Disease {disease: 'XXX'})-->(precaution) RETURN precaution as text
"""
# Set connection
url = get_p... | def get_recommendation_graphdb(list_medical):
| print("{} - Get Recommendation from GraphDB".format(LOGPREFIX))
list_recommendation = []
query = """
MATCH (disease:Disease {disease: 'XXX'})-->(precaution) RETURN precaution as text
"""
# Set connection
url = get_parameter_value("serverless-graphdb-url")
u... | ("ssm")
value = ssm_client.get_parameter(Name=key, WithDecryption=True)
# print("{} - key: {} - value: {}".format(LOGPREFIX, key, value.get("Parameter").get("Value")))
return value.get("Parameter").get("Value")
def get_recommendation_graphdb(list_medical):
| 70 | 71 | 238 | 11 | 59 | jfdaniel77/myHealth-consultation | recommendation.py | Python | get_recommendation_graphdb | get_recommendation_graphdb | 530 | 561 | 530 | 530 | 8f17905f1063003cd7e9562d4ebf059e25684683 | bigcode/the-stack | train |
fd39982127f585040cd20732 | train | function | def analyze_heart_rate(value, patientId):
print("{} - Analyze Heart Rate".format(LOGPREFIX))
print("{} - Payload: patientId: {} and value: {}".format(LOGPREFIX, patientId, value))
response = None
# Get Age
age = get_age(patientId)
# Ref: https://my.clevelandclinic.org/health/diagnosti... | def analyze_heart_rate(value, patientId):
| print("{} - Analyze Heart Rate".format(LOGPREFIX))
print("{} - Payload: patientId: {} and value: {}".format(LOGPREFIX, patientId, value))
response = None
# Get Age
age = get_age(patientId)
# Ref: https://my.clevelandclinic.org/health/diagnostics/17402-pulse--heart-rate
if age < 25... | analyze_blood_pressure(value):
print("{} - Analyze Blood Pressure".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = None
temp = value.split("/")
sys = int(temp[0])
dias = int(temp[1])
if sys <= 120 and dias <= 80:
response = {
"m... | 207 | 207 | 692 | 10 | 196 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_heart_rate | analyze_heart_rate | 290 | 401 | 290 | 290 | 0a6e25cd0946bcd8679c96a5cfbc40548805fd4a | bigcode/the-stack | train |
65732d5f3f4a698d0485ff77 | train | function | def analyze_bmi(height, weight):
print("{} - Analyze BMI".format(LOGPREFIX))
print("{} - Payload: height: {} and weight: {}".format(LOGPREFIX, height, weight))
bmi_response = None
bmi = weight/((height/100)*(height/100))
if bmi < 18.5 and bmi > 25:
if bmi <= 18.5:
... | def analyze_bmi(height, weight):
| print("{} - Analyze BMI".format(LOGPREFIX))
print("{} - Payload: height: {} and weight: {}".format(LOGPREFIX, height, weight))
bmi_response = None
bmi = weight/((height/100)*(height/100))
if bmi < 18.5 and bmi > 25:
if bmi <= 18.5:
bmi_response = {
... | value))
response = {}
if value > 37.5:
response = {
"message": "You have fever"
}
else:
response = {
"message": "NORMAL"
}
print("{} - Fever: {}".format(LOGPREFIX, response))
return response
def analyze_bmi(height, weight):
| 75 | 75 | 250 | 8 | 66 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_bmi | analyze_bmi | 225 | 259 | 225 | 225 | 484a438c8e7912161c27139718d87e8c6675008c | bigcode/the-stack | train |
a1b86e1fa9bc75e1a2e559c0 | train | function | def analyze_body_temperature(value):
print("{} - Analyze body temperature".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = {}
if value > 37.5:
response = {
"message": "You have fever"
}
else:
response = {
"mes... | def analyze_body_temperature(value):
| print("{} - Analyze body temperature".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = {}
if value > 37.5:
response = {
"message": "You have fever"
}
else:
response = {
"message": "NORMAL"
}
pr... | "PATIENT_ID": patient_id,
"MESSAGE_T": rr_resp["message"],
"MSG_TP_T": "VITAL_SIGN"
}
list_payload.append(payload_db)
# Store to MSSQL
insert_records(list_payload)
# Common functions
def analyze_body_temperature(value):
| 64 | 64 | 96 | 6 | 57 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_body_temperature | analyze_body_temperature | 207 | 223 | 207 | 207 | c4dcdfa4a60276db440078e8c6899c9271f17669 | bigcode/the-stack | train |
0a54f86b0052750823545b62 | train | function | def insert_records(records):
print("{} - Insert Records to MSSQL".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, records))
mssql_url = get_parameter_value('serverless-mssql-url')
engine = create_engine(mssql_url)
with Session(engine) as session:
try:
for item... | def insert_records(records):
| print("{} - Insert Records to MSSQL".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, records))
mssql_url = get_parameter_value('serverless-mssql-url')
engine = create_engine(mssql_url)
with Session(engine) as session:
try:
for item in records:
... | = {
"MSG_TP_T": q.MSG_TP_T.strip(),
"MESSAGE_T": msg
}
list_recommendation.append(data)
print("{} - List Recommendation: {}".format(LOGPREFIX, list_recommendation))
return list_recommendation
def insert_records(records):
| 64 | 64 | 187 | 5 | 58 | jfdaniel77/myHealth-consultation | recommendation.py | Python | insert_records | insert_records | 501 | 521 | 501 | 501 | 788544847746cf0e83d24d3423d7dddd5294b5eb | bigcode/the-stack | train |
895f99314f0a806064a04a83 | train | class | class RECOMMENDATION(Base):
__tablename__ = "RECOMMENDATION"
ID = Column("ID", Integer, primary_key=True, autoincrement=False)
PATIENT_ID = Column("PATIENT_ID", String)
MESSAGE_T = Column("MESSAGE_T", String)
MSG_TP_T = Column("MSG_TP_T", String)
CREATED_DT = Column("CREATED_DT", DateTime)
| class RECOMMENDATION(Base):
| __tablename__ = "RECOMMENDATION"
ID = Column("ID", Integer, primary_key=True, autoincrement=False)
PATIENT_ID = Column("PATIENT_ID", String)
MESSAGE_T = Column("MESSAGE_T", String)
MSG_TP_T = Column("MSG_TP_T", String)
CREATED_DT = Column("CREATED_DT", DateTime)
| for item in resp:
for key in item.keys():
list_recommendation.append(item.get(key))
session.close()
driver.close()
print("{} - Recommendation: {}".format(LOGPREFIX, list_recommendation))
return list_recommendation
class RECOMMENDATION(Base):
| 64 | 64 | 89 | 7 | 56 | jfdaniel77/myHealth-consultation | recommendation.py | Python | RECOMMENDATION | RECOMMENDATION | 563 | 570 | 563 | 563 | ae6104b64402ae8d94f208a8a159bba199b75d72 | bigcode/the-stack | train |
1020f9117a568c1dad584e7f | train | function | def analyze_blood_pressure(value):
print("{} - Analyze Blood Pressure".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = None
temp = value.split("/")
sys = int(temp[0])
dias = int(temp[1])
if sys <= 120 and dias <= 80:
response = {
... | def analyze_blood_pressure(value):
| print("{} - Analyze Blood Pressure".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = None
temp = value.split("/")
sys = int(temp[0])
dias = int(temp[1])
if sys <= 120 and dias <= 80:
response = {
"message": "NORMAL"
}
... | {} which means you are obese.'.format(bmi)
}
else:
bmi_response = {
"bmi": bmi,
"message": 'NORMAL'
}
print("{} - BMI: {}".format(LOGPREFIX, bmi_response))
return bmi_response
def analyze_blood_pressure(value):
| 64 | 64 | 198 | 7 | 56 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_blood_pressure | analyze_blood_pressure | 261 | 288 | 261 | 261 | 1325084da148747a5ea8ebc709578160fe10549e | bigcode/the-stack | train |
a33b4560f523b2cf32fcaa36 | train | function | def analyze_medical_problem(event, context):
print("{} - Analyze Medical Problem".format(LOGPREFIX))
# Get value from SQS
print("{} - Number of records = {}".format(LOGPREFIX, len(event.get("Records"))))
list_payload = []
if len(event.get("Records")) > 0:
for record in event.get("R... | def analyze_medical_problem(event, context):
| print("{} - Analyze Medical Problem".format(LOGPREFIX))
# Get value from SQS
print("{} - Number of records = {}".format(LOGPREFIX, len(event.get("Records"))))
list_payload = []
if len(event.get("Records")) > 0:
for record in event.get("Records"):
input_para... | ").get("patientId"):
patient_id = event.get("pathParameters").get("patientId")
else:
response_payload = {
"message": "Missing Patient ID"
}
return {"statusCode": 400, "body": dumps(response_payload), "headers": {"Content-Type": "application/json", "Access-Control-Allow-Or... | 175 | 176 | 587 | 9 | 165 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_medical_problem | analyze_medical_problem | 47 | 112 | 47 | 47 | 5f1d2027de2cb4b53c1f2752d129b8cae52053a8 | bigcode/the-stack | train |
86169503ee9370b410b16fa2 | train | function | def get_recommendation_record(userId):
print("{} - Get Recommendation from MSSQL".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, userId))
list_recommendation = []
temp_list = []
mssql_url = get_parameter_value('serverless-mssql-url')
engine = create_engine(mssql_url)
... | def get_recommendation_record(userId):
| print("{} - Get Recommendation from MSSQL".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, userId))
list_recommendation = []
temp_list = []
mssql_url = get_parameter_value('serverless-mssql-url')
engine = create_engine(mssql_url)
with Session(engine) as session:
... | ' AND USER_ID = :USER_ID
"""
qs = session.execute(query, {
"USER_ID": userId
})
for q in qs:
age = q.AGE
print("{} - Age: {}".format(LOGPREFIX, age))
return age
def get_recommendation_record(userId):
| 70 | 70 | 235 | 9 | 60 | jfdaniel77/myHealth-consultation | recommendation.py | Python | get_recommendation_record | get_recommendation_record | 464 | 499 | 464 | 464 | 9ee6a4be9dda562b65cc111e2fe7783dc88da46b | bigcode/the-stack | train |
508e19e1790684f363475308 | train | function | def get_parameter_value(key):
print("{} - Get Parameter key: {}".format(LOGPREFIX, key))
ssm_client = boto3.client("ssm")
value = ssm_client.get_parameter(Name=key, WithDecryption=True)
# print("{} - key: {} - value: {}".format(LOGPREFIX, key, value.get("Parameter").get("Value")))
return value.get("... | def get_parameter_value(key):
| print("{} - Get Parameter key: {}".format(LOGPREFIX, key))
ssm_client = boto3.client("ssm")
value = ssm_client.get_parameter(Name=key, WithDecryption=True)
# print("{} - key: {} - value: {}".format(LOGPREFIX, key, value.get("Parameter").get("Value")))
return value.get("Parameter").get("Value")
| row = mapping_RECOMMENDATION(item)
session.add(row)
session.commit()
except Exception as e:
print("{} - Exception: {}".format(LOGPREFIX, str(e)))
session.rollback()
print("{} - Insert Records to MSSQL ends.".format(LOGPREFIX))
def get_parameter_value... | 64 | 64 | 88 | 6 | 58 | jfdaniel77/myHealth-consultation | recommendation.py | Python | get_parameter_value | get_parameter_value | 523 | 528 | 523 | 523 | 611d2c270f1b0c0cfbef0ecfb722cf3dbd40dc55 | bigcode/the-stack | train |
b23740637e07d693b5cda64d | train | function | def mapping_RECOMMENDATION(data):
currentDateTime = datetime.now()
return RECOMMENDATION(
ID=data.get("ID"),
PATIENT_ID=data.get("PATIENT_ID"),
MESSAGE_T=data.get("MESSAGE_T"),
MSG_TP_T=data.get("MSG_TP_T"),
CREATED_DT=currentDateTime
) | def mapping_RECOMMENDATION(data):
| currentDateTime = datetime.now()
return RECOMMENDATION(
ID=data.get("ID"),
PATIENT_ID=data.get("PATIENT_ID"),
MESSAGE_T=data.get("MESSAGE_T"),
MSG_TP_T=data.get("MSG_TP_T"),
CREATED_DT=currentDateTime
) | crement=False)
PATIENT_ID = Column("PATIENT_ID", String)
MESSAGE_T = Column("MESSAGE_T", String)
MSG_TP_T = Column("MSG_TP_T", String)
CREATED_DT = Column("CREATED_DT", DateTime)
def mapping_RECOMMENDATION(data):
| 63 | 64 | 73 | 8 | 55 | jfdaniel77/myHealth-consultation | recommendation.py | Python | mapping_RECOMMENDATION | mapping_RECOMMENDATION | 572 | 581 | 572 | 572 | a462e2abc177b18cbb5abd33a1a6e5d48f3a5e6e | bigcode/the-stack | train |
dd0833d071e644972c70c67e | train | function | def get_recommendation(event, context):
print("{} - Get Recommendation".format(LOGPREFIX))
list_recommendation = []
# Get Input Parameter
patient_id = None
if event.get("pathParameters") and event.get("pathParameters").get("patientId"):
patient_id = event.get("pathParameters").get(... | def get_recommendation(event, context):
| print("{} - Get Recommendation".format(LOGPREFIX))
list_recommendation = []
# Get Input Parameter
patient_id = None
if event.get("pathParameters") and event.get("pathParameters").get("patientId"):
patient_id = event.get("pathParameters").get("patientId")
else:
response_... | datetime import datetime, date, timedelta
from random import randrange, randint, uniform
from neo4j import GraphDatabase
# Constants
LOGPREFIX = "myHealth"
NUMBER_RECOMMENDATION = 10
# declarative base class
Base = declarative_base()
def get_recommendation(event, context):
| 66 | 66 | 221 | 9 | 57 | jfdaniel77/myHealth-consultation | recommendation.py | Python | get_recommendation | get_recommendation | 25 | 45 | 25 | 25 | 256766d8f66ecd5a56b47f443c682444f3c21fa1 | bigcode/the-stack | train |
f4ced692fc22cb1227c7aad9 | train | function | def analyze_vital_sign(event, context):
print("{} - Analyze Vital Sign".format(LOGPREFIX))
# Get value from SQS
print("{} - Number of records = {}".format(LOGPREFIX, len(event.get("Records"))))
list_payload = []
if len(event.get("Records")) > 0:
for record in event.get("Records"):
... | def analyze_vital_sign(event, context):
| print("{} - Analyze Vital Sign".format(LOGPREFIX))
# Get value from SQS
print("{} - Number of records = {}".format(LOGPREFIX, len(event.get("Records"))))
list_payload = []
if len(event.get("Records")) > 0:
for record in event.get("Records"):
input_parameter... | list_category:
# if entity.get("Text") not in list_medical_condition:
# list_medical_condition.append(entity.get("Text"))
# print("{} - Condition: {}".format(LOGPREFIX, list_medical_condition))
# # Get recommendat... | 204 | 205 | 684 | 9 | 195 | jfdaniel77/myHealth-consultation | recommendation.py | Python | analyze_vital_sign | analyze_vital_sign | 114 | 204 | 114 | 114 | c86d2b691786596f9034bad782dab6c55eb75f64 | bigcode/the-stack | train |
ff7efad2b3cb4eed532ad511 | train | function | def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
| def install(package):
| subprocess.check_call([sys.executable, "-m", "pip", "install", package])
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from packaging.version import parse as parse_version
from packaging.utils import canonicalize_version
import requests
import subprocess
import sys
def install(package):
| 44 | 64 | 24 | 4 | 39 | paulsaxe/seamm_dashboard | devtools/scripts/install_chromedriver.py | Python | install | install | 11 | 12 | 11 | 11 | ce23b19210184394c01f77e7a3cf9d59200365ef | bigcode/the-stack | train |
a514fd405ed9837d53c2e353 | train | function | def chrome_version():
"""Return the version of Chrome installed."""
if sys.platform == "linux" or sys.platform == "linux2":
# linux
exe = "google-chrome"
elif sys.platform == "darwin":
# OS X
exe = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
elif sys.pl... | def chrome_version():
| """Return the version of Chrome installed."""
if sys.platform == "linux" or sys.platform == "linux2":
# linux
exe = "google-chrome"
elif sys.platform == "darwin":
# OS X
exe = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
elif sys.platform == "win32":
... | python
# -*- coding: utf-8 -*-
from packaging.version import parse as parse_version
from packaging.utils import canonicalize_version
import requests
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
def chrome_version():
| 64 | 64 | 152 | 4 | 60 | paulsaxe/seamm_dashboard | devtools/scripts/install_chromedriver.py | Python | chrome_version | chrome_version | 15 | 32 | 15 | 15 | 8138513a6cc769d00dbef184c6d9196066afc6dc | bigcode/the-stack | train |
a04751ac0bf3468ad782b234 | train | class | class Hardware:
@staticmethod
def get_bios()->Dict:
"""
Returns Bios version
"""
value = subprocess.getoutput("wmic bios get smbiosbiosversion")
response = {
"name" : value.split()[0],
"version": value.split()[1]
}
return response... | class Hardware:
@staticmethod
| def get_bios()->Dict:
"""
Returns Bios version
"""
value = subprocess.getoutput("wmic bios get smbiosbiosversion")
response = {
"name" : value.split()[0],
"version": value.split()[1]
}
return response
@staticmethod
def g... | from typing import Dict, Tuple, Sequence, List, NoReturn
import subprocess
import json
class Hardware:
@staticmethod
| 27 | 256 | 875 | 7 | 19 | adolabsnet/sarenka | sarenka/backend/api_searcher/windows/hardware.py | Python | Hardware | Hardware | 5 | 125 | 5 | 6 | 5da2fac9f0ee8c851a783561d4b8418adbf6193a | bigcode/the-stack | train |
01023ab5454eeb0815389fcf | train | function | def directories(path):
for directory in path.split('/'):
if directory != ROOT_DIR:
yield directory
| def directories(path):
| for directory in path.split('/'):
if directory != ROOT_DIR:
yield directory
| URES solution. It uses a tree to
simulate the process described in the problem statement and runs in time
linear of the number of bytes in the input file, which is asymptotically
optimal.
"""
from collections import defaultdict
ROOT_DIR = ''
def tree(): return defaultdict(tree)
def directories(path):
| 64 | 64 | 23 | 4 | 60 | py-in-the-sky/challenges | google-code-jam/file_fixit.py | Python | directories | directories | 20 | 23 | 20 | 20 | 54f76afac5fe449b8c0624d0143d690900e987b4 | bigcode/the-stack | train |
d8413f982556cf747cc96c23 | train | function | def tree(): return defaultdict(tree)
| def tree(): | return defaultdict(tree)
| This solution is a simple DATA STRUCTURES solution. It uses a tree to
simulate the process described in the problem statement and runs in time
linear of the number of bytes in the input file, which is asymptotically
optimal.
"""
from collections import defaultdict
ROOT_DIR = ''
def tree(): | 63 | 64 | 7 | 4 | 59 | py-in-the-sky/challenges | google-code-jam/file_fixit.py | Python | tree | tree | 17 | 17 | 17 | 17 | f647854f8b05dcfc9aa0348e0c02891b1e56ec2b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.