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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7849f09f16e1fc6be5da098a | train | class | class RuleHandler(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The va... | class RuleHandler(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | """
ORY Oathkeeper
ORY Oathkeeper is a reverse proxy that checks the HTTP Authorization for validity against a set of rules. This service uses Hydra to validate access tokens and policies. # noqa: E501
The version of the OpenAPI document: v0.38.15-beta.1
Contact: hi@ory.am
Generated by: https://o... | 211 | 256 | 2,123 | 6 | 204 | russelg/sdk | clients/oathkeeper/python/ory_oathkeeper_client/model/rule_handler.py | Python | RuleHandler | RuleHandler | 34 | 260 | 34 | 34 | ede7ded1c7c20404713d1a4317d551f515c6a32c | bigcode/the-stack | train |
a900f605302aa2dc941da04a | train | class | class JiraManager(BaseManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.conn = None
def issue_ticket(self, conn, message, **kwargs):
self.conn: JiraConnector = self.locator.get_connector('JiraConnector')
self.conn.issue_ticket(conn, message, ... | class JiraManager(BaseManager):
| def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.conn = None
def issue_ticket(self, conn, message, **kwargs):
self.conn: JiraConnector = self.locator.get_connector('JiraConnector')
self.conn.issue_ticket(conn, message, **kwargs)
| from spaceone.core.manager import BaseManager
from spaceone.notification.connector.jira import JiraConnector
class JiraManager(BaseManager):
| 26 | 64 | 77 | 6 | 19 | choonho/plugin-jira-noti-protocol | src/spaceone/notification/manager/jira_manager.py | Python | JiraManager | JiraManager | 5 | 13 | 5 | 6 | e2cd4f9f125084796f89532bafa2e2b477f222f3 | bigcode/the-stack | train |
10673cc21600f6ef520fcce7 | train | function | def con():
ppc = {"version": '0'}
ppc["baseMVA"] = 1000
ppc["con"] = array([
[1, 1, 0.9, 0.9, 1000, 1000, 1000],
[5, 10, 0.9, 0.9, 1000, 1000, 1000],
[10, 20, 0.9, 0.9, 1000, 1000, 1000],
])
return ppc
| def con():
| ppc = {"version": '0'}
ppc["baseMVA"] = 1000
ppc["con"] = array([
[1, 1, 0.9, 0.9, 1000, 1000, 1000],
[5, 10, 0.9, 0.9, 1000, 1000, 1000],
[10, 20, 0.9, 0.9, 1000, 1000, 1000],
])
return ppc
| AC side, maximal reactive power inject power to AC side, maximal reactive power inject power to DC side
"""
AC_ID = 0
DC_ID = 1
EFF_A2D = 2
EFF_D2A = 3
SMAX = 4
from numpy import array
def con():
| 64 | 64 | 129 | 3 | 60 | Matrixeigs/EnergyManagementSourceCodes | distribution_system_optimization/data_format/case_converters.py | Python | con | con | 16 | 25 | 16 | 16 | 03aa239989698d028279ec9e15fcaea7835f8183 | bigcode/the-stack | train |
73daa24db279ef1810cef5bd | train | function | def div_by_100(x):
return x % 100 == 0
| def div_by_100(x):
| return x % 100 == 0
| True
else:
return False
else:
return True
else:
return False
def div_by_4(x):
return x % 4 == 0
def div_by_400(x):
return x % 400 == 0
def div_by_100(x):
| 64 | 64 | 17 | 7 | 56 | heymajor/exercism | python/leap/leap.py | Python | div_by_100 | div_by_100 | 19 | 20 | 19 | 19 | 2c7b6483996a51d4c1fcaca9f305137b542bcc0a | bigcode/the-stack | train |
a3f36dae9a92cc151042dee4 | train | function | def leap_year(year):
if div_by_4(year):
if div_by_100(year):
if div_by_400(year):
return True
else:
return False
else:
return True
else:
return False
| def leap_year(year):
| if div_by_4(year):
if div_by_100(year):
if div_by_400(year):
return True
else:
return False
else:
return True
else:
return False
| def leap_year(year):
| 5 | 64 | 54 | 5 | 0 | heymajor/exercism | python/leap/leap.py | Python | leap_year | leap_year | 1 | 11 | 1 | 1 | 781e7bd600ec080853f2e2242cbc4f5b3c7d249a | bigcode/the-stack | train |
eacda48d2b01bc9469e0d0c7 | train | function | def div_by_4(x):
return x % 4 == 0
| def div_by_4(x):
| return x % 4 == 0
| def leap_year(year):
if div_by_4(year):
if div_by_100(year):
if div_by_400(year):
return True
else:
return False
else:
return True
else:
return False
def div_by_4(x):
| 61 | 64 | 17 | 7 | 53 | heymajor/exercism | python/leap/leap.py | Python | div_by_4 | div_by_4 | 13 | 14 | 13 | 13 | 3f71de034a94f00fe23d6dc64e51b3e953df9ca3 | bigcode/the-stack | train |
d41b98b452e5ee7ef3906d3c | train | function | def div_by_400(x):
return x % 400 == 0
| def div_by_400(x):
| return x % 400 == 0
| if div_by_100(year):
if div_by_400(year):
return True
else:
return False
else:
return True
else:
return False
def div_by_4(x):
return x % 4 == 0
def div_by_400(x):
| 64 | 64 | 17 | 7 | 56 | heymajor/exercism | python/leap/leap.py | Python | div_by_400 | div_by_400 | 16 | 17 | 16 | 16 | b9f851ffc51ae303c2549dfb4970663aa7dcd75b | bigcode/the-stack | train |
a55a04f4c25189636066e3e4 | train | function | def findReplace(directory, find, replace, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with open(filepath) as f:
s = f.read()
s =... | def findReplace(directory, find, replace, filePattern):
| for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with open(filepath) as f:
s = f.read()
s = s.replace(find, replace)
s = s.replace(... | #!/usr/bin/env python
import lxml.html
from lxml import etree
import sys, os, fnmatch
from pygments import highlight
from pygments.lexers import *
from pygments.formatters import HtmlFormatter
import copy
def findReplace(directory, find, replace, filePattern):
| 62 | 179 | 597 | 12 | 49 | shivshankardayal/time-travel-prithviraj | domp_lxml.py | Python | findReplace | findReplace | 11 | 74 | 11 | 11 | ae230be0cdcf5e3083724016cee2262038f6d5b4 | bigcode/the-stack | train |
7ba4c5e1c3ebe30e9b920582 | train | function | def get_id_alias2relations_dict(dataset):
id_alias2relations_dict = {}
with open(f'data/{dataset.lower()}_processed.jsonl', 'r') as f:
for line in jsonlines.Reader(f):
alias2relations_dict = {}
text = line["text"]
for elem in line['rel_candidates']:
sp... | def get_id_alias2relations_dict(dataset):
| id_alias2relations_dict = {}
with open(f'data/{dataset.lower()}_processed.jsonl', 'r') as f:
for line in jsonlines.Reader(f):
alias2relations_dict = {}
text = line["text"]
for elem in line['rel_candidates']:
span = elem['char_span']
rel... | for r in elem["relation"]:
if r in dev_relations:
elemrel.append(r)
elem["relation"] = elemrel
if len(elem["relation"]) > 0:
item['rel_candidates'].append(elem)
writer.write(item)
def ge... | 64 | 64 | 214 | 9 | 55 | HaoyunHong/deepex | scripts/rc/post_process.py | Python | get_id_alias2relations_dict | get_id_alias2relations_dict | 27 | 45 | 27 | 27 | d6b47a18807362afb29660374b3da9d0182ece69 | bigcode/the-stack | train |
fe98941c946217feeb19bcc7 | train | function | def get_processed_output(dataset):
lemmatized_matcher = LemmatizeStringMatcher(f'{dataset.lower()}_aliases_lemmatized.json')
unlemmatized_matcher = UnLemmatizeStringMatcher(f'{dataset.lower()}_aliases_unlemmatized.json')
dev_relations = ['crosses', 'original language of film or TV show', 'competition class'... | def get_processed_output(dataset):
| lemmatized_matcher = LemmatizeStringMatcher(f'{dataset.lower()}_aliases_lemmatized.json')
unlemmatized_matcher = UnLemmatizeStringMatcher(f'{dataset.lower()}_aliases_unlemmatized.json')
dev_relations = ['crosses', 'original language of film or TV show', 'competition class', 'part of', 'sport', 'constellatio... | import tqdm
import json
import argparse
import jsonlines
from dataset_preparation import get_relation_candidates
from string_matcher import UnLemmatizeStringMatcher, LemmatizeStringMatcher
def get_processed_output(dataset):
| 47 | 89 | 298 | 6 | 40 | HaoyunHong/deepex | scripts/rc/post_process.py | Python | get_processed_output | get_processed_output | 8 | 25 | 8 | 8 | c35d2a2ae0a03ef6d29182a1b325e66f0b1997dc | bigcode/the-stack | train |
ebf41643d3ee1f32cf7475b0 | train | class | class Sim(object):
""" Main class to run algorithms and experiments. """
def __init__(self, config, gpu_id=0, ngpu=1):
self._hp = self._default_hparams()
self.override_defaults(config)
self._hp.agent['log_dir'] = self._hp.log_dir
self.agent = self._hp.agent['type'](self._hp.agen... | class Sim(object):
| """ Main class to run algorithms and experiments. """
def __init__(self, config, gpu_id=0, ngpu=1):
self._hp = self._default_hparams()
self.override_defaults(config)
self._hp.agent['log_dir'] = self._hp.log_dir
self.agent = self._hp.agent['type'](self._hp.agent)
self.pol... | import os
import os.path
from visual_mpc.agent.utils.utils import timed
import sys
from visual_mpc.agent.utils.raw_saver import RawSaver
from visual_mpc.agent.utils.traj_saver import GeneralAgentSaver
from visual_mpc.agent.utils.hdf5_saver import HDF5Saver
from tensorflow.contrib.training import HParams
sys.path.append... | 92 | 256 | 935 | 4 | 88 | Asap7772/visual_foresight | visual_mpc/sim/simulator.py | Python | Sim | Sim | 13 | 114 | 13 | 13 | a4a30f1b224906bdfb5ab5c50bb4eb5f6896335c | bigcode/the-stack | train |
8a1ffa428981cd687e40b257 | train | class | class RootNotFound(NodeNotFound):
pass
| class RootNotFound(NodeNotFound):
| pass
| : utf-8 -*-
"""
Exceptions raised by Nodular.
"""
from werkzeug.exceptions import NotFound, Gone
__all__ = ['NodeNotFound', 'RootNotFound', 'NodeGone', 'ViewNotFound']
class NodeNotFound(NotFound):
pass
class RootNotFound(NodeNotFound):
| 64 | 64 | 11 | 8 | 55 | hasgeek/nodular | nodular/exceptions.py | Python | RootNotFound | RootNotFound | 16 | 17 | 16 | 16 | 3790ae109e15f5597f551fa216ff6bc2c70cfef1 | bigcode/the-stack | train |
628b7da071828b4b97bdf732 | train | class | class NodeNotFound(NotFound):
pass
| class NodeNotFound(NotFound):
| pass
| # -*- coding: utf-8 -*-
"""
Exceptions raised by Nodular.
"""
from werkzeug.exceptions import NotFound, Gone
__all__ = ['NodeNotFound', 'RootNotFound', 'NodeGone', 'ViewNotFound']
class NodeNotFound(NotFound):
| 56 | 64 | 10 | 7 | 49 | hasgeek/nodular | nodular/exceptions.py | Python | NodeNotFound | NodeNotFound | 12 | 13 | 12 | 12 | c9466fc2a78f2def8d1cc51ec7bbc77a13a559c6 | bigcode/the-stack | train |
50cf1af5dcb6b2104400f6d6 | train | class | class NodeGone(Gone):
pass
| class NodeGone(Gone):
| pass
| Nodular.
"""
from werkzeug.exceptions import NotFound, Gone
__all__ = ['NodeNotFound', 'RootNotFound', 'NodeGone', 'ViewNotFound']
class NodeNotFound(NotFound):
pass
class RootNotFound(NodeNotFound):
pass
class NodeGone(Gone):
| 64 | 64 | 9 | 6 | 57 | hasgeek/nodular | nodular/exceptions.py | Python | NodeGone | NodeGone | 20 | 21 | 20 | 20 | cde659a4c03179b68d4deedb9aeefd5fd8bca219 | bigcode/the-stack | train |
b933870a3195d08218db96aa | train | class | class ViewNotFound(NotFound):
pass
| class ViewNotFound(NotFound):
| pass
| Found, Gone
__all__ = ['NodeNotFound', 'RootNotFound', 'NodeGone', 'ViewNotFound']
class NodeNotFound(NotFound):
pass
class RootNotFound(NodeNotFound):
pass
class NodeGone(Gone):
pass
class ViewNotFound(NotFound):
| 64 | 64 | 10 | 7 | 56 | hasgeek/nodular | nodular/exceptions.py | Python | ViewNotFound | ViewNotFound | 24 | 25 | 24 | 24 | c54128bb7315111e9d7e6082cfe12d17b136ba3f | bigcode/the-stack | train |
e5f13d2182f86b59b85b72f7 | train | class | class Generator(nn.Module):
def __init__(self, graphSizes, adjValues, edgeOnes, E_starts, E_ends,
upAsgnIndices, upAsgnValues,
dsp=4, dspe=512, ch=64):
# dsp - dimensions of the simulation parameters
# dspe - dimensions of the simulation parameters' encode
... | class Generator(nn.Module):
| def __init__(self, graphSizes, adjValues, edgeOnes, E_starts, E_ends,
upAsgnIndices, upAsgnValues,
dsp=4, dspe=512, ch=64):
# dsp - dimensions of the simulation parameters
# dspe - dimensions of the simulation parameters' encode
# ch - channel multiplie... | # Generator architecture
import torch
import torch.nn as nn
import torch.nn.functional as F
from resblock import BasicBlockGenerator, LastBlockGenerator
from layer import *
import pdb
class Generator(nn.Module):
| 45 | 256 | 1,191 | 5 | 39 | trainsn/GNN-Surrogate | model/generator.py | Python | Generator | Generator | 12 | 91 | 12 | 12 | 1ad8a7eee075e62d241802fa7aa768ceaf013b96 | bigcode/the-stack | train |
a328a0709e5e95f8ce720755 | train | function | def test_follow_lnk():
pass
| def test_follow_lnk():
| pass
| {"name": "not-available"}])
with pytest.raises(ConnectionError):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "Liesl-Mock-EEG"}])
def test_add_to_path():
pass
def test_follow_lnk():
| 64 | 64 | 9 | 6 | 57 | jasmainak/pyliesl | tests/files/recorder/test_manager.py | Python | test_follow_lnk | test_follow_lnk | 20 | 21 | 20 | 20 | 4ddf53a5db88d176886213d8bf68bd4ade708591 | bigcode/the-stack | train |
5680461f4813e315d4b11401 | train | function | def test_validate_raises(mock, markermock):
with pytest.raises(ConnectionError):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "not-available"}])
with pytest.raises(ConnectionError):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "Liesl-Mock-EEG"}])
| def test_validate_raises(mock, markermock):
| with pytest.raises(ConnectionError):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "not-available"}])
with pytest.raises(ConnectionError):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "Liesl-Mock-EEG"}])
| liesl.files.labrecorder.manager import *
import pytest
def test_validate(mock, markermock):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "Liesl-Mock-Marker"}])
def test_validate_raises(mock, markermock):
| 64 | 64 | 86 | 11 | 53 | jasmainak/pyliesl | tests/files/recorder/test_manager.py | Python | test_validate_raises | test_validate_raises | 9 | 13 | 9 | 9 | 8e593499863ec465e1d0a6072a24b8d196710141 | bigcode/the-stack | train |
809c5367371431382c6fe4f8 | train | function | @pytest.mark.parametrize("fname", ["test.txt", "LabRecorderCLI.exe"])
def test_find_file(tmpdir, fname):
p = tmpdir.mkdir("sub").join(fname)
p.write("content")
find_file(path=str(tmpdir), file=fname)
| @pytest.mark.parametrize("fname", ["test.txt", "LabRecorderCLI.exe"])
def test_find_file(tmpdir, fname):
| p = tmpdir.mkdir("sub").join(fname)
p.write("content")
find_file(path=str(tmpdir), file=fname)
| l-Mock-EEG"}, {"name": "Liesl-Mock-EEG"}])
def test_add_to_path():
pass
def test_follow_lnk():
pass
@pytest.mark.parametrize("fname", ["test.txt", "LabRecorderCLI.exe"])
def test_find_file(tmpdir, fname):
| 64 | 64 | 55 | 25 | 38 | jasmainak/pyliesl | tests/files/recorder/test_manager.py | Python | test_find_file | test_find_file | 24 | 28 | 24 | 25 | f65616e8fefb74495710c905e2e91de2df3050e6 | bigcode/the-stack | train |
a3479d2bef36dff925131d44 | train | function | def test_add_to_path():
pass
| def test_add_to_path():
| pass
| Liesl-Mock-EEG"}, {"name": "not-available"}])
with pytest.raises(ConnectionError):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "Liesl-Mock-EEG"}])
def test_add_to_path():
| 64 | 64 | 9 | 6 | 58 | jasmainak/pyliesl | tests/files/recorder/test_manager.py | Python | test_add_to_path | test_add_to_path | 16 | 17 | 16 | 16 | c503421e18cec06e0ba74f1b46d8e90a1cbb2d57 | bigcode/the-stack | train |
07a9ca90b05d6180f912b9de | train | function | def test_validate(mock, markermock):
sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "Liesl-Mock-Marker"}])
| def test_validate(mock, markermock):
| sids = validate([{"name": "Liesl-Mock-EEG"}, {"name": "Liesl-Mock-Marker"}])
| from liesl.files.labrecorder.manager import *
import pytest
def test_validate(mock, markermock):
| 22 | 64 | 41 | 9 | 12 | jasmainak/pyliesl | tests/files/recorder/test_manager.py | Python | test_validate | test_validate | 5 | 6 | 5 | 5 | 970a2db9cfa3123bfa30f6788a7281de3e4d207b | bigcode/the-stack | train |
8eb6cb33a704fb156ba48a17 | train | class | class TestAttachment (unittest.TestCase):
def setUp(self):
self.att = attachment.Attachment(att_j['value'][0])
def test_isType(self):
self.assertTrue(self.att.isType('txt'))
def test_getType(self):
self.assertEqual(self.att.getType(),'.txt')
def test_save(self):
name = self.att.json['Name']
name1 = se... | class TestAttachment (unittest.TestCase):
| def setUp(self):
self.att = attachment.Attachment(att_j['value'][0])
def test_isType(self):
self.assertTrue(self.att.isType('txt'))
def test_getType(self):
self.assertEqual(self.att.getType(),'.txt')
def test_save(self):
name = self.att.json['Name']
name1 = self.newFileName(name)
self.att.json['Name'... | from O365 import attachment
import unittest
import json
import base64
from random import randint
att_rep = open('attachment.json','r').read()
att_j = json.loads(att_rep)
class TestAttachment (unittest.TestCase):
| 50 | 136 | 456 | 9 | 41 | rehanalam1/python-o365 | tests/test_attachment.py | Python | TestAttachment | TestAttachment | 11 | 67 | 11 | 12 | ecf1efcc8ab9910f35a12909c7abf792733a99c0 | bigcode/the-stack | train |
1c62e68365ff59b0c6f3934a | train | class | class SVMSK(DetektorModel):
@classmethod
def _class_name(cls):
return "Support Vector Machine (Scikit-learn)"
def __init__(self, tensor_provider, use_bow=True, use_embedsum=False, display_step=1, verbose=False,
name_formatter="{}"):
"""
:param TensorProvider tensor_... | class SVMSK(DetektorModel):
@classmethod
| def _class_name(cls):
return "Support Vector Machine (Scikit-learn)"
def __init__(self, tensor_provider, use_bow=True, use_embedsum=False, display_step=1, verbose=False,
name_formatter="{}"):
"""
:param TensorProvider tensor_provider:
:param bool verbose:
... | import numpy as np
from util.tensor_provider import TensorProvider
from models.model_base import DetektorModel
from sklearn.svm import SVC
class SVMSK(DetektorModel):
@classmethod
| 43 | 166 | 554 | 13 | 29 | sfvnDTU/deep_detektor | models/baselines/svm.py | Python | SVMSK | SVMSK | 7 | 77 | 7 | 8 | b53496a5df0915f8accada3e2499b68cc5a4c183 | bigcode/the-stack | train |
f2e7aac45950080074ff2c02 | train | class | class CleanAndEmb(Tokenize):
def __init__(self):
super(CleanAndEmb, self).__init__()
self.model = load_bert_base_model()
def clean_sents(self, tokenized_str: list):
# For now we only remove \r and \n, as we might remove context useable by the BERT model
pp_special_chars... | class CleanAndEmb(Tokenize):
| def __init__(self):
super(CleanAndEmb, self).__init__()
self.model = load_bert_base_model()
def clean_sents(self, tokenized_str: list):
# For now we only remove \r and \n, as we might remove context useable by the BERT model
pp_special_chars = lambda sent: re.sub("\s+", " ",... | self.pca = pickle.load(f)
def reduce_dim(self, embedding: np.ndarray):
return self.pca.transform(embedding.reshape(1,-1))[0]
class Tokenize(object):
def load_tokenizer(self):
try:
self.tokenizer = nltk.data.load("tokenizers/punkt/danish.pickle")
except LookupError... | 170 | 171 | 572 | 8 | 161 | Lantow/embed_and_reduce | embed_and_reduce/emb_and_reduce.py | Python | CleanAndEmb | CleanAndEmb | 41 | 92 | 41 | 42 | 9192fa6466fca03ebcb315d59b85dde234a2585e | bigcode/the-stack | train |
2204cdaf51d31e184df93d93 | train | class | class Tokenize(object):
def load_tokenizer(self):
try:
self.tokenizer = nltk.data.load("tokenizers/punkt/danish.pickle")
except LookupError:
nltk.download('punkt')
self.tokenizer = nltk.data.load("tokenizers/punkt/danish.pickle")
except Exception as E... | class Tokenize(object):
| def load_tokenizer(self):
try:
self.tokenizer = nltk.data.load("tokenizers/punkt/danish.pickle")
except LookupError:
nltk.download('punkt')
self.tokenizer = nltk.data.load("tokenizers/punkt/danish.pickle")
except Exception as E:
raise E
de... | .abspath(".") + "/pca.pkl"
with open(file_path, "rb") as f:
self.pca = pickle.load(f)
def reduce_dim(self, embedding: np.ndarray):
return self.pca.transform(embedding.reshape(1,-1))[0]
class Tokenize(object):
| 64 | 64 | 126 | 6 | 58 | Lantow/embed_and_reduce | embed_and_reduce/emb_and_reduce.py | Python | Tokenize | Tokenize | 21 | 38 | 21 | 22 | 909367c2a0668b76d3be3903b097f720d9a4e43a | bigcode/the-stack | train |
0d2e362eecda6b611f307b61 | train | class | class EmbAndReduce(CleanAndEmb, ReduceDim):
def embed_and_reduce(self, search_string):
embedding = self.clean_and_embed(search_string)
return self.reduce_dim(embedding)
| class EmbAndReduce(CleanAndEmb, ReduceDim):
| def embed_and_reduce(self, search_string):
embedding = self.clean_and_embed(search_string)
return self.reduce_dim(embedding)
| else:
raise E
def clean_and_embed(self, search_string: str):
tokens = self.tokenize_raw_text_data(search_string)
clean_sentences = self.clean_sents(tokens)
return self.embed_text(clean_sentences)
class EmbAndReduce(CleanAndEmb, ReduceDim):
| 63 | 64 | 40 | 12 | 51 | Lantow/embed_and_reduce | embed_and_reduce/emb_and_reduce.py | Python | EmbAndReduce | EmbAndReduce | 94 | 98 | 94 | 95 | 47712661e38a99c4ed71965cbba91b410e83dfbf | bigcode/the-stack | train |
a56fd476624232a57fbf6f7d | train | class | class ReduceDim(object):
def __init__(self):
file_path = path.abspath(".") + "/pca.pkl"
with open(file_path, "rb") as f:
self.pca = pickle.load(f)
def reduce_dim(self, embedding: np.ndarray):
return self.pca.transform(embedding.reshape(1,-1))[0]
| class ReduceDim(object):
| def __init__(self):
file_path = path.abspath(".") + "/pca.pkl"
with open(file_path, "rb") as f:
self.pca = pickle.load(f)
def reduce_dim(self, embedding: np.ndarray):
return self.pca.transform(embedding.reshape(1,-1))[0]
| from danlp.models import load_bert_base_model
import numpy as np
import nltk
import re
import pickle
from os import path
#import glob
#from pathlib import Path
class ReduceDim(object):
| 44 | 64 | 76 | 6 | 37 | Lantow/embed_and_reduce | embed_and_reduce/emb_and_reduce.py | Python | ReduceDim | ReduceDim | 11 | 19 | 11 | 12 | 84a88c02b3ca310e98eca1dff7a71a4af224cefa | bigcode/the-stack | train |
781bcd922949a6cf57923146 | train | function | def _load_coins(coins_json_name: str) -> Dict[str, CoinInfo]:
raw_coins_dict = json.loads(open(coins_json_name).read())
ret = {}
for chain_code, coins in raw_coins_dict.items():
for coin in coins:
coin_info = CoinInfo(chain_code=chain_code, **coin)
ret[coin_info.code] = coin... | def _load_coins(coins_json_name: str) -> Dict[str, CoinInfo]:
| raw_coins_dict = json.loads(open(coins_json_name).read())
ret = {}
for chain_code, coins in raw_coins_dict.items():
for coin in coins:
coin_info = CoinInfo(chain_code=chain_code, **coin)
ret[coin_info.code] = coin_info
return ret
| (open(chains_json_name).read())
ret = {}
for config in raw_chains:
chain_info = ChainInfo(**config)
ret[chain_info.chain_code] = chain_info
return ret
def _load_coins(coins_json_name: str) -> Dict[str, CoinInfo]:
| 64 | 64 | 88 | 19 | 44 | Umiiii/electrum | electrum_gui/common/coin/registry.py | Python | _load_coins | _load_coins | 19 | 28 | 19 | 19 | 9fbfaeb946a3fb2cbebb8d440f34f09a271bd4c6 | bigcode/the-stack | train |
9e9b2e12cd35b0b2c8b64d59 | train | function | def _load_chains(chains_json_name: str) -> Dict[str, ChainInfo]:
raw_chains = json.loads(open(chains_json_name).read())
ret = {}
for config in raw_chains:
chain_info = ChainInfo(**config)
ret[chain_info.chain_code] = chain_info
return ret
| def _load_chains(chains_json_name: str) -> Dict[str, ChainInfo]:
| raw_chains = json.loads(open(chains_json_name).read())
ret = {}
for config in raw_chains:
chain_info = ChainInfo(**config)
ret[chain_info.chain_code] = chain_info
return ret
| import json
import os
from typing import Dict
from electrum_gui.common.coin.data import ChainInfo, CoinInfo
def _load_chains(chains_json_name: str) -> Dict[str, ChainInfo]:
| 44 | 64 | 71 | 19 | 24 | Umiiii/electrum | electrum_gui/common/coin/registry.py | Python | _load_chains | _load_chains | 8 | 16 | 8 | 8 | 70fdc361060e35bd98486585299498e0326b2934 | bigcode/the-stack | train |
6483afd3b401f2872b841968 | train | function | def main():
from pytools import Table
tbl = Table()
tbl.add_row(("type", "size [MiB]", "time [ms]", "mem.bw [GB/s]"))
from random import shuffle
for dtype_out in [numpy.float32, numpy.float64]:
for ex in range(15,27):
sz = 1 << ex
print(sz)
from pycuda.c... | def main():
| from pytools import Table
tbl = Table()
tbl.add_row(("type", "size [MiB]", "time [ms]", "mem.bw [GB/s]"))
from random import shuffle
for dtype_out in [numpy.float32, numpy.float64]:
for ex in range(15,27):
sz = 1 << ex
print(sz)
from pycuda.curandom impo... | from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import pycuda.autoinit
import pycuda.gpuarray as gpuarray
import pycuda.driver as cuda
import numpy
from six.moves import range
def main():
| 59 | 106 | 354 | 3 | 55 | dariodsa/pycuda | test/undistributed/reduction-perf.py | Python | main | main | 12 | 62 | 12 | 12 | d6a5671cf56db8f5b3f5de629341bafb9c4289a1 | bigcode/the-stack | train |
19e037a97af341dc33db954f | train | function | @verbose
def rescale(data, times, baseline, mode, verbose=None, copy=True):
"""Rescale aka baseline correct data
Parameters
----------
data : array
It can be of any shape. The only constraint is that the last
dimension should be time.
times : 1D array
Time instants is second... | @verbose
def rescale(data, times, baseline, mode, verbose=None, copy=True):
| """Rescale aka baseline correct data
Parameters
----------
data : array
It can be of any shape. The only constraint is that the last
dimension should be time.
times : 1D array
Time instants is seconds.
baseline : tuple or list of length 2, or None
The time interv... | """Util function to baseline correct data
"""
# Authors: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
import numpy as np
from .utils import logger, verbose
@verbose
def rescale(data, times, baseline, mode, verbose=None, copy=True):
| 69 | 205 | 685 | 20 | 48 | Anevar/mne-python | mne/baseline.py | Python | rescale | rescale | 13 | 89 | 13 | 14 | ff65d61c7616e6085b4364464ea41e2b49817366 | bigcode/the-stack | train |
901f029c0844e77b62773b68 | train | function | def create_presigned_url(object_name):
"""Generate a presigned URL to share an S3 object with a capped expiration of 60 seconds
:param object_name: string
:return: Presigned URL as string. If error, returns None.
"""
s3_client = boto3.client('s3',
region_name=os.environ... | def create_presigned_url(object_name):
| """Generate a presigned URL to share an S3 object with a capped expiration of 60 seconds
:param object_name: string
:return: Presigned URL as string. If error, returns None.
"""
s3_client = boto3.client('s3',
region_name=os.environ.get('S3_PERSISTENCE_REGION'),
... | import logging
import os
import boto3
from botocore.exceptions import ClientError
def create_presigned_url(object_name):
| 27 | 64 | 193 | 8 | 18 | sysfort-inc/github-alexa-demo | lambda/utils.py | Python | create_presigned_url | create_presigned_url | 7 | 27 | 7 | 7 | 39fd96910e0768f70cdc75ba68f840823e4ab13e | bigcode/the-stack | train |
ecb54a4ffdd7c5bb0d61d2f8 | train | function | @pytest.fixture(params=all_virtual_indicators())
def virtual_indicator(request):
return request.param
| @pytest.fixture(params=all_virtual_indicators())
def virtual_indicator(request):
| return request.param
| mod in ["anuclim", "cf", "icclim"]:
for name, ind in getattr(indicators, mod).iter_indicators():
yield pytest.param((mod, name, ind), id=f"{mod}.{name}")
@pytest.fixture(params=all_virtual_indicators())
def virtual_indicator(request):
| 63 | 64 | 19 | 14 | 49 | fossabot/xclim | xclim/testing/tests/test_modules.py | Python | virtual_indicator | virtual_indicator | 22 | 24 | 22 | 23 | 3509a53f3169379fbb49929f83ef56c1a38e13c3 | bigcode/the-stack | train |
34afe3585a8723216cdd0921 | train | function | def test_default_modules_exist():
from xclim.indicators import anuclim, cf, icclim # noqa
assert hasattr(icclim, "TG")
assert hasattr(anuclim, "P1_AnnMeanTemp")
assert hasattr(anuclim, "P19_PrecipColdestQuarter")
assert hasattr(cf, "fg")
assert len(list(icclim.iter_indicators())) == 55
... | def test_default_modules_exist():
| from xclim.indicators import anuclim, cf, icclim # noqa
assert hasattr(icclim, "TG")
assert hasattr(anuclim, "P1_AnnMeanTemp")
assert hasattr(anuclim, "P19_PrecipColdestQuarter")
assert hasattr(cf, "fg")
assert len(list(icclim.iter_indicators())) == 55
assert len(list(anuclim.iter_indic... | icclim"]:
for name, ind in getattr(indicators, mod).iter_indicators():
yield pytest.param((mod, name, ind), id=f"{mod}.{name}")
@pytest.fixture(params=all_virtual_indicators())
def virtual_indicator(request):
return request.param
def test_default_modules_exist():
| 64 | 64 | 110 | 6 | 57 | fossabot/xclim | xclim/testing/tests/test_modules.py | Python | test_default_modules_exist | test_default_modules_exist | 27 | 38 | 27 | 27 | 2e04db48967eda109876d27985b9d81bac6e01cb | bigcode/the-stack | train |
cddef70c124c6d39539c21e2 | train | class | class TestOfficalYaml(yamale.YamaleTestCase):
base_dir = str(Path(__file__).parent.parent.parent / "data")
schema = "schema.yml"
yaml = ["cf.yml", "anuclim.yml", "icclim.yml"]
def test_all(self):
assert self.validate()
| class TestOfficalYaml(yamale.YamaleTestCase):
| base_dir = str(Path(__file__).parent.parent.parent / "data")
schema = "schema.yml"
yaml = ["cf.yml", "anuclim.yml", "icclim.yml"]
def test_all(self):
assert self.validate()
| .assert_equal(out1[0], out2[0])
# Check that missing was not modified even with injecting `freq`.
assert ex1.RX5day.missing == indicators.atmos.max_n_day_precipitation_amount.missing
class TestOfficalYaml(yamale.YamaleTestCase):
| 64 | 64 | 67 | 14 | 49 | fossabot/xclim | xclim/testing/tests/test_modules.py | Python | TestOfficalYaml | TestOfficalYaml | 103 | 109 | 103 | 103 | b4e0e32a7b31bb949cb4377ca07ab5168db95d99 | bigcode/the-stack | train |
e969a71116319ce76e486b93 | train | function | def all_virtual_indicators():
for mod in ["anuclim", "cf", "icclim"]:
for name, ind in getattr(indicators, mod).iter_indicators():
yield pytest.param((mod, name, ind), id=f"{mod}.{name}")
| def all_virtual_indicators():
| for mod in ["anuclim", "cf", "icclim"]:
for name, ind in getattr(indicators, mod).iter_indicators():
yield pytest.param((mod, name, ind), id=f"{mod}.{name}")
| array as xr
import yamale
from xclim import indicators
from xclim.core.indicator import build_indicator_module_from_yaml
from xclim.core.options import set_options
from xclim.core.utils import InputKind
from xclim.testing import open_dataset
def all_virtual_indicators():
| 64 | 64 | 57 | 6 | 57 | fossabot/xclim | xclim/testing/tests/test_modules.py | Python | all_virtual_indicators | all_virtual_indicators | 16 | 19 | 16 | 16 | e6360c3f1c53368bfb92fa639cbc05159c31ea93 | bigcode/the-stack | train |
1d2f5a3c5a04adfeedf640bb | train | function | @pytest.mark.requires_docs
def test_custom_indices():
# Use the example in the Extending Xclim notebook for testing.
nbpath = Path(__file__).parent.parent.parent.parent / "docs" / "notebooks"
schema = yamale.make_schema(
Path(__file__).parent.parent.parent / "data" / "schema.yml"
)
data = y... | @pytest.mark.requires_docs
def test_custom_indices():
# Use the example in the Extending Xclim notebook for testing.
| nbpath = Path(__file__).parent.parent.parent.parent / "docs" / "notebooks"
schema = yamale.make_schema(
Path(__file__).parent.parent.parent / "data" / "schema.yml"
)
data = yamale.make_data(nbpath / "example.yml")
yamale.validate(schema, data)
pr = open_dataset("ERA5/daily_surface_canc... | warn"):
# skip when missing default values
mod, indname, ind = virtual_indicator
for name, param in ind.parameters.items():
if param.kind is not InputKind.DATASET and (
param.default in (None, _empty)
or (param.default == name and name not in atmosds)
... | 124 | 124 | 415 | 26 | 98 | fossabot/xclim | xclim/testing/tests/test_modules.py | Python | test_custom_indices | test_custom_indices | 57 | 100 | 57 | 59 | 75fef83da7e4dbf5ba1b9aa3612a1c7783de70a1 | bigcode/the-stack | train |
347545d852aa0f64b4d224a8 | train | function | @pytest.mark.slow
def test_encoding():
import sys
import _locale
# remove xclim
del sys.modules["xclim"]
# patch so that the default encoding is not UTF-8
old = _locale.nl_langinfo
_locale.nl_langinfo = lambda x: "GBK"
try:
import xclim # noqa
finally:
# Put the ... | @pytest.mark.slow
def test_encoding():
| import sys
import _locale
# remove xclim
del sys.modules["xclim"]
# patch so that the default encoding is not UTF-8
old = _locale.nl_langinfo
_locale.nl_langinfo = lambda x: "GBK"
try:
import xclim # noqa
finally:
# Put the correct function back
_locale.n... | cf.yml", "anuclim.yml", "icclim.yml"]
def test_all(self):
assert self.validate()
# It's not really slow, but this is an unstable test (when it fails) and we might not want to execute it on all builds
@pytest.mark.slow
def test_encoding():
| 64 | 64 | 103 | 9 | 54 | fossabot/xclim | xclim/testing/tests/test_modules.py | Python | test_encoding | test_encoding | 113 | 130 | 113 | 114 | ef2230c77904bcca7fba0a00a0acc152c1dca313 | bigcode/the-stack | train |
a2317833eccc1d5a95a11af4 | train | function | @pytest.mark.slow
def test_virtual_modules(virtual_indicator, atmosds):
with set_options(cf_compliance="warn"):
# skip when missing default values
mod, indname, ind = virtual_indicator
for name, param in ind.parameters.items():
if param.kind is not InputKind.DATASET and (
... | @pytest.mark.slow
def test_virtual_modules(virtual_indicator, atmosds):
| with set_options(cf_compliance="warn"):
# skip when missing default values
mod, indname, ind = virtual_indicator
for name, param in ind.parameters.items():
if param.kind is not InputKind.DATASET and (
param.default in (None, _empty)
or (param.defau... | "fg")
assert len(list(icclim.iter_indicators())) == 55
assert len(list(anuclim.iter_indicators())) == 19
# Not testing cf because many indices are waiting to be implemented.
@pytest.mark.slow
def test_virtual_modules(virtual_indicator, atmosds):
| 64 | 64 | 122 | 16 | 48 | fossabot/xclim | xclim/testing/tests/test_modules.py | Python | test_virtual_modules | test_virtual_modules | 42 | 54 | 42 | 43 | 55cac4d84c3061896e049d0de8aa528276c0fd08 | bigcode/the-stack | train |
47ad1e01e4b4b6ce447ff101 | train | function | def SocPokecRelationships(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/networkrepository",
version: str = "latest",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new instance of the ... | def SocPokecRelationships(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/networkrepository",
version: str = "latest",
**additional_graph_kwargs: Dict
) -> Graph:
| """Return new instance of the soc-pokec-relationships graph.
The graph is automatically retrieved from the NetworkRepository repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool... | Nesreen K. Ahmed},
booktitle = {AAAI},
url={http://networkrepository.com},
year={2015}
}
```
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen import Graph # pylint: disable=import-error
def SocPokecRelationships(
directed: bool = False,... | 140 | 140 | 467 | 74 | 65 | AnacletoLAB/ensmallen_graph | bindings/python/ensmallen/datasets/networkrepository/socpokecrelationships.py | Python | SocPokecRelationships | SocPokecRelationships | 27 | 94 | 27 | 36 | d8eee939df066d29aeecac53ffb5dd3719315adc | bigcode/the-stack | train |
aab768120c298ee911dadc21 | train | class | class dummy_row_test(openram_test):
def runTest(self):
globals.init_openram("config_{0}".format(OPTS.tech_name))
debug.info(2, "Testing dummy row for 6t_cell")
a = factory.create(module_type="dummy_array", rows=1, cols=4)
self.local_check(a)
debug.info(2, "Testing dummy co... | class dummy_row_test(openram_test):
| def runTest(self):
globals.init_openram("config_{0}".format(OPTS.tech_name))
debug.info(2, "Testing dummy row for 6t_cell")
a = factory.create(module_type="dummy_array", rows=1, cols=4)
self.local_check(a)
debug.info(2, "Testing dummy column for 6t_cell")
a = factor... | 9 Regents of the University of California
# All rights reserved.
#
import unittest
from testutils import *
import sys,os
sys.path.append(os.getenv("OPENRAM_HOME"))
import globals
from globals import OPTS
from sram_factory import factory
import debug
class dummy_row_test(openram_test):
| 64 | 64 | 119 | 8 | 55 | mguthaus/OpenRAM | compiler/tests/05_dummy_array_test.py | Python | dummy_row_test | dummy_row_test | 16 | 29 | 16 | 17 | f1ea7ccce649ea5e6666ca485d10674c5fdb6392 | bigcode/the-stack | train |
127dc1675e58c554ba447bef | train | function | def solution(n):
hh, mm = n // 60, n % 60
return hh // 10 + hh % 10 + mm // 10 + mm % 10
| def solution(n):
| hh, mm = n // 60, n % 60
return hh // 10 + hh % 10 + mm // 10 + mm % 10
| def solution(n):
| 4 | 64 | 41 | 4 | 0 | tinesife94/random | codesignal/arcade/python/the_core_07_late_ride.py | Python | solution | solution | 1 | 3 | 1 | 1 | 89b642be15dc2c172040d871800e5a893798ef67 | bigcode/the-stack | train |
718c26f819725c4953fce7b9 | train | function | def reject_outliers(data, m):
if len(data) > 2:
return data[abs(data - np.mean(data)) < m * np.std(data)]
else:
return data
| def reject_outliers(data, m):
| if len(data) > 2:
return data[abs(data - np.mean(data)) < m * np.std(data)]
else:
return data
| data/2018_10-1JV/'
names = listdir(Directory)
names_fs = []
names_rs = []
names_hold = []
#%%
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def reject_outliers(data, m):
| 64 | 64 | 42 | 8 | 55 | rstoddard24/PVtools | PVtools/JV/JV_DOE_analysis_100118.py | Python | reject_outliers | reject_outliers | 60 | 64 | 60 | 60 | e0d1db06c99bbc09753a6c3d978fdfdd8ae65a7a | bigcode/the-stack | train |
4c64c3b12c5967162c7556e7 | train | function | def is_number(s):
try:
float(s)
return True
except ValueError:
return False
| def is_number(s):
| try:
float(s)
return True
except ValueError:
return False
| : 22}
mpl.rc('font', **font)
mpl.rc('axes', linewidth=3)
Directory = '../../data/JVdata/2018_10-1JV/'
names = listdir(Directory)
names_fs = []
names_rs = []
names_hold = []
#%%
def is_number(s):
| 64 | 64 | 25 | 5 | 59 | rstoddard24/PVtools | PVtools/JV/JV_DOE_analysis_100118.py | Python | is_number | is_number | 53 | 58 | 53 | 53 | 7fb2138879eebb4d11262f792c55f2d5538d2923 | bigcode/the-stack | train |
c36cf44af3609d683723e726 | train | function | def _is_submitted():
"""Consider the form submitted if there is an active request and
the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
"""
return bool(request) and request.method in SUBMIT_METHODS
| def _is_submitted():
| """Consider the form submitted if there is an active request and
the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
"""
return bool(request) and request.method in SUBMIT_METHODS
| ):
f = getattr(self, f, None)
if f is None or not isinstance(f.widget, HiddenInput):
continue
yield f
return Markup(
u'\n'.join(text_type(f) for f in hidden_fields(fields or self))
)
def _is_submitted():
| 64 | 64 | 57 | 6 | 58 | philfreo/flask-wtf | flask_wtf/form.py | Python | _is_submitted | _is_submitted | 138 | 143 | 138 | 138 | fc1188fffb9afa37bdc963c26efd65974b316caf | bigcode/the-stack | train |
3160bd0483fbefd8018648f0 | train | class | class FlaskForm(Form):
"""Flask-specific subclass of WTForms :class:`~wtforms.form.Form`.
If ``formdata`` is not specified, this will use :attr:`flask.request.form`
and :attr:`flask.request.files`. Explicitly pass ``formdata=None`` to
prevent this.
"""
class Meta(DefaultMeta):
csrf_cl... | class FlaskForm(Form):
| """Flask-specific subclass of WTForms :class:`~wtforms.form.Form`.
If ``formdata`` is not specified, this will use :attr:`flask.request.form`
and :attr:`flask.request.files`. Explicitly pass ``formdata=None`` to
prevent this.
"""
class Meta(DefaultMeta):
csrf_class = _FlaskFormCSRF
... | import warnings
from flask import current_app, request, session
from jinja2 import Markup
from werkzeug.datastructures import CombinedMultiDict, ImmutableMultiDict
from werkzeug.utils import cached_property
from wtforms import Form
from wtforms.meta import DefaultMeta
from wtforms.widgets import HiddenInput
from ._co... | 149 | 237 | 791 | 5 | 144 | philfreo/flask-wtf | flask_wtf/form.py | Python | FlaskForm | FlaskForm | 24 | 135 | 24 | 24 | 4ceeb29c3267b4b2af2fb617ddb54ee630ea44b0 | bigcode/the-stack | train |
8f637d018bfc310f7a300977 | train | class | class Form(FlaskForm):
"""
.. deprecated:: 0.13
Renamed to :class:`~flask_wtf.FlaskForm`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(FlaskWTFDeprecationWarning(
'"flask_wtf.Form" has been renamed to "FlaskForm" '
'and will be removed in 1.0.'
... | class Form(FlaskForm):
| """
.. deprecated:: 0.13
Renamed to :class:`~flask_wtf.FlaskForm`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(FlaskWTFDeprecationWarning(
'"flask_wtf.Form" has been renamed to "FlaskForm" '
'and will be removed in 1.0.'
), stacklevel=3)
... | def _is_submitted():
"""Consider the form submitted if there is an active request and
the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
"""
return bool(request) and request.method in SUBMIT_METHODS
class Form(FlaskForm):
| 64 | 64 | 112 | 7 | 56 | philfreo/flask-wtf | flask_wtf/form.py | Python | Form | Form | 146 | 157 | 146 | 146 | ee146b4f698a300870e38a2a4feabbf0c020e2a3 | bigcode/the-stack | train |
78ff474faf7c2144d8279a4c | train | function | def float16(val):
# Fraction is 10 LSB, Exponent middle 5, and Sign the MSB
frac = val & 0x03ff
exp = (val >> 10) & 0x1F
sign = val >> 15
if exp:
value = 2 ** (exp - 16) * (1 + float(frac) / 2**10)
else:
value = float(frac) / 2**9
if sign:
value *= -1
return va... | def float16(val):
# Fraction is 10 LSB, Exponent middle 5, and Sign the MSB
| frac = val & 0x03ff
exp = (val >> 10) & 0x1F
sign = val >> 15
if exp:
value = 2 ** (exp - 16) * (1 + float(frac) / 2**10)
else:
value = float(frac) / 2**9
if sign:
value *= -1
return value
| _data[0]
def two_comp16(val):
if val >> 15:
val = -(~val & 0x7fff) - 1
return val
def float16(val):
# Fraction is 10 LSB, Exponent middle 5, and Sign the MSB
| 64 | 64 | 121 | 26 | 37 | wqshen/MetPy | metpy/io/nexrad.py | Python | float16 | float16 | 647 | 661 | 647 | 648 | 9084dd470645dece3ac18725e0ba14a75b4476e8 | bigcode/the-stack | train |
2b6798070a57f45a4c537231 | train | function | def float_elem(ind1, ind2):
# Masking below in python will properly convert signed values to unsigned
return lambda seq: float32(seq[ind1] & 0xFFFF, seq[ind2] & 0xFFFF)
| def float_elem(ind1, ind2):
# Masking below in python will properly convert signed values to unsigned
| return lambda seq: float32(seq[ind1] & 0xFFFF, seq[ind2] & 0xFFFF)
| shift
if seq[ind2] < 0:
seq[ind2] += shift
return (seq[ind1] << 16) | seq[ind2]
return inner
def float_elem(ind1, ind2):
# Masking below in python will properly convert signed values to unsigned
| 64 | 64 | 51 | 24 | 39 | wqshen/MetPy | metpy/io/nexrad.py | Python | float_elem | float_elem | 691 | 693 | 691 | 692 | e9a868d1fec739a411f03bca50635c50d2677930 | bigcode/the-stack | train |
a1f823d30b92d61df34f3e4b | train | function | def scaled_elem(index, scale):
def inner(seq):
return seq[index] * scale
return inner
| def scaled_elem(index, scale):
| def inner(seq):
return seq[index] * scale
return inner
| >f', struct.pack('>HH', short1, short2))[0]
def date_elem(ind_days, ind_minutes):
def inner(seq):
return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000)
return inner
def scaled_elem(index, scale):
| 64 | 64 | 24 | 7 | 56 | wqshen/MetPy | metpy/io/nexrad.py | Python | scaled_elem | scaled_elem | 674 | 677 | 674 | 674 | 6596ff791eada1d12427dee0ac4194068e703662 | bigcode/the-stack | train |
22626ff2082d57c0ef215733 | train | class | class DigitalVILMapper(DataMapper):
def __init__(self, prod):
lin_scale = float16(prod.thresholds[0])
lin_offset = float16(prod.thresholds[1])
log_start = prod.thresholds[2]
log_scale = float16(prod.thresholds[3])
log_offset = float16(prod.thresholds[4])
self.lut = np... | class DigitalVILMapper(DataMapper):
| def __init__(self, prod):
lin_scale = float16(prod.thresholds[0])
lin_offset = float16(prod.thresholds[1])
log_start = prod.thresholds[2]
log_scale = float16(prod.thresholds[3])
log_offset = float16(prod.thresholds[4])
self.lut = np.empty((256,), dtype=np.float)
... | = 0.001
_min_data = 1
_max_data = 254
units = 'dBA'
class DigitalStormPrecipMapper(DigitalMapper):
units = 'inches'
_inc_scale = 0.01
class DigitalVILMapper(DataMapper):
| 64 | 64 | 194 | 8 | 55 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalVILMapper | DigitalVILMapper | 771 | 785 | 771 | 771 | 95a649f1ecffa241e477b7f418e59ba44f07faf8 | bigcode/the-stack | train |
96fc4ee0a7419c4c7d218bd1 | train | function | def bzip_blocks_decompress_all(data):
frames = bytearray()
offset = 0
while offset < len(data):
size_bytes = data[offset:offset + 4]
offset += 4
block_cmp_bytes = abs(Struct('>l').unpack(size_bytes)[0])
if block_cmp_bytes:
frames.extend(bz2.decompress(data[offset:... | def bzip_blocks_decompress_all(data):
| frames = bytearray()
offset = 0
while offset < len(data):
size_bytes = data[offset:offset + 4]
offset += 4
block_cmp_bytes = abs(Struct('>l').unpack(size_bytes)[0])
if block_cmp_bytes:
frames.extend(bz2.decompress(data[offset:offset + block_cmp_bytes]))
... | data = bytes(data)
while data:
decomp = zlib.decompressobj()
try:
frames.extend(decomp.decompress(data))
except zlib.error:
break
data = decomp.unused_data
return frames + data
def bzip_blocks_decompress_all(data):
| 64 | 64 | 114 | 9 | 54 | wqshen/MetPy | metpy/io/nexrad.py | Python | bzip_blocks_decompress_all | bzip_blocks_decompress_all | 65 | 78 | 65 | 65 | 2089aa1836b613d7b156556633f2bc06504df997 | bigcode/the-stack | train |
f2b777e9819ac88eb973c082 | train | function | def zlib_decompress_all_frames(data):
frames = bytearray()
data = bytes(data)
while data:
decomp = zlib.decompressobj()
try:
frames.extend(decomp.decompress(data))
except zlib.error:
break
data = decomp.unused_data
return frames + data
| def zlib_decompress_all_frames(data):
| frames = bytearray()
data = bytes(data)
while data:
decomp = zlib.decompressobj()
try:
frames.extend(decomp.decompress(data))
except zlib.error:
break
data = decomp.unused_data
return frames + data
| )
def scaler(scale):
def inner(val):
return val * scale
return inner
def angle(val):
return val * 360. / 2**16
def az_rate(val):
return val * 90. / 2**16
def zlib_decompress_all_frames(data):
| 64 | 64 | 71 | 9 | 54 | wqshen/MetPy | metpy/io/nexrad.py | Python | zlib_decompress_all_frames | zlib_decompress_all_frames | 52 | 62 | 52 | 52 | c0f26ea694bf141f33456fdd434765b3b64adb29 | bigcode/the-stack | train |
25519cc38987392f9499c06f | train | function | def combine_elem(ind1, ind2):
def inner(seq):
shift = 2**16
if seq[ind1] < 0:
seq[ind1] += shift
if seq[ind2] < 0:
seq[ind2] += shift
return (seq[ind1] << 16) | seq[ind2]
return inner
| def combine_elem(ind1, ind2):
| def inner(seq):
shift = 2**16
if seq[ind1] < 0:
seq[ind1] += shift
if seq[ind2] < 0:
seq[ind2] += shift
return (seq[ind1] << 16) | seq[ind2]
return inner
| def inner(seq):
return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000)
return inner
def scaled_elem(index, scale):
def inner(seq):
return seq[index] * scale
return inner
def combine_elem(ind1, ind2):
| 64 | 64 | 78 | 9 | 54 | wqshen/MetPy | metpy/io/nexrad.py | Python | combine_elem | combine_elem | 680 | 688 | 680 | 680 | 1845a13c590ab066ea4d61c4f648b54b7f94ac36 | bigcode/the-stack | train |
5554183c929e49b3727e26bc | train | class | class Level3XDRParser(Unpacker):
def __call__(self, code):
xdr = OrderedDict()
if code == 28:
xdr.update(self._unpack_prod_desc())
else:
log.warning('XDR: code %d not implemented', code)
# Check that we got it all
self.done()
return xdr
... | class Level3XDRParser(Unpacker):
| def __call__(self, code):
xdr = OrderedDict()
if code == 28:
xdr.update(self._unpack_prod_desc())
else:
log.warning('XDR: code %d not implemented', code)
# Check that we got it all
self.done()
return xdr
def unpack_string(self):
... | ,
14: _unpack_packet_special_graphic_symbol,
15: _unpack_packet_special_graphic_symbol,
16: _unpack_packet_digital_radial,
17: _unpack_packet_digital_precipitation,
18: _unpack_packet_digital_precipitation,
19: _... | 256 | 256 | 952 | 9 | 247 | wqshen/MetPy | metpy/io/nexrad.py | Python | Level3XDRParser | Level3XDRParser | 2,081 | 2,200 | 2,081 | 2,081 | a110d7f1279bcc53291ff1922d7ccf21d1e76b25 | bigcode/the-stack | train |
9449417a33b72243069710b3 | train | class | class DigitalHMCMapper(DataMapper):
labels = ['ND', 'BI', 'GC', 'IC', 'DS', 'WS', 'RA', 'HR',
'BD', 'GR', 'HA', 'UK', 'RF']
def __init__(self, prod):
self.lut = [self.MISSING] * 256
for i in range(10, 256):
self.lut[i] = i // 10
self.lut[150] = self.RANGE_FOLD
... | class DigitalHMCMapper(DataMapper):
| labels = ['ND', 'BI', 'GC', 'IC', 'DS', 'WS', 'RA', 'HR',
'BD', 'GR', 'HA', 'UK', 'RF']
def __init__(self, prod):
self.lut = [self.MISSING] * 256
for i in range(10, 256):
self.lut[i] = i // 10
self.lut[150] = self.RANGE_FOLD
self.lut = np.array(self.lut... | self.lut[1] = self.RANGE_FOLD
for i in range(leading_flags, max_data_val - trailing_flags):
self.lut[i] = (i - offset) / scale
self.lut = np.array(self.lut)
class DigitalHMCMapper(DataMapper):
| 64 | 64 | 122 | 8 | 56 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalHMCMapper | DigitalHMCMapper | 825 | 834 | 825 | 825 | 02b02e27702989cebd7a7faf748baafe43340e9c | bigcode/the-stack | train |
cf1346add330ea7168ab3a81 | train | function | def remap_status(val):
bad = BAD_DATA if val & 0xF0 else 0
val = val & 0x0F
if val == 0:
status = START_ELEVATION
elif val == 1:
status = 0
elif val == 2:
status = END_ELEVATION
elif val == 3:
status = START_ELEVATION | START_VOLUME
elif val == 4:
stat... | def remap_status(val):
| bad = BAD_DATA if val & 0xF0 else 0
val = val & 0x0F
if val == 0:
status = START_ELEVATION
elif val == 1:
status = 0
elif val == 2:
status = END_ELEVATION
elif val == 3:
status = START_ELEVATION | START_VOLUME
elif val == 4:
status = END_ELEVATION | EN... | frames
def nexrad_to_datetime(julian_date, ms_midnight):
# Subtracting one from julian_date is because epoch date is 1
return datetime.datetime.fromtimestamp((julian_date - 1) * day +
ms_midnight * milli)
def remap_status(val):
| 64 | 64 | 139 | 6 | 58 | wqshen/MetPy | metpy/io/nexrad.py | Python | remap_status | remap_status | 87 | 103 | 87 | 87 | 9eb9c39a548fa61c97ffda884fcca8c15b73acfd | bigcode/the-stack | train |
16ce55c31a04e5eedc185059 | train | function | @exporter.export
def is_precip_mode(vcp_num):
r'''Determine if the NEXRAD radar is operating in precipitation mode
Parameters
----------
vcp_num : int
The NEXRAD volume coverage pattern (VCP) number
Returns
-------
bool
True if the VCP corresponds to precipitation mode, Fal... | @exporter.export
def is_precip_mode(vcp_num):
| r'''Determine if the NEXRAD radar is operating in precipitation mode
Parameters
----------
vcp_num : int
The NEXRAD volume coverage pattern (VCP) number
Returns
-------
bool
True if the VCP corresponds to precipitation mode, False otherwise
'''
return not vcp_num //... | text'])
def _unpack_text(self):
return self.text_fmt(parameters=self._unpack_parameters(),
text=self.unpack_string())
_component_lookup = {1: _unpack_radial, 4: _unpack_text}
@exporter.export
def is_precip_mode(vcp_num):
| 64 | 64 | 93 | 14 | 50 | wqshen/MetPy | metpy/io/nexrad.py | Python | is_precip_mode | is_precip_mode | 2,203 | 2,217 | 2,203 | 2,204 | 9543d5c32254a69ed5f46759974f690a2314645c | bigcode/the-stack | train |
f931fb42a79b45b7c1c3f008 | train | function | def nexrad_to_datetime(julian_date, ms_midnight):
# Subtracting one from julian_date is because epoch date is 1
return datetime.datetime.fromtimestamp((julian_date - 1) * day +
ms_midnight * milli)
| def nexrad_to_datetime(julian_date, ms_midnight):
# Subtracting one from julian_date is because epoch date is 1
| return datetime.datetime.fromtimestamp((julian_date - 1) * day +
ms_midnight * milli)
| offset + block_cmp_bytes]))
offset += block_cmp_bytes
else:
frames.extend(size_bytes)
frames.extend(data[offset:])
return frames
def nexrad_to_datetime(julian_date, ms_midnight):
# Subtracting one from julian_date is because epoch date is 1
| 64 | 64 | 56 | 32 | 31 | wqshen/MetPy | metpy/io/nexrad.py | Python | nexrad_to_datetime | nexrad_to_datetime | 81 | 84 | 81 | 82 | b7d35b49325443d77c64639ded2e730c1ae3347b | bigcode/the-stack | train |
beb05fc5f9229c03d8eccb30 | train | function | def float32(short1, short2):
return struct.unpack('>f', struct.pack('>HH', short1, short2))[0]
| def float32(short1, short2):
| return struct.unpack('>f', struct.pack('>HH', short1, short2))[0]
| value = 2 ** (exp - 16) * (1 + float(frac) / 2**10)
else:
value = float(frac) / 2**9
if sign:
value *= -1
return value
def float32(short1, short2):
| 64 | 64 | 31 | 9 | 54 | wqshen/MetPy | metpy/io/nexrad.py | Python | float32 | float32 | 664 | 665 | 664 | 664 | a5018a383b7f9651a1ccaf53322ac47b162313bf | bigcode/the-stack | train |
31e43a5a06920deaa3d909a7 | train | function | def version(val):
if val / 100. > 2.:
ver = val / 100.
else:
ver = val / 10.
return '{:.1f}'.format(ver)
| def version(val):
| if val / 100. > 2.:
ver = val / 100.
else:
ver = val / 10.
return '{:.1f}'.format(ver)
| Struct, Enum, IOBuffer, NamedStruct, bits_to_code
exporter = Exporter(globals())
log = logging.getLogger("metpy.io.nexrad")
log.addHandler(logging.StreamHandler()) # Python 2.7 needs a handler set
log.setLevel(logging.WARNING)
def version(val):
| 64 | 64 | 45 | 4 | 60 | wqshen/MetPy | metpy/io/nexrad.py | Python | version | version | 30 | 35 | 30 | 30 | f78e03adc17d8c727d541983c3be85cdc6f630cc | bigcode/the-stack | train |
d89d3c89c02a80af29e794f4 | train | class | class GenericDigitalMapper(DataMapper):
def __init__(self, prod):
scale = float32(prod.thresholds[0], prod.thresholds[1])
offset = float32(prod.thresholds[2], prod.thresholds[3])
max_data_val = prod.thresholds[5]
leading_flags = prod.thresholds[6]
trailing_flags = prod.thresh... | class GenericDigitalMapper(DataMapper):
| def __init__(self, prod):
scale = float32(prod.thresholds[0], prod.thresholds[1])
offset = float32(prod.thresholds[2], prod.thresholds[3])
max_data_val = prod.thresholds[5]
leading_flags = prod.thresholds[6]
trailing_flags = prod.thresholds[7]
self.lut = [self.MISSING... | (i & topped_mask)
self.lut = np.array(self.lut)
self.topped_lut = np.array(self.topped_lut)
def __call__(self, data_vals):
return self.lut[data_vals], self.topped_lut[data_vals]
class GenericDigitalMapper(DataMapper):
| 64 | 64 | 160 | 7 | 57 | wqshen/MetPy | metpy/io/nexrad.py | Python | GenericDigitalMapper | GenericDigitalMapper | 807 | 822 | 807 | 807 | 6c84c81ea7b699969d46670fe34846463d87c5c6 | bigcode/the-stack | train |
59cc0228ed0c2fecf60cb45a | train | class | @exporter.export
class Level2File(object):
r'''A class that handles reading the NEXRAD Level 2 data and the various
messages that are contained within.
This class attempts to decode every byte that is in a given data file.
It supports both external compression, as well as the internal BZ2
compressi... | @exporter.export
class Level2File(object):
| r'''A class that handles reading the NEXRAD Level 2 data and the various
messages that are contained within.
This class attempts to decode every byte that is in a given data file.
It supports both external compression, as well as the internal BZ2
compression that is used.
Attributes
------... | _datetime(julian_date, ms_midnight):
# Subtracting one from julian_date is because epoch date is 1
return datetime.datetime.fromtimestamp((julian_date - 1) * day +
ms_midnight * milli)
def remap_status(val):
bad = BAD_DATA if val & 0xF0 else 0
val = val & 0x0... | 256 | 256 | 5,709 | 11 | 244 | wqshen/MetPy | metpy/io/nexrad.py | Python | Level2File | Level2File | 113 | 631 | 113 | 114 | a1baa7fac43aacee0da2528851c04e4f11e1d643 | bigcode/the-stack | train |
347b427ad97b912e45e1fcd3 | train | function | def reduce_lists(d):
for field in d:
old_data = d[field]
if len(old_data) == 1:
d[field] = old_data[0]
| def reduce_lists(d):
| for field in d:
old_data = d[field]
if len(old_data) == 1:
d[field] = old_data[0]
| , msg_hdr, size):
hdr_size = msg_hdr.size_hw * 2 - self.msg_hdr_fmt.size
assert size == hdr_size, ('Message type %d should be %d bytes but got %d' %
(msg_hdr.msg_type, size, hdr_size))
def reduce_lists(d):
| 64 | 64 | 38 | 5 | 59 | wqshen/MetPy | metpy/io/nexrad.py | Python | reduce_lists | reduce_lists | 634 | 638 | 634 | 634 | 7a7dba8495bd4ffb4a2db20d487ce0f2fc692aa9 | bigcode/the-stack | train |
26359501e1114d9fb94c4084 | train | class | class DataMapper(object):
# Need to find way to handle range folded
# RANGE_FOLD = -9999
RANGE_FOLD = float('nan')
MISSING = float('nan')
def __call__(self, data):
return self.lut[data]
| class DataMapper(object):
# Need to find way to handle range folded
# RANGE_FOLD = -9999
| RANGE_FOLD = float('nan')
MISSING = float('nan')
def __call__(self, data):
return self.lut[data]
| units
# Default is to use numpy array indexing to use LUT to change data bytes
# into physical values. Can also have a 'labels' attribute to give
# categorical labels
class DataMapper(object):
# Need to find way to handle range folded
# RANGE_FOLD = -9999
| 64 | 64 | 59 | 26 | 37 | wqshen/MetPy | metpy/io/nexrad.py | Python | DataMapper | DataMapper | 712 | 719 | 712 | 714 | 562275232f6cfc6eb91d03021251c6699f11a06b | bigcode/the-stack | train |
13ad80ca737fd26c1bf2ff82 | train | class | class EDRMapper(DataMapper):
def __init__(self, prod):
scale = prod.thresholds[0] / 1000.
offset = prod.thresholds[1] / 1000.
data_levels = prod.thresholds[2]
leading_flags = prod.thresholds[3]
self.lut = [self.MISSING] * data_levels
for i in range(leading_flags, data... | class EDRMapper(DataMapper):
| def __init__(self, prod):
scale = prod.thresholds[0] / 1000.
offset = prod.thresholds[1] / 1000.
data_levels = prod.thresholds[2]
leading_flags = prod.thresholds[3]
self.lut = [self.MISSING] * data_levels
for i in range(leading_flags, data_levels):
self.lu... | 256
for i in range(10, 256):
self.lut[i] = i // 10
self.lut[150] = self.RANGE_FOLD
self.lut = np.array(self.lut)
# 156, 157
class EDRMapper(DataMapper):
| 64 | 64 | 112 | 7 | 56 | wqshen/MetPy | metpy/io/nexrad.py | Python | EDRMapper | EDRMapper | 838 | 847 | 838 | 838 | 19854fb564363c585f78cb7bceac29cb8c3076b1 | bigcode/the-stack | train |
d831725ca7f112ff001c3f91 | train | class | class DigitalEETMapper(DataMapper):
def __init__(self, prod):
data_mask = prod.thresholds[0]
scale = prod.thresholds[1]
offset = prod.thresholds[2]
topped_mask = prod.thresholds[3]
self.lut = [self.MISSING] * 256
self.topped_lut = [False] * 256
for i in range(... | class DigitalEETMapper(DataMapper):
| def __init__(self, prod):
data_mask = prod.thresholds[0]
scale = prod.thresholds[1]
offset = prod.thresholds[2]
topped_mask = prod.thresholds[3]
self.lut = [self.MISSING] * 256
self.topped_lut = [False] * 256
for i in range(2, 256):
self.lut[i] = (... | 255)
self.lut[2:log_start] = (ind[2:log_start] - lin_offset) / lin_scale
self.lut[log_start:-1] = np.exp((ind[log_start:] - log_offset) / log_scale)
class DigitalEETMapper(DataMapper):
| 64 | 64 | 180 | 8 | 56 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalEETMapper | DigitalEETMapper | 788 | 804 | 788 | 788 | 2e0ec142f5a10cd1d2828dfc0eb0d573fe880c0d | bigcode/the-stack | train |
b0052c31dc98c8c14abc4b77 | train | function | def angle(val):
return val * 360. / 2**16
| def angle(val):
| return val * 360. / 2**16
| if val / 100. > 2.:
ver = val / 100.
else:
ver = val / 10.
return '{:.1f}'.format(ver)
def scaler(scale):
def inner(val):
return val * scale
return inner
def angle(val):
| 64 | 64 | 17 | 4 | 59 | wqshen/MetPy | metpy/io/nexrad.py | Python | angle | angle | 44 | 45 | 44 | 44 | b67fcd8d4c7bbab920482aa7e37224eb006468fc | bigcode/the-stack | train |
2ba30c2cd8554a42307d2898 | train | class | class DigitalVelMapper(DigitalMapper):
units = 'm/s'
range_fold = True
| class DigitalVelMapper(DigitalMapper):
| units = 'm/s'
range_fold = True
| 1)
for i in range(num_levels):
self.lut[i + self._min_data] = min_val + i * inc
self.lut = np.array(self.lut)
class DigitalRefMapper(DigitalMapper):
units = 'dBZ'
class DigitalVelMapper(DigitalMapper):
| 64 | 64 | 21 | 8 | 56 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalVelMapper | DigitalVelMapper | 749 | 751 | 749 | 749 | 29d6d58c79b415fcccebd314ec1c340160bc1c06 | bigcode/the-stack | train |
51ce23722c114bb1dd79a89d | train | class | class DigitalStormPrecipMapper(DigitalMapper):
units = 'inches'
_inc_scale = 0.01
| class DigitalStormPrecipMapper(DigitalMapper):
| units = 'inches'
_inc_scale = 0.01
| = 129
_max_data = 149
class PrecipArrayMapper(DigitalMapper):
_inc_scale = 0.001
_min_data = 1
_max_data = 254
units = 'dBA'
class DigitalStormPrecipMapper(DigitalMapper):
| 64 | 64 | 27 | 10 | 54 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalStormPrecipMapper | DigitalStormPrecipMapper | 766 | 768 | 766 | 766 | 82021e12174538d99042a40185c962e347e688d3 | bigcode/the-stack | train |
19ba8611dba2a5aa8f451b52 | train | class | @exporter.export
class Level3File(object):
r'''A class that handles reading the wide array of NEXRAD Level 3 (NIDS)
product files.
This class attempts to decode every byte that is in a given product file.
It supports all of the various compression formats that exist for these
products in the wild.
... | @exporter.export
class Level3File(object):
| r'''A class that handles reading the wide array of NEXRAD Level 3 (NIDS)
product files.
This class attempts to decode every byte that is in a given product file.
It supports all of the various compression formats that exist for these
products in the wild.
Attributes
----------
metadata... | label = self.lut_names[val]
if label in ('Blank', 'TH', 'ND'):
val = self.MISSING
elif label == 'RF':
val = self.RANGE_FOLD
elif codes >> 6:
val *= 0.01
label = '%.2f' % val
e... | 256 | 256 | 14,198 | 11 | 245 | wqshen/MetPy | metpy/io/nexrad.py | Python | Level3File | Level3File | 896 | 2,078 | 896 | 897 | 69815dceba40657d6f85d2394b4fa6cec46607e9 | bigcode/the-stack | train |
439cb6f561c827901813ad22 | train | class | class PrecipArrayMapper(DigitalMapper):
_inc_scale = 0.001
_min_data = 1
_max_data = 254
units = 'dBA'
| class PrecipArrayMapper(DigitalMapper):
| _inc_scale = 0.001
_min_data = 1
_max_data = 254
units = 'dBA'
| ):
units = 'dBZ'
class DigitalVelMapper(DigitalMapper):
units = 'm/s'
range_fold = True
class DigitalSPWMapper(DigitalVelMapper):
_min_data = 129
_max_data = 149
class PrecipArrayMapper(DigitalMapper):
| 64 | 64 | 42 | 9 | 54 | wqshen/MetPy | metpy/io/nexrad.py | Python | PrecipArrayMapper | PrecipArrayMapper | 759 | 763 | 759 | 759 | 73b7ec2751536ec43d7a19be8bd72fce7526d1c3 | bigcode/the-stack | train |
b18c394ff340109e78e8d61a | train | function | def high_byte(ind):
def inner(seq):
return seq[ind] >> 8
return inner
| def high_byte(ind):
| def inner(seq):
return seq[ind] >> 8
return inner
| seq[ind2]
return inner
def float_elem(ind1, ind2):
# Masking below in python will properly convert signed values to unsigned
return lambda seq: float32(seq[ind1] & 0xFFFF, seq[ind2] & 0xFFFF)
def high_byte(ind):
| 64 | 64 | 23 | 5 | 59 | wqshen/MetPy | metpy/io/nexrad.py | Python | high_byte | high_byte | 696 | 699 | 696 | 696 | 875eb44e2441f9ccd7a25c7c6c2e7fafc6bf5e59 | bigcode/the-stack | train |
9bd5ede59ecf8fb1e337a28e | train | class | class DigitalRefMapper(DigitalMapper):
units = 'dBZ'
| class DigitalRefMapper(DigitalMapper):
| units = 'dBZ'
| = min(num_levels, self._max_data - self._min_data + 1)
for i in range(num_levels):
self.lut[i + self._min_data] = min_val + i * inc
self.lut = np.array(self.lut)
class DigitalRefMapper(DigitalMapper):
| 64 | 64 | 15 | 8 | 56 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalRefMapper | DigitalRefMapper | 745 | 746 | 745 | 745 | af5fff9f1a8f2e7f27c4a964536de9501e50897a | bigcode/the-stack | train |
67f2f07d9c59b8d30fd21fdb | train | function | def two_comp16(val):
if val >> 15:
val = -(~val & 0x7fff) - 1
return val
| def two_comp16(val):
| if val >> 15:
val = -(~val & 0x7fff) - 1
return val
| d bytes but got %d' %
(msg_hdr.msg_type, size, hdr_size))
def reduce_lists(d):
for field in d:
old_data = d[field]
if len(old_data) == 1:
d[field] = old_data[0]
def two_comp16(val):
| 64 | 64 | 34 | 6 | 58 | wqshen/MetPy | metpy/io/nexrad.py | Python | two_comp16 | two_comp16 | 641 | 644 | 641 | 641 | 98cb9b0db14388e2d62807325d1c8e8148b0dcb1 | bigcode/the-stack | train |
26faa9c3894959dea68bc2d8 | train | function | def scaler(scale):
def inner(val):
return val * scale
return inner
| def scaler(scale):
| def inner(val):
return val * scale
return inner
| 2.7 needs a handler set
log.setLevel(logging.WARNING)
def version(val):
if val / 100. > 2.:
ver = val / 100.
else:
ver = val / 10.
return '{:.1f}'.format(ver)
def scaler(scale):
| 64 | 64 | 19 | 4 | 60 | wqshen/MetPy | metpy/io/nexrad.py | Python | scaler | scaler | 38 | 41 | 38 | 38 | 9c42321929a6f0de20663009f77cbcbfa456ddb7 | bigcode/the-stack | train |
56f2e9afa43ce5506a407dcf | train | function | def date_elem(ind_days, ind_minutes):
def inner(seq):
return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000)
return inner
| def date_elem(ind_days, ind_minutes):
| def inner(seq):
return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000)
return inner
| float(frac) / 2**9
if sign:
value *= -1
return value
def float32(short1, short2):
return struct.unpack('>f', struct.pack('>HH', short1, short2))[0]
def date_elem(ind_days, ind_minutes):
| 64 | 64 | 40 | 9 | 55 | wqshen/MetPy | metpy/io/nexrad.py | Python | date_elem | date_elem | 668 | 671 | 668 | 668 | 6de53d0cc81d41bb74815c9336ce911b386c2b45 | bigcode/the-stack | train |
0186e5d62a5b73d3bfeb158d | train | function | def low_byte(ind):
def inner(seq):
return seq[ind] & 0x00FF
return inner
| def low_byte(ind):
| def inner(seq):
return seq[ind] & 0x00FF
return inner
| python will properly convert signed values to unsigned
return lambda seq: float32(seq[ind1] & 0xFFFF, seq[ind2] & 0xFFFF)
def high_byte(ind):
def inner(seq):
return seq[ind] >> 8
return inner
def low_byte(ind):
| 64 | 64 | 26 | 5 | 58 | wqshen/MetPy | metpy/io/nexrad.py | Python | low_byte | low_byte | 702 | 705 | 702 | 702 | 7f7e02188d6648c9ea82167405f68fd6f4738c89 | bigcode/the-stack | train |
e1d129303ee734a21c450263 | train | function | def az_rate(val):
return val * 90. / 2**16
| def az_rate(val):
| return val * 90. / 2**16
| 100.
else:
ver = val / 10.
return '{:.1f}'.format(ver)
def scaler(scale):
def inner(val):
return val * scale
return inner
def angle(val):
return val * 360. / 2**16
def az_rate(val):
| 64 | 64 | 18 | 5 | 58 | wqshen/MetPy | metpy/io/nexrad.py | Python | az_rate | az_rate | 48 | 49 | 48 | 48 | 32224fbb7663e274efaa997a7397c90b760d3881 | bigcode/the-stack | train |
fb265c0bccaad10b6106427a | train | class | class DigitalSPWMapper(DigitalVelMapper):
_min_data = 129
_max_data = 149
| class DigitalSPWMapper(DigitalVelMapper):
| _min_data = 129
_max_data = 149
| min_val + i * inc
self.lut = np.array(self.lut)
class DigitalRefMapper(DigitalMapper):
units = 'dBZ'
class DigitalVelMapper(DigitalMapper):
units = 'm/s'
range_fold = True
class DigitalSPWMapper(DigitalVelMapper):
| 64 | 64 | 26 | 10 | 53 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalSPWMapper | DigitalSPWMapper | 754 | 756 | 754 | 754 | e729896f0311e10b819a6dce7f79edd818e3b567 | bigcode/the-stack | train |
b7656e6397b0e618ccae802c | train | class | class LegacyMapper(DataMapper):
lut_names = ['Blank', 'TH', 'ND', 'RF', 'BI', 'GC', 'IC', 'GR', 'WS',
'DS', 'RA', 'HR', 'BD', 'HA', 'UK']
def __init__(self, prod):
self.labels = []
self.lut = []
for t in prod.thresholds:
codes, val = t >> 8, t & 0xFF
... | class LegacyMapper(DataMapper):
| lut_names = ['Blank', 'TH', 'ND', 'RF', 'BI', 'GC', 'IC', 'GR', 'WS',
'DS', 'RA', 'HR', 'BD', 'HA', 'UK']
def __init__(self, prod):
self.labels = []
self.lut = []
for t in prod.thresholds:
codes, val = t >> 8, t & 0xFF
label = ''
if c... | __(self, prod):
scale = prod.thresholds[0] / 1000.
offset = prod.thresholds[1] / 1000.
data_levels = prod.thresholds[2]
leading_flags = prod.thresholds[3]
self.lut = [self.MISSING] * data_levels
for i in range(leading_flags, data_levels):
self.lut = scale * i ... | 107 | 107 | 357 | 6 | 101 | wqshen/MetPy | metpy/io/nexrad.py | Python | LegacyMapper | LegacyMapper | 850 | 893 | 850 | 850 | 0183d617dea850d3765754d3dfdd01428d62e3a7 | bigcode/the-stack | train |
985fee62c0f8146b4ffca9c3 | train | class | class DigitalMapper(DataMapper):
_min_scale = 0.1
_inc_scale = 0.1
_min_data = 2
_max_data = 255
range_fold = False
def __init__(self, prod):
min_val = two_comp16(prod.thresholds[0]) * self._min_scale
inc = prod.thresholds[1] * self._inc_scale
num_levels = prod.threshold... | class DigitalMapper(DataMapper):
| _min_scale = 0.1
_inc_scale = 0.1
_min_data = 2
_max_data = 255
range_fold = False
def __init__(self, prod):
min_val = two_comp16(prod.thresholds[0]) * self._min_scale
inc = prod.thresholds[1] * self._inc_scale
num_levels = prod.thresholds[2]
self.lut = [self.MIS... | DataMapper(object):
# Need to find way to handle range folded
# RANGE_FOLD = -9999
RANGE_FOLD = float('nan')
MISSING = float('nan')
def __call__(self, data):
return self.lut[data]
class DigitalMapper(DataMapper):
| 64 | 64 | 213 | 6 | 58 | wqshen/MetPy | metpy/io/nexrad.py | Python | DigitalMapper | DigitalMapper | 722 | 742 | 722 | 722 | 477ea5773318dc7b68b90b1cd6c81a2cabbeb268 | bigcode/the-stack | train |
bc494dd17cc1e18056f82dc8 | train | class | class TicketAdmin(admin.ModelAdmin):
class Meta:
model = Ticket
list_display = ["subject", "sender", "subdate"]
| class TicketAdmin(admin.ModelAdmin):
| class Meta:
model = Ticket
list_display = ["subject", "sender", "subdate"]
| from django.contrib import admin
from ticketsub.models import Ticket
class TicketAdmin(admin.ModelAdmin):
| 20 | 64 | 30 | 7 | 12 | Elemnir/presentations | utk_prog_team_2015_04_09/djtest/ticketsub/admin.py | Python | TicketAdmin | TicketAdmin | 5 | 8 | 5 | 5 | 825c4d385e99d7b7c94f3d85f83cb02296fb78c1 | bigcode/the-stack | train |
3c6ffbbf42be6c12508f6f6a | train | class | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) <= 1:
return
left = 0
right = len(nums) - 1
for i in range(len(nums)):
# left == right 时 [0:left-1... | class Solution:
| def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) <= 1:
return
left = 0
right = len(nums) - 1
for i in range(len(nums)):
# left == right 时 [0:left-1] 为 0 [right+1:... | from typing import List
class Solution:
| 8 | 78 | 260 | 3 | 4 | phiysng/leetcode | leetcode/python/75.sort-colors.py | Python | Solution | Solution | 3 | 30 | 3 | 3 | 3096bf91088802e55c96302007696476a8a9cb27 | bigcode/the-stack | train |
c0efc5db06bf3a775bf56d11 | train | function | def get_date_feature(df: pd.DataFrame, dt_prop: str, date_col: str) -> np.ndarray:
"""Extracts date related features from a datetime column
Parameters
----------
df: pd.DataFrame
Data set with a datetime column
dt_prop: str
Name of a date field property, e.g. "weekofyear", "month"... | def get_date_feature(df: pd.DataFrame, dt_prop: str, date_col: str) -> np.ndarray:
| """Extracts date related features from a datetime column
Parameters
----------
df: pd.DataFrame
Data set with a datetime column
dt_prop: str
Name of a date field property, e.g. "weekofyear", "month"
date_col: str
Name of a datetime column
Returns
-------
... | from sklearn.preprocessing import OneHotEncoder, FunctionTransformer
from sklearn.pipeline import make_pipeline, make_union, Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
def get_date_feature(df: pd.DataFrame, dt_prop: str, date_col: str) -> np.ndarray:
| 64 | 64 | 135 | 24 | 39 | sash-ko/ml_playgound | snippets/sklearn_transformers.py | Python | get_date_feature | get_date_feature | 20 | 41 | 20 | 20 | 4e28942069ddc854b8654a8a9b87fac53ca4f59e | bigcode/the-stack | train |
af4f078d87e185c299f5d42c | train | function | def create_simple_pipeline(
cat_features: List,
passthrough: List,
date_col: str,
**fit_params
) -> Pipeline:
"""Combines transformers and builds a prediction pipeline"""
# one hot encoded date features
transform_encoded_date_features = make_pipeline(
make_union(
Functio... | def create_simple_pipeline(
cat_features: List,
passthrough: List,
date_col: str,
**fit_params
) -> Pipeline:
| """Combines transformers and builds a prediction pipeline"""
# one hot encoded date features
transform_encoded_date_features = make_pipeline(
make_union(
FunctionTransformer(get_date_feature, kw_args={
'op': 'weekofyear', 'date_col': date_col}),
... | str
Name of a date field property, e.g. "weekofyear", "month"
date_col: str
Name of a datetime column
Returns
-------
feature: np.ndarray
"""
feature = getattr(df[date_col].dt, dt_prop).values.reshape(-1, 1)
return feature
def create_simple_pipeline(
cat_features: Lis... | 107 | 107 | 357 | 33 | 73 | sash-ko/ml_playgound | snippets/sklearn_transformers.py | Python | create_simple_pipeline | create_simple_pipeline | 44 | 92 | 44 | 49 | ad58b95c20596082246d5fc02f691d641d79f8f5 | bigcode/the-stack | train |
259742cae0b792aa4592c9bb | train | function | def get_feature_names(pipeline: Pipeline) -> List:
"""Extract feature names from a pipeline"""
names = []
if hasattr(pipeline, 'steps'):
for step in pipeline.steps:
names.extend(get_feature_names(step[1]))
elif hasattr(pipeline, 'transformer_list'):
for... | def get_feature_names(pipeline: Pipeline) -> List:
| """Extract feature names from a pipeline"""
names = []
if hasattr(pipeline, 'steps'):
for step in pipeline.steps:
names.extend(get_feature_names(step[1]))
elif hasattr(pipeline, 'transformer_list'):
for tr in pipeline.transformer_list:
names... | target variable
regressor = TransformedTargetRegressor(
regressor, func=np.log1p, inverse_func=np.exp
)
# combine feature transformers and regressor in one pipeline
return make_pipeline(transform_features, regressor)
def get_feature_names(pipeline: Pipeline) -> List:
| 64 | 64 | 110 | 12 | 52 | sash-ko/ml_playgound | snippets/sklearn_transformers.py | Python | get_feature_names | get_feature_names | 95 | 111 | 95 | 95 | e72895f41d283b112ba44fe61f44bd9040f67690 | bigcode/the-stack | train |
6e6962e35617de2e82790d88 | train | function | def make_prediction(
df: pd.DataFrame,
y: pd.Series,
cat_features: List,
passthrough: List,
date_col: str,
sample_weight_col: str = None
) -> np.array:
X_train, X_test, y_train, y_test = train_test_split(df, y)
# pass additional parameters to model fit
fit_p... | def make_prediction(
df: pd.DataFrame,
y: pd.Series,
cat_features: List,
passthrough: List,
date_col: str,
sample_weight_col: str = None
) -> np.array:
| X_train, X_test, y_train, y_test = train_test_split(df, y)
# pass additional parameters to model fit
fit_params = {}
if sample_weight_col:
# 'transformedtargetregressor' is the name
# of the last step of the pipeline generated automatically
fit_params['transformedtargetregressor... | names.extend(pipeline.get_feature_names())
return names
def make_prediction(
df: pd.DataFrame,
y: pd.Series,
cat_features: List,
passthrough: List,
date_col: str,
sample_weight_col: str = None
) -> np.array:
| 64 | 64 | 205 | 50 | 13 | sash-ko/ml_playgound | snippets/sklearn_transformers.py | Python | make_prediction | make_prediction | 114 | 139 | 114 | 122 | eb518171cef18979ebe14292ee34c6c3b0a5cd95 | bigcode/the-stack | train |
8ee970358ee0164df02fd465 | train | function | def transform(interactions_file="source/dgidb/interactions.tsv",
emitter_prefix=None,
emitter_directory="dgidb"):
emitter = JSONEmitter(directory=emitter_directory, prefix=emitter_prefix)
emitted_compounds = {}
interactions = read_tsv(interactions_file)
# gene_name gene_cla... | def transform(interactions_file="source/dgidb/interactions.tsv",
emitter_prefix=None,
emitter_directory="dgidb"):
| emitter = JSONEmitter(directory=emitter_directory, prefix=emitter_prefix)
emitted_compounds = {}
interactions = read_tsv(interactions_file)
# gene_name gene_claim_name entrez_id interaction_claim_source interaction_types drug_claim_name drug_claim_primary_name drug_name drug_chembl_id PMIDs
for lin... | import json
import logging
from bmeg.ioutils import read_tsv
from bmeg.emitter import JSONEmitter
from bmeg import (Gene, G2PAssociation, Project, Publication, Compound,
G2PAssociation_Compounds_Compound, G2PAssociation_Genes_Gene,
G2PAssociation_Publications_Publication)
import bme... | 119 | 227 | 758 | 28 | 90 | bmeg/bmeg-etl | transform/dgidb/transform.py | Python | transform | transform | 12 | 98 | 12 | 15 | 7045b98764b30a0adfba2f151cbea50d2fc10e52 | bigcode/the-stack | train |
3056957bb2c4b0a67c2ace07 | train | function | def last_page(doc):
""" Returns last page no in the original Blurb doc. """
pages = doc.xpath('.//section/page')
return int(pages[-1].get('number'))
| def last_page(doc):
| """ Returns last page no in the original Blurb doc. """
pages = doc.xpath('.//section/page')
return int(pages[-1].get('number'))
| 00', 'number': str(page)})
return find_page(doc, pageno)
def empty_pages(doc):
""" Returns all empty pages in the original Blurb doc. """
for page in doc.findall('.//section/page'):
if not page.findall('container'):
yield page
def last_page(doc):
| 64 | 64 | 41 | 5 | 58 | richardkchapman/BlurbFlow | flowblurb.py | Python | last_page | last_page | 427 | 430 | 427 | 427 | 7ff967e62bcc09e64a626f3077ec79504dbd7ccd | bigcode/the-stack | train |
59f0d1f91fc5032c6cdc5970 | train | function | def initialize_output_directory(args):
""" Check/create output directories. """
if args.output_dir:
if os.path.exists(args.output_dir):
if not args.force:
print ('Target directory %s already exists' % args.output_dir)
sys.exit()
shutil.rmtree(args.... | def initialize_output_directory(args):
| """ Check/create output directories. """
if args.output_dir:
if os.path.exists(args.output_dir):
if not args.force:
print ('Target directory %s already exists' % args.output_dir)
sys.exit()
shutil.rmtree(args.output_dir)
istemp = False
... | ':''})
for pageno in range(0, 20):
ET.SubElement(section, 'page', {'color':'#00000000', 'number': str(pageno+1)})
ET.ElementTree(book).write(path+'/bbf2.xml', pretty_print=True)
def initialize_output_directory(args):
| 64 | 64 | 131 | 6 | 58 | richardkchapman/BlurbFlow | flowblurb.py | Python | initialize_output_directory | initialize_output_directory | 836 | 854 | 836 | 836 | 967362b903c2e72c2cdedbcec3e8122647c3d036 | bigcode/the-stack | train |
d2f2649e6ec030ed46e0dc43 | train | function | def preview_one(layout, pageno, double, args, previews):
""" Output jpegs for a single tiled page. """
preview_scale = float(args.preview_ppi)/72
if double:
page_size = (int(args.page_width*preview_scale*2), int(args.page_height*preview_scale))
else:
page_size = (int(args.page_width*prev... | def preview_one(layout, pageno, double, args, previews):
| """ Output jpegs for a single tiled page. """
preview_scale = float(args.preview_ppi)/72
if double:
page_size = (int(args.page_width*preview_scale*2), int(args.page_height*preview_scale))
else:
page_size = (int(args.page_width*preview_scale), int(args.page_height*preview_scale))
canv... | {'scale':str(img.scale),
'x':'0', 'y':'0',
'autolayout':'fill',
'flip':'none',
'src':img.image.name+'.jpg'
})
def preview(args, populated, previews):
""" O... | 140 | 140 | 468 | 14 | 126 | richardkchapman/BlurbFlow | flowblurb.py | Python | preview_one | preview_one | 631 | 663 | 631 | 631 | d2af5b70043f7666059d4305e2e6af6a1799e3d3 | bigcode/the-stack | train |
f35bb4dac59a8464325f9c8d | train | function | def recommend_size(args, img):
""" Recommend size (in pixels) for populated image to reach 300 dpi"""
current_ppi = 72.0/img.scale
target_ppi = args.normal_ppi
scale = target_ppi/current_ppi
return (int(img.image.width*scale), int(img.image.height*scale))
| def recommend_size(args, img):
| """ Recommend size (in pixels) for populated image to reach 300 dpi"""
current_ppi = 72.0/img.scale
target_ppi = args.normal_ppi
scale = target_ppi/current_ppi
return (int(img.image.width*scale), int(img.image.height*scale))
| ='green', width=5)
draw.line((x, y+height, x+width, y), fill='green', width=5)
canvas.save('page%03d.jpg'%pageno)
previews.append('page%03d.jpg'%pageno)
def recommend_size(args, img):
| 64 | 64 | 73 | 7 | 57 | richardkchapman/BlurbFlow | flowblurb.py | Python | recommend_size | recommend_size | 665 | 670 | 665 | 665 | f07aac0fc48aa2b938f6f928fb6cad5bebec1c3e | bigcode/the-stack | train |
153e93de0303413c967b3087 | train | function | def populate_sections(doc, args, pagenos, images, previews):
""" Populate all images for multiple sections. """
sections_map = find_sections(args, images)
if not args.sections:
args.sections = sorted(sections_map.keys())
for section in args.sections:
section_args = argparse.Namespace(**v... | def populate_sections(doc, args, pagenos, images, previews):
| """ Populate all images for multiple sections. """
sections_map = find_sections(args, images)
if not args.sections:
args.sections = sorted(sections_map.keys())
for section in args.sections:
section_args = argparse.Namespace(**vars(args))
setattr(section_args, 'section_title', sec... | _sizes(args, populated)
if args.preview:
preview(args, populated, previews)
else:
update_blurb(doc, populated)
if args.section_blank_end:
del pagenos[0:args.section_blank_end]
def populate_sections(doc, args, pagenos, images, previews):
| 64 | 64 | 156 | 15 | 49 | richardkchapman/BlurbFlow | flowblurb.py | Python | populate_sections | populate_sections | 971 | 985 | 971 | 971 | 7f6bc0aa970a5ff0b1b9456e9ca993368ec9fb67 | bigcode/the-stack | train |
2633a6be7617d93db2bfecaa | train | function | def find_page(doc, pageno):
""" Find or create specific page in blurb document. """
matches = doc.xpath('.//section/page[@number=\'%d\']' % pageno)
if matches:
return matches[0]
section = doc.xpath('.//section')[-1]
# we need to create the page, but we also need to create any pages between t... | def find_page(doc, pageno):
| """ Find or create specific page in blurb document. """
matches = doc.xpath('.//section/page[@number=\'%d\']' % pageno)
if matches:
return matches[0]
section = doc.xpath('.//section')[-1]
# we need to create the page, but we also need to create any pages between the
# last page and this ... | "-j", "-n", filename))[0]
def get_tag(self, filename, tag):
""" Return single exif tag. """
ret = self.tags(filename).get(tag, None)
if not ret:
self.missing_tags += 1
return ret
def find_page(doc, pageno):
| 67 | 67 | 225 | 8 | 58 | richardkchapman/BlurbFlow | flowblurb.py | Python | find_page | find_page | 403 | 419 | 403 | 403 | d35a8df9c4a136f04333cf0bf6ac8c52c8cf312f | bigcode/the-stack | train |
fe7b39d4ded8485e33c49a8b | train | function | def preview(args, populated, previews):
""" Output jpegs for each tiled page. """
threads = []
for layout, pageno, double in populated:
thread = threading.Thread(target=preview_one, args=(layout, pageno, double, args, previews))
thread.start()
threads.append(thread)
for thread in... | def preview(args, populated, previews):
| """ Output jpegs for each tiled page. """
threads = []
for layout, pageno, double in populated:
thread = threading.Thread(target=preview_one, args=(layout, pageno, double, args, previews))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
prev... | })
ET.SubElement(container, 'image',
{'scale':str(img.scale),
'x':'0', 'y':'0',
'autolayout':'fill',
'flip':'none',
'src':img.image.name+'.jpg'
... | 64 | 64 | 81 | 8 | 56 | richardkchapman/BlurbFlow | flowblurb.py | Python | preview | preview | 620 | 629 | 620 | 620 | 7138a681a050d557feda9fe05d17a4f0ca692391 | bigcode/the-stack | train |
14709b241666cb28f40a142a | train | function | def make_builder(args, images):
""" Return a PageBuilder object appropriate for given args."""
if args.smart:
return SmartPageBuilder(args, images)
else:
if args.reverse:
images = images[::-1]
return PageBuilder(args, images)
| def make_builder(args, images):
| """ Return a PageBuilder object appropriate for given args."""
if args.smart:
return SmartPageBuilder(args, images)
else:
if args.reverse:
images = images[::-1]
return PageBuilder(args, images)
| align-center line-height-qt">' \
'<span class="font-%s" ' \
'style="font-size:%dpx;color:#000000;">%s</span></p>' % \
(args.section_title_font, args.section_title_fontsize, title)
def make_builder(args, images):
| 64 | 64 | 56 | 7 | 57 | richardkchapman/BlurbFlow | flowblurb.py | Python | make_builder | make_builder | 885 | 892 | 885 | 885 | 587d962f5b40322df5f07127d117aa67fd09faa5 | bigcode/the-stack | train |
a3582b02450872751eda8b02 | train | function | def update_blurb(doc, populated):
""" Update a blurb file from a populated layout. """
for layout, pageno, double in populated:
page = find_page(doc, pageno)
page.set('spread', 'true' if double else 'false')
if double:
rhs = find_page(doc, pageno+1)
rhs.getparent(... | def update_blurb(doc, populated):
| """ Update a blurb file from a populated layout. """
for layout, pageno, double in populated:
page = find_page(doc, pageno)
page.set('spread', 'true' if double else 'false')
if double:
rhs = find_page(doc, pageno+1)
rhs.getparent().remove(rhs)
for img in l... | .force:
print ('Target file %s already exists' % args.output)
sys.exit()
if not args.output:
args.output = args.input
if not (args.output or args.output_dir):
print ('No target specified')
sys.exit()
return args
def update_blurb(doc, populated):
| 67 | 67 | 224 | 8 | 58 | richardkchapman/BlurbFlow | flowblurb.py | Python | update_blurb | update_blurb | 594 | 618 | 594 | 594 | 808f9b11dfd252c064885a45b03a085253ff5725 | bigcode/the-stack | train |
40455d68df58646811a5833b | train | function | def check_sizes(args, populated):
""" Check all image resolutions are reasonable. """
for layout, _, _ in populated:
for img in layout:
ppi = 72.0/img.scale
name = os.path.splitext(os.path.basename(img.image.src))[0]
width, height = recommend_size(args, img)
... | def check_sizes(args, populated):
| """ Check all image resolutions are reasonable. """
for layout, _, _ in populated:
for img in layout:
ppi = 72.0/img.scale
name = os.path.splitext(os.path.basename(img.image.src))[0]
width, height = recommend_size(args, img)
if ppi < args.min_ppi:
... | populated image to reach 300 dpi"""
current_ppi = 72.0/img.scale
target_ppi = args.normal_ppi
scale = target_ppi/current_ppi
return (int(img.image.width*scale), int(img.image.height*scale))
def check_sizes(args, populated):
| 64 | 64 | 159 | 7 | 57 | richardkchapman/BlurbFlow | flowblurb.py | Python | check_sizes | check_sizes | 672 | 684 | 672 | 672 | d7a93759ff4cc0abfd9bba58b9fee13e2766169b | bigcode/the-stack | train |
8c229136583c5681261c1fe8 | train | function | def populate_pages(args, images, pagenos):
""" Return a page for each page number provided."""
return make_builder(args, images).get_pages(pagenos)
| def populate_pages(args, images, pagenos):
| """ Return a page for each page number provided."""
return make_builder(args, images).get_pages(pagenos)
| (args, images):
""" Return a PageBuilder object appropriate for given args."""
if args.smart:
return SmartPageBuilder(args, images)
else:
if args.reverse:
images = images[::-1]
return PageBuilder(args, images)
def populate_pages(args, images, pagenos):
| 64 | 64 | 36 | 11 | 53 | richardkchapman/BlurbFlow | flowblurb.py | Python | populate_pages | populate_pages | 894 | 896 | 894 | 894 | 563c87dc089f4a22ee818ca9302b5b769fa3abfc | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.