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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20d59f563009f342b3d9311a | train | function | def test_cutoff_selector_in_pipeline():
logging.debug('Load data...')
data = pd.read_csv('../example_data/test_data_files/sampled_app_train.csv')
logging.debug('Data loaded')
logging.debug('Features modification from user side...')
data['BIRTH_DATE'] = (np.datetime64('2018-01-01') + data['DAYS_BIRT... | def test_cutoff_selector_in_pipeline():
| logging.debug('Load data...')
data = pd.read_csv('../example_data/test_data_files/sampled_app_train.csv')
logging.debug('Data loaded')
logging.debug('Features modification from user side...')
data['BIRTH_DATE'] = (np.datetime64('2018-01-01') + data['DAYS_BIRTH'].astype(np.dtype('timedelta64[D]'))).... | #!/usr/bin/env python
# coding: utf-8
import logging
import os
import pickle
import time
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from lightautoml.automl.base import AutoML
from lightautoml.ml_algo.boost_lgbm import BoostLGB... | 202 | 256 | 1,327 | 8 | 194 | alexeytomashyov/LightAutoML | tests/demo1.py | Python | test_cutoff_selector_in_pipeline | test_cutoff_selector_in_pipeline | 25 | 152 | 25 | 25 | 2a8241d128d935202559822d5d7f7c2cd10ca561 | bigcode/the-stack | train |
6f79cf639b0621ef073c912a | train | function | def longestSubString(string):
dict = {}
min, min_r = None
max_r = None
range = None
if len(string) == 0:
return
for let, i in enumerate(string):
if let in string:
if min is None:
min = i
if dict[let] > min:
min = dict[let]... | def longestSubString(string):
| dict = {}
min, min_r = None
max_r = None
range = None
if len(string) == 0:
return
for let, i in enumerate(string):
if let in string:
if min is None:
min = i
if dict[let] > min:
min = dict[let] + 1
else:
... | = 'cfghijakl'
input = 'abcdaac'
dict [letter] = last position
range: min(beginning of non repeating character) to max
max_range, cur_range
if its in the dict: min = prev_last position and keep going
"""
def longestSubString(string):
| 64 | 64 | 132 | 6 | 58 | itsmeolivia/interview | subset.py | Python | longestSubString | longestSubString | 12 | 34 | 12 | 12 | fb5d15cf3bf9483ce0c9c425d1d82ada4916812f | bigcode/the-stack | train |
f60a3a907e1eb02b22c49761 | train | class | class TaskPause(LMCPObject.LMCPObject):
def __init__(self):
self.LMCP_TYPE = 22
self.SERIES_NAME = "UXTASK"
self.FULL_LMCP_TYPE_NAME = "uxas.messages.task.TaskPause"
#Series Name turned into a long for quick comparisons.
self.SERIES_NAME_ID = 6149757930721443840
sel... | class TaskPause(LMCPObject.LMCPObject):
| def __init__(self):
self.LMCP_TYPE = 22
self.SERIES_NAME = "UXTASK"
self.FULL_LMCP_TYPE_NAME = "uxas.messages.task.TaskPause"
#Series Name turned into a long for quick comparisons.
self.SERIES_NAME_ID = 6149757930721443840
self.SERIES_VERSION = 7
#Define mes... | #! /usr/bin/python
import sys, struct
import xml.dom.minidom
from lmcp import LMCPObject
## ===============================================================================
## Authors: AFRL/RQQA
## Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
##
## Copyright (... | 146 | 255 | 852 | 12 | 134 | GaloisInc/salty | examples/VIP-Escort/lmcp/py/uxas/messages/task/TaskPause.py | Python | TaskPause | TaskPause | 20 | 134 | 20 | 21 | d1cf0a584bb1b86334949b075edc4a880ec3fa49 | bigcode/the-stack | train |
8c7c07aff32ddba2b8bb3a81 | train | function | def __create_text_and_labels(data_dir,
file,
punct_marks=',.?'):
'''
Create datasets for training and evaluation.
The data will be splitted into 2 files: text.txt and labels.txt. \
Each line of the text.txt file contains text sequences, where wor... | def __create_text_and_labels(data_dir,
file,
punct_marks=',.?'):
| '''
Create datasets for training and evaluation.
The data will be splitted into 2 files: text.txt and labels.txt. \
Each line of the text.txt file contains text sequences, where words\
are separated with spaces. The labels.txt file contains \
corresponding labels for each word in text.txt, the l... | dev_file.write(' '.join(lines[-dev_size:]))
def remove_punctuation(word):
"""
Removes all punctuation marks from a word except for '
that is often a part of word: don't, it's, and so on
"""
all_punct_marks = string.punctuation.replace("'", '')
return re.sub('['+all_punct_marks+']', '', wor... | 100 | 100 | 336 | 18 | 82 | seovchinnikov/NeMo | scripts/get_tatoeba_data.py | Python | __create_text_and_labels | __create_text_and_labels | 140 | 176 | 140 | 142 | 79d1104a469f0fb3d6fda9f7119100ae15fb8aa8 | bigcode/the-stack | train |
ad60c6539666baab3f0526d2 | train | function | def remove_punctuation(word):
"""
Removes all punctuation marks from a word except for '
that is often a part of word: don't, it's, and so on
"""
all_punct_marks = string.punctuation.replace("'", '')
return re.sub('['+all_punct_marks+']', '', word)
| def remove_punctuation(word):
| """
Removes all punctuation marks from a word except for '
that is often a part of word: don't, it's, and so on
"""
all_punct_marks = string.punctuation.replace("'", '')
return re.sub('['+all_punct_marks+']', '', word)
| _file = open(train_file, 'w')
dev_file = open(dev_file, 'w')
dev_size = int(len(lines) * percent_dev)
train_file.write(' '.join(lines[:-dev_size]))
dev_file.write(' '.join(lines[-dev_size:]))
def remove_punctuation(word):
| 63 | 64 | 68 | 6 | 57 | seovchinnikov/NeMo | scripts/get_tatoeba_data.py | Python | remove_punctuation | remove_punctuation | 131 | 137 | 131 | 131 | 2698076d4d83489227a4f555c124540b9def54e5 | bigcode/the-stack | train |
c54e890f2b2cb0354daffe2d | train | function | def __process_english_sentences(in_file,
out_file,
percent_to_cut=0,
num_to_combine=1,
num_samples=-1):
"""
Extract English sentences from the Tatoeba dataset.
Expected in_file for... | def __process_english_sentences(in_file,
out_file,
percent_to_cut=0,
num_to_combine=1,
num_samples=-1):
| """
Extract English sentences from the Tatoeba dataset.
Expected in_file format
that
contrain letters and punctuation marks (,.?).
Chop and combine sentences.
Args:
in_file: local filepath to the tatoeba dataset.
Format: id [TAB] region_name [TAB] sentence,
for example: "1276... | os.path.exists(destination):
print(f'Downloading {source}')
print(f'Downloading could take a long time ' +
'To get the data faster consider running in a terminal:\n' +
'wget https://downloads.tatoeba.org/exports/sentences.csv\n' +
'grep -P "\teng\t" sentences.c... | 153 | 153 | 510 | 35 | 118 | seovchinnikov/NeMo | scripts/get_tatoeba_data.py | Python | __process_english_sentences | __process_english_sentences | 47 | 104 | 47 | 51 | 6ac3cfac2bc32d27343db14f07dd8b5b79abc61d | bigcode/the-stack | train |
a7d97ca430052783b60d7d25 | train | function | def __maybe_download_file(destination: str, source: str):
"""
Downloads source to destination if not exists.
If exists, skips download
Args:
destination: local filepath
source: url of resource
"""
source = URL[source]
if not os.path.exists(destination):
print(f'Downlo... | def __maybe_download_file(destination: str, source: str):
| """
Downloads source to destination if not exists.
If exists, skips download
Args:
destination: local filepath
source: url of resource
"""
source = URL[source]
if not os.path.exists(destination):
print(f'Downloading {source}')
print(f'Downloading could take a ... | the License.****
import argparse
import os
import random
import re
import string
import urllib.request
from collections import Counter
URL = {'tatoeba': 'https://downloads.tatoeba.org/exports/sentences.csv'}
def __maybe_download_file(destination: str, source: str):
| 63 | 64 | 176 | 13 | 50 | seovchinnikov/NeMo | scripts/get_tatoeba_data.py | Python | __maybe_download_file | __maybe_download_file | 27 | 44 | 27 | 27 | 991aecc6f0438b130d5a7f485fff734ae540a7e8 | bigcode/the-stack | train |
febc7270435392f0c5b8631a | train | function | def __delete_file(file_to_del):
"""
Deletes the file
Args:
file_to_del: local filepath to the file to delete
"""
if os.path.exists(file_to_del):
os.remove(file_to_del)
| def __delete_file(file_to_del):
| """
Deletes the file
Args:
file_to_del: local filepath to the file to delete
"""
if os.path.exists(file_to_del):
os.remove(file_to_del)
| label += 'U'
else:
label += 'O'
word = word.lower()
text += word + ' '
labels += label + ' '
text_f.write(text.strip() + '\n')
labels_f.write(labels.strip() + '\n')
def __delete_file(file_to_del):
| 64 | 64 | 49 | 8 | 56 | seovchinnikov/NeMo | scripts/get_tatoeba_data.py | Python | __delete_file | __delete_file | 179 | 186 | 179 | 179 | de11e4a060e4d8e04fc45a93c525697c00a03d90 | bigcode/the-stack | train |
b7d72bca7c1a3ae6dbb90ae2 | train | function | def __split_into_train_dev(in_file,
train_file,
dev_file,
percent_dev):
"""
Create train and dev split of the dataset.
Args:
in_file: local filepath to the dataset
train_file: local filepath to the train dataset... | def __split_into_train_dev(in_file,
train_file,
dev_file,
percent_dev):
| """
Create train and dev split of the dataset.
Args:
in_file: local filepath to the dataset
train_file: local filepath to the train dataset
dev_file: local filepath to the dev dataset
percent_dev: Percent of the sentences in the dev set
"""
if not os.path.exists(in_fi... | if len(lines_to_combine) > 0 and \
(samples_count < num_samples or num_samples < 0):
out_file.write(' '.join(lines_to_combine) + '\n')
def __split_into_train_dev(in_file,
train_file,
dev_file,
percent_dev):
| 64 | 64 | 178 | 21 | 43 | seovchinnikov/NeMo | scripts/get_tatoeba_data.py | Python | __split_into_train_dev | __split_into_train_dev | 107 | 128 | 107 | 110 | 736c6130e8e9b644d9009d8e14ee7f89ddbeba6c | bigcode/the-stack | train |
e43b910d88726161c50fbed6 | train | function | def validate_password(
password: str,
min_length: int,
max_length: int,
user_attrs: Optional[list[str]] = None,
) -> None:
"""
Validates the password with all the password validation related
functions in this module.
"""
password = validate_password_length(password, min_length, max_l... | def validate_password(
password: str,
min_length: int,
max_length: int,
user_attrs: Optional[list[str]] = None,
) -> None:
| """
Validates the password with all the password validation related
functions in this module.
"""
password = validate_password_length(password, min_length, max_length)
password = validate_password_not_numeric(password)
password = validate_password_not_similar_to_user_attributes(password, use... | if password.lower().strip() in _PASSWORD_LIST:
raise exceptions.InvalidPasswordError("Password is too common.")
return password
def validate_password(
password: str,
min_length: int,
max_length: int,
user_attrs: Optional[list[str]] = None,
) -> None:
| 64 | 64 | 110 | 36 | 27 | jorge4larcon/fastproject | fastproject/modules/users/password_validators.py | Python | validate_password | validate_password | 123 | 137 | 123 | 128 | 6c9f810e7746783244c545cc729d9a30bba1b568 | bigcode/the-stack | train |
3299b6f82c21b7e9c7dd210f | train | function | def validate_password_length(password: str, min_length: int, max_length: int) -> str:
"""Validates that the password has the correct length."""
if not min_length <= len(password) <= max_length:
raise exceptions.InvalidPasswordError(
f"Password can not have less than {min_length} or more "
... | def validate_password_length(password: str, min_length: int, max_length: int) -> str:
| """Validates that the password has the correct length."""
if not min_length <= len(password) <= max_length:
raise exceptions.InvalidPasswordError(
f"Password can not have less than {min_length} or more "
f"than {max_length} characters."
)
return password
| for p in file}
except OSError:
with open(password_list_path, "rt", encoding="utf-8") as file:
_PASSWORD_LIST = {p.strip() for p in file}
def validate_password_length(password: str, min_length: int, max_length: int) -> str:
| 64 | 64 | 85 | 21 | 43 | jorge4larcon/fastproject | fastproject/modules/users/password_validators.py | Python | validate_password_length | validate_password_length | 28 | 35 | 28 | 28 | 99b07f6dc3695864aa31ff0714a84e612d1321f8 | bigcode/the-stack | train |
79dd1dc0743e88e6fcf89d01 | train | function | def exceeds_maximum_length_ratio(
password: str, max_similarity: float, value: str
) -> float:
"""
Test that value is within a reasonable range of password.
The following ratio calculations are based on testing difflib.SequenceMatcher like
this:
for i in range(0,6):
print(10**i, difflib.... | def exceeds_maximum_length_ratio(
password: str, max_similarity: float, value: str
) -> float:
| """
Test that value is within a reasonable range of password.
The following ratio calculations are based on testing difflib.SequenceMatcher like
this:
for i in range(0,6):
print(10**i, difflib.SequenceMatcher(a='A', b='A'*(10**i)).quick_ratio())
which yields:
1 1.0
10 0.1818181... | f"than {max_length} characters."
)
return password
def validate_password_not_numeric(password: str) -> str:
"""Validates that the password is not entirely numeric."""
if password.isdigit():
raise exceptions.InvalidPasswordError("Password can not be entirely numeric.")
retur... | 89 | 89 | 299 | 25 | 63 | jorge4larcon/fastproject | fastproject/modules/users/password_validators.py | Python | exceeds_maximum_length_ratio | exceeds_maximum_length_ratio | 45 | 74 | 45 | 47 | b3ef3d8bfe23179237064b16ded83b3e25f05b82 | bigcode/the-stack | train |
9d08867fe0f4e74aa14a41be | train | function | def _load_password_list(password_list_path=_PASSWORD_LIST_PATH) -> None:
"""Loads the password list."""
global _PASSWORD_LIST
try:
with gzip.open(password_list_path, "rt", encoding="utf-8") as file:
_PASSWORD_LIST = {p.strip() for p in file}
except OSError:
with open(password... | def _load_password_list(password_list_path=_PASSWORD_LIST_PATH) -> None:
| """Loads the password list."""
global _PASSWORD_LIST
try:
with gzip.open(password_list_path, "rt", encoding="utf-8") as file:
_PASSWORD_LIST = {p.strip() for p in file}
except OSError:
with open(password_list_path, "rt", encoding="utf-8") as file:
_PASSWORD_LIST =... |
import gzip
import pathlib
import re
from typing import Optional
from . import exceptions
_PASSWORD_LIST_PATH = (
pathlib.Path(__file__).resolve().parent / "common-passwords.txt.gz"
)
_PASSWORD_LIST = set()
def _load_password_list(password_list_path=_PASSWORD_LIST_PATH) -> None:
| 64 | 64 | 104 | 16 | 48 | jorge4larcon/fastproject | fastproject/modules/users/password_validators.py | Python | _load_password_list | _load_password_list | 17 | 25 | 17 | 17 | 63ba54cc59cbb02fb778e65d01d049b36c9be71c | bigcode/the-stack | train |
8515f6c707063aacc64b4d9c | train | function | def validate_password_not_numeric(password: str) -> str:
"""Validates that the password is not entirely numeric."""
if password.isdigit():
raise exceptions.InvalidPasswordError("Password can not be entirely numeric.")
return password
| def validate_password_not_numeric(password: str) -> str:
| """Validates that the password is not entirely numeric."""
if password.isdigit():
raise exceptions.InvalidPasswordError("Password can not be entirely numeric.")
return password
| if not min_length <= len(password) <= max_length:
raise exceptions.InvalidPasswordError(
f"Password can not have less than {min_length} or more "
f"than {max_length} characters."
)
return password
def validate_password_not_numeric(password: str) -> str:
| 64 | 64 | 48 | 12 | 51 | jorge4larcon/fastproject | fastproject/modules/users/password_validators.py | Python | validate_password_not_numeric | validate_password_not_numeric | 38 | 42 | 38 | 38 | 5232e9e4c1996931fe4b74c3756dd99574751e82 | bigcode/the-stack | train |
367768e8a461cdb7f1af2e67 | train | function | def validate_password_not_similar_to_user_attributes(
password: str, user_attrs: Optional[dict[str, str]]
) -> str:
"""
Validate that the password is sufficiently different from the user's
attributes.
If no specific attributes are provided, look at a sensible list of
defaults. Attributes that d... | def validate_password_not_similar_to_user_attributes(
password: str, user_attrs: Optional[dict[str, str]]
) -> str:
| """
Validate that the password is sufficiently different from the user's
attributes.
If no specific attributes are provided, look at a sensible list of
defaults. Attributes that don't exist are ignored. Comparison is made to
not only the full attribute value, but also its components, so that, f... | the potentially
expensive sequence matching.
"""
pwd_len = len(password)
length_bound_similarity = max_similarity / 2 * pwd_len
value_len = len(value)
return pwd_len >= 10 * value_len and value_len < length_bound_similarity
def validate_password_not_similar_to_user_attributes(
password: str... | 85 | 85 | 285 | 29 | 55 | jorge4larcon/fastproject | fastproject/modules/users/password_validators.py | Python | validate_password_not_similar_to_user_attributes | validate_password_not_similar_to_user_attributes | 77 | 108 | 77 | 79 | 0c76d151ea2abc522e14a3a90cd239d91a6a4366 | bigcode/the-stack | train |
6931c1dc87cd8e1c45fd3cd8 | train | function | def validate_password_not_common(password: str) -> None:
"""
Validates that the password not occurs in a list of 20,000 common
passwords.
"""
if not _PASSWORD_LIST:
_load_password_list()
if password.lower().strip() in _PASSWORD_LIST:
raise exceptions.InvalidPasswordError("Passwor... | def validate_password_not_common(password: str) -> None:
| """
Validates that the password not occurs in a list of 20,000 common
passwords.
"""
if not _PASSWORD_LIST:
_load_password_list()
if password.lower().strip() in _PASSWORD_LIST:
raise exceptions.InvalidPasswordError("Password is too common.")
return password
| difflib.SequenceMatcher(a=password_lower, b=part).quick_ratio()
>= max_similarity
):
raise exceptions.InvalidPasswordError(
"The password is very similar to " f"the {attr}"
)
return password
def validate_password_not_com... | 64 | 64 | 78 | 12 | 51 | jorge4larcon/fastproject | fastproject/modules/users/password_validators.py | Python | validate_password_not_common | validate_password_not_common | 111 | 120 | 111 | 111 | 581de1a6a04c44095c2eb6347df4892dcca11f0e | bigcode/the-stack | train |
f95ab4e3d008fd8b1dac8aa4 | train | class | class BlogModel(models.Model):
title = models.CharField(max_length=200)
content = models.TextField(blank=True)
def __str__(self):
return self.title
| class BlogModel(models.Model):
| title = models.CharField(max_length=200)
content = models.TextField(blank=True)
def __str__(self):
return self.title
|
from django.db import models
class BlogModel(models.Model):
| 13 | 64 | 35 | 6 | 6 | mr-shubhamsinghal/Django-Routers | blog/models.py | Python | BlogModel | BlogModel | 5 | 10 | 5 | 5 | 36e8945f396e69d2f6006f4df6ccdac49abd0572 | bigcode/the-stack | train |
341e4597ea792f52dd5605f5 | train | class | class OrganizationInvitation(SafeDeleteModel):
""" This model will store information on invitations to join an organization and requests to join an organization """
class Meta:
db_table = "organization_invitations"
get_latest_by = "updated_at"
ordering = ["updated_at", "id"]
STATUS... | class OrganizationInvitation(SafeDeleteModel):
| """ This model will store information on invitations to join an organization and requests to join an organization """
class Meta:
db_table = "organization_invitations"
get_latest_by = "updated_at"
ordering = ["updated_at", "id"]
STATUS_CHOICES = (
("PENDING", "PENDING"),
... | from django.db import models
from safedelete.managers import SafeDeleteDeletedManager, SafeDeleteManager
from safedelete.models import SOFT_DELETE, SafeDeleteModel
from resources_portal.models.organization import Organization
from resources_portal.models.user import User
class OrganizationInvitation(SafeDeleteModel):... | 62 | 92 | 309 | 8 | 53 | AlexsLemonade/resources-portal | api/resources_portal/models/organization_invitation.py | Python | OrganizationInvitation | OrganizationInvitation | 10 | 45 | 10 | 10 | 91ea9e8447a19524ecae0b9960220d6a0ee71007 | bigcode/the-stack | train |
d1487cb4534d05638b23fd2d | train | function | def direct_to_play(url, show_lyrics, title):
"""Direct the song to be played according to the play_type."""
if show_lyrics:
lyric = search_lyricswikia(title)
print("----\n{}\n----".format(lyric))
run_mpv(url, title)
| def direct_to_play(url, show_lyrics, title):
| """Direct the song to be played according to the play_type."""
if show_lyrics:
lyric = search_lyricswikia(title)
print("----\n{}\n----".format(lyric))
run_mpv(url, title)
| error = subprocess.Popen(
c, stdout=subprocess.PIPE, stderr=subprocess.PIPE
).communicate()
output = output.decode("utf-8").strip()
error = error.decode("utf-8").strip()
return (output, error)
def direct_to_play(url, show_lyrics, title):
| 64 | 64 | 65 | 12 | 52 | Saul-Dickson/playx | playx/utility.py | Python | direct_to_play | direct_to_play | 26 | 32 | 26 | 26 | 5a02e9f8ec11ba944cf90c207d630edd6d8a87d5 | bigcode/the-stack | train |
4310ccc38e5f78b6963f0b3d | train | function | def move_songs():
"""Recent changes moved the song directory to ~/.playx/songs
from ~/.playx.
Function to make sure the migration is done properly.
Disable after a few days."""
OLD_DIR = os.path.expanduser("~/.playx")
NEW_DIR = os.path.expanduser("~/.playx/songs")
if not os.path.isdir(NEW_... | def move_songs():
| """Recent changes moved the song directory to ~/.playx/songs
from ~/.playx.
Function to make sure the migration is done properly.
Disable after a few days."""
OLD_DIR = os.path.expanduser("~/.playx")
NEW_DIR = os.path.expanduser("~/.playx/songs")
if not os.path.isdir(NEW_DIR):
os.m... | really-quiet", "-no-video", "--audio-display=no"]
subprocess.Popen(cli).wait()
def run_mpv_dir(directory):
logger.info("Playing using mpv from directory :: {}".format(directory))
cli = 'mpv "{}"'.format(directory)
os.system(cli)
def move_songs():
| 64 | 64 | 129 | 5 | 59 | Saul-Dickson/playx | playx/utility.py | Python | move_songs | move_songs | 51 | 65 | 51 | 51 | 79f81b099da8c01202d707b8506971e8fb4dc0fa | bigcode/the-stack | train |
4a5c5761037678dc3eeaabac | train | function | def run_mpv(stream_url, title=None):
if title.endswith(".mp3"):
title = "".join(title.split(".")[:-1])
logger.info("Playing [{}]".format(title))
cli = ["mpv", stream_url, "--really-quiet", "-no-video", "--audio-display=no"]
subprocess.Popen(cli).wait()
| def run_mpv(stream_url, title=None):
| if title.endswith(".mp3"):
title = "".join(title.split(".")[:-1])
logger.info("Playing [{}]".format(title))
cli = ["mpv", stream_url, "--really-quiet", "-no-video", "--audio-display=no"]
subprocess.Popen(cli).wait()
| ):
"""Direct the song to be played according to the play_type."""
if show_lyrics:
lyric = search_lyricswikia(title)
print("----\n{}\n----".format(lyric))
run_mpv(url, title)
def run_mpv(stream_url, title=None):
| 64 | 64 | 72 | 10 | 54 | Saul-Dickson/playx | playx/utility.py | Python | run_mpv | run_mpv | 35 | 42 | 35 | 36 | b767f955a48172edebb503d3654aedae19fc53f5 | bigcode/the-stack | train |
c9fb9e67a9fad408e549cd7c | train | function | def run_mpv_dir(directory):
logger.info("Playing using mpv from directory :: {}".format(directory))
cli = 'mpv "{}"'.format(directory)
os.system(cli)
| def run_mpv_dir(directory):
| logger.info("Playing using mpv from directory :: {}".format(directory))
cli = 'mpv "{}"'.format(directory)
os.system(cli)
| mp3"):
title = "".join(title.split(".")[:-1])
logger.info("Playing [{}]".format(title))
cli = ["mpv", stream_url, "--really-quiet", "-no-video", "--audio-display=no"]
subprocess.Popen(cli).wait()
def run_mpv_dir(directory):
| 64 | 64 | 39 | 7 | 57 | Saul-Dickson/playx | playx/utility.py | Python | run_mpv_dir | run_mpv_dir | 45 | 48 | 45 | 45 | 69eb52097df0078e4493f2a4c14171b455beaa56 | bigcode/the-stack | train |
2bd9ee0b6dd2eddd2cf3aede | train | function | def exe(command):
"""Execute the command externally."""
command = command.strip()
c = command.split()
output, error = subprocess.Popen(
c, stdout=subprocess.PIPE, stderr=subprocess.PIPE
).communicate()
output = output.decode("utf-8").strip()
error = error.decode("utf-8").strip()
... | def exe(command):
| """Execute the command externally."""
command = command.strip()
c = command.split()
output, error = subprocess.Popen(
c, stdout=subprocess.PIPE, stderr=subprocess.PIPE
).communicate()
output = output.decode("utf-8").strip()
error = error.decode("utf-8").strip()
return (output, er... | #!/usr/bin/env python3
"""A utility module for misc operations."""
import os
import subprocess
from shutil import move
from playx.lyrics import search_lyricswikia
from playx.logger import Logger
# Setup logger
logger = Logger("utility")
def exe(command):
| 59 | 64 | 78 | 4 | 55 | Saul-Dickson/playx | playx/utility.py | Python | exe | exe | 14 | 23 | 14 | 14 | 77e6ca5489744feda857c63ea8efc55b1e8b128c | bigcode/the-stack | train |
84ce4f5419fd606603c9b30b | train | function | def softmax(arr):
assert type(arr) in [list, tuple, set]
total = sum(arr)
return list(map(lambda x: x / total, arr))
| def softmax(arr):
| assert type(arr) in [list, tuple, set]
total = sum(arr)
return list(map(lambda x: x / total, arr))
| x/songs")
if not os.path.isdir(NEW_DIR):
os.makedirs(NEW_DIR)
for file in os.listdir(OLD_DIR):
if file.endswith("mp3"):
move(os.path.join(OLD_DIR, file), os.path.join(NEW_DIR, file))
def softmax(arr):
| 64 | 64 | 37 | 5 | 59 | Saul-Dickson/playx | playx/utility.py | Python | softmax | softmax | 68 | 71 | 68 | 68 | 9be52832356a1ebcd136a51922152bd1ec7801a9 | bigcode/the-stack | train |
e4452d842b3304a5e7640841 | train | function | @pytest.fixture()
def tracker():
class TestTracker():
def __init__(self):
self.tracks = set()
def tracks_gen(self):
time = datetime.datetime(2018, 1, 1, 14)
state_vector = StateVector([[0]])
for i in range(2):
self.tracks = {
... | @pytest.fixture()
def tracker():
| class TestTracker():
def __init__(self):
self.tracks = set()
def tracks_gen(self):
time = datetime.datetime(2018, 1, 1, 14)
state_vector = StateVector([[0]])
for i in range(2):
self.tracks = {
Track(
... | [GroundTruthState(
state_vector + i + 10*j, timestamp=time)
for j in range(i)])
for _ in range(i)}
yield time, self.groundtruth_paths
time += datetime.timedelta(minutes=1)
return TestGroundTruthReader()
@pytest... | 64 | 64 | 132 | 6 | 58 | GSORF/Stone-Soup | stonesoup/writer/tests/conftest.py | Python | tracker | tracker | 52 | 71 | 52 | 53 | 05581f8df5307e513c4e6d8ee155608838025deb | bigcode/the-stack | train |
b6cd5199d1e9379b9fe4c61a | train | function | @pytest.fixture()
def groundtruth_reader():
class TestGroundTruthReader():
def __init__(self):
self.groundtruth_paths = set()
def groundtruth_paths_gen(self):
time = datetime.datetime(2018, 1, 1, 14)
state_vector = StateVector([[0]])
for i in range(3)... | @pytest.fixture()
def groundtruth_reader():
| class TestGroundTruthReader():
def __init__(self):
self.groundtruth_paths = set()
def groundtruth_paths_gen(self):
time = datetime.datetime(2018, 1, 1, 14)
state_vector = StateVector([[0]])
for i in range(3):
self.groundtruth_paths = {... | for i in range(3):
self.detections = {
Detection(state_vector + i, timestamp=time)
for _ in range(i)}
yield time, self.detections
time += datetime.timedelta(minutes=1)
return TestDetectionReader()
@pytest.fixture()
def groundt... | 64 | 64 | 146 | 8 | 56 | GSORF/Stone-Soup | stonesoup/writer/tests/conftest.py | Python | groundtruth_reader | groundtruth_reader | 31 | 49 | 31 | 32 | 851edbbc7bc30a3b687c4abdad0f463fc9064279 | bigcode/the-stack | train |
e4417b91935a83297071a292 | train | function | @pytest.fixture()
def detection_reader():
class TestDetectionReader():
def __init__(self):
self.detections = set()
def detections_gen(self):
time = datetime.datetime(2018, 1, 1, 14)
state_vector = StateVector([[0]])
for i in range(3):
... | @pytest.fixture()
def detection_reader():
| class TestDetectionReader():
def __init__(self):
self.detections = set()
def detections_gen(self):
time = datetime.datetime(2018, 1, 1, 14)
state_vector = StateVector([[0]])
for i in range(3):
self.detections = {
De... | coding: utf-8 -*-
import datetime
import pytest
from ...types.array import StateVector
from ...types.detection import Detection
from ...types.groundtruth import GroundTruthState, GroundTruthPath
from ...types.state import State
from ...types.track import Track
@pytest.fixture()
def detection_reader():
| 64 | 64 | 119 | 7 | 56 | GSORF/Stone-Soup | stonesoup/writer/tests/conftest.py | Python | detection_reader | detection_reader | 13 | 28 | 13 | 14 | 7f7d5360e80691253cc8c751b27ad144f7872e50 | bigcode/the-stack | train |
8edd8df6f83aa1497f053bcd | train | class | class ClubhouseWebhookTest(WebhookTestCase):
STREAM_NAME = 'clubhouse'
URL_TEMPLATE = "/api/v1/external/clubhouse?stream={stream}&api_key={api_key}"
FIXTURE_DIR_NAME = 'clubhouse'
def test_story_create(self) -> None:
expected_message = u"New story [Add cool feature!](https://app.clubhouse.io/zu... | class ClubhouseWebhookTest(WebhookTestCase):
| STREAM_NAME = 'clubhouse'
URL_TEMPLATE = "/api/v1/external/clubhouse?stream={stream}&api_key={api_key}"
FIXTURE_DIR_NAME = 'clubhouse'
def test_story_create(self) -> None:
expected_message = u"New story [Add cool feature!](https://app.clubhouse.io/zulip/story/11) of type **feature** was created... | import json
from mock import MagicMock, patch
from zerver.lib.test_classes import WebhookTestCase
class ClubhouseWebhookTest(WebhookTestCase):
| 33 | 256 | 3,171 | 10 | 22 | DD2480-group7-2020/zulip | zerver/webhooks/clubhouse/tests.py | Python | ClubhouseWebhookTest | ClubhouseWebhookTest | 8 | 240 | 8 | 8 | 318c95942f86ecb4d16b00cab0951a4c94e639de | bigcode/the-stack | train |
c581c774dd283a4d9b6b2008 | train | function | def nPr(n, r):
"""
Calculates nPr.
Args:
n (int): total number of items.
r (int): items to permute
Returns:
nPr.
"""
f = math.factorial
return int(f(n) / f(n-r))
| def nPr(n, r):
| """
Calculates nPr.
Args:
n (int): total number of items.
r (int): items to permute
Returns:
nPr.
"""
f = math.factorial
return int(f(n) / f(n-r))
| Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r))
def nPr(n, r):
| 64 | 64 | 64 | 7 | 57 | JosephMontoya-TRI/monty | monty/math.py | Python | nPr | nPr | 35 | 47 | 35 | 35 | 3b79b8e22cb1b00fa78e07aa40f37a9b371f73e5 | bigcode/the-stack | train |
31b29cc8b6909b0fe31fb16a | train | function | def nCr(n, r):
"""
Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r))
| def nCr(n, r):
| """
Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r))
| Copyright 2013, The Materials Virtual Lab'
__version__ = '0.1'
__maintainer__ = 'Shyue Ping Ong'
__email__ = 'ongsp@ucsd.edu'
__date__ = '10/28/14'
import math
def nCr(n, r):
| 64 | 64 | 67 | 7 | 56 | JosephMontoya-TRI/monty | monty/math.py | Python | nCr | nCr | 20 | 32 | 20 | 20 | 893768978186a49fa051c38c62e175ab16f9a904 | bigcode/the-stack | train |
ec72696dab7f93f869065a71 | train | class | class Connectivity_Fault_Management_CFM(Base):
__slots__ = ()
_SDM_NAME = 'cfm'
_SDM_ATT_MAP = {
'Common Header': 'cfm.cfmHeader.commonHeader',
'Select Packet Header': 'cfm.cfmHeader.selectPacketHeader',
'TLVs': 'cfm.cfmHeader.tlvs',
}
def __init__(self, parent):
sup... | class Connectivity_Fault_Management_CFM(Base):
| __slots__ = ()
_SDM_NAME = 'cfm'
_SDM_ATT_MAP = {
'Common Header': 'cfm.cfmHeader.commonHeader',
'Select Packet Header': 'cfm.cfmHeader.selectPacketHeader',
'TLVs': 'cfm.cfmHeader.tlvs',
}
def __init__(self, parent):
super(Connectivity_Fault_Management_CFM, self).__i... | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class Connectivity_Fault_Management_CFM(Base):
| 28 | 81 | 272 | 10 | 17 | Vibaswan/ixnetwork_restpy | ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/configelement/stack/cfm_template.py | Python | Connectivity_Fault_Management_CFM | Connectivity_Fault_Management_CFM | 5 | 33 | 5 | 5 | 06a6c0598c18b8095b9659e06be93da07d12eac8 | bigcode/the-stack | train |
30eedcb7924b1787e5009bc8 | train | class | class QuboleOperatorTest(unittest.TestCase):
def setUp(self):
db.merge_conn(
Connection(conn_id=DEFAULT_CONN, conn_type='HTTP'))
def test_init_with_default_connection(self):
op = QuboleOperator(task_id=TASK_ID)
self.assertEqual(op.task_id, TASK_ID)
self.assertEqual(o... | class QuboleOperatorTest(unittest.TestCase):
| def setUp(self):
db.merge_conn(
Connection(conn_id=DEFAULT_CONN, conn_type='HTTP'))
def test_init_with_default_connection(self):
op = QuboleOperator(task_id=TASK_ID)
self.assertEqual(op.task_id, TASK_ID)
self.assertEqual(op.qubole_conn_id, DEFAULT_CONN)
def test... | # "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT... | 229 | 229 | 764 | 10 | 219 | ltxhxpdd123/gateway-airflow | tests/contrib/operators/test_qubole_operator.py | Python | QuboleOperatorTest | QuboleOperatorTest | 38 | 115 | 38 | 38 | 841e0dc5124726f7d877aa60da6450f2a8f695ed | bigcode/the-stack | train |
5306bd90d5394655367169dc | train | class | class TrackState:
"""
Enumeration type for the single target track state. Newly created tracks are
classified as `tentative` until enough evidence has been collected. Then,
the track state is changed to `confirmed`. Tracks that are no longer alive
are classified as `deleted` to mark them for removal... | class TrackState:
| """
Enumeration type for the single target track state. Newly created tracks are
classified as `tentative` until enough evidence has been collected. Then,
the track state is changed to `confirmed`. Tracks that are no longer alive
are classified as `deleted` to mark them for removal from the set of a... | # vim: expandtab:ts=4:sw=4
class TrackState:
| 18 | 64 | 97 | 4 | 13 | genghan77/IS02_PT_Capstone_Human_Re-ID | human_tracker/deep_sort/track.py | Python | TrackState | TrackState | 4 | 16 | 4 | 4 | e010c04ad5d3c68940bd27c5f90486a112b6819a | bigcode/the-stack | train |
2c87285a8a2b5863586a16ef | train | class | class Track:
"""
A single target track with state space `(x, y, a, h)` and associated
velocities, where `(x, y)` is the center of the bounding box, `a` is the
aspect ratio and `h` is the height.
Parameters
----------
mean : ndarray
Mean vector of the initial state distribution.
... | class Track:
| """
A single target track with state space `(x, y, a, h)` and associated
velocities, where `(x, y)` is the center of the bounding box, `a` is the
aspect ratio and `h` is the height.
Parameters
----------
mean : ndarray
Mean vector of the initial state distribution.
covariance : ... | # vim: expandtab:ts=4:sw=4
class TrackState:
"""
Enumeration type for the single target track state. Newly created tracks are
classified as `tentative` until enough evidence has been collected. Then,
the track state is changed to `confirmed`. Tracks that are no longer alive
are classified as `dele... | 114 | 256 | 1,161 | 3 | 110 | genghan77/IS02_PT_Capstone_Human_Re-ID | human_tracker/deep_sort/track.py | Python | Track | Track | 19 | 183 | 19 | 19 | 2a4b2acd8b3c33f06440bcc9d6121e68bf0acefc | bigcode/the-stack | train |
a2e72dec0395bbb1f141382b | train | class | class TestInstall(object):
def test_ceph_dir_exists(self, host, node):
assert host.file('/etc/ceph').exists
def test_ceph_dir_is_a_directory(self, host, node):
assert host.file('/etc/ceph').is_directory
def test_ceph_conf_exists(self, host, node):
assert host.file(node["conf_path"... | class TestInstall(object):
| def test_ceph_dir_exists(self, host, node):
assert host.file('/etc/ceph').exists
def test_ceph_dir_is_a_directory(self, host, node):
assert host.file('/etc/ceph').is_directory
def test_ceph_conf_exists(self, host, node):
assert host.file(node["conf_path"]).exists
def test_ceph... | import pytest
import re
class TestInstall(object):
| 11 | 64 | 138 | 5 | 5 | project-oblivion/ceph-ansible | tests/functional/tests/test_install.py | Python | TestInstall | TestInstall | 5 | 21 | 5 | 6 | 367de188f9619889dfbf658b55609feee352b25d | bigcode/the-stack | train |
93c0ae96ae87cfeb4feb922e | train | class | class TestCephConf(object):
def test_mon_host_line_has_correct_value(self, node, host):
mon_host_line = host.check_output("grep 'mon host = ' /etc/ceph/{cluster}.conf".format(cluster=node['cluster_name'])) # noqa E501
result = True
for x in range(0, node["num_mons"]):
pattern =... | class TestCephConf(object):
| def test_mon_host_line_has_correct_value(self, node, host):
mon_host_line = host.check_output("grep 'mon host = ' /etc/ceph/{cluster}.conf".format(cluster=node['cluster_name'])) # noqa E501
result = True
for x in range(0, node["num_mons"]):
pattern = re.compile(("v2:{subnet}.1{x... |
def test_ceph_conf_is_a_file(self, host, node):
assert host.file(node["conf_path"]).is_file
@pytest.mark.no_docker
def test_ceph_command_exists(self, host, node):
assert host.exists("ceph")
class TestCephConf(object):
| 64 | 64 | 140 | 7 | 57 | project-oblivion/ceph-ansible | tests/functional/tests/test_install.py | Python | TestCephConf | TestCephConf | 24 | 33 | 24 | 25 | 245ea18226e2066bd2a7812efebc53608e8cf5bf | bigcode/the-stack | train |
dc3b0b3c0809c0f660ac3ee5 | train | class | class SodaMachine:
def __init__(self):
self.register = []
self.inventory = []
self.fill_register()
self.fill_inventory()
def fill_register(self):
"""Method will fill SodaMachine's register with certain amounts of each coin when called."""
for index in range(8):
... | class SodaMachine:
| def __init__(self):
self.register = []
self.inventory = []
self.fill_register()
self.fill_inventory()
def fill_register(self):
"""Method will fill SodaMachine's register with certain amounts of each coin when called."""
for index in range(8):
self.reg... | from coins import Quarter
from coins import Dime
from coins import Nickel
from coins import Penny
from cans import Cola
from cans import OrangeSoda
from cans import RootBeer
import user_interface
class SodaMachine:
| 47 | 256 | 1,157 | 4 | 42 | Jamesburgess44/SodaMachineDebugging | dCC_Python_SodaMachine/soda_machine.py | Python | SodaMachine | SodaMachine | 11 | 145 | 11 | 11 | c7749e5ea2bbf8d38e953faed1175cc309ced978 | bigcode/the-stack | train |
edbddf96a7bf59eccf5aa47d | train | class | class SetWatchpointAPITestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Our simple source filename.
self.source = 'main.c'
# Find the line number to break inside main().
self.line = line_... | class SetWatchpointAPITestCase(TestBase):
| mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Our simple source filename.
self.source = 'main.c'
# Find the line number to break inside main().
self.line = line_number(
self.source, '// Set br... | """
Use lldb Python SBValue API to create a watchpoint for read_write of 'globl' var.
"""
from __future__ import print_function
import os
import time
import re
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class SetWatchpointAPITestCase(... | 86 | 227 | 759 | 10 | 75 | frank-lesser/lldb | packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py | Python | SetWatchpointAPITestCase | SetWatchpointAPITestCase | 17 | 112 | 17 | 18 | 0b344f0d027c0cc1de648ce413a05d94c3df8e15 | bigcode/the-stack | train |
b91aa43b89a6ce9f7588e15a | train | function | def pascal_triangle(n):
if n >= 1:
print ("1")
if n >= 2:
print ("1 1")
a = [1, 1]
for j in range(2, n):
b = [1]
for i in range(len(a)-1):
b.append(a[i] + a[i+1])
b.append(1)
for i in b:
print (i, end=" ")
print()
a = b
| def pascal_triangle(n):
| if n >= 1:
print ("1")
if n >= 2:
print ("1 1")
a = [1, 1]
for j in range(2, n):
b = [1]
for i in range(len(a)-1):
b.append(a[i] + a[i+1])
b.append(1)
for i in b:
print (i, end=" ")
print()
a = b
| def pascal_triangle(n):
| 6 | 64 | 103 | 6 | 0 | sowmyamanojna/BT3051-Data-Structures-and-Algorithms | self_assesment/self_assesment1/pascal_triangle.py | Python | pascal_triangle | pascal_triangle | 1 | 16 | 1 | 1 | 7df623aa981b17a7f2ec077f01b663b1171cb80f | bigcode/the-stack | train |
f18f308c87b9198c46cdc2c8 | train | function | @app.route('/chain', methods=['GET'])
def full_chain():
response = {
# TODO: Return the chain and its current length
'chain': blockchain.chain,
'length': len(blockchain.chain)
}
return jsonify(response), 200
| @app.route('/chain', methods=['GET'])
def full_chain():
| response = {
# TODO: Return the chain and its current length
'chain': blockchain.chain,
'length': len(blockchain.chain)
}
return jsonify(response), 200
| a new Transaction
index = blockchain.new_transaction(values['sender'],
values['recipient'],
values['amount'])
response = {'message': f'Transaction will be added to Block {index}'}
return jsonify(response), 201
@app.route('/chain... | 64 | 64 | 55 | 13 | 50 | cammac725/Blockchain | basic_block_gp/blockchain.py | Python | full_chain | full_chain | 202 | 209 | 202 | 203 | 601172e723865ffc361a55462db497179e85d031 | bigcode/the-stack | train |
fc7fb57aec36639dec7de912 | train | class | class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
self.nodes = set()
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
"""
Create a new Block in the Blockchain
:param pr... | class Blockchain(object):
| def __init__(self):
self.chain = []
self.current_transactions = []
self.nodes = set()
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
"""
Create a new Block in the Blockchain
:param proof: <int> The proof given... | # to restart the flask server on file change use FLASK_APP=blockchain.py FLASK_DEBUG=1 python -m flask run in the basic_block_gp folder while in a virtualenv shell
import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
class Blockchain(object):
| 70 | 256 | 855 | 4 | 65 | cammac725/Blockchain | basic_block_gp/blockchain.py | Python | Blockchain | Blockchain | 12 | 142 | 12 | 12 | 99af9cc1f4e3b0728a5de91710deb6ccddc29c2f | bigcode/the-stack | train |
ec2e535fb8fca1d2962dcbd8 | train | function | @app.route('/mine', methods=['GET'])
def mine():
# We run the proof of work algorithm to get the next proof...
proof = blockchain.proof_of_work()
print(f'Found valid proof: {proof}')
# We must receive a reward for finding the proof.
# TODO:
# The sender is "0" to signify that this node has mine... | @app.route('/mine', methods=['GET'])
def mine():
# We run the proof of work algorithm to get the next proof...
| proof = blockchain.proof_of_work()
print(f'Found valid proof: {proof}')
# We must receive a reward for finding the proof.
# TODO:
# The sender is "0" to signify that this node has mine a new coin
# The recipient is the current node, it did the mining!
# The amount is 1 coin as a reward for ... | # Instantiate our Node
app = Flask(__name__)
# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')
# Instantiate the Blockchain
blockchain = Blockchain()
@app.route('/mine', methods=['GET'])
def mine():
# We run the proof of work algorithm to get the next proof...
| 69 | 69 | 232 | 27 | 42 | cammac725/Blockchain | basic_block_gp/blockchain.py | Python | mine | mine | 155 | 181 | 155 | 157 | 2045eb14840f08038ca2ddb0c43a13a22cc46bf0 | bigcode/the-stack | train |
868fd432fecb47958f3bb336 | train | function | @app.route('/transactions/new', methods=['POST'])
def new_transaction():
values = request.get_json()
# Check that the required fields are in the POST'ed data
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing Values', 400
# Create a new ... | @app.route('/transactions/new', methods=['POST'])
def new_transaction():
| values = request.get_json()
# Check that the required fields are in the POST'ed data
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing Values', 400
# Create a new Transaction
index = blockchain.new_transaction(values['sender'],
... | "New Block Forged",
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
| 64 | 64 | 122 | 14 | 49 | cammac725/Blockchain | basic_block_gp/blockchain.py | Python | new_transaction | new_transaction | 184 | 199 | 184 | 185 | cc11da8be0200662331793460457cc602d0f4c47 | bigcode/the-stack | train |
a0bc0d24dfccc5cf4589a054 | train | function | @app.route('/chain_validity', methods=['GET'])
def chain_validity():
response = {
"valid_chain": blockchain.valid_chain(blockchain.chain)
}
return jsonify(response), 200
| @app.route('/chain_validity', methods=['GET'])
def chain_validity():
| response = {
"valid_chain": blockchain.valid_chain(blockchain.chain)
}
return jsonify(response), 200
| GET'])
def full_chain():
response = {
# TODO: Return the chain and its current length
'chain': blockchain.chain,
'length': len(blockchain.chain)
}
return jsonify(response), 200
@app.route('/chain_validity', methods=['GET'])
def chain_validity():
| 64 | 64 | 42 | 16 | 47 | cammac725/Blockchain | basic_block_gp/blockchain.py | Python | chain_validity | chain_validity | 212 | 217 | 212 | 213 | 59b89e707cc5e1fe62e034f224ef0269c08d8b54 | bigcode/the-stack | train |
4bb3eae3810104a9e30ecffd | train | function | def main():
# Read and scatter the initial temperature field
if rank == 0:
field, field0 = init_fields('bottle.dat')
shape = field.shape
dtype = field.dtype
# TODO: send the shape and dtype to everyone else
else:
field = None
# TODO: receive the shape and dtyp... | def main():
# Read and scatter the initial temperature field
| if rank == 0:
field, field0 = init_fields('bottle.dat')
shape = field.shape
dtype = field.dtype
# TODO: send the shape and dtype to everyone else
else:
field = None
# TODO: receive the shape and dtype
if shape[0] % size:
raise ValueError('Number of row... | first row of real data
rbuf = ... # ghost row
comm.Sendrecv(...)
def iterate(field, local_field, local_field0, timesteps, image_interval):
for m in range(1, timesteps+1):
exchange(local_field0)
evolve(local_field, local_field0, a, dt, dx2, dy2)
if m % image_interval == 0:
... | 132 | 132 | 441 | 13 | 119 | kahilah/hpc-python | mpi/heat-equation/skeleton.py | Python | main | main | 87 | 133 | 87 | 88 | e4505027f166bb394f27326d3480d3f7291c682a | bigcode/the-stack | train |
c629a26edba6d2c2a571b1be | train | function | def write_field(field, step):
plt.gca().clear()
plt.imshow(field)
plt.axis('off')
plt.savefig('heat_{0:03d}.png'.format(step))
| def write_field(field, step):
| plt.gca().clear()
plt.imshow(field)
plt.axis('off')
plt.savefig('heat_{0:03d}.png'.format(step))
| dy2 )
u_previous[:] = u[:]
def init_fields(filename):
# Read the initial temperature field from file
field = np.loadtxt(filename)
field0 = field.copy() # Array for field of previous time step
return field, field0
def write_field(field, step):
| 64 | 64 | 41 | 7 | 56 | kahilah/hpc-python | mpi/heat-equation/skeleton.py | Python | write_field | write_field | 58 | 62 | 58 | 58 | 20747c074e82ab717ee2535b6055c790b50f2a5d | bigcode/the-stack | train |
ddfecf89c61449d73bccf572 | train | function | def evolve(u, u_previous, a, dt, dx2, dy2):
"""Explicit time evolution.
u: new temperature field
u_previous: previous field
a: diffusion constant
dt: time step
dx2: grid spacing squared, i.e. dx^2
dy2: -- "" -- ... | def evolve(u, u_previous, a, dt, dx2, dy2):
| """Explicit time evolution.
u: new temperature field
u_previous: previous field
a: diffusion constant
dt: time step
dx2: grid spacing squared, i.e. dx^2
dy2: -- "" -- , i.e. dy^2"""
u[1:-1, 1:-1] = u_previo... | : find out your rank and communicator size
# Up/down neighbouring MPI ranks
up = rank - 1
down = rank + 1
# TODO: if at the edge of the grid, use MPI.PROC_NULL
def evolve(u, u_previous, a, dt, dx2, dy2):
| 64 | 64 | 215 | 17 | 46 | kahilah/hpc-python | mpi/heat-equation/skeleton.py | Python | evolve | evolve | 36 | 50 | 36 | 36 | 584aca4d66bd32d0c261f564a1f2ff047a12e731 | bigcode/the-stack | train |
be59fd4cb2f7a915b16c49e5 | train | function | def init_fields(filename):
# Read the initial temperature field from file
field = np.loadtxt(filename)
field0 = field.copy() # Array for field of previous time step
return field, field0
| def init_fields(filename):
# Read the initial temperature field from file
| field = np.loadtxt(filename)
field0 = field.copy() # Array for field of previous time step
return field, field0
| _previous[1:-1, 2:] - 2*u_previous[1:-1, 1:-1] + \
u_previous[1:-1, :-2]) / dy2 )
u_previous[:] = u[:]
def init_fields(filename):
# Read the initial temperature field from file
| 64 | 64 | 46 | 15 | 48 | kahilah/hpc-python | mpi/heat-equation/skeleton.py | Python | init_fields | init_fields | 52 | 56 | 52 | 53 | 1e20bacd9792022ba56a7cbbf4c9107e51225a04 | bigcode/the-stack | train |
bd6e5f9b5bb51d1ec4536d64 | train | function | def exchange(field):
# TODO: select border rows from the field and add MPI calls to
# exchange them with the neighbouring tasks
# send down, receive from up
sbuf = ... # last row of real data
rbuf = ... # ghost row
comm.Sendrecv(...)
# send up, receive from down
sbuf = ... # fir... | def exchange(field):
# TODO: select border rows from the field and add MPI calls to
# exchange them with the neighbouring tasks
# send down, receive from up
| sbuf = ... # last row of real data
rbuf = ... # ghost row
comm.Sendrecv(...)
# send up, receive from down
sbuf = ... # first row of real data
rbuf = ... # ghost row
comm.Sendrecv(...)
| .imshow(field)
plt.axis('off')
plt.savefig('heat_{0:03d}.png'.format(step))
def exchange(field):
# TODO: select border rows from the field and add MPI calls to
# exchange them with the neighbouring tasks
# send down, receive from up
| 64 | 64 | 104 | 39 | 25 | kahilah/hpc-python | mpi/heat-equation/skeleton.py | Python | exchange | exchange | 64 | 74 | 64 | 67 | 47f828ea46cb3fa134382060af4d0edc29dffa32 | bigcode/the-stack | train |
62c0f2d346a89e60367dc964 | train | function | def iterate(field, local_field, local_field0, timesteps, image_interval):
for m in range(1, timesteps+1):
exchange(local_field0)
evolve(local_field, local_field0, a, dt, dx2, dy2)
if m % image_interval == 0:
# TODO: gather partial fields to reconstruct the full field
... | def iterate(field, local_field, local_field0, timesteps, image_interval):
| for m in range(1, timesteps+1):
exchange(local_field0)
evolve(local_field, local_field0, a, dt, dx2, dy2)
if m % image_interval == 0:
# TODO: gather partial fields to reconstruct the full field
comm.Gather(...)
if rank == 0:
write_field(fie... | # ghost row
comm.Sendrecv(...)
# send up, receive from down
sbuf = ... # first row of real data
rbuf = ... # ghost row
comm.Sendrecv(...)
def iterate(field, local_field, local_field0, timesteps, image_interval):
| 63 | 64 | 97 | 17 | 46 | kahilah/hpc-python | mpi/heat-equation/skeleton.py | Python | iterate | iterate | 76 | 84 | 76 | 76 | b93715e6e3c04334a8e047d6bf20d9b1505bbfab | bigcode/the-stack | train |
e07298ecb5324383d674aa54 | train | class | class TestResultPayload(unittest.TestCase):
def setUp(self):
register_stanza_plugin(FormField, FormValidation)
def test_parsing(self):
form = Form()
types = [str(FOAF.Person), str(RHO.Owner)]
urn = 'urn.instance.owner'
form.add_reported(var=str(RDF.about), ftype=str(R... | class TestResultPayload(unittest.TestCase):
| def setUp(self):
register_stanza_plugin(FormField, FormValidation)
def test_parsing(self):
form = Form()
types = [str(FOAF.Person), str(RHO.Owner)]
urn = 'urn.instance.owner'
form.add_reported(var=str(RDF.about), ftype=str(RDFS.Literal))
form.add_reported(var=s... | """
Unit tests for the result payload.
"""
import unittest
from rdflib.namespace import RDF, RDFS, FOAF
from rhobot.namespace import RHO, GRAPH
from sleekxmpp.plugins.xep_0004.stanza.form import Form
from rhobot.components.storage import ResultCollectionPayload, ResultPayload
from rhobot.components.storage.enums import... | 123 | 243 | 811 | 8 | 114 | rerobins/rhobot_framework | test/components/storage_client/test_result_payload.py | Python | TestResultPayload | TestResultPayload | 15 | 137 | 15 | 16 | b7743f2f8c6841ee0343d14f74ec4bc5ce1a290e | bigcode/the-stack | train |
161d9163692a4ab8dee26b7c | train | class | class Greater_Of_Two_Horizontals(IMC):
"""Class defining steps and invalid imts, for greater of two horizontals.
"""
# making invalid IMTs a class variable because
# 1) it doesn't change with instances
# 2) information can now be retrieved without
# instantiating first
_invalid_imts = []... | class Greater_Of_Two_Horizontals(IMC):
| """Class defining steps and invalid imts, for greater of two horizontals.
"""
# making invalid IMTs a class variable because
# 1) it doesn't change with instances
# 2) information can now be retrieved without
# instantiating first
_invalid_imts = []
def __init__(self, imc, imt, perc... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Local imports
from gmprocess.metrics.imc.imc import IMC
class Greater_Of_Two_Horizontals(IMC):
| 43 | 73 | 245 | 13 | 29 | ftbernales/groundmotion-processing | gmprocess/metrics/imc/greater_of_two_horizontals.py | Python | Greater_Of_Two_Horizontals | Greater_Of_Two_Horizontals | 8 | 37 | 8 | 8 | 215f70d1827984e0f2897e9d0476343d6d2756bb | bigcode/the-stack | train |
3237c89f967e4bfd29b1fe89 | train | function | def loadfile(filename):
data = numpy.genfromtxt(filename, delimiter=",", dtype="f8, f8", names=["t", "y"])
return data["t"], data["y"]
| def loadfile(filename):
| data = numpy.genfromtxt(filename, delimiter=",", dtype="f8, f8", names=["t", "y"])
return data["t"], data["y"]
| from __future__ import division, print_function
import numpy
import scipy
import scipy.signal
from foldedleastsquares import transitleastsquares
from foldedleastsquares.template_generator.default_transit_template_generator import DefaultTransitTemplateGenerator
def loadfile(filename):
| 54 | 64 | 42 | 5 | 48 | martindevora/tls | foldedleastsquares/tests/test_shapes.py | Python | loadfile | loadfile | 9 | 11 | 9 | 9 | 742bfb673e35ad4190e703f7f8b746b1be7e3024 | bigcode/the-stack | train |
31cc012e3d39c773b7680c18 | train | class | class TestTransitTemplateGenerator(DefaultTransitTemplateGenerator):
def __init__(self):
super().__init__()
| class TestTransitTemplateGenerator(DefaultTransitTemplateGenerator):
| def __init__(self):
super().__init__()
| _generator.default_transit_template_generator import DefaultTransitTemplateGenerator
def loadfile(filename):
data = numpy.genfromtxt(filename, delimiter=",", dtype="f8, f8", names=["t", "y"])
return data["t"], data["y"]
class TestTransitTemplateGenerator(DefaultTransitTemplateGenerator):
| 64 | 64 | 22 | 10 | 54 | martindevora/tls | foldedleastsquares/tests/test_shapes.py | Python | TestTransitTemplateGenerator | TestTransitTemplateGenerator | 13 | 15 | 13 | 13 | bc808ecc1c9f665d4e918e80b1a71fc0c27c0f71 | bigcode/the-stack | train |
3306dd6c6f6259724b22bb71 | train | class | class ListUsersOfStreamResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
... | class ListUsersOfStreamResponse(SdkResponse):
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class ListUsersOfStreamResponse(SdkResponse):
| 40 | 240 | 800 | 11 | 28 | NQLoong/huaweicloud-sdk-python-v3 | huaweicloud-sdk-live/huaweicloudsdklive/v2/model/list_users_of_stream_response.py | Python | ListUsersOfStreamResponse | ListUsersOfStreamResponse | 12 | 135 | 12 | 14 | 65be8270e2af338b8e4442996cfec2bb1938947b | bigcode/the-stack | train |
7e6d7e592da1bd9da4c6bddf | train | class | class SetAnnouncementHandler(webapp2.RequestHandler):
def get(self):
"""Set Announcement in Memcache."""
# TODO 1
ConferenceApi._cacheAnnouncement()
| class SetAnnouncementHandler(webapp2.RequestHandler):
| def get(self):
"""Set Announcement in Memcache."""
# TODO 1
ConferenceApi._cacheAnnouncement()
| 2014 may 24
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from conference import ConferenceApi
class SetAnnouncementHandler(webapp2.RequestHandler):
| 64 | 64 | 36 | 10 | 53 | chaddienhart/UdacityP4-GAE-API | main.py | Python | SetAnnouncementHandler | SetAnnouncementHandler | 21 | 25 | 21 | 21 | 07402ddc1ca6c4f26f9976703d702a76227937d5 | bigcode/the-stack | train |
77e0610904c4be847b2abed8 | train | class | class SendConfirmationEmailHandler(webapp2.RequestHandler):
def post(self):
"""Send email confirming Conference creation."""
mail.send_mail(
'noreply@%s.appspotmail.com' % (
app_identity.get_application_id()), # from
self.request.get('email'), ... | class SendConfirmationEmailHandler(webapp2.RequestHandler):
| def post(self):
"""Send email confirming Conference creation."""
mail.send_mail(
'noreply@%s.appspotmail.com' % (
app_identity.get_application_id()), # from
self.request.get('email'), # to
'You created a new Conference!', ... | app_identity
from google.appengine.api import mail
from conference import ConferenceApi
class SetAnnouncementHandler(webapp2.RequestHandler):
def get(self):
"""Set Announcement in Memcache."""
# TODO 1
ConferenceApi._cacheAnnouncement()
class SendConfirmationEmailHandler(webapp2.RequestHa... | 64 | 64 | 113 | 11 | 53 | chaddienhart/UdacityP4-GAE-API | main.py | Python | SendConfirmationEmailHandler | SendConfirmationEmailHandler | 27 | 38 | 27 | 27 | 5dfe3c3237a244c7bd542b81f3d694da809115d1 | bigcode/the-stack | train |
efa03f2766ead2114e6f1deb | train | class | class SetFeaturedSpeakerHandler(webapp2.RequestHandler):
def post(self):
"""Check to see if the speaker is now the featured speaker and update memcache if so."""
ConferenceApi._cacheFeaturedSpeaker(self.request.get('websafeConferenceKey'), self.request.get('speaker'))
| class SetFeaturedSpeakerHandler(webapp2.RequestHandler):
| def post(self):
"""Check to see if the speaker is now the featured speaker and update memcache if so."""
ConferenceApi._cacheFeaturedSpeaker(self.request.get('websafeConferenceKey'), self.request.get('speaker'))
| '), # to
'You created a new Conference!', # subj
'Hi, you have created a following ' # body
'conference:\r\n\r\n%s' % self.request.get(
'conferenceInfo')
)
class SetFeaturedSpeakerHandler(webapp2.RequestHandler):
| 64 | 64 | 58 | 11 | 53 | chaddienhart/UdacityP4-GAE-API | main.py | Python | SetFeaturedSpeakerHandler | SetFeaturedSpeakerHandler | 40 | 43 | 40 | 40 | 3006348ae0ed27d2578fd748e7ae8898ab24d3e4 | bigcode/the-stack | train |
b7b009949a109ab754d4dd67 | train | class | class UpdateClassGenerator:
def __init__(self, spec, input):
self._spec = spec
self._input = input
self.gen_update_class_segments = [
GenUpdateClassSegment(*args) for args in re.findall(GEN_UPDATE_CLASS_PATTERN, self._input)
]
def generate_code_for_class_segments(sel... | class UpdateClassGenerator:
| def __init__(self, spec, input):
self._spec = spec
self._input = input
self.gen_update_class_segments = [
GenUpdateClassSegment(*args) for args in re.findall(GEN_UPDATE_CLASS_PATTERN, self._input)
]
def generate_code_for_class_segments(self):
generated_segmen... | for schema in schemas:
for prop_name, prop in self._get_schema_properties(schema).items():
prop_name = utils.to_snake_case(prop_name)
if prop_name not in ignore:
constructor_body += " " * (indentation + 4) + "self.{} = {}\n".format(prop_name, prop_... | 255 | 256 | 1,277 | 5 | 250 | haakonvt/cognite-sdk-python | openapi/generator.py | Python | UpdateClassGenerator | UpdateClassGenerator | 104 | 221 | 104 | 104 | 3874d13197c5fc4572f1c52475860fef864c70f4 | bigcode/the-stack | train |
57ae85a7a894b97fa4a91b80 | train | class | class CodeGenerator:
def __init__(self, spec_url: str = None, spec_path: str = None):
self.open_api_spec = OpenAPISpec(url=spec_url, path=spec_path)
def generate(self, input: str, output):
generated = self.generate_to_str(input)
with open(output, "w") as f:
f.write(generated... | class CodeGenerator:
| def __init__(self, spec_url: str = None, spec_path: str = None):
self.open_api_spec = OpenAPISpec(url=spec_url, path=spec_path)
def generate(self, input: str, output):
generated = self.generate_to_str(input)
with open(output, "w") as f:
f.write(generated)
def generate_t... | staticmethod
def _get_schema_properties(schema):
if "allOf" in schema:
properties = {}
for s in schema["allOf"]:
for prop_name, prop in UpdateClassGenerator._get_schema_properties(s).items():
properties[prop_name] = prop
return properti... | 221 | 222 | 742 | 4 | 217 | haakonvt/cognite-sdk-python | openapi/generator.py | Python | CodeGenerator | CodeGenerator | 224 | 294 | 224 | 224 | bc82c8011d69b63c41f50c191b8e568ceb48d167 | bigcode/the-stack | train |
220eee004bfd641fcc2e1a97 | train | class | class ClassGenerator:
def __init__(self, spec, input):
self._spec = spec
self._input = input
self.gen_class_segments = [GenClassSegment(*args) for args in re.findall(GEN_CLASS_PATTERN, self._input)]
def generate_code_for_class_segments(self):
generated_segments = {}
for ... | class ClassGenerator:
| def __init__(self, spec, input):
self._spec = spec
self._input = input
self.gen_class_segments = [GenClassSegment(*args) for args in re.findall(GEN_CLASS_PATTERN, self._input)]
def generate_code_for_class_segments(self):
generated_segments = {}
for class_segment in self.... | import os
import re
from collections import namedtuple
from black import FileMode, format_str
from openapi import utils
from openapi.openapi import OpenAPISpec
from openapi.utils import TYPE_MAPPING
TO_EXCLUDE = ["project", "cursor"]
GEN_CLASS_PATTERN = "# GenClass: ([\S ]+)\s+class (\S+)\(.+\):(?:(?!# GenStop)[\s\S... | 177 | 256 | 863 | 4 | 173 | haakonvt/cognite-sdk-python | openapi/generator.py | Python | ClassGenerator | ClassGenerator | 19 | 101 | 19 | 19 | 2b3004d2addf76380494c664aa901a877b057ed0 | bigcode/the-stack | train |
b77c3a06a8755fcce3419ffd | train | function | def is_sqr(x): # 用math包中的函数定义可开(整)平方的数
return math.sqrt(x) % 1 == 0
| def is_sqr(x): # 用math包中的函数定义可开(整)平方的数
| return math.sqrt(x) % 1 == 0
|
newlist = list(tmplist) # filter结果和map结果一样,都是内存地址,需用list()转换为列表才可展示
print(newlist)
import math
def is_sqr(x): # 用math包中的函数定义可开(整)平方的数
| 64 | 64 | 36 | 23 | 40 | oca-john/Python3-New2Learn | Python3Codes/1.python3.filter.py | Python | is_sqr | is_sqr | 13 | 14 | 13 | 13 | f51d1f95a9b35f556364f451b91fa6781a0f0597 | bigcode/the-stack | train |
a24581a6f3b6fb33e4a89440 | train | function | def is_odd(n): # 判断是否为奇数
return n % 2 == 1
| def is_odd(n): # 判断是否为奇数
| return n % 2 == 1
| #!/usr/bin/python3
# filter是个过滤函数
# 定义函数用于过滤
def is_odd(n): # 判断是否为奇数
| 34 | 64 | 24 | 14 | 19 | oca-john/Python3-New2Learn | Python3Codes/1.python3.filter.py | Python | is_odd | is_odd | 5 | 6 | 5 | 5 | c93e8278b9b844cce4bcd2ad4d7e03a5b05c1f35 | bigcode/the-stack | train |
f163ddb9cf38b7f4ff8f137b | train | function | def check_issuance_amount_1_no_reissuance(
issuance: CAssetIssuance, asset_name: str
) -> Optional[str]:
# Make sure that this is unblinded issuance
if not issuance.assetBlindingNonce.is_null():
return (
f"unexpected {asset_name} issuance configuration: "
f"assetBlindingNonce... | def check_issuance_amount_1_no_reissuance(
issuance: CAssetIssuance, asset_name: str
) -> Optional[str]:
# Make sure that this is unblinded issuance
| if not issuance.assetBlindingNonce.is_null():
return (
f"unexpected {asset_name} issuance configuration: "
f"assetBlindingNonce is not null"
)
# Check that the amount of the control_asset issued is 1
if issuance.nAmount.to_amount() != 1:
return (
f... | {descr} output does not match expected amount "
f"({expected_amount})"
)
def check_issuance_amount_1_no_reissuance(
issuance: CAssetIssuance, asset_name: str
) -> Optional[str]:
# Make sure that this is unblinded issuance
| 64 | 64 | 202 | 44 | 20 | RuggedBytes/liquid_loans_cli | lib/__init__.py | Python | check_issuance_amount_1_no_reissuance | check_issuance_amount_1_no_reissuance | 90 | 111 | 90 | 93 | 6897975f37b42408354ad9aea353be8c884169c6 | bigcode/the-stack | train |
9592f17f80b3cf415087301b | train | function | def check_output(
tx: CElementsTransaction,
txout_index: int,
blinding_key: CKey,
descr: str,
expected_spk: CScript,
expected_asset: CAsset,
expected_amount: int,
) -> None:
"""Check that the output contains expected things
and return the error string if it contains wrong"""
txou... | def check_output(
tx: CElementsTransaction,
txout_index: int,
blinding_key: CKey,
descr: str,
expected_spk: CScript,
expected_asset: CAsset,
expected_amount: int,
) -> None:
| """Check that the output contains expected things
and return the error string if it contains wrong"""
txout = tx.vout[txout_index]
if expected_spk is not None:
if txout.scriptPubKey != expected_spk:
raise CheckOutputError(
f"{descr} output scriptPubKey ({b2x(txout.sc... | ateral_stage is not None:
found_stage = find_vstage(vstage.next_lateral_stage)
if found_stage is not None:
return found_stage
return None
return find_vstage(plan.first_lateral_stage)
def check_output(
tx: CElementsTransaction,
txout_index: int,
... | 104 | 104 | 348 | 56 | 48 | RuggedBytes/liquid_loans_cli | lib/__init__.py | Python | check_output | check_output | 45 | 87 | 45 | 53 | e30ef679f7a1b40721c3e283368621abe3514d26 | bigcode/the-stack | train |
3dc75127395e7fb05e174681 | train | function | def get_vstage_by_script(
plan: RepaymentPlan, script: CScript
) -> Optional[VerticalProgressionStage]:
"""Return stage that belongs to this script"""
def find_vstage(
lstage: LateralProgressionStage
) -> Optional[VerticalProgressionStage]:
for vstage in lstage.vertical_stages:
... | def get_vstage_by_script(
plan: RepaymentPlan, script: CScript
) -> Optional[VerticalProgressionStage]:
| """Return stage that belongs to this script"""
def find_vstage(
lstage: LateralProgressionStage
) -> Optional[VerticalProgressionStage]:
for vstage in lstage.vertical_stages:
current_script = P2WSHCoinAddress.from_redeemScript(
vstage.script_data.script
... | AssetIssuance, CElementsTransaction
from .types import (
RepaymentPlan, LateralProgressionStage, VerticalProgressionStage,
CheckOutputError
)
def get_vstage_by_script(
plan: RepaymentPlan, script: CScript
) -> Optional[VerticalProgressionStage]:
| 64 | 64 | 171 | 28 | 36 | RuggedBytes/liquid_loans_cli | lib/__init__.py | Python | get_vstage_by_script | get_vstage_by_script | 19 | 42 | 19 | 21 | 6bf09969935aa61c4312ddc2da5c047beb4715ce | bigcode/the-stack | train |
fdcee0605be35847f7d99119 | train | class | class BKpyIGTLink:
""" Send BK data over OpenIGTLink. """
def __init__(self, TCP_IP='128.16.0.3', TCP_PORT=7915, TIMEOUT=5, FPS=8): #pylint:disable=invalid-name
logging.info("Creating BKpyIGTLink connection")
self.bk5000 = BK5000(TIMEOUT, FPS)
self.bk5000.connect_to_host(TCP_IP, TCP_POR... | class BKpyIGTLink:
| """ Send BK data over OpenIGTLink. """
def __init__(self, TCP_IP='128.16.0.3', TCP_PORT=7915, TIMEOUT=5, FPS=8): #pylint:disable=invalid-name
logging.info("Creating BKpyIGTLink connection")
self.bk5000 = BK5000(TIMEOUT, FPS)
self.bk5000.connect_to_host(TCP_IP, TCP_PORT)
self.ig... | 0] * self.image_size[1] + 22
while len(self.buffer) < self.minimum_size:
self.buffer.extend(self.socket.recv(self.minimum_size))
valid_frame = self.receive_image()
if valid_frame:
self.valid_frame = True
else:
self.buffe... | 76 | 76 | 254 | 7 | 69 | SciKit-Surgery/scikit-surgerybk | sksurgerybk/interface/bk5000.py | Python | BKpyIGTLink | BKpyIGTLink | 422 | 452 | 422 | 422 | 4e083fd5ff6f7bea389713ccebd904582d9a1015 | bigcode/the-stack | train |
52b43cef4d38aa2f8ee17e4f | train | function | def main():
""" Entry point for OpenCV/pyIGTLink. """
# OpenCV or PyIGTLink can be selected from command line
# 'python bk5000.py' without any arguments wll run openCV
# adding any argument will use IGTLink instead e.g.
# 'python bk5000.py 1'
if len(sys.argv) > 1:
bk_igtlink = BKpyIGTL... | def main():
| """ Entry point for OpenCV/pyIGTLink. """
# OpenCV or PyIGTLink can be selected from command line
# 'python bk5000.py' without any arguments wll run openCV
# adding any argument will use IGTLink instead e.g.
# 'python bk5000.py 1'
if len(sys.argv) > 1:
bk_igtlink = BKpyIGTLink()
... | iton/streaming. """
self.bk5000.query_win_size()
self.bk5000.start_streaming()
while True:
self.bk5000.get_frame()
cv2.imshow('a', self.bk5000.img)
cv2.waitKey(1)
def main():
| 64 | 64 | 123 | 3 | 61 | SciKit-Surgery/scikit-surgerybk | sksurgerybk/interface/bk5000.py | Python | main | main | 473 | 487 | 473 | 473 | e2a2251bafc4cddc89f280caf990a36582e7807c | bigcode/the-stack | train |
c68ba9ed3507283475f1289b | train | class | class BKOpenCV:
""" Display BK data using OpenCV."""
#pylint:disable=no-member, invalid-name, import-error
def __init__(self, TCP_IP='128.16.0.3', TCP_PORT=7915, TIMEOUT=5, FPS=25):
self.bk5000 = BK5000(TIMEOUT, FPS)
self.bk5000.connect_to_host(TCP_IP, TCP_PORT)
def start(self):
... | class BKOpenCV:
| """ Display BK data using OpenCV."""
#pylint:disable=no-member, invalid-name, import-error
def __init__(self, TCP_IP='128.16.0.3', TCP_PORT=7915, TIMEOUT=5, FPS=25):
self.bk5000 = BK5000(TIMEOUT, FPS)
self.bk5000.connect_to_host(TCP_IP, TCP_PORT)
def start(self):
""" Start acqu... | _server.is_connected():
self.bk5000.get_frame()
image_message = ImageMessage(self.bk5000.img)
self.igtlink_server.add_message_to_send_queue(image_message)
def stop(self):
""" Stop acquisition/streaming."""
self.active = False
class BKOpenCV:
| 64 | 64 | 164 | 5 | 58 | SciKit-Surgery/scikit-surgerybk | sksurgerybk/interface/bk5000.py | Python | BKOpenCV | BKOpenCV | 454 | 471 | 454 | 454 | 63cd918900987a2c4a197d43cea46c08b6580e78 | bigcode/the-stack | train |
5faa35ab44e1f678ec21baa9 | train | class | class BK5000():
#pylint:disable=too-many-instance-attributes
"""This class sets the TCP connection with the BK scanner"""
def __init__(self, timeout, frames_per_second):
""" The DataSourceWorker constructor.
Sets a number of class members.
Parameters:
timeout(positive float):... | class BK5000():
#pylint:disable=too-many-instance-attributes
| """This class sets the TCP connection with the BK scanner"""
def __init__(self, timeout, frames_per_second):
""" The DataSourceWorker constructor.
Sets a number of class members.
Parameters:
timeout(positive float): the connection timeout in seconds.
frames_per_second(... | """This module sets the connection to the BK scanner"""
import socket
import logging
import sys
import cv2
import numpy as np
from sksurgerybk.pyigtlink.pyIGTLink import PyIGTLink, ImageMessage
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class BK5000():
#pylint:disable=too-many-insta... | 82 | 256 | 3,295 | 17 | 65 | SciKit-Surgery/scikit-surgerybk | sksurgerybk/interface/bk5000.py | Python | BK5000 | BK5000 | 14 | 419 | 14 | 16 | 61e0c53ff5ba455e83139d177c8c89226bab5495 | bigcode/the-stack | train |
195a4a4f6287fd2fb13b44ab | train | class | class CiFuzzTargetRunner(BaseFuzzTargetRunner):
"""Runner for fuzz targets used in CI (patch-fuzzing) context."""
@property
def quit_on_bug_found(self):
return True
| class CiFuzzTargetRunner(BaseFuzzTargetRunner):
| """Runner for fuzz targets used in CI (patch-fuzzing) context."""
@property
def quit_on_bug_found(self):
return True
| _parser.parse_fuzzer_output(result.stacktrace,
bug_summary_artifact_path)
bug_found = True
if self.quit_on_bug_found:
logging.info('Bug found. Stopping fuzzing.')
return bug_found
return bug_found
class CiFuzzTargetRunner(BaseFuzzTargetRunner):
| 64 | 64 | 45 | 12 | 51 | aawc/oss-fuzz | infra/cifuzz/run_fuzzers.py | Python | CiFuzzTargetRunner | CiFuzzTargetRunner | 166 | 171 | 166 | 166 | 4a01f945cf4332d40a6307f34f780d901fb60c1b | bigcode/the-stack | train |
21c35aa7963d42b5d5d8967c | train | class | class BatchFuzzTargetRunner(BaseFuzzTargetRunner):
"""Runner for fuzz targets used in batch fuzzing context."""
@property
def quit_on_bug_found(self):
return False
| class BatchFuzzTargetRunner(BaseFuzzTargetRunner):
| """Runner for fuzz targets used in batch fuzzing context."""
@property
def quit_on_bug_found(self):
return False
| _found
return bug_found
class CiFuzzTargetRunner(BaseFuzzTargetRunner):
"""Runner for fuzz targets used in CI (patch-fuzzing) context."""
@property
def quit_on_bug_found(self):
return True
class BatchFuzzTargetRunner(BaseFuzzTargetRunner):
| 64 | 64 | 41 | 12 | 51 | aawc/oss-fuzz | infra/cifuzz/run_fuzzers.py | Python | BatchFuzzTargetRunner | BatchFuzzTargetRunner | 174 | 179 | 174 | 174 | 9926f797d82144e809430975649267037afbf50c | bigcode/the-stack | train |
827cc55a44285bf1572eaf5f | train | class | class RunFuzzersResult(enum.Enum):
"""Enum result from running fuzzers."""
ERROR = 0
BUG_FOUND = 1
NO_BUG_FOUND = 2
| class RunFuzzersResult(enum.Enum):
| """Enum result from running fuzzers."""
ERROR = 0
BUG_FOUND = 1
NO_BUG_FOUND = 2
| import shutil
import sys
import time
import clusterfuzz_deployment
import fuzz_target
import stack_parser
# pylint: disable=wrong-import-position,import-error
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import utils
class RunFuzzersResult(enum.Enum):
| 64 | 64 | 40 | 9 | 54 | aawc/oss-fuzz | infra/cifuzz/run_fuzzers.py | Python | RunFuzzersResult | RunFuzzersResult | 32 | 36 | 32 | 32 | 15c61bac2ea0e607c92b2593affc05b3b21ed1d2 | bigcode/the-stack | train |
02ee17182833de32a68198bd | train | function | def get_fuzz_target_runner(config):
"""Returns a fuzz target runner object based on the run_fuzzers_mode of
|config|."""
logging.info('RUN_FUZZERS_MODE is: %s', config.run_fuzzers_mode)
if config.run_fuzzers_mode == 'batch':
return BatchFuzzTargetRunner(config)
return CiFuzzTargetRunner(config)
| def get_fuzz_target_runner(config):
| """Returns a fuzz target runner object based on the run_fuzzers_mode of
|config|."""
logging.info('RUN_FUZZERS_MODE is: %s', config.run_fuzzers_mode)
if config.run_fuzzers_mode == 'batch':
return BatchFuzzTargetRunner(config)
return CiFuzzTargetRunner(config)
| @property
def quit_on_bug_found(self):
return True
class BatchFuzzTargetRunner(BaseFuzzTargetRunner):
"""Runner for fuzz targets used in batch fuzzing context."""
@property
def quit_on_bug_found(self):
return False
def get_fuzz_target_runner(config):
| 64 | 64 | 83 | 8 | 55 | aawc/oss-fuzz | infra/cifuzz/run_fuzzers.py | Python | get_fuzz_target_runner | get_fuzz_target_runner | 182 | 188 | 182 | 182 | eff6f54ef7ae7ca64c01d31b3d710cbae967a499 | bigcode/the-stack | train |
e187fb828df2da82aab12589 | train | function | def run_fuzzers(config): # pylint: disable=too-many-locals
"""Runs fuzzers for a specific OSS-Fuzz project.
Args:
config: A RunFuzzTargetsConfig.
Returns:
A RunFuzzersResult enum value indicating what happened during fuzzing.
"""
fuzz_target_runner = get_fuzz_target_runner(config)
if not fuzz_tar... | def run_fuzzers(config): # pylint: disable=too-many-locals
| """Runs fuzzers for a specific OSS-Fuzz project.
Args:
config: A RunFuzzTargetsConfig.
Returns:
A RunFuzzersResult enum value indicating what happened during fuzzing.
"""
fuzz_target_runner = get_fuzz_target_runner(config)
if not fuzz_target_runner.initialize():
# We didn't fuzz at all because... | ZZERS_MODE is: %s', config.run_fuzzers_mode)
if config.run_fuzzers_mode == 'batch':
return BatchFuzzTargetRunner(config)
return CiFuzzTargetRunner(config)
def run_fuzzers(config): # pylint: disable=too-many-locals
| 64 | 64 | 190 | 19 | 45 | aawc/oss-fuzz | infra/cifuzz/run_fuzzers.py | Python | run_fuzzers | run_fuzzers | 191 | 211 | 191 | 191 | f5a7c88b9b3c47cf55e9cb39f6830708aa8d7dab | bigcode/the-stack | train |
1081d6b6721591b6c2cae482 | train | class | class BaseFuzzTargetRunner:
"""Base class for fuzzer runners."""
def __init__(self, config):
self.config = config
self.clusterfuzz_deployment = (
clusterfuzz_deployment.get_clusterfuzz_deployment(self.config))
# Set by the initialize method.
self.out_dir = None
self.fuzz_target_paths = ... | class BaseFuzzTargetRunner:
| """Base class for fuzzer runners."""
def __init__(self, config):
self.config = config
self.clusterfuzz_deployment = (
clusterfuzz_deployment.get_clusterfuzz_deployment(self.config))
# Set by the initialize method.
self.out_dir = None
self.fuzz_target_paths = None
self.artifacts_dir ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 246 | 256 | 1,123 | 7 | 238 | aawc/oss-fuzz | infra/cifuzz/run_fuzzers.py | Python | BaseFuzzTargetRunner | BaseFuzzTargetRunner | 39 | 163 | 39 | 39 | 31a582b026255d2094aef449b3156f6e63f793be | bigcode/the-stack | train |
b4ad308fa0d4ca1272ec6748 | train | class | class CocoStuff10k(BaseDataSet):
def __init__(self, warp_image = True, **kwargs):
self.warp_image = warp_image
self.num_classes = 182
self.palette = palette.COCO_palette
super(CocoStuff10k, self).__init__(**kwargs)
def _set_files(self):
if self.split in ['train', 'test',... | class CocoStuff10k(BaseDataSet):
| def __init__(self, warp_image = True, **kwargs):
self.warp_image = warp_image
self.num_classes = 182
self.palette = palette.COCO_palette
super(CocoStuff10k, self).__init__(**kwargs)
def _set_files(self):
if self.split in ['train', 'test', 'all']:
file_list = ... | # Originally written by Kazuto Nakashima
# https://github.com/kazuto1011/deeplab-pytorch
from base import BaseDataSet, BaseDataLoader
from PIL import Image
from glob import glob
import numpy as np
import scipy.io as sio
from utils import palette
import torch
import os
import cv2
class CocoStuff10k(BaseDataSet):
| 83 | 96 | 320 | 9 | 73 | can-song/pytorch_segmentation | dataloaders/coco.py | Python | CocoStuff10k | CocoStuff10k | 14 | 38 | 14 | 14 | 55160edd35d1e43bce0aa46f0131cb653f12f700 | bigcode/the-stack | train |
29c591a750b154507a6af3da | train | class | class CocoStuff164k(BaseDataSet):
def __init__(self, **kwargs):
self.num_classes = 182
self.palette = palette.COCO_palette
super(CocoStuff164k, self).__init__(**kwargs)
def _set_files(self):
if self.split in ['train2017', 'val2017']:
file_list = sorted(glob(os.path.j... | class CocoStuff164k(BaseDataSet):
| def __init__(self, **kwargs):
self.num_classes = 182
self.palette = palette.COCO_palette
super(CocoStuff164k, self).__init__(**kwargs)
def _set_files(self):
if self.split in ['train2017', 'val2017']:
file_list = sorted(glob(os.path.join(self.root, 'images', self.spli... | 255
if self.warp_image:
image = cv2.resize(image, (513, 513), interpolation=cv2.INTER_LINEAR)
label = np.asarray(Image.fromarray(label).resize((513, 513), resample=Image.NEAREST))
return image, label, image_id
class CocoStuff164k(BaseDataSet):
| 73 | 73 | 246 | 9 | 63 | can-song/pytorch_segmentation | dataloaders/coco.py | Python | CocoStuff164k | CocoStuff164k | 40 | 58 | 40 | 40 | 99f1891fa5f9d3239b38302e3bfcb3dcba66371a | bigcode/the-stack | train |
a30918bcfcc337680317eec3 | train | class | class COCO(BaseDataLoader):
def __init__(self, data_dir, batch_size, split, crop_size=None, base_size=None, scale=True, num_workers=1, partition='CocoStuff164k',
shuffle=False, flip=False, rotate=False, blur= False, augment=False, val_split= None, return_id=False, val=False):
self.MEAN ... | class COCO(BaseDataLoader):
| def __init__(self, data_dir, batch_size, split, crop_size=None, base_size=None, scale=True, num_workers=1, partition='CocoStuff164k',
shuffle=False, flip=False, rotate=False, blur= False, augment=False, val_split= None, return_id=False, val=False):
self.MEAN = [0.43931922, 0.41310471, 0... | .IMREAD_GRAYSCALE)
return image, label, image_id
def get_parent_class(value, dictionary):
for k, v in dictionary.items():
if isinstance(v, list):
if value in v:
yield k
elif isinstance(v, dict):
if value in list(v.keys()):
yield k
... | 93 | 93 | 312 | 7 | 85 | can-song/pytorch_segmentation | dataloaders/coco.py | Python | COCO | COCO | 72 | 102 | 72 | 72 | ebbfb16babe53ceb08e5a3562e2281db01a8d915 | bigcode/the-stack | train |
00eed33a199fb06dafcb2046 | train | function | def get_parent_class(value, dictionary):
for k, v in dictionary.items():
if isinstance(v, list):
if value in v:
yield k
elif isinstance(v, dict):
if value in list(v.keys()):
yield k
else:
for res in get_parent_class(... | def get_parent_class(value, dictionary):
| for k, v in dictionary.items():
if isinstance(v, list):
if value in v:
yield k
elif isinstance(v, dict):
if value in list(v.keys()):
yield k
else:
for res in get_parent_class(value, v):
yield res
| annotations', self.split, image_id + '.png')
image = np.asarray(Image.open(image_path).convert('RGB'), dtype=np.float32)
label = cv2.imread(label_path, cv2.IMREAD_GRAYSCALE)
return image, label, image_id
def get_parent_class(value, dictionary):
| 64 | 64 | 71 | 8 | 55 | can-song/pytorch_segmentation | dataloaders/coco.py | Python | get_parent_class | get_parent_class | 60 | 70 | 60 | 60 | f63196b6ad1e34507f1f7c519fa6ce34d3f2df3a | bigcode/the-stack | train |
a8882156a0a594e1b7b51641 | train | function | def crawl_month_amlich(year, month):
if not (1 <= month <= 12): # invalid month
return []
link = "https://www.informatik.uni-leipzig.de/~duc/amlich/PHP/index.php?dd=1&mm={}&yy={}".format(month, year)
try:
f = urllib.request.urlopen(link, timeout=10)
except urllib.error.HTTPError as e:
print('Error... | def crawl_month_amlich(year, month):
| if not (1 <= month <= 12): # invalid month
return []
link = "https://www.informatik.uni-leipzig.de/~duc/amlich/PHP/index.php?dd=1&mm={}&yy={}".format(month, year)
try:
f = urllib.request.urlopen(link, timeout=10)
except urllib.error.HTTPError as e:
print('Error code: ', e.code)
return []
excep... | }/{}".format(l_date[0], l_date[1])
if l_date == 1 and l_date[3] == 1:
str_lunar += " (N)"
else:
str_lunar = str(l_date[0])
calendar[-1][day_of_week] = (loc_date, str_lunar)
day_of_week = (day_of_week + 1) % 7
if day_of_week == 0 and loc_date + 1 <= days:
calendar.append([None] * 7)
... | 131 | 131 | 437 | 9 | 121 | neihousaigaai/own-lunar-calendar | get_data.py | Python | crawl_month_amlich | crawl_month_amlich | 47 | 92 | 47 | 47 | c2283e3c53bf837f03cad62d45871790d910d525 | bigcode/the-stack | train |
576777b4e440fb2f4b0d300a | train | function | def count_days_in_month(year, month):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
else: # month == 2
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
return 29
else:
return 28
| def count_days_in_month(year, month):
| if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
else: # month == 2
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
return 29
else:
return 28
| import urllib.request
import urllib.error
def count_days_in_month(year, month):
| 17 | 64 | 107 | 9 | 7 | neihousaigaai/own-lunar-calendar | get_data.py | Python | count_days_in_month | count_days_in_month | 5 | 14 | 5 | 5 | 59390405cabb1c341700bff04ea602b1eb3e3e99 | bigcode/the-stack | train |
5ebbb5a3ea3354522bba1c27 | train | function | def get_month_offline(year, month):
if not (1 <= month <= 12): # invalid month
return []
import AL_offline
import datetime
days = count_days_in_month(year, month)
day_of_week = datetime.date(year, month, 1).weekday() # Monday
calendar = [[None] * 7]
for loc_date in range(1, days+1):
l_date =... | def get_month_offline(year, month):
| if not (1 <= month <= 12): # invalid month
return []
import AL_offline
import datetime
days = count_days_in_month(year, month)
day_of_week = datetime.date(year, month, 1).weekday() # Monday
calendar = [[None] * 7]
for loc_date in range(1, days+1):
l_date = AL_offline.S2L(loc_date, month, year... | in [4, 6, 9, 11]:
return 30
else: # month == 2
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
return 29
else:
return 28
def get_month_offline(year, month):
| 76 | 76 | 254 | 9 | 66 | neihousaigaai/own-lunar-calendar | get_data.py | Python | get_month_offline | get_month_offline | 17 | 44 | 17 | 17 | 8a7f663a37d907f86e0246b441dba9df450503a5 | bigcode/the-stack | train |
586f048b0461ea3291d25b0e | train | function | def main():
start = Path('data/pages')
data_files = []
mod_dirs = []
config_dirs = []
config_un_dirs = set()
config_un_files = {}
components_data = OrderedDict()
# noinspection SpellCheckingInspection
def_data = OrderedDict((
('fixed', False),
('restart', F... | def main():
| start = Path('data/pages')
data_files = []
mod_dirs = []
config_dirs = []
config_un_dirs = set()
config_un_files = {}
components_data = OrderedDict()
# noinspection SpellCheckingInspection
def_data = OrderedDict((
('fixed', False),
('restart', False),
... | import os
import sys
import traceback
from collections import OrderedDict
from pathlib import Path
def make_component(parts):
return str(Path(*(p[(p.index('%') + 1) if '%' in p else 0:] for p in parts)))
def main():
| 56 | 256 | 2,876 | 3 | 53 | PolyacovYury/ModPacker | src/component_generator.py | Python | main | main | 12 | 292 | 12 | 12 | a59ed7027ba708a449fec0e39d4e16db34beab48 | bigcode/the-stack | train |
e28bffc65deb340395033b10 | train | function | def make_component(parts):
return str(Path(*(p[(p.index('%') + 1) if '%' in p else 0:] for p in parts)))
| def make_component(parts):
| return str(Path(*(p[(p.index('%') + 1) if '%' in p else 0:] for p in parts)))
| import os
import sys
import traceback
from collections import OrderedDict
from pathlib import Path
def make_component(parts):
| 25 | 64 | 33 | 5 | 19 | PolyacovYury/ModPacker | src/component_generator.py | Python | make_component | make_component | 8 | 9 | 8 | 8 | 655b3f51f51eb25ec664c4eb872478388bbf6346 | bigcode/the-stack | train |
edc1a1bcc293230ad7de6d2e | train | class | class TestBitcoinCli(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
"""Main test logic"""
self.log.info("Sleeping 30 seconds...")
time.sleep(30)
self.log.info("Compare responses from gewal... | class TestBitcoinCli(BitcoinTestFramework):
| def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
"""Main test logic"""
self.log.info("Sleeping 30 seconds...")
time.sleep(30)
self.log.info("Compare responses from gewalletinfo RPC and `redspace-cli getwalletinfo`"... | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test redspace-cli"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util... | 93 | 156 | 521 | 9 | 83 | salo50/coin | test/functional/interface_bitcoin_cli.py | Python | TestBitcoinCli | TestBitcoinCli | 10 | 54 | 10 | 11 | 7af730a5f7b72e38000c8b0e745558be57708916 | bigcode/the-stack | train |
54b1ed2c0acd435df684fd52 | train | function | def getDistance(bounding_target, bounding_list):
distance = []
bx, by, bw, bh = cv2.boundingRect(bounding_target)
for index in range(len(bounding_list)):
x, y, w, h = cv2.boundingRect(bounding_list[index])
d_x = bx - x
d_y = by - y
d = pow(d_x, 2) + pow(d_y, 2)
d = po... | def getDistance(bounding_target, bounding_list):
| distance = []
bx, by, bw, bh = cv2.boundingRect(bounding_target)
for index in range(len(bounding_list)):
x, y, w, h = cv2.boundingRect(bounding_list[index])
d_x = bx - x
d_y = by - y
d = pow(d_x, 2) + pow(d_y, 2)
d = pow(d, 0.5)
distance.append(d)
return d... | #!/usr/bin/python3
import cv2
import numpy as np
import time
import os
def getDistance(bounding_target, bounding_list):
| 31 | 64 | 113 | 10 | 20 | don6105/OCR-Captcha-Recognition | process_img.py | Python | getDistance | getDistance | 7 | 17 | 7 | 7 | 2e71122e15cd9d5ab97b04ba2e73a1eec65ae23b | bigcode/the-stack | train |
b0cb0fce9f6746ed094eaa39 | train | function | def run(input_path, output_path, index_filename = 0):
if (os.path.exists(output_path) == False):
os.makedirs(output_path) #Create folder
files = os.listdir(input_path)
index = 0
for filename in files:
img = cv2.imread(os.path.join(input_path, filename))
# 灰阶
img_gray = c... | def run(input_path, output_path, index_filename = 0):
| if (os.path.exists(output_path) == False):
os.makedirs(output_path) #Create folder
files = os.listdir(input_path)
index = 0
for filename in files:
img = cv2.imread(os.path.join(input_path, filename))
# 灰阶
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
... | np.int0([[x,y], [x+w/2,y], [x+w/2,y+h], [x,y+h]])
box_right = np.int0([[x+w/2,y], [x+w,y], [x+w,y+h], [x+w/2,y+h]])
result.append(box_left)
result.append(box_right)
else:
box = np.int0([[x,y], [x+w,y], [x+w,y+h], [x,y+h]])
result.append(box)
f... | 130 | 130 | 435 | 14 | 115 | don6105/OCR-Captcha-Recognition | process_img.py | Python | run | run | 62 | 94 | 62 | 62 | 8f68ac291a5e439082967aa1978103a3218018fb | bigcode/the-stack | train |
114837163572de55bfcbeb3b | train | function | def splitText(img_res):
contours, hierarchy = cv2.findContours(img_res, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours.sort(key=lambda x: cv2.boundingRect(x)[2] * cv2.boundingRect(x)[3]) # small area first
height, width = img_res.shape
avg_height = height * 0.8
avg_width = width * 0.25 * 0.... | def splitText(img_res):
| contours, hierarchy = cv2.findContours(img_res, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours.sort(key=lambda x: cv2.boundingRect(x)[2] * cv2.boundingRect(x)[3]) # small area first
height, width = img_res.shape
avg_height = height * 0.8
avg_width = width * 0.25 * 0.7 # 4 char per img, padd... | #!/usr/bin/python3
import cv2
import numpy as np
import time
import os
def getDistance(bounding_target, bounding_list):
distance = []
bx, by, bw, bh = cv2.boundingRect(bounding_target)
for index in range(len(bounding_list)):
x, y, w, h = cv2.boundingRect(bounding_list[index])
d_x = bx - x
... | 140 | 158 | 527 | 6 | 133 | don6105/OCR-Captcha-Recognition | process_img.py | Python | splitText | splitText | 19 | 60 | 19 | 19 | 325c165da02684c1270512d7f9acf83f068efadb | bigcode/the-stack | train |
06ff8a2ad1afd8a5ababece5 | train | class | class ImplicitCarlaEnv(BaseCarlaEnv):
'''
The Carla environment for RL training
'''
def __init__(self, args):
self.args = args
self.port = args.port
self.host = args.host
self._simulator_cfg = self.args.simulator
self.weather_list = self.args.weather_list
... | class ImplicitCarlaEnv(BaseCarlaEnv):
| '''
The Carla environment for RL training
'''
def __init__(self, args):
self.args = args
self.port = args.port
self.host = args.host
self._simulator_cfg = self.args.simulator
self.weather_list = self.args.weather_list
self.town = self.args.town
s... | import time
import os
import copy
from enum import Enum
from pathlib import Path
from collections import deque, namedtuple, OrderedDict
import numpy as np
import carla
import torch
from core.simulators import CarlaSimulator
from core.envs.base_carla_env import BaseCarlaEnv
from models import ImplicitSupervisedModel
f... | 154 | 256 | 4,431 | 11 | 143 | timothijoe/DI-drive | demo/implicit/carla_env.py | Python | ImplicitCarlaEnv | ImplicitCarlaEnv | 22 | 480 | 22 | 22 | 6d5ec0b3a339c2007871f910361377d87836975b | bigcode/the-stack | train |
c79b9a3441472b58f9d47d0b | train | class | @register_predictor("Xgboost")
class XgboostRegressionMoap(Moap):
def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using XGBoost.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will be scaled
... | @register_predictor("Xgboost")
class XgboostRegressionMoap(Moap):
| def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using XGBoost.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will be scaled
before classification
ncpus : int, optional
... | df_X.shape[0]:
raise ValueError("number of regions is not equal")
if self.scale:
logger.debug("Scaling motif scores")
# Scale motif scores
df_X[:] = scale(df_X, axis=0)
# logger.debug("Scaling y")
# Normalize across samples and features
... | 195 | 195 | 652 | 20 | 174 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | XgboostRegressionMoap | XgboostRegressionMoap | 183 | 264 | 183 | 184 | 0bfd9a87244da83d08bdbbe415c10dcb9933ede9 | bigcode/the-stack | train |
0ba85e7f1e07215cc057e539 | train | class | @register_predictor("MWU")
class MWUMoap(Moap):
def __init__(self, *args, **kwargs):
"""Predict motif activities using Mann-Whitney U p-value
This method compares the motif score distribution of each
cluster versus the motif score distribution of all other
clusters.
Paramet... | @register_predictor("MWU")
class MWUMoap(Moap):
| def __init__(self, *args, **kwargs):
"""Predict motif activities using Mann-Whitney U p-value
This method compares the motif score distribution of each
cluster versus the motif score distribution of all other
clusters.
Parameters
----------
Attributes
... | if self.act_.loc[motif, col] != 0:
high = df_y.loc[
df_X[motif] >= df_X[motif].quantile(0.75), col
].mean()
low = df_y.loc[
df_X[motif] <= df_X[motif].quantile(0.25), col
].mea... | 147 | 147 | 493 | 17 | 130 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | MWUMoap | MWUMoap | 267 | 324 | 267 | 268 | 0558d121950da5f1c6ffddce4b257d006e89d1db | bigcode/the-stack | train |
0920f23b3a078db65e213359 | train | class | @register_predictor("BayesianRidge")
class BayesianRidgeMoap(Moap):
def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using Bayesian Ridge Regression.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will b... | @register_predictor("BayesianRidge")
class BayesianRidgeMoap(Moap):
| def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using Bayesian Ridge Regression.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will be scaled
before classification.
ncpus : int, op... | ification_predictors(self):
"""List available classification predictors."""
preds = [self.create(x) for x in self._predictors.keys()]
return [x.name for x in preds if x.ptype == "classification"]
@classmethod
def list_regression_predictors(self):
"""List available regression pre... | 132 | 132 | 440 | 20 | 111 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | BayesianRidgeMoap | BayesianRidgeMoap | 122 | 180 | 122 | 123 | bcfe7f7e6b4286e369f1c66c9a88a134fb083887 | bigcode/the-stack | train |
b6b9f8af22a0dc0dc486b1e2 | train | function | def moap(
inputfile,
method="hypergeom",
scoring=None,
outfile=None,
motiffile=None,
pfmfile=None,
genome=None,
fpr=0.01,
ncpus=None,
subsample=None,
zscore=True,
gc=True,
):
"""Run a single motif activity prediction algorithm.
Parameters
----------
input... | def moap(
inputfile,
method="hypergeom",
scoring=None,
outfile=None,
motiffile=None,
pfmfile=None,
genome=None,
fpr=0.01,
ncpus=None,
subsample=None,
zscore=True,
gc=True,
):
| """Run a single motif activity prediction algorithm.
Parameters
----------
inputfile : str
:1File with regions (chr:start-end) in first column and either cluster
name in second column or a table with values.
method : str, optional
Motif activity method to use. Any of 'hyper... | =0)
# logger.debug("Scaling y")
# Normalize across samples and features
# y = df_y.apply(scale, 1).apply(scale, 0)
y = df_y
self.columns = df_y.columns
X = df_X.loc[y.index]
clf = LinearSVR()
self.model = MultiOutputRegressor(clf, n_jobs=1)
logg... | 256 | 256 | 1,108 | 66 | 190 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | moap | moap | 598 | 754 | 598 | 611 | abd887e7e4a27460afe71697656219688b3a53c5 | bigcode/the-stack | train |
5370c487f07c9e265d5acd76 | train | function | def warn(*args, **kwargs):
pass
| def warn(*args, **kwargs):
| pass
| eringen <simon.vanheeringen@gmail.com>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
""" Module for motif activity prediction """
def warn(*args, **kwargs):
| 63 | 64 | 11 | 8 | 55 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | warn | warn | 9 | 10 | 9 | 9 | 36a509ee6894af6d19b1667a3f56b788dda983f1 | bigcode/the-stack | train |
399cc4dec00c3ed72a135e4d | train | class | class Moap(object):
"""Moap base class.
Motif activity prediction.
"""
_predictors = {}
name = None
@classmethod
def create(cls, name, ncpus=None):
"""Create a Moap instance based on the predictor name.
Parameters
----------
name : str
Name of ... | class Moap(object):
| """Moap base class.
Motif activity prediction.
"""
_predictors = {}
name = None
@classmethod
def create(cls, name, ncpus=None):
"""Create a Moap instance based on the predictor name.
Parameters
----------
name : str
Name of the predictor (eg. X... | .preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import xgboost
from gimmemotifs import __version__
from gimmemotifs.motif import read_motifs
from gimmemotifs.scanner import scan_regionfile_to_table
from gimmemotifs.config import MotifConfig
from gimmemotifs.utils import pfmfile_location
im... | 108 | 108 | 360 | 5 | 103 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | Moap | Moap | 58 | 116 | 58 | 58 | 70f5ab1e348bd90c369a3cb45513a81852abd793 | bigcode/the-stack | train |
0bb448a25810b354ff7cecad | train | class | @register_predictor("RF")
class RFMoap(Moap):
def __init__(self, ncpus=None):
"""Predict motif activities using a random forest classifier
Parameters
----------
ncpus : int, optional
Number of threads. Default is the number specified in the config.
Attributes
... | @register_predictor("RF")
class RFMoap(Moap):
| def __init__(self, ncpus=None):
"""Predict motif activities using a random forest classifier
Parameters
----------
ncpus : int, optional
Number of threads. Default is the number specified in the config.
Attributes
----------
act_ : DataFrame, sha... | p = []
for pt, pf, nt in zip(pos_true, pos_false, neg_true):
n = pt + nt
N = pt + pf
x = pt - 1
p.append(hypergeom.sf(x, M, n, N))
pvals.append(p)
# correct for multipe testing
pvals = np.array(pvals)
fpr ... | 159 | 159 | 530 | 15 | 144 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | RFMoap | RFMoap | 391 | 453 | 391 | 392 | 7e47acf5f2de33c954453017c0cb31494180b522 | bigcode/the-stack | train |
2e75adcd3107195159044e41 | train | class | @register_predictor("Hypergeom")
class HypergeomMoap(Moap):
def __init__(self, *args, **kwargs):
"""Predict motif activities using hypergeometric p-value
Parameters
----------
Attributes
----------
act_ : DataFrame, shape (n_motifs, n_clusters)
-log10 of... | @register_predictor("Hypergeom")
class HypergeomMoap(Moap):
| def __init__(self, *args, **kwargs):
"""Predict motif activities using hypergeometric p-value
Parameters
----------
Attributes
----------
act_ : DataFrame, shape (n_motifs, n_clusters)
-log10 of the hypergeometric p-value, corrected for multiple
... | ], neg[m], alternative="greater")[1])
except Exception as e:
sys.stderr.write(str(e) + "\n")
sys.stderr.write("motif {} failed, setting to p = 1\n".format(m))
p.append(1)
pvals.append(p)
# correct for multipe testing
... | 157 | 157 | 525 | 17 | 140 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | HypergeomMoap | HypergeomMoap | 327 | 388 | 327 | 328 | 3427dc279a0fe93b89af79657df630e8f191d5b5 | bigcode/the-stack | train |
bc85c0d0c7b87cfc07878592 | train | class | @register_predictor("SVR")
class SVRMoap(Moap):
def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using Support Vector Regression.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will be scaled
... | @register_predictor("SVR")
class SVRMoap(Moap):
| def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using Support Vector Regression.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will be scaled
before classification.
ncpus : int, op... | ]
model = Pipeline(
[
("scale", StandardScaler()),
(
"reg",
MultiTaskLassoCV(
fit_intercept=False, n_alphas=20, n_jobs=self.ncpus
),
),
]
)
... | 147 | 147 | 491 | 17 | 130 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | SVRMoap | SVRMoap | 529 | 595 | 529 | 530 | bfc7dc6ae0a369f0b6add58309bf7ca4fb806c68 | bigcode/the-stack | train |
07648276c0c8b36b643256e6 | train | class | @register_predictor("MultiTaskLasso")
class MultiTaskLassoMoap(Moap):
def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using MultiTaskLasso.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will be scaled
... | @register_predictor("MultiTaskLasso")
class MultiTaskLassoMoap(Moap):
| def __init__(self, scale=True, ncpus=None):
"""Predict motif activities using MultiTaskLasso.
Parameters
----------
scale : boolean, optional, default True
If ``True``, the motif scores will be scaled
before classification.
ncpus : int, optional
... | ances_, clf.feature_importances_]
).T
for i, _ in enumerate(le.classes_):
diff = df_X.loc[y == i].quantile(q=0.75) - df_X.loc[y != i].quantile(q=0.75)
sign = (diff >= 0) * 2 - 1
importances[:, i] *= sign
# create output DataFrame
self.act_ = pd.D... | 149 | 149 | 498 | 21 | 128 | Maarten-vd-Sande/gimmemotifs | gimmemotifs/moap.py | Python | MultiTaskLassoMoap | MultiTaskLassoMoap | 456 | 526 | 456 | 457 | 18edc46c9e778f0dd09029274ea6b3eaacb1e737 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.