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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3e37bde9b6325a28f7a2d52 | train | function | def parse(file_tf):
r = ReadSkill()
with open(file_tf,"r") as f:
#data = read(f,0)
r.read(f)
return r.obj
| def parse(file_tf):
| r = ReadSkill()
with open(file_tf,"r") as f:
#data = read(f,0)
r.read(f)
return r.obj
| not val.isspace():
data[key] = val.lstrip("\"").rstrip("\"")
else:
level += 1
data[key] = read(f,level,pkey=key)
continue
buf.append(line.lstrip().rstrip())
return data
def parse(file_tf):
| 64 | 64 | 41 | 5 | 58 | wulffern/cicpytools | cicpytools/skill.py | Python | parse | parse | 386 | 393 | 386 | 387 | 85b6a2b0056341070643c6cbefa9b728cb37e292 | bigcode/the-stack | train |
d485a74cad8b19b1bc43410e | train | class | class SkillObject:
def __init__(self,name=""):
self.name = name
self.tokens = list()
self.children = list()
self.commands = dict()
self.parent = None
self.comment = list()
def addToken(self,token):
self.tokens.append(token)
def addComment(self,comme... | class SkillObject:
| def __init__(self,name=""):
self.name = name
self.tokens = list()
self.children = list()
self.commands = dict()
self.parent = None
self.comment = list()
def addToken(self,token):
self.tokens.append(token)
def addComment(self,comment):
self.co... | AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
## SOFTWARE.
##
####################... | 83 | 83 | 279 | 4 | 78 | wulffern/cicpytools | cicpytools/skill.py | Python | SkillObject | SkillObject | 31 | 84 | 31 | 32 | 71338d398a6c39e79269939b9dc8736076970d56 | bigcode/the-stack | train |
d070f2c16b9952473f5f27f7 | train | function | def read_data(buffer):
if not buffer:
return
if not buffer[0].startswith(";"):
# print(f"INFO: don't know how to parse this buffer '{buffer}'")
return
header = buffer[0].replace(";","")
print(header)
htok = tokenize(header)
print(htok)
| def read_data(buffer):
| if not buffer:
return
if not buffer[0].startswith(";"):
# print(f"INFO: don't know how to parse this buffer '{buffer}'")
return
header = buffer[0].replace(";","")
print(header)
htok = tokenize(header)
print(htok)
| key = ""
break
else:
if isinstance(data,dict):
raise Exception("Ops, data is dict without key tok:'" + tok + "' key:'"+key+"'")
else:
data.append(tok)
prev_tok = tok
return data
def read_data(buffer):
| 64 | 64 | 71 | 5 | 58 | wulffern/cicpytools | cicpytools/skill.py | Python | read_data | read_data | 338 | 350 | 338 | 339 | 9758839bb709a46874e63b7006e01a9afcb3b28b | bigcode/the-stack | train |
cc8ce8700d24521c971d0b34 | train | function | def sim_plot(popin=None, confin=None, outpng='', city='N/A'):
# working mode
if popin == None and confin != None:
with open(confin) as cin:
config = json.load(cin)
start_date = config['start_date']
stop_date = config['stop_date']
datetime_format = '%Y-%m-%d %H:%M:%S'
start = datetime.strp... | def sim_plot(popin=None, confin=None, outpng='', city='N/A'):
# working mode
| if popin == None and confin != None:
with open(confin) as cin:
config = json.load(cin)
start_date = config['start_date']
stop_date = config['stop_date']
datetime_format = '%Y-%m-%d %H:%M:%S'
start = datetime.strptime(start_date, datetime_format)
stop = datetime.strptime(start_date, date... | #! /usr/bin/env python3
import json
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
def sim_plot(popin=None, confin=None, outpng='', city='N/A'):
# working mode
| 52 | 256 | 1,159 | 23 | 28 | physycom/slides | utils/report/sim_plotter.py | Python | sim_plot | sim_plot | 8 | 135 | 8 | 9 | 9a64f6379840e5f1b905c282cb875b2a567c5a95 | bigcode/the-stack | train |
1116ce797c6a124f0718dbb8 | train | function | @click.command(help=__DOC)
@click.option(
'--sample-metadata-project',
help='The sample-metadata project to import manifest into',
)
@click.option('--default-sample-type', default='blood')
@click.option('--default-sequence-type', default='wgs')
@click.option(
'--confirm', is_flag=True, help='Confirm with us... | @click.command(help=__DOC)
@click.option(
'--sample-metadata-project',
help='The sample-metadata project to import manifest into',
)
@click.option('--default-sample-type', default='blood')
@click.option('--default-sequence-type', default='wgs')
@click.option(
'--confirm', is_flag=True, help='Confirm with us... | """Run script from CLI arguments"""
if not manifests:
raise ValueError('Expected at least 1 manifest')
extra_seach_paths = [m for m in manifests if m.startswith('gs://')]
if extra_seach_paths:
search_path = list(set(search_path).union(set(extra_seach_paths)))
parser = SampleFileMap... | @click.command(help=__DOC)
@click.option(
'--sample-metadata-project',
help='The sample-metadata project to import manifest into',
)
@click.option('--default-sample-type', default='blood')
@click.option('--default-sequence-type', default='wgs')
@click.option(
'--confirm', is_flag=True, help='Confirm with us... | 255 | 128 | 429 | 255 | 0 | gregsmi/sample-metadata | sample_metadata/parser/sample_file_map_parser.py | Python | main | main | 83 | 142 | 83 | 119 | f4e1b499c1ceb6978057694e36c04ff237221636 | bigcode/the-stack | train |
d81a96a29fef93f387ea2ee3 | train | class | class SampleFileMapParser(GenericMetadataParser):
"""Parser for SampleFileMap"""
def __init__(
self,
search_locations: List[str],
sample_metadata_project: str,
default_sequence_type='genome',
default_sample_type='blood',
allow_extra_files_in_search_path=False,
... | class SampleFileMapParser(GenericMetadataParser):
| """Parser for SampleFileMap"""
def __init__(
self,
search_locations: List[str],
sample_metadata_project: str,
default_sequence_type='genome',
default_sample_type='blood',
allow_extra_files_in_search_path=False,
):
super().__init__(
search_... |
Apollo sample_id004 sample_id004.filename-R2.fastq.gz
This format is useful for ingesting filenames for the seqr loading pipeline
"""
logger = logging.getLogger(__file__)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)
class SampleFileMapParser(GenericMetadataParser):
| 64 | 64 | 185 | 9 | 55 | gregsmi/sample-metadata | sample_metadata/parser/sample_file_map_parser.py | Python | SampleFileMapParser | SampleFileMapParser | 55 | 80 | 55 | 55 | 359676e045efc4212ffcdad329453e24ec379a68 | bigcode/the-stack | train |
f2d513a0253d3603de28a346 | train | function | @require_http_methods(["GET"])
def get_coders(request):
try:
coderObj = coders.objects.all()
coderList = []
for coder in coderObj:
coderList.append({
"name":coder.username,
"phone":coder.phone,
})
data = {
"coder": c... | @require_http_methods(["GET"])
def get_coders(request):
| try:
coderObj = coders.objects.all()
coderList = []
for coder in coderObj:
coderList.append({
"name":coder.username,
"phone":coder.phone,
})
data = {
"coder": coderList,
"msg":"success",
"erro... | import coders,clients
from django.http import HttpResponse, HttpResponseRedirect
import json
from django.views.decorators.http import require_http_methods
from django.core import serializers
import requests
# Create your views here.
# noinspection PyInterpreter
@require_http_methods(["GET"])
def get_coders(request):... | 64 | 64 | 130 | 13 | 50 | Eniac-co/web | web/views.py | Python | get_coders | get_coders | 12 | 33 | 12 | 13 | b4d34286c2b3b867a1d20d214958e16f29cfd9a2 | bigcode/the-stack | train |
0092c8b099347bc9b3dea3f6 | train | function | @require_http_methods(["POST"])
def register_coders(request):
print("i'm in")
try:
username = request.POST.get('username')
phone = request.POST.get('phone')
mail = request.POST.get('mail')
skype = request.POST.get('skype')
coders.objects.create(username=username,phone=pho... | @require_http_methods(["POST"])
def register_coders(request):
| print("i'm in")
try:
username = request.POST.get('username')
phone = request.POST.get('phone')
mail = request.POST.get('mail')
skype = request.POST.get('skype')
coders.objects.create(username=username,phone=phone,email=mail,password=skype)
data = {
"us... | 0,
}
except Exception as e:
data = {
"msg":str(e),
"coder":[],
"errorNum":1
}
return HttpResponse(json.dumps(data), content_type="application/json")
@require_http_methods(["POST"])
def register_coders(request):
| 63 | 64 | 178 | 13 | 50 | Eniac-co/web | web/views.py | Python | register_coders | register_coders | 37 | 62 | 37 | 38 | f4a8103a1cd49883aa2e847d4a8ed37778ef34b6 | bigcode/the-stack | train |
fe68d628e00edb9de1618dc2 | train | function | def plot_paes(paes, Ls=None, dpi=100, fig=True):
num_models = len(paes)
if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
for n,pae in enumerate(paes):
plt.subplot(1,num_models,n+1)
plt.title(f"rank_{n+1}")
Ln = pae.shape[0]
plt.imshow(pae,cmap="bwr",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))
i... | def plot_paes(paes, Ls=None, dpi=100, fig=True):
| num_models = len(paes)
if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
for n,pae in enumerate(paes):
plt.subplot(1,num_models,n+1)
plt.title(f"rank_{n+1}")
Ln = pae.shape[0]
plt.imshow(pae,cmap="bwr",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))
if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
... | .plot([L,L],[0,100],color="black")
plt.legend()
plt.ylim(0,100)
plt.ylabel("Predicted lDDT")
plt.xlabel("Positions")
return plt
def plot_paes(paes, Ls=None, dpi=100, fig=True):
| 64 | 64 | 146 | 18 | 45 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_paes | plot_paes | 546 | 556 | 546 | 546 | a6c273fe2ad9977d44e0c5b7c286bd53ace0c893 | bigcode/the-stack | train |
0648be8171a63b3ef68ed4cf | train | function | def rm(x):
'''remove data from device'''
jax.tree_util.tree_map(lambda y: y.device_buffer.delete(), x)
| def rm(x):
| '''remove data from device'''
jax.tree_util.tree_map(lambda y: y.device_buffer.delete(), x)
| ymol_cmap = matplotlib.colors.ListedColormap(pymol_color_list)
alphabet_list = list(ascii_uppercase+ascii_lowercase)
aatypes = set('ACDEFGHIKLMNPQRSTVWY')
###########################################
# control gpu/cpu memory usage
###########################################
def rm(x):
| 64 | 64 | 28 | 4 | 60 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | rm | rm | 51 | 53 | 51 | 51 | a90208d87c6f25226c6e195ddb1f1f0dd718d118 | bigcode/the-stack | train |
ca18f983f55735b828cdd9e1 | train | function | def kabsch(a, b, weights=None, return_v=False):
a = np.asarray(a)
b = np.asarray(b)
if weights is None: weights = np.ones(len(b))
else: weights = np.asarray(weights)
B = np.einsum('ji,jk->ik', weights[:, None] * a, b)
u, s, vh = np.linalg.svd(B)
if np.linalg.det(u @ vh) < 0: u[:, -1] = -u[:, -1]
if retu... | def kabsch(a, b, weights=None, return_v=False):
| a = np.asarray(a)
b = np.asarray(b)
if weights is None: weights = np.ones(len(b))
else: weights = np.asarray(weights)
B = np.einsum('ji,jk->ik', weights[:, None] * a, b)
u, s, vh = np.linalg.svd(B)
if np.linalg.det(u @ vh) < 0: u[:, -1] = -u[:, -1]
if return_v: return u
else: return u @ vh
| plt.imshow(dist,extent=(0, Ln, Ln, 0))
if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
plt.colorbar()
return plt
##########################################################################
##########################################################################
def kabsch(a, b, weights=None, return_v=... | 64 | 64 | 127 | 14 | 50 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | kabsch | kabsch | 585 | 594 | 585 | 585 | 0a39670acee4e7517e52f2a3eee37b6c2c450636 | bigcode/the-stack | train |
f4895452f6e7e77b20d8853d | train | function | def chain_break(idx_res, Ls, length=200):
# Minkyung's code
# add big enough number to residue index to indicate chain breaks
L_prev = 0
for L_i in Ls[:-1]:
idx_res[L_prev+L_i:] += length
L_prev += L_i
return idx_res
| def chain_break(idx_res, Ls, length=200):
# Minkyung's code
# add big enough number to residue index to indicate chain breaks
| L_prev = 0
for L_i in Ls[:-1]:
idx_res[L_prev+L_i:] += length
L_prev += L_i
return idx_res
| mod_msas.append(mod_msa)
mod_mtxs.append(mod_mtx)
return mod_msas, mod_mtxs
def chain_break(idx_res, Ls, length=200):
# Minkyung's code
# add big enough number to residue index to indicate chain breaks
| 64 | 64 | 76 | 35 | 28 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | chain_break | chain_break | 347 | 354 | 347 | 349 | 0ca3d7a2155fee0dc7116cf6ecb5ea0fa4fa7e63 | bigcode/the-stack | train |
782afbb21800cbada60b02b3 | train | function | def plot_plddts(plddts, Ls=None, dpi=100, fig=True):
if fig: plt.figure(figsize=(8,5),dpi=100)
plt.title("Predicted lDDT per position")
for n,plddt in enumerate(plddts):
plt.plot(plddt,label=f"rank_{n+1}")
if Ls is not None:
L_prev = 0
for L_i in Ls[:-1]:
L = L_prev + L_i
L_prev += L_i
... | def plot_plddts(plddts, Ls=None, dpi=100, fig=True):
| if fig: plt.figure(figsize=(8,5),dpi=100)
plt.title("Predicted lDDT per position")
for n,plddt in enumerate(plddts):
plt.plot(plddt,label=f"rank_{n+1}")
if Ls is not None:
L_prev = 0
for L_i in Ls[:-1]:
L = L_prev + L_i
L_prev += L_i
plt.plot([L,L],[0,100],color="black")
plt.lege... | C','O','N','CA']
view.addStyle({'atom':BB},{'stick':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
view.zoomTo()
return view
def plot_plddts(plddts, Ls=None, dpi=100, fig=True):
| 64 | 64 | 165 | 20 | 43 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_plddts | plot_plddts | 529 | 544 | 529 | 529 | e1d0c3e5d029c2217ffb832beb73bda5effdad44 | bigcode/the-stack | train |
7a52b0c67ffd73a7265523a7 | train | function | def run_mmseqs2(x, prefix, use_env=True, use_filter=True,
use_templates=False, filter=None, use_pairing=False,
host_url="https://a3m.mmseqs.com") -> Tuple[List[str], List[str]]:
submission_endpoint = "ticket/pair" if use_pairing else "ticket/msa"
def submit(seqs, mode, N=101):
n... | def run_mmseqs2(x, prefix, use_env=True, use_filter=True,
use_templates=False, filter=None, use_pairing=False,
host_url="https://a3m.mmseqs.com") -> Tuple[List[str], List[str]]:
| submission_endpoint = "ticket/pair" if use_pairing else "ticket/msa"
def submit(seqs, mode, N=101):
n, query = N, ""
for seq in seqs:
query += f">{n}\n{seq}\n"
n += 1
res = requests.post(f'{host_url}/{submission_endpoint}', data={'q':query,'mode': mode})
try:
out = res.json()
... | ol_color_list)
alphabet_list = list(ascii_uppercase+ascii_lowercase)
aatypes = set('ACDEFGHIKLMNPQRSTVWY')
###########################################
# control gpu/cpu memory usage
###########################################
def rm(x):
'''remove data from device'''
jax.tree_util.tree_map(lambda y: y.device_buff... | 256 | 256 | 1,703 | 53 | 203 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | run_mmseqs2 | run_mmseqs2 | 71 | 251 | 71 | 73 | 4549f6a6ebee5804556f82440c0df6f890fb87e3 | bigcode/the-stack | train |
b7d87c2dee686af7c85e5baf | train | function | def plot_adjs(adjs, Ls=None, dpi=100, fig=True):
num_models = len(adjs)
if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
for n,adj in enumerate(adjs):
plt.subplot(1,num_models,n+1)
plt.title(f"rank_{n+1}")
Ln = adj.shape[0]
plt.imshow(adj,cmap="binary",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))
... | def plot_adjs(adjs, Ls=None, dpi=100, fig=True):
| num_models = len(adjs)
if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
for n,adj in enumerate(adjs):
plt.subplot(1,num_models,n+1)
plt.title(f"rank_{n+1}")
Ln = adj.shape[0]
plt.imshow(adj,cmap="binary",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))
if Ls is not None and len(Ls) > 1: plot_ticks(Ls... | ,vmax=30,extent=(0, Ln, Ln, 0))
if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
plt.colorbar()
return plt
def plot_adjs(adjs, Ls=None, dpi=100, fig=True):
| 64 | 64 | 143 | 18 | 45 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_adjs | plot_adjs | 558 | 568 | 558 | 558 | 0bb4af55765b309736d8693ed2cc4b6d40feea0e | bigcode/the-stack | train |
59f13ecef498207a424e6414 | train | function | def add_text(text, ax):
return plt.text(0.5, 1.01, text, horizontalalignment='center',
verticalalignment='bottom', transform=ax.transAxes)
| def add_text(text, ax):
| return plt.text(0.5, 1.01, text, horizontalalignment='center',
verticalalignment='bottom', transform=ax.transAxes)
| / np.diff(ax.get_xlim())
lines = mcoll.LineCollection(seg_xy[ord], colors=colors[ord], linewidths=linewidths,
path_effects=[matplotlib.patheffects.Stroke(capstyle="round")])
return ax.add_collection(lines)
def add_text(text, ax):
| 64 | 64 | 39 | 7 | 57 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | add_text | add_text | 664 | 666 | 664 | 664 | cee2f84ead62e48e024babda5c7f1720a79c453f | bigcode/the-stack | train |
1d487b264e60589f3d6a9dfe | train | function | def homooliomerize(msas, deletion_matrices, homooligomer=1):
return homooligomerize(msas, deletion_matrices, homooligomer=homooligomer)
| def homooliomerize(msas, deletion_matrices, homooligomer=1):
| return homooligomerize(msas, deletion_matrices, homooligomer=homooligomer)
| s in msa])
new_mtxs.append([[0]*L+m+[0]*R for m in mtx])
return new_msas, new_mtxs
# keeping typo for cross-compatibility
def homooliomerize(msas, deletion_matrices, homooligomer=1):
| 64 | 64 | 43 | 19 | 44 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | homooliomerize | homooliomerize | 276 | 277 | 276 | 276 | c0a1ca7c42d80091aa0d1e9c80475fec8d1ee99b | bigcode/the-stack | train |
4ab3f810812f35720ab1c383 | train | function | def homooligomerize_heterooligomer(msas, deletion_matrices, lengths, homooligomers):
'''
----- inputs -----
msas: list of msas
deletion_matrices: list of deletion matrices
lengths: list of lengths for each component in complex
homooligomers: list of number of homooligomeric copies for each component
-----... | def homooligomerize_heterooligomer(msas, deletion_matrices, lengths, homooligomers):
| '''
----- inputs -----
msas: list of msas
deletion_matrices: list of deletion matrices
lengths: list of lengths for each component in complex
homooligomers: list of number of homooligomeric copies for each component
----- outputs -----
(msas, deletion_matrices)
'''
if max(homooligomers) == 1:
re... | homooligomerize(msas, deletion_matrices, homooligomer=1):
if homooligomer == 1:
return msas, deletion_matrices
else:
new_msas = []
new_mtxs = []
for o in range(homooligomer):
for msa,mtx in zip(msas, deletion_matrices):
num_res = len(msa[0])
L = num_res * o
R = num_res * (homooligomer-(... | 240 | 240 | 803 | 25 | 215 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | homooligomerize_heterooligomer | homooligomerize_heterooligomer | 279 | 345 | 279 | 279 | c0fe741f51d6382d972750ffa434f8c134bbc8c2 | bigcode/the-stack | train |
2d4dc80ff8231c08e2117d77 | train | function | def plot_ticks(Ls):
Ln = sum(Ls)
L_prev = 0
for L_i in Ls[:-1]:
L = L_prev + L_i
L_prev += L_i
plt.plot([0,Ln],[L,L],color="black")
plt.plot([L,L],[0,Ln],color="black")
ticks = np.cumsum([0]+Ls)
ticks = (ticks[1:] + ticks[:-1])/2
plt.yticks(ticks,alphabet_list[:len(ticks)])
| def plot_ticks(Ls):
| Ln = sum(Ls)
L_prev = 0
for L_i in Ls[:-1]:
L = L_prev + L_i
L_prev += L_i
plt.plot([0,Ln],[L,L],color="black")
plt.plot([L,L],[0,Ln],color="black")
ticks = np.cumsum([0]+Ls)
ticks = (ticks[1:] + ticks[:-1])/2
plt.yticks(ticks,alphabet_list[:len(ticks)])
| 0, 0, color=c)
plt.legend(thresh, frameon=False,
loc='center', ncol=6,
handletextpad=1,
columnspacing=1,
markerscale=0.5,)
plt.axis(False)
return plt
def plot_ticks(Ls):
| 64 | 64 | 116 | 6 | 57 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_ticks | plot_ticks | 374 | 384 | 374 | 374 | 556bddfd4281e3d247b3300c64806de4f614c51b | bigcode/the-stack | train |
9131f0900c3cbbe15cd27d0b | train | function | def read_pdb_renum(pdb_filename, Ls=None):
if Ls is not None:
L_init = 0
new_chain = {}
for L,c in zip(Ls, alphabet_list):
new_chain.update({i:c for i in range(L_init,L_init+L)})
L_init += L
n,pdb_out = 1,[]
resnum_,chain_ = 1,"A"
for line in open(pdb_filename,"r"):
if line[:4] ==... | def read_pdb_renum(pdb_filename, Ls=None):
| if Ls is not None:
L_init = 0
new_chain = {}
for L,c in zip(Ls, alphabet_list):
new_chain.update({i:c for i in range(L_init,L_init+L)})
L_init += L
n,pdb_out = 1,[]
resnum_,chain_ = 1,"A"
for line in open(pdb_filename,"r"):
if line[:4] == "ATOM":
chain = line[21:22]
re... | plt.xlim(0,lines.shape[1])
plt.ylim(0,lines.shape[0])
plt.colorbar(label="Sequence identity to query")
plt.xlabel("Positions")
plt.ylabel("Sequences")
if return_plt: return plt
def read_pdb_renum(pdb_filename, Ls=None):
| 71 | 71 | 238 | 15 | 55 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | read_pdb_renum | read_pdb_renum | 467 | 486 | 467 | 467 | 78942cffee39eb656945db83cf6b4f8949ecbad9 | bigcode/the-stack | train |
91abb383d5773c11b20a7909 | train | function | def homooligomerize(msas, deletion_matrices, homooligomer=1):
if homooligomer == 1:
return msas, deletion_matrices
else:
new_msas = []
new_mtxs = []
for o in range(homooligomer):
for msa,mtx in zip(msas, deletion_matrices):
num_res = len(msa[0])
L = num_res * o
R = num_res * (homooligome... | def homooligomerize(msas, deletion_matrices, homooligomer=1):
| if homooligomer == 1:
return msas, deletion_matrices
else:
new_msas = []
new_mtxs = []
for o in range(homooligomer):
for msa,mtx in zip(msas, deletion_matrices):
num_res = len(msa[0])
L = num_res * o
R = num_res * (homooligomer-(o+1))
new_msas.append(["-"*L+s+"-"*R for s in msa])
... | return (a3m_lines, template_paths) if use_templates else a3m_lines
#########################################################################
# utils
#########################################################################
def get_hash(x):
return hashlib.sha1(x.encode()).hexdigest()
def homooligomerize(msas, dele... | 63 | 64 | 164 | 20 | 43 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | homooligomerize | homooligomerize | 260 | 273 | 260 | 260 | 53ff9bcfcf8e8497e7820fe9f88ef887475fbe97 | bigcode/the-stack | train |
1472846bc08058b392cb7e83 | train | function | def to(x,device="cpu"):
'''move data to device'''
d = jax.devices(device)[0]
return jax.tree_util.tree_map(lambda y:jax.device_put(y,d), x)
| def to(x,device="cpu"):
| '''move data to device'''
d = jax.devices(device)[0]
return jax.tree_util.tree_map(lambda y:jax.device_put(y,d), x)
| = set('ACDEFGHIKLMNPQRSTVWY')
###########################################
# control gpu/cpu memory usage
###########################################
def rm(x):
'''remove data from device'''
jax.tree_util.tree_map(lambda y: y.device_buffer.delete(), x)
def to(x,device="cpu"):
| 64 | 64 | 44 | 8 | 56 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | to | to | 55 | 58 | 55 | 55 | 555096bc4ae501603c892212a38c1a18c95be675 | bigcode/the-stack | train |
1efe2376a430e743655fa757 | train | function | def plot_plddt_legend(dpi=100):
thresh = ['plDDT:','Very low (<50)','Low (60)','OK (70)','Confident (80)','Very high (>90)']
plt.figure(figsize=(1,0.1),dpi=dpi)
########################################
for c in ["#FFFFFF","#FF0000","#FFFF00","#00FF00","#00FFFF","#0000FF"]:
plt.bar(0, 0, color=c)
plt.legen... | def plot_plddt_legend(dpi=100):
| thresh = ['plDDT:','Very low (<50)','Low (60)','OK (70)','Confident (80)','Very high (>90)']
plt.figure(figsize=(1,0.1),dpi=dpi)
########################################
for c in ["#FFFFFF","#FF0000","#FFFF00","#00FF00","#00FFFF","#0000FF"]:
plt.bar(0, 0, color=c)
plt.legend(thresh, frameon=False,
... | indicate chain breaks
L_prev = 0
for L_i in Ls[:-1]:
idx_res[L_prev+L_i:] += length
L_prev += L_i
return idx_res
##################################################
# plotting
##################################################
def plot_plddt_legend(dpi=100):
| 64 | 64 | 152 | 12 | 52 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_plddt_legend | plot_plddt_legend | 360 | 372 | 360 | 360 | 5cbf9350761fa2b80de3b058b8a228b6b9e74557 | bigcode/the-stack | train |
c56004ee928ff1170a63debb | train | function | def plot_confidence(plddt, pae=None, Ls=None, dpi=100):
use_ptm = False if pae is None else True
if use_ptm:
plt.figure(figsize=(10,3), dpi=dpi)
plt.subplot(1,2,1);
else:
plt.figure(figsize=(5,3), dpi=dpi)
plt.title('Predicted lDDT')
plt.plot(plddt)
if Ls is not None:
L_prev = 0
for L_i ... | def plot_confidence(plddt, pae=None, Ls=None, dpi=100):
| use_ptm = False if pae is None else True
if use_ptm:
plt.figure(figsize=(10,3), dpi=dpi)
plt.subplot(1,2,1);
else:
plt.figure(figsize=(5,3), dpi=dpi)
plt.title('Predicted lDDT')
plt.plot(plddt)
if Ls is not None:
L_prev = 0
for L_i in Ls[:-1]:
L = L_prev + L_i
L_prev += L_i
... | ,Ln],[L,L],color="black")
plt.plot([L,L],[0,Ln],color="black")
ticks = np.cumsum([0]+Ls)
ticks = (ticks[1:] + ticks[:-1])/2
plt.yticks(ticks,alphabet_list[:len(ticks)])
def plot_confidence(plddt, pae=None, Ls=None, dpi=100):
| 84 | 84 | 282 | 19 | 65 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_confidence | plot_confidence | 386 | 412 | 386 | 386 | 486f7e5410b20a8fb0af54f91bb5073aee8f3cad | bigcode/the-stack | train |
d555361373c15874636d2268 | train | function | def plot_msas(msa, ori_seq=None, sort_by_seqid=True, deduplicate=True, dpi=100, return_plt=True):
'''
plot the msas
'''
if ori_seq is None: ori_seq = msa[0]
seqs = ori_seq.replace("/","").split(":")
seqs_dash = ori_seq.replace(":","").split("/")
Ln = np.cumsum(np.append(0,[len(seq) for seq in seqs]))
L... | def plot_msas(msa, ori_seq=None, sort_by_seqid=True, deduplicate=True, dpi=100, return_plt=True):
| '''
plot the msas
'''
if ori_seq is None: ori_seq = msa[0]
seqs = ori_seq.replace("/","").split(":")
seqs_dash = ori_seq.replace(":","").split("/")
Ln = np.cumsum(np.append(0,[len(seq) for seq in seqs]))
Ln_dash = np.cumsum(np.append(0,[len(seq) for seq in seqs_dash]))
Nn,lines = [],[]
#for msa in ... | ]:
L = L_prev + L_i
L_prev += L_i
plt.plot([L,L],[0,100],color="black")
plt.ylim(0,100)
plt.ylabel('plDDT')
plt.xlabel('position')
if use_ptm:
plt.subplot(1,2,2);plt.title('Predicted Aligned Error')
Ln = pae.shape[0]
plt.imshow(pae,cmap="bwr",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))
... | 194 | 194 | 648 | 30 | 163 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_msas | plot_msas | 414 | 465 | 414 | 414 | 2fa62fbc4e4b64cd94742379a6f023d93cb8d307 | bigcode/the-stack | train |
812cdb1131e975e0c7ea5990 | train | function | def plot_protein(protein=None, pos=None, plddt=None, Ls=None, dpi=100, best_view=True, line_w=2.0):
if protein is not None:
pos = np.asarray(protein.atom_positions[:,1,:])
plddt = np.asarray(protein.b_factors[:,0])
# get best view
if best_view:
if plddt is not None:
weights = plddt/100
... | def plot_protein(protein=None, pos=None, plddt=None, Ls=None, dpi=100, best_view=True, line_w=2.0):
| if protein is not None:
pos = np.asarray(protein.atom_positions[:,1,:])
plddt = np.asarray(protein.b_factors[:,0])
# get best view
if best_view:
if plddt is not None:
weights = plddt/100
pos = pos - (pos * weights[:,None]).sum(0,keepdims=True) / weights.sum()
pos = pos @ kabsch(pos,... | _max)
ax.set_ylim(xy_min,xy_max)
ax.set_aspect('equal')
# determine linewidths
width = fig.bbox_inches.width * ax.get_position().width
linewidths = line_w * 72 * width / np.diff(ax.get_xlim())
lines = mcoll.LineCollection(seg_xy[ord], colors=colors[ord], linewidths=linewidths,
... | 186 | 186 | 622 | 36 | 150 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_protein | plot_protein | 668 | 720 | 668 | 669 | be94c06caff7f5010395302c7157a73ec727e5eb | bigcode/the-stack | train |
a1a2ac9c488b8fe3084e8c71 | train | function | def plot_pseudo_3D(xyz, c=None, ax=None, chainbreak=5,
cmap="gist_rainbow", line_w=2.0,
cmin=None, cmax=None, zmin=None, zmax=None):
def rescale(a,amin=None,amax=None):
a = np.copy(a)
if amin is None: amin = a.min()
if amax is None: amax = a.max()
a[a < amin] = a... | def plot_pseudo_3D(xyz, c=None, ax=None, chainbreak=5,
cmap="gist_rainbow", line_w=2.0,
cmin=None, cmax=None, zmin=None, zmax=None):
| def rescale(a,amin=None,amax=None):
a = np.copy(a)
if amin is None: amin = a.min()
if amax is None: amax = a.max()
a[a < amin] = amin
a[a > amax] = amax
return (a - amin)/(amax - amin)
# make segments
xyz = np.asarray(xyz)
seg = np.concatenate([xyz[:-1,None,:],xyz[1:,None,:]],axis=-2)
... | plt.colorbar()
return plt
##########################################################################
##########################################################################
def kabsch(a, b, weights=None, return_v=False):
a = np.asarray(a)
b = np.asarray(b)
if weights is None: weights = np.ones(len(b))
e... | 192 | 192 | 643 | 53 | 138 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_pseudo_3D | plot_pseudo_3D | 596 | 662 | 596 | 599 | d38626c1c814a4be385bc10684ad0cf909998c8d | bigcode/the-stack | train |
e7466a506dbcb6a24d9e0034 | train | function | def clear_mem(device="gpu"):
'''remove all data from device'''
backend = jax.lib.xla_bridge.get_backend(device)
for buf in backend.live_buffers(): buf.delete()
| def clear_mem(device="gpu"):
| '''remove all data from device'''
backend = jax.lib.xla_bridge.get_backend(device)
for buf in backend.live_buffers(): buf.delete()
| _util.tree_map(lambda y: y.device_buffer.delete(), x)
def to(x,device="cpu"):
'''move data to device'''
d = jax.devices(device)[0]
return jax.tree_util.tree_map(lambda y:jax.device_put(y,d), x)
def clear_mem(device="gpu"):
| 64 | 64 | 39 | 7 | 57 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | clear_mem | clear_mem | 60 | 63 | 60 | 60 | b7f3cb0fd8dda89df5f8c7bade38cab0b4259722 | bigcode/the-stack | train |
af0bf691e7f0386cdf8d8bec | train | function | def get_hash(x):
return hashlib.sha1(x.encode()).hexdigest()
| def get_hash(x):
| return hashlib.sha1(x.encode()).hexdigest()
| print(f"{n-N}\tno_templates_found")
else:
template_paths_.append(template_paths[n])
template_paths = template_paths_
return (a3m_lines, template_paths) if use_templates else a3m_lines
#########################################################################
# utils
######################... | 64 | 64 | 16 | 5 | 59 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | get_hash | get_hash | 257 | 258 | 257 | 257 | 37404427db53054071c1cd5a4906ba3de208fdbb | bigcode/the-stack | train |
1b4983b7db47468d8cb45366 | train | function | def show_pdb(pred_output_path, show_sidechains=False, show_mainchains=False,
color="lDDT", chains=None, Ls=None, vmin=50, vmax=90,
color_HP=False, size=(800,480)):
if chains is None:
chains = 1 if Ls is None else len(Ls)
view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', wi... | def show_pdb(pred_output_path, show_sidechains=False, show_mainchains=False,
color="lDDT", chains=None, Ls=None, vmin=50, vmax=90,
color_HP=False, size=(800,480)):
| if chains is None:
chains = 1 if Ls is None else len(Ls)
view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', width=size[0], height=size[1])
view.addModel(read_pdb_renum(pred_output_path, Ls),'pdb')
if color == "lDDT":
view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min... | for line in open(pdb_filename,"r"):
if line[:4] == "ATOM":
chain = line[21:22]
resnum = int(line[22:22+5])
if resnum != resnum_ or chain != chain_:
resnum_,chain_ = resnum,chain
n += 1
if Ls is None: pdb_out.append("%s%4i%s" % (line[:22],n,line[26:]))
else: pdb_out.app... | 197 | 197 | 657 | 53 | 144 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | show_pdb | show_pdb | 488 | 527 | 488 | 491 | aa11e93a8b28c53d7e69b1b41639672163f58137 | bigcode/the-stack | train |
c4fba621a85cad5af2cc0e3c | train | function | def plot_dists(dists, Ls=None, dpi=100, fig=True):
num_models = len(dists)
if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
for n,dist in enumerate(dists):
plt.subplot(1,num_models,n+1)
plt.title(f"rank_{n+1}")
Ln = dist.shape[0]
plt.imshow(dist,extent=(0, Ln, Ln, 0))
if Ls is not None an... | def plot_dists(dists, Ls=None, dpi=100, fig=True):
| num_models = len(dists)
if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
for n,dist in enumerate(dists):
plt.subplot(1,num_models,n+1)
plt.title(f"rank_{n+1}")
Ln = dist.shape[0]
plt.imshow(dist,extent=(0, Ln, Ln, 0))
if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
plt.colorbar()
... | ,vmax=1,extent=(0, Ln, Ln, 0))
if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
plt.colorbar()
return plt
def plot_dists(dists, Ls=None, dpi=100, fig=True):
| 64 | 64 | 130 | 18 | 45 | EnzoAndree/ColabFold | colabfold/colabfold.py | Python | plot_dists | plot_dists | 570 | 580 | 570 | 570 | e08f76c0ec9bea5435d095ef069177bf10c8af7e | bigcode/the-stack | train |
a0d8a8b2446e2ffeb00c793e | train | class | class JsonCustomEncoder(json.JSONEncoder):
"""Support for data types that JSON default encoder
does not do.
This includes:
* Numpy array or number
* Complex number
* Set
* Bytes
* astropy.UnitBase
* astropy.Quantity
Examples
--------
>>> import ... | class JsonCustomEncoder(json.JSONEncoder):
| """Support for data types that JSON default encoder
does not do.
This includes:
* Numpy array or number
* Complex number
* Set
* Bytes
* astropy.UnitBase
* astropy.Quantity
Examples
--------
>>> import json
>>> import numpy as np
>>> fro... | onerror=onerror,
followlinks=followlinks):
# These lists must be updated in-place so os.walk will skip
# hidden directories
dirs[:] = [d for d in dirs if not is_path_hidden(d)]
files[:] = [f for f in files if not is_path_hidden(f)]
yield root, dirs, files
class JsonC... | 83 | 83 | 278 | 8 | 74 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | JsonCustomEncoder | JsonCustomEncoder | 363 | 405 | 363 | 363 | e3fd83f715a98ffe67e8aa39e0f206c49257c6d1 | bigcode/the-stack | train |
ea15182f3f1edc9d8941271e | train | function | def did_you_mean(s, candidates, n=3, cutoff=0.8, fix=None):
"""
When a string isn't found in a set of candidates, we can be nice
to provide a list of alternatives in the exception. This
convenience function helps to format that part of the exception.
Parameters
----------
s : str
cand... | def did_you_mean(s, candidates, n=3, cutoff=0.8, fix=None):
| """
When a string isn't found in a set of candidates, we can be nice
to provide a list of alternatives in the exception. This
convenience function helps to format that part of the exception.
Parameters
----------
s : str
candidates : sequence of str or dict of str keys
n : int
... | ):
return list(obj)
elif isinstance(obj, bytes): # pragma: py3
return obj.decode()
elif isinstance(obj, (u.UnitBase, u.FunctionUnitBase)):
if obj == u.dimensionless_unscaled:
obj = 'dimensionless_unit'
else:
return obj.to_s... | 164 | 164 | 548 | 21 | 143 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | did_you_mean | did_you_mean | 419 | 494 | 419 | 419 | 275d1531a2de7f242d9b11e3d372996901312e5c | bigcode/the-stack | train |
fc6e0f8ddd7bdd2991b1200b | train | function | def indent(s, shift=1, width=4):
"""Indent a block of text. The indentation is applied to each line."""
indented = '\n'.join(' ' * (width * shift) + l if l else ''
for l in s.splitlines())
if s[-1] == '\n':
indented += '\n'
return indented
| def indent(s, shift=1, width=4):
| """Indent a block of text. The indentation is applied to each line."""
indented = '\n'.join(' ' * (width * shift) + l if l else ''
for l in s.splitlines())
if s[-1] == '\n':
indented += '\n'
return indented
| 'IncompatibleShapeError',
'dtype_bytes_or_chars']
def isiterable(obj):
"""Returns `True` if the given object is iterable."""
try:
iter(obj)
return True
except TypeError:
return False
def indent(s, shift=1, width=4):
| 64 | 64 | 81 | 12 | 51 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | indent | indent | 49 | 57 | 49 | 49 | 64c6d12fe795dc404e553e110a786d0dedb16b4d | bigcode/the-stack | train |
a96366ee5836bcbb6e205491 | train | function | def is_path_hidden(filepath):
"""
Determines if a given file or directory is hidden.
Parameters
----------
filepath : str
The path to a file or directory
Returns
-------
hidden : bool
Returns `True` if the file is hidden
"""
name = os.path.basename(os.path.abspa... | def is_path_hidden(filepath):
| """
Determines if a given file or directory is hidden.
Parameters
----------
filepath : str
The path to a file or directory
Returns
-------
hidden : bool
Returns `True` if the file is hidden
"""
name = os.path.basename(os.path.abspath(filepath))
if isinstanc... | :
attrs = ctypes.windll.kernel32.GetFileAttributesW(filepath)
result = bool(attrs & 2) and attrs != -1
except AttributeError:
result = False
return result
else:
def _has_hidden_attribute(filepath):
return False
def is_path_hidden(filepath):
| 64 | 64 | 113 | 6 | 57 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | is_path_hidden | is_path_hidden | 319 | 338 | 319 | 319 | a17110d516ecd8056fc167d4d5d072fecaf733a8 | bigcode/the-stack | train |
5e290b244ffd762434890c80 | train | function | @contextlib.contextmanager
def silence():
"""A context manager that silences sys.stdout and sys.stderr."""
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
yield
sys.stdout = old_stdout
sys.stderr = old_stderr
| @contextlib.contextmanager
def silence():
| """A context manager that silences sys.stdout and sys.stderr."""
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
yield
sys.stdout = old_stdout
sys.stderr = old_stderr
| else ''
for l in s.splitlines())
if s[-1] == '\n':
indented += '\n'
return indented
class _DummyFile:
"""A noop writeable object."""
def write(self, s):
pass
@contextlib.contextmanager
def silence():
| 64 | 64 | 72 | 9 | 54 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | silence | silence | 67 | 77 | 67 | 68 | ca3a513934d964baafb39c128a6a9393660a43ae | bigcode/the-stack | train |
d1fcb7cebd1246a45f5d6e93 | train | function | @contextmanager
def set_locale(name):
"""
Context manager to temporarily set the locale to ``name``.
An example is setting locale to "C" so that the C strtod()
function will use "." as the decimal point to enable consistent
numerical string parsing.
Note that one cannot nest multiple set_local... | @contextmanager
def set_locale(name):
| """
Context manager to temporarily set the locale to ``name``.
An example is setting locale to "C" so that the C strtod()
function will use "." as the decimal point to enable consistent
numerical string parsing.
Note that one cannot nest multiple set_locale() context manager
statements as ... | descriptors.items():
instances.sort()
instances = OrderedDict((key, value) for value, key in instances)
setattr(cls, descriptor_cls._class_attribute_, instances)
super().__init__(cls_name, bases, members)
LOCALE_LOCK = threading.Lock()
@contextmanager
def set_locale(name)... | 64 | 64 | 216 | 9 | 55 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | set_locale | set_locale | 829 | 860 | 829 | 830 | 9a20f25b073ed8e2620f59938631cc57b6c2cac9 | bigcode/the-stack | train |
d767b1be2d1a0aa0e732d1c8 | train | class | class _DummyFile:
"""A noop writeable object."""
def write(self, s):
pass
| class _DummyFile:
| """A noop writeable object."""
def write(self, s):
pass
| indentation is applied to each line."""
indented = '\n'.join(' ' * (width * shift) + l if l else ''
for l in s.splitlines())
if s[-1] == '\n':
indented += '\n'
return indented
class _DummyFile:
| 64 | 64 | 23 | 5 | 58 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | _DummyFile | _DummyFile | 60 | 64 | 60 | 60 | 09a27942df729bea59fcc7779b1ed269103a75b1 | bigcode/the-stack | train |
59d2a21cf6dfcf864c113e98 | train | class | class IncompatibleShapeError(ValueError):
def __init__(self, shape_a, shape_a_idx, shape_b, shape_b_idx):
super().__init__(shape_a, shape_a_idx, shape_b, shape_b_idx)
| class IncompatibleShapeError(ValueError):
| def __init__(self, shape_a, shape_a_idx, shape_b, shape_b_idx):
super().__init__(shape_a, shape_a_idx, shape_b, shape_b_idx)
| instance formed from the elements at the given indices.
Parameters are as for :meth:`~numpy.ndarray.take`, except that,
obviously, no output array can be given.
"""
return self._apply('take', indices, axis=axis, mode=mode)
class IncompatibleShapeError(ValueError):
| 64 | 64 | 48 | 8 | 56 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | IncompatibleShapeError | IncompatibleShapeError | 1,057 | 1,059 | 1,057 | 1,057 | be18ad1d28d245dfb41d00f1720dc6c85caf7c96 | bigcode/the-stack | train |
a3b214799f514cf73f60e93c | train | function | def find_api_page(obj, version=None, openinbrowser=True, timeout=None):
"""
Determines the URL of the API page for the specified object, and
optionally open that page in a web browser.
.. note::
You must be connected to the internet for this to function even if
``openinbrowser`` is `Fal... | def find_api_page(obj, version=None, openinbrowser=True, timeout=None):
| """
Determines the URL of the API page for the specified object, and
optionally open that page in a web browser.
.. note::
You must be connected to the internet for this to function even if
``openinbrowser`` is `False`, unless you provide a local version of
the documentation to ... | the RNG state back to whatever it was before.
This is primarily intended for use in the astropy testing suit, but it
may be useful in ensuring reproducibility of Monte Carlo simulations in a
science context.
Parameters
----------
seed : int
The value to use to seed the numpy RNG
... | 256 | 256 | 900 | 17 | 239 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | find_api_page | find_api_page | 161 | 280 | 161 | 161 | 5ea7a8688e26a48ec1ff9d66f0a5f2d49ea117f1 | bigcode/the-stack | train |
a977ece0dd6fe264647bbd3e | train | class | class OrderedDescriptorContainer(type):
"""
Classes should use this metaclass if they wish to use `OrderedDescriptor`
attributes, which are class attributes that "remember" the order in which
they were defined in the class body.
Every subclass of `OrderedDescriptor` has an attribute called
``_c... | class OrderedDescriptorContainer(type):
| """
Classes should use this metaclass if they wish to use `OrderedDescriptor`
attributes, which are class attributes that "remember" the order in which
they were defined in the class body.
Every subclass of `OrderedDescriptor` has an attribute called
``_class_attribute_``. For example, if we h... | _name_attribute_ = None
"""
Subclasses may optionally define this attribute to specify the name of an
attribute on instances of the class that should be filled with the
instance's attribute name at class creation time.
"""
def __init__(self, *args, **kwargs):
# The _nextid attribute is... | 256 | 256 | 1,858 | 6 | 249 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | OrderedDescriptorContainer | OrderedDescriptorContainer | 627 | 823 | 627 | 627 | fb945be38627d9dad27eb0cc0f4afad7a33607b3 | bigcode/the-stack | train |
56db50989e941b8f4bebf30b | train | function | def signal_number_to_name(signum):
"""
Given an OS signal number, returns a signal name. If the signal
number is unknown, returns ``'UNKNOWN'``.
"""
# Since these numbers and names are platform specific, we use the
# builtin signal module and build a reverse mapping.
signal_to_name_map = d... | def signal_number_to_name(signum):
| """
Given an OS signal number, returns a signal name. If the signal
number is unknown, returns ``'UNKNOWN'``.
"""
# Since these numbers and names are platform specific, we use the
# builtin signal module and build a reverse mapping.
signal_to_name_map = dict((k, v) for v, k in signal.__dic... | resurl = baseurl + loc
break
if resurl is None:
raise ValueError('Could not find the docs for the object {obj}'.format(obj=obj))
elif openinbrowser:
webbrowser.open(resurl)
return resurl
def signal_number_to_name(signum):
| 64 | 64 | 110 | 8 | 55 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | signal_number_to_name | signal_number_to_name | 283 | 294 | 283 | 283 | 6ebb8903148154b1fc9b7562c0d09805fde5816f | bigcode/the-stack | train |
fa5c67ce9d3693a5a8d6686a | train | function | def check_broadcast(*shapes):
"""
Determines whether two or more Numpy arrays can be broadcast with each
other based on their shape tuple alone.
Parameters
----------
*shapes : tuple
All shapes to include in the comparison. If only one shape is given it
is passed through unmodi... | def check_broadcast(*shapes):
| """
Determines whether two or more Numpy arrays can be broadcast with each
other based on their shape tuple alone.
Parameters
----------
*shapes : tuple
All shapes to include in the comparison. If only one shape is given it
is passed through unmodified. If no shapes are given ... | that,
obviously, no output array can be given.
"""
return self._apply('take', indices, axis=axis, mode=mode)
class IncompatibleShapeError(ValueError):
def __init__(self, shape_a, shape_a_idx, shape_b, shape_b_idx):
super().__init__(shape_a, shape_a_idx, shape_b, shape_b_idx)
def c... | 88 | 88 | 294 | 8 | 80 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | check_broadcast | check_broadcast | 1,062 | 1,107 | 1,062 | 1,062 | 4349acda952169e2501f34e16430aab7d5ddb4ac | bigcode/the-stack | train |
779d6f360f79df15ef436dca | train | class | class OrderedDescriptor(metaclass=abc.ABCMeta):
"""
Base class for descriptors whose order in the class body should be
preserved. Intended for use in concert with the
`OrderedDescriptorContainer` metaclass.
Subclasses of `OrderedDescriptor` must define a value for a class attribute
called ``_c... | class OrderedDescriptor(metaclass=abc.ABCMeta):
| """
Base class for descriptors whose order in the class body should be
preserved. Intended for use in concert with the
`OrderedDescriptorContainer` metaclass.
Subclasses of `OrderedDescriptor` must define a value for a class attribute
called ``_class_attribute_``. This is the name of a class ... | =InheritDocstrings):
... def wiggle(self):
... "Wiggle the thingamajig"
... pass
>>> class B(A):
... def wiggle(self):
... pass
>>> B.wiggle.__doc__
u'Wiggle the thingamajig'
"""
def __init__(cls, name, bases, dct):... | 231 | 231 | 770 | 12 | 219 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | OrderedDescriptor | OrderedDescriptor | 543 | 624 | 543 | 543 | 4edbcc71d829bb00699d40fff947c2cb62d30d9d | bigcode/the-stack | train |
ce5ef04bf326866d2cb1967d | train | class | class NumpyRNGContext:
"""
A context manager (for use with the ``with`` statement) that will seed the
numpy random number generator (RNG) to a specific value, and then restore
the RNG state back to whatever it was before.
This is primarily intended for use in the astropy testing suit, but it
ma... | class NumpyRNGContext:
| """
A context manager (for use with the ``with`` statement) that will seed the
numpy random number generator (RNG) to a specific value, and then restore
the RNG state back to whatever it was before.
This is primarily intended for use in the astropy testing suit, but it
may be useful in ensuring... | (sys.exc_info()[2], limit=1)
if len(tb) > 0:
filename, lineno, func, text = tb[0]
else:
filename = lineno = func = text = '<unknown>'
return msg.format(*args, filename=filename, lineno=lineno, func=func,
text=text, **kwargs)
class NumpyRNGContext:
| 85 | 85 | 285 | 7 | 78 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | NumpyRNGContext | NumpyRNGContext | 114 | 158 | 114 | 114 | fdd67a295bbb00a001446a94f84b4cfadb25615f | bigcode/the-stack | train |
830072b7a5a42fa93fa353a6 | train | function | def dtype_bytes_or_chars(dtype):
"""
Parse the number out of a dtype.str value like '<U5' or '<f8'.
See #5819 for discussion on the need for this function for getting
the number of characters corresponding to a string dtype.
Parameters
----------
dtype : numpy dtype object
Input dt... | def dtype_bytes_or_chars(dtype):
| """
Parse the number out of a dtype.str value like '<U5' or '<f8'.
See #5819 for discussion on the need for this function for getting
the number of characters corresponding to a string dtype.
Parameters
----------
dtype : numpy dtype object
Input dtype
Returns
-------
... | max_dim = dim
max_dim_idx = idx
elif dim != max_dim:
raise IncompatibleShapeError(
shapes[max_dim_idx], max_dim_idx, shapes[idx], idx)
full_shape.append(max_dim)
return tuple(full_shape[::-1])
def dtype_bytes_or_chars(dtype):
| 64 | 64 | 135 | 7 | 57 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | dtype_bytes_or_chars | dtype_bytes_or_chars | 1,110 | 1,129 | 1,110 | 1,110 | f2216161c79d80c275708b4f36975c32390b0261 | bigcode/the-stack | train |
c9a3c011a850a554fbd14297 | train | function | def format_exception(msg, *args, **kwargs):
"""
Given an exception message string, uses new-style formatting arguments
``{filename}``, ``{lineno}``, ``{func}`` and/or ``{text}`` to fill in
information about the exception that occurred. For example:
try:
1/0
except:
... | def format_exception(msg, *args, **kwargs):
| """
Given an exception message string, uses new-style formatting arguments
``{filename}``, ``{lineno}``, ``{func}`` and/or ``{text}`` to fill in
information about the exception that occurred. For example:
try:
1/0
except:
raise ZeroDivisionError(
... | , s):
pass
@contextlib.contextmanager
def silence():
"""A context manager that silences sys.stdout and sys.stderr."""
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
yield
sys.stdout = old_stdout
sys.stderr = old_stderr
def f... | 89 | 89 | 298 | 11 | 77 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | format_exception | format_exception | 80 | 111 | 80 | 80 | 83b360444374bfab2b1d1fc7f8b7b078a93884f2 | bigcode/the-stack | train |
e07f0d85851189c0593131d7 | train | class | class ShapedLikeNDArray(metaclass=abc.ABCMeta):
"""Mixin class to provide shape-changing methods.
The class proper is assumed to have some underlying data, which are arrays
or array-like structures. It must define a ``shape`` property, which gives
the shape of those data, as well as an ``_apply`` metho... | class ShapedLikeNDArray(metaclass=abc.ABCMeta):
| """Mixin class to provide shape-changing methods.
The class proper is assumed to have some underlying data, which are arrays
or array-like structures. It must define a ``shape`` property, which gives
the shape of those data, as well as an ``_apply`` method that creates a new
instance in which a `~n... | ._class_attribute_, instances)
super().__init__(cls_name, bases, members)
LOCALE_LOCK = threading.Lock()
@contextmanager
def set_locale(name):
"""
Context manager to temporarily set the locale to ``name``.
An example is setting locale to "C" so that the C strtod()
function will use "." as ... | 256 | 256 | 1,632 | 15 | 241 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | ShapedLikeNDArray | ShapedLikeNDArray | 863 | 1,054 | 863 | 863 | ff92d2e5f40bfdbac6841192bcc786607b1cb437 | bigcode/the-stack | train |
6d4583a954e3a0351d0cada7 | train | function | def strip_accents(s):
"""
Remove accents from a Unicode string.
This helps with matching "ångström" to "angstrom", for example.
"""
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
| def strip_accents(s):
| """
Remove accents from a Unicode string.
This helps with matching "ångström" to "angstrom", for example.
"""
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
|
return obj.decode()
elif isinstance(obj, (u.UnitBase, u.FunctionUnitBase)):
if obj == u.dimensionless_unscaled:
obj = 'dimensionless_unit'
else:
return obj.to_string()
return json.JSONEncoder.default(self, obj)
def strip_accents(s):
| 64 | 64 | 66 | 6 | 58 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | strip_accents | strip_accents | 408 | 416 | 408 | 408 | a2413a9a448f976d3931104085dbf815eefe5bf8 | bigcode/the-stack | train |
c64a346266965a27d5fd61b4 | train | class | class InheritDocstrings(type):
"""
This metaclass makes methods of a class automatically have their
docstrings filled in from the methods they override in the base
class.
If the class uses multiple inheritance, the docstring will be
chosen from the first class in the bases list, in the same way... | class InheritDocstrings(type):
| """
This metaclass makes methods of a class automatically have their
docstrings filled in from the methods they override in the base
class.
If the class uses multiple inheritance, the docstring will be
chosen from the first class in the bases list, in the same way as
methods are normally re... | None:
mapped_matches = []
for match in matches:
mapped_matches.extend(fix(match))
matches = mapped_matches
matches = list(set(matches))
matches = sorted(matches)
if len(matches) == 1:
matches = matches[0]
else:
... | 103 | 104 | 349 | 7 | 96 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | InheritDocstrings | InheritDocstrings | 497 | 540 | 497 | 497 | fc670d9b7c5324019ad9aeb48ed3549f853573cc | bigcode/the-stack | train |
2baeec80a232a8f0c053a568 | train | function | def isiterable(obj):
"""Returns `True` if the given object is iterable."""
try:
iter(obj)
return True
except TypeError:
return False
| def isiterable(obj):
| """Returns `True` if the given object is iterable."""
try:
iter(obj)
return True
except TypeError:
return False
| _skip_hidden',
'JsonCustomEncoder', 'indent', 'InheritDocstrings',
'OrderedDescriptor', 'OrderedDescriptorContainer', 'set_locale',
'ShapedLikeNDArray', 'check_broadcast', 'IncompatibleShapeError',
'dtype_bytes_or_chars']
def isiterable(obj):
| 64 | 64 | 39 | 6 | 58 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | isiterable | isiterable | 39 | 46 | 39 | 39 | 39e191e07c52fee99d8ace9f2b55443f802ad0fb | bigcode/the-stack | train |
8ad125630a92e3d3d07973e1 | train | function | def walk_skip_hidden(top, onerror=None, followlinks=False):
"""
A wrapper for `os.walk` that skips hidden files and directories.
This function does not have the parameter ``topdown`` from
`os.walk`: the directories must always be recursed top-down when
using this function.
See also
-------... | def walk_skip_hidden(top, onerror=None, followlinks=False):
| """
A wrapper for `os.walk` that skips hidden files and directories.
This function does not have the parameter ``topdown`` from
`os.walk`: the directories must always be recursed top-down when
using this function.
See also
--------
os.walk : For a description of the parameters
"""
... | = os.path.basename(os.path.abspath(filepath))
if isinstance(name, bytes):
is_dotted = name.startswith(b'.')
else:
is_dotted = name.startswith('.')
return is_dotted or _has_hidden_attribute(filepath)
def walk_skip_hidden(top, onerror=None, followlinks=False):
| 64 | 64 | 179 | 14 | 50 | temelkirci/Motion_Editor | venv/Lib/site-packages/astropy/utils/misc.py | Python | walk_skip_hidden | walk_skip_hidden | 341 | 360 | 341 | 341 | 122346fefa2b0423cc7baec4e309051ca592cc76 | bigcode/the-stack | train |
b135198ec7429c6e017e05c7 | train | class | class AzureRMPropertyInfo(AzureRMModuleBase):
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(
type='str',
required=true
),
service_name=dict(
type='str',
required=true
... | class AzureRMPropertyInfo(AzureRMModuleBase):
| def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(
type='str',
required=true
),
service_name=dict(
type='str',
required=true
),
prop_id=dict(
... | Property
'''
RETURN = '''
property:
description: >-
A list of dict results where the key is the name of the Property and the
values are the facts for that Property.
returned: always
type: complex
contains:
property_name:
description: The key is the name of the server that the va... | 256 | 256 | 864 | 11 | 244 | audevbot/autorest.devops.debug | generated/ansible-collection/apimanagementproperty_info.py | Python | AzureRMPropertyInfo | AzureRMPropertyInfo | 137 | 262 | 137 | 137 | 41ac4ace7ff34ae9a7e18cca272f66479d4e1f9e | bigcode/the-stack | train |
8f2712a31025112777429938 | train | function | def main():
AzureRMPropertyInfo()
| def main():
| AzureRMPropertyInfo()
| ['temp_item'] = json.loads(response.text)
# self.log('Response : {0}'.format(response))
except CloudError as e:
self.log('Could not get info for @(Model.ModuleOperationNameUpper).')
return results
def format_item(item):
return item
def main():
| 64 | 64 | 9 | 3 | 60 | audevbot/autorest.devops.debug | generated/ansible-collection/apimanagementproperty_info.py | Python | main | main | 265 | 266 | 265 | 265 | 677cd9fd36902bb5a4a43d5f0178ab35fa9ee620 | bigcode/the-stack | train |
bdebfa2dbb37e9a04b2396ac | train | function | def main():
print('main()')
qmlRegisterType(MatplotlibController, "Matplot", 1, 0, "Matplot")
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
main_controller = MainController(app)
context = engine.rootContext()
context.setContextProperty("main", main_controller)
s... | def main():
| print('main()')
qmlRegisterType(MatplotlibController, "Matplot", 1, 0, "Matplot")
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
main_controller = MainController(app)
context = engine.rootContext()
context.setContextProperty("main", main_controller)
script_direct... | import os
import sys
from PySide2.QtQml import QQmlApplicationEngine, qmlRegisterType
from PySide2.QtWidgets import QApplication
from controllers.main import MainController
from controllers.matplot import MatplotlibController
def main():
| 52 | 64 | 114 | 3 | 48 | maldata/matplotlib_qtquick_playground | qml-screens-plot/__main__.py | Python | main | main | 11 | 26 | 11 | 11 | f9552fc755c970660724bc0a47c16d079d8ff7ef | bigcode/the-stack | train |
d12ea5bb399b2a27905582e7 | train | function | def averaging(h, w):
window = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
sum1 = 0
for i in range(3):
for j in range(3):
sum1 = sum1 + (in_img[h - 1 + i][w - 1 + j] * window[i][j])
out_img[h][w] = sum1 // 9
| def averaging(h, w):
| window = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
sum1 = 0
for i in range(3):
for j in range(3):
sum1 = sum1 + (in_img[h - 1 + i][w - 1 + j] * window[i][j])
out_img[h][w] = sum1 // 9
| and width of the image
height = in_img.shape[0]
width = in_img.shape[1]
#Initializing the output image
out_img = np.zeros(shape = (height, width), dtype = np.uint8)
#Function for applying the averaging filter on the image
def averaging(h, w):
| 64 | 64 | 105 | 7 | 56 | dhavalsharma97/Computer-Vision | Assignment 4/Question2B.py | Python | averaging | averaging | 33 | 42 | 33 | 34 | a5c972ac7904f602681f2daa4ac4a0372e2992e2 | bigcode/the-stack | train |
dd98e26193b831d8aea0a9b7 | train | class | class ImportExternalReferenceConnector:
def __init__(self):
# Instantiate the connector helper from config
config_file_path = os.path.dirname(os.path.abspath(__file__)) + "/config.yml"
config = (
yaml.load(open(config_file_path), Loader=yaml.FullLoader)
if os.path.isf... | class ImportExternalReferenceConnector:
| def __init__(self):
# Instantiate the connector helper from config
config_file_path = os.path.dirname(os.path.abspath(__file__)) + "/config.yml"
config = (
yaml.load(open(config_file_path), Loader=yaml.FullLoader)
if os.path.isfile(config_file_path)
else {... | import os
import ssl
import urllib.request
import certifi
import html2text
import pdfkit
import yaml
from pdfminer.converter import HTMLConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager
from pdfminer.pdfpage import PDFPage
from pycti import OpenCTIConn... | 86 | 256 | 1,309 | 6 | 79 | opencti-platform/connectors | internal-enrichment/import-external-reference/src/import-external-reference.py | Python | ImportExternalReferenceConnector | ImportExternalReferenceConnector | 16 | 186 | 16 | 16 | 16dbe61d7699ad6de8a959f5a3b9963e529e7f83 | bigcode/the-stack | train |
79a796bb9d7eda771f7ccc53 | train | class | class SelectElement(WebElement):
'''select元素
'''
@property
def options(self):
'''返回所有选项列表
'''
option_list = []
for it in self.get_elements('/option'):
option_list.append(it.inner_text.strip())
return option_list
@property
def selection(self):... | class SelectElement(WebElement):
| '''select元素
'''
@property
def options(self):
'''返回所有选项列表
'''
option_list = []
for it in self.get_elements('/option'):
option_list.append(it.inner_text.strip())
return option_list
@property
def selection(self):
'''当前选择项
'''
... | 的value
:type val: string
'''
self._webdriver.set_property(self._locators, 'value', str(val))
self._webdriver.fire_event(self._locators, 'input')
self._webdriver.fire_event(self._locators, 'change')
class SelectElement(WebElement):
| 64 | 64 | 200 | 6 | 58 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | SelectElement | SelectElement | 1,299 | 1,330 | 1,299 | 1,299 | bc494d3841e8b2c618c77460ebac8310e360b5e5 | bigcode/the-stack | train |
8bc72e61454f2c5e108c56a6 | train | class | class FrameElement(WebElement):
'''frame/iframe元素
'''
def __init__(self, root, locator):
loc = XPath(locator).break_frames()[-1]
if not ('/iframe' in loc or '/frame' in loc):
raise ValueError("Not a Frame nor IFrame: '%s'" % locator)
super(FrameElement, self).__init__(roo... | class FrameElement(WebElement):
| '''frame/iframe元素
'''
def __init__(self, root, locator):
loc = XPath(locator).break_frames()[-1]
if not ('/iframe' in loc or '/frame' in loc):
raise ValueError("Not a Frame nor IFrame: '%s'" % locator)
super(FrameElement, self).__init__(root, locator)
self._frame_... | result = self._webdriver.read_console_log(self._locator)
if result: return result
time.sleep(0.1)
else:
raise TimeoutError('Read console log timeout')
def screenshot(self):
'''获取page页面截图
'''
self._webview.screenshot()
class FrameElemen... | 69 | 69 | 232 | 6 | 63 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | FrameElement | FrameElement | 1,249 | 1,276 | 1,249 | 1,249 | c1b50f74efeda49d35d7e3521f6d301f9f14a925 | bigcode/the-stack | train |
a503d3e3dbfdb2c0e272f9e8 | train | function | def ui_list(control_cls):
'''列表类型
'''
return type('%sList' % control_cls.__name__, (UIListBase,), {'ui_control_type': control_cls})
| def ui_list(control_cls):
| '''列表类型
'''
return type('%sList' % control_cls.__name__, (UIListBase,), {'ui_control_type': control_cls})
| _name)
if index: value = value.__getitem__(index)
if value != condition[key]:
equal_flag = False
break
if equal_flag: return elem
raise RuntimeError('未找到满足条件:%s 的子控件' % condition)
def ui_list(control_cls):
| 64 | 64 | 39 | 6 | 58 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | ui_list | ui_list | 1,408 | 1,411 | 1,408 | 1,408 | 088a12bcdd5b22ba3d7b5846d5a23ee3573c1ed8 | bigcode/the-stack | train |
84b696895b4ff4fc9be5de32 | train | class | class WebElement(ControlContainer, IWebElement):
'''IWebElement实现
'''
def __init__(self, root, locator):
ControlContainer.__init__(self)
from qt4w.__init__ import XPath
from qt4w.util import WebElementAttributes, WebElementStyles
if isinstance(root, WebPage):
sel... | class WebElement(ControlContainer, IWebElement):
| '''IWebElement实现
'''
def __init__(self, root, locator):
ControlContainer.__init__(self)
from qt4w.__init__ import XPath
from qt4w.util import WebElementAttributes, WebElementStyles
if isinstance(root, WebPage):
self._page = root
else:
self._pa... | ):
raise NameError("%s没有名为'%s'的子控件!" % (type(self), name))
ui_control = self._ui_map[name]
ui_type = self.ui_control_type if self.ui_control_type else WebElement
if isinstance(ui_control, dict):
if 'type' in ui_control: ui_type = ui_control['type']
if not issu... | 256 | 256 | 3,991 | 9 | 247 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | WebElement | WebElement | 600 | 1,056 | 600 | 600 | de833b27a66e2e23f445979489a31587788785ef | bigcode/the-stack | train |
90886bf94b1b8560a447f102 | train | class | class ControlContainer(object):
'''控件容器基类
'''
ui_control_type = None
ui_map = {}
def __init__(self):
self._locator_dict = {}
self._ui_map = {}
self._update_ui_map()
def __getitem__(self, key):
'''获取控件
'''
item = copy.copy(self._locator_dict[key])... | class ControlContainer(object):
| '''控件容器基类
'''
ui_control_type = None
ui_map = {}
def __init__(self):
self._locator_dict = {}
self._ui_map = {}
self._update_ui_map()
def __getitem__(self, key):
'''获取控件
'''
item = copy.copy(self._locator_dict[key])
cls = item.pop('type')
... | 离控件区域左上角的纵向偏移。
:type y_offset: int或float
'''
raise NotImplementedError
def drag(self, x, y):
'''拖放元素到指定位置
:param x: 拖放终点距离起点的横向偏移。
:type x: int或float
:param y: 放终点距离起点的纵向偏移。
:type y: int或float
'''
raise NotImplementedError
def... | 249 | 249 | 830 | 5 | 243 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | ControlContainer | ControlContainer | 493 | 598 | 493 | 493 | b4f8c85f53236f060034912d3cec55e6be435e24 | bigcode/the-stack | train |
0d557261ef3c2b4118a2ff4e | train | class | class InputElement(WebElement):
'''input元素
'''
@property
def value(self):
'''当前的value
'''
return self._webdriver.get_property(self._locators, 'value')
@value.setter
def value(self, val):
'''设置新的value
:param val: 新设置的value
:type val: string
... | class InputElement(WebElement):
| '''input元素
'''
@property
def value(self):
'''当前的value
'''
return self._webdriver.get_property(self._locators, 'value')
@value.setter
def value(self, val):
'''设置新的value
:param val: 新设置的value
:type val: string
'''
self._webdriver.s... |
self._frame_page = WebPage(webview, self._locators)
self._frame_page.updateLocator(self._page._locator_dict)
return self._frame_page
@property
def FramePage(self):
'''
'''
return self.framepage
class InputElement(WebElement):
| 64 | 64 | 128 | 6 | 57 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | InputElement | InputElement | 1,279 | 1,297 | 1,279 | 1,279 | 72958cdc4ef7bddfbf98cc13dab31ee13368b340 | bigcode/the-stack | train |
cf9afd4017fca78c70d7ceeb | train | class | class WebPage(ControlContainer, IWebPage):
'''IWebPage接口实现
'''
ui_control_type = WebElement
WebElement.ui_control_type = WebElement # 不能直接在WebElement中赋值
def __init__(self, webview_or_webpage, locator=None, wait_for_ready=True):
ControlContainer.__init__(self)
if locator is None: lo... | class WebPage(ControlContainer, IWebPage):
| '''IWebPage接口实现
'''
ui_control_type = WebElement
WebElement.ui_control_type = WebElement # 不能直接在WebElement中赋值
def __init__(self, webview_or_webpage, locator=None, wait_for_ready=True):
ControlContainer.__init__(self)
if locator is None: locator = []
if isinstance(webview_or... | 0:
rect[3] += rect[1]
rect[1] = 0
if rect[0] + rect[2] > screen_size[0]:
rect[2] = screen_size[0] - rect[0]
if rect[1] + rect[3] > screen_size[1]:
rect[3] = screen_size[1] - rect[1]
mid_x = rect[0] + rect[2] / 2
mid_y = rect[1] + rect[3] / ... | 256 | 256 | 1,544 | 9 | 246 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | WebPage | WebPage | 1,058 | 1,247 | 1,058 | 1,058 | d28fddb19e7daf788682296d9bc9fd80e11e9cd3 | bigcode/the-stack | train |
1eac6087dddbaaee6a688160 | train | class | class MetisView(object):
'''实现IMetisView接口
'''
def __init__(self, page_or_elem):
if isinstance(page_or_elem, WebPage):
self._page = page_or_elem
self._elem = None
else:
self._page = page_or_elem.page
self._elem = page_or_elem
self._web... | class MetisView(object):
| '''实现IMetisView接口
'''
def __init__(self, page_or_elem):
if isinstance(page_or_elem, WebPage):
self._page = page_or_elem
self._elem = None
else:
self._page = page_or_elem.page
self._elem = page_or_elem
self._webview = self._page._webvie... | index = ''
ret = pattern.match(attr_name)
if ret != None:
attr_name = ret.group(1)
index = ret.group(2)[1:-1]
if not hasattr(child_elem, attr_name):
raise RuntimeError('控件:%s 没有属性:%s' % (child_elem, attr_name))
... | 185 | 185 | 617 | 6 | 179 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | MetisView | MetisView | 1,413 | 1,489 | 1,413 | 1,413 | 5a9016d8a3dc175f1b910f918693aeec845fcf0b | bigcode/the-stack | train |
cd8c1a1533fbaf9a01341967 | train | class | class IWebPage(object):
'''WebPage接口定义
'''
@property
def browser_type(self):
'''浏览器类型
'''
raise NotImplementedError
@property
def url(self):
'''页面url
'''
raise NotImplementedError
@Deprecated('url')
@property
def Url(self):
'... | class IWebPage(object):
| '''WebPage接口定义
'''
@property
def browser_type(self):
'''浏览器类型
'''
raise NotImplementedError
@property
def url(self):
'''页面url
'''
raise NotImplementedError
@Deprecated('url')
@property
def Url(self):
'''页面url
'''
... | # -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making QT4W available.
# Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the BSD 3-Clause License (the "License");you may not use this
# file except in compliance with the License. You may... | 231 | 256 | 980 | 5 | 225 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | IWebPage | IWebPage | 28 | 212 | 28 | 28 | 0392c6a02e7844425c58c5c662a0adf56a49ae5c | bigcode/the-stack | train |
e1f9be059458d099fa9a40ae | train | class | class IWebElement(object):
'''WebElement接口定义
'''
@property
def page(self):
'''元素所在WebPage
'''
raise NotImplementedError
@property
def attributes(self):
'''元素的属性集合
'''
raise NotImplementedError
@Deprecated('attributes')
@property
def A... | class IWebElement(object):
| '''WebElement接口定义
'''
@property
def page(self):
'''元素所在WebPage
'''
raise NotImplementedError
@property
def attributes(self):
'''元素的属性集合
'''
raise NotImplementedError
@Deprecated('attributes')
@property
def Attributes(self):
''... |
:param locator: 元素的xpath路径
:type locator: string或XPath
'''
raise NotImplementedError
@Deprecated('get_elements')
def getElements(self, locator):
'''在页面中查找元素,返回包含所有匹配的元素的列表
:param locator: 元素的xpath路径
:type locator: string或XPath
'''
rai... | 256 | 256 | 1,891 | 5 | 250 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | IWebElement | IWebElement | 214 | 491 | 214 | 214 | c30cff7f3f3aeff1ac2d44859ce63a3daf1c3a07 | bigcode/the-stack | train |
40a2463599165dc2a957d656 | train | class | class UIListBase(object):
'''List控件基类
'''
ui_control_type = None
def __init__(self, root, locator):
self._root = root
self._locator = locator
self._ui_map = {}
self._elements = []
def _get_elements(self):
'''获取元素列表
'''
if self._elements: retu... | class UIListBase(object):
| '''List控件基类
'''
ui_control_type = None
def __init__(self, root, locator):
self._root = root
self._locator = locator
self._ui_map = {}
self._elements = []
def _get_elements(self):
'''获取元素列表
'''
if self._elements: return self._elements
... | 返回所有选项列表
'''
option_list = []
for it in self.get_elements('/option'):
option_list.append(it.inner_text.strip())
return option_list
@property
def selection(self):
'''当前选择项
'''
return self._webdriver.get_property(self._locators, 'selectedIndex')... | 182 | 182 | 607 | 6 | 176 | jacobcliu/QT4W | qt4w/webcontrols.py | Python | UIListBase | UIListBase | 1,333 | 1,406 | 1,333 | 1,333 | 7dc9c035563a4df0571aa08fe6dd26f0b9344aab | bigcode/the-stack | train |
99cb7da349d04de30d82025b | train | function | @router.delete('/{id}',status_code=204,responses={404: {}})
async def delete(id: str, db: Session = Depends(get_db)):
try:
crud.delete(db, id)
return Response(status_code=204)
except NoResultFound:
raise HTTPException(status_code = 404)
| @router.delete('/{id}',status_code=204,responses={404: {}})
async def delete(id: str, db: Session = Depends(get_db)):
| try:
crud.delete(db, id)
return Response(status_code=204)
except NoResultFound:
raise HTTPException(status_code = 404)
| except NoResultFound:
raise HTTPException(status_code = 404)
except FileExistsError:
raise HTTPException(status_code = 403)
@router.delete('/{id}',status_code=204,responses={404: {}})
async def delete(id: str, db: Session = Depends(get_db)):
| 64 | 64 | 67 | 33 | 31 | hollyhockberry/track-location | webapi/beacon/router.py | Python | delete | delete | 56 | 62 | 56 | 57 | 9bd6cffb11cc283c93ac9ed1f381eaf1f4f0da5e | bigcode/the-stack | train |
c564a7fefe1c462ba02555fe | train | function | @router.post('/{id}',
description=
'The created record must have a unique combination of UUID, Major and Minor.',
status_code=204,
responses={
403: {'description': 'Duplicate combinations of UUID, Major and Minor'},
400: {}
})
async def create(id: str, data: schemas.BeaconCreate, db: Session = Depends(get_db)):
t... | @router.post('/{id}',
description=
'The created record must have a unique combination of UUID, Major and Minor.',
status_code=204,
responses={
403: {'description': 'Duplicate combinations of UUID, Major and Minor'},
400: {}
})
async def create(id: str, data: schemas.BeaconCreate, db: Session = Depends(get_db)):
| try:
crud.create(db, id, data)
return Response(status_code=204)
except IntegrityError:
raise HTTPException(status_code = 400)
except FileExistsError:
raise HTTPException(status_code = 403)
| @router.post('/{id}',
description=
'The created record must have a unique combination of UUID, Major and Minor.',
status_code=204,
responses={
403: {'description': 'Duplicate combinations of UUID, Major and Minor'},
400: {}
})
async def create(id: str, data: schemas.BeaconCreate, db: Session = Depends(get_db)):
| 77 | 64 | 128 | 77 | 0 | hollyhockberry/track-location | webapi/beacon/router.py | Python | create | create | 21 | 36 | 21 | 29 | 4dc15e464131d12e1250a4a665b2451c7b5b4db2 | bigcode/the-stack | train |
afaefeb28d82ccba1bd4b655 | train | function | @router.get('/',summary='Read all records',response_model=List[schemas.Beacon])
async def read(db: Session = Depends(get_db)):
return crud.read(db)
| @router.get('/',summary='Read all records',response_model=List[schemas.Beacon])
async def read(db: Session = Depends(get_db)):
| return crud.read(db)
| sqlalchemy.orm import Session
from typing import List
from . import schemas, crud
from database.db import get_db
router = APIRouter(tags=['beacons'])
@router.get('/',summary='Read all records',response_model=List[schemas.Beacon])
async def read(db: Session = Depends(get_db)):
| 64 | 64 | 36 | 30 | 34 | hollyhockberry/track-location | webapi/beacon/router.py | Python | read | read | 16 | 18 | 16 | 17 | 86f2a8c950ee5114742b2c209cfe081ef74c092c | bigcode/the-stack | train |
0fe3fe9ad8fc75bc224d6e42 | train | function | @router.put('/{id}',
description=
'The updated record must have a unique combination of UUID and Major and Minor.',
status_code=204,
responses={
403: {'description': 'Duplicate combinations of UUID, Major and Minor'},
404: {}})
async def update(id: str, data: schemas.BeaconUpdate, db: Session = Depends(get_db)):
... | @router.put('/{id}',
description=
'The updated record must have a unique combination of UUID and Major and Minor.',
status_code=204,
responses={
403: {'description': 'Duplicate combinations of UUID, Major and Minor'},
404: {}})
async def update(id: str, data: schemas.BeaconUpdate, db: Session = Depends(get_db)):
| try:
crud.update(db, id, data)
return Response(status_code=204)
except NoResultFound:
raise HTTPException(status_code = 404)
except FileExistsError:
raise HTTPException(status_code = 403)
| @router.put('/{id}',
description=
'The updated record must have a unique combination of UUID and Major and Minor.',
status_code=204,
responses={
403: {'description': 'Duplicate combinations of UUID, Major and Minor'},
404: {}})
async def update(id: str, data: schemas.BeaconUpdate, db: Session = Depends(get_db)):
| 77 | 64 | 129 | 77 | 0 | hollyhockberry/track-location | webapi/beacon/router.py | Python | update | update | 39 | 53 | 39 | 46 | e2059854b0b3b686aa2676996e95bb73b285d737 | bigcode/the-stack | train |
45db48825993fe9e683625d4 | train | class | class TfExampleDecoderTest(tf.test.TestCase):
def _EncodeImage(self, image_tensor, encoding_type='jpeg'):
with self.test_session():
if encoding_type == 'jpeg':
image_encoded = tf.image.encode_jpeg(tf.constant(image_tensor)).eval()
elif encoding_type == 'png':
image_encoded = tf.image.... | class TfExampleDecoderTest(tf.test.TestCase):
| def _EncodeImage(self, image_tensor, encoding_type='jpeg'):
with self.test_session():
if encoding_type == 'jpeg':
image_encoded = tf.image.encode_jpeg(tf.constant(image_tensor)).eval()
elif encoding_type == 'png':
image_encoded = tf.image.encode_png(tf.constant(image_tensor)).eval()
... | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 191 | 256 | 2,568 | 10 | 180 | MourabitElBachir/visual-recognition-server-control-back | object_detection/data_decoders/tf_example_decoder_test.py | Python | TfExampleDecoderTest | TfExampleDecoderTest | 25 | 284 | 25 | 26 | 1a49423a30a712599529ef6e378d9141d5ad0e46 | bigcode/the-stack | train |
0642091d8215d4e1bf8430d4 | train | function | def main():
print("Can partition: " + str(can_partition([1, 2, 3, 4])))
print("Can partition: " + str(can_partition([1, 1, 3, 4, 7])))
print("Can partition: " + str(can_partition([2, 3, 4, 6])))
| def main():
| print("Can partition: " + str(can_partition([1, 2, 3, 4])))
print("Can partition: " + str(can_partition([1, 1, 3, 4, 7])))
print("Can partition: " + str(can_partition([2, 3, 4, 6])))
| if num[currentIndex] <= sum:
if(can_partition_recursive(num, sum - num[currentIndex], currentIndex + 1)):
return True
# recursive call after excluding the number at the 'currentIndex'
return can_partition_recursive(num, sum, currentIndex + 1)
def main():
| 64 | 64 | 75 | 3 | 61 | mkoryor/Python | coding patterns/dynamic programming/knapsack_and_fib/equal_subset_sum_partition_brute_force.py | Python | main | main | 51 | 54 | 51 | 51 | 4ffa9ffe3734989220cd562fcb5fd15556cec0ee | bigcode/the-stack | train |
9b97ba508fabc099ca9701ad | train | function | def can_partition_recursive(num, sum, currentIndex):
# base check
if sum == 0:
return True
n = len(num)
if n == 0 or currentIndex >= n:
return False
# recursive call after choosing the number at the `currentIndex`
# if the number at `currentIndex` exceeds the sum, we shouldn't process this
if nu... | def can_partition_recursive(num, sum, currentIndex):
# base check
| if sum == 0:
return True
n = len(num)
if n == 0 or currentIndex >= n:
return False
# recursive call after choosing the number at the `currentIndex`
# if the number at `currentIndex` exceeds the sum, we shouldn't process this
if num[currentIndex] <= sum:
if(can_partition_recursive(num, sum - nu... | if 's' is a an odd number, we can't have two subsets with equal sum
if s % 2 != 0:
return False
return can_partition_recursive(num, s / 2, 0)
def can_partition_recursive(num, sum, currentIndex):
# base check
| 64 | 64 | 143 | 16 | 48 | mkoryor/Python | coding patterns/dynamic programming/knapsack_and_fib/equal_subset_sum_partition_brute_force.py | Python | can_partition_recursive | can_partition_recursive | 32 | 48 | 32 | 33 | 2fd2041151444c3da7934d3b593afca1b952056e | bigcode/the-stack | train |
a1c501eb3061ced6af476aa5 | train | function | def can_partition(num):
s = sum(num)
# if 's' is a an odd number, we can't have two subsets with equal sum
if s % 2 != 0:
return False
return can_partition_recursive(num, s / 2, 0)
| def can_partition(num):
| s = sum(num)
# if 's' is a an odd number, we can't have two subsets with equal sum
if s % 2 != 0:
return False
return can_partition_recursive(num, s / 2, 0)
| 4, 7}
Output: True
Explanation: The given set can be partitioned into two subsets with equal sum: {1, 3, 4} & {1, 7}
"""
# Time: O(2^n) Space: O(N * S)
def can_partition(num):
| 64 | 64 | 61 | 5 | 59 | mkoryor/Python | coding patterns/dynamic programming/knapsack_and_fib/equal_subset_sum_partition_brute_force.py | Python | can_partition | can_partition | 23 | 29 | 23 | 23 | 7cd404efd51cc3e77cb5bcee917609b2e4f0139f | bigcode/the-stack | train |
31378a1b05a01528eedb278e | train | function | def init(*args):
dic = defaultdict()
dic.__setitem__('kclient', kclient(User(args[0])))
return dic
| def init(*args):
| dic = defaultdict()
dic.__setitem__('kclient', kclient(User(args[0])))
return dic
| ENANT_NAME', os.getenv('OS_TENANT_NAME', 'None'))
prms.__setitem__('OS_PASSWORD', os.getenv('OS_PASSWORD', 'None'))
prms.__setitem__('OS_AUTH_URL', os.getenv('OS_AUTH_URL', 'None'))
return prms
def init(*args):
| 64 | 64 | 29 | 5 | 58 | fmount/zaqar-feed | zaqarfeed/cli.py | Python | init | init | 75 | 78 | 75 | 75 | fef66b3bcec35d65836b96a35bfe829457d59c1f | bigcode/the-stack | train |
49e3a14cfc5fafb0b1cbb7c5 | train | function | def read_env(parser):
if(os.getenv('OS_USERNAME') is None) or \
(os.getenv('OS_PASSWORD') is None) or \
(os.getenv('OS_TENANT_NAME') is None) or \
(os.getenv('OS_AUTH_URL') is None):
print(parser.usage)
exit(-1)
prms = defaultdict()
prms.__setitem__('OS_USERNAME', os.getenv('OS_USERNAME', 'None'))
prm... | def read_env(parser):
| if(os.getenv('OS_USERNAME') is None) or \
(os.getenv('OS_PASSWORD') is None) or \
(os.getenv('OS_TENANT_NAME') is None) or \
(os.getenv('OS_AUTH_URL') is None):
print(parser.usage)
exit(-1)
prms = defaultdict()
prms.__setitem__('OS_USERNAME', os.getenv('OS_USERNAME', 'None'))
prms.__setitem__('OS_TENANT... | export', '', line)
#print(' - '.join((l.split('=')[0].lstrip(), l.split('=')[1])))
prms.__setitem__(item.split("=")[0].lstrip(), item.split("=")[1].rstrip())
return prms
def read_env(parser):
| 64 | 64 | 160 | 6 | 57 | fmount/zaqar-feed | zaqarfeed/cli.py | Python | read_env | read_env | 58 | 72 | 58 | 59 | 4af4ae1e2e82d2876a8048e897ad6c2a857f3cec | bigcode/the-stack | train |
5f8aef54510aa8b51f0c5b11 | train | function | def cli():
print("------------------------------")
print("ZAQAR CLI PLUGIN")
print("------------------------------\n")
parser = optparse.OptionParser('\nsource keystonerc* \nusage %prog -f tenant_file')
parser.add_option('-f', dest='tenant_file', type='string', help='tenant file to authenticate on keystone')
par... | def cli():
| print("------------------------------")
print("ZAQAR CLI PLUGIN")
print("------------------------------\n")
parser = optparse.OptionParser('\nsource keystonerc* \nusage %prog -f tenant_file')
parser.add_option('-f', dest='tenant_file', type='string', help='tenant file to authenticate on keystone')
parser.add_opt... | ('OS_PASSWORD', 'None'))
prms.__setitem__('OS_AUTH_URL', os.getenv('OS_AUTH_URL', 'None'))
return prms
def init(*args):
dic = defaultdict()
dic.__setitem__('kclient', kclient(User(args[0])))
return dic
def cli():
| 64 | 64 | 197 | 3 | 60 | fmount/zaqar-feed | zaqarfeed/cli.py | Python | cli | cli | 81 | 104 | 81 | 81 | 421d407aef5cae4e3b01572edf1e1406c085bec0 | bigcode/the-stack | train |
1bff0729d1f6b2caeb615e0b | train | function | def read_keystonerc(ksrc):
prms = defaultdict()
with open(ksrc, 'r') as f:
for line in f:
if(line.startswith("export")):
item = re.sub('export', '', line)
#print(' - '.join((l.split('=')[0].lstrip(), l.split('=')[1])))
prms.__setitem__(item.split("=")[0].lstrip(), item.split("=")[1].rstrip())
return... | def read_keystonerc(ksrc):
| prms = defaultdict()
with open(ksrc, 'r') as f:
for line in f:
if(line.startswith("export")):
item = re.sub('export', '', line)
#print(' - '.join((l.split('=')[0].lstrip(), l.split('=')[1])))
prms.__setitem__(item.split("=")[0].lstrip(), item.split("=")[1].rstrip())
return prms
| 2. Define better the debug level and the file used
# 3.
#
SUPPORTED_API_VERSIONS = [2, 3]
logging.basicConfig(filename='/tmp/zaqar_cli.log', level=logging.DEBUG)
LOG = logging.getLogger(__name__)
def read_keystonerc(ksrc):
| 64 | 64 | 105 | 10 | 54 | fmount/zaqar-feed | zaqarfeed/cli.py | Python | read_keystonerc | read_keystonerc | 47 | 55 | 47 | 47 | 2df48004c43d635bd509ced6f4f1744835a2a3f1 | bigcode/the-stack | train |
2fc2db7aeac1c330a0d63de3 | train | class | class Mention:
def __init__ (self, id, cat, pos):
self.id = id # str
self.cat = cat # str
self.pos = pos # (start_pos, end_pos)
self.bbox = None # [xmin, ymin, xmax, ymax] float
self.bbox_pred = None # [xmin, ymin, xmax, ymax] float
| class Mention:
| def __init__ (self, id, cat, pos):
self.id = id # str
self.cat = cat # str
self.pos = pos # (start_pos, end_pos)
self.bbox = None # [xmin, ymin, xmax, ymax] float
self.bbox_pred = None # [xmin, ymin, xmax, ymax] float
| class Mention:
| 3 | 64 | 88 | 3 | 0 | liujch1998/SoftLabelCCRF | SoftLabelCCRF/structures/mention.py | Python | Mention | Mention | 1 | 8 | 1 | 2 | a198a49711e5951dd9f539ce7db2cc9fcf1db49b | bigcode/the-stack | train |
c623a688e24e0ecff52224aa | train | function | def write_file_chunk(path, stream, offset, chunk_size,
checksum=None, checksum_type=None):
_initialize_file_path(path)
with open(path, 'rb+') as f:
if chunk_size:
fcntl.lockf(f, fcntl.LOCK_EX, chunk_size, offset, 0)
else:
fcntl.flock(f, fcntl.LOCK_E... | def write_file_chunk(path, stream, offset, chunk_size,
checksum=None, checksum_type=None):
| _initialize_file_path(path)
with open(path, 'rb+') as f:
if chunk_size:
fcntl.lockf(f, fcntl.LOCK_EX, chunk_size, offset, 0)
else:
fcntl.flock(f, fcntl.LOCK_EX)
f.seek(offset)
chunk = stream.read(chunk_size)
if checksum is not None:
ha... | return:
"""
if os.path.exists(path):
return
_mkdirs(os.path.dirname(path))
# touch the file to make sure it exists
open(path, 'ab').close()
def write_file_chunk(path, stream, offset, chunk_size,
checksum=None, checksum_type=None):
| 64 | 64 | 155 | 21 | 43 | happybits/napfs | napfs/fs.py | Python | write_file_chunk | write_file_chunk | 67 | 86 | 67 | 69 | b6d488b8903d9a5876fa6a1f828f68ff92744dd0 | bigcode/the-stack | train |
55ca64934e414700f3c09d75 | train | function | def _mkdirs(dir_name):
# there's a race condition where we could see the directory doesn't exist
# and then hit an error when trying to create the directory because
# another process is doing the same thing at the exact same time.
# if that's the case, swallow the error.
if os.path.exists(dir_name):... | def _mkdirs(dir_name):
# there's a race condition where we could see the directory doesn't exist
# and then hit an error when trying to create the directory because
# another process is doing the same thing at the exact same time.
# if that's the case, swallow the error.
| if os.path.exists(dir_name):
return
try:
os.makedirs(dir_name)
except OSError as e:
if e.errno != errno.EEXIST:
raise
| }
def _mkdirs(dir_name):
# there's a race condition where we could see the directory doesn't exist
# and then hit an error when trying to create the directory because
# another process is doing the same thing at the exact same time.
# if that's the case, swallow the error.
| 64 | 64 | 104 | 63 | 1 | happybits/napfs | napfs/fs.py | Python | _mkdirs | _mkdirs | 21 | 32 | 21 | 25 | 16908fa5301d48534209c3328b05d003bb974c4f | bigcode/the-stack | train |
e9b5ef8eeb389c63ccaee506 | train | function | def copy_file(src, dst):
_mkdirs(os.path.dirname(dst))
shutil.copy(src, dst)
| def copy_file(src, dst):
| _mkdirs(os.path.dirname(dst))
shutil.copy(src, dst)
| the exact same time.
# if that's the case, swallow the error.
if os.path.exists(dir_name):
return
try:
os.makedirs(dir_name)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def copy_file(src, dst):
| 64 | 64 | 23 | 7 | 56 | happybits/napfs | napfs/fs.py | Python | copy_file | copy_file | 35 | 37 | 35 | 35 | f903c3f3c334059d12b08aa3cbcfab57d6b564e9 | bigcode/the-stack | train |
6c0e6645cab8afd174f742f8 | train | function | def _initialize_file_path(path):
"""
:param path:
:return:
"""
if os.path.exists(path):
return
_mkdirs(os.path.dirname(path))
# touch the file to make sure it exists
open(path, 'ab').close()
| def _initialize_file_path(path):
| """
:param path:
:return:
"""
if os.path.exists(path):
return
_mkdirs(os.path.dirname(path))
# touch the file to make sure it exists
open(path, 'ab').close()
| dst)
def delete_file(path):
try:
os.unlink(path)
except (IOError, OSError):
pass
return False if os.path.exists(path) else True
def open_file(path, mode='rb'):
return open(path, mode=mode)
def _initialize_file_path(path):
| 64 | 64 | 59 | 7 | 57 | happybits/napfs | napfs/fs.py | Python | _initialize_file_path | _initialize_file_path | 53 | 64 | 53 | 53 | 77cae6c60cdaca33b36bf3101890151bcfae4ee1 | bigcode/the-stack | train |
d02ec7ef7f9bed4f15c421fd | train | function | def delete_file(path):
try:
os.unlink(path)
except (IOError, OSError):
pass
return False if os.path.exists(path) else True
| def delete_file(path):
| try:
os.unlink(path)
except (IOError, OSError):
pass
return False if os.path.exists(path) else True
| (dir_name):
return
try:
os.makedirs(dir_name)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def copy_file(src, dst):
_mkdirs(os.path.dirname(dst))
shutil.copy(src, dst)
def delete_file(path):
| 64 | 64 | 37 | 5 | 59 | happybits/napfs | napfs/fs.py | Python | delete_file | delete_file | 40 | 46 | 40 | 40 | fcd2aa03fdf347bbc455514182dd804ceb79e809 | bigcode/the-stack | train |
8e580076d81e95912e2c8d50 | train | function | def checksum_response(response, checksum):
hashcalc = supported_checksum_methods.get(checksum, hashlib.sha1)()
for chunk in response():
hashcalc.update(chunk)
return hashcalc.hexdigest()
| def checksum_response(response, checksum):
| hashcalc = supported_checksum_methods.get(checksum, hashlib.sha1)()
for chunk in response():
hashcalc.update(chunk)
return hashcalc.hexdigest()
| f:
f.seek(first_byte)
bytes_left = length
while bytes_left > 0:
chunk_size = min(bytes_left, READ_BLOCK_SIZE)
data = f.read(chunk_size)
bytes_left -= chunk_size
yield data
return response
def checksum_response(resp... | 64 | 64 | 42 | 7 | 56 | happybits/napfs | napfs/fs.py | Python | checksum_response | checksum_response | 116 | 120 | 116 | 116 | b3a12aefd07185f418e1dcbf26282d9f5a668277 | bigcode/the-stack | train |
a15b8aef44808c305b76b604 | train | function | def read_file_chunk(f, first_byte, length):
"""
utility generator function to serve up the bytes
allows us to return the response headers and then stream the bytes
to the client without blocking or buffering all the bytes into memory.
this is especially important for really big files.
:param f... | def read_file_chunk(f, first_byte, length):
| """
utility generator function to serve up the bytes
allows us to return the response headers and then stream the bytes
to the client without blocking or buffering all the bytes into memory.
this is especially important for really big files.
:param f:
:param length:
:param first_byte:
... | not None:
hashcalc = supported_checksum_methods.get(checksum_type,
hashlib.sha1)()
hashcalc.update(chunk)
if hashcalc.hexdigest() != checksum:
raise InvalidChecksumException()
f.write(chunk)
return... | 64 | 64 | 146 | 11 | 53 | happybits/napfs | napfs/fs.py | Python | read_file_chunk | read_file_chunk | 89 | 113 | 89 | 89 | 23d158b1c15db549cea4071fcd807af2bd8323f1 | bigcode/the-stack | train |
329bc7cc5ad832ca3fe03e99 | train | function | def open_file(path, mode='rb'):
return open(path, mode=mode)
| def open_file(path, mode='rb'):
| return open(path, mode=mode)
| dst):
_mkdirs(os.path.dirname(dst))
shutil.copy(src, dst)
def delete_file(path):
try:
os.unlink(path)
except (IOError, OSError):
pass
return False if os.path.exists(path) else True
def open_file(path, mode='rb'):
| 64 | 64 | 18 | 9 | 54 | happybits/napfs | napfs/fs.py | Python | open_file | open_file | 49 | 50 | 49 | 49 | d232f2bb8b77ed59d536354970b0e03aea606bd9 | bigcode/the-stack | train |
1f9a6edec1cc9c3e94ffdbc4 | train | class | class test_pi18_decode(unittest.TestCase):
maxDiff = None
def test_pi18_PI(self):
"""test the decode of a PI response"""
protocol = pi()
response = b"^D00518\xca\xed\r"
command = "PI"
expected = {
"raw_response": ["^D00518Êí\r", ""],
"_command": "... | class test_pi18_decode(unittest.TestCase):
| maxDiff = None
def test_pi18_PI(self):
"""test the decode of a PI response"""
protocol = pi()
response = b"^D00518\xca\xed\r"
command = "PI"
expected = {
"raw_response": ["^D00518Êí\r", ""],
"_command": "PI",
"_command_description": "D... | import unittest
from mppsolar.protocols.pi18 import pi18 as pi
class test_pi18_decode(unittest.TestCase):
| 26 | 64 | 131 | 9 | 16 | kchiem/mpp-solar | tests/test_protocol_pi18.py | Python | test_pi18_decode | test_pi18_decode | 5 | 21 | 5 | 5 | 17c3c96c58bfb7d87ec268d9baaad1219dd85f10 | bigcode/the-stack | train |
5fcadf7c05b53ece904eb2f7 | train | function | def PseudogymnoascusVerrucosus(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new instance of the P... | def PseudogymnoascusVerrucosus(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
| """Return new instance of the Pseudogymnoascus verrucosus graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True... | va, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
fr... | 182 | 182 | 608 | 83 | 98 | AnacletoLAB/ensmallen_graph | bindings/python/ensmallen/datasets/string/pseudogymnoascusverrucosus.py | Python | PseudogymnoascusVerrucosus | PseudogymnoascusVerrucosus | 30 | 104 | 30 | 39 | 3acffe15777e1c646575632049b1042e007f381c | bigcode/the-stack | train |
08a74a50db535e607946e275 | train | class | class TestRandom(base.TestCase):
def setUp(self):
super(TestRandom, self).setUp()
self.sess = mock.Mock(spec=adapter.Adapter)
# self.sess.get = mock.Mock()
self.sess.post = mock.Mock()
self.sot = misc.Random()
def test_basic(self):
sot = misc.Random()
se... | class TestRandom(base.TestCase):
| def setUp(self):
super(TestRandom, self).setUp()
self.sess = mock.Mock(spec=adapter.Adapter)
# self.sess.get = mock.Mock()
self.sess.post = mock.Mock()
self.sot = misc.Random()
def test_basic(self):
sot = misc.Random()
self.assertEqual(None, sot.resource_... | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneauth1 import adapter
import mock
from openstack.tests.unit import base
from otcextensions.sdk.kms.v1 import misc
EXAMPLE = {
'rand... | 116 | 116 | 388 | 7 | 109 | artem-lifshits/python-otcextensions | otcextensions/tests/unit/sdk/kms/v1/test_misc.py | Python | TestRandom | TestRandom | 26 | 75 | 26 | 27 | 5260a63cbe595f106c70bbc995fa2e8865ee9043 | bigcode/the-stack | train |
59da2c5e0254d8b99ae309d7 | train | class | class TestQuota(base.TestCase):
def setUp(self):
super(TestQuota, self).setUp()
self.sess = mock.Mock(spec=adapter.Adapter)
self.sess.get = mock.Mock()
def test_list(self):
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.headers = {}
... | class TestQuota(base.TestCase):
| def setUp(self):
super(TestQuota, self).setUp()
self.sess = mock.Mock(spec=adapter.Adapter)
self.sess.get = mock.Mock()
def test_list(self):
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.headers = {}
mock_response.json.return_v... | ()
result = sot.fetch(self.sess)
self.sess.get.assert_called_once_with(
'kms/user-instances',
microversion=None,
params={}
)
self.assertEqual(sot, result)
self.assertEqual(5, result.instance_num)
class TestQuota(base.TestCase):
| 64 | 64 | 213 | 7 | 57 | artem-lifshits/python-otcextensions | otcextensions/tests/unit/sdk/kms/v1/test_misc.py | Python | TestQuota | TestQuota | 110 | 145 | 110 | 111 | a2abda9a697f08613778815632022f0a40f1447f | bigcode/the-stack | train |
954d63121845621c35b629aa | train | class | class TestInstanceNum(base.TestCase):
def setUp(self):
super(TestInstanceNum, self).setUp()
self.sess = mock.Mock(spec=adapter.Adapter)
self.sess.default_microversion = None
self.sess.get = mock.Mock()
self.sot = misc.InstanceNumber()
def test_get(self):
mock_re... | class TestInstanceNum(base.TestCase):
| def setUp(self):
super(TestInstanceNum, self).setUp()
self.sess = mock.Mock(spec=adapter.Adapter)
self.sess.default_microversion = None
self.sess.get = mock.Mock()
self.sot = misc.InstanceNumber()
def test_get(self):
mock_response = mock.Mock()
mock_respo... | call_args[1]['json'])
self.sess.post.assert_called_once()
self.assertEqual(sot, result)
self.assertEqual(EXAMPLE['random_data'], result.random_data)
self.assertEqual(EXAMPLE['random_data_length'],
result.random_data_length)
class TestInstanceNum(base.TestCase)... | 64 | 64 | 185 | 8 | 56 | artem-lifshits/python-otcextensions | otcextensions/tests/unit/sdk/kms/v1/test_misc.py | Python | TestInstanceNum | TestInstanceNum | 78 | 107 | 78 | 79 | d9c1c43b7199ccd00427618a5b92ec19b2b5f88f | bigcode/the-stack | train |
df8788930e43deb60ddce17f | train | function | def train(task_id, data, mnet, hnet, device, config, shared, logger, writer):
r"""Train the network using the task-specific loss plus a regularizer that
should weaken catastrophic forgetting.
.. math::
\text{loss} = \text{task\_loss} + \beta * \text{regularizer}
In case coresets are used to re... | def train(task_id, data, mnet, hnet, device, config, shared, logger, writer):
| r"""Train the network using the task-specific loss plus a regularizer that
should weaken catastrophic forgetting.
.. math::
\text{loss} = \text{task\_loss} + \beta * \text{regularizer}
In case coresets are used to regularize towards high entropy on previous
tasks, the loss becomes
.. ... | _target_logvars,
prev_theta=prev_hnet_theta, prev_task_embs=prev_task_embs,
batch_size=config.hnet_reg_batch_size)
loss = dis_loss + config.beta * loss_reg
loss.backward()
if config.clip_grad_value != -1:
torch.nn.utils.clip_grad_value_(optim... | 256 | 256 | 4,567 | 23 | 233 | chrhenning/posterior_replay_cl | probabilistic/prob_mnist/train_bbb.py | Python | train | train | 371 | 844 | 371 | 371 | 7c2d4aca9a2dfc0954f4653487114a575dd45b6f | bigcode/the-stack | train |
93053e10f66c5258114d201f | train | function | def evaluate(task_id, data, mnet, hnet, device, config, shared, logger, writer,
train_iter):
"""Evaluate the network. Evaluate the performance of the network on a
single task on the validation set.
Note, if no validation set is available, the test set will be used instead.
Args:
... | def evaluate(task_id, data, mnet, hnet, device, config, shared, logger, writer,
train_iter):
| """Evaluate the network. Evaluate the performance of the network on a
single task on the validation set.
Note, if no validation set is available, the test set will be used instead.
Args:
(....): See docstring of function :func:`train`. Note, ``hnet`` can be
passed as ``None``. In ... | from warnings import warn
from mnets.classifier_interface import Classifier
from hnets.hnet_helpers import get_conditional_parameters
from probabilistic import prob_utils as putils
from probabilistic import GaussianBNNWrapper
from probabilistic import train_vi
from probabilistic.prob_cifar import train_utils as pcutil... | 160 | 160 | 534 | 27 | 132 | chrhenning/posterior_replay_cl | probabilistic/prob_mnist/train_bbb.py | Python | evaluate | evaluate | 64 | 116 | 64 | 65 | 2194acf93d37a76f531f371c31f71b91906df391 | bigcode/the-stack | train |
7358f73cfe7a0060add7f4c3 | train | function | def train_multitask_coresets(dhandlers, mnet, hnet, device, config, shared,
logger, writer):
r"""Fine-tune the network on the coresets after training on all tasks.
This function performs a multitask fine-tuning stage after the models have
been sequentially trained on all tasks... | def train_multitask_coresets(dhandlers, mnet, hnet, device, config, shared,
logger, writer):
| r"""Fine-tune the network on the coresets after training on all tasks.
This function performs a multitask fine-tuning stage after the models have
been sequentially trained on all tasks. For this stage, a set of samples
stored in task-specific coresets which were not used during the sequential
train... | for d in w_mean])
writer.add_histogram('train/task_%d/predicted_means' % task_id,
mean_outputs, i)
if w_std is not None:
std_outputs = torch.cat([d.clone().view(-1) for d in w_std])
writer.add_histogram('train/task_%d/predicted_st... | 256 | 256 | 3,270 | 29 | 227 | chrhenning/posterior_replay_cl | probabilistic/prob_mnist/train_bbb.py | Python | train_multitask_coresets | train_multitask_coresets | 846 | 1,148 | 846 | 847 | ec3e673df06277baf3ed539c58bae36cc87df7a1 | bigcode/the-stack | train |
85a18b99f5bfeec0e624d272 | train | function | def distill_net(task_id, data, mnet, hnet, hhnet, device, config, shared,
logger, writer):
"""Distill the current weights of the main network into the hypernet.
If the no hyper-hypernetwork ``hhnet`` is given, then this function takes
the trained main network and distills its weights into t... | def distill_net(task_id, data, mnet, hnet, hhnet, device, config, shared,
logger, writer):
| """Distill the current weights of the main network into the hypernet.
If the no hyper-hypernetwork ``hhnet`` is given, then this function takes
the trained main network and distills its weights into the hypernet using
the embedding corresponding to ``task_id``.
Otherwise, the the hypernetwork ``hn... | _utils.compute_acc(task_id, data, mnet, hnet,
device, config, shared, split_type='val', return_dataset=False,
return_entropies=True, return_pred_labels=False)
logger.info('Eval - Accuracy on %s set: %f%%.' % (split_name, acc))
writer.add_scalar('eval/task_%d/accuracy' % task_id,... | 256 | 256 | 2,357 | 29 | 227 | chrhenning/posterior_replay_cl | probabilistic/prob_mnist/train_bbb.py | Python | distill_net | distill_net | 118 | 369 | 118 | 119 | 49639e1febd011d23f953879c9c40931fd57ba7a | bigcode/the-stack | train |
2030c56c3e560d9388dba3f6 | train | function | def run(config, experiment='split_bbb'):
"""Run the training.
Args:
config: Command-line arguments.
experiment: Which kind of experiment should be performed?
- "gmm_bbb": Synthetic Gaussian Mixture Model Dataset
- "split_bbb": Split MNIST
- "perm_bbb": Permu... | def run(config, experiment='split_bbb'):
| """Run the training.
Args:
config: Command-line arguments.
experiment: Which kind of experiment should be performed?
- "gmm_bbb": Synthetic Gaussian Mixture Model Dataset
- "split_bbb": Split MNIST
- "perm_bbb": Permuted MNIST
- "cifar_zenke_bbb"... | _size
loss_nll += loss_nll_curr_task
loss_curr_task = kl_scale * loss_kl_curr_task + loss_nll_curr_task
loss_curr_task.backward()
loss = kl_scale * loss_kl + loss_nll
# Note, we call `backward` above inside the loop, and accumulate
# gradients, to avoid memo... | 256 | 256 | 2,188 | 10 | 246 | chrhenning/posterior_replay_cl | probabilistic/prob_mnist/train_bbb.py | Python | run | run | 1,150 | 1,357 | 1,150 | 1,150 | 1510e83b1e309240e91d31b8aed769fa85e58d32 | bigcode/the-stack | train |
4f90adb855b8180d38f19c23 | train | class | class W2LModelTests(Speech2TextModelTests):
def setUp(self):
self.base_model = base_model
self.base_params = base_params
self.train_params = train_params
self.eval_params = eval_params
def tearDown(self):
pass
def test_convergence(self):
return self.convergence_test(5.0, 30.0, 0.1)
d... | class W2LModelTests(Speech2TextModelTests):
| def setUp(self):
self.base_model = base_model
self.base_params = base_params
self.train_params = train_params
self.eval_params = eval_params
def tearDown(self):
pass
def test_convergence(self):
return self.convergence_test(5.0, 30.0, 0.1)
def test_mp_collection(self):
return self.... | _literals
import tensorflow as tf
from open_seq2seq.test_utils.test_speech_configs.w2l_test_config import \
base_params, train_params, eval_params, base_model
from .speech2text_test import Speech2TextModelTests
class W2LModelTests(Speech2TextModelTests):
| 64 | 64 | 107 | 13 | 50 | Kipok/OpenSeq2Seq | open_seq2seq/models/speech2text_w2l_test.py | Python | W2LModelTests | W2LModelTests | 12 | 27 | 12 | 13 | b911bbc02fd88c36923dc88b918565d3e7c0483e | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.