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
ffd8bdb6aa37285922a26992
train
function
@cli.group() def microk8s(): pass
@cli.group() def microk8s():
pass
seconds.', color='green', ) kubeflow_info(controller, model) @cli.command() @click.argument('CONTROLLER') @click.option('--model', default='kubeflow') def info(controller, model): kubeflow_info(controller, model) @cli.group() def microk8s():
64
64
13
10
54
RFMVasconcelos/bundle-kubeflow
scripts/cli.py
Python
microk8s
microk8s
365
367
365
366
f1fac5252377ee73a61469fc99fe578eb0b4d688
bigcode/the-stack
train
968ca8b28fc60b176bb104cb
train
function
def juju(*args, env=None, die=True): run('juju', *args, env=env, die=die)
def juju(*args, env=None, die=True):
run('juju', *args, env=env, die=die)
import subprocess import sys import tempfile import textwrap import time from pathlib import Path import click import yaml DEFAULT_CONTROLLERS = {'microk8s': 'uk8s', 'aws': 'ckkf'} def juju(*args, env=None, die=True):
63
64
28
12
51
RFMVasconcelos/bundle-kubeflow
scripts/cli.py
Python
juju
juju
18
19
18
18
b104c13fd47afa9a2bed8ab94fa1c4ebe39cc690
bigcode/the-stack
train
235696a56f475d0b1af3b1f1
train
function
@cli.command(name='deploy-to') @click.argument('CONTROLLER') @click.option('--cloud') @click.option('--model', default='kubeflow') @click.option('--channel', default='stable') @click.option('--public-address') @click.option('--build/--no-build', default=False) @click.option('-o', '--overlays', multiple=True) @click.pas...
@cli.command(name='deploy-to') @click.argument('CONTROLLER') @click.option('--cloud') @click.option('--model', default='kubeflow') @click.option('--channel', default='stable') @click.option('--public-address') @click.option('--build/--no-build', default=False) @click.option('-o', '--overlays', multiple=True) @click.pas...
password_overlay = { "applications": { "dex-auth": {"options": {"static-username": "admin", "static-password": password}}, "katib-db": {"options": {"root_password": get_random_pass()}}, "modeldb-db": {"options": {"root_password": get_random_pass()}}, "oidc-gat...
_ip except (KeyError, subprocess.CalledProcessError) as err: pass # If all else fails, just use localhost return 'localhost' def get_random_pass(): """Generates decently long random password.""" return ''.join(random.choices(string.ascii_uppercase + string.digits, k=30)) ####### # CLI ...
256
256
1,169
140
115
RFMVasconcelos/bundle-kubeflow
scripts/cli.py
Python
deploy_to
deploy_to
219
355
219
232
862e7ef2d875ef8b82a1d652f4d465718afd9180
bigcode/the-stack
train
1d38301e6960460cdd1b4222
train
class
class Game: """A basis for all games on the Surrogate.tv platform Game consists of callback methods, which are automatically called by the game engine during the game loop. All messaging with the game engine is done through GameIO class, which is accessed through self.io. The game loop is started w...
class Game:
"""A basis for all games on the Surrogate.tv platform Game consists of callback methods, which are automatically called by the game engine during the game loop. All messaging with the game engine is done through GameIO class, which is accessed through self.io. The game loop is started with a run() ...
] NOT_IMPLEMENTED_DEFAULT_INFO = "not implemented." NOT_IMPLEMENTED_ADDITIONAL_INFO = { "on_init": " No inputs/outputs were registered.", "on_config": " Using the current set.", } # Mapping from GE event to Game loop event names and handler names # This is used for logging and starting the correct event handle...
256
256
3,124
3
253
IvarK/surrortg-sdk
surrortg/game.py
Python
Game
Game
60
489
60
60
736298b1446fb67baa5d9bd16b9f1df50404ad4b
bigcode/the-stack
train
403d23a1f4be250a6309afda
train
class
class RobotHelperX(RobotHelper): def __init__(self, startworld=True, usereal = True, autorotate = False): super(RobotHelperX, self).__init__(startworld=startworld, autorotate = autorotate) import robotconn.yumirapid.yumi_robot as yr import robotconn.yumirapid.yumi_state as ys import...
class RobotHelperX(RobotHelper):
def __init__(self, startworld=True, usereal = True, autorotate = False): super(RobotHelperX, self).__init__(startworld=startworld, autorotate = autorotate) import robotconn.yumirapid.yumi_robot as yr import robotconn.yumirapid.yumi_state as ys import robotconn.rpc.phoxi.phoxi_client ...
Primitive(startarmjnts, direction, distance, [], [[]], obstaclecmlist, type="source") if len(path) > 0: return path else: return None def startworld(self, autorotate = False): """ :return: """ # 1700, -1000, -1000, 300 self.base = pa...
256
256
907
8
247
Photon26/wrs-main-210414
0000_huri/robothelper.py
Python
RobotHelperX
RobotHelperX
278
369
278
279
7278ecc1f72bca12dfc846c34e3565f51bab7828
bigcode/the-stack
train
d17216639ce63a99866d1085
train
class
class RobotHelper(object): def __init__(self, startworld=True, autorotate = False): """ helper function to simplify everything :return: """ self.env = yumisetting.Env() self.obscmlist = self.env.getstationaryobslist() self.rgthndfa = yi.YumiIntegratedFactor...
class RobotHelper(object):
def __init__(self, startworld=True, autorotate = False): """ helper function to simplify everything :return: """ self.env = yumisetting.Env() self.obscmlist = self.env.getstationaryobslist() self.rgthndfa = yi.YumiIntegratedFactory() self.lfthndfa = ...
import numpy as np import utiltools.robotmath as rm from robotsim.robots.dualarm.yumi import yumi from robotsim.robots.dualarm.yumi import yumimesh, yumiball import environment.suitayuminotop as yumisetting import manipulation.grip.yumiintegrated.yumiintegrated as yi from pandaplotutils import pandactrl from motion imp...
162
256
2,415
5
156
Photon26/wrs-main-210414
0000_huri/robothelper.py
Python
RobotHelper
RobotHelper
18
276
18
19
f2d251d7794db3455cdaa8cf4ad1ba1606eb0174
bigcode/the-stack
train
a8d0980db58e833f19dd3fa4
train
class
class Employee: def __init__(self, name, manager): self.name = name self.manager = manager def __repr__(self): return f"{self.name}, {self.manager}"
class Employee:
def __init__(self, name, manager): self.name = name self.manager = manager def __repr__(self): return f"{self.name}, {self.manager}"
= cursor.execute(""" SELECT CONCAT(e.name, ' (', e.job_title, ' )') AS "Employee", CONCAT(m.name, ' (', m.job_title, ' )') AS "Manager" FROM employees e LEFT JOIN employees m ON e.manager_id = m.id; """) class Employee:
64
64
44
3
61
kzborisov/SoftUni
4. Python Web (January 2022)/4.1 Python Web Basics (January 2022)/django_101/postgresSQL/main.py
Python
Employee
Employee
21
27
21
21
5dea9c85e9170d0c5e25a372aa8ce2d103582511
bigcode/the-stack
train
c18b1d831941524e48f857f1
train
class
class RawLoaderTestCase(unittest.TestCase): def _verify_schema1_content(self, schema: SchemaDefinition, source_file, addl_checks: Callable[[SchemaDefinition], None]=None) -> None: expected = loads(f"""{{ "default_prefix": "http://example.org/{source_file}/", ...
class RawLoaderTestCase(unittest.TestCase):
def _verify_schema1_content(self, schema: SchemaDefinition, source_file, addl_checks: Callable[[SchemaDefinition], None]=None) -> None: expected = loads(f"""{{ "default_prefix": "http://example.org/{source_file}/", "name": "{source_file}", "id...
import os import unittest from typing import Callable from jsonasobj import as_json, loads, load, as_dict, JsonObj from linkml_model.meta import SchemaDefinition from linkml.utils.rawloader import load_raw_schema from linkml.utils.schemaloader import SchemaLoader from tests.test_utils.environment import env class Raw...
78
256
893
9
68
bpow/linkml
tests/test_utils/test_load_raw_schema.py
Python
RawLoaderTestCase
RawLoaderTestCase
13
102
13
14
b30dcf11ed8f4fffcd19a0abe5f4e06d0d2647a1
bigcode/the-stack
train
a912aa08c987692e287d8693
train
function
def get_repos_dir(vivp_dir): """returns the repos directory withing vivp_dir""" return os.path.join(vivp_dir, VPACKAGE_HIDDEN, REPOS)
def get_repos_dir(vivp_dir):
"""returns the repos directory withing vivp_dir""" return os.path.join(vivp_dir, VPACKAGE_HIDDEN, REPOS)
else: return False except: return False return True def get_cache_dir(vivp_dir): """returns the chache directory withing vivp_dir""" return os.path.join(vivp_dir, VPACKAGE_HIDDEN) def get_repos_dir(vivp_dir):
64
64
40
10
54
AdityaNG/VPM
libvivp/utils.py
Python
get_repos_dir
get_repos_dir
90
92
90
90
85b73616dda9b4eff8614a1bd91f3dcfb849aa39
bigcode/the-stack
train
d725cd13b43f6dce6ce8c1da
train
function
def replaceAll(s, subs, rep): """ Replaces all substrings in a string with another string """ count = 0 for i in s: if i == subs: count += 1 return s.replace(subs, rep, count)
def replaceAll(s, subs, rep):
""" Replaces all substrings in a string with another string """ count = 0 for i in s: if i == subs: count += 1 return s.replace(subs, rep, count)
░ ▒ ░ ░ ░░ ░▒ ░ ░░ ▒ ░ ░░ ░░ ░ ░ ░ ░ ░ """ def replaceAll(s, subs, rep):
64
64
61
9
55
AdityaNG/VPM
libvivp/utils.py
Python
replaceAll
replaceAll
22
30
22
22
9073b07ab5be5d6ba48b777a8a27083f7c790425
bigcode/the-stack
train
c250b6b1bde58d764df30d13
train
function
def make_safe(s): """Replaces all spaces with '\\ '""" return replaceAll(s, " ", "\\ ")
def make_safe(s):
"""Replaces all spaces with '\\ '""" return replaceAll(s, " ", "\\ ")
All(s, subs, rep): """ Replaces all substrings in a string with another string """ count = 0 for i in s: if i == subs: count += 1 return s.replace(subs, rep, count) def make_safe(s):
64
64
25
5
59
AdityaNG/VPM
libvivp/utils.py
Python
make_safe
make_safe
33
35
33
33
c9a8dfa5740eb99cbde5d6fd83d39c9ba9025c1c
bigcode/the-stack
train
885ed8c940dbeb97a3adf31d
train
function
def is_valid_git_url(u): """Returns True if u is a valid git URL, False otherwise""" try: a = urlparse(u) if a.netloc == "github.com": return True else: return False except: return False return True
def is_valid_git_url(u):
"""Returns True if u is a valid git URL, False otherwise""" try: a = urlparse(u) if a.netloc == "github.com": return True else: return False except: return False return True
_file(vivp_dir, d): """Returns True if d is a file within the directory vivp_dir, False otherwise""" try: open(os.path.join(vivp_dir, d), "r") return True except IOError: return False def is_valid_git_url(u):
64
64
64
7
56
AdityaNG/VPM
libvivp/utils.py
Python
is_valid_git_url
is_valid_git_url
72
82
72
72
db20e138c50e2749141342e815eb010efebadb3a
bigcode/the-stack
train
65dbab1de0f710645508f28d
train
function
def is_sub_file(vivp_dir, d): """Returns True if d is a file within the directory vivp_dir, False otherwise""" try: open(os.path.join(vivp_dir, d), "r") return True except IOError: return False
def is_sub_file(vivp_dir, d):
"""Returns True if d is a file within the directory vivp_dir, False otherwise""" try: open(os.path.join(vivp_dir, d), "r") return True except IOError: return False
_file(d): """Returns True if d is a vpackage.json, False otherwise""" # TODO : Validate the vpackage.json structure and validity try: open(d, "r") return True except IOError: return False def is_sub_file(vivp_dir, d):
64
64
60
11
52
AdityaNG/VPM
libvivp/utils.py
Python
is_sub_file
is_sub_file
63
69
63
63
29fbd48f54c1013647d97b23269bf39f372951b6
bigcode/the-stack
train
4fc1b5d768b00b468fb5eb3c
train
function
def get_cache_dir(vivp_dir): """returns the chache directory withing vivp_dir""" return os.path.join(vivp_dir, VPACKAGE_HIDDEN)
def get_cache_dir(vivp_dir):
"""returns the chache directory withing vivp_dir""" return os.path.join(vivp_dir, VPACKAGE_HIDDEN)
Returns True if u is a valid git URL, False otherwise""" try: a = urlparse(u) if a.netloc == "github.com": return True else: return False except: return False return True def get_cache_dir(vivp_dir):
64
64
37
9
54
AdityaNG/VPM
libvivp/utils.py
Python
get_cache_dir
get_cache_dir
85
87
85
85
8fc640b2e3548cab48319c88e36d8c993e49411c
bigcode/the-stack
train
78a555be7d3e7762c8aadcbe
train
function
def is_vivp_file(d): """Returns True if d is a vpackage.json, False otherwise""" # TODO : Validate the vpackage.json structure and validity try: open(d, "r") return True except IOError: return False
def is_vivp_file(d):
"""Returns True if d is a vpackage.json, False otherwise""" # TODO : Validate the vpackage.json structure and validity try: open(d, "r") return True except IOError: return False
.path.exists(os.path.join(d, VPACKAGE_JSON)): return False # TODO : Validate the vpackage.json file try: # Check if git repo g = Git(d) g.remote() except: return False return True def is_vivp_file(d):
64
64
58
8
55
AdityaNG/VPM
libvivp/utils.py
Python
is_vivp_file
is_vivp_file
53
60
53
53
28986e4127f78a2edadcec5e842b41c92e16b1c0
bigcode/the-stack
train
bd87a1218bb3527ba43548f8
train
function
def is_vivp_dir(d): """Returns True if d is a vivp directory, False otherwise""" return os.path.exists(os.path.join(d, VPACKAGE_JSON)) if not os.path.exists(os.path.join(d, VPACKAGE_JSON)): return False # TODO : Validate the vpackage.json file try: # Check if git repo g = Git(d) ...
def is_vivp_dir(d):
"""Returns True if d is a vivp directory, False otherwise""" return os.path.exists(os.path.join(d, VPACKAGE_JSON)) if not os.path.exists(os.path.join(d, VPACKAGE_JSON)): return False # TODO : Validate the vpackage.json file try: # Check if git repo g = Git(d) g.remote() ...
for i in s: if i == subs: count += 1 return s.replace(subs, rep, count) def make_safe(s): """Replaces all spaces with '\\ '""" return replaceAll(s, " ", "\\ ") def is_vivp_dir(d):
63
64
97
8
55
AdityaNG/VPM
libvivp/utils.py
Python
is_vivp_dir
is_vivp_dir
38
50
38
38
56f445573b808731652fe60feb9e4c59e5dbfb4e
bigcode/the-stack
train
fa605ed7bdb69010292dabab
train
function
def halve_until_1(start): element = start while True: if element < 1: break yield element element = int(element / 2)
def halve_until_1(start):
element = start while True: if element < 1: break yield element element = int(element / 2)
def halve_until_1(start):
7
64
39
7
0
evolutics/sparse-approximation
src/lib/sequence.py
Python
halve_until_1
halve_until_1
1
7
1
1
c2cc8da2115fdca6fbe06854e6dd81c2fd2ca660
bigcode/the-stack
train
e622812f37547302bbcd6ac2
train
function
def ostu(img): area = 0 image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转灰度 blur = cv2.GaussianBlur(image, (5, 5), 0) # 阈值一定要设为 0 !高斯模糊 ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # 二值化 0 = black ; 1 = white # cv2.namedWindow("image", cv2.WINDOW_FREERATIO) # c...
def ostu(img):
area = 0 image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转灰度 blur = cv2.GaussianBlur(image, (5, 5), 0) # 阈值一定要设为 0 !高斯模糊 ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # 二值化 0 = black ; 1 = white # cv2.namedWindow("image", cv2.WINDOW_FREERATIO) # cv2.imshow('imag...
#! /usr/bin/env python # -*- coding: utf-8 -*- import cv2 # from PIL import Image # INFO 2020/6/12 16:12 liliangbin 获取砂子的面积 ############################################二值化砂子像素统计 def ostu(img):
64
66
220
5
58
BorrowHome/flasky-sandbox
app/utils/areas_height/areaS.py
Python
ostu
ostu
10
26
10
10
3706091ebe6b0cce91f6e8a72f228cfb2209d850
bigcode/the-stack
train
b90271d63f3912c5776e55ae
train
function
def trick_or_treat(): """ heavily borrowed from chanrankim's trick_or_treat.ipynb """ return 'trick' if random.random() < .5 else 'treat'
def trick_or_treat():
""" heavily borrowed from chanrankim's trick_or_treat.ipynb """ return 'trick' if random.random() < .5 else 'treat'
import random def trick_or_treat():
9
64
44
6
2
Pseudo-Lab/halloween_devfest
2021/seokhyunseo/give_some_candies_or_not.py
Python
trick_or_treat
trick_or_treat
4
8
4
4
66ff2e8b2e68da0a22b0f804a7b24d71cfc24355
bigcode/the-stack
train
bddbf4d11f837c7f15bffca9
train
function
def give_some_candies_or_not(tot): """ tot : string trick or treat! return: # of candies: int (1~50) if treat None: None if trick """ num_of_candies = random.randint(1, 50) if tot == 'treat': return num_of_candies else: return None
def give_some_candies_or_not(tot):
""" tot : string trick or treat! return: # of candies: int (1~50) if treat None: None if trick """ num_of_candies = random.randint(1, 50) if tot == 'treat': return num_of_candies else: return None
import random def trick_or_treat(): """ heavily borrowed from chanrankim's trick_or_treat.ipynb """ return 'trick' if random.random() < .5 else 'treat' def give_some_candies_or_not(tot):
58
64
87
11
47
Pseudo-Lab/halloween_devfest
2021/seokhyunseo/give_some_candies_or_not.py
Python
give_some_candies_or_not
give_some_candies_or_not
11
23
11
11
81bf72096209fc47827406a77c6201b3b488177d
bigcode/the-stack
train
0277e82de004059c61815ecf
train
class
class CTFDumper: def __init__(self, url, threads=10): self.url = url self.threads_num = threads self.tasks = queue.Queue() self.results_submissions = queue.Queue() self.results_users = queue.Queue() def _worker(self): def get_submission_data(submission_task): ...
class CTFDumper:
def __init__(self, url, threads=10): self.url = url self.threads_num = threads self.tasks = queue.Queue() self.results_submissions = queue.Queue() self.results_users = queue.Queue() def _worker(self): def get_submission_data(submission_task): page_num...
import requests, queue, re, urllib.parse, json, threading, tqdm, time import pandas as pd class CTFDumper:
29
256
1,122
6
22
Ccamm/ctfdumper
ctfdumper/ctfdumper.py
Python
CTFDumper
CTFDumper
4
156
4
5
c4153fc1a0c21368373add4ef204cdf37759f78e
bigcode/the-stack
train
2082aef4fcd99d965b41ff3b
train
function
def positive_nonzero_int(val): ival = positive_int(val) if ival == 0: raise argparse.ArgumentTypeError("must be nonzero") return ival
def positive_nonzero_int(val):
ival = positive_int(val) if ival == 0: raise argparse.ArgumentTypeError("must be nonzero") return ival
def positive_int(val): try: ival = int(val) except ValueError: raise argparse.ArgumentTypeError("must be an integer") if ival < 0: raise argparse.ArgumentTypeError("must be positive") return ival def positive_nonzero_int(val):
64
64
40
7
56
ploth/bcc
tools/offcputime.py
Python
positive_nonzero_int
positive_nonzero_int
32
36
32
32
720b662a485f9d05161c93eeeda4b3f28e764097
bigcode/the-stack
train
82b1dc1d68ff3d79e568639f
train
function
def stack_id_err(stack_id): # -EFAULT in get_stackid normally means the stack-trace is not availible, # Such as getting kernel stack trace in userspace code return (stack_id < 0) and (stack_id != -errno.EFAULT)
def stack_id_err(stack_id): # -EFAULT in get_stackid normally means the stack-trace is not availible, # Such as getting kernel stack trace in userspace code
return (stack_id < 0) and (stack_id != -errno.EFAULT)
if ival == 0: raise argparse.ArgumentTypeError("must be nonzero") return ival def stack_id_err(stack_id): # -EFAULT in get_stackid normally means the stack-trace is not availible, # Such as getting kernel stack trace in userspace code
64
64
59
40
23
ploth/bcc
tools/offcputime.py
Python
stack_id_err
stack_id_err
38
41
38
40
efe739a3af70fd5f6965f19a9bf70b5903ac2b3d
bigcode/the-stack
train
e9b4219068c570875d54329c
train
function
def positive_int(val): try: ival = int(val) except ValueError: raise argparse.ArgumentTypeError("must be an integer") if ival < 0: raise argparse.ArgumentTypeError("must be positive") return ival
def positive_int(val):
try: ival = int(val) except ValueError: raise argparse.ArgumentTypeError("must be an integer") if ival < 0: raise argparse.ArgumentTypeError("must be positive") return ival
License") # # 13-Jan-2016 Brendan Gregg Created this. from __future__ import print_function from bcc import BPF from sys import stderr from time import sleep, strftime import argparse import errno import signal # arg validation def positive_int(val):
64
64
56
5
58
ploth/bcc
tools/offcputime.py
Python
positive_int
positive_int
22
30
22
22
b63cb63e1de24e3a68fabdc5dce953b0abd3c54d
bigcode/the-stack
train
0f419befd0ee410bbfb605a9
train
function
def signal_ignore(signal, frame): print()
def signal_ignore(signal, frame):
print()
argparse.SUPPRESS) args = parser.parse_args() if args.pid and args.tgid: parser.error("specify only one of -p and -t") folded = args.folded duration = int(args.duration) debug = 0 # signal handler def signal_ignore(signal, frame):
64
64
10
7
56
ploth/bcc
tools/offcputime.py
Python
signal_ignore
signal_ignore
109
110
109
109
e60c0d1f4a3f90513571687f80bcbf356d24c880
bigcode/the-stack
train
c82ef3cc4d773d991840146f
train
function
def get_blocking_entities_at_location(entities, destination_x, destination_y): for entity in entities: if entity.blocks and entity.x == destination_x and entity.y == destination_y: return entity return None
def get_blocking_entities_at_location(entities, destination_x, destination_y):
for entity in entities: if entity.blocks and entity.x == destination_x and entity.y == destination_y: return entity return None
to move towards the player (closer to the corridor opening) self.move_towards(target.x, target.y, game_map, entities) # Delete the path to free memory libtcod.path_delete(my_path) def get_blocking_entities_at_location(entities, destination_x, destination_y):
64
64
47
16
48
pypedreams/apoc
entity.py
Python
get_blocking_entities_at_location
get_blocking_entities_at_location
130
135
130
130
f23d52430b00e1c847d19c88c7e0214fcf49c76d
bigcode/the-stack
train
bdc1747b79cf65cde5a2a2e7
train
class
class Entity: """ A generic object to represent players, enemies, items, etc. """ def __init__(self, x, y, char, color, name, blocks=False, render_order=RenderOrder.CORPSE, fighter=None, ai=None, item=None, inventory=None, stairs=None, level=None, equipment=None, equippable=None): ...
class Entity:
""" A generic object to represent players, enemies, items, etc. """ def __init__(self, x, y, char, color, name, blocks=False, render_order=RenderOrder.CORPSE, fighter=None, ai=None, item=None, inventory=None, stairs=None, level=None, equipment=None, equippable=None): self.x = x ...
import libtcodpy as libtcod import math from components.item import Item from render_functions import RenderOrder class Entity:
29
256
1,127
3
25
pypedreams/apoc
entity.py
Python
Entity
Entity
10
127
10
10
ab9bad0e56c683ea8b6158ab093f5b7c4063e0ec
bigcode/the-stack
train
6ccfcf74564441f99da2cb91
train
function
def test_span_extensions(): try: nlp.add_pipe("contextual spellchecker") except BaseException: print("contextual SpellCheck already in pipeline") doc = nlp( "Income was $9.4 milion compared to the prior year of $2.7 milion." ) gold_score = { doc[2]: [], doc[3...
def test_span_extensions():
try: nlp.add_pipe("contextual spellchecker") except BaseException: print("contextual SpellCheck already in pipeline") doc = nlp( "Income was $9.4 milion compared to the prior year of $2.7 milion." ) gold_score = { doc[2]: [], doc[3]: [], doc[4]: [ ...
value in doc._.score_spellCheck.values() for word_score in value ] == [ word_score[0] for value in gold_score.values() for word_score in value ] assert [ word_score[1] for value in doc._.score_spellCheck.values() for word_score in value ] == approx( [ ...
134
134
447
5
129
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_span_extensions
test_span_extensions
427
482
427
427
6bf202840e38bbfed123da57774bef8120405f99
bigcode/the-stack
train
43a4f4dc1e0a6650fd1c9fce
train
function
def test_doc_extensions(): nlp.add_pipe("contextual spellchecker") doc = nlp( "Income was $9.4 milion compared to the prior year of $2.7 milion." ) gold_suggestion = { doc[4]: "million", doc[13]: "million", } gold_outcome = ( "Income was $9.4 million compared to ...
def test_doc_extensions():
nlp.add_pipe("contextual spellchecker") doc = nlp( "Income was $9.4 milion compared to the prior year of $2.7 milion." ) gold_suggestion = { doc[4]: "million", doc[13]: "million", } gold_outcome = ( "Income was $9.4 million compared to the prior year of $2.7 mill...
Sentence) (misspellings, doc) = checker.misspell_identify(doc) doc, suggestions = checker.candidate_generator(doc, misspellings) selectedWord = checker.candidate_ranking(doc, suggestions) # changes made after v0.1 # assert selectedWord == # {doc[key]: value for key, value in misspell.items()} ...
195
195
653
5
189
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_doc_extensions
test_doc_extensions
347
424
347
347
dd1f7a11925a90a124d502cf44e8c6b8d9caae25
bigcode/the-stack
train
560dad33b486cd46578b3ff7
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ("Mr Bond should be skipped", 1), ("Amitabh Bachan should not be in mis spell", 0), ("Amitabh Bachan shuld not be in mis spell", 1), ], ) def test_skipName_misspellIdentify(inputSentence, misspell): print("Start name not in m...
@pytest.mark.parametrize( "inputSentence, misspell", [ ("Mr Bond should be skipped", 1), ("Amitabh Bachan should not be in mis spell", 0), ("Amitabh Bachan shuld not be in mis spell", 1), ], ) def test_skipName_misspellIdentify(inputSentence, misspell):
print("Start name not in misspell word test\n") doc = nlp(inputSentence) # Number should not be skipped for misspell assert doc[misspell] not in checker.misspell_identify(doc)[0]
@pytest.mark.parametrize( "inputSentence, misspell", [ ("Mr Bond should be skipped", 1), ("Amitabh Bachan should not be in mis spell", 0), ("Amitabh Bachan shuld not be in mis spell", 1), ], ) def test_skipName_misspellIdentify(inputSentence, misspell):
77
64
128
77
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_skipName_misspellIdentify
test_skipName_misspellIdentify
98
110
98
106
568bc555c784b60e8ee731f0df372e1004cd6024
bigcode/the-stack
train
3c1f99cac9c0363ec0a56da2
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", [4, 13], ) ], ) def test_type_misspellIdentify(inputSentence, misspell): print("Start type correction test for spelling mistake identifica...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", [4, 13], ) ], ) def test_type_misspellIdentify(inputSentence, misspell):
print("Start type correction test for spelling mistake identification\n") doc = nlp(inputSentence) assert isinstance(checker.misspell_identify(doc)[0], type(misspell)) assert isinstance(checker.misspell_identify(doc)[1], type(doc)) assert checker.misspell_identify(doc)[1] == doc
doc) @pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", [4, 13], ) ], ) def test_type_misspellIdentify(inputSentence, misspell):
64
64
134
62
2
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_type_misspellIdentify
test_type_misspellIdentify
38
52
38
47
35090af68bb5501236c95ca56afb071049300ba4
bigcode/the-stack
train
055e9c30e9d299f00d609c9f
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", True, ), ("This package was introduced in 2020", False), ], ) def test_extension_candidateGenerator(inputSentence, misspell): doc ...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", True, ), ("This package was introduced in 2020", False), ], ) def test_extension_candidateGenerator(inputSentence, misspell):
doc = nlp(inputSentence) (misspellings, doc) = checker.misspell_identify(doc) checker.candidate_generator(doc, misspellings) assert doc._.performed_spellCheck == misspell
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", True, ), ("This package was introduced in 2020", False), ], ) def test_extension_candidateGenerator(inputSentence, misspell):
69
64
117
69
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_extension_candidateGenerator
test_extension_candidateGenerator
220
234
220
230
b06e748a50d589382bc9692075dd30c55ee77b7f
bigcode/the-stack
train
cbccad185ae2f9902df1822e
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", { 4: [ ("million", 0.59422), ("billion", 0.24349), (",", 0.08809), ...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", { 4: [ ("million", 0.59422), ("billion", 0.24349), (",", 0.08809), ...
doc = nlp(inputSentence) (misspellings, doc) = checker.misspell_identify(doc) doc, suggestions = checker.candidate_generator(doc, misspellings) # changes after v0.1.0 assert [tokIndex.i for tokIndex in doc._.score_spellCheck.keys()] == [ tokIndex for tokIndex in misspell.keys() ] as...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", { 4: [ ("million", 0.59422), ("billion", 0.24349), (",", 0.08809), ...
408
183
613
408
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_extension2_candidateGenerator
test_extension2_candidateGenerator
237
310
237
288
5c1b28732d3d305de6eaa23b3b7434c0bf59a3e0
bigcode/the-stack
train
1327537821c2b274237b81a7
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", [4, 13], ), ("This packge was cretaed in 2020", [1, 3]), ], ) def test_identify_misspellIdentify(inputSentence, misspell): print("...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", [4, 13], ), ("This packge was cretaed in 2020", [1, 3]), ], ) def test_identify_misspellIdentify(inputSentence, misspell):
print("Start misspell word identifation test\n") doc = nlp(inputSentence) checkerReturn = checker.misspell_identify(doc)[0] assert isinstance(checkerReturn, list) # Changed the approach after v0.1.0 assert [tok.text_with_ws for tok in checkerReturn] == [ doc[i].text_with_ws for i in miss...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", [4, 13], ), ("This packge was cretaed in 2020", [1, 3]), ], ) def test_identify_misspellIdentify(inputSentence, misspell):
83
64
193
83
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_identify_misspellIdentify
test_identify_misspellIdentify
55
74
55
65
6eea027800b14d33e23f59ca073f3a76ce5fff77
bigcode/the-stack
train
5090a246442f80c58eb3420e
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", { 4: [ "million", "billion", ",", "trillion", ...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", { 4: [ "million", "billion", ",", "trillion", ...
print("Start misspell word identifation test\n") doc = nlp(inputSentence) (misspellings, doc) = checker.misspell_identify(doc) doc, suggestions = checker.candidate_generator(doc, misspellings) # changed after v1.0 because of deepCopy creatng issue with == # gold_suggestions = {doc[key]: value fo...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", { 4: [ "million", "billion", ",", "trillion", ...
225
108
363
225
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_identify_candidateGenerator
test_identify_candidateGenerator
154
215
154
205
f834704c57eee0dfef931ac6b49b01f8d59af496
bigcode/the-stack
train
4776fb5d8d922e24c2b6a171
train
function
def test_warning(): nlp = spacy.load("en_core_web_sm") if "contextual spellchecker" not in nlp.pipe_names: nlp.add_pipe("contextual spellchecker") # merge_ents = nlp.create_pipe("merge_entities") nlp.add_pipe("merge_entities") doc = nlp( "Income was $9.4 milion compared to the prior ...
def test_warning():
nlp = spacy.load("en_core_web_sm") if "contextual spellchecker" not in nlp.pipe_names: nlp.add_pipe("contextual spellchecker") # merge_ents = nlp.create_pipe("merge_entities") nlp.add_pipe("merge_entities") doc = nlp( "Income was $9.4 milion compared to the prior year of $2.7 milion....
doc[4]._.get_suggestion_spellCheck == gold_suggestions # Match words and score separately to incorporate approx fn in pytest assert [word_score[0] for word_score in doc[4]._.score_spellCheck] == [ word_score[0] for word_score in gold_score ] assert [ word_score[1] for word_score in doc[...
139
139
466
4
135
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_warning
test_warning
520
573
520
520
f087dad91d8b9d9740041b9278b06c44add1b333
bigcode/the-stack
train
774fc2741ca5acf5ff7c4544
train
function
@pytest.mark.parametrize( "max_edit_distance,expected_spell_check_flag", [(0, False), (1, False), (2, True), (3, True)], ) def test_max_edit_dist(max_edit_distance, expected_spell_check_flag): nlp = spacy.load("en_core_web_sm") if "contextual spellchecker" in nlp.pipe_names: nlp.remove_pipe("con...
@pytest.mark.parametrize( "max_edit_distance,expected_spell_check_flag", [(0, False), (1, False), (2, True), (3, True)], ) def test_max_edit_dist(max_edit_distance, expected_spell_check_flag):
nlp = spacy.load("en_core_web_sm") if "contextual spellchecker" in nlp.pipe_names: nlp.remove_pipe("contextual spellchecker") # checker_edit_dist = ContextualSpellCheck(max_edit_dist=max_edit_distance) nlp.add_pipe( "contextual spellchecker", config={"max_edit_dist": max_edit_distance} ...
_sm") ContextualSpellCheck(nlp, "contextualSpellCheck", model_name=model_name) except OSError: pytest.fail("Specificed model is not present in transformers") except Exception as uncatched_error: pytest.fail(str(uncatched_error)) @pytest.mark.parametrize( "max_edit_distance,expected_s...
108
108
360
51
57
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_max_edit_dist
test_max_edit_dist
625
657
625
629
579303aa85e20ae72740bf91ebe8886c86e15280
bigcode/the-stack
train
fffbab59b48fedc4f78e2ab0
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ("eng-movies.com shuld be skipped", 0), ("bollywood.in shuld not be in mis spell", 0), ], ) def test_type_candidateGenerator(inputSentence, misspell): doc = nlp(inputSentence) misspell, doc = checker.misspell_identify(doc) as...
@pytest.mark.parametrize( "inputSentence, misspell", [ ("eng-movies.com shuld be skipped", 0), ("bollywood.in shuld not be in mis spell", 0), ], ) def test_type_candidateGenerator(inputSentence, misspell):
doc = nlp(inputSentence) misspell, doc = checker.misspell_identify(doc) assert isinstance(checker.candidate_generator(doc, misspell), tuple) assert isinstance(checker.candidate_generator(doc, misspell)[0], type(doc)) assert isinstance(checker.candidate_generator(doc, misspell)[1], dict)
_identify(doc)[0] @pytest.mark.parametrize( "inputSentence, misspell", [ ("eng-movies.com shuld be skipped", 0), ("bollywood.in shuld not be in mis spell", 0), ], ) def test_type_candidateGenerator(inputSentence, misspell):
64
64
130
58
6
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_type_candidateGenerator
test_type_candidateGenerator
139
151
139
146
2dd9e405bf5deb0dbf01f6f0b5aae7ad45124d5a
bigcode/the-stack
train
9fcd019deb961b2caca1df5f
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ("eng-movies.com should be skipped", 0), ("bollywood.in should not be in mis spell", 0), ], ) def test_skipURL_misspellIdentify(inputSentence, misspell): print("Start URL not in misspell word test\n") doc = nlp(inputSentence) ...
@pytest.mark.parametrize( "inputSentence, misspell", [ ("eng-movies.com should be skipped", 0), ("bollywood.in should not be in mis spell", 0), ], ) def test_skipURL_misspellIdentify(inputSentence, misspell):
print("Start URL not in misspell word test\n") doc = nlp(inputSentence) assert doc[misspell] not in checker.misspell_identify(doc)[0]
ify(doc)[0] @pytest.mark.parametrize( "inputSentence, misspell", [ ("eng-movies.com should be skipped", 0), ("bollywood.in should not be in mis spell", 0), ], ) def test_skipURL_misspellIdentify(inputSentence, misspell):
64
64
99
59
5
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_skipURL_misspellIdentify
test_skipURL_misspellIdentify
126
136
126
133
82a28de3f81155dcf5e01b05d7cad5641d5f59d2
bigcode/the-stack
train
44e3f27d510c9d98554ad43b
train
function
def test_bert_model_name(): model_name = "a_random_model" error_message = ( f"Can't load config for '{model_name}'. Make sure that:\n\n" f"- '{model_name}' is a correct model identifier listed on \ 'https://huggingface.co/models'\n\n" f"- or '{model_name}' is the correct path to a direct...
def test_bert_model_name():
model_name = "a_random_model" error_message = ( f"Can't load config for '{model_name}'. Make sure that:\n\n" f"- '{model_name}' is a correct model identifier listed on \ 'https://huggingface.co/models'\n\n" f"- or '{model_name}' is the correct path to a directory \ containing a config.js...
Check( nlp, "contextualSpellCheck", vocab_path=testVocab, debug=True ) with open(orgDebugFilePath) as f1: with open(debugPathFile) as f2: assert f1.read() == f2.read() def test_bert_model_name():
64
64
142
7
57
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_bert_model_name
test_bert_model_name
598
611
598
598
006c94742e755a18f5493f3aa70d2ae8f4a01c11
bigcode/the-stack
train
80056b0935d38dfcab2a3192
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ("Bond@movies.com should be skipped", 0), ("Amitabh.Bachan@bollywood.in should not be in mis spell", 0), ], ) def test_skipEmail_misspellIdentify(inputSentence, misspell): print("Start Email not in misspell word test\n") doc = nl...
@pytest.mark.parametrize( "inputSentence, misspell", [ ("Bond@movies.com should be skipped", 0), ("Amitabh.Bachan@bollywood.in should not be in mis spell", 0), ], ) def test_skipEmail_misspellIdentify(inputSentence, misspell):
print("Start Email not in misspell word test\n") doc = nlp(inputSentence) assert doc[misspell] not in checker.misspell_identify(doc)[0]
@pytest.mark.parametrize( "inputSentence, misspell", [ ("Bond@movies.com should be skipped", 0), ("Amitabh.Bachan@bollywood.in should not be in mis spell", 0), ], ) def test_skipEmail_misspellIdentify(inputSentence, misspell):
65
64
105
65
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_skipEmail_misspellIdentify
test_skipEmail_misspellIdentify
113
123
113
120
0eafa2f2eed49b597d596f60e58484fc58f77879
bigcode/the-stack
train
1a19666371da2eb9294a33fe
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", 3, ), ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", 12, ), ("This packge ...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", 3, ), ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", 12, ), ("This packge ...
print("Start number not in misspell word test\n") doc = nlp(inputSentence) # Number should not be skipped for misspell assert doc[misspell] not in checker.misspell_identify(doc)[0]
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", 3, ), ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", 12, ), ("This packge ...
106
64
157
106
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_skipNumber_misspellIdentify
test_skipNumber_misspellIdentify
77
95
77
91
0a0ccc84ddccb875a524c5f61bb145748f2ceb48
bigcode/the-stack
train
f2db300c5d2d5a8cccbb7290
train
function
def test_correct_model_name(): model_name = "TurkuNLP/bert-base-finnish-cased-v1" try: nlp = spacy.load("en_core_web_sm") ContextualSpellCheck(nlp, "contextualSpellCheck", model_name=model_name) except OSError: pytest.fail("Specificed model is not present in transformers") except...
def test_correct_model_name():
model_name = "TurkuNLP/bert-base-finnish-cased-v1" try: nlp = spacy.load("en_core_web_sm") ContextualSpellCheck(nlp, "contextualSpellCheck", model_name=model_name) except OSError: pytest.fail("Specificed model is not present in transformers") except Exception as uncatched_error: ...
config.json file\n\n" ) with pytest.raises(OSError) as e: nlp = spacy.load("en_core_web_sm") ContextualSpellCheck(nlp, "contextualSpellCheck", model_name=model_name) assert e == error_message def test_correct_model_name():
64
64
97
6
57
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_correct_model_name
test_correct_model_name
614
622
614
614
46272709b08425c9146198fe4a6f8badc62f6392
bigcode/the-stack
train
bc563d85c7d4fa06f193c7c4
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 million \ compared to the prior year of $2.7 million.", [], ), ("who is Rajat Goel?", []), ("He released this package in year 2020!", []), ], ) def test_no_misspellIdentify(input...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 million \ compared to the prior year of $2.7 million.", [], ), ("who is Rajat Goel?", []), ("He released this package in year 2020!", []), ], ) def test_no_misspellIdentify(input...
print("Start no spelling mistake test\n") doc = nlp(inputSentence) assert checker.misspell_identify(doc) == (misspell, doc)
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 million \ compared to the prior year of $2.7 million.", [], ), ("who is Rajat Goel?", []), ("He released this package in year 2020!", []), ], ) def test_no_misspellIdentify(input...
84
64
119
84
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_no_misspellIdentify
test_no_misspellIdentify
20
35
20
32
552f08d7fcf7c7f0e98a2f95b994a2e351733265
bigcode/the-stack
train
e8c12eb889f12e144c908c51
train
function
def test_compatible_spacyPipeline(): nlp.add_pipe("contextual spellchecker") assert "contextual spellchecker" in nlp.pipe_names nlp.remove_pipe("contextual spellchecker") assert "contextual spellchecker" not in nlp.pipe_names
def test_compatible_spacyPipeline():
nlp.add_pipe("contextual spellchecker") assert "contextual spellchecker" in nlp.pipe_names nlp.remove_pipe("contextual spellchecker") assert "contextual spellchecker" not in nlp.pipe_names
misspell.items()} assert [tok.i for tok in selectedWord.keys()] == [ tok for tok in misspell.keys() ] assert [tokString for tokString in selectedWord.values()] == [ tok for tok in misspell.values() ] def test_compatible_spacyPipeline():
63
64
59
8
55
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_compatible_spacyPipeline
test_compatible_spacyPipeline
339
344
339
339
070d82a7ac5b1d0fa707c634dda24773a01824ef
bigcode/the-stack
train
708bc844b91d482b5d2d04fd
train
function
@pytest.mark.parametrize( "input_sentence,expected_outcome,\ expected_suggestion_doc,possible_misspel_index,misspell_suggestion", [ ( "This is not a pure Python Spell Checking based on Peter Norvig’s \ blog post on setting up a simple spell checking algorithm.", "", {...
@pytest.mark.parametrize( "input_sentence,expected_outcome,\ expected_suggestion_doc,possible_misspel_index,misspell_suggestion", [ ( "This is not a pure Python Spell Checking based on Peter Norvig’s \ blog post on setting up a simple spell checking algorithm.", "", {...
nlp_lg = spacy.load("en_core_web_lg") # checker_deep_tokenize = # ContextualSpellCheck(nlp,"contextualSpellCheck",max_edit_dist=3) nlp_lg.add_pipe("contextual spellchecker", config={"max_edit_dist": 3}) doc = nlp_lg(input_sentence) # To check the status of `performed_spell_check` flag asser...
@pytest.mark.parametrize( "input_sentence,expected_outcome,\ expected_suggestion_doc,possible_misspel_index,misspell_suggestion", [ ( "This is not a pure Python Spell Checking based on Peter Norvig’s \ blog post on setting up a simple spell checking algorithm.", "", {...
211
123
410
211
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_doc_extensions_bug
test_doc_extensions_bug
660
709
660
691
3792e312bbef97b4a89fadb78461cbaf24d7aac4
bigcode/the-stack
train
f136b0d7b3f51ecefcdaff93
train
function
def test_vocab_file(): with warnings.catch_warnings(record=True) as w: nlp = spacy.load("en_core_web_sm") ContextualSpellCheck( nlp, "contextualSpellCheck", vocab_path="testing.txt" ) assert any([issubclass(i.category, UserWarning) for i in w]) assert any(["Using ...
def test_vocab_file():
with warnings.catch_warnings(record=True) as w: nlp = spacy.load("en_core_web_sm") ContextualSpellCheck( nlp, "contextualSpellCheck", vocab_path="testing.txt" ) assert any([issubclass(i.category, UserWarning) for i in w]) assert any(["Using default vocab" in str(i...
million") assert e.type is ValueError try: nlp = spacy.load("en_core_web_sm") ContextualSpellCheck(nlp, "contextualSpellCheck", max_edit_dist="3.1") except Exception as uncatched_error: pytest.fail(str(uncatched_error)) def test_vocab_file():
71
71
238
5
66
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_vocab_file
test_vocab_file
576
595
576
576
263d04f079983aab6b60e60f9111017033947c15
bigcode/the-stack
train
c0bc593b1823f3a4a07623e0
train
function
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", {4: "million", 13: "million"}, ), ("This package was introduced in 2020", {}), ], ) def test_ranking_candidateRanking(inputSentence, m...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", {4: "million", 13: "million"}, ), ("This package was introduced in 2020", {}), ], ) def test_ranking_candidateRanking(inputSentence, m...
doc = nlp(inputSentence) (misspellings, doc) = checker.misspell_identify(doc) doc, suggestions = checker.candidate_generator(doc, misspellings) selectedWord = checker.candidate_ranking(doc, suggestions) # changes made after v0.1 # assert selectedWord == # {doc[key]: value for key, value in m...
@pytest.mark.parametrize( "inputSentence, misspell", [ ( "Income was $9.4 milion compared to the prior year of $2.7 milion.", {4: "million", 13: "million"}, ), ("This package was introduced in 2020", {}), ], ) def test_ranking_candidateRanking(inputSentence, m...
79
64
215
79
0
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_ranking_candidateRanking
test_ranking_candidateRanking
313
336
313
323
8f8f4b165b50834a2920dbc55d2ed07b0de29728
bigcode/the-stack
train
b8aa91f3b5ae95dd361a671d
train
function
def test_token_extension(): if "contextual spellchecker" not in nlp.pipe_names: nlp.add_pipe("contextual spellchecker") doc = nlp( "Income was $9.4 milion compared to the prior year of $2.7 milion." ) gold_suggestions = "million" gold_score = [ ("million", 0.59422), ...
def test_token_extension():
if "contextual spellchecker" not in nlp.pipe_names: nlp.add_pipe("contextual spellchecker") doc = nlp( "Income was $9.4 milion compared to the prior year of $2.7 milion." ) gold_suggestions = "million" gold_score = [ ("million", 0.59422), ("billion", 0.24349), ...
] == approx( [ word_score[1] for value in gold_score.values() for word_score in value ], rel=1e-4, abs=1e-4, ) # assert doc[2:6]._.score_spellCheck == # approx(gold_score,rel=1e-4, abs=1e-4) nlp.remove_pipe("contextual spellchecker") ...
98
98
328
5
93
dc-aichara/contextualSpellCheck
contextualSpellCheck/tests/test_contextualSpellCheck.py
Python
test_token_extension
test_token_extension
485
517
485
485
74e443ea18da80e728fd1e058f32b3a7663e505d
bigcode/the-stack
train
26947dfc055fceb66cb9daef
train
function
def timeout(duration, default=None): def decorator(func): class InterruptableThread(threading.Thread): def __init__(self, args, kwargs): threading.Thread.__init__(self) self.args = args self.kwargs = kwargs self.result = default ...
def timeout(duration, default=None):
def decorator(func): class InterruptableThread(threading.Thread): def __init__(self, args, kwargs): threading.Thread.__init__(self) self.args = args self.kwargs = kwargs self.result = default self.daemon = True ...
from sklearn.cluster import DBSCAN class TestTimeoutException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # thanks to https://gist.github.com/vadimg/2902788 def timeout(duration, default=None):
64
64
194
7
56
sherbold/replication-kit-2020-smoke-testing
generated-tests/sklearn/test_SKLEARN_DBSCAN.py
Python
timeout
timeout
24
52
24
24
f0cd944e960ad6d960f1169f8e34a10e2e387154
bigcode/the-stack
train
a297efdaf809c7495d4b1ba2
train
class
class test_SKLEARN_DBSCAN(unittest.TestCase): params = [("{'p':None,'min_samples':5,'leaf_size':50,'metric':'euclidean','n_jobs':None,'eps':0.1,'algorithm':'auto',}", {'p':None,'min_samples':5,'leaf_size':50,'metric':'euclidean','n_jobs':None,'eps':0.1,'algorithm':'auto',}), ("{'p':None,'min_samples'...
class test_SKLEARN_DBSCAN(unittest.TestCase):
params = [("{'p':None,'min_samples':5,'leaf_size':50,'metric':'euclidean','n_jobs':None,'eps':0.1,'algorithm':'auto',}", {'p':None,'min_samples':5,'leaf_size':50,'metric':'euclidean','n_jobs':None,'eps':0.1,'algorithm':'auto',}), ("{'p':None,'min_samples':5,'leaf_size':50,'metric':'euclidean','n_jobs'...
class TestTimeoutException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # thanks to https://gist.github.com/vadimg/2902788 def timeout(duration, default=None): def decorator(func): class InterruptableThread(threading.Thread)...
256
256
3,803
11
244
sherbold/replication-kit-2020-smoke-testing
generated-tests/sklearn/test_SKLEARN_DBSCAN.py
Python
test_SKLEARN_DBSCAN
test_SKLEARN_DBSCAN
54
315
54
55
1b7ea1a33093b5a7ce0ab8921fe79ab69ad477e1
bigcode/the-stack
train
dcc231be9e2f8af201bc646c
train
class
class TestTimeoutException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
class TestTimeoutException(Exception):
def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
threading import functools import inspect import math import warnings import traceback from parameterized import parameterized from scipy.io.arff import loadarff from scipy.stats import ttest_1samp, ks_2samp from sklearn.cluster import DBSCAN class TestTimeoutException(Exception):
64
64
34
6
57
sherbold/replication-kit-2020-smoke-testing
generated-tests/sklearn/test_SKLEARN_DBSCAN.py
Python
TestTimeoutException
TestTimeoutException
17
21
17
17
9f2d76cf9a4b7b15b7e682a99d1a7ce9592e70cb
bigcode/the-stack
train
9c65f56f31230b576a170d0b
train
function
def test_datetime_from_iso_timestamp(): # arrange t = VatsimGeneral( "1", # version "1", # reload "00000", # update "2021-04-27T18:39:55", # timestamp 1, # connected clients 1, # unique clients ) # act dt = t.get_datetime() print(dt.timetz.__...
def test_datetime_from_iso_timestamp(): # arrange
t = VatsimGeneral( "1", # version "1", # reload "00000", # update "2021-04-27T18:39:55", # timestamp 1, # connected clients 1, # unique clients ) # act dt = t.get_datetime() print(dt.timetz.__repr__) # assert assert dt == datetime.fromis...
from datetime import datetime import pytest from ..models.models import VatsimGeneral def test_datetime_from_iso_timestamp(): # arrange
29
64
128
11
17
ahuimanu/vatsimlib
tests/test_models.py
Python
test_datetime_from_iso_timestamp
test_datetime_from_iso_timestamp
7
22
7
8
9e0b5bbbe2d424d83e5a166fcc28ed0d2b9474a5
bigcode/the-stack
train
87969e60d8aa61130bceb719
train
function
def test_generator_local_git_repo_root_directory(): """Generator for tests requiring operation in a git repository. This will move into a temporary directory which is a git repository. It will then return the tests with the given script and settings list. When called by nosetests, nosetests will run e...
def test_generator_local_git_repo_root_directory():
"""Generator for tests requiring operation in a git repository. This will move into a temporary directory which is a git repository. It will then return the tests with the given script and settings list. When called by nosetests, nosetests will run every yielded test function. Yields: A :...
_creation_fails_if_located_inside_local_git_repository_root_directory", 'arguments': "test_module_git_root_directory", 'exception_type': "VerificationError", 'exception_string': "Currently in a git repository, please move elsewhere and try again.", }, ] def test_generator_local_git_repo_r...
64
64
161
9
55
hir12111/dls_ade
system_testing/start_new_module/local_verification_tests.py
Python
test_generator_local_git_repo_root_directory
test_generator_local_git_repo_root_directory
78
103
78
78
e811bfcb7c951e941e3d8b11958a8327f06989ed
bigcode/the-stack
train
9fe81c6e198ac29c28f8e113
train
function
def test_generator_conflicting_filepaths_expected(): """Generator for tests involving a conflict of filepaths. This will move into a temporary directory which already has a number of folders that will conflict with the file creation process. It will then return the tests with the given script and setti...
def test_generator_conflicting_filepaths_expected():
"""Generator for tests involving a conflict of filepaths. This will move into a temporary directory which already has a number of folders that will conflict with the file creation process. It will then return the tests with the given script and settings list. When called by nosetests, nosetests wi...
VerificationError", 'exception_string': "Directory testB21/testB21-EA-IOC-01 already exists, please move elsewhere and try again.", 'create_folder': "testB21/testB21-EA-IOC-01" }, ] def test_generator_conflicting_filepaths_expected():
64
64
183
9
55
hir12111/dls_ade
system_testing/start_new_module/local_verification_tests.py
Python
test_generator_conflicting_filepaths_expected
test_generator_conflicting_filepaths_expected
35
62
35
35
5d19b47e509c011dc4824e4f67f6b1e3fa8bbf43
bigcode/the-stack
train
7610c711718b4912bdab2eb2
train
class
class TranslateService: translator = Translator() def __init__(self): return def translate(self, text, src, dest): t = self.translator.translate(text, src=src, dest=dest) return t.text
class TranslateService:
translator = Translator() def __init__(self): return def translate(self, text, src, dest): t = self.translator.translate(text, src=src, dest=dest) return t.text
from googletrans import Translator class TranslateService:
10
64
52
4
5
alejandro-mosso/language-service
app/translate/services.py
Python
TranslateService
TranslateService
4
13
4
5
7998f529d8280cc2ee0e6820ed0cd79bfa53a5be
bigcode/the-stack
train
90a9aaa48c78552190638fc2
train
function
def random_name_generator(first, second, x): """ Generates random names. Arguments: - list of first names - list of last names - number of random names """ names = [] for i in range(x): names.append("{0} {1}".format(choice(first), choice(second))) r...
def random_name_generator(first, second, x):
""" Generates random names. Arguments: - list of first names - list of last names - number of random names """ names = [] for i in range(x): names.append("{0} {1}".format(choice(first), choice(second))) return set(names)
from random import choice def random_name_generator(first, second, x):
15
64
75
10
4
webdevhub42/Lambda
WEEKS/CD_Sata-Structures/_RESOURCES/python-prac/python-scripts/scripts/13_random_name_generator.py
Python
random_name_generator
random_name_generator
4
15
4
4
4334aea2d2a8400fd29600a1fab76ed9226596a6
bigcode/the-stack
train
1c4376ddaf609f6413038982
train
function
@register.inclusion_tag("admin/includes/recent_comments.html", takes_context=True) def recent_comments(context): """ Dashboard widget for displaying recent comments. """ latest = context["settings"].COMMENTS_NUM_LATEST comments = ThreadedComment.objects.all().select_related("user") context["comm...
@register.inclusion_tag("admin/includes/recent_comments.html", takes_context=True) def recent_comments(context):
""" Dashboard widget for displaying recent comments. """ latest = context["settings"].COMMENTS_NUM_LATEST comments = ThreadedComment.objects.all().select_related("user") context["comments"] = comments.order_by("-id")[:latest] return context.flatten()
_comments"].get(parent_id, []), "no_comments": parent_id is None and not context["all_comments"], "replied_to": replied_to, } ) return context.flatten() @register.inclusion_tag("admin/includes/recent_comments.html", takes_context=True) def recent_comments(context):
64
64
80
22
42
DatCGI2net/mezzanine
mezzanine/generic/templatetags/comment_tags.py
Python
recent_comments
recent_comments
68
76
68
69
12db31872da18904fbc564a54146f29b49c4e60c
bigcode/the-stack
train
84c5ae96f7acd553de862c29
train
function
@register.filter def comment_filter(comment_text): """ Passed comment text to be rendered through the function defined by the ``COMMENT_FILTER`` setting. If no function is defined (the default), Django's ``linebreaksbr`` and ``urlize`` filters are used. """ filter_func = settings.COMMENT_FIL...
@register.filter def comment_filter(comment_text):
""" Passed comment text to be rendered through the function defined by the ``COMMENT_FILTER`` setting. If no function is defined (the default), Django's ``linebreaksbr`` and ``urlize`` filters are used. """ filter_func = settings.COMMENT_FILTER if not filter_func: def filter_fun...
widget for displaying recent comments. """ latest = context["settings"].COMMENTS_NUM_LATEST comments = ThreadedComment.objects.all().select_related("user") context["comments"] = comments.order_by("-id")[:latest] return context.flatten() @register.filter def comment_filter(comment_text):
64
64
129
10
54
DatCGI2net/mezzanine
mezzanine/generic/templatetags/comment_tags.py
Python
comment_filter
comment_filter
79
95
79
80
c2c5167bdbda0db2caa6cfc8237c86100e797061
bigcode/the-stack
train
7c31f9fddedb0f384eb37f22
train
function
@register.inclusion_tag("generic/includes/comments.html", takes_context=True) def comments_for(context, obj): """ Provides a generic context variable name for the object that comments are being rendered for. """ form_class = import_dotted_path(settings.COMMENT_FORM_CLASS) form = form_class(conte...
@register.inclusion_tag("generic/includes/comments.html", takes_context=True) def comments_for(context, obj):
""" Provides a generic context variable name for the object that comments are being rendered for. """ form_class = import_dotted_path(settings.COMMENT_FORM_CLASS) form = form_class(context["request"], obj) context_form = context.get("posted_comment_form", form) context.update( { ...
reverse from mezzanine import template from mezzanine.conf import settings from mezzanine.generic.models import ThreadedComment from mezzanine.utils.importing import import_dotted_path register = template.Library() @register.inclusion_tag("generic/includes/comments.html", takes_context=True) def comments_for(context...
64
64
146
22
42
DatCGI2net/mezzanine
mezzanine/generic/templatetags/comment_tags.py
Python
comments_for
comments_for
14
33
14
15
62319d68c6f0686e1c3a26ccd77deb41f8c138fa
bigcode/the-stack
train
fb8c2d64c94a0b79af926937
train
function
@register.inclusion_tag("generic/includes/comment.html", takes_context=True) def comment_thread(context, parent): """ Return a list of child comments for the given parent, storing all comments in a dict in the context when first called, using parents as keys for retrieval on subsequent recursive calls f...
@register.inclusion_tag("generic/includes/comment.html", takes_context=True) def comment_thread(context, parent):
""" Return a list of child comments for the given parent, storing all comments in a dict in the context when first called, using parents as keys for retrieval on subsequent recursive calls from the comments template. """ if "all_comments" not in context: comments = defaultdict(list) ...
"posted_comment_form": context_form if context_form.target_object == obj else form, "unposted_comment_form": form, "comment_url": reverse("comment"), "object_for_comments": obj, } ) return context.flatten() @register.inclusion_tag("generic/inc...
78
78
263
22
56
DatCGI2net/mezzanine
mezzanine/generic/templatetags/comment_tags.py
Python
comment_thread
comment_thread
36
65
36
37
061fe239106c412f8ce161044a817e034be33a54
bigcode/the-stack
train
6d37aa215268fe952a50c4ad
train
function
def by_id( move_data: DataFrame, id_: Optional[int] = None, label_id: Optional[Text] = TRAJ_ID, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]: """ Filters trajectories points according to specified trajectory id. Parameters ---------- ...
def by_id( move_data: DataFrame, id_: Optional[int] = None, label_id: Optional[Text] = TRAJ_ID, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
""" Filters trajectories points according to specified trajectory id. Parameters ---------- move_data : dataframe The input trajectory data id_ : int Specifies the number of the id used to filter the trajectories points label_id : str, optional The label of the colum...
return move_data.drop(index=move_data[~filter_].index, inplace=inplace) def by_id( move_data: DataFrame, id_: Optional[int] = None, label_id: Optional[Text] = TRAJ_ID, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
81
81
273
61
20
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
by_id
by_id
214
249
214
220
ba4d1b0a048fb85042e1cbe987d64e7622b64e7b
bigcode/the-stack
train
2ed1322fdaa66bdfa4fb9647
train
function
def by_datetime( move_data: DataFrame, start_datetime: Optional[Text] = None, end_datetime: Optional[Text] = None, filter_out: Optional[bool] = False, inplace: Optional[bool] = False, ) -> Optional[DataFrame]: """ Filters trajectories points according to specified time range. Parameters...
def by_datetime( move_data: DataFrame, start_datetime: Optional[Text] = None, end_datetime: Optional[Text] = None, filter_out: Optional[bool] = False, inplace: Optional[bool] = False, ) -> Optional[DataFrame]:
""" Filters trajectories points according to specified time range. Parameters ---------- move_data : dataframe The input trajectory data start_datetime : str The start date and time (Datetime format) of the time range, by default None end_datetime : str The end date ...
[2]) & (move_data[LONGITUDE] <= bbox[3]) ) if filter_out: filter_ = ~filter_ return move_data.drop(index=move_data[~filter_].index, inplace=inplace) def by_datetime( move_data: DataFrame, start_datetime: Optional[Text] = None, end_datetime: Optional[Text] = None, filter_out:...
112
112
375
61
51
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
by_datetime
by_datetime
125
171
125
131
c6b0ef1f00988a8d42fd39e6c1db6280f0a71492
bigcode/the-stack
train
f0b2541b0e3898e3833a3dff
train
function
def by_tid( move_data: DataFrame, tid_: Optional[Text] = None, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]: """ Filters trajectories points according to a specified trajectory tid. Parameters ---------- move_data : dataframe ...
def by_tid( move_data: DataFrame, tid_: Optional[Text] = None, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
""" Filters trajectories points according to a specified trajectory tid. Parameters ---------- move_data : dataframe The input trajectory data tid_ : str Specifies the number of the tid used to filter the trajectories points label_tid : str, optional The label of th...
Returns dataframe with trajectories points filtered by id or None """ return by_label(move_data, id_, label_id, filter_out, inplace) def by_tid( move_data: DataFrame, tid_: Optional[Text] = None, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
79
79
265
49
30
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
by_tid
by_tid
252
285
252
257
3488c43b2e1580489300f466f6f1b26841623b09
bigcode/the-stack
train
374f8a7731bf7bf7c14ca26a
train
function
def clean_trajectories_short_and_few_points( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TID, min_trajectory_distance: Optional[float] = 100, min_points_per_trajectory: Optional[int] = 2, label_dtype: Optional[Callable] = np.float64, inplace: Optional...
def clean_trajectories_short_and_few_points( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TID, min_trajectory_distance: Optional[float] = 100, min_points_per_trajectory: Optional[int] = 2, label_dtype: Optional[Callable] = np.float64, inplace: Optional...
""" Eliminates from the given dataframe trajectories with fewer points and shorter length. Parameters ---------- move_data : dataframe The input trajectory data label_id : str, optional The label of the column which contains the tid of the trajectories, by default TID min_tr...
'\n...Tids before drop: %s' % move_df[label_tid].unique().shape[0] ) move_df.drop(index=idx, inplace=True) logger.debug( '\n...Tids after drop: %s' % move_df[label_tid].unique().shape[0] ) logger.debug( '\n...Shape - before drop: %...
227
227
757
114
112
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_trajectories_short_and_few_points
clean_trajectories_short_and_few_points
855
942
855
862
b57d82252731946250848272f82027457f457f64
bigcode/the-stack
train
c65b265fb2390f028e91050f
train
function
def clean_gps_nearby_points_by_speed( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, speed_radius: Optional[float] = 0.0, label_dtype: Optional[Callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'Dask...
def clean_gps_nearby_points_by_speed( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, speed_radius: Optional[float] = 0.0, label_dtype: Optional[Callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'Dask...
""" Removes points from the trajectories with smaller speed of travel. Parameters ---------- move_data : dataframe The input trajectory data label_id : str, optional Indicates the label of the id column in the user dataframe, be defalt TRAJ_ID speed_radius : float, optional...
arg2=radius_area, outliers=False ) if not inplace: return move_df def clean_gps_nearby_points_by_speed( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, speed_radius: Optional[float] = 0.0, label_dtype: Optional[Callable] = np.flo...
123
123
412
100
22
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_gps_nearby_points_by_speed
clean_gps_nearby_points_by_speed
653
707
653
659
1e3b7427004338d8c0dd158be5fc322e45ea0434
bigcode/the-stack
train
9cc3edd59c644958fdb68c0b
train
function
def clean_gps_jumps_by_distance( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, jump_coefficient: Optional[float] = 3.0, threshold: Optional[float] = 1, label_dtype: Optional[callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional...
def clean_gps_jumps_by_distance( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, jump_coefficient: Optional[float] = 3.0, threshold: Optional[float] = 1, label_dtype: Optional[callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional...
""" Removes the trajectories points that are outliers from the dataframe. Parameters ---------- move_data : dataframe The input trajectory data label_id : str, optional Indicates the label of the id column in the user dataframe, by default TRAJ_ID jump_coefficient : float, ...
logger.debug('%s GPS points were dropped' % sum_drop) return move_data def clean_gps_jumps_by_distance( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, jump_coefficient: Optional[float] = 3.0, threshold: Optional[float] = 1, label_dtype: Opt...
130
130
435
111
18
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_gps_jumps_by_distance
clean_gps_jumps_by_distance
534
592
534
541
e8844532b2ddfeae1c65354ac6b75b49238852b2
bigcode/the-stack
train
defca5a3071a33269f861696
train
function
def clean_consecutive_duplicates( move_data: DataFrame, subset: Optional[Union[int, Text]] = None, keep: Optional[Union[Text, bool]] = 'first', inplace: Optional[bool] = False ) -> Optional[DataFrame]: """ Removes consecutive duplicate rows of the Dataframe. Optionally only certain columns ...
def clean_consecutive_duplicates( move_data: DataFrame, subset: Optional[Union[int, Text]] = None, keep: Optional[Union[Text, bool]] = 'first', inplace: Optional[bool] = False ) -> Optional[DataFrame]:
""" Removes consecutive duplicate rows of the Dataframe. Optionally only certain columns can be consider. Parameters ---------- move_data : dataframe The input trajectory data subset : Array of strs, optional Specifies Column label or sequence of labels, considered for ...
logger.debug('...Filtering jumps \n') return move_data.drop(index=move_data[~filter_].index, inplace=inplace) else: logger.warning('...Distances features were not created') return move_data def clean_consecutive_duplicates( move_data: DataFrame, subset: Optional[Union[int, Text]] =...
106
106
356
58
47
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_consecutive_duplicates
clean_consecutive_duplicates
354
399
354
359
8d1cdc1c86d31bff57d5432f2984c3a7847d8ece
bigcode/the-stack
train
17edb5869607f130a1d488ab
train
function
def by_bbox( move_data: DataFrame, bbox: Tuple[int, int, int, int], filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]: """ Filters points of the trajectories according to specified bounding box. Parameters ---------- move_data : dataframe ...
def by_bbox( move_data: DataFrame, bbox: Tuple[int, int, int, int], filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
""" Filters points of the trajectories according to specified bounding box. Parameters ---------- move_data : dataframe The input trajectories data bbox : tuple Tuple of 4 elements, containing the minimum and maximum values of latitude and longitude of the bounding box. ...
.cos(lat)) lonmin = lon - delta_lon lonmax = lon + delta_lon return np.rad2deg([latmin, lonmin, latmax, lonmax]) def by_bbox( move_data: DataFrame, bbox: Tuple[int, int, int, int], filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
91
91
305
51
40
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
by_bbox
by_bbox
84
122
84
89
91f10be252344e76cbf8fa1cc64d3a020b623393
bigcode/the-stack
train
57ff0c194b694d473114740e
train
function
def _filter_speed_max_radius(move_data: DataFrame, **kwargs): """ Filters from a dataframe rows with current or previous row features exceeding value. Parameters ---------- move_data : dataframe Dataframe to be filtered. **kwargs : arguments - arg1 : feature - arg2 : val...
def _filter_speed_max_radius(move_data: DataFrame, **kwargs):
""" Filters from a dataframe rows with current or previous row features exceeding value. Parameters ---------- move_data : dataframe Dataframe to be filtered. **kwargs : arguments - arg1 : feature - arg2 : value Returns ------- DataFrame Filtered dat...
- arg1 : feature - arg2 : value Returns ------- DataFrame Filtered dataframe. """ return move_data[move_data[kwargs['arg1']] <= kwargs['arg2']] def _filter_speed_max_radius(move_data: DataFrame, **kwargs):
63
64
148
15
48
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
_filter_speed_max_radius
_filter_speed_max_radius
423
445
423
423
7975ffa549e40cbbac7802d76388ed4d9a6812cc
bigcode/the-stack
train
1ec2909353494aca7778c9ac
train
function
def get_bbox_by_radius( coordinates: Tuple[float, float], radius: Optional[float] = 1000 ) -> List: """ Defines minimum and maximum coordinates, given a distance radius from a point. Parameters ---------- coords : tuple (lat, lon) The coordinates of point radius: float, optional (1...
def get_bbox_by_radius( coordinates: Tuple[float, float], radius: Optional[float] = 1000 ) -> List:
""" Defines minimum and maximum coordinates, given a distance radius from a point. Parameters ---------- coords : tuple (lat, lon) The coordinates of point radius: float, optional (1000 by default) Returns ------- array coordinates min and max of the bbox Refe...
.utils.log import logger if TYPE_CHECKING: from pymove.core.dask import DaskMoveDataFrame from pymove.core.pandas import PandasMoveDataFrame def get_bbox_by_radius( coordinates: Tuple[float, float], radius: Optional[float] = 1000 ) -> List:
68
68
228
30
37
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
get_bbox_by_radius
get_bbox_by_radius
46
81
46
48
25e06799dd3584cff1907917b7457c940b0da1e6
bigcode/the-stack
train
511f48434d3b209eae338033
train
function
def _filter_data(move_data: DataFrame, f: callable, kwargs: Dict): """ Filter the dataframe using condition from given function. Parameters ---------- move_data : dataframe Dataframe to be filtered. f : function Filtering function **kwargs : arguments - arg1 : featur...
def _filter_data(move_data: DataFrame, f: callable, kwargs: Dict):
""" Filter the dataframe using condition from given function. Parameters ---------- move_data : dataframe Dataframe to be filtered. f : function Filtering function **kwargs : arguments - arg1 : feature - arg2 : value - outliers : special behavior if c...
['arg1']].shift(1)) > kwargs['arg2']) | (np.nan_to_num(move_data[kwargs['arg1']]) > kwargs['arg2']) ) return move_data[filter_] def _filter_data(move_data: DataFrame, f: callable, kwargs: Dict):
65
65
218
18
46
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
_filter_data
_filter_data
448
486
448
448
a0039111aa89feb101d22a3c6d8e9548b23404a3
bigcode/the-stack
train
9ca771f41fbc929d99af0649
train
function
def _filter_single_by_max(move_data: DataFrame, **kwargs): """ Filters from a dataframe rows with features below value. Parameters ---------- move_data : dataframe Dataframe to be filtered. **kwargs : arguments - arg1 : feature - arg2 : value Returns ------- ...
def _filter_single_by_max(move_data: DataFrame, **kwargs):
""" Filters from a dataframe rows with features below value. Parameters ---------- move_data : dataframe Dataframe to be filtered. **kwargs : arguments - arg1 : feature - arg2 : value Returns ------- DataFrame Filtered dataframe. """ return ...
1) else: filter_ = (move_data[subset].shift(n) != move_data[subset]).any(axis=1) return move_data.drop(index=move_data[~filter_].index, inplace=inplace) def _filter_single_by_max(move_data: DataFrame, **kwargs):
64
64
101
15
49
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
_filter_single_by_max
_filter_single_by_max
402
420
402
402
741a54d30af892eb4939a93dce0315b6319d3e67
bigcode/the-stack
train
1a949754466a35faac3e1fa3
train
function
def outliers( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], jump_coefficient: Optional[float] = 3.0, threshold: Optional[float] = 1, filter_out: Optional[bool] = False, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveDataFrame']]: """ Filt...
def outliers( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], jump_coefficient: Optional[float] = 3.0, threshold: Optional[float] = 1, filter_out: Optional[bool] = False, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveDataFrame']]:
""" Filters trajectories points that are outliers. Parameters ---------- move_data : dataframe The input trajectory data jump_coefficient : float, optional by default 3 threshold : float, optional Minimum value that the distance features must have in order to...
be altered to contain the result of the filtering, otherwise a copy will be returned, by default False Returns ------- DataFrame Returns a dataframe with trajectories points filtered or None """ return by_label(move_data, tid_, TID, filter_out, inplace) def outliers( move_data...
152
152
509
90
62
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
outliers
outliers
288
351
288
294
56394f2d1547f641447fbeefe596eae11feb9158
bigcode/the-stack
train
775efa0e761bd9cb815af14d
train
function
def by_label( move_data: DataFrame, value: Any, label_name: Text, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]: """ Filters trajectories points according to specified value and column label. Parameters ---------- move_data : datafr...
def by_label( move_data: DataFrame, value: Any, label_name: Text, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
""" Filters trajectories points according to specified value and column label. Parameters ---------- move_data : dataframe The input trajectory data value : The value to be use to filter the trajectories Specifies the value used to filter the trajectories points label_name :...
start_datetime if filter_out: filter_ = ~filter_ return move_data.drop(index=move_data[~filter_].index, inplace=inplace) def by_label( move_data: DataFrame, value: Any, label_name: Text, filter_out: Optional[bool] = False, inplace: Optional[bool] = False ) -> Optional[DataFrame]:
85
85
284
50
35
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
by_label
by_label
174
211
174
180
3c26a096e4e38967e96b4ee035417991e932e774
bigcode/the-stack
train
df2b8d7983f3c1c153fe10a4
train
function
def clean_trajectories_with_few_points( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_tid: Optional[Text] = TID, min_points_per_trajectory: Optional[int] = 2, inplace: Optional[bool] = False ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveDataFrame']]: """ Removes from ...
def clean_trajectories_with_few_points( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_tid: Optional[Text] = TID, min_points_per_trajectory: Optional[int] = 2, inplace: Optional[bool] = False ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveDataFrame']]:
""" Removes from the given dataframe, trajectories with fewer points. Parameters ---------- move_data : dataframe The input trajectory data label_tid : str, optional The label of the column which contains the tid of the trajectories, by default TID min_points_per_trajectory:...
( label_id=label_id, label_dtype=label_dtype ) logger.debug( '\nClean gps points with speed max > %s meters by seconds' % speed_max ) move_df = _clean_gps( move_df, _filter_speed_max_radius, arg1=SPEED_TO_PREV, arg2=speed_max, out...
182
182
608
86
95
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_trajectories_with_few_points
clean_trajectories_with_few_points
776
852
776
781
2a0812ba61062dc579d84ea5c942cda9c241635a
bigcode/the-stack
train
a0cc1b9219cbe4471a86a8a1
train
function
def clean_id_by_time_max( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, time_max: Optional[float] = 3600, label_dtype: Optional[Callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveDataFrame']...
def clean_id_by_time_max( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, time_max: Optional[float] = 3600, label_dtype: Optional[Callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveDataFrame']...
""" Clears GPS points with time by ID greater than a user-defined limit. Parameters ---------- move_data: dataframe. The input data. label_id: str, optional The label of the column which contains the id of the trajectories, by default TRAJ_ID time_max: float, optiona...
ids_before_drop, move_df[label_id].unique().shape[0]) ) move_df.drop(index=idx, inplace=True) logger.debug( '\n...Shape - before drop: %s - after drop: %s' % (shape_before_drop, move_df.shape) ) if not inplace: return move_df def clean_id_by_time_max(...
168
168
562
95
72
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_id_by_time_max
clean_id_by_time_max
945
1,014
945
951
0e68749b01203de2947954aa85ca4c98c31484e9
bigcode/the-stack
train
67e1fe99f544c809cd3ce531
train
function
def _clean_gps(move_data: DataFrame, f: callable, **kwargs): """ Cleans gps points from a dataframe using condition from given function. Parameters ---------- move_data : dataframe Dataframe to be filtered. f : function Filtering function **kwargs : arguments - arg1 ...
def _clean_gps(move_data: DataFrame, f: callable, **kwargs):
""" Cleans gps points from a dataframe using condition from given function. Parameters ---------- move_data : dataframe Dataframe to be filtered. f : function Filtering function **kwargs : arguments - arg1 : feature - arg2 : value - outliers : special...
threshold=kwargs['arg2'], inplace=False ) else: filter_data_points = f( move_data, arg1=kwargs['arg1'], arg2=kwargs['arg2'], inplace=False ) rows_to_drop = filter_data_points.shape[0] return filter_data_points, r...
92
92
307
18
73
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
_clean_gps
_clean_gps
489
531
489
489
bcf2436ec5e780ee940712806317ed2155b5bbac
bigcode/the-stack
train
4755023a5b290d824acd4956
train
function
def clean_gps_nearby_points_by_distances( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, radius_area: Optional[float] = 10.0, label_dtype: Optional[callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', '...
def clean_gps_nearby_points_by_distances( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, radius_area: Optional[float] = 10.0, label_dtype: Optional[callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', '...
""" Removes points from the trajectories with smaller distance from the point before. Parameters ---------- move_data : dataframe The input trajectory data label_id : str, optional Indicates the label of the id column in the user dataframe, by default TRAJ_ID radius_area : ...
, arg2=threshold, outliers=True ) if not inplace: return move_df def clean_gps_nearby_points_by_distances( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, radius_area: Optional[float] = 10.0, label_dtype: Optional[callable...
126
126
423
102
23
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_gps_nearby_points_by_distances
clean_gps_nearby_points_by_distances
595
650
595
601
ef3e96e2e7c7aef819248765bf7bbd2731f11e08
bigcode/the-stack
train
df745ec25572a4807bd3dc87
train
function
def clean_gps_speed_max_radius( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, speed_max: Optional[float] = 50.0, label_dtype: Optional[Callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveData...
def clean_gps_speed_max_radius( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], label_id: Optional[Text] = TRAJ_ID, speed_max: Optional[float] = 50.0, label_dtype: Optional[Callable] = np.float64, inplace: Optional[bool] = False, ) -> Optional[Union['PandasMoveDataFrame', 'DaskMoveData...
""" Removes trajectories points with higher speed. Given any point p of the trajectory, the point will be removed if one of the following happens: if the travel speed from the point before p to p is greater than the max value of speed between adjacent points set by the user. Or the travel spee...
\n' % speed_radius ) move_df = _clean_gps( move_df, _filter_single_by_max, arg1=SPEED_TO_PREV, arg2=speed_radius, outliers=False ) if not inplace: return move_df def clean_gps_speed_max_radius( move_data: Union['PandasMoveDataFrame', 'DaskMove...
159
159
533
97
61
safarzadeh-reza/PyMove
pymove/preprocessing/filters.py
Python
clean_gps_speed_max_radius
clean_gps_speed_max_radius
710
773
710
716
9001c52f92d35359508d3d823f75bf0206a38e83
bigcode/the-stack
train
25d814485012b10f0350e62e
train
class
class Book: def __init__(self, readme_fpath='README.md', outpath='content', toc_path='_toc.md', ): self.outpath = outpath self.parser = ReadmeParser(fpath=readme_fpath) def generate_stubs(self): self.stubs = [] ...
class Book:
def __init__(self, readme_fpath='README.md', outpath='content', toc_path='_toc.md', ): self.outpath = outpath self.parser = ReadmeParser(fpath=readme_fpath) def generate_stubs(self): self.stubs = [] for topic in...
bibtex entries, that would be a better # data structure to parse for this. Oh well. Later. Bibtex + jinja. Noted. from loguru import logger from collections import defaultdict from unidecode import unidecode import string from pathlib import Path class Book:
64
64
176
3
60
dmarx/anthology-of-modern-ml
readme2book.py
Python
Book
Book
23
46
23
23
c80b2a115271f46b7af0adf9a7416dee925e766e
bigcode/the-stack
train
2285f1174564c29ce3596c30
train
class
class Stub: _header = """--- jupytext: formats: md:myst text_representation: extension: .md format_name: myst kernelspec: display_name: Python 3 language: python name: python3 ---""" _pdf_embed_template = """```{{code-cell}} ipython3 :tags: [hide-input] import panel as pn pn.extension() pdf_...
class Stub:
_header = """--- jupytext: formats: md:myst text_representation: extension: .md format_name: myst kernelspec: display_name: Python 3 language: python name: python3 ---""" _pdf_embed_template = """```{{code-cell}} ipython3 :tags: [hide-input] import panel as pn pn.extension() pdf_pane = pn.pa...
headings' not in topic: continue for subtopic, entries in topic['subheadings'].items(): for entry in entries: stub = Stub(entry, depth=3) self.stubs.append(stub) # write stub to disk stub.write(se...
96
96
320
3
92
dmarx/anthology-of-modern-ml
readme2book.py
Python
Stub
Stub
50
94
50
50
6ff3fe8687c5d945a762979c8a5297d338215020
bigcode/the-stack
train
f3caf5ea77c9532edcfb932d
train
class
class ReadmeParser: def __init__(self, fpath='README.md'): self.fpath = fpath self.read() self.entries = self.parse() def read(self): with open(self.fpath, 'rb') as f: text = f.read() self.text = text.decode("utf-8") def parse(self): ...
class ReadmeParser:
def __init__(self, fpath='README.md'): self.fpath = fpath self.read() self.entries = self.parse() def read(self): with open(self.fpath, 'rb') as f: text = f.read() self.text = text.decode("utf-8") def parse(self): self.errors = []...
code-cell}} ipython3 :tags: [hide-input] import panel as pn pn.extension() pdf_pane = pn.pane.PDF('{pdf_url}', width=700, height=1000) pdf_pane ```""" def __init__(self, item, depth=1): self.item = item self.depth=depth @property def title(self): h = '#'*self.depth return f...
254
256
980
5
249
dmarx/anthology-of-modern-ml
readme2book.py
Python
ReadmeParser
ReadmeParser
98
228
98
98
7340cc5ae0375077926c9d4d738b622dad2037e1
bigcode/the-stack
train
bb80943e3037117de4da0d5c
train
class
class PolyNondom: """Enumerates and visualises different sets of (non-dominated) points. .. glossary:: non-dominated point A point *y* is non-dominated (in the point set P) if there is no other point *z* in P such that *z_i <= y_i* for all i with at least one strict inequali...
class PolyNondom:
"""Enumerates and visualises different sets of (non-dominated) points. .. glossary:: non-dominated point A point *y* is non-dominated (in the point set P) if there is no other point *z* in P such that *z_i <= y_i* for all i with at least one strict inequality. domin...
param tuple item: Point belonging to point set """ self.points.add(item) def update(self, items): """Add items to points. :param iterable items: Points belonging to point set """ self.points.update(items) def add_visualised_items(self, items): """Add it...
256
256
4,471
6
249
asbestian/polynondom
polynondom.py
Python
PolyNondom
PolyNondom
293
747
293
293
0cce8a1774ed4f8200719ce853febb6217efff8a
bigcode/the-stack
train
7a871897530901166c4fc3f3
train
class
class AssignmentDomain(GenericDomain): """Feasible domain of an assignment problem. The assignment problem has a number of agents and a(n equal) number of tasks. Any agent can be assigned to perform any task. A feasible solution is given by an assignment of agents to tasks in such a way that...
class AssignmentDomain(GenericDomain):
"""Feasible domain of an assignment problem. The assignment problem has a number of agents and a(n equal) number of tasks. Any agent can be assigned to perform any task. A feasible solution is given by an assignment of agents to tasks in such a way that each agent is one task and all tasks a...
self.dim = dim def __iter__(self): """Iterator for generic domain.""" raise NotImplementedError def __str__(self): """String representation of domain.""" return self.__class__.__name__ + str(set([elem for elem in self])) class AssignmentDomain(GenericDomain):
63
64
214
6
57
asbestian/polynondom
polynondom.py
Python
AssignmentDomain
AssignmentDomain
70
95
70
70
3ef0cde6a3c4a322571b7fa062323bfc63a4d1db
bigcode/the-stack
train
7c9b80a4c77274be7700d89f
train
class
class ExplicitDomain(GenericDomain): """Explicitely given feasible domain. :ivar Iterable domain: Feasible domain :Example: ed = ExplicitDomain(3, some_iterable) """ def __init__(self, dim, domain): """Initialises feasible domain via given domain.""" super().__init__(dim) ...
class ExplicitDomain(GenericDomain):
"""Explicitely given feasible domain. :ivar Iterable domain: Feasible domain :Example: ed = ExplicitDomain(3, some_iterable) """ def __init__(self, dim, domain): """Initialises feasible domain via given domain.""" super().__init__(dim) assert isinstance(self.domain...
def __init__(self, dim): """Initialises feasible domain given by standard cube.""" super().__init__(dim) def __iter__(self): """Iterator for cube domain.""" for prod in product(range(2), repeat=self.dim): yield prod class ExplicitDomain(GenericDomain):
64
64
116
6
57
asbestian/polynondom
polynondom.py
Python
ExplicitDomain
ExplicitDomain
114
132
114
114
6992b37e520635b0cbb4fb5113042e610663e364
bigcode/the-stack
train
57cb10207c39c5c1b5323b8f
train
class
class Points: """Represents certain set of points in objective space. :ivar str _id: Identifier for points :ivar str _color: Color used for visualisation of points :ivar list _visualised_items: Container for visualised items :ivar set points: Container for points """ def __init__(self, ide...
class Points:
"""Represents certain set of points in objective space. :ivar str _id: Identifier for points :ivar str _color: Color used for visualisation of points :ivar list _visualised_items: Container for visualised items :ivar set points: Container for points """ def __init__(self, identifier, color...
for line in file: bracket_open = line.find("[") bracket_close = line.find("]") if bracket_open == -1 or bracket_close == -1: continue else: substring = line[bracket_open+1:brac...
135
135
451
3
131
asbestian/polynondom
polynondom.py
Python
Points
Points
215
291
215
215
a45b7a44119378a8ffab66f834ca6321d5c56f3b
bigcode/the-stack
train
663205ed942ac418eb8699e7
train
class
class Error(Exception): """Base class for exceptions."""
class Error(Exception):
"""Base class for exceptions."""
ArgumentParser from collections import Iterable from itertools import combinations, permutations, product, zip_longest import logging import math from numpy import array, dot, linspace, meshgrid from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d class Error(Exception):
64
64
11
4
59
asbestian/polynondom
polynondom.py
Python
Error
Error
40
41
40
40
3be9f5161f6c49104c86bf17e33b4291a93be7cd
bigcode/the-stack
train
25dd50faa178c73ab1fea7f9
train
class
class InfeasibleBoxError(Error): """Rectangular box is infeasible."""
class InfeasibleBoxError(Error):
"""Rectangular box is infeasible."""
product, zip_longest import logging import math from numpy import array, dot, linspace, meshgrid from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d class Error(Exception): """Base class for exceptions.""" class InfeasibleBoxError(Error):
64
64
17
8
56
asbestian/polynondom
polynondom.py
Python
InfeasibleBoxError
InfeasibleBoxError
43
44
43
43
1ed425f0b7052022f73cc82c5af53744d8dc5173
bigcode/the-stack
train
d1a6f33a00491c1377f1501a
train
class
class CubeDomain(GenericDomain): """Feasible domain given by the vertices of an n-dimensional standard cube. :Example: cd = CubeDomain(3) """ def __init__(self, dim): """Initialises feasible domain given by standard cube.""" super().__init__(dim) def __iter__(self): ""...
class CubeDomain(GenericDomain):
"""Feasible domain given by the vertices of an n-dimensional standard cube. :Example: cd = CubeDomain(3) """ def __init__(self, dim): """Initialises feasible domain given by standard cube.""" super().__init__(dim) def __iter__(self): """Iterator for cube domain.""" ...
Iterator for assignment domain.""" for perm in permutations(list(range(self.num_agents))): feas_sol = [0]*self.dim for i, val in enumerate(perm): feas_sol[i*self.num_agents + val] = 1 yield tuple(feas_sol) class CubeDomain(GenericDomain):
64
64
94
6
58
asbestian/polynondom
polynondom.py
Python
CubeDomain
CubeDomain
98
111
98
98
cc4c4ed6a687a5fa8d262d053f718a87d637f95c
bigcode/the-stack
train
5754fe39b9b5fcb6004e1e56
train
function
def get_cmd_line_parser(): """Command line interface.""" parser = ArgumentParser(description='Enumerates and visualises different \ sets of non-dominated points') parent_parser = ArgumentParser(add_help=False) parent_parser.add_argument('-f', '--file', metavar="i...
def get_cmd_line_parser():
"""Command line interface.""" parser = ArgumentParser(description='Enumerates and visualises different \ sets of non-dominated points') parent_parser = ArgumentParser(add_help=False) parent_parser.add_argument('-f', '--file', metavar="input_file", type=str, ...
, 3) x_z = meshgrid(x, z, sparse=True) y_z = meshgrid(y, z, sparse=True) for i in interval1: self._ax.plot_surface(i, *y_z, facecolors=my_face_color, alpha=my_alpha) for i in interval2: self._ax.plot_surface(x_z[0], ...
153
153
511
6
147
asbestian/polynondom
polynondom.py
Python
get_cmd_line_parser
get_cmd_line_parser
750
787
750
750
2dcad0f069bada5e9f94e7850ed588931eadfc58
bigcode/the-stack
train
ab03a60830203ee110fc5bb3
train
class
class Objectives: """Represents the objectives of a multi-criteria optimisation problem. :ivar list objectives: Objective functions """ def __init__(self): """Initialise with no objectives.""" self._objectives = [] def length(self): if self._objectives: for...
class Objectives:
"""Represents the objectives of a multi-criteria optimisation problem. :ivar list objectives: Objective functions """ def __init__(self): """Initialise with no objectives.""" self._objectives = [] def length(self): if self._objectives: for i, j in combinati...
) """ def __init__(self, dim): """Initialises feasible domain given by standard cube.""" super().__init__(dim) def __iter__(self): """Iterator for cube domain.""" for prod in product(range(2), repeat=self.dim): yield prod class ExplicitDomain(GenericDomain): ...
180
180
603
3
176
asbestian/polynondom
polynondom.py
Python
Objectives
Objectives
135
213
135
135
7a8328e8af516ee0e5570c15e9583b6a0e23d4d6
bigcode/the-stack
train
e4cfecc9ffc688b90c60f388
train
class
class GenericDomain: """Feasible domain of a generic optimisation problem. :ivar int dim: Dimension of feasible domain .. note:: Do not use this class directly. """ def __init__(self, dim): """Initialises generic domain. :param: int dim: Dimension of feasible dom...
class GenericDomain:
"""Feasible domain of a generic optimisation problem. :ivar int dim: Dimension of feasible domain .. note:: Do not use this class directly. """ def __init__(self, dim): """Initialises generic domain. :param: int dim: Dimension of feasible domain """ ...
numpy import array, dot, linspace, meshgrid from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d class Error(Exception): """Base class for exceptions.""" class InfeasibleBoxError(Error): """Rectangular box is infeasible.""" class GenericDomain:
64
64
129
4
60
asbestian/polynondom
polynondom.py
Python
GenericDomain
GenericDomain
46
67
46
46
186bd440762e4e700ee5c4ec8d49ce96d730f6e3
bigcode/the-stack
train
2134e6ac5a303e1891bcef4d
train
class
class TextSystem(object): def __init__(self, args): self.text_detector = predict_det.TextDetector(args) self.text_recognizer = predict_rec.TextRecognizer(args) self.use_angle_cls = args.use_angle_cls self.drop_score = args.drop_score if self.use_angle_cls: self.te...
class TextSystem(object):
def __init__(self, args): self.text_detector = predict_det.TextDetector(args) self.text_recognizer = predict_rec.TextRecognizer(args) self.use_angle_cls = args.use_angle_cls self.drop_score = args.drop_score if self.use_angle_cls: self.text_classifier = predict_cl...
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing pe...
235
235
784
5
230
jiashanyao/PaddleOCR
tools/infer/predict_system.py
Python
TextSystem
TextSystem
39
118
39
39
c3236d671a88dbec6ce9c20cf08b43c768ba763f
bigcode/the-stack
train
2500a4513547cc9472cd8632
train
function
def main(args): image_file_list = get_image_file_list(args.image_dir) text_sys = TextSystem(args) is_visualize = True font_path = args.vis_font_path drop_score = args.drop_score for image_file in image_file_list: img, flag = check_and_read_gif(image_file) if not flag: ...
def main(args):
image_file_list = get_image_file_list(args.image_dir) text_sys = TextSystem(args) is_visualize = True font_path = args.vis_font_path drop_score = args.drop_score for image_file in image_file_list: img, flag = check_and_read_gif(image_file) if not flag: img = cv2.imrea...
][0])) _boxes = list(sorted_boxes) for i in range(num_boxes - 1): if abs(_boxes[i + 1][0][1] - _boxes[i][0][1]) < 10 and \ (_boxes[i + 1][0][0] < _boxes[i][0][0]): tmp = _boxes[i] _boxes[i] = _boxes[i + 1] _boxes[i + 1] = tmp return _boxes def mai...
111
111
370
4
106
jiashanyao/PaddleOCR
tools/infer/predict_system.py
Python
main
main
142
183
142
142
902283d76006fc88e3c2208835b0adc4cc97a0b5
bigcode/the-stack
train
6e9736857c40c18b64840d5f
train
function
def sorted_boxes(dt_boxes): """ Sort text boxes in order from top to bottom, left to right args: dt_boxes(array):detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2] """ num_boxes = dt_boxes.shape[0] sorted_boxes = sorted(dt_boxes, key=lambda x:...
def sorted_boxes(dt_boxes):
""" Sort text boxes in order from top to bottom, left to right args: dt_boxes(array):detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2] """ num_boxes = dt_boxes.shape[0] sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0])) _bo...
for box, rec_reuslt in zip(dt_boxes, rec_res): text, score = rec_reuslt if score >= self.drop_score: filter_boxes.append(box) filter_rec_res.append(rec_reuslt) return filter_boxes, filter_rec_res def sorted_boxes(dt_boxes):
64
64
200
6
57
jiashanyao/PaddleOCR
tools/infer/predict_system.py
Python
sorted_boxes
sorted_boxes
121
139
121
121
98f0446b45c993e3a921859c3b200461264fbc3a
bigcode/the-stack
train
a13f09aa9ff2af03eca59c58
train
function
@routes.route('/', strict_slashes=True) def home(): return render_template('home.html')
@routes.route('/', strict_slashes=True) def home():
return render_template('home.html')
request, Response, render_template from model.roads import Roads from pyldapi import ContainerRenderer import conf import ast import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home():
64
64
20
12
51
GeoscienceAustralia/FSDF-Roads
API/controller/routes.py
Python
home
home
12
14
12
13
55ac5ff05a86653ab20a1ea4ad45d465e2a631b9
bigcode/the-stack
train
0345f7ec0cc2415f736f772f
train
function
@routes.route('/rds/<string:roads_id>') def road(roads_id): roads = Roads(request, request.base_url) return roads.render()
@routes.route('/rds/<string:roads_id>') def road(roads_id):
roads = Roads(request, request.base_url) return roads.render()
folium.PolyLine(points, color="red", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id):
64
64
33
18
46
GeoscienceAustralia/FSDF-Roads
API/controller/routes.py
Python
road
road
99
102
99
100
118738938d7471777713cf55203aae1f3b47b719
bigcode/the-stack
train
2cbf9d579100457fc6ce742c
train
function
@routes.route('/rds/') def roads(): # Search specific items using keywords search_string = request.values.get('search') try: # get the register length from the online DB sql = 'SELECT COUNT(*) FROM "transportroads"' if search_string: sql += '''WHERE UPPER(cast("id" as t...
@routes.route('/rds/') def roads(): # Search specific items using keywords
search_string = request.values.get('search') try: # get the register length from the online DB sql = 'SELECT COUNT(*) FROM "transportroads"' if search_string: sql += '''WHERE UPPER(cast("id" as text)) LIKE '%{search_string}%' OR UPPER("name") LIKE '%{search_string}%'; ...
from flask import Blueprint, request, Response, render_template from model.roads import Roads from pyldapi import ContainerRenderer import conf import ast import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return r...
95
143
478
18
77
GeoscienceAustralia/FSDF-Roads
API/controller/routes.py
Python
roads
roads
17
70
17
19
ab2461d0d210ad2fa6086dccba464d62e808a57e
bigcode/the-stack
train
0ca09ac1032656920551d8a7
train
function
@routes.route('/map') def show_map(): ''' Function to render a map around the specified line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping points = [] for coords in coords_list: points.append(tuple...
@routes.route('/map') def show_map():
''' Function to render a map around the specified line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping points = [] for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat...
_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, ...
64
64
205
10
54
GeoscienceAustralia/FSDF-Roads
API/controller/routes.py
Python
show_map
show_map
73
96
73
74
0d2e538be6a99844342462aac49549387fd7f59c
bigcode/the-stack
train