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
6f48bb415d5f80224d4c136d
train
function
def image_to_string(image, lang=None, builder=None): if builder is None: builder = builders.TextBuilder() handle = tesseract_raw.init(lang=lang) lvl_line = tesseract_raw.PageIteratorLevel.TEXTLINE lvl_word = tesseract_raw.PageIteratorLevel.WORD try: # XXX(Jflesch): Issue #51: ...
def image_to_string(image, lang=None, builder=None):
if builder is None: builder = builders.TextBuilder() handle = tesseract_raw.init(lang=lang) lvl_line = tesseract_raw.PageIteratorLevel.TEXTLINE lvl_word = tesseract_raw.PageIteratorLevel.WORD try: # XXX(Jflesch): Issue #51: # Tesseract TessBaseAPIRecognize() may segfault wh...
Orientation.PAGE_RIGHT: 90, tesseract_raw.Orientation.PAGE_DOWN: 180, tesseract_raw.Orientation.PAGE_LEFT: 270, }[os["orientation"]] return {"angle": orientation, "confidence": os["confidence"]} finally: tesseract_raw.cleanup(handle) def get_name(): return "Tess...
173
173
578
12
161
xingkong0113/bookworm
bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py
Python
image_to_string
image_to_string
89
158
89
89
084de42743fd3d56f0ecf29c191bb7fa92f485c0
bigcode/the-stack
train
a14eebd7deb276c8c3348de8
train
class
class DataIterator(object): def __init__(self, dataloader): self.dataloader = dataloader self.iterator = enumerate(self.dataloader) def next(self): try: _, data = next(self.iterator) except Exception: self.iterator = enumerate(self.dataloader) ...
class DataIterator(object):
def __init__(self, dataloader): self.dataloader = dataloader self.iterator = enumerate(self.dataloader) def next(self): try: _, data = next(self.iterator) except Exception: self.iterator = enumerate(self.dataloader) _, data = next(self.iterato...
-1] # 2 BGR img = np.transpose(img, [2, 0, 1]) # 2 (3, H, W) img = np.ascontiguousarray(img) img = torch.from_numpy(img).float() return img class DataIterator(object):
64
64
81
5
58
aptsunny/SinglePathOneShot
src/Supernet_hpo_cifar/dataset.py
Python
DataIterator
DataIterator
73
85
73
74
d3038381a5776d2cdb954ea3a098456f6738aa8e
bigcode/the-stack
train
8ed2d85e4e41530f735207fc
train
class
class SubsetSampler(Sampler): r"""Samples elements from a given list of indices, without replacement. Arguments: indices (sequence): a sequence of indices """ def __init__(self, indices): self.indices = indices def __iter__(self): return (i for i in self.indices) def _...
class SubsetSampler(Sampler):
r"""Samples elements from a given list of indices, without replacement. Arguments: indices (sequence): a sequence of indices """ def __init__(self, indices): self.indices = indices def __iter__(self): return (i for i in self.indices) def __len__(self): return l...
self.iterator = enumerate(self.dataloader) def next(self): try: _, data = next(self.iterator) except Exception: self.iterator = enumerate(self.dataloader) _, data = next(self.iterator) return data[0], data[1] class SubsetSampler(Sampler):
64
64
82
7
57
aptsunny/SinglePathOneShot
src/Supernet_hpo_cifar/dataset.py
Python
SubsetSampler
SubsetSampler
87
100
87
87
386e7a1b476cbb1955053113f3034ad175b59d55
bigcode/the-stack
train
c8721dcf3bf109b389edf8a2
train
class
class OpencvResize(object): def __init__(self, size=256): self.size = size def __call__(self, img): assert isinstance(img, PIL.Image.Image) img = np.asarray(img) # (H,W,3) RGB img = img[:,:, ::-1] # 2 BGR img = np.ascontiguousarray(img) H, W, _ = img.shape ...
class OpencvResize(object):
def __init__(self, size=256): self.size = size def __call__(self, img): assert isinstance(img, PIL.Image.Image) img = np.asarray(img) # (H,W,3) RGB img = img[:,:, ::-1] # 2 BGR img = np.ascontiguousarray(img) H, W, _ = img.shape target_size = (int(self.si...
np.clip(x + self.length // 2, 0, w) mask[y1: y2, x1: x2] = 0. mask = torch.from_numpy(mask) mask = mask.expand_as(img) img *= mask return img class OpencvResize(object):
64
64
186
6
57
aptsunny/SinglePathOneShot
src/Supernet_hpo_cifar/dataset.py
Python
OpencvResize
OpencvResize
43
59
43
44
72b5416dc688d5ae8d621ff7b3825eab7c817380
bigcode/the-stack
train
83c06ab2f80bfdc366f7b2c9
train
class
class ToBGRTensor(object): def __call__(self, img): assert isinstance(img, (np.ndarray, PIL.Image.Image)) if isinstance(img, PIL.Image.Image): img = np.asarray(img) img = img[:,:, ::-1] # 2 BGR img = np.transpose(img, [2, 0, 1]) # 2 (3, H, W) img = np.ascontiguou...
class ToBGRTensor(object):
def __call__(self, img): assert isinstance(img, (np.ndarray, PIL.Image.Image)) if isinstance(img, PIL.Image.Image): img = np.asarray(img) img = img[:,:, ::-1] # 2 BGR img = np.transpose(img, [2, 0, 1]) # 2 (3, H, W) img = np.ascontiguousarray(img) img = to...
0.5)) img = cv2.resize(img, target_size, interpolation=cv2.INTER_LINEAR) img = img[:,:, ::-1] # 2 RGB img = np.ascontiguousarray(img) img = Image.fromarray(img) return img class ToBGRTensor(object):
64
64
110
7
56
aptsunny/SinglePathOneShot
src/Supernet_hpo_cifar/dataset.py
Python
ToBGRTensor
ToBGRTensor
61
71
61
62
8596e6089d94a6125eac55604e0eff5cc9f68c5b
bigcode/the-stack
train
f7099af36e3182d3e90f2ccb
train
class
class Cutout(object): def __init__(self, length): self.length = length def __call__(self, img): h, w = img.size(1), img.size(2) mask = np.ones((h, w), np.float32) y = np.random.randint(h) x = np.random.randint(w) y1 = np.clip(y - self.length // 2, 0, h) ...
class Cutout(object):
def __init__(self, length): self.length = length def __call__(self, img): h, w = img.size(1), img.size(2) mask = np.ones((h, w), np.float32) y = np.random.randint(h) x = np.random.randint(w) y1 = np.clip(y - self.length // 2, 0, h) y2 = np.clip(y + self....
, CIFAR100, SVHN from torch.utils.data import Sampler # import torchvision.transforms as transforms # import torchvision.datasets as datasets from RandAugment import RandAugment from sklearn.model_selection import StratifiedShuffleSplit from torch.utils.data import SubsetRandomSampler class Cutout(object):
64
64
193
5
58
aptsunny/SinglePathOneShot
src/Supernet_hpo_cifar/dataset.py
Python
Cutout
Cutout
21
41
21
21
8acead3596791706878c1f2ca753ae576f0f7f6a
bigcode/the-stack
train
a26c482b323f56febb664662
train
function
def get_dataset(dataset, batch_size, split=1.0, cutout_length=0, N=3, M=5, RandA=False): """ MEAN = [0.49139968, 0.48215827, 0.44653124] STD = [0.24703233, 0.24348505, 0.26158768] transf = [ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip() ] normalize = [...
def get_dataset(dataset, batch_size, split=1.0, cutout_length=0, N=3, M=5, RandA=False):
""" MEAN = [0.49139968, 0.48215827, 0.44653124] STD = [0.24703233, 0.24348505, 0.26158768] transf = [ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip() ] normalize = [ transforms.Resize(224), # 32 transforms.ToTensor(), transforms.N...
[:,:, ::-1] # 2 BGR img = np.transpose(img, [2, 0, 1]) # 2 (3, H, W) img = np.ascontiguousarray(img) img = torch.from_numpy(img).float() return img class DataIterator(object): def __init__(self, dataloader): self.dataloader = dataloader self.iterator = enumerate(sel...
256
256
947
32
224
aptsunny/SinglePathOneShot
src/Supernet_hpo_cifar/dataset.py
Python
get_dataset
get_dataset
102
198
102
102
09ecb57a21eebeb9fe1e214160269722c70a9750
bigcode/the-stack
train
6ad108825a4324787612fca9
train
class
class TestUtilityTrayNotificationsAccessibility(GaiaTestCase): def setUp(self): GaiaTestCase.setUp(self) self.system = System(self.marionette) def test_a11y_utility_tray_notifications(self): self.system.wait_for_status_bar_displayed() utility_tray = self.system.open_utility_tr...
class TestUtilityTrayNotificationsAccessibility(GaiaTestCase):
def setUp(self): GaiaTestCase.setUp(self) self.system = System(self.marionette) def test_a11y_utility_tray_notifications(self): self.system.wait_for_status_bar_displayed() utility_tray = self.system.open_utility_tray() utility_tray.wait_for_notification_container_displa...
of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from marionette.by import By from gaiatest import GaiaTestCase from gaiatest.apps.system.app import System class TestUtilityTrayNotificationsAccessibility(GaiaTestCase):
64
64
191
12
51
dlxswangli/gaia
tests/python/gaia-ui-tests/gaiatest/tests/accessibility/system/test_a11y_utility_tray_notifications.py
Python
TestUtilityTrayNotificationsAccessibility
TestUtilityTrayNotificationsAccessibility
10
31
10
11
affb332ad3a00ddb89a849f00086ffbeb2c18a63
bigcode/the-stack
train
3c9e215ab93c9139aa06d15a
train
class
class AlibabaWdkMarketingVersionGenerateRequest(RestApi): def __init__(self, domain='gw.api.taobao.com', port=80): RestApi.__init__(self, domain, port) self.param = None def getapiname(self): return 'alibaba.wdk.marketing.version.generate'
class AlibabaWdkMarketingVersionGenerateRequest(RestApi):
def __init__(self, domain='gw.api.taobao.com', port=80): RestApi.__init__(self, domain, port) self.param = None def getapiname(self): return 'alibaba.wdk.marketing.version.generate'
''' Created by auto_sdk on 2018.10.24 ''' from top.api.base import RestApi class AlibabaWdkMarketingVersionGenerateRequest(RestApi):
34
64
67
11
22
ScottLeeF/python-example
taobao-tianmao/top/api/rest/AlibabaWdkMarketingVersionGenerateRequest.py
Python
AlibabaWdkMarketingVersionGenerateRequest
AlibabaWdkMarketingVersionGenerateRequest
7
13
7
7
56ec9fbd9430291c5a73676797998b4d5900d337
bigcode/the-stack
train
5f0213bf50b99b1806abb2ab
train
function
def check_process( process_path: str, ) -> (bool, Union[str, None], Union[str, None], Union[str, None], bool): """Function to check the status of a process. Reads the process file from the yaml and checks the process id. Args: process_path (str): Path to the process file. Returns: ...
def check_process( process_path: str, ) -> (bool, Union[str, None], Union[str, None], Union[str, None], bool):
"""Function to check the status of a process. Reads the process file from the yaml and checks the process id. Args: process_path (str): Path to the process file. Returns: bool: Flag if process exists. Union ([str, None]): Process id if process exists, else None. Union (...
process["pid"] = p.pid if verbose: st.success(f"Started process PID {p.pid} at {now}") with open(process_file, "w") as file: yaml.dump(process, file, sort_keys=False) def check_process( process_path: str, ) -> (bool, Union[str, None], Union[str, None], Union[str, None], bool):
84
84
280
32
52
mgleeming/alphapept
alphapept/gui/utils.py
Python
check_process
check_process
130
163
130
132
dffdfca8d4fd8b0a8c8693129d931c285c6b7121
bigcode/the-stack
train
465d6eb835a42c6f85542cd6
train
function
def escape_markdown(text: str) -> str: """Helper function to escape markdown in text. Args: text (str): Input text. Returns: str: Converted text to be used in markdown. """ MD_SPECIAL_CHARS = "\`*_{}[]()#+-.!" for char in MD_SPECIAL_CHARS: text = text.replace(char, "\\"...
def escape_markdown(text: str) -> str:
"""Helper function to escape markdown in text. Args: text (str): Input text. Returns: str: Converted text to be used in markdown. """ MD_SPECIAL_CHARS = "\`*_{}[]()#+-.!" for char in MD_SPECIAL_CHARS: text = text.replace(char, "\\" + char) return text
import os import datetime import yaml import streamlit as st from multiprocessing import Process import psutil import time import pandas as pd from typing import Callable, Union def escape_markdown(text: str) -> str:
50
64
87
11
38
mgleeming/alphapept
alphapept/gui/utils.py
Python
escape_markdown
escape_markdown
12
24
12
12
222f8779df679392934fc08818c14a903fa04c07
bigcode/the-stack
train
1427218668b51efd04cca0bc
train
function
def start_process( target: Callable, process_file: str, args: Union[list, None] = None, verbose: bool = True, ): """Function to initiate a process. It will launch the process and save the process id to a yaml file. Args: target (Callable): Target function for the process. proces...
def start_process( target: Callable, process_file: str, args: Union[list, None] = None, verbose: bool = True, ):
"""Function to initiate a process. It will launch the process and save the process id to a yaml file. Args: target (Callable): Target function for the process. process_file (str): Path to the yaml file where the process information will be stored. args (Union[list, None], optional): Add...
"r") as logfile: lines = logfile.readlines() lines = [_ for _ in lines if "__" not in _] st.code("".join(lines)) def start_process( target: Callable, process_file: str, args: Union[list, None] = None, verbose: bool = True, ):
69
69
233
34
35
mgleeming/alphapept
alphapept/gui/utils.py
Python
start_process
start_process
99
127
99
104
bda65f5aafdbbfaaeb5b24d19c5a8e045ed61e31
bigcode/the-stack
train
e384f7827640c7b768858ce5
train
function
def init_process(process_path: str, **kwargs: dict): """Waits until a process file is created and then writes an init flag to the file Args: process_path (str): Path to process yaml. """ while True: if os.path.isfile(process_path): with open(process_path, "r") as process_fil...
def init_process(process_path: str, **kwargs: dict):
"""Waits until a process file is created and then writes an init flag to the file Args: process_path (str): Path to process yaml. """ while True: if os.path.isfile(process_path): with open(process_path, "r") as process_file: p = yaml.load(process_file, Loader...
_pid) with p_.oneshot(): p_name = p_.name() status = p_.status() return True, last_pid, p_name, status, p_init return False, None, None, None, False def init_process(process_path: str, **kwargs: dict):
64
64
145
13
50
mgleeming/alphapept
alphapept/gui/utils.py
Python
init_process
init_process
166
183
166
166
fda878a481b545d43a767bdae4c5872f2ca64f09
bigcode/the-stack
train
e5756060075f4d2aed71a719
train
function
def files_in_folder(folder: str, ending: str, sort: str = "name") -> list: """Reads a folder and returns all files that have this ending. Sorts the files by name or creation date. Args: folder (str): Path to folder. ending (str): Ending. sort (str, optional): How files should be sorted....
def files_in_folder(folder: str, ending: str, sort: str = "name") -> list:
"""Reads a folder and returns all files that have this ending. Sorts the files by name or creation date. Args: folder (str): Path to folder. ending (str): Ending. sort (str, optional): How files should be sorted. Defaults to 'name'. Raises: NotImplementedError: If a sorting...
Args: description (str): Description. link (str): Target URL. """ _ = f"[{description}]({link})" st.markdown(_, unsafe_allow_html=True) def files_in_folder(folder: str, ending: str, sort: str = "name") -> list:
64
64
188
22
42
mgleeming/alphapept
alphapept/gui/utils.py
Python
files_in_folder
files_in_folder
38
63
38
38
3d3f57dfca2229dd16aa2b13c148ef4a528b1950
bigcode/the-stack
train
fd19d6aa58412127e2fd73fe
train
function
def files_in_folder_pandas(folder: str) -> pd.DataFrame: """Reads a folder and returns a pandas dataframe containing the files and additional information. Args: folder (str): Path to folder. Returns: pd.DataFrame: PandasDataFrame. """ files = os.listdir(folder) created = [time.c...
def files_in_folder_pandas(folder: str) -> pd.DataFrame:
"""Reads a folder and returns a pandas dataframe containing the files and additional information. Args: folder (str): Path to folder. Returns: pd.DataFrame: PandasDataFrame. """ files = os.listdir(folder) created = [time.ctime(os.path.getctime(os.path.join(folder, _))) for _ in ...
files.sort() elif sort == "date": files.sort(key=lambda x: os.path.getctime(os.path.join(folder, x))) else: raise NotImplementedError files = files[::-1] return files def files_in_folder_pandas(folder: str) -> pd.DataFrame:
64
64
152
15
48
mgleeming/alphapept
alphapept/gui/utils.py
Python
files_in_folder_pandas
files_in_folder_pandas
66
81
66
66
1126e9c041bdb17db2985b8d65a4ef581b64b17e
bigcode/the-stack
train
69caf13c8f8eea01d0d5c640
train
function
def markdown_link(description: str, link: str): """Creates a markdown compatible link. Args: description (str): Description. link (str): Target URL. """ _ = f"[{description}]({link})" st.markdown(_, unsafe_allow_html=True)
def markdown_link(description: str, link: str):
"""Creates a markdown compatible link. Args: description (str): Description. link (str): Target URL. """ _ = f"[{description}]({link})" st.markdown(_, unsafe_allow_html=True)
: str: Converted text to be used in markdown. """ MD_SPECIAL_CHARS = "\`*_{}[]()#+-.!" for char in MD_SPECIAL_CHARS: text = text.replace(char, "\\" + char) return text def markdown_link(description: str, link: str):
64
64
61
11
52
mgleeming/alphapept
alphapept/gui/utils.py
Python
markdown_link
markdown_link
27
35
27
27
18571ec7980201dc135ea6eac84723facff6fe67
bigcode/the-stack
train
9170beb8cf7f463388e61196
train
function
def read_log(log_path: str): """Reads logfile and removes lines with __. Lines with __ are used to indicate progress for the AlphaPept GUI. Args: log_path (str): Path to the logile. """ if os.path.isfile(log_path): with st.beta_expander("Run log"): with st.spinner("Parsin...
def read_log(log_path: str):
"""Reads logfile and removes lines with __. Lines with __ are used to indicate progress for the AlphaPept GUI. Args: log_path (str): Path to the logile. """ if os.path.isfile(log_path): with st.beta_expander("Run log"): with st.spinner("Parsing file"): wit...
size(os.path.join(folder, _)) / 1024 ** 2 for _ in files] df = pd.DataFrame(files, columns=["File"]) df["Created"] = created df["Filesize (Mb)"] = sizes return df def read_log(log_path: str):
64
64
118
8
55
mgleeming/alphapept
alphapept/gui/utils.py
Python
read_log
read_log
84
96
84
84
08113371f5944be74171b3d43181f35ce346f244
bigcode/the-stack
train
433b2f3e658166e14fbab447
train
class
class widerface(IMDB): def __init__(self, image_set, root_path, data_path): super(widerface, self).__init__('WIDERFACE', image_set, root_path, data_path) self._test_flag = True if image_set == 'test' else False split = image_set self._split = image_set self._image_set = imag...
class widerface(IMDB):
def __init__(self, image_set, root_path, data_path): super(widerface, self).__init__('WIDERFACE', image_set, root_path, data_path) self._test_flag = True if image_set == 'test' else False split = image_set self._split = image_set self._image_set = image_set self._an...
# -------------------------------------------------------- # SSH: Single Stage Headless Face Detector # Wider Dataset Loader # Written by Pouya Samangouei and Mahyar Najibi # -------------------------------------------------------- from __future__ import print_function try: import cPickle as pickle except ImportErr...
128
256
2,980
6
121
templeblock/mxnet-SSHA
rcnn/dataset/widerface.py
Python
widerface
widerface
22
312
22
22
a582198a2bd71c73b0f4c8c48b95c6d9bd712eab
bigcode/the-stack
train
26aa8a1e9e430ff04a743093
train
class
class patch_submodule: """ Patch a submodule attribute of an object, by keeping all other submodules intact at all levels. Example:: >>> import importlib >>> from datasets.load import dataset_module_factory >>> from datasets.streaming import patch_submodule, xjoin >>> ...
class patch_submodule:
""" Patch a submodule attribute of an object, by keeping all other submodules intact at all levels. Example:: >>> import importlib >>> from datasets.load import dataset_module_factory >>> from datasets.streaming import patch_submodule, xjoin >>> >>> dataset_module =...
from .logging import get_logger logger = get_logger(__name__) class _PatchedModuleObj: """Set all the modules components as attributes of the _PatchedModuleObj object.""" def __init__(self, module, attrs=None): attrs = attrs or [] if module is not None: for key in module.__dict_...
100
111
373
5
95
MitchellTesla/datasets
src/datasets/utils/patching.py
Python
patch_submodule
patch_submodule
18
69
18
18
91d00288889caed572c7e9dc1dd07235088a369d
bigcode/the-stack
train
0f0f02f0b043dd6c849e1b8a
train
class
class _PatchedModuleObj: """Set all the modules components as attributes of the _PatchedModuleObj object.""" def __init__(self, module, attrs=None): attrs = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__"): ...
class _PatchedModuleObj:
"""Set all the modules components as attributes of the _PatchedModuleObj object.""" def __init__(self, module, attrs=None): attrs = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__"): setattr...
from .logging import get_logger logger = get_logger(__name__) class _PatchedModuleObj:
21
64
81
7
14
MitchellTesla/datasets
src/datasets/utils/patching.py
Python
_PatchedModuleObj
_PatchedModuleObj
7
15
7
7
103ac66a136ad8c4e1598579dc49b7a0b2a6193c
bigcode/the-stack
train
7223492c2d6ce4f88865af65
train
class
class NodeGroup(Node): def __init__(self, node): super.__init__(node) self._inner = None def get_inner(self): self._inner = self._node.items()[0] def get_inner_tag(self): return self.get_inner().tag() def get_inner_element(self): """Get the inner element of this group. Only ...
class NodeGroup(Node):
def __init__(self, node): super.__init__(node) self._inner = None def get_inner(self): self._inner = self._node.items()[0] def get_inner_tag(self): return self.get_inner().tag() def get_inner_element(self): """Get the inner element of this group. Only one of the elements insi...
#!/usr/bin/env python3 """ Super class for all xsd:group types """ from .node import Node class NodeGroup(Node):
30
64
173
5
24
cobhimself/doxyparser
doxyparser/nodegroup.py
Python
NodeGroup
NodeGroup
7
33
7
8
70dcd3ef3a6ef749da57e6a80154e0aa6a51947b
bigcode/the-stack
train
a07a781fb2b66c093e86c31a
train
function
def make_json(df, image_set='train'): annotations = [] images = [] licenses = [] categories = [ { "id": 1, "name": "opacity"} ] info = { "description": "SIIM Covid Dataset", "url": "http://kaggle.com", "version": "1.0", ...
def make_json(df, image_set='train'):
annotations = [] images = [] licenses = [] categories = [ { "id": 1, "name": "opacity"} ] info = { "description": "SIIM Covid Dataset", "url": "http://kaggle.com", "version": "1.0", "year": 2021, "contributor...
import json def make_json(df, image_set='train'):
13
127
425
10
2
ngockhanh5110/DETR-SIIM-Kaggle
siim/coco_generator.py
Python
make_json
make_json
3
60
3
3
7e0bd38ad364f57376b4565a995d89074e02f60a
bigcode/the-stack
train
a035ee1dfe160b14da5df5c3
train
function
def extract_features(Y, fixed_effect_time_order): """Extract the design features from longitudinal data Parameters ---------- Y : `pandas.DataFrame`, shape=(n_samples, n_long_features) The longitudinal data. Each element of the dataframe is a pandas.Series fixed_effect_time_order :...
def extract_features(Y, fixed_effect_time_order):
"""Extract the design features from longitudinal data Parameters ---------- Y : `pandas.DataFrame`, shape=(n_samples, n_long_features) The longitudinal data. Each element of the dataframe is a pandas.Series fixed_effect_time_order : `int` Order of the higher time monomial c...
_effect_time_order : `int` Order of fixed effect features Returns ------- U_il : `np.array` The corresponding fixed-effect design features V_il : `np.array` The corresponding random-effect design features Y_il : `np.array` The corresponding outcomes n_il : `list`...
206
206
687
10
195
Califrais/lights
lights/base/base.py
Python
extract_features
extract_features
161
234
161
161
5acbee6dcbd5efcd8c2f53fd7d059098e9db5119
bigcode/the-stack
train
d8dab18aef1bbb7894d83464
train
function
def logistic_loss(z): """Overflow proof computation of log(1 + exp(-z)) """ idx_pos = np.where(z >= 0.) idx_neg = np.where(z < 0.) res = np.empty(z.shape) res[idx_pos] = np.log(1. + np.exp(-z[idx_pos])) z_neg = z[idx_neg] res[idx_neg] = -z_neg + np.log(1. + np.exp(z_neg)) return res
def logistic_loss(z):
"""Overflow proof computation of log(1 + exp(-z)) """ idx_pos = np.where(z >= 0.) idx_neg = np.where(z < 0.) res = np.empty(z.shape) res[idx_pos] = np.log(1. + np.exp(-z[idx_pos])) z_neg = z[idx_neg] res[idx_neg] = -z_neg + np.log(1. + np.exp(z_neg)) return res
0.) res = np.empty(z.shape) res[idx_pos] = 1. / (1. + np.exp(-z[idx_pos])) res[idx_neg] = 1 - 1. / (1. + np.exp(z[idx_neg])) return res def logistic_loss(z):
64
64
103
5
58
Califrais/lights
lights/base/base.py
Python
logistic_loss
logistic_loss
248
257
248
248
191a5bf8064ed9bb4a6f2748d435498bb2296564
bigcode/the-stack
train
b642fdb7fc42127dc87c36b7
train
function
def logistic_grad(z): """Overflow proof computation of 1 / (1 + exp(-z))) """ idx_pos = np.where(z >= 0.) idx_neg = np.where(z < 0.) res = np.empty(z.shape) res[idx_pos] = 1. / (1. + np.exp(-z[idx_pos])) res[idx_neg] = 1 - 1. / (1. + np.exp(z[idx_neg])) return res
def logistic_grad(z):
"""Overflow proof computation of 1 / (1 + exp(-z))) """ idx_pos = np.where(z >= 0.) idx_neg = np.where(z < 0.) res = np.empty(z.shape) res[idx_pos] = 1. / (1. + np.exp(-z[idx_pos])) res[idx_neg] = 1 - 1. / (1. + np.exp(z[idx_neg])) return res
[l] = np.concatenate(tuple(U_L[l])) V_L[l] = block_diag(V_L[l]) y_L[l] = np.concatenate(tuple(y_L[l])) return (U, V, y, N), (U_L, V_L, y_L, N_L) def logistic_grad(z):
64
64
101
5
59
Califrais/lights
lights/base/base.py
Python
logistic_grad
logistic_grad
237
245
237
237
e64c6aa90d88177898f12470ac8dc1a8340e4c7e
bigcode/the-stack
train
cfda5c91bff81861a42f29fe
train
function
def normalize(X): """Normalize X to have mean 0 and std 1 Parameters ---------- X : `np.ndarray`, shape=(n, d) A time-independent features matrix Returns ------- X_norm : `np.ndarray`, shape=(n, d) The corresponding normilized matrix with mean 0 and std 1 """ mean =...
def normalize(X):
"""Normalize X to have mean 0 and std 1 Parameters ---------- X : `np.ndarray`, shape=(n, d) A time-independent features matrix Returns ------- X_norm : `np.ndarray`, shape=(n, d) The corresponding normilized matrix with mean 0 and std 1 """ mean = X.mean(axis=0) ...
=out_dtype) r, c = 0, 0 for i, (rr, cc) in enumerate(shapes): out[r:r + rr, c:c + cc] = l_arr[i] r += rr c += cc return out def normalize(X):
64
64
115
4
59
Califrais/lights
lights/base/base.py
Python
normalize
normalize
108
125
108
108
be160fd21c8a7c17453744c8f593588555e0e3e5
bigcode/the-stack
train
9d3ffeb39f07099b872bfe16
train
function
def get_vect_from_ext(v_ext): """Get the time-independent coefficient vector from its extension on positive and negative parts Parameters ---------- v_ext : `np.ndarray`, shape=(2*dim,) The extended vector decomposed on positive and negative parts Returns ------- v : `np.ndarra...
def get_vect_from_ext(v_ext):
"""Get the time-independent coefficient vector from its extension on positive and negative parts Parameters ---------- v_ext : `np.ndarray`, shape=(2*dim,) The extended vector decomposed on positive and negative parts Returns ------- v : `np.ndarray`, shape=(dim,) The r...
xi = xi_ext[:dim] - xi_ext[dim:] if fit_intercept: xi_0 = xi[0] xi = xi[1:] else: xi_0 = 0 return xi_0, xi def get_vect_from_ext(v_ext):
64
64
114
8
55
Califrais/lights
lights/base/base.py
Python
get_vect_from_ext
get_vect_from_ext
338
354
338
338
ff34b3d312957461775c540d311428ef632cf594
bigcode/the-stack
train
a2a36635876ec67d1074b511
train
class
class Learner: """The base class for a Solver. Not intended for end-users, but for development only. It should be sklearn-learn compliant Parameters ---------- verbose : `bool`, default=True If `True`, we verbose things, otherwise the solver does not print anything (but records ...
class Learner:
"""The base class for a Solver. Not intended for end-users, but for development only. It should be sklearn-learn compliant Parameters ---------- verbose : `bool`, default=True If `True`, we verbose things, otherwise the solver does not print anything (but records information in ...
from datetime import datetime from lights.base.history import History from time import time import numpy as np class Learner:
26
149
499
4
21
Califrais/lights
lights/base/base.py
Python
Learner
Learner
7
81
7
7
01230453faec679a12853a0aeebe1b20aec5f59b
bigcode/the-stack
train
1678c560b0f8c99f8deaa760
train
function
def get_times_infos(T, T_u): """Get censored times indicators Parameters ---------- T : `np.ndarray`, shape=(n_samples,) Censored times of the event of interest T_u : `np.ndarray`, shape=(J,) The J unique training censored times of the event of interest Returns ------- ...
def get_times_infos(T, T_u):
"""Get censored times indicators Parameters ---------- T : `np.ndarray`, shape=(n_samples,) Censored times of the event of interest T_u : `np.ndarray`, shape=(J,) The J unique training censored times of the event of interest Returns ------- J : `int` Number of ...
= np.empty(z.shape) res[idx_pos] = np.log(1. + np.exp(-z[idx_pos])) z_neg = z[idx_neg] res[idx_neg] = -z_neg + np.log(1. + np.exp(z_neg)) return res def get_times_infos(T, T_u):
67
67
224
9
57
Califrais/lights
lights/base/base.py
Python
get_times_infos
get_times_infos
260
285
260
260
f6eac369e345ff5dfc07d69b70f3e5dd71f4df59
bigcode/the-stack
train
5258ec190dcac8e795c0b01d
train
function
def clean_xi_ext(xi_ext, fit_intercept): """Removes potential intercept coefficients in the time-independent coefficient vector decomposed on positive and negative parts Parameters ---------- xi_ext : `np.ndarray`, shape=(2*n_time_indep_features,) The time-independent coefficient vector dec...
def clean_xi_ext(xi_ext, fit_intercept):
"""Removes potential intercept coefficients in the time-independent coefficient vector decomposed on positive and negative parts Parameters ---------- xi_ext : `np.ndarray`, shape=(2*n_time_indep_features,) The time-independent coefficient vector decomposed on positive and negative ...
v : `np.ndarray`, shape=(dim,) The returned vector """ dim = len(v_ext) // 2 v = (v_ext[:dim] - v_ext[dim:]).flatten() return v def clean_xi_ext(xi_ext, fit_intercept):
64
64
194
13
50
Califrais/lights
lights/base/base.py
Python
clean_xi_ext
clean_xi_ext
357
380
357
357
fc34d6f665e83e96bd2af40d4b6d4db3cddfa76c
bigcode/the-stack
train
1ee69d6c6ea3ceba90bc5c24
train
function
def block_diag(l_arr): """Create a block diagonal matrix from provided list of arrays. Parameters ---------- l_arr : list of arrays, up to 2-D Input arrays. Returns ------- out : ndarray Array with input arrays on the diagonal. """ shapes = np.array([a.shape for a i...
def block_diag(l_arr):
"""Create a block diagonal matrix from provided list of arrays. Parameters ---------- l_arr : list of arrays, up to 2-D Input arrays. Returns ------- out : ndarray Array with input arrays on the diagonal. """ shapes = np.array([a.shape for a in l_arr]) out_dtype...
return self.history.values else: return val def get_history_keys(self): """Return names of the elements stored in history Returns ------- output : `list` list containing names of history keys """ return self.history.values.keys() def...
64
64
170
6
58
Califrais/lights
lights/base/base.py
Python
block_diag
block_diag
84
105
84
84
1d4f2761f6a8d0475df46dfed232055f6abeb9a4
bigcode/the-stack
train
91d1509a4b949882b8a6b7a0
train
function
def get_ext_from_vect(v): """Get extension on positive and negative parts of a vector Parameters ---------- v : `np.ndarray`, shape=(dim,) A vector Returns ------- v_ext : `np.ndarray`, shape=(2 * dim,) The extended vector decomposed on positive and negative parts """ ...
def get_ext_from_vect(v):
"""Get extension on positive and negative parts of a vector Parameters ---------- v : `np.ndarray`, shape=(dim,) A vector Returns ------- v_ext : `np.ndarray`, shape=(2 * dim,) The extended vector decomposed on positive and negative parts """ v_ext = np.concatenate(...
indicator_1 = (T.reshape(-1, 1) == T_u).astype(np.ushort) indicator_2 = (T.reshape(-1, 1) >= T_u).astype(np.ushort) return J, indicator_1, indicator_2 def get_ext_from_vect(v):
64
64
110
7
56
Califrais/lights
lights/base/base.py
Python
get_ext_from_vect
get_ext_from_vect
288
303
288
288
d51b11a6efe78c180add5a578bd72325d4a1c426
bigcode/the-stack
train
c7608cb8f361954de9d2b04a
train
function
def get_xi_from_xi_ext(xi_ext, fit_intercept): """Get the time-independent coefficient vector from its extension on positive and negative parts Parameters ---------- xi_ext : `np.ndarray`, shape=(2*n_time_indep_features,) The time-independent coefficient vector decomposed on positive and ...
def get_xi_from_xi_ext(xi_ext, fit_intercept):
"""Get the time-independent coefficient vector from its extension on positive and negative parts Parameters ---------- xi_ext : `np.ndarray`, shape=(2*n_time_indep_features,) The time-independent coefficient vector decomposed on positive and negative parts fit_intercept : `bool...
vector decomposed on positive and negative parts """ v_ext = np.concatenate((v, -v)).reshape(-1, 1) v_ext[v_ext < 0] = 0 return v_ext def get_xi_from_xi_ext(xi_ext, fit_intercept):
64
64
209
16
47
Califrais/lights
lights/base/base.py
Python
get_xi_from_xi_ext
get_xi_from_xi_ext
306
335
306
306
e3bf485ebb76abcb047427a9e23d9c78ff64c6b9
bigcode/the-stack
train
381674a90ba812b39bbecc77
train
function
def from_ts_to_design_features(Y_il, fixed_effect_time_order): """Extracts the design features from a given longitudinal trajectory Parameters ---------- Y_il : `pandas.Series` A longitudinal trajectory fixed_effect_time_order : `int` Order of fixed effect features Returns ...
def from_ts_to_design_features(Y_il, fixed_effect_time_order):
"""Extracts the design features from a given longitudinal trajectory Parameters ---------- Y_il : `pandas.Series` A longitudinal trajectory fixed_effect_time_order : `int` Order of fixed effect features Returns ------- U_il : `np.array` The corresponding fixed-e...
shape=(n, d) The corresponding normilized matrix with mean 0 and std 1 """ mean = X.mean(axis=0) std = X.std(axis=0) X_norm = (X - mean) / std return X_norm def from_ts_to_design_features(Y_il, fixed_effect_time_order):
73
73
244
14
58
Califrais/lights
lights/base/base.py
Python
from_ts_to_design_features
from_ts_to_design_features
128
158
128
128
c8dba591a6fce49b8fd619be59833f63b6902d8c
bigcode/the-stack
train
f30e70224fdbedda61a1bed9
train
class
class ProbeInfoSensor(BaseSensor): KIND = u'probeinfo' def __init__(self, info): super(ProbeInfoSensor, self).__init__() self.info = info """ :type: ProbeInfo """ def define(self, configuration): result = SensorDescription(u"Probeinformationen", self.KIND) result.de...
class ProbeInfoSensor(BaseSensor):
KIND = u'probeinfo' def __init__(self, info): super(ProbeInfoSensor, self).__init__() self.info = info """ :type: ProbeInfo """ def define(self, configuration): result = SensorDescription(u"Probeinformationen", self.KIND) result.description = u"Liefert Informationen...
# coding=utf-8 from pyprobe.sensors import * __author__ = 'Dirk Dittert' class ProbeInfoSensor(BaseSensor):
31
64
212
7
24
dittert/pyprobe
src/pyprobe/sensors/probe/sensor_probeinfo.py
Python
ProbeInfoSensor
ProbeInfoSensor
9
31
9
9
8fb08cb70e8c285f75903811e816274aff0a9698
bigcode/the-stack
train
5134108ab72e4a0569ca27c0
train
class
class F5BigIpLtmProfileTftp(F5BigIpNamedObject): def _set_crud_methods(self): self._methods = { 'create': self._api.tm.ltm.profile.tftps.tftp.create, 'read': self._api.tm.ltm.profile.tftps.tftp.load, 'update': self._api.tm.ltm.profile.tftps.tftp.update, 'delet...
class F5BigIpLtmProfileTftp(F5BigIpNamedObject):
def _set_crud_methods(self): self._methods = { 'create': self._api.tm.ltm.profile.tftps.tftp.create, 'read': self._api.tm.ltm.profile.tftps.tftp.load, 'update': self._api.tm.ltm.profile.tftps.tftp.update, 'delete': self._api.tm.ltm.profile.tftps.tftp.delete, ...
(type='str') ) argument_spec.update(F5_PROVIDER_ARGS) argument_spec.update(F5_NAMED_OBJ_ARGS) return argument_spec @property def supports_check_mode(self): return True class F5BigIpLtmProfileTftp(F5BigIpNamedObject):
64
64
124
17
46
GabrielFortin/ansible-module-f5bigip
library/f5bigip_ltm_profile_tftp.py
Python
F5BigIpLtmProfileTftp
F5BigIpLtmProfileTftp
113
121
113
113
d95f81194b41c7825478c4f035c88af0c753d443
bigcode/the-stack
train
b576852d87900b183a9aa76a
train
function
def main(): params = ModuleParams() module = AnsibleModule(argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode) try: obj = F5BigIpLtmProfileTftp(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except E...
def main():
params = ModuleParams() module = AnsibleModule(argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode) try: obj = F5BigIpLtmProfileTftp(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except Exception as ...
ps.tftp.load, 'update': self._api.tm.ltm.profile.tftps.tftp.update, 'delete': self._api.tm.ltm.profile.tftps.tftp.delete, 'exists': self._api.tm.ltm.profile.tftps.tftp.exists } def main():
64
64
83
3
61
GabrielFortin/ansible-module-f5bigip
library/f5bigip_ltm_profile_tftp.py
Python
main
main
124
133
124
124
4ff89acc88a9b269442d35d6b96833445b079e9c
bigcode/the-stack
train
86341032a04c362d917e0fef
train
class
class ModuleParams(object): @property def argument_spec(self): argument_spec = dict( app_service=dict(type='str'), defaults_from=dict(type='str'), description=dict(type='str'), idle_timeout=dict(type='int'), log_publisher=dict(type='str'), ...
class ModuleParams(object): @property
def argument_spec(self): argument_spec = dict( app_service=dict(type='str'), defaults_from=dict(type='str'), description=dict(type='str'), idle_timeout=dict(type='int'), log_publisher=dict(type='str'), log_profile=dict(type='str') ...
ansible.module_utils.basic import AnsibleModule from ansible_common_f5.base import F5_NAMED_OBJ_ARGS from ansible_common_f5.base import F5_PROVIDER_ARGS from ansible_common_f5.bigip import F5BigIpNamedObject class ModuleParams(object): @property
64
64
112
9
54
GabrielFortin/ansible-module-f5bigip
library/f5bigip_ltm_profile_tftp.py
Python
ModuleParams
ModuleParams
93
110
93
94
cbcee2b6d97d776837a6b1c120e7d8e17151dc4d
bigcode/the-stack
train
285042ca8126ac57845b6211
train
class
class Executable(object): """Class representing a program that can be run on the command line.""" def __init__(self, name): self.exe = shlex.split(name) self.default_env = {} self.returncode = None if not self.exe: raise ProcessError("Cannot construct executable for...
class Executable(object):
"""Class representing a program that can be run on the command line.""" def __init__(self, name): self.exe = shlex.split(name) self.default_env = {} self.returncode = None if not self.exe: raise ProcessError("Cannot construct executable for '%s'" % name) def ad...
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os import re import shlex import subprocess from six import string_types, text_type import llnl.util.tty as tty i...
105
256
1,498
5
100
Bidibulke/spack
lib/spack/spack/util/executable.py
Python
Executable
Executable
19
224
19
19
a07ed79ce87ccf3e4e935cf3342e298fc41bd981
bigcode/the-stack
train
d03679c654dee71c34ad8845
train
function
def which_string(*args, **kwargs): """Like ``which()``, but return a string instead of an ``Executable``.""" path = kwargs.get('path', os.environ.get('PATH', '')) required = kwargs.get('required', False) if isinstance(path, string_types): path = path.split(os.pathsep) for name in args: ...
def which_string(*args, **kwargs):
"""Like ``which()``, but return a string instead of an ``Executable``.""" path = kwargs.get('path', os.environ.get('PATH', '')) required = kwargs.get('required', False) if isinstance(path, string_types): path = path.split(os.pathsep) for name in args: for directory in path: ...
) def __hash__(self): return hash((type(self), ) + tuple(self.exe)) def __repr__(self): return '<exe: %s>' % self.exe def __str__(self): return ' '.join(self.exe) def which_string(*args, **kwargs):
64
64
146
9
55
Bidibulke/spack
lib/spack/spack/util/executable.py
Python
which_string
which_string
227
244
227
227
cfcaf645773112dcba9c26ea5c9d424acb0d4707
bigcode/the-stack
train
e3b9ea88929242739d96ba12
train
class
class ProcessError(spack.error.SpackError): """ProcessErrors are raised when Executables exit with an error code."""
class ProcessError(spack.error.SpackError):
"""ProcessErrors are raised when Executables exit with an error code."""
set to True, raise an error if executable not found Returns: Executable: The first executable that is found in the path """ exe = which_string(*args, **kwargs) return Executable(exe) if exe else None class ProcessError(spack.error.SpackError):
64
64
25
10
53
Bidibulke/spack
lib/spack/spack/util/executable.py
Python
ProcessError
ProcessError
267
268
267
267
41d3230c14801a42c981e4a80791939d1643a47e
bigcode/the-stack
train
0c4f4ccd89c9c82eea28feeb
train
function
def which(*args, **kwargs): """Finds an executable in the path like command-line which. If given multiple executables, returns the first one that is found. If no executables are found, returns None. Parameters: *args (str): One or more executables to search for Keyword Arguments: ...
def which(*args, **kwargs):
"""Finds an executable in the path like command-line which. If given multiple executables, returns the first one that is found. If no executables are found, returns None. Parameters: *args (str): One or more executables to search for Keyword Arguments: path (:func:`list` or str): ...
name) if os.path.isfile(exe) and os.access(exe, os.X_OK): return exe if required: tty.die("spack requires '%s'. Make sure it is in your path." % args[0]) return None def which(*args, **kwargs):
64
64
151
8
55
Bidibulke/spack
lib/spack/spack/util/executable.py
Python
which
which
247
264
247
247
8f11dbf603c648616c7812c5e90b25ff3cd2118f
bigcode/the-stack
train
e92fc1c5f6c08341987f9ead
train
class
class MainHandler(BaseHandler): """Main handler for requests""" @authenticated def get(self): self.render_template( "index.html", badge_base_url=self.settings['badge_base_url'], base_url=self.settings['base_url'], submit=False, google_anal...
class MainHandler(BaseHandler):
"""Main handler for requests""" @authenticated def get(self): self.render_template( "index.html", badge_base_url=self.settings['badge_base_url'], base_url=self.settings['base_url'], submit=False, google_analytics_code=self.settings['google...
BaseHandler SPEC_NAMES = { "gh": "GitHub", "gist": "Gist", "gl": "GitLab", "git": "Git repo", "zenodo": "Zenodo", "figshare": "Figshare" } class MainHandler(BaseHandler):
64
64
95
6
58
bdrian/binderhub
binderhub/main.py
Python
MainHandler
MainHandler
23
36
23
23
836b814413184d44e8d166b2b610151f458b18e1
bigcode/the-stack
train
4077b7dc441c7149096e7be3
train
class
class LegacyRedirectHandler(BaseHandler): """Redirect handler from legacy Binder""" @authenticated def get(self, user, repo, urlpath=None): url = '/v2/gh/{user}/{repo}/master'.format(user=user, repo=repo) if urlpath is not None and urlpath.strip('/'): url = url_concat(url, dict(...
class LegacyRedirectHandler(BaseHandler):
"""Redirect handler from legacy Binder""" @authenticated def get(self, user, repo, urlpath=None): url = '/v2/gh/{user}/{repo}/master'.format(user=user, repo=repo) if urlpath is not None and urlpath.strip('/'): url = url_concat(url, dict(urlpath=urlpath)) self.redirect(ur...
, # urlpath=self.get_argument('urlpath', None), submit=True, google_analytics_code=self.settings['google_analytics_code'], google_analytics_domain=self.settings['google_analytics_domain'], extra_footer_scripts=self.settings['extra_footer_scripts'], ) c...
64
64
86
7
57
bdrian/binderhub
binderhub/main.py
Python
LegacyRedirectHandler
LegacyRedirectHandler
108
116
108
108
1baec4ea8ad679f2ff4def48a73b30bc681958c1
bigcode/the-stack
train
77db8215f29ed4dbbeb5a928
train
class
class ParameterizedMainHandler(BaseHandler): """Main handler that allows different parameter settings""" @authenticated async def get(self, provider_prefix, _unescaped_spec): prefix = '/v2/' + provider_prefix spec = self.get_spec_from_request(prefix) spec = spec.rstrip("/") ...
class ParameterizedMainHandler(BaseHandler):
"""Main handler that allows different parameter settings""" @authenticated async def get(self, provider_prefix, _unescaped_spec): prefix = '/v2/' + provider_prefix spec = self.get_spec_from_request(prefix) spec = spec.rstrip("/") try: self.get_provider(provider_p...
authenticated from tornado.httputil import url_concat from tornado.log import app_log from .base import BaseHandler SPEC_NAMES = { "gh": "GitHub", "gist": "Gist", "gl": "GitLab", "git": "Git repo", "zenodo": "Zenodo", "figshare": "Figshare" } class MainHandler(BaseHandler): """Main hand...
184
184
614
8
176
bdrian/binderhub
binderhub/main.py
Python
ParameterizedMainHandler
ParameterizedMainHandler
39
105
39
39
3fdd8d77ee7a46ba73714855920a92916639c070
bigcode/the-stack
train
6e3a9af8463e4ffd3bed378f
train
class
class InputCheckBox(Input): def __repr__(self): return "[Input/Checkbox: %s %s]" % (self.name, self.value) def set(self, value): self.value = int(not not value)
class InputCheckBox(Input):
def __repr__(self): return "[Input/Checkbox: %s %s]" % (self.name, self.value) def set(self, value): self.value = int(not not value)
/Text: %s %s]" % (self.name, self.value) class InputSubmit(Input): def __repr__(self): return "[Input/Submit: %s %s]" % (self.name, self.value) def set(self): raise Exception("TODO") class InputCheckBox(Input):
64
64
49
6
58
braph/snippets
python/autoforms.py
Python
InputCheckBox
InputCheckBox
99
104
99
99
8b6915180ca1d97b3e8e7cca27d63d5c20029576
bigcode/the-stack
train
65446e9c4b263e1a5c39d94a
train
class
class AutoForm(): __slots__ = ('_inputs') def __init__(self, tree): #self.action = tree.attrib['action'] self._inputs = {} for tag in tree.xpath('.//input'): try: self._inputs[tag.name] = Input.fromTree(tag) except Exception as e: ...
class AutoForm():
__slots__ = ('_inputs') def __init__(self, tree): #self.action = tree.attrib['action'] self._inputs = {} for tag in tree.xpath('.//input'): try: self._inputs[tag.name] = Input.fromTree(tag) except Exception as e: pError('err', e, ...
def set(self): raise Exception("TODO") class InputCheckBox(Input): def __repr__(self): return "[Input/Checkbox: %s %s]" % (self.name, self.value) def set(self, value): self.value = int(not not value) class AutoForm():
64
64
144
4
60
braph/snippets
python/autoforms.py
Python
AutoForm
AutoForm
106
126
106
106
d2f0db522a469e263bc18e2a178870e192ca192b
bigcode/the-stack
train
c1a9a7776e93a735e62d9261
train
class
class InputSubmit(Input): def __repr__(self): return "[Input/Submit: %s %s]" % (self.name, self.value) def set(self): raise Exception("TODO")
class InputSubmit(Input):
def __repr__(self): return "[Input/Submit: %s %s]" % (self.name, self.value) def set(self): raise Exception("TODO")
): def __repr__(self): return "[Input/Hidden: %s %s]" % (self.name, self.value) class InputText(Input): def __repr__(self): return "[Input/Text: %s %s]" % (self.name, self.value) class InputSubmit(Input):
64
64
43
5
59
braph/snippets
python/autoforms.py
Python
InputSubmit
InputSubmit
92
97
92
92
2debf82a9b1adf17aebdaa196b4160b5747723a4
bigcode/the-stack
train
4cc8d723dbffce8dda7e718a
train
function
def autoForms(tree): for form in tree.xpath('.//form'): yield AutoForm(form)
def autoForms(tree):
for form in tree.xpath('.//form'): yield AutoForm(form)
import html import traceback def pError(*args): print(*args) traceback.print_exc() url = 'http://www.spiegel.de/extra/a-961705.html' def getTree(url): result = requests.get(url) return html.fromstring(result.content) def autoForms(tree):
64
64
21
5
59
braph/snippets
python/autoforms.py
Python
autoForms
autoForms
17
19
17
17
0c58bbf32e4c44f507e125fe43d9a942a5675e1a
bigcode/the-stack
train
d91ebe85abe3b31e2b5e6392
train
class
class InputHidden(Input): def __repr__(self): return "[Input/Hidden: %s %s]" % (self.name, self.value)
class InputHidden(Input):
def __repr__(self): return "[Input/Hidden: %s %s]" % (self.name, self.value)
typ = { 'hidden': InputHidden, 'submit': InputSubmit, 'text': InputText, 'checkbox': InputCheckBox }[tree.attrib['type'].lower()] return typ(tree.name, tree.attrib.get('value', '')) class InputHidden(Input):
64
64
32
5
59
braph/snippets
python/autoforms.py
Python
InputHidden
InputHidden
84
86
84
84
8379ba97865fc94ca2a414a1d1f86a1ecf257701
bigcode/the-stack
train
625dd0dff441e8f0063f3f04
train
function
def pError(*args): print(*args) traceback.print_exc()
def pError(*args):
print(*args) traceback.print_exc()
#!/usr/bin/python3 import requests from lxml import html import traceback def pError(*args):
24
64
16
6
17
braph/snippets
python/autoforms.py
Python
pError
pError
7
9
7
7
18804b5a8a435bf2b28b40f3da51a5b1d2581199
bigcode/the-stack
train
0d59fb187b09967060b5608d
train
class
class Select(): __slots__ = ('name', 'value', 'values') def __init__(self, name, values): self.name = name self.values = values self.value = '' def __repr__(self): return "[Select %s: %s (%s)]" % (self.name, self.value, self.values) def fromTree(tree): values =...
class Select():
__slots__ = ('name', 'value', 'values') def __init__(self, name, values): self.name = name self.values = values self.value = '' def __repr__(self): return "[Select %s: %s (%s)]" % (self.name, self.value, self.values) def fromTree(tree): values = {} for...
class Base(): __slots__ = ('name', 'value') def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "[%s: %s]" % (self.name, self.value) class Select():
64
64
192
3
61
braph/snippets
python/autoforms.py
Python
Select
Select
32
60
32
32
fa31f8af85824b2416b949f3eeb28beed3164f78
bigcode/the-stack
train
971a13b5831b92f561ba7cd3
train
function
def getTree(url): result = requests.get(url) return html.fromstring(result.content)
def getTree(url):
result = requests.get(url) return html.fromstring(result.content)
#!/usr/bin/python3 import requests from lxml import html import traceback def pError(*args): print(*args) traceback.print_exc() url = 'http://www.spiegel.de/extra/a-961705.html' def getTree(url):
56
64
20
5
51
braph/snippets
python/autoforms.py
Python
getTree
getTree
13
15
13
13
04480214c7d6ac58f51a86156902902fd2afce6c
bigcode/the-stack
train
34ad87f0efabfa0531216f8e
train
class
class InputText(Input): def __repr__(self): return "[Input/Text: %s %s]" % (self.name, self.value)
class InputText(Input):
def __repr__(self): return "[Input/Text: %s %s]" % (self.name, self.value)
CheckBox }[tree.attrib['type'].lower()] return typ(tree.name, tree.attrib.get('value', '')) class InputHidden(Input): def __repr__(self): return "[Input/Hidden: %s %s]" % (self.name, self.value) class InputText(Input):
64
64
31
5
59
braph/snippets
python/autoforms.py
Python
InputText
InputText
88
90
88
88
c262e58f3f050d89e9e28e84d08b0b038d918422
bigcode/the-stack
train
8cbdd55ae7f801e380ba7617
train
class
class Base(): __slots__ = ('name', 'value') def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "[%s: %s]" % (self.name, self.value)
class Base():
__slots__ = ('name', 'value') def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "[%s: %s]" % (self.name, self.value)
.print_exc() url = 'http://www.spiegel.de/extra/a-961705.html' def getTree(url): result = requests.get(url) return html.fromstring(result.content) def autoForms(tree): for form in tree.xpath('.//form'): yield AutoForm(form) class Base():
64
64
61
3
61
braph/snippets
python/autoforms.py
Python
Base
Base
22
30
22
22
aa69c40eb522290653d33c179bfd124581085359
bigcode/the-stack
train
98663cfb01885d17e0e7c286
train
class
class Input(): __slots__ = ('name', 'value') def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "[%s: %s]" % (self.name, self.value) def set(self, value): self.value = value def fromTree(tree): typ = { ...
class Input():
__slots__ = ('name', 'value') def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "[%s: %s]" % (self.name, self.value) def set(self, value): self.value = value def fromTree(tree): typ = { 'hidden': ...
.attrib, o.text) values[val] = o.text return Select(tree.name, values) def select(self, value): if value not in self.values: raise Exception("Value %s not in %s" % (value, self.name)) self.value = value class Input():
64
64
140
3
60
braph/snippets
python/autoforms.py
Python
Input
Input
62
82
62
62
3715eb650311c258b1a7124cc1c8e8f0b598c7b6
bigcode/the-stack
train
52210422ed75dc3b04fe9345
train
class
class RectGrid(AffineGridWithOrthogonalCentersInterface): """Basic implementation of a rectangular |Grid| on a rectangular domain. The global face, edge and vertex indices are given as follows :: x1 ^ | 6--10---7--11---8 | ...
class RectGrid(AffineGridWithOrthogonalCentersInterface):
"""Basic implementation of a rectangular |Grid| on a rectangular domain. The global face, edge and vertex indices are given as follows :: x1 ^ | 6--10---7--11---8 | | | 3 2 4 3 5 ...
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2019 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np from pymor.grids.interfaces import AffineGridWithOrthogonalCentersInterface fr...
103
256
3,011
13
89
ManuelMBaumann/pymor
src/pymor/grids/rect.py
Python
RectGrid
RectGrid
11
236
11
11
e5ca5e500b6bf27b39a395038e6ae7dcad231a84
bigcode/the-stack
train
0ced64ccfbdf2093777d9a30
train
class
class Emoji(_EmojiTag, AssetMixin): """Represents a custom emoji. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two emoji are the same. .. describe:: x != y ...
class Emoji(_EmojiTag, AssetMixin):
"""Represents a custom emoji. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two emoji are the same. .. describe:: x != y Checks if two emoji are not...
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ...
256
256
1,622
9
246
Enegg/disnake
disnake/emoji.py
Python
Emoji
Emoji
48
264
48
48
94d80ac0586076a0367271a4aeda3ed81878ecec
bigcode/the-stack
train
aa52e7cbf8761ba66351558a
train
class
class ProtectedExpatParser(expatreader.ExpatParser): """An expat parser which disables DTD's and entities by default.""" def __init__(self, forbid_dtd=True, forbid_entities=True, *args, **kwargs): # Python 2.x old style class expatreader.ExpatParser.__init__(self, *args, **kwar...
class ProtectedExpatParser(expatreader.ExpatParser):
"""An expat parser which disables DTD's and entities by default.""" def __init__(self, forbid_dtd=True, forbid_entities=True, *args, **kwargs): # Python 2.x old style class expatreader.ExpatParser.__init__(self, *args, **kwargs) self.forbid_dtd = forbid_dtd self...
, do_raise=False: '{%s}%s' % (ns, obj[0]) if selector is None: selector = name # Build the root element root = TemplateElement(elemname, selector=selector, subselector=subselector, colon_ns=colon_ns) # Build an element to represent all the keys and values elem =...
125
125
418
12
112
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
ProtectedExpatParser
ProtectedExpatParser
933
974
933
933
51639178caf93f5b00a85edecf49633709f91322
bigcode/the-stack
train
c7694c1021bd7a5c49808d46
train
class
class ConstantSelector(object): """Returns a constant.""" def __init__(self, value): """Initialize the selector. :param value: The value to return. """ self.value = value def __repr__(self): """Return a representation of the selector.""" return repr(self....
class ConstantSelector(object):
"""Returns a constant.""" def __init__(self, value): """Initialize the selector. :param value: The value to return. """ self.value = value def __repr__(self): """Return a representation of the selector.""" return repr(self.value) def __call__(self, _...
Selector would return None.""" def __call__(self, obj, do_raise=False): """Returns empty string if the selected value does not exist.""" try: return super(EmptyStringSelector, self).__call__(obj, True) except KeyError: return "" class ConstantSelector(object):
63
64
113
5
58
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
ConstantSelector
ConstantSelector
117
140
117
117
dd2e6b56a902add3369a008483e11b88c9b9dc7e
bigcode/the-stack
train
fff983ecce5e7c7c7427acb8
train
class
class TemplateElement(object): """Represent an element in the template.""" def __init__(self, tag, attrib=None, selector=None, subselector=None, colon_ns=False, **extra): """Initialize an element. Initializes an element in the template. Keyword arguments specify attri...
class TemplateElement(object):
"""Represent an element in the template.""" def __init__(self, tag, attrib=None, selector=None, subselector=None, colon_ns=False, **extra): """Initialize an element. Initializes an element in the template. Keyword arguments specify attributes to be set on the element;...
): # No sense going any further if do_raise: # Convert to a KeyError, for consistency raise KeyError(elem) return None # Return the finally-selected object return obj def get_items(obj): ""...
256
256
2,422
5
250
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
TemplateElement
TemplateElement
143
511
143
143
6f1d56a57a54941b9d8f3ca6f0f4668cb3d9a754
bigcode/the-stack
train
9bea5a4f2e6e151e00d71565
train
class
class MasterTemplate(Template): """Represent a master template. Master templates are versioned derivatives of templates that additionally allow slave templates to be attached. Slave templates allow modification of the serialized result without directly changing the master. """ def __init_...
class MasterTemplate(Template):
"""Represent a master template. Master templates are versioned derivatives of templates that additionally allow slave templates to be attached. Slave templates allow modification of the serialized result without directly changing the master. """ def __init__(self, root, version, nsmap=Non...
dictionary. An overridable hook method to return the namespace dictionary. """ return self.nsmap.copy() def unwrap(self): """Unwraps a template to return a template element.""" # Return the root element return self.root def wrap(self): """Wraps a tem...
198
198
660
6
192
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
MasterTemplate
MasterTemplate
687
779
687
687
2c5a90e373114942345dbc26f2dda48331ccdb33
bigcode/the-stack
train
7d63891fa8468915248a2663
train
function
def get_items(obj): """Get items in obj.""" return list(obj.items())
def get_items(obj):
"""Get items in obj.""" return list(obj.items())
obj[elem] except (KeyError, IndexError): # No sense going any further if do_raise: # Convert to a KeyError, for consistency raise KeyError(elem) return None # Return the finally-selected...
64
64
18
5
58
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
get_items
get_items
100
103
100
100
1f3d596162ce90f400061508cb5ac7ae6ee533d1
bigcode/the-stack
train
a4eb418f9479a52c6fcebc67
train
function
def validate_schema(xml, schema_name, version='v1.1'): if isinstance(xml, str): xml = etree.fromstring(xml) base_path = 'nova/api/openstack/compute/schemas/' if schema_name not in ('atom', 'atom-link'): base_path += '%s/' % version schema_path = os.path.join(utils.novadir(), ...
def validate_schema(xml, schema_name, version='v1.1'):
if isinstance(xml, str): xml = etree.fromstring(xml) base_path = 'nova/api/openstack/compute/schemas/' if schema_name not in ('atom', 'atom-link'): base_path += '%s/' % version schema_path = os.path.join(utils.novadir(), '%s%s.rng' % (base_path, schema_name...
.openstack.org/compute/api/v1.1' XMLNS_COMMON_V10 = 'http://docs.openstack.org/common/api/v1.0' XMLNS_ATOM = 'http://www.w3.org/2005/Atom' def validate_schema(xml, schema_name, version='v1.1'):
64
64
121
15
49
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
validate_schema
validate_schema
38
48
38
38
38db6c1e46523c4260c5f7a7450c322f6e417a02
bigcode/the-stack
train
be77ab1ab5a2746fad4716f1
train
function
def make_links(parent, selector=None): """ Attach an Atom <links> element to the parent. """ elem = SubTemplateElement(parent, '{%s}link' % XMLNS_ATOM, selector=selector) elem.set('rel') elem.set('type') elem.set('href') # Just for completeness... retu...
def make_links(parent, selector=None):
""" Attach an Atom <links> element to the parent. """ elem = SubTemplateElement(parent, '{%s}link' % XMLNS_ATOM, selector=selector) elem.set('rel') elem.set('type') elem.set('href') # Just for completeness... return elem
Return the template return cls._tmpl def construct(self): """Construct a template. Called to construct a template instance, which it must return. Only called once. """ raise NotImplementedError(_("subclasses must implement construct()!")) def make_links(parent, se...
63
64
77
8
55
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
make_links
make_links
882
894
882
882
7bdacded1e746c6772c32f0be12278716e226705
bigcode/the-stack
train
716a9ffcb0ce28e1adff6638
train
class
class TemplateBuilder(object): """Template builder. This class exists to allow templates to be lazily built without having to build them each time they are needed. It must be subclassed, and the subclass must implement the construct() method, which must return a Template (or subclass) instance. T...
class TemplateBuilder(object):
"""Template builder. This class exists to allow templates to be lazily built without having to build them each time they are needed. It must be subclassed, and the subclass must implement the construct() method, which must return a Template (or subclass) instance. The constructor will always ...
between min_vers and max_vers. :param master: The master template to test. """ # Does the master meet our minimum version requirement? if master.version < self.min_vers: return False # How about our maximum version requirement? if self.max_vers is ...
89
89
297
5
83
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
TemplateBuilder
TemplateBuilder
836
879
836
836
7ac6b4ffe1118c203c2abc6a987cebb8e1e04489
bigcode/the-stack
train
b14a02aa324b214257db2bbc
train
function
def make_flat_dict(name, selector=None, subselector=None, ns=None, colon_ns=False): """ Utility for simple XML templates that traditionally used XMLDictSerializer with no metadata. Returns a template element where the top-level element has the given tag name, and where sub-elemen...
def make_flat_dict(name, selector=None, subselector=None, ns=None, colon_ns=False):
""" Utility for simple XML templates that traditionally used XMLDictSerializer with no metadata. Returns a template element where the top-level element has the given tag name, and where sub-elements have tag names derived from the object's keys and text derived from the object's values. This o...
element to the parent. """ elem = SubTemplateElement(parent, '{%s}link' % XMLNS_ATOM, selector=selector) elem.set('rel') elem.set('type') elem.set('href') # Just for completeness... return elem def make_flat_dict(name, selector=None, subselector=None, ...
81
81
273
21
59
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
make_flat_dict
make_flat_dict
897
930
897
898
4f3e93f0322b304b2de2542d620ce2600daa68a3
bigcode/the-stack
train
90b3dccab4f986a547658790
train
class
class EmptyStringSelector(Selector): """Returns the empty string if Selector would return None.""" def __call__(self, obj, do_raise=False): """Returns empty string if the selected value does not exist.""" try: return super(EmptyStringSelector, self).__call__(obj, True) excep...
class EmptyStringSelector(Selector):
"""Returns the empty string if Selector would return None.""" def __call__(self, obj, do_raise=False): """Returns empty string if the selected value does not exist.""" try: return super(EmptyStringSelector, self).__call__(obj, True) except KeyError: return ""
if do_raise: # Convert to a KeyError, for consistency raise KeyError(elem) return None # Return the finally-selected object return obj def get_items(obj): """Get items in obj.""" return list(obj.items())...
64
64
72
7
57
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
EmptyStringSelector
EmptyStringSelector
106
114
106
106
6e1a902ffd20cf8a4067917d32936a974fea8cbd
bigcode/the-stack
train
928461f0d818d8b0feeb804f
train
function
def safe_minidom_parse_string(xml_string): """Parse an XML string using minidom safely.""" try: return minidom.parseString(xml_string, parser=ProtectedExpatParser()) except (sax.SAXParseException, ValueError, expat.ExpatError, LookupError) as e: #NOTE(Vijaya Erukala): XML input s...
def safe_minidom_parse_string(xml_string):
"""Parse an XML string using minidom safely.""" try: return minidom.parseString(xml_string, parser=ProtectedExpatParser()) except (sax.SAXParseException, ValueError, expat.ExpatError, LookupError) as e: #NOTE(Vijaya Erukala): XML input such as # <?xml...
_entity_ref self._parser.NotationDeclHandler = self.notation_decl try: self._parser.SkippedEntityHandler = None except AttributeError: # some pyexpat versions do not support SkippedEntity pass def safe_minidom_parse_string(xml_string):
64
64
125
10
53
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
safe_minidom_parse_string
safe_minidom_parse_string
977
986
977
977
e959fdc50d3700d74ffe04b4fe75fa1b2503d20d
bigcode/the-stack
train
06ac09cc22c7494854800c8f
train
class
class SlaveTemplate(Template): """Represent a slave template. Slave templates are versioned derivatives of templates. Each slave has a minimum version and optional maximum version of the master template to which they can be attached. """ def __init__(self, root, min_vers, max_vers=None, nsmap...
class SlaveTemplate(Template):
"""Represent a slave template. Slave templates are versioned derivatives of templates. Each slave has a minimum version and optional maximum version of the master template to which they can be attached. """ def __init__(self, root, min_vers, max_vers=None, nsmap=None): """Initialize a...
, 'mastertag': self.root.tag} raise ValueError(msg) # Make sure slave applies to this template if not slave.apply(self): continue slave_list.append(slave) # Add the slaves self.slave...
120
120
400
6
113
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
SlaveTemplate
SlaveTemplate
782
833
782
782
352885e33edbd306d16a2d3a9f596be2a8104b33
bigcode/the-stack
train
dee65b55d6628f5d4c537c8e
train
function
def SubTemplateElement(parent, tag, attrib=None, selector=None, subselector=None, colon_ns=False, **extra): """Create a template element as a child of another. Corresponds to the etree.SubElement interface. Parameters are as for TemplateElement, with the addition of the parent. ...
def SubTemplateElement(parent, tag, attrib=None, selector=None, subselector=None, colon_ns=False, **extra):
"""Create a template element as a child of another. Corresponds to the etree.SubElement interface. Parameters are as for TemplateElement, with the addition of the parent. """ # Convert attributes attrib = attrib or {} attrib.update(extra) # Get a TemplateElement elem = TemplateEl...
() for c in self] # Return the result return ('<%s>%s</%s>' % (' '.join(contents), ''.join(children), self.tag)) def SubTemplateElement(parent, tag, attrib=None, selector=None, subselector=None, colon_ns=False, **extra):
64
64
140
26
38
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
SubTemplateElement
SubTemplateElement
514
534
514
515
814f018628096dcacc0f3b57fe75f278b63ad10f
bigcode/the-stack
train
80f42088dad9fa8277e94605
train
class
class Template(object): """Represent a template.""" def __init__(self, root, nsmap=None): """Initialize a template. :param root: The root element of the template. :param nsmap: An optional namespace dictionary to be associated with the root element of the ...
class Template(object):
"""Represent a template.""" def __init__(self, root, nsmap=None): """Initialize a template. :param root: The root element of the template. :param nsmap: An optional namespace dictionary to be associated with the root element of the template. ...
(): contents.append('%s=%r' % (key, value)) # If there are no children, return it as a closed tag if len(self) == 0: return '<%s/>' % ' '.join([str(i) for i in contents]) # OK, recurse to our children children = [c.tree() for c in self] # Return the res...
256
256
924
4
251
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
Template
Template
537
684
537
537
7150d41c4ab9c31092f5702e9f7955506a32e0d1
bigcode/the-stack
train
3c51ba7be3a99041323b336c
train
class
class Selector(object): """Selects datum to operate on from an object.""" def __init__(self, *chain): """Initialize the selector. Each argument is a subsequent index into the object. """ self.chain = chain def __repr__(self): """Return a representation of the sele...
class Selector(object):
"""Selects datum to operate on from an object.""" def __init__(self, *chain): """Initialize the selector. Each argument is a subsequent index into the object. """ self.chain = chain def __repr__(self): """Return a representation of the selector.""" return...
if schema_name not in ('atom', 'atom-link'): base_path += '%s/' % version schema_path = os.path.join(utils.novadir(), '%s%s.rng' % (base_path, schema_name)) schema_doc = etree.parse(schema_path) relaxng = etree.RelaxNG(schema_doc) relaxng.assertValid(xml) class...
81
81
273
4
77
bdelliott/nova
nova/api/openstack/xmlutil.py
Python
Selector
Selector
51
97
51
51
53f2ad404c9ea0669e0e8bb0e08fb3fb73e2c56d
bigcode/the-stack
train
1d7f9b67ec59ea7ba25af4fa
train
class
@unittest.skipIf(sys.platform == 'win32', 'Failed, debug later') class CommonUtilsTestCase(TestCase): @classmethod def setUp(self): init_response() create_mock_experiment() @classmethod def tearDown(self): stop_mock_experiment() @responses.activate def test_get_...
@unittest.skipIf(sys.platform == 'win32', 'Failed, debug later') class CommonUtilsTestCase(TestCase): @classmethod
def setUp(self): init_response() create_mock_experiment() @classmethod def tearDown(self): stop_mock_experiment() @responses.activate def test_get_experiment_status(self): self.assertEqual('RUNNING', get_experiment_status(8080)) @responses.activate ...
_rest, \ trial_ls, list_experiment import unittest from unittest import TestCase, main import responses # FIXME: debug it later # This test case failed on Windows and the output was messed on VSO web. # https://msrasrg.visualstudio.com/NNIOpenSource/_build/results?buildId=15665 @unittest.skipIf(sys.platform == 'win32'...
102
102
342
30
71
qfyin/nni
test/ut/tools/nnictl/test_nnictl_utils.py
Python
CommonUtilsTestCase
CommonUtilsTestCase
22
68
22
24
29b04733d39aa6320b803f5cb3288d15a5c98fdb
bigcode/the-stack
train
4a2117031402fd51cd459633
train
function
def main(argv): im = cv2.imread(argv[1],-1) #read in image im_scaled = np.array(cv2.normalize(im,dst=None,alpha=0,beta=65535,norm_type=cv2.NORM_MINMAX),dtype='uint16') #scale image sf.show_image("test",im_scaled,600,600) #display image on screen #competitive learning algorithm for an image ...
def main(argv):
im = cv2.imread(argv[1],-1) #read in image im_scaled = np.array(cv2.normalize(im,dst=None,alpha=0,beta=65535,norm_type=cv2.NORM_MINMAX),dtype='uint16') #scale image sf.show_image("test",im_scaled,600,600) #display image on screen #competitive learning algorithm for an image ksize = 5 ...
"Some Message"", "git push origin master" #run script using python3 #SOM implementation for automated image segmentation by Daniel Han 24/8/2020 import matplotlib.pyplot as plt import som_functions as sf import sys import cv2 import numpy as np def main(argv):
64
64
214
4
59
dadanhan/som
comp_learn.py
Python
main
main
10
26
10
10
e40915d4466627c4b1283241b2dc956fd6ee7719
bigcode/the-stack
train
7aa748ea27f26d4b33b055ff
train
function
def cases(s): c = 0 for a, b in zip(s, s[len(s) // 2 :]): if a == b == "*": c += 1 elif a != b and not (a == "*" or b == "*"): return 0 return 2 ** c
def cases(s):
c = 0 for a, b in zip(s, s[len(s) // 2 :]): if a == b == "*": c += 1 elif a != b and not (a == "*" or b == "*"): return 0 return 2 ** c
import sys def cases(s):
7
64
70
4
2
ferhatelmas/algo
codeEval/medium/double_trouble.py
Python
cases
cases
4
11
4
4
985a7be3ada45caf62f703e5c5e4d4c46a95814c
bigcode/the-stack
train
cbcf2d808355d93c989a363b
train
class
class Solution: def countSegments(self, s: str) -> int: if s=='': return 0 return sum([1 for c in re.split(' ',s) if c!=''])
class Solution:
def countSegments(self, s: str) -> int: if s=='': return 0 return sum([1 for c in re.split(' ',s) if c!=''])
sequence of non-space characters. # # Please note that the string does not contain any non-printable characters. # # Example: # # Input: "Hello, my name is John" # Output: 5 # # # # @lc code=start import re class Solution:
64
64
45
3
60
Lonitch/hackerRank
434.number-of-segments-in-a-string.py
Python
Solution
Solution
31
36
31
31
a14abc9b07afc12655cd122be2a8b2d49d0b3eaa
bigcode/the-stack
train
87393335c8b245a2eea926f7
train
function
def train_GCNv2(): # Instanize model device = "cuda" if torch.cuda.is_available() else "cpu" print("model train on {}".format(device)) model = GCNv2_tiny().to(device) # Add train code here # Save model (parameter and structure) # NOTE: do not use model.state_dict() here since we want ...
def train_GCNv2(): # Instanize model
device = "cuda" if torch.cuda.is_available() else "cpu" print("model train on {}".format(device)) model = GCNv2_tiny().to(device) # Add train code here # Save model (parameter and structure) # NOTE: do not use model.state_dict() here since we want to store the structure PYTORCH_FILENA...
import sys import torch from arch import GCNv2, GCNv2_tiny def train_GCNv2(): # Instanize model
35
64
111
14
20
XiaoSong9905/GCNv2
models/train.py
Python
train_GCNv2
train_GCNv2
6
18
6
7
d0c488157ce931ae91be659688f16a7e220673eb
bigcode/the-stack
train
557b46b9e404bd25304bb8e6
train
function
def bar_plot(): # x-axis values x = [5, 2, 9, 4, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot the bar plt.bar(x,y) # function to show the plot plt.show()
def bar_plot(): # x-axis values
x = [5, 2, 9, 4, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot the bar plt.bar(x,y) # function to show the plot plt.show()
4, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot plt.plot(x,y) # function to show the plot plt.show() def bar_plot(): # x-axis values
63
64
78
10
53
ultimus11/Data-Visualization
code/visualization.py
Python
bar_plot
bar_plot
17
28
17
18
e0321a4b394f43c802ac24369d583dede6a9bd02
bigcode/the-stack
train
3a00ac48e6e0b4117d1f821c
train
function
def line_plot(): # x-axis values x = [5, 2, 9, 4, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot plt.plot(x,y) # function to show the plot plt.show()
def line_plot(): # x-axis values
x = [5, 2, 9, 4, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot plt.plot(x,y) # function to show the plot plt.show()
# importing matplotlib module from matplotlib import pyplot as plt def line_plot(): # x-axis values
22
64
76
10
11
ultimus11/Data-Visualization
code/visualization.py
Python
line_plot
line_plot
4
15
4
5
21cdc4193163c7fbd1e45ecb956c3ae3bdf35239
bigcode/the-stack
train
bdc2bc5781d91d74f8c86040
train
function
def histogram(): # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot histogram plt.hist(y) # Function to show the plot plt.show()
def histogram(): # Y-axis values
y = [10, 5, 8, 4, 2] # Function to plot histogram plt.hist(y) # Function to show the plot plt.show()
, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot the bar plt.bar(x,y) # function to show the plot plt.show() def histogram(): # Y-axis values
63
64
51
9
54
ultimus11/Data-Visualization
code/visualization.py
Python
histogram
histogram
30
38
30
31
deb49202aeb2b91c938a91cb1733ed6bb5c29c21
bigcode/the-stack
train
d624fc5b88bdd10bb9ed90f6
train
function
def scatter_plot(): # x-axis values x = [5, 2, 9, 4, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot scatter plt.scatter(x, y) # function to show the plot plt.show()
def scatter_plot(): # x-axis values
x = [5, 2, 9, 4, 7] # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot scatter plt.scatter(x, y) # function to show the plot plt.show()
() def histogram(): # Y-axis values y = [10, 5, 8, 4, 2] # Function to plot histogram plt.hist(y) # Function to show the plot plt.show() def scatter_plot(): # x-axis values
62
64
78
10
52
ultimus11/Data-Visualization
code/visualization.py
Python
scatter_plot
scatter_plot
41
52
41
42
6c58c729be7f24e4e6f3ea2638e07bf915a3a8d3
bigcode/the-stack
train
c874264b98a1f7d6e101831a
train
function
def test_manual_call_with_fewer_rows(): features = make_features_with_no_columns(num_rows=2) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b'])
def test_manual_call_with_fewer_rows():
features = make_features_with_no_columns(num_rows=2) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b'])
_rows=0) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, np.array([], dtype=str)) def test_manual_call_with_fewer_rows():
64
64
73
9
55
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_manual_call_with_fewer_rows
test_manual_call_with_fewer_rows
67
75
67
67
dad5c1522969cb200e13ed65972333c9bb4e1736
bigcode/the-stack
train
c4ca10a26384672bfd820455
train
function
def test_constant_call_with_some_rows(): features = make_features_with_no_columns(num_rows=3) encoding = ConstantStringEncoding(constant='abc') values = encoding(features) np.testing.assert_equal(values, 'abc')
def test_constant_call_with_some_rows():
features = make_features_with_no_columns(num_rows=3) encoding = ConstantStringEncoding(constant='abc') values = encoding(features) np.testing.assert_equal(values, 'abc')
0.25], } ) def test_constant_call_with_no_rows(): features = make_features_with_no_columns(num_rows=0) encoding = ConstantStringEncoding(constant='abc') values = encoding(features) np.testing.assert_equal(values, 'abc') def test_constant_call_with_some_rows():
64
64
48
8
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_constant_call_with_some_rows
test_constant_call_with_some_rows
47
53
47
47
068fec6125eb624ed4ceb4ae11a57597fe8d0fff
bigcode/the-stack
train
2cab0285be98baf3449f03da
train
function
def test_constant_call_with_no_rows(): features = make_features_with_no_columns(num_rows=0) encoding = ConstantStringEncoding(constant='abc') values = encoding(features) np.testing.assert_equal(values, 'abc')
def test_constant_call_with_no_rows():
features = make_features_with_no_columns(num_rows=0) encoding = ConstantStringEncoding(constant='abc') values = encoding(features) np.testing.assert_equal(values, 'abc')
) @pytest.fixture def numeric_features() -> pd.DataFrame: return pd.DataFrame( { 'label': [1, 2, 3], 'confidence': [0.5, 1, 0.25], } ) def test_constant_call_with_no_rows():
64
64
48
8
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_constant_call_with_no_rows
test_constant_call_with_no_rows
38
44
38
38
35f2fa95a95ac9434a238ec194555e7e564a13d9
bigcode/the-stack
train
82c96da019d86cc248fb6a70
train
function
def test_format_with_missing_field(features): encoding = FormatStringEncoding(format='{class}: {score:.2f}') with pytest.raises(KeyError): encoding(features)
def test_format_with_missing_field(features):
encoding = FormatStringEncoding(format='{class}: {score:.2f}') with pytest.raises(KeyError): encoding(features)
0.50', 'b: 1.00', 'c: 0.25']) def test_format_with_bad_string(features): encoding = FormatStringEncoding(format='{class}: {confidence:.2f') with pytest.raises(ValueError): encoding(features) def test_format_with_missing_field(features):
64
64
35
8
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_format_with_missing_field
test_format_with_missing_field
124
127
124
124
e3835bd5db1de452e490c6b2e3faa202cbe3dd7f
bigcode/the-stack
train
dc67b5ff0f9f67668aa42ab6
train
function
def test_validate_from_constant_dict(): constant = 'test' argument = {'constant': constant} expected = ConstantStringEncoding(constant=constant) actual = StringEncoding.validate(argument) assert actual == expected
def test_validate_from_constant_dict():
constant = 'test' argument = {'constant': constant} expected = ConstantStringEncoding(constant=constant) actual = StringEncoding.validate(argument) assert actual == expected
) actual = StringEncoding.validate(argument) assert actual == expected def test_validate_from_sequence(): argument = ['a', 'b', 'c'] expected = ManualStringEncoding(array=argument) actual = StringEncoding.validate(argument) assert actual == expected def test_validate_from_constant_dict():
64
64
46
7
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_validate_from_constant_dict
test_validate_from_constant_dict
163
170
163
163
f63fe877d615b9997a5c2c976b0bd75189d02dcf
bigcode/the-stack
train
8ecc04b9f5ff1bab914ddc5a
train
function
def test_validate_from_sequence(): argument = ['a', 'b', 'c'] expected = ManualStringEncoding(array=argument) actual = StringEncoding.validate(argument) assert actual == expected
def test_validate_from_sequence():
argument = ['a', 'b', 'c'] expected = ManualStringEncoding(array=argument) actual = StringEncoding.validate(argument) assert actual == expected
StringEncoding(format=argument) actual = StringEncoding.validate(argument) assert actual == expected def test_validate_from_non_format_string(): argument = 'abc' expected = DirectStringEncoding(feature=argument) actual = StringEncoding.validate(argument) assert actual == expected def test_...
64
64
42
6
57
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_validate_from_sequence
test_validate_from_sequence
154
160
154
154
f88dd92b33eeaf31d6b89a62f86ea10f22db3fa4
bigcode/the-stack
train
f167658489b515b688c041af
train
function
@pytest.fixture def numeric_features() -> pd.DataFrame: return pd.DataFrame( { 'label': [1, 2, 3], 'confidence': [0.5, 1, 0.25], } )
@pytest.fixture def numeric_features() -> pd.DataFrame:
return pd.DataFrame( { 'label': [1, 2, 3], 'confidence': [0.5, 1, 0.25], } )
.fixture def features() -> pd.DataFrame: return pd.DataFrame( { 'class': ['a', 'b', 'c'], 'confidence': [0.5, 1, 0.25], } ) @pytest.fixture def numeric_features() -> pd.DataFrame:
64
64
54
12
52
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
numeric_features
numeric_features
28
35
28
29
51aeff78aaefb54ca1abe67a9215edc54e87ffb3
bigcode/the-stack
train
4cb6ea395b5810937edddbc6
train
function
def test_manual_with_more_rows(): features = make_features_with_no_columns(num_rows=4) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b', 'c', 'd'])
def test_manual_with_more_rows():
features = make_features_with_no_columns(num_rows=4) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b', 'c', 'd'])
3) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b', 'c']) def test_manual_with_more_rows():
63
64
77
7
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_manual_with_more_rows
test_manual_with_more_rows
89
97
89
89
3a58a9ab23a6f8e706de4cf18856ac1b2223ed7c
bigcode/the-stack
train
357940fb336ba912d4f93115
train
function
def test_validate_from_manual_dict(): array = ['a', 'b', 'c'] default = 'd' argument = {'array': array, 'default': default} expected = ManualStringEncoding(array=array, default=default) actual = StringEncoding.validate(argument) assert actual == expected
def test_validate_from_manual_dict():
array = ['a', 'b', 'c'] default = 'd' argument = {'array': array, 'default': default} expected = ManualStringEncoding(array=array, default=default) actual = StringEncoding.validate(argument) assert actual == expected
StringEncoding.validate(argument) assert actual == expected def test_validate_from_constant_dict(): constant = 'test' argument = {'constant': constant} expected = ConstantStringEncoding(constant=constant) actual = StringEncoding.validate(argument) assert actual == expected def test_validat...
64
64
65
7
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_validate_from_manual_dict
test_validate_from_manual_dict
173
181
173
173
543cd1c20c10a25d091d02bb82856fec98b9535b
bigcode/the-stack
train
2a981780b886b2c695e190fb
train
function
def test_validate_from_format_dict(): format = '{class}: {score:.2f}' argument = {'format': format} expected = FormatStringEncoding(format=format) actual = StringEncoding.validate(argument) assert actual == expected
def test_validate_from_format_dict():
format = '{class}: {score:.2f}' argument = {'format': format} expected = FormatStringEncoding(format=format) actual = StringEncoding.validate(argument) assert actual == expected
= StringEncoding.validate(argument) assert actual == expected def test_validate_from_direct_dict(): feature = 'class' argument = {'feature': feature} expected = DirectStringEncoding(feature=feature) actual = StringEncoding.validate(argument) assert actual == expected def test_validate_from...
64
64
50
7
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_validate_from_format_dict
test_validate_from_format_dict
194
201
194
194
dfcff23f79898fd26632e6d58002fabffcc4d2b8
bigcode/the-stack
train
ec7556b2d9a81d33e583017c
train
function
def test_validate_from_format_string(): argument = '{class}: {score:.2f}' expected = FormatStringEncoding(format=argument) actual = StringEncoding.validate(argument) assert actual == expected
def test_validate_from_format_string():
argument = '{class}: {score:.2f}' expected = FormatStringEncoding(format=argument) actual = StringEncoding.validate(argument) assert actual == expected
encoding = FormatStringEncoding(format='{label:d}: {confidence:.2f}') values = encoding(numeric_features) np.testing.assert_array_equal(values, ['1: 0.50', '2: 1.00', '3: 0.25']) def test_validate_from_format_string():
63
64
43
7
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_validate_from_format_string
test_validate_from_format_string
136
142
136
136
d532ee08c2c7559c6d023605cea36334895fc7d1
bigcode/the-stack
train
5b8e26377502889a55634235
train
function
def test_format_with_mixed_feature_numeric_types(numeric_features): encoding = FormatStringEncoding(format='{label:d}: {confidence:.2f}') values = encoding(numeric_features) np.testing.assert_array_equal(values, ['1: 0.50', '2: 1.00', '3: 0.25'])
def test_format_with_mixed_feature_numeric_types(numeric_features):
encoding = FormatStringEncoding(format='{label:d}: {confidence:.2f}') values = encoding(numeric_features) np.testing.assert_array_equal(values, ['1: 0.50', '2: 1.00', '3: 0.25'])
confidence:.2f') with pytest.raises(ValueError): encoding(features) def test_format_with_missing_field(features): encoding = FormatStringEncoding(format='{class}: {score:.2f}') with pytest.raises(KeyError): encoding(features) def test_format_with_mixed_feature_numeric_types(numeric_feature...
64
64
70
13
51
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_format_with_mixed_feature_numeric_types
test_format_with_mixed_feature_numeric_types
130
133
130
130
c931dfcb82479e04caaaa6463c275691508a459c
bigcode/the-stack
train
56c6bb7e3ceba3a2a7174f46
train
function
def test_format(features): encoding = FormatStringEncoding(format='{class}: {confidence:.2f}') values = encoding(features) np.testing.assert_array_equal(values, ['a: 0.50', 'b: 1.00', 'c: 0.25'])
def test_format(features):
encoding = FormatStringEncoding(format='{class}: {confidence:.2f}') values = encoding(features) np.testing.assert_array_equal(values, ['a: 0.50', 'b: 1.00', 'c: 0.25'])
encoding = DirectStringEncoding(feature='class') values = encoding(features) np.testing.assert_array_equal(values, features['class']) def test_direct_with_a_missing_feature(features): encoding = DirectStringEncoding(feature='not_class') with pytest.raises(KeyError): encoding(features) def tes...
64
64
59
5
59
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_format
test_format
112
115
112
112
e52c54c80397bf1ca6bd0a87575bda19a1eb9067
bigcode/the-stack
train
9583dd6dfe26a4767ab07bbb
train
function
def test_manual_call_with_same_rows(): features = make_features_with_no_columns(num_rows=3) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b', 'c'])
def test_manual_call_with_same_rows():
features = make_features_with_no_columns(num_rows=3) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b', 'c'])
_rows=2) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, ['a', 'b']) def test_manual_call_with_same_rows():
63
64
75
8
55
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_manual_call_with_same_rows
test_manual_call_with_same_rows
78
86
78
78
e497c135328f4c50826808869dbe451c8a657401
bigcode/the-stack
train
12f2067781e8262915b2408a
train
function
@pytest.fixture def features() -> pd.DataFrame: return pd.DataFrame( { 'class': ['a', 'b', 'c'], 'confidence': [0.5, 1, 0.25], } )
@pytest.fixture def features() -> pd.DataFrame:
return pd.DataFrame( { 'class': ['a', 'b', 'c'], 'confidence': [0.5, 1, 0.25], } )
ConstantStringEncoding, DirectStringEncoding, FormatStringEncoding, ManualStringEncoding, StringEncoding, ) def make_features_with_no_columns(*, num_rows) -> pd.DataFrame: return pd.DataFrame({}, index=range(num_rows)) @pytest.fixture def features() -> pd.DataFrame:
64
64
53
11
53
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
features
features
18
25
18
19
6e8a864928a3ac0cd02d10c0f9c6df0768b9f305
bigcode/the-stack
train
b8ddf832e997387cafde0d0c
train
function
def test_manual_call_with_no_rows(): features = make_features_with_no_columns(num_rows=0) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, np.array([], dtype=str))
def test_manual_call_with_no_rows():
features = make_features_with_no_columns(num_rows=0) array = ['a', 'b', 'c'] default = 'd' encoding = ManualStringEncoding(array=array, default=default) values = encoding(features) np.testing.assert_array_equal(values, np.array([], dtype=str))
.testing.assert_equal(values, 'abc') def test_constant_call_with_some_rows(): features = make_features_with_no_columns(num_rows=3) encoding = ConstantStringEncoding(constant='abc') values = encoding(features) np.testing.assert_equal(values, 'abc') def test_manual_call_with_no_rows():
64
64
72
8
56
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_manual_call_with_no_rows
test_manual_call_with_no_rows
56
64
56
56
da86e70a533a45d7441b1e256cc5cf5886378d2a
bigcode/the-stack
train
10f4b3b064eec241946a8414
train
function
def test_validate_from_non_format_string(): argument = 'abc' expected = DirectStringEncoding(feature=argument) actual = StringEncoding.validate(argument) assert actual == expected
def test_validate_from_non_format_string():
argument = 'abc' expected = DirectStringEncoding(feature=argument) actual = StringEncoding.validate(argument) assert actual == expected
1.00', '3: 0.25']) def test_validate_from_format_string(): argument = '{class}: {score:.2f}' expected = FormatStringEncoding(format=argument) actual = StringEncoding.validate(argument) assert actual == expected def test_validate_from_non_format_string():
64
64
38
8
55
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
test_validate_from_non_format_string
test_validate_from_non_format_string
145
151
145
145
c170d637905567bb2c418ac51e739321d0b26e80
bigcode/the-stack
train
9250253ba14742305ad04a58
train
function
def make_features_with_no_columns(*, num_rows) -> pd.DataFrame: return pd.DataFrame({}, index=range(num_rows))
def make_features_with_no_columns(*, num_rows) -> pd.DataFrame:
return pd.DataFrame({}, index=range(num_rows))
import numpy as np import pandas as pd import pytest from napari.layers.utils.string_encoding import ( ConstantStringEncoding, DirectStringEncoding, FormatStringEncoding, ManualStringEncoding, StringEncoding, ) def make_features_with_no_columns(*, num_rows) -> pd.DataFrame:
63
64
28
16
47
jojoelfe/napari
napari/layers/utils/_tests/test_string_encoding.py
Python
make_features_with_no_columns
make_features_with_no_columns
14
15
14
14
6fad9de51daaa1c41b6418361860440e894b04da
bigcode/the-stack
train