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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4117015545d065b5279976c9 | train | class | class FileLink(object):
"""Class for embedding a local file link in an IPython session, based on path
e.g. to embed a link that was generated in the IPython notebook as my/data.txt
you would do::
local_file = FileLink("my/data.txt")
display(local_file)
or in the HTML notebook, just::... | class FileLink(object):
| """Class for embedding a local file link in an IPython session, based on path
e.g. to embed a link that was generated in the IPython notebook as my/data.txt
you would do::
local_file = FileLink("my/data.txt")
display(local_file)
or in the HTML notebook, just::
FileLink("my/d... | the document
Use the view_mode params to specify display type one off scroll | slideshow | book
e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
"""
def __init__(self, id, width=400, heigh... | 137 | 137 | 459 | 5 | 132 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | FileLink | FileLink | 346 | 410 | 346 | 346 | dfa339433cb4628792c027ed46413ceee3d591bb | bigcode/the-stack | train |
895c9b599f7c9401a7ceba5e | train | class | class ScribdDocument(IFrame):
"""
Class for embedding a Scribd document in an IPython session
Use the start_page params to specify a starting point in the document
Use the view_mode params to specify display type one off scroll | slideshow | book
e.g to Display Wes' foundational paper about PANDAS... | class ScribdDocument(IFrame):
| """
Class for embedding a Scribd document in an IPython session
Use the start_page params to specify a starting point in the document
Use the view_mode params to specify display type one off scroll | slideshow | book
e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
... | """
def __init__(self, id, width=400, height=300, **kwargs):
src="https://player.vimeo.com/video/{0}".format(id)
super(VimeoVideo, self).__init__(src, width, height, **kwargs)
class ScribdDocument(IFrame):
| 64 | 64 | 167 | 7 | 57 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | ScribdDocument | ScribdDocument | 330 | 344 | 330 | 330 | 1be14ce305b250826b01cb83a874ea8156039926 | bigcode/the-stack | train |
df9ec848bf9298802cca7190 | train | class | class YouTubeVideo(IFrame):
"""Class for embedding a YouTube Video in an IPython session, based on its video id.
e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
do::
vid = YouTubeVideo("foo")
display(vid)
To start from 30 seconds::
vid = YouTubeVi... | class YouTubeVideo(IFrame):
| """Class for embedding a YouTube Video in an IPython session, based on its video id.
e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
do::
vid = YouTubeVideo("foo")
display(vid)
To start from 30 seconds::
vid = YouTubeVideo("abc", start=30)
... | _repr_html_(self):
"""return the embed iframe"""
if self.params:
try:
from urllib.parse import urlencode # Py 3
except ImportError:
from urllib import urlencode
params = "?" + urlencode(self.params)
else:
params = "... | 91 | 91 | 305 | 7 | 84 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | YouTubeVideo | YouTubeVideo | 281 | 319 | 281 | 281 | 53a3e0b2f3bfd8ab89a634fb502a1d90d9d00285 | bigcode/the-stack | train |
39058e8b17678744b85eedec | train | class | class Audio(DisplayObject):
"""Create an audio object.
When this object is returned by an input cell or passed to the
display function, it will result in Audio controls being displayed
in the frontend (only works in the notebook).
Parameters
----------
data : numpy array, list, unicode, st... | class Audio(DisplayObject):
| """Create an audio object.
When this object is returned by an input cell or passed to the
display function, it will result in Audio controls being displayed
in the frontend (only works in the notebook).
Parameters
----------
data : numpy array, list, unicode, str or bytes
Can be on... | """Various display related classes.
Authors : MinRK, gregcaporaso, dannystaple
"""
from html import escape as html_escape
from os.path import exists, isfile, splitext, abspath, join, isdir
from os import walk, sep, fsdecode
from IPython.core.display import DisplayObject, TextDisplayObject
__all__ = ['Audio', 'IFrame... | 117 | 256 | 1,914 | 5 | 112 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | Audio | Audio | 15 | 243 | 15 | 15 | db9f1acdf012386807e6bf15b99ad0557bfe96e9 | bigcode/the-stack | train |
3d1f1d7ebb1cc3a9573f202c | train | class | class FileLinks(FileLink):
"""Class for embedding local file links in an IPython session, based on path
e.g. to embed links to files that were generated in the IPython notebook
under ``my/data``, you would do::
local_files = FileLinks("my/data")
display(local_files)
or in the HTML not... | class FileLinks(FileLink):
| """Class for embedding local file links in an IPython session, based on path
e.g. to embed links to files that were generated in the IPython notebook
under ``my/data``, you would do::
local_files = FileLinks("my/data")
display(local_files)
or in the HTML notebook, just::
File... | : str
text to append at the end of link [default: '<br>']
"""
if isdir(path):
raise ValueError("Cannot display a directory using FileLink. "
"Use FileLinks to display '%s'." % path)
self.path = fsdecode(path)
self.url_prefix = url_prefix
sel... | 256 | 256 | 1,523 | 6 | 250 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | FileLinks | FileLinks | 412 | 605 | 412 | 412 | 0e92b844032daa9ebba342b21d875c70c8cc4790 | bigcode/the-stack | train |
3f821979ee1400f87a070086 | train | class | class VimeoVideo(IFrame):
"""
Class for embedding a Vimeo video in an IPython session, based on its video id.
"""
def __init__(self, id, width=400, height=300, **kwargs):
src="https://player.vimeo.com/video/{0}".format(id)
super(VimeoVideo, self).__init__(src, width, height, **kwargs)
| class VimeoVideo(IFrame):
| """
Class for embedding a Vimeo video in an IPython session, based on its video id.
"""
def __init__(self, id, width=400, height=300, **kwargs):
src="https://player.vimeo.com/video/{0}".format(id)
super(VimeoVideo, self).__init__(src, width, height, **kwargs)
| def _repr_jpeg_(self):
# Deferred import
from urllib.request import urlopen
try:
return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read()
except IOError:
return None
class VimeoVideo(IFrame):
| 64 | 64 | 84 | 6 | 57 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | VimeoVideo | VimeoVideo | 321 | 328 | 321 | 321 | 819654838cd8042bd64e38d9f82f7069743552cb | bigcode/the-stack | train |
ab68d293365c7ca5ce26b682 | train | class | class IFrame(object):
"""
Generic class to embed an iframe in an IPython notebook
"""
iframe = """
<iframe
width="{width}"
height="{height}"
src="{src}{params}"
frameborder="0"
allowfullscreen
></iframe>
"""
def __... | class IFrame(object):
| """
Generic class to embed an iframe in an IPython notebook
"""
iframe = """
<iframe
width="{width}"
height="{height}"
src="{src}{params}"
frameborder="0"
allowfullscreen
></iframe>
"""
def __init__(self, src, widt... | if(self.autoplay):
return 'autoplay="autoplay"'
else:
return ''
def element_id_attr(self):
if (self.element_id):
return 'id="{element_id}"'.format(element_id=self.element_id)
else:
return ''
class IFrame(object):
| 64 | 64 | 189 | 5 | 59 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | IFrame | IFrame | 245 | 279 | 245 | 245 | aad8ae348503b6c91ec31a7562cdb1078b8408ae | bigcode/the-stack | train |
6e4baef937af27523e7b2d7e | train | class | class Code(TextDisplayObject):
"""Display syntax-highlighted source code.
This uses Pygments to highlight the code for HTML and Latex output.
Parameters
----------
data : str
The code as a string
url : str
A URL to fetch the code from
filename : str
A local filename... | class Code(TextDisplayObject):
| """Display syntax-highlighted source code.
This uses Pygments to highlight the code for HTML and Latex output.
Parameters
----------
data : str
The code as a string
url : str
A URL to fetch the code from
filename : str
A local filename to load the code from
lang... | return '\n'.join(result_lines)
def __repr__(self):
"""return newline-separated absolute paths
"""
result_lines = []
if self.recursive:
walked_dir = list(walk(self.path))
else:
walked_dir = [next(walk(self.path))]
walked_dir.sort()
for... | 113 | 113 | 377 | 6 | 107 | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | .venv/lib/python3.7/site-packages/IPython/lib/display.py | Python | Code | Code | 608 | 654 | 608 | 608 | 402ef17f4f5cfeef9c9b192ba68b64320407b475 | bigcode/the-stack | train |
75c2594babba554c58edb35f | train | class | class DjangoWhiteNoise(DynamicWhiteNoise):
def __init__(self, application, static_prefix=None, **kwargs):
super(DjangoWhiteNoise, self).__init__(application, **kwargs)
self.static_prefix = static_prefix
if not self.autorefresh and self.static_prefix:
self.add_files_from_finders()... | class DjangoWhiteNoise(DynamicWhiteNoise):
| def __init__(self, application, static_prefix=None, **kwargs):
super(DjangoWhiteNoise, self).__init__(application, **kwargs)
self.static_prefix = static_prefix
if not self.autorefresh and self.static_prefix:
self.add_files_from_finders()
def add_files_from_finders(self):
... | if self.dynamic_check is not None and self.dynamic_check.match(url):
return self.dynamic_finder.find(url)
def candidate_paths_for_url(self, url):
paths = super(DynamicWhiteNoise, self).candidate_paths_for_url(url)
for path in paths:
yield path
path = self.get... | 87 | 87 | 291 | 9 | 77 | indirectlylit/kolibri | kolibri/utils/kolibri_whitenoise.py | Python | DjangoWhiteNoise | DjangoWhiteNoise | 117 | 150 | 117 | 117 | b5c60a9252eeae8705a4921bb214bdd055712c8a | bigcode/the-stack | train |
49ef7589172a1f8211409f79 | train | class | class FileFinder(finders.FileSystemFinder):
"""
A modified version of the Django FileSystemFinder class
which allows us to pass in arbitrary locations to find files
"""
def __init__(self, locations):
# List of locations with static files
self.locations = []
self.prefixes = s... | class FileFinder(finders.FileSystemFinder):
| """
A modified version of the Django FileSystemFinder class
which allows us to pass in arbitrary locations to find files
"""
def __init__(self, locations):
# List of locations with static files
self.locations = []
self.prefixes = set()
# Maps dir paths to an appropri... | import os
import re
import stat
from collections import OrderedDict
from django.contrib.staticfiles import finders
from django.core.files.storage import FileSystemStorage
from django.utils._os import safe_join
from whitenoise import WhiteNoise
from whitenoise.string_utils import decode_path_info
class FileFinder(finde... | 69 | 100 | 336 | 9 | 59 | indirectlylit/kolibri | kolibri/utils/kolibri_whitenoise.py | Python | FileFinder | FileFinder | 13 | 56 | 13 | 13 | 6ed8b6f3b21ef120685b70409396da9832f9f3a5 | bigcode/the-stack | train |
f42ebd27a6488d204b3e994a | train | class | class DynamicWhiteNoise(WhiteNoise):
def __init__(self, application, dynamic_locations=None, **kwargs):
whitenoise_settings = {
# Use 1 day as the default cache time for static assets
"max_age": 24 * 60 * 60,
# Add a test for any file name that contains a semantic version... | class DynamicWhiteNoise(WhiteNoise):
| def __init__(self, application, dynamic_locations=None, **kwargs):
whitenoise_settings = {
# Use 1 day as the default cache time for static assets
"max_age": 24 * 60 * 60,
# Add a test for any file name that contains a semantic version number
# or a 32 digit n... | , root))
self.prefixes.add(prefix)
for prefix, root in self.locations:
filesystem_storage = FileSystemStorage(location=root)
filesystem_storage.prefix = prefix
self.storages[root] = filesystem_storage
def find_location(self, root, path, prefix=None):
... | 166 | 166 | 554 | 8 | 157 | indirectlylit/kolibri | kolibri/utils/kolibri_whitenoise.py | Python | DynamicWhiteNoise | DynamicWhiteNoise | 59 | 114 | 59 | 59 | 362c4b40f13702edc587f6fb6487b650f2948da5 | bigcode/the-stack | train |
b66b4943ee88d37a74b00617 | train | function | def main():
print('AML SDK library loaded; version:', azureml.core.VERSION)
# parse the command-line args:
parser = argparse.ArgumentParser()
parser.add_argument('--kernel', type=str, default='linear',
help='Kernel type to be used in the algorithm')
parser.add_argument('--pe... | def main():
| print('AML SDK library loaded; version:', azureml.core.VERSION)
# parse the command-line args:
parser = argparse.ArgumentParser()
parser.add_argument('--kernel', type=str, default='linear',
help='Kernel type to be used in the algorithm')
parser.add_argument('--penalty', type... | # Modified from https://www.geeksforgeeks.org/multiclass-classification-using-scikit-learn/
import argparse
import joblib
import os
import numpy as np
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classificat... | 159 | 177 | 590 | 3 | 155 | cjoakim/azure-aml | src/train_iris.py | Python | main | main | 27 | 94 | 27 | 27 | 2ee5919fa4e07b7681200f128937385531e2f3dc | bigcode/the-stack | train |
b298d0b497bc63964340ce54 | train | class | class TestFeaturedProjectService(BaseTestCase):
def test_featured_projects_service(self):
self.test_project, self.test_user = create_canned_project()
# Featured a not created project.
with self.assertRaises(NotFound):
ProjectService.set_project_as_featured(project_id=100)
... | class TestFeaturedProjectService(BaseTestCase):
| def test_featured_projects_service(self):
self.test_project, self.test_user = create_canned_project()
# Featured a not created project.
with self.assertRaises(NotFound):
ProjectService.set_project_as_featured(project_id=100)
# Feature an already created project.
... | from backend.services.project_service import ProjectService
from backend.models.postgis.utils import NotFound
from tests.backend.helpers.test_helpers import create_canned_project
from tests.backend.base import BaseTestCase
class TestFeaturedProjectService(BaseTestCase):
| 49 | 64 | 170 | 9 | 39 | KathmanduLivingLabs/tasking-manager | tests/backend/integration/services/test_featured_projects_services.py | Python | TestFeaturedProjectService | TestFeaturedProjectService | 8 | 27 | 8 | 8 | e9cd43cf9947ee27d1be42e0a14ff56a0c090a99 | bigcode/the-stack | train |
85cee82be0f919b772505a2e | train | function | def no_install():
"""Run `which mafft` to see if mafft is already installed."""
result = subprocess.run(["which", "mafft"])
return result
| def no_install():
| """Run `which mafft` to see if mafft is already installed."""
result = subprocess.run(["which", "mafft"])
return result
| if result.returncode != SUCCESS_RETURN_CODE:
result = debian_install()
if result.returncode != SUCCESS_RETURN_CODE:
print("Debian-based installation failed. Trying with brew instead...")
result = brew_install()
if result.returncode != SUCCESS_RETURN_CODE:
... | 64 | 64 | 37 | 4 | 60 | pagpires/seqlike | setup.py | Python | no_install | no_install | 44 | 47 | 44 | 44 | a004cc1b1f6905910e133c8f799090f2d1cd8f09 | bigcode/the-stack | train |
572631875a7e983484c49bc1 | train | function | def brew_install():
"""Attempt installation by brew."""
result = subprocess.run(["which", "brew"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["brew", "update"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["brew", "install", "mafft"])
... | def brew_install():
| """Attempt installation by brew."""
result = subprocess.run(["which", "brew"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["brew", "update"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["brew", "install", "mafft"])
return result
| brew instead...")
result = brew_install()
if result.returncode != SUCCESS_RETURN_CODE:
warning_install()
def no_install():
"""Run `which mafft` to see if mafft is already installed."""
result = subprocess.run(["which", "mafft"])
return result
def brew_install():
| 64 | 64 | 72 | 4 | 59 | pagpires/seqlike | setup.py | Python | brew_install | brew_install | 50 | 57 | 50 | 50 | 458585942ce43d8e4492ea3972a771401c7f71cd | bigcode/the-stack | train |
d5f8ab89b033054485e6753e | train | function | def rpm_install():
"""Install MAFFT using RPM."""
raise NotImplementedError("Installation by RPM not yet supported.")
| def rpm_install():
| """Install MAFFT using RPM."""
raise NotImplementedError("Installation by RPM not yet supported.")
| "install", "-y", "ghostscript"])
if result.returncode == SUCCESS_RETURN_CODE:
deb_filepath = download_mafft(kind="deb")
print(f"Installing {deb_filepath}...")
result = subprocess.run(["dpkg", "--install", deb_filepath])
return result
def rpm_install():
| 64 | 64 | 25 | 4 | 59 | pagpires/seqlike | setup.py | Python | rpm_install | rpm_install | 74 | 76 | 74 | 74 | 5dc609b76f129111821875d92c7b637fccb3a57d | bigcode/the-stack | train |
d2d654d83c37d8cae1693060 | train | function | def debian_install():
"""Install MAFFT on debian."""
result = subprocess.run(["which", "apt-get"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["apt-get", "update"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["apt-get", "install", "-y",... | def debian_install():
| """Install MAFFT on debian."""
result = subprocess.run(["which", "apt-get"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["apt-get", "update"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["apt-get", "install", "-y", "ghostscript"])
i... | = subprocess.run(["which", "brew"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["brew", "update"])
if result.returncode == SUCCESS_RETURN_CODE:
result = subprocess.run(["brew", "install", "mafft"])
return result
def debian_install():
| 64 | 64 | 127 | 5 | 58 | pagpires/seqlike | setup.py | Python | debian_install | debian_install | 60 | 71 | 60 | 60 | 409c354329e69c89039417c0a0d0b4cfe441ded6 | bigcode/the-stack | train |
a2f6c61b4cb6c0485ee0116a | train | function | def download_mafft(kind="deb") -> Path:
"""Download MAFFT from the original website."""
acceptable_kinds = ["deb", "rpm"]
if kind not in acceptable_kinds:
raise NameError(f"`kind` should be one of {acceptable_kinds}.")
if kind == "deb":
mafft_file = "mafft_7.487-1_amd64.deb"
if kind... | def download_mafft(kind="deb") -> Path:
| """Download MAFFT from the original website."""
acceptable_kinds = ["deb", "rpm"]
if kind not in acceptable_kinds:
raise NameError(f"`kind` should be one of {acceptable_kinds}.")
if kind == "deb":
mafft_file = "mafft_7.487-1_amd64.deb"
if kind == "rpm":
mafft_file = "mafft-7... | install MAFFT to enjoy SeqLike's Series Accessor's "
"method-chained alignment capabilities. \n\n"
"MAFFT installation instructions can be found on "
"https://mafft.cbrc.jp/alignment/software/."
)
def download_mafft(kind="deb") -> Path:
| 64 | 64 | 207 | 11 | 53 | pagpires/seqlike | setup.py | Python | download_mafft | download_mafft | 90 | 108 | 90 | 90 | a04215c59d084799ab8ac30c41a891aa638ce53a | bigcode/the-stack | train |
b84d47ed16a86dff91d5da06 | train | function | def warning_install():
"""Raise a warning that none of the previous installation methods worked."""
warnings.warn(
"Installation by dpkg and brew failed. "
"Please manually install MAFFT to enjoy SeqLike's Series Accessor's "
"method-chained alignment capabilities. \n\n"
"MAFFT i... | def warning_install():
| """Raise a warning that none of the previous installation methods worked."""
warnings.warn(
"Installation by dpkg and brew failed. "
"Please manually install MAFFT to enjoy SeqLike's Series Accessor's "
"method-chained alignment capabilities. \n\n"
"MAFFT installation instruction... | fft(kind="deb")
print(f"Installing {deb_filepath}...")
result = subprocess.run(["dpkg", "--install", deb_filepath])
return result
def rpm_install():
"""Install MAFFT using RPM."""
raise NotImplementedError("Installation by RPM not yet supported.")
def warning_install():
| 63 | 64 | 90 | 4 | 59 | pagpires/seqlike | setup.py | Python | warning_install | warning_install | 79 | 87 | 79 | 79 | 00224e1f8ab82b6d310ccc60c101d80caa400c31 | bigcode/the-stack | train |
456f7b2c75763480335396c3 | train | class | class InstallWrapper(install):
"""Install MAFFT binary executables and other requirements.
The order of priority in which we try:
- Determine whether no installation is necessary (no_install).
- Try to install via dpkg (debian_install).
- Try to install via brew (brew_install).
- Raise warning... | class InstallWrapper(install):
| """Install MAFFT binary executables and other requirements.
The order of priority in which we try:
- Determine whether no installation is necessary (no_install).
- Try to install via dpkg (debian_install).
- Try to install via brew (brew_install).
- Raise warning to install on their own (warni... | import os
import subprocess
import warnings
from distutils.command.install import install as orig_install
from pathlib import Path
import requests
from setuptools import find_packages, setup
from setuptools.command.install import install
SUCCESS_RETURN_CODE = 0
class InstallWrapper(install):
| 56 | 85 | 285 | 6 | 49 | pagpires/seqlike | setup.py | Python | InstallWrapper | InstallWrapper | 14 | 41 | 14 | 14 | 63e2bcc6318afc0ceb1b6c0773bbd878ed94af1d | bigcode/the-stack | train |
86dfddeef388c2c511168de1 | train | class | class MartindalePageData:
####
# GENERAL SETTINGS
####
# URLs
# Staging
MARTINDALE_URL = "http://my.stg-martindalenolo.com/0004973/site/editor/cms"
#Production
#MARTINDALE_URL = "http://my.martindalenolo.com/0022415/site/editor/cms"
MARTINDALE_STAGING_URL_FRAME_ONLY = "http://my.stg-martindalen... | class MartindalePageData:
####
# GENERAL SETTINGS
####
# URLs
# Staging
| MARTINDALE_URL = "http://my.stg-martindalenolo.com/0004973/site/editor/cms"
#Production
#MARTINDALE_URL = "http://my.martindalenolo.com/0022415/site/editor/cms"
MARTINDALE_STAGING_URL_FRAME_ONLY = "http://my.stg-martindalenolo.com/0004973/"
MARTINDALE_AUTOMATION_URL = "http://my.stg-martindalenolo.c... | class MartindalePageData:
####
# GENERAL SETTINGS
####
# URLs
# Staging
| 22 | 256 | 910 | 22 | 0 | tate138/Martindale_Automation | library/page_data/martindale_app/martindale_data.py | Python | MartindalePageData | MartindalePageData | 1 | 146 | 1 | 7 | c9ab080b1cec5b66bebd6df8d71d72e82e5b1c77 | bigcode/the-stack | train |
d91207ac37a358d5c3584830 | train | class | class TestUserEndpoint(BaseCase):
''' A class to test the user endpoints '''
def setUp(self):
super(TestUserEndpoint, self).setUp()
def test_get_returns_all_users(self):
with self.app.app_context():
response = self.client().get('/api/v1/users',
... | class TestUserEndpoint(BaseCase):
| ''' A class to test the user endpoints '''
def setUp(self):
super(TestUserEndpoint, self).setUp()
def test_get_returns_all_users(self):
with self.app.app_context():
response = self.client().get('/api/v1/users',
headers=self.auth_headers()... | import json
from tests.base_test import BaseCase
from app.models.user import User
class TestUserEndpoint(BaseCase):
| 25 | 141 | 473 | 7 | 17 | Enkya/ims_beta | tests/api/v1/test_user_endpoint.py | Python | TestUserEndpoint | TestUserEndpoint | 7 | 53 | 7 | 7 | 774495ac3c56a3ee9cd45edfdb06f97d2e7a2f3f | bigcode/the-stack | train |
c911213a30e8005d4eb3b667 | train | function | def slices(series, length):
"""
Returns a list of adjacent elements of length n in the given series.
"""
if length > len(series):
raise ValueError('Length is greater than the total length of the series!')
elif length < 1:
raise ValueError('Length should be a positive number greater t... | def slices(series, length):
| """
Returns a list of adjacent elements of length n in the given series.
"""
if length > len(series):
raise ValueError('Length is greater than the total length of the series!')
elif length < 1:
raise ValueError('Length should be a positive number greater than zero.')
else:
... | def slices(series, length):
| 6 | 64 | 109 | 6 | 0 | gurupratap-matharu/Exercism | python/series/series.py | Python | slices | slices | 1 | 14 | 1 | 1 | 612eba14cd022e50a129ac99ca3a780c2e01e552 | bigcode/the-stack | train |
5cb99a9679a5aa6c35100683 | train | function | def extract_features(dir_name, files, i_start, i_end):
dict_features_index = {}
for i in range(i_start, i_end):
if(i % 100 == 0):
tf.logging.info("loading features...(%d/%d)"%(i,i_end-i_start))
cur_features_file = dir_name + '/' + files[i]
basename = os.path.basename(cur_feat... | def extract_features(dir_name, files, i_start, i_end):
| dict_features_index = {}
for i in range(i_start, i_end):
if(i % 100 == 0):
tf.logging.info("loading features...(%d/%d)"%(i,i_end-i_start))
cur_features_file = dir_name + '/' + files[i]
basename = os.path.basename(cur_features_file)
basename = os.path.splitext(basename... | 0.8
PLOT_FIG = False
#INDEX_FEATURE_FOLDER = 'data/oxford5k_features'
#QUERY_FEATURE_FOLDER = 'data/oxford5k_features'
#OUT_PUT_FILE = 'out.csv'
def extract_features(dir_name, files, i_start, i_end):
| 64 | 64 | 184 | 14 | 50 | zijing-wu/models | research/delf/delf/python/examples/match_images_all.py | Python | extract_features | extract_features | 54 | 70 | 54 | 54 | 18207784cbb5245263f361daaaaa5b2ab9f4de97 | bigcode/the-stack | train |
cac94358590c7c4fa825f667 | train | function | def main():
if len(sys.argv) != 7:
print('Syntax: {} <train_dir/> <test_dir/> <test_start> <test_end> <batch_size> <out_dir/>'.format(sys.argv[0]))
sys.exit(0)
(train_dir, test_dir, test_start, test_end, batch_size, out_dir) = sys.argv[1:]
test_start=int(test_start)
test_end=int(test_end... | def main():
| if len(sys.argv) != 7:
print('Syntax: {} <train_dir/> <test_dir/> <test_start> <test_end> <batch_size> <out_dir/>'.format(sys.argv[0]))
sys.exit(0)
(train_dir, test_dir, test_start, test_end, batch_size, out_dir) = sys.argv[1:]
test_start=int(test_start)
test_end=int(test_end)
batch_... | _args = None
_DISTANCE_THRESHOLD = 0.8
PLOT_FIG = False
#INDEX_FEATURE_FOLDER = 'data/oxford5k_features'
#QUERY_FEATURE_FOLDER = 'data/oxford5k_features'
#OUT_PUT_FILE = 'out.csv'
def extract_features(dir_name, files, i_start, i_end):
dict_features_index = {}
for i in range(i_start, i_end):
if(i % 10... | 252 | 252 | 843 | 3 | 248 | zijing-wu/models | research/delf/delf/python/examples/match_images_all.py | Python | main | main | 73 | 148 | 73 | 73 | cf062a2a42562f050ab23a48bc24c621a94f7bae | bigcode/the-stack | train |
97e41073f76eb170a234150b | train | class | class PeersView(view.View):
_mode_name = "peers"
def __init__(self):
self._peerinfo = None # raw data from getpeerinfo
super().__init__()
async def _draw(self):
self._clear_init_pad()
if self._peerinfo:
po = self._peerinfo
self._pad.addstr(0, 1, ... | class PeersView(view.View):
| _mode_name = "peers"
def __init__(self):
self._peerinfo = None # raw data from getpeerinfo
super().__init__()
async def _draw(self):
self._clear_init_pad()
if self._peerinfo:
po = self._peerinfo
self._pad.addstr(0, 1, "Node IP Versio... | # Copyright (c) 2014-2017 esotericnonsense (Daniel Edgecumbe)
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://opensource.org/licenses/mit-license.php
import datetime
import time
import math
import curses
import asyncio
import view
class PeersView(view.View):
| 72 | 239 | 799 | 7 | 64 | Groestlcoin/groestlcoind-ncurses2 | peers.py | Python | PeersView | PeersView | 14 | 100 | 14 | 14 | 15fdc8e282c56920f5ab6467d9eb46308d2995ed | bigcode/the-stack | train |
7796e05c28525b15c90ccb71 | train | function | def create_symbols_zip():
if get_target_arch() == 'mips64el':
return
dist_name = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'symbols')
zip_file = os.path.join(DIST_DIR, dist_name)
licenses = ['LICENSE', 'LICENSES.chromium.html', 'version']
with scoped_cwd(DIST_DIR):
dirs = ['{0}.breakpad.syms'.for... | def create_symbols_zip():
| if get_target_arch() == 'mips64el':
return
dist_name = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'symbols')
zip_file = os.path.join(DIST_DIR, dist_name)
licenses = ['LICENSE', 'LICENSES.chromium.html', 'version']
with scoped_cwd(DIST_DIR):
dirs = ['{0}.breakpad.syms'.format(PROJECT_NAME)]
mak... | '..', 'ffmpeg', ffmpeg_name),
DIST_DIR)
if PLATFORM == 'linux':
strip_binary(os.path.join(DIST_DIR, ffmpeg_name))
with scoped_cwd(DIST_DIR):
make_zip(zip_file, [ffmpeg_name, 'LICENSE', 'LICENSES.chromium.html'], [])
def create_symbols_zip():
| 71 | 72 | 240 | 5 | 66 | Pephers/electron | script/create-dist.py | Python | create_symbols_zip | create_symbols_zip | 296 | 317 | 296 | 296 | 6dd653ca256ddc9fa56943554e5aff6848a64a7f | bigcode/the-stack | train |
9b018f074e1338bac9049f36 | train | function | def create_chrome_binary_zip(binary, version):
dist_name = get_zip_name(binary, version)
zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name)
with scoped_cwd(DIST_DIR):
files = ['LICENSE', 'LICENSES.chromium.html']
if PLATFORM == 'win32':
files += [binary + '.exe']
else:
files += [bina... | def create_chrome_binary_zip(binary, version):
| dist_name = get_zip_name(binary, version)
zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name)
with scoped_cwd(DIST_DIR):
files = ['LICENSE', 'LICENSES.chromium.html']
if PLATFORM == 'win32':
files += [binary + '.exe']
else:
files += [binary]
make_zip(zip_file, files, [])
| _DIR):
files = TARGET_BINARIES[PLATFORM] + TARGET_BINARIES_EXT + ['LICENSE',
'LICENSES.chromium.html', 'version']
dirs = TARGET_DIRECTORIES[PLATFORM]
make_zip(zip_file, files, dirs)
def create_chrome_binary_zip(binary, version):
| 64 | 64 | 95 | 10 | 54 | Pephers/electron | script/create-dist.py | Python | create_chrome_binary_zip | create_chrome_binary_zip | 262 | 272 | 262 | 262 | 480ece61f239ccd1513727f4e24825837786dab1 | bigcode/the-stack | train |
f6d69fd62929dd0894d6d36a | train | function | def strip_binary(binary_path):
if get_target_arch() == 'arm':
strip = 'arm-linux-gnueabihf-strip'
elif get_target_arch() == 'arm64':
strip = 'aarch64-linux-gnu-strip'
elif get_target_arch() == 'mips64el':
strip = 'mips64el-redhat-linux-strip'
else:
strip = 'strip'
execute([strip, binary_path],... | def strip_binary(binary_path):
| if get_target_arch() == 'arm':
strip = 'arm-linux-gnueabihf-strip'
elif get_target_arch() == 'arm64':
strip = 'aarch64-linux-gnu-strip'
elif get_target_arch() == 'mips64el':
strip = 'mips64el-redhat-linux-strip'
else:
strip = 'strip'
execute([strip, binary_path], env=build_env())
| (infile),
'--out={0}'.format(outfile)], env=env)
def strip_binaries():
for binary in TARGET_BINARIES[PLATFORM]:
if binary.endswith('.so') or '.' not in binary:
strip_binary(os.path.join(DIST_DIR, binary))
def strip_binary(binary_path):
| 64 | 64 | 101 | 6 | 58 | Pephers/electron | script/create-dist.py | Python | strip_binary | strip_binary | 215 | 224 | 215 | 215 | a1dfbc05de390b1aaed6ee7fdfc14e7d0a04ba0b | bigcode/the-stack | train |
fb86357b80717862a232c141 | train | function | def create_typescript_definitions():
node_bin_dir = os.path.join(SOURCE_ROOT, 'node_modules', '.bin')
env = os.environ.copy()
env['PATH'] = os.path.pathsep.join([node_bin_dir, env['PATH']])
infile = os.path.relpath(os.path.join(DIST_DIR, 'electron-api.json'))
outfile = os.path.relpath(os.path.join(DIST_DIR, '... | def create_typescript_definitions():
| node_bin_dir = os.path.join(SOURCE_ROOT, 'node_modules', '.bin')
env = os.environ.copy()
env['PATH'] = os.path.pathsep.join([node_bin_dir, env['PATH']])
infile = os.path.relpath(os.path.join(DIST_DIR, 'electron-api.json'))
outfile = os.path.relpath(os.path.join(DIST_DIR, 'electron.d.ts'))
execute(['electron... | .path.relpath(os.path.join(DIST_DIR, 'electron-api.json'))
execute(['electron-docs-linter', 'docs', '--outfile={0}'.format(outfile),
'--version={}'.format(ELECTRON_VERSION.replace('v', ''))],
env=env)
def create_typescript_definitions():
| 64 | 64 | 123 | 7 | 57 | Pephers/electron | script/create-dist.py | Python | create_typescript_definitions | create_typescript_definitions | 200 | 207 | 200 | 200 | 8b5224cac26e8bd50c0835d3c1e315621c34bd78 | bigcode/the-stack | train |
9cf7484acfada5c83c5699f8 | train | function | def strip_binaries():
for binary in TARGET_BINARIES[PLATFORM]:
if binary.endswith('.so') or '.' not in binary:
strip_binary(os.path.join(DIST_DIR, binary))
| def strip_binaries():
| for binary in TARGET_BINARIES[PLATFORM]:
if binary.endswith('.so') or '.' not in binary:
strip_binary(os.path.join(DIST_DIR, binary))
| (DIST_DIR, 'electron-api.json'))
outfile = os.path.relpath(os.path.join(DIST_DIR, 'electron.d.ts'))
execute(['electron-typescript-definitions', '--in={0}'.format(infile),
'--out={0}'.format(outfile)], env=env)
def strip_binaries():
| 64 | 64 | 42 | 5 | 59 | Pephers/electron | script/create-dist.py | Python | strip_binaries | strip_binaries | 209 | 212 | 209 | 209 | 4d7b5cdd4b52fc7a796ee4e36c626d0aab1b89bf | bigcode/the-stack | train |
4af07eca0fccd3555db93b41 | train | function | def copy_license():
shutil.copy2(os.path.join(CHROMIUM_DIR, '..', 'LICENSES.chromium.html'),
DIST_DIR)
shutil.copy2(os.path.join(SOURCE_ROOT, 'LICENSE'), DIST_DIR)
| def copy_license():
| shutil.copy2(os.path.join(CHROMIUM_DIR, '..', 'LICENSES.chromium.html'),
DIST_DIR)
shutil.copy2(os.path.join(SOURCE_ROOT, 'LICENSE'), DIST_DIR)
| .path.join(ucrt_dir, '*.dll'))
if len(dlls) == 0:
raise Exception('UCRT files not found')
for dll in dlls:
shutil.copy2(dll, DIST_DIR)
TARGET_BINARIES_EXT.append(os.path.basename(dll))
def copy_license():
| 64 | 64 | 46 | 4 | 60 | Pephers/electron | script/create-dist.py | Python | copy_license | copy_license | 186 | 189 | 186 | 186 | 51ae07d82494a2099b663bb80ddb04d20c8c1f02 | bigcode/the-stack | train |
02373e2fef6e952be3da3855 | train | function | def copy_binaries():
for binary in TARGET_BINARIES[PLATFORM]:
shutil.copy2(os.path.join(OUT_DIR, binary), DIST_DIR)
for directory in TARGET_DIRECTORIES[PLATFORM]:
shutil.copytree(os.path.join(OUT_DIR, directory),
os.path.join(DIST_DIR, directory),
symlinks=True)
| def copy_binaries():
| for binary in TARGET_BINARIES[PLATFORM]:
shutil.copy2(os.path.join(OUT_DIR, binary), DIST_DIR)
for directory in TARGET_DIRECTORIES[PLATFORM]:
shutil.copytree(os.path.join(OUT_DIR, directory),
os.path.join(DIST_DIR, directory),
symlinks=True)
| _binary_zip('mksnapshot', ELECTRON_VERSION)
create_ffmpeg_zip()
create_symbols_zip()
def force_build():
build = os.path.join(SOURCE_ROOT, 'script', 'build.py')
execute([sys.executable, build, '-c', 'Release'])
def copy_binaries():
| 63 | 64 | 73 | 5 | 58 | Pephers/electron | script/create-dist.py | Python | copy_binaries | copy_binaries | 124 | 131 | 124 | 124 | 324d7dcb2df18a5134d90c8a005e1496824ef1aa | bigcode/the-stack | train |
553647cdc8175a23be876703 | train | function | def create_ffmpeg_zip():
dist_name = get_zip_name('ffmpeg', ELECTRON_VERSION)
zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name)
if PLATFORM == 'darwin':
ffmpeg_name = 'libffmpeg.dylib'
elif PLATFORM == 'linux':
ffmpeg_name = 'libffmpeg.so'
elif PLATFORM == 'win32':
ffmpeg_name = 'ffmpeg.dll... | def create_ffmpeg_zip():
| dist_name = get_zip_name('ffmpeg', ELECTRON_VERSION)
zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name)
if PLATFORM == 'darwin':
ffmpeg_name = 'libffmpeg.dylib'
elif PLATFORM == 'linux':
ffmpeg_name = 'libffmpeg.so'
elif PLATFORM == 'win32':
ffmpeg_name = 'ffmpeg.dll'
shutil.copy2(os.path... | with scoped_cwd(DIST_DIR):
files = ['LICENSE', 'LICENSES.chromium.html']
if PLATFORM == 'win32':
files += [binary + '.exe']
else:
files += [binary]
make_zip(zip_file, files, [])
def create_ffmpeg_zip():
| 63 | 64 | 173 | 6 | 57 | Pephers/electron | script/create-dist.py | Python | create_ffmpeg_zip | create_ffmpeg_zip | 275 | 293 | 275 | 275 | b7c40c3bda02e1bd69f7c74058ecea05c071912e | bigcode/the-stack | train |
b6101c828c0351c3a95dd949 | train | function | def main():
args = parse_args()
if args.chromium_dir:
globals().update(CHROMIUM_DIR=args.chromium_dir)
if args.verbose:
enable_verbose_mode()
rm_rf(DIST_DIR)
os.makedirs(DIST_DIR)
force_build()
create_symbols()
copy_binaries()
copy_chrome_binary('chromedriver')
copy_chrome_binary('mksnap... | def main():
| args = parse_args()
if args.chromium_dir:
globals().update(CHROMIUM_DIR=args.chromium_dir)
if args.verbose:
enable_verbose_mode()
rm_rf(DIST_DIR)
os.makedirs(DIST_DIR)
force_build()
create_symbols()
copy_binaries()
copy_chrome_binary('chromedriver')
copy_chrome_binary('mksnapshot')
cop... | _EXT = []
TARGET_DIRECTORIES = {
'darwin': [
'{0}.app'.format(PRODUCT_NAME),
],
'win32': [
'resources',
'locales',
],
'linux': [
'resources',
'locales',
],
}
def main():
| 64 | 64 | 201 | 3 | 61 | Pephers/electron | script/create-dist.py | Python | main | main | 82 | 116 | 82 | 82 | 1f563f39fca5001c91b70b7d59433bb081183583 | bigcode/the-stack | train |
27bd8a7b15d77aef5af46d12 | train | function | def create_dist_zip():
dist_name = get_zip_name(PROJECT_NAME, ELECTRON_VERSION)
zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name)
with scoped_cwd(DIST_DIR):
files = TARGET_BINARIES[PLATFORM] + TARGET_BINARIES_EXT + ['LICENSE',
'LICENSES.chromium.html', 'version']
dirs = TARGET_DIRECTORI... | def create_dist_zip():
| dist_name = get_zip_name(PROJECT_NAME, ELECTRON_VERSION)
zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name)
with scoped_cwd(DIST_DIR):
files = TARGET_BINARIES[PLATFORM] + TARGET_BINARIES_EXT + ['LICENSE',
'LICENSES.chromium.html', 'version']
dirs = TARGET_DIRECTORIES[PLATFORM]
make_z... | tree(dsym, os.path.join(DIST_DIR, os.path.basename(dsym)))
elif PLATFORM == 'win32':
pdbs = glob.glob(os.path.join(OUT_DIR, '*.pdb'))
for pdb in pdbs:
shutil.copy2(pdb, DIST_DIR)
def create_dist_zip():
| 64 | 64 | 98 | 5 | 59 | Pephers/electron | script/create-dist.py | Python | create_dist_zip | create_dist_zip | 251 | 259 | 251 | 251 | f03a41787e992eebc3e2fdf904a07ac6af40dd97 | bigcode/the-stack | train |
698f33c13ff03b8a559af565 | train | function | def copy_ucrt_binaries():
with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Windows Kits\Installed Roots"
) as key:
ucrt_dir = _winreg.QueryValueEx(key, "KitsRoot10")[0]
arch = get_target_arch()
if arch == "ia32":
arch = "x86"
ucrt_dir ... | def copy_ucrt_binaries():
| with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Windows Kits\Installed Roots"
) as key:
ucrt_dir = _winreg.QueryValueEx(key, "KitsRoot10")[0]
arch = get_target_arch()
if arch == "ia32":
arch = "x86"
ucrt_dir += r"Redist\ucrt\DLLs\{0}"... | vcruntime140.dll"]
# Note: copyfile is used to remove the read-only flag
for dll in dlls:
shutil.copyfile(crt_dir + dll, os.path.join(DIST_DIR, dll))
TARGET_BINARIES_EXT.append(dll)
def copy_ucrt_binaries():
| 64 | 64 | 173 | 7 | 57 | Pephers/electron | script/create-dist.py | Python | copy_ucrt_binaries | copy_ucrt_binaries | 165 | 183 | 165 | 165 | 0209908a8ee882f8aeed211f7cb85d90d48ebd6c | bigcode/the-stack | train |
4ef4f36dfe17e2c5977ba714 | train | function | def create_symbols():
if get_target_arch() == 'mips64el':
return
destination = os.path.join(DIST_DIR, '{0}.breakpad.syms'.format(PROJECT_NAME))
dump_symbols = os.path.join(SOURCE_ROOT, 'script', 'dump-symbols.py')
execute([sys.executable, dump_symbols, destination])
if PLATFORM == 'darwin':
dsyms = ... | def create_symbols():
| if get_target_arch() == 'mips64el':
return
destination = os.path.join(DIST_DIR, '{0}.breakpad.syms'.format(PROJECT_NAME))
dump_symbols = os.path.join(SOURCE_ROOT, 'script', 'dump-symbols.py')
execute([sys.executable, dump_symbols, destination])
if PLATFORM == 'darwin':
dsyms = glob.glob(os.path.join... | = 'strip'
execute([strip, binary_path], env=build_env())
def create_version():
version_path = os.path.join(SOURCE_ROOT, 'dist', 'version')
with open(version_path, 'w') as version_file:
version_file.write(ELECTRON_VERSION)
def create_symbols():
| 64 | 64 | 172 | 4 | 60 | Pephers/electron | script/create-dist.py | Python | create_symbols | create_symbols | 233 | 248 | 233 | 233 | e26ed2985b90b03db14282be55af26130759a283 | bigcode/the-stack | train |
6f8c1b036d7bafb8e6ebb8b2 | train | function | def create_version():
version_path = os.path.join(SOURCE_ROOT, 'dist', 'version')
with open(version_path, 'w') as version_file:
version_file.write(ELECTRON_VERSION)
| def create_version():
| version_path = os.path.join(SOURCE_ROOT, 'dist', 'version')
with open(version_path, 'w') as version_file:
version_file.write(ELECTRON_VERSION)
| strip = 'aarch64-linux-gnu-strip'
elif get_target_arch() == 'mips64el':
strip = 'mips64el-redhat-linux-strip'
else:
strip = 'strip'
execute([strip, binary_path], env=build_env())
def create_version():
| 64 | 64 | 43 | 4 | 60 | Pephers/electron | script/create-dist.py | Python | create_version | create_version | 227 | 230 | 227 | 227 | 06e260cbae5469ffe10b7773a9f2bc059526c605 | bigcode/the-stack | train |
7c1334b0f89cc9e37fe67c04 | train | function | def create_api_json_schema():
node_bin_dir = os.path.join(SOURCE_ROOT, 'node_modules', '.bin')
env = os.environ.copy()
env['PATH'] = os.path.pathsep.join([node_bin_dir, env['PATH']])
outfile = os.path.relpath(os.path.join(DIST_DIR, 'electron-api.json'))
execute(['electron-docs-linter', 'docs', '--outfile={0}'... | def create_api_json_schema():
| node_bin_dir = os.path.join(SOURCE_ROOT, 'node_modules', '.bin')
env = os.environ.copy()
env['PATH'] = os.path.pathsep.join([node_bin_dir, env['PATH']])
outfile = os.path.relpath(os.path.join(DIST_DIR, 'electron-api.json'))
execute(['electron-docs-linter', 'docs', '--outfile={0}'.format(outfile),
'... | TARGET_BINARIES_EXT.append(os.path.basename(dll))
def copy_license():
shutil.copy2(os.path.join(CHROMIUM_DIR, '..', 'LICENSES.chromium.html'),
DIST_DIR)
shutil.copy2(os.path.join(SOURCE_ROOT, 'LICENSE'), DIST_DIR)
def create_api_json_schema():
| 64 | 64 | 114 | 6 | 58 | Pephers/electron | script/create-dist.py | Python | create_api_json_schema | create_api_json_schema | 191 | 198 | 191 | 191 | 28d70a9b1813d9a8832a8e53fe559fb6fd524783 | bigcode/the-stack | train |
239c31b192f8cfc818a9933f | train | function | def force_build():
build = os.path.join(SOURCE_ROOT, 'script', 'build.py')
execute([sys.executable, build, '-c', 'Release'])
| def force_build():
| build = os.path.join(SOURCE_ROOT, 'script', 'build.py')
execute([sys.executable, build, '-c', 'Release'])
| if PLATFORM == 'linux':
strip_binaries()
create_version()
create_dist_zip()
create_chrome_binary_zip('chromedriver', ELECTRON_VERSION)
create_chrome_binary_zip('mksnapshot', ELECTRON_VERSION)
create_ffmpeg_zip()
create_symbols_zip()
def force_build():
| 64 | 64 | 36 | 4 | 60 | Pephers/electron | script/create-dist.py | Python | force_build | force_build | 119 | 121 | 119 | 119 | f45f5d2421c709c2b4657a2fc884a598ab21a068 | bigcode/the-stack | train |
ac9250103ca80a9de7618c61 | train | function | def copy_chrome_binary(binary):
if PLATFORM == 'win32':
binary += '.exe'
src = os.path.join(CHROMIUM_DIR, binary)
dest = os.path.join(DIST_DIR, binary)
# Copy file and keep the executable bit.
shutil.copyfile(src, dest)
os.chmod(dest, os.stat(dest).st_mode | stat.S_IEXEC)
| def copy_chrome_binary(binary):
| if PLATFORM == 'win32':
binary += '.exe'
src = os.path.join(CHROMIUM_DIR, binary)
dest = os.path.join(DIST_DIR, binary)
# Copy file and keep the executable bit.
shutil.copyfile(src, dest)
os.chmod(dest, os.stat(dest).st_mode | stat.S_IEXEC)
| ]:
shutil.copy2(os.path.join(OUT_DIR, binary), DIST_DIR)
for directory in TARGET_DIRECTORIES[PLATFORM]:
shutil.copytree(os.path.join(OUT_DIR, directory),
os.path.join(DIST_DIR, directory),
symlinks=True)
def copy_chrome_binary(binary):
| 64 | 64 | 82 | 7 | 57 | Pephers/electron | script/create-dist.py | Python | copy_chrome_binary | copy_chrome_binary | 134 | 142 | 134 | 134 | 01a8b58f4c90383d8354139342e024dcbac2c931 | bigcode/the-stack | train |
b70d06bed13dbd70623a152b | train | function | def copy_vcruntime_binaries():
with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\VisualStudio\14.0\Setup\VC", 0,
_winreg.KEY_READ | _winreg.KEY_WOW64_32KEY) as key:
crt_dir = _winreg.QueryValueEx(key, "ProductDir")[0]
arch = get_target_arch()
... | def copy_vcruntime_binaries():
| with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\VisualStudio\14.0\Setup\VC", 0,
_winreg.KEY_READ | _winreg.KEY_WOW64_32KEY) as key:
crt_dir = _winreg.QueryValueEx(key, "ProductDir")[0]
arch = get_target_arch()
if arch == "ia32":
arch = "... | .join(CHROMIUM_DIR, binary)
dest = os.path.join(DIST_DIR, binary)
# Copy file and keep the executable bit.
shutil.copyfile(src, dest)
os.chmod(dest, os.stat(dest).st_mode | stat.S_IEXEC)
def copy_vcruntime_binaries():
| 64 | 64 | 199 | 8 | 56 | Pephers/electron | script/create-dist.py | Python | copy_vcruntime_binaries | copy_vcruntime_binaries | 145 | 162 | 145 | 145 | 96c88f35c27959795a608ec66dce433c226ccbb6 | bigcode/the-stack | train |
6cd5ff8b4af3f11312e48ba2 | train | function | def parse_args():
parser = argparse.ArgumentParser(description='Create Electron Distribution')
parser.add_argument('--no_api_docs',
action='store_true',
help='Skip generating the Electron API Documentation!')
parser.add_argument('--chromium_dir',
he... | def parse_args():
| parser = argparse.ArgumentParser(description='Create Electron Distribution')
parser.add_argument('--no_api_docs',
action='store_true',
help='Skip generating the Electron API Documentation!')
parser.add_argument('--chromium_dir',
help='Specify a cust... | ':
pdb_name = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'pdb')
with scoped_cwd(DIST_DIR):
pdbs = glob.glob('*.pdb')
make_zip(os.path.join(DIST_DIR, pdb_name), pdbs + licenses, [])
def parse_args():
| 63 | 64 | 104 | 4 | 59 | Pephers/electron | script/create-dist.py | Python | parse_args | parse_args | 320 | 331 | 320 | 320 | 7d9ce6af1ad062f5c5d90c444824cd124495479e | bigcode/the-stack | train |
80494dc4757c8d8d0309d921 | train | class | class RemoteConf(LocalConf):
_lock = ComboLock(get_temp_path('remote-conf.lock'))
"""Config dictionary fetched from mycroft.ai."""
def __init__(self, cache=None):
super(RemoteConf, self).__init__(None)
cache = cache or join(xdg.BaseDirectory.xdg_cache_home, 'mycroft',
... | class RemoteConf(LocalConf):
| _lock = ComboLock(get_temp_path('remote-conf.lock'))
"""Config dictionary fetched from mycroft.ai."""
def __init__(self, cache=None):
super(RemoteConf, self).__init__(None)
cache = cache or join(xdg.BaseDirectory.xdg_cache_home, 'mycroft',
'web_cache.json')
... | unreachable to load settings
that are as close to the user's as possible.
"""
with self._lock:
path = path or self.path
config_dir = dirname(path)
if not exists(config_dir):
os.makedirs(config_dir)
with open(path, 'w') as f:
... | 94 | 94 | 316 | 6 | 88 | quod/mycroft-core | mycroft/configuration/config.py | Python | RemoteConf | RemoteConf | 137 | 182 | 137 | 137 | d924d5a4bc1d22a0f4cefcb578cc2db05708fd82 | bigcode/the-stack | train |
4868ad57d5f475a1e27f3134 | train | class | class LocalConf(dict):
"""Config dictionary from file."""
_lock = ComboLock(get_temp_path('local-conf.lock'))
def __init__(self, path):
super(LocalConf, self).__init__()
if path:
self.path = path
self.load_local(path)
def load_local(self, path):
"""Load ... | class LocalConf(dict):
| """Config dictionary from file."""
_lock = ComboLock(get_temp_path('local-conf.lock'))
def __init__(self, path):
super(LocalConf, self).__init__()
if path:
self.path = path
self.load_local(path)
def load_local(self, path):
"""Load local json file into se... | values):
"""Translate list formated by mycroft server.
Args:
config (dict): target config
values (list): list from mycroft server config
"""
for v in values:
module = v["@type"]
if v.get("active"):
config["module"] = module
config[module] = config.ge... | 89 | 89 | 297 | 5 | 84 | quod/mycroft-core | mycroft/configuration/config.py | Python | LocalConf | LocalConf | 89 | 134 | 89 | 89 | 551872fe6e070f62fbc82e9fa857948fa9cf8344 | bigcode/the-stack | train |
a9c87875cb7694d56a7e7baf | train | function | def translate_list(config, values):
"""Translate list formated by mycroft server.
Args:
config (dict): target config
values (list): list from mycroft server config
"""
for v in values:
module = v["@type"]
if v.get("active"):
config["module"] = module
... | def translate_list(config, values):
| """Translate list formated by mycroft server.
Args:
config (dict): target config
values (list): list from mycroft server config
"""
for v in values:
module = v["@type"]
if v.get("active"):
config["module"] = module
config[module] = config.get(module, ... | v)
elif isinstance(v, list):
if is_remote_list(v):
if key not in config:
config[key] = {}
translate_list(config[key], v)
else:
config[key] = v
else:
config[key] = ... | 64 | 64 | 89 | 7 | 56 | quod/mycroft-core | mycroft/configuration/config.py | Python | translate_list | translate_list | 74 | 86 | 74 | 74 | 76dfa90eaa3af5060a447c21410ecd0b0de117b4 | bigcode/the-stack | train |
d1d4a7340db14253f546c4ec | train | function | def is_remote_list(values):
"""Check if list corresponds to a backend formatted collection of dicts
"""
for v in values:
if not isinstance(v, dict):
return False
if "@type" not in v.keys():
return False
return True
| def is_remote_list(values):
| """Check if list corresponds to a backend formatted collection of dicts
"""
for v in values:
if not isinstance(v, dict):
return False
if "@type" not in v.keys():
return False
return True
| ComboLock
from mycroft.util.file_utils import get_temp_path
from mycroft.util.json_helper import load_commented_json, merge_dict
from mycroft.util.log import LOG
from .locations import DEFAULT_CONFIG, USER_CONFIG, OLD_USER_CONFIG
from .locations import SYSTEM_CONFIG
def is_remote_list(values):
| 64 | 64 | 59 | 6 | 57 | quod/mycroft-core | mycroft/configuration/config.py | Python | is_remote_list | is_remote_list | 35 | 43 | 35 | 35 | 72cc93a5b364e22c3130e31dfeb5adbc66daa518 | bigcode/the-stack | train |
e9546fc097acab619113dba8 | train | function | def translate_remote(config, setting):
"""Translate config names from server to equivalents for mycroft-core.
Args:
config: base config to populate
settings: remote settings to be translated
"""
IGNORED_SETTINGS = ["uuid", "@type", "active", "user", "device"]
for k, v in sett... | def translate_remote(config, setting):
| """Translate config names from server to equivalents for mycroft-core.
Args:
config: base config to populate
settings: remote settings to be translated
"""
IGNORED_SETTINGS = ["uuid", "@type", "active", "user", "device"]
for k, v in setting.items():
if k not in IGNORE... | _remote_list(values):
"""Check if list corresponds to a backend formatted collection of dicts
"""
for v in values:
if not isinstance(v, dict):
return False
if "@type" not in v.keys():
return False
return True
def translate_remote(config, setting):
| 64 | 64 | 206 | 7 | 56 | quod/mycroft-core | mycroft/configuration/config.py | Python | translate_remote | translate_remote | 46 | 71 | 46 | 46 | 45dd769233f113e4f88489cc35790dcfab4e731e | bigcode/the-stack | train |
942cb62f62e7205bfc9be083 | train | function | def _log_old_location_deprecation():
LOG.warning("\n ===============================================\n"
" == DEPRECATION WARNING ==\n"
" ===============================================\n"
f" You still have a config file at {OLD_USER_CONFIG}\n"
... | def _log_old_location_deprecation():
| LOG.warning("\n ===============================================\n"
" == DEPRECATION WARNING ==\n"
" ===============================================\n"
f" You still have a config file at {OLD_USER_CONFIG}\n"
" Note that this locati... | .error("RequestException fetching remote configuration: {}"
.format(str(e)))
self.load_local(cache)
except Exception as e:
LOG.error("Failed to fetch remote configuration: %s" % repr(e),
exc_info=True)
self.load_local(cache)
def _l... | 64 | 64 | 101 | 8 | 56 | quod/mycroft-core | mycroft/configuration/config.py | Python | _log_old_location_deprecation | _log_old_location_deprecation | 185 | 193 | 185 | 185 | 7661633f5b639a72d7c9edd64c650d439be89558 | bigcode/the-stack | train |
34b020347d4f6eda9dd35dc4 | train | class | class Configuration:
"""Namespace for operations on the configuration singleton."""
__config = {} # Cached config
__patch = {} # Patch config that skills can update to override config
@staticmethod
def get(configs=None, cache=True, remote=True):
"""Get configuration
Returns cache... | class Configuration:
| """Namespace for operations on the configuration singleton."""
__config = {} # Cached config
__patch = {} # Patch config that skills can update to override config
@staticmethod
def get(configs=None, cache=True, remote=True):
"""Get configuration
Returns cached instance if availab... | isfile(cache):
location = load_commented_json(cache).get('location')
if location:
setting["location"] = location
# Remove server specific entries
config = {}
translate_remote(config, setting)
for key in config:
... | 238 | 239 | 799 | 3 | 235 | quod/mycroft-core | mycroft/configuration/config.py | Python | Configuration | Configuration | 196 | 323 | 196 | 196 | 58d153bd6f0c9a34cc5d854505fedf77368ffe95 | bigcode/the-stack | train |
974cb6123bb5e53b2ce8ca7f | train | function | def make_metric(_class, other, registry: Registry) -> Metric:
name, doc = other.split("\t", 1)
return _class(
name=name,
documentation=doc,
registry=registry
)
| def make_metric(_class, other, registry: Registry) -> Metric:
| name, doc = other.split("\t", 1)
return _class(
name=name,
documentation=doc,
registry=registry
)
| if type not in METRIC_MAPPING:
raise TypeError("Type {} incorrect".format(
type
))
result.append(
METRIC_MAPPING[type](
other, registry
)
)
return result
def make_metric(_class... | 64 | 64 | 49 | 15 | 48 | belousovalex/prometheus_aioredis_metric_extractor | prometheus_aioredis_metric_extractor/extractor.py | Python | make_metric | make_metric | 116 | 122 | 116 | 116 | a1b14c79da3687de4b90bc84618836f8d8da21e7 | bigcode/the-stack | train |
112a7dba9ced7b489b02eb81 | train | function | def make_metrics_from_source(source_file, registry: Registry) -> list:
if not os.path.exists(source_file):
raise Exception("Not found source file {}".format(
source_file
))
result = []
with open(source_file) as f:
for line in f:
line = line.strip()
... | def make_metrics_from_source(source_file, registry: Registry) -> list:
| if not os.path.exists(source_file):
raise Exception("Not found source file {}".format(
source_file
))
result = []
with open(source_file) as f:
for line in f:
line = line.strip()
if not line:
continue
type, other = line.s... | _manager=TaskManager()
)
self.init_metrics()
return self._registry
def init_metrics(self):
if not self.metrics:
self.metrics = make_metrics_from_source(
self.source, self._registry
)
def make_metrics_from_source(source_file, registry: ... | 64 | 64 | 136 | 15 | 49 | belousovalex/prometheus_aioredis_metric_extractor | prometheus_aioredis_metric_extractor/extractor.py | Python | make_metrics_from_source | make_metrics_from_source | 92 | 113 | 92 | 92 | f8191c9502c3272ee693c12d3eb5b25b5a12b80e | bigcode/the-stack | train |
9d883fdc509a9f4b17cb3118 | train | class | class Extractor(object):
def __init__(
self,
redis_dsn: str,
pool_size: int=100,
redis_timeout: int=10,
host: str='0.0.0.0',
port: int=9000,
registry: Registry=None,
source: str or None=None
):
self.redi... | class Extractor(object):
| def __init__(
self,
redis_dsn: str,
pool_size: int=100,
redis_timeout: int=10,
host: str='0.0.0.0',
port: int=9000,
registry: Registry=None,
source: str or None=None
):
self.redis_dsn = redis_dsn
... | import os
from functools import partial
from aiohttp import web
from aioredis import create_redis_pool
from prometheus_aioredis_client import (
Registry, TaskManager
)
from prometheus_aioredis_client.metrics import (
Metric, Counter, Gauge, Summary, Histogram
)
class Extractor(object):
| 67 | 137 | 459 | 5 | 62 | belousovalex/prometheus_aioredis_metric_extractor | prometheus_aioredis_metric_extractor/extractor.py | Python | Extractor | Extractor | 15 | 90 | 15 | 16 | 8abeef6131451a1c7f4cb7d7a476ed107aecb345 | bigcode/the-stack | train |
e35f11a5447eb9727897452c | train | function | def make_histogram(other, registry: Registry) -> Histogram:
name, buckets, doc = other.split("\t", 2)
buckets = [
(int(b) if b.isdigit() else float(b))
for b in buckets.split(",")
]
return Histogram(
name=name,
documentation=doc,
buckets=buckets,
registry=... | def make_histogram(other, registry: Registry) -> Histogram:
| name, buckets, doc = other.split("\t", 2)
buckets = [
(int(b) if b.isdigit() else float(b))
for b in buckets.split(",")
]
return Histogram(
name=name,
documentation=doc,
buckets=buckets,
registry=registry
)
| result
def make_metric(_class, other, registry: Registry) -> Metric:
name, doc = other.split("\t", 1)
return _class(
name=name,
documentation=doc,
registry=registry
)
def make_histogram(other, registry: Registry) -> Histogram:
| 64 | 64 | 81 | 13 | 51 | belousovalex/prometheus_aioredis_metric_extractor | prometheus_aioredis_metric_extractor/extractor.py | Python | make_histogram | make_histogram | 124 | 135 | 124 | 124 | f6ebd6b0fbdf856b07c15e1b47fe368d7a3d69fb | bigcode/the-stack | train |
9175919a0f2b7ec94c145d68 | train | function | @app.shell_context_processor
def make_shell_context():
return {
'db': db,
'User': User,
'AlertServiceNotifierClient': AlertServiceNotifierClient,
'PaymentProcessor': PaymentProcessor
}
| @app.shell_context_processor
def make_shell_context():
| return {
'db': db,
'User': User,
'AlertServiceNotifierClient': AlertServiceNotifierClient,
'PaymentProcessor': PaymentProcessor
}
| from app import create_app, db # noqa: F401
from app.models import User, PaymentProcessor, AlertServiceNotifierClient
app = create_app()
@app.shell_context_processor
def make_shell_context():
| 43 | 64 | 47 | 10 | 33 | oldcryptogeek/coinjerk-btcp | coinjerk.py | Python | make_shell_context | make_shell_context | 7 | 14 | 7 | 8 | 4f8df83c382dcf8b7a30ca47043006a2a5fd24b1 | bigcode/the-stack | train |
5325b05825658a459aec2b81 | train | class | class E2EModel(ModelBase):
def __init__(self, args):
super(E2EModel, self).__init__()
self.opt = args
self.fbank_model = FbankModel(args)
args.idim = args.fbank_dim
self.e2e = E2E(args)
self.sum = np.zeros(shape=[1, args.fbank_dim], dtype=np.float32)
... | class E2EModel(ModelBase):
| def __init__(self, args):
super(E2EModel, self).__init__()
self.opt = args
self.fbank_model = FbankModel(args)
args.idim = args.fbank_dim
self.e2e = E2E(args)
self.sum = np.zeros(shape=[1, args.fbank_dim], dtype=np.float32)
self.sum_sq = np.zeros(shap... | import logging
import math
import sys
import numpy as np
import six
from progressbar import ProgressBar
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from model.e2e_common import ModelBase, lecun_normal_init_parameters, set_forget_bias_to_one, to_cuda
from model.e2e_model import E2E... | 100 | 256 | 1,107 | 8 | 91 | hajiejue/FP-Code | model/joint_model.py | Python | E2EModel | E2EModel | 17 | 118 | 17 | 17 | fff10f9c8f20f5693747f442c8074cb25fc7ab87 | bigcode/the-stack | train |
6eeb61ab0d4796b3ba758f4c | train | function | def test_minibatch_parse():
"""Simple tests for the minibatch_parse function
Warning: these are not exhaustive
"""
sentences = [["right", "arcs", "only"],
["right", "arcs", "only", "again"],
["left", "arcs", "only"],
["left", "arcs", "only", "again"]]
... | def test_minibatch_parse():
| """Simple tests for the minibatch_parse function
Warning: these are not exhaustive
"""
sentences = [["right", "arcs", "only"],
["right", "arcs", "only", "again"],
["left", "arcs", "only"],
["left", "arcs", "only", "again"]]
deps = minibatch_parse(se... | for pp in partial_parses]
def test_dependencies(name, deps, ex_deps):
"""Tests the provided dependencies match the expected dependencies"""
deps = tuple(sorted(deps))
assert deps == ex_deps, \
"{:} test resulted in dependency list {:}, expected {:}".format(name, deps, ex_deps)
def test_minibatch_... | 76 | 76 | 256 | 7 | 69 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | test_minibatch_parse | test_minibatch_parse | 167 | 184 | 167 | 167 | 85b3dde8cedf9309c35dfce7cd2e128850cd1476 | bigcode/the-stack | train |
8ff1194a67b7592158ae5297 | train | class | class DummyModel:
"""Dummy model for testing the minibatch_parse function
First shifts everything onto the stack and then does exclusively right arcs if the first word of
the sentence is "right", "left" if otherwise.
"""
def predict(self, partial_parses):
return [("RA" if pp.stack[1] is "rig... | class DummyModel:
| """Dummy model for testing the minibatch_parse function
First shifts everything onto the stack and then does exclusively right arcs if the first word of
the sentence is "right", "left" if otherwise.
"""
def predict(self, partial_parses):
return [("RA" if pp.stack[1] is "right" else "LA") if ... | expected, \
"parse test resulted in dependencies {:}, expected {:}".format(dependencies, expected)
assert tuple(sentence) == ("parse", "this", "sentence"), \
"parse test failed: the input sentence should not be modified"
print("parse test passed!")
class DummyModel:
| 63 | 64 | 99 | 4 | 59 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | DummyModel | DummyModel | 150 | 157 | 150 | 150 | b15a7a60cb2fc97beae54a72491dbbf8a9d6a507 | bigcode/the-stack | train |
6fe575f9189137d479f7a555 | train | class | class PartialParse(object):
def __init__(self, sentence):
"""Initializes this partial parse.
Your code should initialize the following fields:
self.stack: The current stack represented as a list with the top of the stack as the
last element of the list.
... | class PartialParse(object):
| def __init__(self, sentence):
"""Initializes this partial parse.
Your code should initialize the following fields:
self.stack: The current stack represented as a list with the top of the stack as the
last element of the list.
self.buffer: The current ... | class PartialParse(object):
| 5 | 143 | 478 | 5 | 0 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | PartialParse | PartialParse | 1 | 60 | 1 | 1 | a4a161b589a44ce1746d47391d0caa4b623d63e8 | bigcode/the-stack | train |
2aa5f88eba0b0741ec301465 | train | function | def test_parse_step():
"""Simple tests for the PartialParse.parse_step function
Warning: these are not exhaustive
"""
test_step("SHIFT", "S", ["ROOT", "the"], ["cat", "sat"], [],
("ROOT", "the", "cat"), ("sat",), ())
test_step("LEFT-ARC", "LA", ["ROOT", "the", "cat"], ["sat"], [],
... | def test_parse_step():
| """Simple tests for the PartialParse.parse_step function
Warning: these are not exhaustive
"""
test_step("SHIFT", "S", ["ROOT", "the"], ["cat", "sat"], [],
("ROOT", "the", "cat"), ("sat",), ())
test_step("LEFT-ARC", "LA", ["ROOT", "the", "cat"], ["sat"], [],
("ROOT", "cat... | resulted in buffer {:}, expected {:}".format(name, buf, ex_buf)
assert deps == ex_deps, \
"{:} test resulted in dependency list {:}, expected {:}".format(name, deps, ex_deps)
print("{:} test passed!".format(name))
def test_parse_step():
| 64 | 64 | 147 | 5 | 59 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | test_parse_step | test_parse_step | 122 | 131 | 122 | 122 | 0630ad43054bbf7b1bcd17df1cf2958c88fb8437 | bigcode/the-stack | train |
ab3b9150ee1a63fb37f71efa | train | function | def test_parse():
"""Simple tests for the PartialParse.parse function
Warning: these are not exhaustive
"""
sentence = ["parse", "this", "sentence"]
dependencies = PartialParse(sentence).parse(["S", "S", "S", "LA", "RA", "RA"])
dependencies = tuple(sorted(dependencies))
expected = (('ROOT', ... | def test_parse():
| """Simple tests for the PartialParse.parse function
Warning: these are not exhaustive
"""
sentence = ["parse", "this", "sentence"]
dependencies = PartialParse(sentence).parse(["S", "S", "S", "LA", "RA", "RA"])
dependencies = tuple(sorted(dependencies))
expected = (('ROOT', 'parse'), ('parse'... | [],
("ROOT", "cat",), ("sat",), (("cat", "the"),))
test_step("RIGHT-ARC", "RA", ["ROOT", "run", "fast"], [], [],
("ROOT", "run",), (), (("run", "fast"),))
def test_parse():
| 64 | 64 | 156 | 4 | 60 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | test_parse | test_parse | 134 | 147 | 134 | 134 | f687bc7fe3ddb0434527ba1b29aa2ffa36bd9001 | bigcode/the-stack | train |
7f5ccc3ac616587786701522 | train | function | def test_step(name, transition, stack, buf, deps,
ex_stack, ex_buf, ex_deps):
"""Tests that a single parse step returns the expected output"""
pp = PartialParse([])
pp.stack, pp.buffer, pp.dependencies = stack, buf, deps
pp.parse_step(transition)
stack, buf, deps = (tuple(pp.stack), t... | def test_step(name, transition, stack, buf, deps,
ex_stack, ex_buf, ex_deps):
| """Tests that a single parse step returns the expected output"""
pp = PartialParse([])
pp.stack, pp.buffer, pp.dependencies = stack, buf, deps
pp.parse_step(transition)
stack, buf, deps = (tuple(pp.stack), tuple(pp.buffer), tuple(sorted(pp.dependencies)))
assert stack == ex_stack, \
"{:... | and not unfinished_parses[i].buffer:
del unfinished_parses[i]
for p in partial_parses:
dependencies.append(p.dependencies)
### END YOUR CODE
return dependencies
def test_step(name, transition, stack, buf, deps,
ex_stack, ex_buf, ex_deps):
| 64 | 64 | 188 | 24 | 39 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | test_step | test_step | 105 | 119 | 105 | 106 | 285a917a87a13321fe85ef64660e4b6cd170d236 | bigcode/the-stack | train |
06d555ee4e05a473a128c599 | train | function | def test_dependencies(name, deps, ex_deps):
"""Tests the provided dependencies match the expected dependencies"""
deps = tuple(sorted(deps))
assert deps == ex_deps, \
"{:} test resulted in dependency list {:}, expected {:}".format(name, deps, ex_deps)
| def test_dependencies(name, deps, ex_deps):
| """Tests the provided dependencies match the expected dependencies"""
deps = tuple(sorted(deps))
assert deps == ex_deps, \
"{:} test resulted in dependency list {:}, expected {:}".format(name, deps, ex_deps)
| otherwise.
"""
def predict(self, partial_parses):
return [("RA" if pp.stack[1] is "right" else "LA") if len(pp.buffer) == 0 else "S"
for pp in partial_parses]
def test_dependencies(name, deps, ex_deps):
| 64 | 64 | 62 | 11 | 53 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | test_dependencies | test_dependencies | 160 | 164 | 160 | 160 | 15aea567d49fb710133998cf1efafafeb0e91b61 | bigcode/the-stack | train |
b738934a51d205ba3cbf6d1c | train | function | def minibatch_parse(sentences, model, batch_size):
"""Parses a list of sentences in minibatches using a model.
Args:
sentences: A list of sentences to be parsed (each sentence is a list of words)
model: The model that makes parsing decisions. It is assumed to have a function
mode... | def minibatch_parse(sentences, model, batch_size):
| """Parses a list of sentences in minibatches using a model.
Args:
sentences: A list of sentences to be parsed (each sentence is a list of words)
model: The model that makes parsing decisions. It is assumed to have a function
model.predict(partial_parses) that takes in a list of P... | ))
### END YOUR CODE
def parse(self, transitions):
"""Applies the provided transitions to this PartialParse
Args:
transitions: The list of transitions in the order they should be applied
Returns:
dependencies: The list of dependencies produced when parsing t... | 113 | 113 | 377 | 12 | 100 | zqyjixiang/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment2/q2_parser_transitions.py | Python | minibatch_parse | minibatch_parse | 63 | 102 | 63 | 63 | 384ecd763ede05eed4c5db71b4274798a5f6beb1 | bigcode/the-stack | train |
a46699cf3d0a43ba687ef8b7 | train | function | def test_shout1():
s = ShoutMessage(True)
s = ShoutMessage(True, None, 1, 1, 1, "message")
print("{}".format(s))
s = YggShout(log=MagicMock())
print("{}".format(s))
main_loop(log=MagicMock())
time.sleep(2)
main_loop(log=MagicMock())
| def test_shout1():
| s = ShoutMessage(True)
s = ShoutMessage(True, None, 1, 1, 1, "message")
print("{}".format(s))
s = YggShout(log=MagicMock())
print("{}".format(s))
main_loop(log=MagicMock())
time.sleep(2)
main_loop(log=MagicMock())
| See /LICENSE for licensing information.
import time
import sys
import requests
import pytest
from mock import patch, MagicMock
import yggscr.exceptions
from yggscr.shout import ShoutMessage, YggShout, main_loop, main as main_shout
def test_shout1():
| 64 | 64 | 84 | 6 | 57 | architek/yggscr | tests/test_shout.py | Python | test_shout1 | test_shout1 | 17 | 25 | 17 | 17 | 19e9356017673e971b6b6c9a156a77cb4ed8dd57 | bigcode/the-stack | train |
0afcb78964f0010b4da04ab3 | train | function | def test_shout_diff():
y = YggShout(log=MagicMock())
y.get_shouts()
y.do_diff() # set last_shouts
time.sleep(2)
y.get_shouts() # set new_shouts
del y.new_shouts[1]
success = False
for removed, shout in y.do_diff():
if removed:
shout.message += "<-- REMOVED"
... | def test_shout_diff():
| y = YggShout(log=MagicMock())
y.get_shouts()
y.do_diff() # set last_shouts
time.sleep(2)
y.get_shouts() # set new_shouts
del y.new_shouts[1]
success = False
for removed, shout in y.do_diff():
if removed:
shout.message += "<-- REMOVED"
success = True
... | , 1, 1, "message")
print("{}".format(s))
s = YggShout(log=MagicMock())
print("{}".format(s))
main_loop(log=MagicMock())
time.sleep(2)
main_loop(log=MagicMock())
def test_shout_diff():
| 64 | 64 | 106 | 6 | 58 | architek/yggscr | tests/test_shout.py | Python | test_shout_diff | test_shout_diff | 28 | 42 | 28 | 28 | 40bc1a5842bd812b7190bb1ccbeb6a7313e26ed2 | bigcode/the-stack | train |
bc0c893795b0f21ed7412090 | train | function | @pytest.mark.skipif(sys.version_info[:2] == (3, 5), reason="python3.5 doesn't have tmp_path")
def test_shout2(tmp_path):
f = tmp_path / "foo.txt"
f.write_text("""
<li use="2" data-id="3087">
<a href="/forum/index.php?members/allain6610.522/" class="avatar avatar--xxs" data-user-id="522" data-xf-init="m... | @pytest.mark.skipif(sys.version_info[:2] == (3, 5), reason="python3.5 doesn't have tmp_path")
def test_shout2(tmp_path):
| f = tmp_path / "foo.txt"
f.write_text("""
<li use="2" data-id="3087">
<a href="/forum/index.php?members/allain6610.522/" class="avatar avatar--xxs" data-user-id="522" data-xf-init="member-tooltip" id="js-XFUniqueId20">
<img src="/forum/data/avatars/s/0/522.jpg?1530742137" alt="Allain6610" class="a... | print("{}".format(s))
main_loop(log=MagicMock())
time.sleep(2)
main_loop(log=MagicMock())
def test_shout_diff():
y = YggShout(log=MagicMock())
y.get_shouts()
y.do_diff() # set last_shouts
time.sleep(2)
y.get_shouts() # set new_shouts
del y.new_shouts[1]
success = Fals... | 171 | 171 | 571 | 36 | 134 | architek/yggscr | tests/test_shout.py | Python | test_shout2 | test_shout2 | 45 | 68 | 45 | 46 | c4112d10a22298dccf727aa7e6ee1d025f68ed22 | bigcode/the-stack | train |
e6c6993f9665d46ce9d27979 | train | function | def test_shout_failures():
# Long test of 1 retry: 16+31 (47s)
# Long test of 2 retries: 16+31+46 (93s)
print("Testing connection failure for 47s")
with patch("yggscr.shout.YggShout.get_shouts", side_effect=requests.exceptions.Timeout):
with pytest.raises(yggscr.exceptions.YggException):
... | def test_shout_failures():
# Long test of 1 retry: 16+31 (47s)
# Long test of 2 retries: 16+31+46 (93s)
| print("Testing connection failure for 47s")
with patch("yggscr.shout.YggShout.get_shouts", side_effect=requests.exceptions.Timeout):
with pytest.raises(yggscr.exceptions.YggException):
main_loop(log=MagicMock(), NTRY=N_MAXTRIES)
assert 0
main_loop(log=MagicMock, NTRY=2)
| assert mock_exit.call_args[0][0] == 1
N_MAXTRIES = 1
def test_shout_failures():
# Long test of 1 retry: 16+31 (47s)
# Long test of 2 retries: 16+31+46 (93s)
| 64 | 64 | 122 | 43 | 20 | architek/yggscr | tests/test_shout.py | Python | test_shout_failures | test_shout_failures | 74 | 82 | 74 | 76 | d06de8443b02d85fae1aead30884ad28fc5c0a63 | bigcode/the-stack | train |
e12107ecdff11da651ada82a | train | class | class ApiErrorsMixin:
"""
Mixin that transforms Django and Python exceptions into rest_framework ones.
without the mixin, they return 500 status code which is not desired.
"""
expected_exceptions = {
ValueError: rest_exceptions.ValidationError,
ValidationError: rest_exceptions.Valid... | class ApiErrorsMixin:
| """
Mixin that transforms Django and Python exceptions into rest_framework ones.
without the mixin, they return 500 status code which is not desired.
"""
expected_exceptions = {
ValueError: rest_exceptions.ValidationError,
ValidationError: rest_exceptions.ValidationError,
Pe... |
from kaffepause.api.errors import get_error_message
# from rest_framework.permissions import IsAuthenticated
# from rest_framework_simplejwt.authentication import JWTAuthentication
#
# class ApiAuthMixin:
# authentication_classes = (JWTAuthentication, )
# permission_classes = (IsAuthenticated, )
class Ap... | 64 | 64 | 147 | 5 | 59 | Eirsteir/kaffepause | kaffepause/api/mixins.py | Python | ApiErrorsMixin | ApiErrorsMixin | 18 | 37 | 18 | 18 | ad6a0e798380acd6b997376234bbff84b7d1704e | bigcode/the-stack | train |
b6f0ccbb76f825a8697a9c4c | train | function | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.scope == 'builtin':
return 'z' + definition.name
if definition.name.startswith("_"):
# It's a 'hidden' func, put it next last
return 'y' +... | def _sort_text(definition):
| """ Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.scope == 'builtin':
return 'z' + definition.name
if definition.name.startswith("_"):
# It's a 'hidden' func, put it next last
return 'y' + definition.name
# Else... | ,
'kind': _kind(d),
'detail': '{0} {1}'.format(d.scope or "", d.name),
'documentation': doc or "",
'sortText': _sort_text(d)})
definitions = new_definitions
return definitions or None
def _sort_text(definition):
| 64 | 64 | 98 | 7 | 56 | ferozco/python-language-server | pyls/plugins/rope_completion.py | Python | _sort_text | _sort_text | 51 | 63 | 51 | 51 | b977d6e98e99caf292612f036981229e081f7718 | bigcode/the-stack | train |
5f3298ddf15b488adaeb17df | train | function | @hookimpl
def pyls_settings():
# Default rope_completion to disabled
return {'plugins': {'rope_completion': {'enabled': False}}}
| @hookimpl
def pyls_settings():
# Default rope_completion to disabled
| return {'plugins': {'rope_completion': {'enabled': False}}}
| # Copyright 2017 Palantir Technologies, Inc.
import logging
from rope.contrib.codeassist import code_assist, sorted_proposals
from pyls import hookimpl, lsp
log = logging.getLogger(__name__)
@hookimpl
def pyls_settings():
# Default rope_completion to disabled
| 64 | 64 | 32 | 17 | 47 | ferozco/python-language-server | pyls/plugins/rope_completion.py | Python | pyls_settings | pyls_settings | 11 | 14 | 11 | 13 | 3eae31ef6a7a854a8bc598d59dd292fa9c6c2256 | bigcode/the-stack | train |
e0d13576647c35a463421341 | train | function | @hookimpl
def pyls_completions(document, position):
# Rope is a bit rubbish at completing module imports, so we'll return None
word = document.word_at_position({
# The -1 should really be trying to look at the previous word, but that might be quite expensive
# So we only skip import completions ... | @hookimpl
def pyls_completions(document, position):
# Rope is a bit rubbish at completing module imports, so we'll return None
| word = document.word_at_position({
# The -1 should really be trying to look at the previous word, but that might be quite expensive
# So we only skip import completions when the cursor is one space after `import`
'line': position['line'], 'character': max(position['character'] - 1, 0),
}... | s import hookimpl, lsp
log = logging.getLogger(__name__)
@hookimpl
def pyls_settings():
# Default rope_completion to disabled
return {'plugins': {'rope_completion': {'enabled': False}}}
@hookimpl
def pyls_completions(document, position):
# Rope is a bit rubbish at completing module imports, so we'll ret... | 79 | 79 | 265 | 31 | 48 | ferozco/python-language-server | pyls/plugins/rope_completion.py | Python | pyls_completions | pyls_completions | 17 | 48 | 17 | 19 | 7048562f8a1a319c60f7defe86c3b6e556ce611a | bigcode/the-stack | train |
bd1bb385123309fde2ce3ec6 | train | function | def _kind(d):
""" Return the VSCode type """
MAP = {
'none': lsp.CompletionItemKind.Value,
'type': lsp.CompletionItemKind.Class,
'tuple': lsp.CompletionItemKind.Class,
'dict': lsp.CompletionItemKind.Class,
'dictionary': lsp.CompletionItemKind.Class,
'function': ls... | def _kind(d):
| """ Return the VSCode type """
MAP = {
'none': lsp.CompletionItemKind.Value,
'type': lsp.CompletionItemKind.Class,
'tuple': lsp.CompletionItemKind.Class,
'dict': lsp.CompletionItemKind.Class,
'dictionary': lsp.CompletionItemKind.Class,
'function': lsp.CompletionIt... | )})
definitions = new_definitions
return definitions or None
def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.scope == 'builtin':
return 'z' + definition.name
if definition.name.startswith("_"... | 117 | 117 | 391 | 5 | 111 | ferozco/python-language-server | pyls/plugins/rope_completion.py | Python | _kind | _kind | 66 | 101 | 66 | 66 | 35e667959e75d5a56a97e37318e6ab4df4f96bd3 | bigcode/the-stack | train |
46ab8ee65990ca7580f763e0 | train | class | class Tests:
level_created = (
"Successfully created level",
"Failed to create level"
)
spawner_entity_created = (
"Spawner entity created successfully",
"Failed to create spawner entity"
)
surface_entity_created = (
"Surface entity created successfully",
... | class Tests:
| level_created = (
"Successfully created level",
"Failed to create level"
)
spawner_entity_created = (
"Spawner entity created successfully",
"Failed to create spawner entity"
)
surface_entity_created = (
"Surface entity created successfully",
"Failed t... | """
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
class Tests:
| 49 | 64 | 122 | 3 | 46 | pollend/o3de | AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py | Python | Tests | Tests | 9 | 29 | 9 | 9 | 2b981c1fd789ac7080cb9a358899d907adb06d24 | bigcode/the-stack | train |
3815ba910d8f76bbba69cfd1 | train | function | def DynamicSliceInstanceSpawner_External_E2E():
"""
Summary:
A new temporary level is created. Surface for planting is created. Simple vegetation area is created using
Dynamic Slice Instance Spawner type using external assets.
Expected Behavior:
Instances plant as expected in the assigned area.... | def DynamicSliceInstanceSpawner_External_E2E():
| """
Summary:
A new temporary level is created. Surface for planting is created. Simple vegetation area is created using
Dynamic Slice Instance Spawner type using external assets.
Expected Behavior:
Instances plant as expected in the assigned area.
Test Steps:
1) Create level
2) C... | """
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
class Tests:
level_created = (
"Successfully created level",
"Failed to create level"
... | 179 | 256 | 1,167 | 11 | 168 | pollend/o3de | AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py | Python | DynamicSliceInstanceSpawner_External_E2E | DynamicSliceInstanceSpawner_External_E2E | 32 | 135 | 32 | 32 | 85438095753415fda35c1fd75e857a29a8a46412 | bigcode/the-stack | train |
2a27f679a41001d1fb7dd880 | train | function | def test_vec_vec_add():
ks_str = """(edef add Integer (Tuple Integer Integer))
(def test (Vec Integer) ((x : (Vec Integer)) (y : (Vec Integer)))
(build (size x) (lam (i : Integer) (add (index i x) (index i y))))
)"""
py_out = translate_and_import(__file__, ks_str, "common")
x = np.array([0, 1, 2, 3, 4, 5]... | def test_vec_vec_add():
| ks_str = """(edef add Integer (Tuple Integer Integer))
(def test (Vec Integer) ((x : (Vec Integer)) (y : (Vec Integer)))
(build (size x) (lam (i : Integer) (add (index i x) (index i y))))
)"""
py_out = translate_and_import(__file__, ks_str, "common")
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([-1, ... | import numpy as np
from ksc.utils import translate_and_import
def test_vec_vec_add():
| 20 | 64 | 165 | 6 | 13 | tomjaguarpaw/knossos-ksc | test/python/test_build.py | Python | test_vec_vec_add | test_vec_vec_add | 5 | 14 | 5 | 5 | 3b8b34cec52c98c5dea1e179eb10e5c45168a4d1 | bigcode/the-stack | train |
fe6e77f0ebc6be54fb9b035b | train | function | def run():
program = IntCode(parseFile('day13.txt'))
# every three output instructions specify the x position (distance from the left), y position (distance from the top), and tile id. The tile id is
# 0 is an empty tile. No game object appears in this tile.
# 1 is a wall tile. Walls are indestructi... | def run():
| program = IntCode(parseFile('day13.txt'))
# every three output instructions specify the x position (distance from the left), y position (distance from the top), and tile id. The tile id is
# 0 is an empty tile. No game object appears in this tile.
# 1 is a wall tile. Walls are indestructible barriers... | from IntCode import IntCode, parseFile
def run():
| 13 | 64 | 155 | 3 | 9 | TseIvan/AdventOfCode2019 | day13.py | Python | run | run | 2 | 16 | 2 | 2 | 1cbe7f6be30c9e7564ca4e6f969269ac987a11c7 | bigcode/the-stack | train |
8cf8ff1ab9e27393c4081abc | train | function | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe1,
"type": "MinMaxScaler",
"columns": ["Distance"],
"is_combined": False,
"target_col": "Capitals",
"categorical_columns": ["Capi... | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe1,
"type": "MinMaxScaler",
"columns": ["Distance"],
"is_combined": False,
"target_col": "Capitals",
"categorical_columns": ["Capi... | scaler = Scaler()
scaler.execute(params=test_input)
if "Distance" in test_input["train_df"].keys():
assert test_input["train_df"]["Distance"].values.all() >= 0
assert test_input["train_df"]["Distance"].values.all() <= 1
else:
assert test_input["train_df"]["Negatives"].values.all(... | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe1,
"type": "MinMaxScaler",
"columns": ["Distance"],
"is_combined": False,
"target_col": "Capitals",
"categorical_columns": ["Capi... | 277 | 113 | 377 | 277 | 0 | DevayaniShivankar/preprocessy | tests/test_scaling.py | Python | test_MinMaxScaler_output | test_MinMaxScaler_output | 96 | 149 | 96 | 141 | 2132a3d19b10b519ae4e45deb17e62597ec87844 | bigcode/the-stack | train |
d270785a3e8a4bcecea6be74 | train | function | @pytest.mark.parametrize(
"test_input, error",
[
({}, ValueError),
({"train_df": dataframe1}, TypeError),
({"train_df": array}, TypeError),
({"train_df": dataframe1, "type": [5]}, TypeError),
(
{
"train_df": dataframe1,
"type": ... | @pytest.mark.parametrize(
"test_input, error",
[
({}, ValueError),
({"train_df": dataframe1}, TypeError),
({"train_df": array}, TypeError),
({"train_df": dataframe1, "type": [5]}, TypeError),
(
{
"train_df": dataframe1,
"type": ... | with pytest.raises(error):
scaler = Scaler()
scaler.execute(params=test_input)
| @pytest.mark.parametrize(
"test_input, error",
[
({}, ValueError),
({"train_df": dataframe1}, TypeError),
({"train_df": array}, TypeError),
({"train_df": dataframe1, "type": [5]}, TypeError),
(
{
"train_df": dataframe1,
"type": ... | 164 | 64 | 183 | 164 | 0 | DevayaniShivankar/preprocessy | tests/test_scaling.py | Python | test_incorrect_input_type | test_incorrect_input_type | 13 | 42 | 13 | 39 | efdd94f007515eb6be0abec5e11e830c0ee47205 | bigcode/the-stack | train |
c019523d5937a885a3e4fe91 | train | function | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe2,
"type": "BinaryScaler",
"columns": ["Negatives"],
"is_combined": True,
"threshold": {"Negatives": -10},
"target_col": "Test",
... | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe2,
"type": "BinaryScaler",
"columns": ["Negatives"],
"is_combined": True,
"threshold": {"Negatives": -10},
"target_col": "Test",
... | scaler = Scaler()
scaler.execute(params=test_input)
assert (
test_input["train_df"]["Negatives"].values.any() == 1
or test_input["train_df"]["Negatives"].values.any() == 0
)
assert not (
test_input["train_df"]["Negatives"]
.between(0, 1, inclusive=False)
.any(... | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe2,
"type": "BinaryScaler",
"columns": ["Negatives"],
"is_combined": True,
"threshold": {"Negatives": -10},
"target_col": "Test",
... | 197 | 99 | 333 | 197 | 0 | DevayaniShivankar/preprocessy | tests/test_scaling.py | Python | test_BinaryScaler_output | test_BinaryScaler_output | 45 | 93 | 45 | 78 | ec060c392db5b30b1dc610eac17c00bda59d1e79 | bigcode/the-stack | train |
74ddb002d458d6eaccc6b0c8 | train | function | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe1,
"type": "StandardScaler",
"columns": ["Distance"],
"is_combined": False,
"target_col": "Other Capitals",
"categorical_columns"... | @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe1,
"type": "StandardScaler",
"columns": ["Distance"],
"is_combined": False,
"target_col": "Other Capitals",
"categorical_columns"... | scaler = Scaler()
scaler.execute(params=test_input)
if "Distance" in test_input["train_df"].keys():
assert round(test_input["train_df"]["Distance"][0], 5) == 1.08006
else:
assert round(test_input["train_df"]["Negatives"][0], 5) == 0.57771
| @pytest.mark.parametrize(
"test_input",
[
(
{
"train_df": dataframe1,
"type": "StandardScaler",
"columns": ["Distance"],
"is_combined": False,
"target_col": "Other Capitals",
"categorical_columns"... | 273 | 105 | 350 | 273 | 0 | DevayaniShivankar/preprocessy | tests/test_scaling.py | Python | test_StandardScaler_output | test_StandardScaler_output | 152 | 203 | 152 | 197 | 7b0a241853b58f5aec768552670f360c814395fc | bigcode/the-stack | train |
55e50d6e404b37436ef3d922 | train | class | class TestBoundingBox(unittest.TestCase):
def test_BoundingBox(self):
bb = BoundingBox(cv2.imread('../../../../test_images/testface_1.jpg'))
self.assertIsNotNone(bb.get_bounding_box())
def test_assert_off_axis_left_upper(self):
bb = BoundingBox(cv2.imread('../../../../test_images/testfa... | class TestBoundingBox(unittest.TestCase):
| def test_BoundingBox(self):
bb = BoundingBox(cv2.imread('../../../../test_images/testface_1.jpg'))
self.assertIsNotNone(bb.get_bounding_box())
def test_assert_off_axis_left_upper(self):
bb = BoundingBox(cv2.imread('../../../../test_images/testface_1_offaxis_left_upper.jpg'))
wit... | import unittest
import cv2
from src.components.BoundingBox.BoundingBox import BoundingBox
class TestBoundingBox(unittest.TestCase):
| 28 | 94 | 316 | 8 | 19 | jinwoo1225/HAiR | src/components/BoundingBox/__test__/test_BoundingBox.py | Python | TestBoundingBox | TestBoundingBox | 8 | 36 | 8 | 8 | 93b94483dfd9d85f10a4b959e1b9ca5585e35fb8 | bigcode/the-stack | train |
935b2c5768a0a8bc2a9617f6 | train | class | class WemoMixin(object):
"""All wemo's have a model and serial number in common."""
serial_number = ndb.StringProperty(required=True)
model = ndb.StringProperty()
@classmethod
@device.static_command
def scan(cls):
event = {'type': 'wemo', 'command': 'scan'}
pushrpc.send_event(event)
def handle_e... | class WemoMixin(object):
| """All wemo's have a model and serial number in common."""
serial_number = ndb.StringProperty(required=True)
model = ndb.StringProperty()
@classmethod
@device.static_command
def scan(cls):
event = {'type': 'wemo', 'command': 'scan'}
pushrpc.send_event(event)
def handle_event(self, event):
se... | """Philips hue integration."""
from google.appengine.ext import ndb
from appengine import device, pushrpc
class WemoMixin(object):
| 30 | 64 | 113 | 6 | 23 | tomwilkie/awesomation | src/appengine/devices/wemo.py | Python | WemoMixin | WemoMixin | 8 | 22 | 8 | 8 | 45fba1cee4861f7dfdab9b9b392b32537cf786e0 | bigcode/the-stack | train |
2d84e5d0a4e1c92ebc8d0608 | train | class | @device.register('wemo_switch')
class WemoSwitch(device.Switch, WemoMixin):
"""A Wemo switch."""
def get_capabilities(self):
return super(WemoSwitch, self).get_capabilities() + ['SCAN']
def sync(self):
"""Update the state of a light."""
event = {'type': 'wemo',
'command': 'set_state',
... | @device.register('wemo_switch')
class WemoSwitch(device.Switch, WemoMixin):
| """A Wemo switch."""
def get_capabilities(self):
return super(WemoSwitch, self).get_capabilities() + ['SCAN']
def sync(self):
"""Update the state of a light."""
event = {'type': 'wemo',
'command': 'set_state',
'serial_number': self.serial_number,
'state': self.... | ):
return ['CLIMATE']
def handle_event(self, event):
"""Handle a device update event."""
WemoMixin.handle_event(self, event)
self.real_occupied_state_change(event['state'])
@device.register('wemo_switch')
class WemoSwitch(device.Switch, WemoMixin):
| 63 | 64 | 139 | 19 | 44 | tomwilkie/awesomation | src/appengine/devices/wemo.py | Python | WemoSwitch | WemoSwitch | 41 | 59 | 41 | 42 | d396f75b918ad999c86774ace3958cf679fdb5ff | bigcode/the-stack | train |
2ab9e7249d4ea089c38b5255 | train | class | @device.register('wemo_motion')
class WemoMotion(device.Device, WemoMixin, device.DetectorMixin):
"""A Wemo Motion Sensor"""
def get_capabilities(self):
return ['OCCUPIED', 'SCAN']
def get_categories(self):
return ['CLIMATE']
def handle_event(self, event):
"""Handle a device update event."""
... | @device.register('wemo_motion')
class WemoMotion(device.Device, WemoMixin, device.DetectorMixin):
| """A Wemo Motion Sensor"""
def get_capabilities(self):
return ['OCCUPIED', 'SCAN']
def get_categories(self):
return ['CLIMATE']
def handle_event(self, event):
"""Handle a device update event."""
WemoMixin.handle_event(self, event)
self.real_occupied_state_change(event['state'])
| rpc.send_event(event)
def handle_event(self, event):
self.device_name = event['name']
self.serial_number = event['serial_number']
self.model = event['model']
@device.register('wemo_motion')
class WemoMotion(device.Device, WemoMixin, device.DetectorMixin):
| 64 | 64 | 99 | 24 | 40 | tomwilkie/awesomation | src/appengine/devices/wemo.py | Python | WemoMotion | WemoMotion | 25 | 38 | 25 | 26 | b14d81795c807089c7055d2c618b1915c5923f9d | bigcode/the-stack | train |
13ec90304b9d35e90ef91489 | train | function | def pyramid(y_vals, h):
# y_vals: data of isocontours, e.g. areas of isocontours, see Table 4.3 for example
# h: difference between isocontours, regular space, see Table 4.3 for example
import numpy as np
# sort out a_0 and a_n, calculate the first term, 1/3*delta_z*(a_0+a_n)
minus_a0 = np.delete(y_val... | def pyramid(y_vals, h):
# y_vals: data of isocontours, e.g. areas of isocontours, see Table 4.3 for example
# h: difference between isocontours, regular space, see Table 4.3 for example
| import numpy as np
# sort out a_0 and a_n, calculate the first term, 1/3*delta_z*(a_0+a_n)
minus_a0 = np.delete(y_vals, 0)
minus_a0_an = np.delete(minus_a0, -1)
first_term = y_vals[0] + y_vals[-1]
# multiply the the first part of second term from sorted list: second_term_1 = (delta_z/3) * (2a1+2a2+... | def pyramid(y_vals, h):
# y_vals: data of isocontours, e.g. areas of isocontours, see Table 4.3 for example
# h: difference between isocontours, regular space, see Table 4.3 for example
| 61 | 100 | 336 | 61 | 0 | datasolver/reservoir-engineering | Unit 4 Volumetrics/functions/pyramidal.py | Python | pyramid | pyramid | 1 | 22 | 1 | 3 | 175582a74d8aae8af4fef289e8109c28774ed517 | bigcode/the-stack | train |
fd48111bb7f7fc862b6e02c3 | train | class | class TomitasGrammarsMods:
"""
Class containing modified versions of automata from paper:
Tomita, M. (1982).
Dynamic Construction of Finite Automata from examples using Hill-climbing.
Proceedings of the Fourth Annual Conference of the Cognitive Science Society
(p./pp. 105-... | class TomitasGrammarsMods:
| """
Class containing modified versions of automata from paper:
Tomita, M. (1982).
Dynamic Construction of Finite Automata from examples using Hill-climbing.
Proceedings of the Fourth Annual Conference of the Cognitive Science Society
(p./pp. 105--108), Ann Arbor, Michigan.... | _types.symbol import SymbolStr
from pythautomata.base_types.alphabet import Alphabet
from pythautomata.automata.deterministic_finite_automaton import \
DeterministicFiniteAutomaton
from pythautomata.model_comparators.hopcroft_karp_comparison_strategy import HopcroftKarpComparisonStrategy as HopcroftKarpComparisonSt... | 119 | 119 | 398 | 8 | 111 | neuralchecker/pythautomata | pythautomata/automata_definitions/tomitas_grammars_modifications.py | Python | TomitasGrammarsMods | TomitasGrammarsMods | 13 | 55 | 13 | 13 | 96cb6c80c4a8b4ecaceb86839512671f9d65a74f | bigcode/the-stack | train |
efe51e2f3d473eeee0c04942 | train | class | class RunnerDBError(Exception):
pass
| class RunnerDBError(Exception):
| pass
| hexlify
from tempfile import NamedTemporaryFile
from collections import namedtuple
import arrow
import dataset
import sqlalchemy
from .tcx import RunnerTCX
log = logging.getLogger(__name__)
Activity = namedtuple('Activity', ['start_date', 'tcx'])
class RunnerDBError(Exception):
| 63 | 64 | 9 | 6 | 57 | crisidev/runnerdash | runnerdash/db.py | Python | RunnerDBError | RunnerDBError | 19 | 20 | 19 | 19 | b41b364ab95c74e688b133ddc2f3a87ce3412b61 | bigcode/the-stack | train |
c02363a41a9ba5a886e3f9e9 | train | class | class RunnerDB(object):
TABLE_ACTIVITIES = 'activities'
TABLE_SETTINGS = 'settings'
TABLE_HEART_RATE_VALUES = 'heart_rate_values'
TABLE_TRACK_POINTS = 'track_points'
def __init__(self, storage_path):
self.storage_path = storage_path
log.debug("initalizing db connection ot sqlite:///... | class RunnerDB(object):
| TABLE_ACTIVITIES = 'activities'
TABLE_SETTINGS = 'settings'
TABLE_HEART_RATE_VALUES = 'heart_rate_values'
TABLE_TRACK_POINTS = 'track_points'
def __init__(self, storage_path):
self.storage_path = storage_path
log.debug("initalizing db connection ot sqlite:///%s", self.storage_path)
... | # -*- coding: utf-8 -*-
import os
import logging
from binascii import hexlify
from tempfile import NamedTemporaryFile
from collections import namedtuple
import arrow
import dataset
import sqlalchemy
from .tcx import RunnerTCX
log = logging.getLogger(__name__)
Activity = namedtuple('Activity', ['start_date', 'tcx'])... | 90 | 256 | 1,736 | 5 | 84 | crisidev/runnerdash | runnerdash/db.py | Python | RunnerDB | RunnerDB | 23 | 243 | 23 | 23 | d05a180eca7ade4010c0b62df7bff6fff9363459 | bigcode/the-stack | train |
dcdf235974e805cb241a2412 | train | function | def parse_args():
parser = argparse.ArgumentParser(
description='MMDet test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('--checkpoint',default=checkpoint_path, help='checkpoint file')
parser.add_argument('--out', help='output result file i... | def parse_args():
| parser = argparse.ArgumentParser(
description='MMDet test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('--checkpoint',default=checkpoint_path, help='checkpoint file')
parser.add_argument('--out', help='output result file in pickle format')
... | import argparse
import os
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from fuse_conv_bn import fuse_module
from mmdet.apis import multi_gpu_test, single_gpu_test
from ... | 119 | 143 | 479 | 4 | 115 | crazyhathello/r3det_piglet-tracking | tools/start_inference.py | Python | parse_args | parse_args | 17 | 67 | 17 | 17 | 51f6267bb863c49f76d5aca7a2775a9203affe89 | bigcode/the-stack | train |
2e80da72e2afd38df6868713 | train | function | def main():
args = parse_args()
assert args.out or args.eval or args.format_only or args.show \
or args.show_dir, \
('Please specify at least one operation (save/eval/format/show the '
'results / save the results) with the argument "--out", "--eval"'
', "--format-only", "--sho... | def main():
| args = parse_args()
assert args.out or args.eval or args.format_only or args.show \
or args.show_dir, \
('Please specify at least one operation (save/eval/format/show the '
'results / save the results) with the argument "--out", "--eval"'
', "--format-only", "--show" or "--sho... | =0.3,
help='score threshold (default: 0.3)')
parser.add_argument(
'--gpu-collect',
action='store_true',
help='whether to use gpu to collect results.')
parser.add_argument(
'--tmpdir',
help='tmp directory used for collecting results from multiple '
'workers... | 195 | 195 | 653 | 3 | 191 | crazyhathello/r3det_piglet-tracking | tools/start_inference.py | Python | main | main | 70 | 146 | 70 | 70 | ba8cb9f70c3cbe69e868ce749f54dae8fd56919b | bigcode/the-stack | train |
55f18c66d54bf5bd22b8adba | train | function | async def test_ohlcv(exchange, symbol):
if exchange.has['fetchOHLCV']:
delay = int(exchange.rateLimit / 1000)
await asyncio.sleep(delay)
ohlcvs = await exchange.fetch_ohlcv(symbol)
dump(green(exchange.id), 'fetched', green(len(ohlcvs)), 'OHLCVs')
else:
dump(yellow(exchang... | async def test_ohlcv(exchange, symbol):
| if exchange.has['fetchOHLCV']:
delay = int(exchange.rateLimit / 1000)
await asyncio.sleep(delay)
ohlcvs = await exchange.fetch_ohlcv(symbol)
dump(green(exchange.id), 'fetched', green(len(ohlcvs)), 'OHLCVs')
else:
dump(yellow(exchange.id), 'fetching OHLCV not supported')
| 'N/A'),
'askVolume: ' + str(orderbook['asks'][0][1] if len(orderbook['asks']) else 'N/A'))
else:
dump(yellow(exchange.id), 'fetch_order_book() supported')
# ------------------------------------------------------------------------------
async def test_ohlcv(exchange, symbol):
| 63 | 64 | 94 | 10 | 53 | dnlsngr/ccxt | python/test/test_async.py | Python | test_ohlcv | test_ohlcv | 137 | 144 | 137 | 137 | 627cd4e44e966d6939625c2025da854fc3b7c91f | bigcode/the-stack | train |
2a39063033658e2063c6bee7 | train | function | def is_active_symbol(exchange, symbol):
return ('.' not in symbol) and (('active' not in exchange.markets[symbol]) or (exchange.markets[symbol]['active']))
| def is_active_symbol(exchange, symbol):
| return ('.' not in symbol) and (('active' not in exchange.markets[symbol]) or (exchange.markets[symbol]['active']))
| argv.token_bucket:
await test_tickers_async(exchange)
if argv.token_bucket:
await test_l2_order_books_async(exchange)
# ------------------------------------------------------------------------------
def get_active_symbols(exchange):
return [symbol for symbol in exchange.symbols if is_active_... | 63 | 64 | 40 | 8 | 55 | dnlsngr/ccxt | python/test/test_async.py | Python | is_active_symbol | is_active_symbol | 174 | 175 | 174 | 174 | f674948b2b450d67777977554c6d9296406ed1f3 | bigcode/the-stack | train |
f78719107fc85732245017e3 | train | function | async def test_ticker(exchange, symbol):
if exchange.has['fetchTicker']:
delay = int(exchange.rateLimit / 1000)
await asyncio.sleep(delay)
ticker = await exchange.fetch_ticker(symbol)
dump(
green(exchange.id),
green(symbol),
'ticker',
t... | async def test_ticker(exchange, symbol):
| if exchange.has['fetchTicker']:
delay = int(exchange.rateLimit / 1000)
await asyncio.sleep(delay)
ticker = await exchange.fetch_ticker(symbol)
dump(
green(exchange.id),
green(symbol),
'ticker',
ticker['datetime'],
'high: ' +... | with symbol loading l2 order book]'),
' Symbol failed to load: {0}, ERROR: {1}'.format(symbol, orderbook))
dump(green(exchange.id), 'fetched', green(len(list(orderbooks))), 'order books')
# ------------------------------------------------------------------------------
async def test_ticker(... | 63 | 64 | 148 | 9 | 54 | dnlsngr/ccxt | python/test/test_async.py | Python | test_ticker | test_ticker | 205 | 221 | 205 | 205 | b90af5308aa796d5de6c34f5d7b2244589788f1b | bigcode/the-stack | train |
d1444f1514120b6a639e0043 | train | function | def green(s):
return style(s, '\033[92m')
| def green(s):
| return style(s, '\033[92m')
| the local folder uninstall it first by running the following commands:\npip uninstall ccxt\npip3 uninstall ccxt\n\n')
# ------------------------------------------------------------------------------
# string coloring functions
def style(s, style):
return str(s) # style + str (s) + '\033[0m'
def green(s):
| 64 | 64 | 15 | 4 | 60 | dnlsngr/ccxt | python/test/test_async.py | Python | green | green | 63 | 64 | 63 | 63 | 7f8fe6623f8a33f93bd7e61675073496697b1f0a | bigcode/the-stack | train |
9c0dea56c8ef69abb8beafec | train | function | def dump_error(*args):
string = ' '.join([str(arg) for arg in args])
print(string)
sys.stderr.write(string + "\n")
| def dump_error(*args):
| string = ' '.join([str(arg) for arg in args])
print(string)
sys.stderr.write(string + "\n")
| return style(s, '\033[1m')
def underline(s):
return style(s, '\033[4m')
# print a colored string
def dump(*args):
print(' '.join([str(arg) for arg in args]))
# print an error string
def dump_error(*args):
| 64 | 64 | 34 | 6 | 57 | dnlsngr/ccxt | python/test/test_async.py | Python | dump_error | dump_error | 97 | 100 | 97 | 97 | 9ce57835a23e82b0c36662f6c9fa79b9f26c1e42 | bigcode/the-stack | train |
8ddb4763a48132b23c102e81 | train | function | def underline(s):
return style(s, '\033[4m')
| def underline(s):
| return style(s, '\033[4m')
| def yellow(s):
return style(s, '\033[93m')
def red(s):
return style(s, '\033[91m')
def pink(s):
return style(s, '\033[95m')
def bold(s):
return style(s, '\033[1m')
def underline(s):
| 64 | 64 | 15 | 4 | 60 | dnlsngr/ccxt | python/test/test_async.py | Python | underline | underline | 87 | 88 | 87 | 87 | 3cd59c934eefe307b180b919fbc1f0f02cbbc6c1 | bigcode/the-stack | train |
846a6a6e0f4d844db9fbf474 | train | function | def pink(s):
return style(s, '\033[95m')
| def pink(s):
| return style(s, '\033[95m')
| def green(s):
return style(s, '\033[92m')
def blue(s):
return style(s, '\033[94m')
def yellow(s):
return style(s, '\033[93m')
def red(s):
return style(s, '\033[91m')
def pink(s):
| 64 | 64 | 15 | 4 | 60 | dnlsngr/ccxt | python/test/test_async.py | Python | pink | pink | 79 | 80 | 79 | 79 | 9a3ada8d9b7feb4aa514acc5adb5db641981768a | bigcode/the-stack | train |
8b59231bcfdaa5738de5b696 | train | function | def red(s):
return style(s, '\033[91m')
| def red(s):
| return style(s, '\033[91m')
| # style + str (s) + '\033[0m'
def green(s):
return style(s, '\033[92m')
def blue(s):
return style(s, '\033[94m')
def yellow(s):
return style(s, '\033[93m')
def red(s):
| 64 | 64 | 15 | 4 | 60 | dnlsngr/ccxt | python/test/test_async.py | Python | red | red | 75 | 76 | 75 | 75 | 5d34a2c23ca9d4277a4497d071ce4c8a84571ea7 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.