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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
52c08773aa63b4269c194ada | train | function | def ReadVersion(version_filename):
if os.path.exists(version_filename):
return open(version_filename).readlines()[0]
else:
return FIRST_VERSION
| def ReadVersion(version_filename):
| if os.path.exists(version_filename):
return open(version_filename).readlines()[0]
else:
return FIRST_VERSION
| import os
FIRST_VERSION = '1.00.00.00'
def ReadVersion(version_filename):
| 21 | 64 | 33 | 6 | 15 | igushev/fase_lib | tools/version_util.py | Python | ReadVersion | ReadVersion | 6 | 10 | 6 | 6 | f6648035142255c8d41b5535863e58c903eddb84 | bigcode/the-stack | train |
21828dab13ebb011f8ed1361 | train | class | class TTk(TTkWidget):
running: bool = False
events = None
key_events = None
mouse_events = None
screen_events = None
def __init__(self, *args, **kwargs):
TTkWidget.__init__(self, *args, **kwargs)
self._name = kwargs.get('name' , 'TTk' )
self.events = queue.Queue()
... | class TTk(TTkWidget):
| running: bool = False
events = None
key_events = None
mouse_events = None
screen_events = None
def __init__(self, *args, **kwargs):
TTkWidget.__init__(self, *args, **kwargs)
self._name = kwargs.get('name' , 'TTk' )
self.events = queue.Queue()
self.key_events = qu... | the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITN... | 256 | 256 | 1,754 | 7 | 249 | ceccopierangiolieugenio/py-ttk | TermTk/TTkCore/ttk.py | Python | TTk | TTk | 41 | 217 | 41 | 41 | 3a42474921c48cf6e298cdf08246d3058bb2c051 | bigcode/the-stack | train |
e698d8b8e76eed05d70f1d8b | train | function | def get_options_from_config():
# Set the options in a dictionary, in order to pass only the
# options that were provided in the configuration file to the
# MySQL connector. Passing empty values would trigger exceptions.
options = dict()
try:
options["host"] = config.get_value('mysql', 'host... | def get_options_from_config():
# Set the options in a dictionary, in order to pass only the
# options that were provided in the configuration file to the
# MySQL connector. Passing empty values would trigger exceptions.
| options = dict()
try:
options["host"] = config.get_value('mysql', 'host')
except (KeyError, NoOptionError): # Do nothing, this value is optional.
pass
try:
options["port"] = config.get_value('mysql', 'port')
except (KeyError, NoOptionError): # Do nothing, this value is op... | import sroka.config.config as config
from configparser import NoOptionError
def get_options_from_config():
# Set the options in a dictionary, in order to pass only the
# options that were provided in the configuration file to the
# MySQL connector. Passing empty values would trigger exceptions.
| 65 | 91 | 305 | 48 | 16 | jacekbj/sroka | sroka/api/mysql/mysql_helpers.py | Python | get_options_from_config | get_options_from_config | 5 | 41 | 5 | 8 | b58cfeabe256dd3ee5e3e5aad0b1ebdb194bd525 | bigcode/the-stack | train |
0471673cb117852da640e4bb | train | function | def validate_options(options: dict):
# If no connection option is given, there is not enough information to
# connect to the database.
if "unix_socket" not in options and "host" not in options:
print('Invalid Configuration: In order to connect to the MySQL database, the host/port options or the unix... | def validate_options(options: dict):
# If no connection option is given, there is not enough information to
# connect to the database.
| if "unix_socket" not in options and "host" not in options:
print('Invalid Configuration: In order to connect to the MySQL database, the host/port options or the unix_socket option must be set.')
return False
# If both keys are present and both have values, the configuration is
# ambiguous.
... | return options
# Ensures that either the options are set to connect to a remote database
# through a host/port combination, or through a unix socket.
def validate_options(options: dict):
# If no connection option is given, there is not enough information to
# connect to the database.
| 64 | 64 | 170 | 30 | 34 | jacekbj/sroka | sroka/api/mysql/mysql_helpers.py | Python | validate_options | validate_options | 46 | 59 | 46 | 48 | 1743c1ac2ffd80316a38889edd1f77379b189724 | bigcode/the-stack | train |
4e9bc9eeecf313f381d050f1 | train | function | def evaluate(
model: Union[
MultitaskTransformerEncoderClassificationModel, MultitaskBertClassificationModel, MultitaskLogisticRegressionClassificationModel],
iterator: Union[SMARTTOKDataLoader], criterion,
label_fields: List[LabelField],
all_classes: List[str],
desir... | def evaluate(
model: Union[
MultitaskTransformerEncoderClassificationModel, MultitaskBertClassificationModel, MultitaskLogisticRegressionClassificationModel],
iterator: Union[SMARTTOKDataLoader], criterion,
label_fields: List[LabelField],
all_classes: List[str],
desir... | """Evaluate method"""
# set model to eval mode
model.eval()
epoch_loss = 0.0
all_targets, all_preds = [], []
val_meter = tqdm(iterator, desc='eval', unit=' batches', leave=False, total=0)
with torch.no_grad():
for batch_idx, batch in enumerate(val_meter):
val_meter.t... |
loss.backward()
# clip grad norm
torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
# optimizer step
optimizer.step()
epoch_loss += loss.item()
# update tqdm meter
tqdm_meter.set_postfix(
ordered_dict={
'loss': f'{los... | 173 | 173 | 578 | 81 | 92 | subhadarship/GermEval2021 | src/training_utils/train_loop.py | Python | evaluate | evaluate | 84 | 149 | 84 | 91 | db808efe470ec3c941f6c2d093a84926e32553ee | bigcode/the-stack | train |
c1d6f4302cc5d6fc51643baf | train | function | def train(
model: Union[
MultitaskTransformerEncoderClassificationModel, MultitaskBertClassificationModel, MultitaskLogisticRegressionClassificationModel],
iterator: Union[SMARTTOKDataLoader],
optimizer, criterion, clip: float, curr_epoch: int, max_epochs: int
) -> float:
"""Trai... | def train(
model: Union[
MultitaskTransformerEncoderClassificationModel, MultitaskBertClassificationModel, MultitaskLogisticRegressionClassificationModel],
iterator: Union[SMARTTOKDataLoader],
optimizer, criterion, clip: float, curr_epoch: int, max_epochs: int
) -> float:
| """Train method"""
# set model to train mode
model.train()
epoch_loss = 0.0
tqdm_meter = tqdm(
iterator,
unit=' batches',
desc=f'[EPOCH {curr_epoch}/{max_epochs}]',
leave=False,
total=0,
)
for batch_idx, batch in enumerate(tqdm_meter):
tqdm... | MultitaskBertClassificationModel,
MultitaskLogisticRegressionClassificationModel,
)
from .eval_metrics import compute_metrics
from .postprocess import postprocess_labels
logger = logging.getLogger(__name__)
def train(
model: Union[
MultitaskTransformerEncoderClassificationModel, MultitaskBertC... | 111 | 111 | 370 | 67 | 44 | subhadarship/GermEval2021 | src/training_utils/train_loop.py | Python | train | train | 20 | 81 | 20 | 25 | e40af4b75a3b12852a4cc1d2776ad5d26f22a443 | bigcode/the-stack | train |
417e9dfed027c27138469da0 | train | function | def print_results(results, final_iterations):
for n_clusters, d in results.items():
print("\n\n------------------------------------")
print("CLUSTERS: "+str(n_clusters))
print("------------------------------------")
for category_name, category in d.items():
print("\nFitne... | def print_results(results, final_iterations):
| for n_clusters, d in results.items():
print("\n\n------------------------------------")
print("CLUSTERS: "+str(n_clusters))
print("------------------------------------")
for category_name, category in d.items():
print("\nFitness function: "+category_name)
prin... | import os
def print_results(results, final_iterations):
| 11 | 64 | 139 | 8 | 2 | EmanueleMusumeci/MMPI-2_GeneticAlgorithm_Clustering_no_data | compute_models_ranking.py | Python | print_results | print_results | 3 | 17 | 3 | 3 | f2e2a1cfa709b111f6ee8e5bfd6ce57ecaf1bfa2 | bigcode/the-stack | train |
ce5ea674fb8b276fe0421d7a | train | function | def models_ranking(snapshots_dir, early_stopping_patience = 10):
results = {
2: {"CentroidDistance" : {}, "MinimumPointDistance" : {}},
4: {"CentroidDistance" : {}, "MinimumPointDistance" : {}}
}
final_iteration = {}
for filename in os.listdir(snapshots_dir):
... | def models_ranking(snapshots_dir, early_stopping_patience = 10):
| results = {
2: {"CentroidDistance" : {}, "MinimumPointDistance" : {}},
4: {"CentroidDistance" : {}, "MinimumPointDistance" : {}}
}
final_iteration = {}
for filename in os.listdir(snapshots_dir):
if filename.endswith("normalized"):
continue
... | ("\nFitness function: "+category_name)
print("------------------------------------")
print("Model name\tValue\tIteration")
print("------------------------------------")
for model_name, result in category.items():
if result == 0:
print(m... | 102 | 103 | 346 | 18 | 84 | EmanueleMusumeci/MMPI-2_GeneticAlgorithm_Clustering_no_data | compute_models_ranking.py | Python | models_ranking | models_ranking | 20 | 56 | 20 | 20 | 4cda704c6f2e6a4d0f2da93d6c1da8898f0231d5 | bigcode/the-stack | train |
8bf4c30e9954572eb302d2e0 | train | class | class NoticeList(Document):
pass
| class NoticeList(Document):
| pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, Sambhaji Kolate and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class NoticeList(Document):
| 58 | 64 | 7 | 5 | 52 | Suraj787/ngse | ngse/ngse/doctype/notice_list/notice_list.py | Python | NoticeList | NoticeList | 9 | 10 | 9 | 9 | 3f3dc6c69461fe5b606c17c64649358809deea50 | bigcode/the-stack | train |
739de2a1b4c4b00546390589 | train | class | class KeyProvider(enum.Enum):
POSTGRES = 1,
MYSQL = 2,
SQLSERVER = 3,
ORACLE = 4
| class KeyProvider(enum.Enum):
| POSTGRES = 1,
MYSQL = 2,
SQLSERVER = 3,
ORACLE = 4
| import enum
class KeyProvider(enum.Enum):
| 9 | 64 | 33 | 6 | 2 | PdrLins/swift-morm | swift/swift.py | Python | KeyProvider | KeyProvider | 4 | 8 | 4 | 4 | 861eff1759a5f268a7ab689b591f7f293e32d11d | bigcode/the-stack | train |
cd821b93ae5fd370619288c6 | train | function | def groupby(key, iterable, transform=None):
"""Group items in `iterable` in a dictionary according to `key`.
Parameters
----------
key : function
Returns a hashable when given an item in `iterable`.
iterable : tuple, list, generator, or array-like
The items to be grouped.
transf... | def groupby(key, iterable, transform=None):
| """Group items in `iterable` in a dictionary according to `key`.
Parameters
----------
key : function
Returns a hashable when given an item in `iterable`.
iterable : tuple, list, generator, or array-like
The items to be grouped.
transform : function, optional
Transform t... | def groupby(key, iterable, transform=None):
| 10 | 64 | 170 | 10 | 0 | gitter-badger/husc | husc/_util.py | Python | groupby | groupby | 2 | 26 | 2 | 2 | 5be3c642c5ffc8d6444897f5bfa857681c1009a3 | bigcode/the-stack | train |
49fedbeb483c51921d7ef950 | train | function | def http_import():
url = "http://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv.zip"
aa = h2o.import_file(path=url)
assert aa.nrow == 194560, "Unexpected number of lines. %s" % aa.nrow
url = "https://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv.zip"
aa... | def http_import():
| url = "http://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv.zip"
aa = h2o.import_file(path=url)
assert aa.nrow == 194560, "Unexpected number of lines. %s" % aa.nrow
url = "https://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv.zip"
aa = h2o.import_file(... | import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def http_import():
| 27 | 64 | 126 | 4 | 22 | kernelrich/h2o-3 | h2o-py/tests/testdir_misc/pyunit_http_import.py | Python | http_import | http_import | 7 | 13 | 7 | 7 | ec57437f560f2f04b5b3f23159d5277aef0f6354 | bigcode/the-stack | train |
ff674b7aaef1dea7ac627d9d | train | function | def validator_row(entry):
todo = {
"fixchar_1": validators.make_validator_null(0.0, 1.0),
}
sco = 0.0
for k,v in todo.items():
s = v(entry[k])
#print("Sco<%s> %s"%(k,str(s)))
sco += s
return sco
| def validator_row(entry):
| todo = {
"fixchar_1": validators.make_validator_null(0.0, 1.0),
}
sco = 0.0
for k,v in todo.items():
s = v(entry[k])
#print("Sco<%s> %s"%(k,str(s)))
sco += s
return sco
|
import scanner_shared
scanner_settings = config_base.base_config()
def validate_ch(st):
if validators.validate_null(st):
return 0.0
s = st.s
if s == "FIL":
return 1.0
return 0.0
def validator_row(entry):
| 64 | 64 | 80 | 5 | 58 | esanwit/SQLCarve | SQLCarve/config_inno_c.py | Python | validator_row | validator_row | 22 | 31 | 22 | 22 | 1230e852cd57678e64f58a604d0b8efa0162544d | bigcode/the-stack | train |
539ce9c52ae685f3b185e080 | train | function | def validate_ch(st):
if validators.validate_null(st):
return 0.0
s = st.s
if s == "FIL":
return 1.0
return 0.0
| def validate_ch(st):
| if validators.validate_null(st):
return 0.0
s = st.s
if s == "FIL":
return 1.0
return 0.0
| #
# See ../LICENSE
#
# This file is a configuration example of an InnoDB Compact table with various types of fields.
#
#
import config_base
import validators
import field_inno_antelope as inno
import scanner_shared
scanner_settings = config_base.base_config()
def validate_ch(st):
| 64 | 64 | 46 | 5 | 59 | esanwit/SQLCarve | SQLCarve/config_inno_c.py | Python | validate_ch | validate_ch | 15 | 21 | 15 | 15 | 7d54c6f15655c164f13ac2f813d86fe746020f69 | bigcode/the-stack | train |
f347298f15635fcdb6a9d91f | train | class | class KennitalaField(forms.CharField):
default_validators = [validatorUser]
def validate(self, value):
super(KennitalaField, self).validate(value)
if not validateKennitala.validate(value):
raise forms.ValidationError(
_('%s er ekki kennitala' % (value)),
... | class KennitalaField(forms.CharField):
| default_validators = [validatorUser]
def validate(self, value):
super(KennitalaField, self).validate(value)
if not validateKennitala.validate(value):
raise forms.ValidationError(
_('%s er ekki kennitala' % (value)),
params={'value': value},
... | 0-9]{10}$', message="Kennitala, án bandstriks")
validatorPass = RegexValidator('^[a-zA-Z][a-zA-Z0-9-_\.]{4,255}$', message="Password should be a combination of letters and numbers")
class KennitalaField(forms.CharField):
| 64 | 64 | 73 | 8 | 56 | GudniNatan/Super_Duper_Ultra_Lokaverkefni | django_project/lokaverkefni/forms.py | Python | KennitalaField | KennitalaField | 10 | 20 | 10 | 10 | 9a138a0071c3dc5a7be545b951b3f718319eb643 | bigcode/the-stack | train |
203cb10c5e48e3761135eebd | train | class | class RegisterForm(forms.Form):
register_username = KennitalaField()
register_password = forms.CharField(validators=[validatorPass])
register_password_repeat = forms.CharField(validators=[validatorPass])
track_id = forms.DecimalField(required=True)
def __init__(self, value):
super(RegisterF... | class RegisterForm(forms.Form):
| register_username = KennitalaField()
register_password = forms.CharField(validators=[validatorPass])
register_password_repeat = forms.CharField(validators=[validatorPass])
track_id = forms.DecimalField(required=True)
def __init__(self, value):
super(RegisterForm, self).__init__(value)
... | .validate(value):
raise forms.ValidationError(
_('%s er ekki kennitala' % (value)),
params={'value': value},
)
class LoginForm(forms.Form):
login_username = KennitalaField()
login_password = forms.CharField(validators=[validatorPass])
class RegisterForm(f... | 64 | 64 | 163 | 6 | 58 | GudniNatan/Super_Duper_Ultra_Lokaverkefni | django_project/lokaverkefni/forms.py | Python | RegisterForm | RegisterForm | 26 | 49 | 26 | 26 | 26c9ade6a5cae722f1a2a73827d71c09f19e4054 | bigcode/the-stack | train |
f7426f2669234eaca7cff371 | train | class | class LoginForm(forms.Form):
login_username = KennitalaField()
login_password = forms.CharField(validators=[validatorPass])
| class LoginForm(forms.Form):
| login_username = KennitalaField()
login_password = forms.CharField(validators=[validatorPass])
| User]
def validate(self, value):
super(KennitalaField, self).validate(value)
if not validateKennitala.validate(value):
raise forms.ValidationError(
_('%s er ekki kennitala' % (value)),
params={'value': value},
)
class LoginForm(forms.Form):
| 64 | 64 | 27 | 6 | 58 | GudniNatan/Super_Duper_Ultra_Lokaverkefni | django_project/lokaverkefni/forms.py | Python | LoginForm | LoginForm | 22 | 24 | 22 | 22 | 6ce7e1c8f60e6cf93b4542380e2ba88a0c5f29d1 | bigcode/the-stack | train |
e911ceddda2154de075115f6 | train | class | class ArrayField(forms.Field):
def __init__(self, *args, **kwargs):
self.base_type = kwargs.pop('base_type')
self.widget = forms.MultipleHiddenInput
super(ArrayField, self).__init__(*args, **kwargs)
def clean(self, value):
for subvalue in value:
self.base_type.valid... | class ArrayField(forms.Field):
| def __init__(self, *args, **kwargs):
self.base_type = kwargs.pop('base_type')
self.widget = forms.MultipleHiddenInput
super(ArrayField, self).__init__(*args, **kwargs)
def clean(self, value):
for subvalue in value:
self.base_type.validate(subvalue)
return [s... | _data.get("register_password_repeat")
if register_password and register_password_repeat:
if register_password != register_password_repeat:
raise forms.ValidationError(
_(u'Lykilorð stemma ekki'),
code='invalid',
params={},
... | 64 | 64 | 92 | 6 | 57 | GudniNatan/Super_Duper_Ultra_Lokaverkefni | django_project/lokaverkefni/forms.py | Python | ArrayField | ArrayField | 51 | 62 | 51 | 52 | 6844536502947fd2b89584d813e2db1a191d0197 | bigcode/the-stack | train |
7150a9f6e8d12e0a1b58bd2b | train | class | class CourseSubmitForm(forms.Form):
courses = ArrayField(base_type=forms.CharField()) | class CourseSubmitForm(forms.Form):
| courses = ArrayField(base_type=forms.CharField()) | .MultipleHiddenInput
super(ArrayField, self).__init__(*args, **kwargs)
def clean(self, value):
for subvalue in value:
self.base_type.validate(subvalue)
return [self.base_type.clean(subvalue) for subvalue in value]
class CourseSubmitForm(forms.Form):
| 64 | 64 | 18 | 7 | 57 | GudniNatan/Super_Duper_Ultra_Lokaverkefni | django_project/lokaverkefni/forms.py | Python | CourseSubmitForm | CourseSubmitForm | 64 | 65 | 64 | 64 | 9ee1f1c5de221d53b305b81881cf6bff490927d3 | bigcode/the-stack | train |
db8820452b435ac047512954 | train | class | class StudySamplesInfoHandler(RESTHandler):
@authenticate_oauth
def get(self, study_id):
study = self.safe_get_study(study_id)
if study is None:
return
st = study.sample_template
if st is None:
info = {'number-of-samples': 0,
'categor... | class StudySamplesInfoHandler(RESTHandler):
@authenticate_oauth
| def get(self, study_id):
study = self.safe_get_study(study_id)
if study is None:
return
st = study.sample_template
if st is None:
info = {'number-of-samples': 0,
'categories': []}
else:
info = {'number-of-samples': len(... | 'samples': {}}
df = study.sample_template.to_dataframe()
for idx, row in df[categories].iterrows():
blob['samples'][idx] = list(row)
self.write(json_encode(blob))
self.finish()
class StudySamplesInfoHandler(RESTHandler):
@authenticate_oauth
| 64 | 64 | 108 | 15 | 49 | jlab/qiita | qiita_pet/handlers/rest/study_samples.py | Python | StudySamplesInfoHandler | StudySamplesInfoHandler | 119 | 136 | 119 | 121 | 1f79009cbadcc31c652c61d5ee2c6d1a58976606 | bigcode/the-stack | train |
87fee22d6f5abb85bf8ec19e | train | class | class StudySamplesHandler(RESTHandler):
@authenticate_oauth
def get(self, study_id):
study = self.safe_get_study(study_id)
if study is None:
return
if study.sample_template is None:
samples = []
else:
samples = list(study.sample_template.keys... | class StudySamplesHandler(RESTHandler):
@authenticate_oauth
| def get(self, study_id):
study = self.safe_get_study(study_id)
if study is None:
return
if study.sample_template is None:
samples = []
else:
samples = list(study.sample_template.keys())
self.write(json_encode(samples))
self.finish... | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | 102 | 125 | 418 | 14 | 87 | jlab/qiita | qiita_pet/handlers/rest/study_samples.py | Python | StudySamplesHandler | StudySamplesHandler | 15 | 81 | 15 | 17 | 36f131576d95aea8f893efa297992f95c4702679 | bigcode/the-stack | train |
cbe6262b89c0d8108ee44620 | train | class | class StudySamplesCategoriesHandler(RESTHandler):
@authenticate_oauth
def get(self, study_id, categories):
if not categories:
self.fail('No categories specified', 405)
return
study = self.safe_get_study(study_id)
if study is None:
return
cat... | class StudySamplesCategoriesHandler(RESTHandler):
@authenticate_oauth
| def get(self, study_id, categories):
if not categories:
self.fail('No categories specified', 405)
return
study = self.safe_get_study(study_id)
if study is None:
return
categories = categories.split(',')
if study.sample_template is None:
... | _template.update(to_update)
status = 200
if new_ids:
to_extend = data.loc[new_ids]
study.sample_template.extend(to_extend)
status = 201
self.set_status(status)
self.finish()
class StudySamplesCategoriesHandler(RESTHandler):
@authenticate_oau... | 64 | 64 | 205 | 15 | 49 | jlab/qiita | qiita_pet/handlers/rest/study_samples.py | Python | StudySamplesCategoriesHandler | StudySamplesCategoriesHandler | 84 | 116 | 84 | 86 | a7c34001bd91ce5e1ac4c1f0366011b57761e5a0 | bigcode/the-stack | train |
299a05c1f090e2738370616e | train | class | class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
m,n = len(mat),len(mat[0])
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j] = dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+mat[i-1][j-1]
... | class Solution:
| def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
m,n = len(mat),len(mat[0])
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j] = dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+mat[i-1][j-1]
def get(x1,y1,x2... | for c in range(ans + 1, r + 1):
# if i + c - 1 <= m and j + c - 1 <= n and getRect(i, j, i + c - 1, j + c - 1) <= threshold:
# ans += 1
# else:
# break
# return ans
class Solution:
| 82 | 82 | 274 | 3 | 78 | ruisunyc/- | leetcode/1292.元素和小于等于阈值的正方形的最大边长/1292-元素和小于等于阈值的正方形的最大边长.py | Python | Solution | Solution | 22 | 43 | 22 | 22 | de46040e5267cdbee91a5e26d317383ef6f4b2f5 | bigcode/the-stack | train |
11016b66bfec8c1b9ad5ba7f | train | function | def predict_file(*args):
"""
Function to make prediction on a local file
"""
message = 'Not implemented in the model (predict_file)'
return message
| def predict_file(*args):
| """
Function to make prediction on a local file
"""
message = 'Not implemented in the model (predict_file)'
return message
| ,
'License': None,
}
for line in pkg.get_metadata_lines("PKG-INFO"):
for par in meta:
if line.startswith(par):
_, value = line.split(": ", 1)
meta[par] = value
return meta
def predict_file(*args):
| 64 | 64 | 37 | 6 | 57 | charlos1204/firsttest | firsttest/models/deepaas_api.py | Python | predict_file | predict_file | 41 | 46 | 41 | 41 | 497f2b9d7364a7531915e9256240ae82bc9ec906 | bigcode/the-stack | train |
680a34c9d465137cc121bf57 | train | function | def predict_url(*args):
"""
Function to make prediction on a URL
"""
message = 'Not implemented in the model (predict_url)'
return message
| def predict_url(*args):
| """
Function to make prediction on a URL
"""
message = 'Not implemented in the model (predict_url)'
return message
| file
"""
message = 'Not implemented in the model (predict_file)'
return message
def predict_data(*args):
"""
Function to make prediction on an uploaded file
"""
message = 'Not implemented in the model (predict_data)'
return message
def predict_url(*args):
| 64 | 64 | 36 | 6 | 57 | charlos1204/firsttest | firsttest/models/deepaas_api.py | Python | predict_url | predict_url | 57 | 62 | 57 | 57 | 690ad5c23570cd1037bf65464c6f62a50b010c31 | bigcode/the-stack | train |
7aa4279f51d93ab867bf67df | train | function | def train(train_args):
"""
Train network
train_args : dict
Json dict with the user's configuration parameters.
Can be loaded with json.loads() or with yaml.safe_load()
"""
data_origin = 'rshare:/traning_data'
data_copy = os.path.join(cfg.BASE_DIR,
... | def train(train_args):
| """
Train network
train_args : dict
Json dict with the user's configuration parameters.
Can be loaded with json.loads() or with yaml.safe_load()
"""
data_origin = 'rshare:/traning_data'
data_copy = os.path.join(cfg.BASE_DIR,
'data')
command = ... | (predict_data)'
return message
def predict_url(*args):
"""
Function to make prediction on a URL
"""
message = 'Not implemented in the model (predict_url)'
return message
###
# Uncomment the following two lines
# if you allow only authorized people to do training
###
# import flaat
# @flaat.... | 81 | 81 | 270 | 5 | 76 | charlos1204/firsttest | firsttest/models/deepaas_api.py | Python | train | train | 71 | 108 | 71 | 71 | fc99909687fa5c86726abe769b8398d3591ce692 | bigcode/the-stack | train |
5834b375b58523ac29a0393f | train | function | def main():
"""
Runs above-described functions depending on input parameters
(see below an example)
"""
if args.method == 'get_metadata':
get_metadata()
elif args.method == 'train':
train(args)
else:
get_metadata()
| def main():
| """
Runs above-described functions depending on input parameters
(see below an example)
"""
if args.method == 'get_metadata':
get_metadata()
elif args.method == 'train':
train(args)
else:
get_metadata()
| _dump(val['default']) #json.dumps(val['default'])
if 'choices' in val:
val['choices'] = [str(item) for item in val['choices']]
return train_args
# during development it might be practical
# to check your code from the command line
def main():
| 64 | 64 | 56 | 3 | 60 | charlos1204/firsttest | firsttest/models/deepaas_api.py | Python | main | main | 128 | 139 | 128 | 128 | 16189f085c042bbcf06ebf6e825c0646e779af54 | bigcode/the-stack | train |
c5522ed168a649d21991659f | train | function | def get_metadata():
"""
Function to read metadata
"""
module = __name__.split('.', 1)
pkg = pkg_resources.get_distribution(module[0])
meta = {
'Name': None,
'Version': None,
'Summary': None,
'Home-page': None,
'Author': None,
'Author-email': None... | def get_metadata():
| """
Function to read metadata
"""
module = __name__.split('.', 1)
pkg = pkg_resources.get_distribution(module[0])
meta = {
'Name': None,
'Version': None,
'Summary': None,
'Home-page': None,
'Author': None,
'Author-email': None,
'License':... | # -*- coding: utf-8 -*-
"""
Model description
"""
import argparse
import pkg_resources
import subprocess
import firsttest.config as cfg
import os
import time
def get_metadata():
| 40 | 64 | 135 | 4 | 35 | charlos1204/firsttest | firsttest/models/deepaas_api.py | Python | get_metadata | get_metadata | 14 | 38 | 14 | 14 | aaf98e07ffa0683cb279ec4231307712701bd9dd | bigcode/the-stack | train |
9ffd3fd4fc075e88e15a5c26 | train | function | def predict_data(*args):
"""
Function to make prediction on an uploaded file
"""
message = 'Not implemented in the model (predict_data)'
return message
| def predict_data(*args):
| """
Function to make prediction on an uploaded file
"""
message = 'Not implemented in the model (predict_data)'
return message
| value = line.split(": ", 1)
meta[par] = value
return meta
def predict_file(*args):
"""
Function to make prediction on a local file
"""
message = 'Not implemented in the model (predict_file)'
return message
def predict_data(*args):
| 64 | 64 | 37 | 6 | 57 | charlos1204/firsttest | firsttest/models/deepaas_api.py | Python | predict_data | predict_data | 49 | 54 | 49 | 49 | 9d0abe4ad10991384019622e3fba045f3087da24 | bigcode/the-stack | train |
69196c923d63f00b038c8376 | train | function | def get_train_args():
"""
Returns a dict of dicts to feed the deepaas API parser
"""
train_args = {} #cfg.train_args
# convert default values and possible 'choices' into strings
for key, val in train_args.items():
val['default'] = str(val['default']) # yaml.safe_dump(val['default']) #j... | def get_train_args():
| """
Returns a dict of dicts to feed the deepaas API parser
"""
train_args = {} #cfg.train_args
# convert default values and possible 'choices' into strings
for key, val in train_args.items():
val['default'] = str(val['default']) # yaml.safe_dump(val['default']) #json.dumps(val['default... | (['rclone', 'copy', data_origin, data_copy])
run_results = {"status": "Training finished",
"train_args": [],
"training": [],
}
run_results["train_args"].append(train_args)
print(run_results)
return run_results
def get_train_args():
| 64 | 64 | 115 | 5 | 58 | charlos1204/firsttest | firsttest/models/deepaas_api.py | Python | get_train_args | get_train_args | 111 | 123 | 111 | 111 | fa7ec95018e0c16cb50743c5e3e353218814661b | bigcode/the-stack | train |
353e4e7338cc0c764b840a63 | train | function | def required_roles(*roles):
""""
Decorater for views to check if user has the permissons
to enter the view.
Example:
from munimap.helper import required_roles
@user.route('/test/')
@required_roles('edit')
"""
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
... | def required_roles(*roles):
| """"
Decorater for views to check if user has the permissons
to enter the view.
Example:
from munimap.helper import required_roles
@user.route('/test/')
@required_roles('edit')
"""
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
if check_user_pe... | hasattr(ex, 'problem'):
self.reason = ex.problem
super(InvalidAppConfigError, self).__init__(ex)
def request_for_static():
if request.endpoint == 'static' or request.endpoint == 'favicon':
return True
else:
return False
def required_roles(*roles):
| 64 | 64 | 108 | 6 | 57 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | required_roles | required_roles | 46 | 65 | 46 | 46 | a676b732b3614bd19bdb2b96a09ee3798946ffb9 | bigcode/the-stack | train |
e88780675683a01dc522e707 | train | function | def plugin_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('PLUGIN_DIR')),
name + '.js'
)
| def plugin_file_path(name):
| return os.path.join(os.path.abspath(
current_app.config.get('PLUGIN_DIR')),
name + '.js'
)
| .path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
name + '.yaml'
)
def selectionlist_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('SELECTIONLISTS_CONFIG_DIR')),
name + '.yaml'
)
def plugin_file_path(name):
| 64 | 64 | 32 | 6 | 58 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | plugin_file_path | plugin_file_path | 273 | 277 | 273 | 273 | d679d6eb10cca7348226a33b98beb45f5a7b8276 | bigcode/the-stack | train |
45c444a3841428cf1609cb8c | train | function | def touch_last_changes_file(times=None):
fname = '%s/%s' % (current_app.config.get('LAYERS_CONF_DIR'), 'last_changes')
with open(fname, 'a'):
os.utime(fname, times)
| def touch_last_changes_file(times=None):
| fname = '%s/%s' % (current_app.config.get('LAYERS_CONF_DIR'), 'last_changes')
with open(fname, 'a'):
os.utime(fname, times)
| .replace('\n', '<br>\n') for p in lines]
if only_first and len(html_lines) > 0:
result = html_lines[0]
else:
result = u'\n\n'.join(html_lines)
return Markup(result)
def touch_last_changes_file(times=None):
| 64 | 64 | 48 | 8 | 56 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | touch_last_changes_file | touch_last_changes_file | 325 | 329 | 325 | 325 | 5e24a663a9ebe2e880f26ba14dae2a96b912f42e | bigcode/the-stack | train |
3372a093ef01fcc1367589dd | train | function | def merge_dict(child, parent):
"""
Return `parent` dict with values from `child` merged in.
Removes `child` values = None from `parent`
"""
for k, v in child.iteritems():
if v is None:
del parent[k]
continue
if k not in parent:
parent[k] = v
... | def merge_dict(child, parent):
| """
Return `parent` dict with values from `child` merged in.
Removes `child` values = None from `parent`
"""
for k, v in child.iteritems():
if v is None:
del parent[k]
continue
if k not in parent:
parent[k] = v
else:
if isinstan... | layersToCheck.append(layer)
filteredLayers = check_layers_permission(layersToCheck)
allowedLayers = allowedLayers + filteredLayers
return allowedLayers
def merge_yaml_dicts(x, y):
z = x.copy()
z.update(y)
return z
def merge_dict(child, parent):
| 64 | 64 | 114 | 7 | 56 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | merge_dict | merge_dict | 152 | 168 | 152 | 152 | 7be11a8bfdd6cc782673e13009e1984b45c983d1 | bigcode/the-stack | train |
5efc30c951b9e45d0e187ce3 | train | function | def layers_allowed_for_user(layers):
allowedLayers = []
layersToCheck = []
for layer in layers:
if not layer['protected']:
allowedLayers.append(layer)
elif current_user.is_anonymous:
pass
else:
layersToCheck.append(layer)
filteredLayers = che... | def layers_allowed_for_user(layers):
| allowedLayers = []
layersToCheck = []
for layer in layers:
if not layer['protected']:
allowedLayers.append(layer)
elif current_user.is_anonymous:
pass
else:
layersToCheck.append(layer)
filteredLayers = check_layers_permission(layersToCheck)
... | (layer):
if not layer['protected']:
return True
if current_user.is_anonymous:
return False
# raises 404 when layer not found
protected_layer = ProtectedLayer.by_name(layer['name'])
return check_layer_permission(protected_layer)
def layers_allowed_for_user(layers):
| 64 | 64 | 86 | 8 | 56 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | layers_allowed_for_user | layers_allowed_for_user | 129 | 144 | 129 | 129 | ce0736707cba8348bea45457f4112f3287f2500d | bigcode/the-stack | train |
2a80a06adfdea317a709fbda | train | function | def layer_allowed_for_user(layer):
if not layer['protected']:
return True
if current_user.is_anonymous:
return False
# raises 404 when layer not found
protected_layer = ProtectedLayer.by_name(layer['name'])
return check_layer_permission(protected_layer)
| def layer_allowed_for_user(layer):
| if not layer['protected']:
return True
if current_user.is_anonymous:
return False
# raises 404 when layer not found
protected_layer = ProtectedLayer.by_name(layer['name'])
return check_layer_permission(protected_layer)
| _user.id, "layer_names": tuple(layer_names)}, mapper=class_mapper(ProtectedLayer))
allowedLayerNames = [r for r, in result]
filteredLayers = [layer for layer in layers if layer['name'] in allowedLayerNames]
return filteredLayers
def layer_allowed_for_user(layer):
| 64 | 64 | 61 | 7 | 56 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | layer_allowed_for_user | layer_allowed_for_user | 116 | 126 | 116 | 116 | c4794aa22d55a62f49ff964fbaf176883a8127f3 | bigcode/the-stack | train |
0d0319fd43e5a8b414aa7334 | train | function | def list_plugins():
configs = glob.glob(os.path.join(os.path.abspath(
current_app.config.get('PLUGIN_DIR')),
'*.js'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
| def list_plugins():
| configs = glob.glob(os.path.join(os.path.abspath(
current_app.config.get('PLUGIN_DIR')),
'*.js'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
| (os.path.join(os.path.abspath(
current_app.config.get('SELECTIONLISTS_CONFIG_DIR')),
'*.yaml'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
def list_plugins():
| 64 | 64 | 65 | 4 | 59 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | list_plugins | list_plugins | 300 | 307 | 300 | 300 | 5586f22e6846875d28aa60354375ff9c10e71f4a | bigcode/the-stack | train |
7d1436eef3c19cfa26d9a934 | train | function | def config_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('LAYERS_CONF_DIR')),
name
)
| def config_file_path(name):
| return os.path.join(os.path.abspath(
current_app.config.get('LAYERS_CONF_DIR')),
name
)
| InvalidAppConfigError(err, app_config_path)
try:
selectionlist_config = yaml.load(open(file_path, 'r'))
except yaml.YAMLError as ex:
raise InvalidAppConfigError(ex, file_path)
field['select'] = selectionlist_config
def config_file_path(name):
| 63 | 64 | 31 | 6 | 56 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | config_file_path | config_file_path | 252 | 256 | 252 | 252 | 63e50704d335f765fdf0327eb770e175912ec7d2 | bigcode/the-stack | train |
ea04f85eb7d40412e2308770 | train | function | def check_layer_permission(layer):
return layer.has_user_permission(layer, current_user)
| def check_layer_permission(layer):
| return layer.has_user_permission(layer, current_user)
| check_group_permission(roles):
for group in current_user.groups:
if group.name in roles:
return True
return False
def check_project_permission(project):
for group in current_user.groups:
if group in project.groups:
return True
return False
def check_layer_permi... | 64 | 64 | 17 | 6 | 57 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | check_layer_permission | check_layer_permission | 82 | 83 | 82 | 82 | 6a2f8406dcf04dbcff17a43bcc879a890800762a | bigcode/the-stack | train |
fb3fc3f009cad85082bb4e32 | train | function | def project_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
name + '.yaml'
)
| def project_file_path(name):
| return os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
name + '.yaml'
)
| AMLError as ex:
raise InvalidAppConfigError(ex, file_path)
field['select'] = selectionlist_config
def config_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('LAYERS_CONF_DIR')),
name
)
def project_file_path(name):
| 64 | 64 | 33 | 6 | 58 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | project_file_path | project_file_path | 259 | 263 | 259 | 259 | 097afbcf4800a407354d6002ec4692964b22af2d | bigcode/the-stack | train |
9ff8c077b828bc0363109365 | train | function | def apply_selectionlists_to_geoeditor(app_config, app_config_path):
if app_config.get('components') is None:
return
if app_config.get('components').get('geoeditor') is None:
return
if app_config.get('components').get('geoeditor').get('formFields') is None:
return
form_fields = a... | def apply_selectionlists_to_geoeditor(app_config, app_config_path):
| if app_config.get('components') is None:
return
if app_config.get('components').get('geoeditor') is None:
return
if app_config.get('components').get('geoeditor').get('formFields') is None:
return
form_fields = app_config['components']['geoeditor']['formFields']
for geometry_... | ']
)
if 'printConfig' in app_config:
app_config['printConfig']['pageMargins'] = current_app.config.get(
'MAPFISH_PRINT_MAP_MARGINS', [0, 0, 0, 0]
)
return app_config
def apply_selectionlists_to_geoeditor(app_config, app_config_path):
| 73 | 73 | 245 | 14 | 58 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | apply_selectionlists_to_geoeditor | apply_selectionlists_to_geoeditor | 222 | 249 | 222 | 222 | fbb16525ae84e5402db511514f70183b1fae6bd1 | bigcode/the-stack | train |
c1ac3307943edc0078261072 | train | function | def nl2br(value, only_first=False):
lines = _paragraph_re.split(escape(value))
html_lines = [u'<p>%s</p>' % p.replace('\n', '<br>\n') for p in lines]
if only_first and len(html_lines) > 0:
result = html_lines[0]
else:
result = u'\n\n'.join(html_lines)
return Markup(result)
| def nl2br(value, only_first=False):
| lines = _paragraph_re.split(escape(value))
html_lines = [u'<p>%s</p>' % p.replace('\n', '<br>\n') for p in lines]
if only_first and len(html_lines) > 0:
result = html_lines[0]
else:
result = u'\n\n'.join(html_lines)
return Markup(result)
| [os.path.splitext(c)[0] for c in configs]
return configs
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
# found at http://flask.pocoo.org/snippets/28/
def nl2br(value, only_first=False):
| 64 | 64 | 92 | 10 | 54 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | nl2br | nl2br | 314 | 322 | 314 | 314 | dbcd31d95e3d86a8c9c3b83f8df2d162d92c7400 | bigcode/the-stack | train |
e444e9cc6f9b0b3deed9d275 | train | function | def check_group_permission(roles):
for group in current_user.groups:
if group.name in roles:
return True
return False
| def check_group_permission(roles):
| for group in current_user.groups:
if group.name in roles:
return True
return False
| _roles('edit')
"""
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
if check_user_permission(roles):
return f(*args, **kwargs)
return abort(403)
return wrapped
return wrapper
def check_group_permission(roles):
| 64 | 64 | 30 | 7 | 56 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | check_group_permission | check_group_permission | 68 | 72 | 68 | 68 | d1970938733f919624896f9d0d204030d1829bec | bigcode/the-stack | train |
aa7f531f1da499996c2f25f5 | train | function | def request_for_static():
if request.endpoint == 'static' or request.endpoint == 'favicon':
return True
else:
return False
| def request_for_static():
| if request.endpoint == 'static' or request.endpoint == 'favicon':
return True
else:
return False
| , 'problem_mark'):
self.position = [
ex.problem_mark.line + 1,
ex.problem_mark.column + 1
]
if hasattr(ex, 'problem'):
self.reason = ex.problem
super(InvalidAppConfigError, self).__init__(ex)
def request_for_static():
| 64 | 64 | 31 | 5 | 59 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | request_for_static | request_for_static | 39 | 43 | 39 | 39 | a3cf2ac8763cd5cae798796940554c8f5758a1b2 | bigcode/the-stack | train |
d1684a651373bda288988569 | train | function | def load_app_config(config=None, without_404=False):
default_config_file = os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
current_app.config.get('DEFAULT_APP_CONFIG')
)
if not os.path.exists(default_config_file):
current_app.logger.warn(
'Default... | def load_app_config(config=None, without_404=False):
| default_config_file = os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
current_app.config.get('DEFAULT_APP_CONFIG')
)
if not os.path.exists(default_config_file):
current_app.logger.warn(
'Default app config not found. (%s)' % default_config_file)
... | parent):
"""
Return `parent` dict with values from `child` merged in.
Removes `child` values = None from `parent`
"""
for k, v in child.iteritems():
if v is None:
del parent[k]
continue
if k not in parent:
parent[k] = v
else:
i... | 121 | 121 | 404 | 12 | 108 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | load_app_config | load_app_config | 170 | 219 | 170 | 170 | 8c5b7ec1a710d3b8c468b51a431cb1e957fbe1a2 | bigcode/the-stack | train |
650a477fb2d365183dbeb862 | train | function | def check_layers_permission(layers):
if len(layers) == 0:
return []
layer_names = [layer['name'] for layer in layers]
sqlTpl = """
SELECT
distinct ON (mm_layer_id)
l.name AS layerName
FROM
mm_layer_group lg
LEFT JOIN mb_user_mb_group ug ... | def check_layers_permission(layers):
| if len(layers) == 0:
return []
layer_names = [layer['name'] for layer in layers]
sqlTpl = """
SELECT
distinct ON (mm_layer_id)
l.name AS layerName
FROM
mm_layer_group lg
LEFT JOIN mb_user_mb_group ug ON lg.mb_group_id = ug.fkey_mb_group_i... | in roles:
return True
return False
def check_project_permission(project):
for group in current_user.groups:
if group in project.groups:
return True
return False
def check_layer_permission(layer):
return layer.has_user_permission(layer, current_user)
def check_layers_... | 64 | 64 | 203 | 7 | 57 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | check_layers_permission | check_layers_permission | 86 | 113 | 86 | 87 | a0c065a8bc833295a8035978e748fc34a106bb0e | bigcode/the-stack | train |
870c67ba12b79107cdf8d495 | train | function | def check_project_permission(project):
for group in current_user.groups:
if group in project.groups:
return True
return False
| def check_project_permission(project):
| for group in current_user.groups:
if group in project.groups:
return True
return False
| _user_permission(roles):
return f(*args, **kwargs)
return abort(403)
return wrapped
return wrapper
def check_group_permission(roles):
for group in current_user.groups:
if group.name in roles:
return True
return False
def check_project_permission(proj... | 64 | 64 | 29 | 6 | 57 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | check_project_permission | check_project_permission | 75 | 79 | 75 | 75 | 074f90d97b9b9fb4243413f1b654f93b3bd1e826 | bigcode/the-stack | train |
57542b537e6cee955b3663ca | train | function | def urlencode_params(params):
encoded_params = ''
for param in params:
encoded_params += param + '=' + params[param] + '&'
return encoded_params
| def urlencode_params(params):
| encoded_params = ''
for param in params:
encoded_params += param + '=' + params[param] + '&'
return encoded_params
| '.join(html_lines)
return Markup(result)
def touch_last_changes_file(times=None):
fname = '%s/%s' % (current_app.config.get('LAYERS_CONF_DIR'), 'last_changes')
with open(fname, 'a'):
os.utime(fname, times)
def urlencode_params(params):
| 64 | 64 | 35 | 5 | 59 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | urlencode_params | urlencode_params | 332 | 336 | 332 | 332 | a6b5796add77b96984e9eb04d6ec3edc2d48431d | bigcode/the-stack | train |
6ad056bf44db184b359d97c2 | train | function | def merge_yaml_dicts(x, y):
z = x.copy()
z.update(y)
return z
| def merge_yaml_dicts(x, y):
| z = x.copy()
z.update(y)
return z
| ']:
allowedLayers.append(layer)
elif current_user.is_anonymous:
pass
else:
layersToCheck.append(layer)
filteredLayers = check_layers_permission(layersToCheck)
allowedLayers = allowedLayers + filteredLayers
return allowedLayers
def merge_yaml_dicts(x, y):... | 64 | 64 | 24 | 9 | 54 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | merge_yaml_dicts | merge_yaml_dicts | 147 | 150 | 147 | 147 | 7bd665735a44259c8fbef95dc69a01763a651b9f | bigcode/the-stack | train |
2dbbf0e457c37c1d0de1ff2b | train | class | class InvalidAppConfigError(Exception):
def __init__(self, ex, filename):
self.filename = filename
self.position = None
self.reason = None
if hasattr(ex, 'problem_mark'):
self.position = [
ex.problem_mark.line + 1,
ex.problem_mark.column + ... | class InvalidAppConfigError(Exception):
| def __init__(self, ex, filename):
self.filename = filename
self.position = None
self.reason = None
if hasattr(ex, 'problem_mark'):
self.position = [
ex.problem_mark.line + 1,
ex.problem_mark.column + 1
]
if hasattr(ex, '... | from flask.ext.babel import gettext as _, lazy_gettext as _l
from sqlalchemy.orm import class_mapper
from munimap.model import ProtectedLayer
from munimap.extensions import db
from jinja2 import Markup, escape
__all__ = ['_', '_l']
class InvalidAppConfigError(Exception):
| 64 | 64 | 99 | 7 | 57 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | InvalidAppConfigError | InvalidAppConfigError | 23 | 36 | 23 | 23 | 7c3344a2d6ae760aaa29871bffc9a30f5f2a749b | bigcode/the-stack | train |
58912a9111361ba1734242c4 | train | function | def list_projects():
configs = glob.glob(os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
'*.yaml'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
| def list_projects():
| configs = glob.glob(os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
'*.yaml'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
| os.path.join(os.path.abspath(
current_app.config.get('SELECTIONLISTS_CONFIG_DIR')),
name + '.yaml'
)
def plugin_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('PLUGIN_DIR')),
name + '.js'
)
def list_projects():
| 64 | 64 | 66 | 4 | 60 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | list_projects | list_projects | 280 | 287 | 280 | 280 | ea7b900a1716eaff785891c2799e90b8076ba538 | bigcode/the-stack | train |
4b8bb88895715439503045cb | train | function | def list_selectionlists():
configs = glob.glob(os.path.join(os.path.abspath(
current_app.config.get('SELECTIONLISTS_CONFIG_DIR')),
'*.yaml'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
| def list_selectionlists():
| configs = glob.glob(os.path.join(os.path.abspath(
current_app.config.get('SELECTIONLISTS_CONFIG_DIR')),
'*.yaml'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
| glob.glob(os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
'*.yaml'
))
configs = [os.path.basename(c) for c in configs]
configs = [os.path.splitext(c)[0] for c in configs]
return configs
def list_selectionlists():
| 64 | 64 | 70 | 5 | 58 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | list_selectionlists | list_selectionlists | 290 | 297 | 290 | 290 | 859fd8bedcaba765d63f5d568937e56b0762a407 | bigcode/the-stack | train |
b6da43c318352241101db377 | train | function | def selectionlist_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('SELECTIONLISTS_CONFIG_DIR')),
name + '.yaml'
)
| def selectionlist_file_path(name):
| return os.path.join(os.path.abspath(
current_app.config.get('SELECTIONLISTS_CONFIG_DIR')),
name + '.yaml'
)
| return os.path.join(os.path.abspath(
current_app.config.get('LAYERS_CONF_DIR')),
name
)
def project_file_path(name):
return os.path.join(os.path.abspath(
current_app.config.get('APP_CONFIG_DIR')),
name + '.yaml'
)
def selectionlist_file_path(name):
| 64 | 64 | 37 | 7 | 57 | MrSnyder/bielefeldGEOCLIENT | munimap/helper.py | Python | selectionlist_file_path | selectionlist_file_path | 266 | 270 | 266 | 266 | da9bdff37d52179a38dc62113749fa4cd714bfb7 | bigcode/the-stack | train |
8d0329e71d07feca7f3a128e | train | function | def init():
railgrid = defaultdict(dict)
carts = []
for y in range(len(data)):
line = data[y].rstrip('\n')
for x in range(len(line)):
if line[x] in CartDirTypes:
carts.append(Cart(x, y, line[x]))
railgrid[y][x] = Rail(x, y, line[x], [carts[-1]]... | def init():
| railgrid = defaultdict(dict)
carts = []
for y in range(len(data)):
line = data[y].rstrip('\n')
for x in range(len(line)):
if line[x] in CartDirTypes:
carts.append(Cart(x, y, line[x]))
railgrid[y][x] = Rail(x, y, line[x], [carts[-1]])
... | (char, cart):
if cart:
types = [0, 0, 1, 1]
index = types[CartDirTypes.index(char)]
else:
index = RailTypes.index(char) if char in RailTypes else RailType.EMPTY
return RailType(index)
def init():
| 64 | 64 | 190 | 3 | 61 | pantaryl/adventofcode | 2018/src/day13.py | Python | init | init | 130 | 151 | 130 | 130 | 5b0aa74b920b195ea1f9d6965781cc05b9140939 | bigcode/the-stack | train |
5f9a4f38456c62190d9d77e7 | train | function | def step(grid, carts, needCollision, needRemoval):
carts.sort(key=lambda x:(x.y, x.x))
for cart in list(carts):
if cart not in carts: continue
cart.move(grid)
if needCollision and str(grid[cart.y][cart.x]) == 'X':
return (cart.x, cart.y)
elif needRemoval and str(grid[... | def step(grid, carts, needCollision, needRemoval):
| carts.sort(key=lambda x:(x.y, x.x))
for cart in list(carts):
if cart not in carts: continue
cart.move(grid)
if needCollision and str(grid[cart.y][cart.x]) == 'X':
return (cart.x, cart.y)
elif needRemoval and str(grid[cart.y][cart.x]) == 'X':
for car in lis... | ' ')
return railgrid, carts
def printGrid(grid):
for y in range(len(grid.keys())):
for x in range(len(grid[y].keys())):
print(grid[y][x], end='')
print()
print()
def step(grid, carts, needCollision, needRemoval):
| 64 | 64 | 129 | 12 | 52 | pantaryl/adventofcode | 2018/src/day13.py | Python | step | step | 160 | 171 | 160 | 160 | 68940312797b468034256eb5805087a8c3a34213 | bigcode/the-stack | train |
2f22ffc9d688ee3ab037eb99 | train | class | class RailType(Enum):
HORIZ = 0
VERT = 1
LEFTUP = 2
RIGHTUP = 3
INTERSECTION = 4
EMPTY = 5
def __int__(self):
return self.value
| class RailType(Enum):
| HORIZ = 0
VERT = 1
LEFTUP = 2
RIGHTUP = 3
INTERSECTION = 4
EMPTY = 5
def __int__(self):
return self.value
| with open("../input/day13.txt.txt", 'r') as inputFile:
data = inputFile.readlines()
from collections import defaultdict
from enum import Enum
class RailType(Enum):
| 38 | 64 | 63 | 5 | 32 | pantaryl/adventofcode | 2018/src/day13.py | Python | RailType | RailType | 7 | 16 | 7 | 7 | ff26af5fa4d84c439dbe52f1239bcef975452a31 | bigcode/the-stack | train |
0732179ef36e8cb1390b0591 | train | function | def determineRailType(char, cart):
if cart:
types = [0, 0, 1, 1]
index = types[CartDirTypes.index(char)]
else:
index = RailTypes.index(char) if char in RailTypes else RailType.EMPTY
return RailType(index)
| def determineRailType(char, cart):
| if cart:
types = [0, 0, 1, 1]
index = types[CartDirTypes.index(char)]
else:
index = RailTypes.index(char) if char in RailTypes else RailType.EMPTY
return RailType(index)
| repr__(self):
if len(self.cars) > 1:
return "X"
elif len(self.cars) > 0:
return CartDirTypes[int(self.cars[0].dir)]
else:
return RailTypes[int(self.type)]
def determineRailType(char, cart):
| 64 | 64 | 65 | 8 | 56 | pantaryl/adventofcode | 2018/src/day13.py | Python | determineRailType | determineRailType | 122 | 128 | 122 | 122 | 9d784ccd11a1cbbc68288e2dbafbd93cd8488862 | bigcode/the-stack | train |
936a4abcdc4862b2fd6c1a31 | train | class | class CartDir(Enum):
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
def __int__(self):
return self.value
def movementVector(self):
return [(-1, 0), (1, 0), (0, -1), (0, 1)][self.value]
| class CartDir(Enum):
| LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
def __int__(self):
return self.value
def movementVector(self):
return [(-1, 0), (1, 0), (0, -1), (0, 1)][self.value]
| ):
HORIZ = 0
VERT = 1
LEFTUP = 2
RIGHTUP = 3
INTERSECTION = 4
EMPTY = 5
def __int__(self):
return self.value
class CartDir(Enum):
| 64 | 64 | 80 | 5 | 58 | pantaryl/adventofcode | 2018/src/day13.py | Python | CartDir | CartDir | 18 | 28 | 18 | 18 | 5e5a78a1b3f0684a40a035eaed1413d207305fc1 | bigcode/the-stack | train |
13a533162ad857ea8dfaa67e | train | function | def printGrid(grid):
for y in range(len(grid.keys())):
for x in range(len(grid[y].keys())):
print(grid[y][x], end='')
print()
print()
| def printGrid(grid):
| for y in range(len(grid.keys())):
for x in range(len(grid[y].keys())):
print(grid[y][x], end='')
print()
print()
| = max(railgrid.keys()) + 1
for y in range(gridY):
for x in range(gridX):
if x not in railgrid[y]:
railgrid[y][x] = Rail(x, y, ' ')
return railgrid, carts
def printGrid(grid):
| 64 | 64 | 42 | 5 | 58 | pantaryl/adventofcode | 2018/src/day13.py | Python | printGrid | printGrid | 153 | 158 | 153 | 153 | 82e693b3cd41f0740b5cb2b447c2c50dea07be7e | bigcode/the-stack | train |
a6a5c76fdcf0322897bc7002 | train | class | class Cart():
def __init__(self, x, y, char):
self.x = x
self.y = y
self.dir = determineCarType(char)
self.turnIdx = 0
global CartId
self.cartId = CartId + 1
CartId += 1
def setNextLoc(self, x, y, newDir, grid):
grid[self.y][self.x].removeCar(self... | class Cart():
| def __init__(self, x, y, char):
self.x = x
self.y = y
self.dir = determineCarType(char)
self.turnIdx = 0
global CartId
self.cartId = CartId + 1
CartId += 1
def setNextLoc(self, x, y, newDir, grid):
grid[self.y][self.x].removeCar(self)
self... | UP = 3
INTERSECTION = 4
EMPTY = 5
def __int__(self):
return self.value
class CartDir(Enum):
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
def __int__(self):
return self.value
def movementVector(self):
return [(-1, 0), (1, 0), (0, -1), (0, 1)][self.va... | 155 | 155 | 519 | 3 | 151 | pantaryl/adventofcode | 2018/src/day13.py | Python | Cart | Cart | 37 | 96 | 37 | 37 | 05ebbb0c889a3a9f27fcae0e22aa2fbca5b533bf | bigcode/the-stack | train |
c4ce304c3e3c9049065a26f6 | train | function | def determineCarType(char):
return CartDir(CartDirTypes.index(char))
| def determineCarType(char):
| return CartDir(CartDirTypes.index(char))
| return self.value
def movementVector(self):
return [(-1, 0), (1, 0), (0, -1), (0, 1)][self.value]
RailTypes = "-|\\/+ "
CartDirTypes = '<>^v'
def determineCarType(char):
| 64 | 64 | 17 | 6 | 58 | pantaryl/adventofcode | 2018/src/day13.py | Python | determineCarType | determineCarType | 32 | 33 | 32 | 32 | 762a5d21260200c651fe42fb17a63cfb002fe4aa | bigcode/the-stack | train |
cb821b3ae9b556b324488247 | train | class | class Rail():
def __init__(self, x, y, char, cars=None):
self.x = x
self.y = y
self.type = determineRailType(char, cars is not None)
self.cars = cars if cars else []
def hasCar(self):
return len(self.cars) > 0
def removeCar(self, car):
self.cars.remove(car)
... | class Rail():
| def __init__(self, x, y, char, cars=None):
self.x = x
self.y = y
self.type = determineRailType(char, cars is not None)
self.cars = cars if cars else []
def hasCar(self):
return len(self.cars) > 0
def removeCar(self, car):
self.cars.remove(car)
def addCa... | vector = moveDir.movementVector()
self.setNextLoc(self.x + vector[0], self.y + vector[1], moveDir, grid)
def __repr__(self):
return "{:d}, {:d} - {}".format(self.x, self.y, self.dir)
class Rail():
| 64 | 64 | 161 | 3 | 61 | pantaryl/adventofcode | 2018/src/day13.py | Python | Rail | Rail | 98 | 120 | 98 | 98 | 222b723aa56749d1ba77e780fa4de87f591641ef | bigcode/the-stack | train |
d0fb92a629dcba768261c91d | train | class | class ConfigView(object):
"""A configuration "view" is a query into a program's configuration
data. A view represents a hypothetical location in the configuration
tree; to extract the data from the location, a client typically
calls the ``view.get()`` method. The client can access children in
the tr... | class ConfigView(object):
| """A configuration "view" is a query into a program's configuration
data. A view represents a hypothetical location in the configuration
tree; to extract the data from the location, a client typically
calls the ``view.get()`` method. The client can access children in
the tree (subviews) by subscript... | += ': {0}'.format(reason)
super(ConfigReadError, self).__init__(message)
# Views and sources.
class ConfigSource(dict):
"""A dictionary augmented with metadata about the source of the
configuration.
"""
def __init__(self, value, filename=None, default=False):
super(ConfigSource, sel... | 256 | 256 | 1,602 | 5 | 251 | maniekmankowski/beets | beets/util/confit.py | Python | ConfigView | ConfigView | 148 | 369 | 148 | 148 | 494acab931077bbf940f1396ab12838fd1b9c874 | bigcode/the-stack | train |
883ff0732bf49d95bec7a3aa | train | function | def _package_path(name):
"""Returns the path to the package containing the named module or
None if the path could not be identified (e.g., if
``name == "__main__"``).
"""
loader = pkgutil.get_loader(name)
if loader is None or name == '__main__':
return None
if hasattr(loader, 'get_f... | def _package_path(name):
| """Returns the path to the package containing the named module or
None if the path could not be identified (e.g., if
``name == "__main__"``).
"""
loader = pkgutil.get_loader(name)
if loader is None or name == '__main__':
return None
if hasattr(loader, 'get_filename'):
filepa... | def add(self, value):
self.parent.add({self.key: value})
def root(self):
return self.parent.root()
# Config file paths, including platform-specific paths and in-package
# defaults.
# Based on get_root_path from Flask by Armin Ronacher.
def _package_path(name):
| 64 | 64 | 127 | 6 | 58 | maniekmankowski/beets | beets/util/confit.py | Python | _package_path | _package_path | 456 | 472 | 456 | 456 | af074006b26a5d463d75dd6b58f2ccc6b092c2e9 | bigcode/the-stack | train |
5ea62567b83ae53e28c47398 | train | class | class ConfigValueError(ConfigError):
"""The value in the configuration is illegal."""
| class ConfigValueError(ConfigError):
| """The value in the configuration is illegal."""
| except StopIteration:
raise ValueError()
# Exceptions.
class ConfigError(Exception):
"""Base class for exceptions raised when querying a configuration.
"""
class NotFoundError(ConfigError):
"""A requested value could not be found in the configuration trees.
"""
class ConfigValueError(Co... | 63 | 64 | 17 | 7 | 56 | maniekmankowski/beets | beets/util/confit.py | Python | ConfigValueError | ConfigValueError | 79 | 80 | 79 | 79 | 809ec5c23eb2cda4e760582cfef9cea10faa103f | bigcode/the-stack | train |
87e5fdbe7f2bdf778836b2d7 | train | function | def as_template(value):
"""Convert a simple "shorthand" Python value to a `Template`.
"""
if isinstance(value, Template):
# If it's already a Template, pass it through.
return value
elif isinstance(value, collections.Mapping):
# Dictionaries work as templates.
return Mapp... | def as_template(value):
| """Convert a simple "shorthand" Python value to a `Template`.
"""
if isinstance(value, Template):
# If it's already a Template, pass it through.
return value
elif isinstance(value, collections.Mapping):
# Dictionaries work as templates.
return MappingTemplate(value)
e... | class AttrDict(dict):
"""A `dict` subclass that can be accessed via attributes (dot
notation) for convenience.
"""
def __getattr__(self, key):
if key in self:
return self[key]
else:
raise AttributeError(key)
def as_template(value):
| 64 | 64 | 204 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | as_template | as_template | 1,253 | 1,281 | 1,253 | 1,253 | 424add78b4cf690fd0d085bf7569540840866114 | bigcode/the-stack | train |
80cdae08219d4cb6d04876c1 | train | function | def config_dirs():
"""Return a platform-specific list of candidates for user
configuration directories on the system.
The candidates are in order of priority, from highest to lowest. The
last element is the "fallback" location to be used when no
higher-priority config file exists.
"""
paths... | def config_dirs():
| """Return a platform-specific list of candidates for user
configuration directories on the system.
The candidates are in order of priority, from highest to lowest. The
last element is the "fallback" location to be used when no
higher-priority config file exists.
"""
paths = []
if platf... | is None or name == '__main__':
return None
if hasattr(loader, 'get_filename'):
filepath = loader.get_filename(name)
else:
# Fall back to importing the specified module.
__import__(name)
filepath = sys.modules[name].__file__
return os.path.dirname(os.path.abspath(fi... | 72 | 72 | 241 | 4 | 68 | maniekmankowski/beets | beets/util/confit.py | Python | config_dirs | config_dirs | 475 | 508 | 475 | 475 | 58ce6f853e91bdaac22d92824333cccab025cebb | bigcode/the-stack | train |
c64ebe102f11cd7d7c89b764 | train | class | class ConfigSource(dict):
"""A dictionary augmented with metadata about the source of the
configuration.
"""
def __init__(self, value, filename=None, default=False):
super(ConfigSource, self).__init__(value)
if filename is not None and not isinstance(filename, BASESTRING):
ra... | class ConfigSource(dict):
| """A dictionary augmented with metadata about the source of the
configuration.
"""
def __init__(self, value, filename=None, default=False):
super(ConfigSource, self).__init__(value)
if filename is not None and not isinstance(filename, BASESTRING):
raise TypeError('filename mu... | (
reason.problem_mark.line + 1,
reason.problem_mark.column + 1,
)
elif reason:
# Generic error message uses exception's message.
message += ': {0}'.format(reason)
super(ConfigReadError, self).__init__(message)
# Views and sources.
cl... | 67 | 67 | 226 | 5 | 62 | maniekmankowski/beets | beets/util/confit.py | Python | ConfigSource | ConfigSource | 116 | 145 | 116 | 116 | 33949d422c308d68396e293d62430bffab29581c | bigcode/the-stack | train |
0aceecdd36e81ea027696150 | train | class | class MappingTemplate(Template):
"""A template that uses a dictionary to specify other types for the
values for a set of keys and produce a validated `AttrDict`.
"""
def __init__(self, mapping):
"""Create a template according to a dict (mapping). The
mapping's values should themselves ei... | class MappingTemplate(Template):
| """A template that uses a dictionary to specify other types for the
values for a set of keys and produce a validated `AttrDict`.
"""
def __init__(self, mapping):
"""Create a template according to a dict (mapping). The
mapping's values should themselves either be Types or
converti... | Check that the value is an int or a float.
"""
if isinstance(value, NUMERIC_TYPES):
return value
else:
self.fail(
'must be numeric, not {0}'.format(type(value).__name__),
view,
True
)
class MappingTemplate(Templa... | 64 | 64 | 203 | 6 | 58 | maniekmankowski/beets | beets/util/confit.py | Python | MappingTemplate | MappingTemplate | 969 | 993 | 969 | 969 | 7c740d7ef376e3753b66a81b4f3d5ef310aa18dc | bigcode/the-stack | train |
68013c56e143ba9f15453c5f | train | class | class NotFoundError(ConfigError):
"""A requested value could not be found in the configuration trees.
"""
| class NotFoundError(ConfigError):
| """A requested value could not be found in the configuration trees.
"""
| iter(sequence)
try:
if PY3:
return next(it)
else:
return it.next()
except StopIteration:
raise ValueError()
# Exceptions.
class ConfigError(Exception):
"""Base class for exceptions raised when querying a configuration.
"""
class NotFoundError(ConfigErr... | 63 | 64 | 23 | 7 | 56 | maniekmankowski/beets | beets/util/confit.py | Python | NotFoundError | NotFoundError | 74 | 76 | 74 | 74 | 40f65c789f0d2d285e7696ddf3daaee6034a110f | bigcode/the-stack | train |
09b9d9ed48452e1e593b19d0 | train | class | class Loader(yaml.SafeLoader):
"""A customized YAML loader. This loader deviates from the official
YAML spec in a few convenient ways:
- All strings as are Unicode objects.
- All maps are OrderedDicts.
- Strings can begin with % without quotation.
"""
# All strings should be Unicode objects... | class Loader(yaml.SafeLoader):
| """A customized YAML loader. This loader deviates from the official
YAML spec in a few convenient ways:
- All strings as are Unicode objects.
- All maps are OrderedDicts.
- Strings can begin with % without quotation.
"""
# All strings should be Unicode objects, regardless of contents.
d... | paths.append(os.environ[WINDOWS_DIR_VAR])
else:
# Assume Unix.
paths.append(UNIX_DIR_FALLBACK)
if UNIX_DIR_VAR in os.environ:
paths.append(os.environ[UNIX_DIR_VAR])
# Expand and deduplicate paths.
out = []
for path in paths:
path = os.path.abspat... | 107 | 107 | 358 | 7 | 100 | maniekmankowski/beets | beets/util/confit.py | Python | Loader | Loader | 513 | 561 | 513 | 513 | b8391589e24b93bf288ea217a7280bc2c0cf8f39 | bigcode/the-stack | train |
93976bd14e822babf918f94d | train | class | class Choice(Template):
"""A template that permits values from a sequence of choices.
"""
def __init__(self, choices):
"""Create a template that validates any of the values from the
iterable `choices`.
If `choices` is a map, then the corresponding value is emitted.
Otherwise... | class Choice(Template):
| """A template that permits values from a sequence of choices.
"""
def __init__(self, choices):
"""Create a template that validates any of the values from the
iterable `choices`.
If `choices` is a map, then the corresponding value is emitted.
Otherwise, the value itself is em... | isinstance(value, BASESTRING):
if self.pattern and not self.regex.match(value):
self.fail(
"must match the pattern {0}".format(self.pattern),
view
)
return value
else:
self.fail('must be a string', view,... | 64 | 64 | 207 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | Choice | Choice | 1,022 | 1,052 | 1,022 | 1,022 | 78de6ae8454bd9e9a7693e97a669dc3524f8522a | bigcode/the-stack | train |
6984d8a5f53e57e886f38aba | train | function | def iter_first(sequence):
"""Get the first element from an iterable or raise a ValueError if
the iterator generates no values.
"""
it = iter(sequence)
try:
if PY3:
return next(it)
else:
return it.next()
except StopIteration:
raise ValueError()
| def iter_first(sequence):
| """Get the first element from an iterable or raise a ValueError if
the iterator generates no values.
"""
it = iter(sequence)
try:
if PY3:
return next(it)
else:
return it.next()
except StopIteration:
raise ValueError()
| 3
STRING = str if PY3 else unicode
BASESTRING = str if PY3 else basestring
NUMERIC_TYPES = (int, float) if PY3 else (int, float, long)
TYPE_TYPES = (type,) if PY3 else (type, types.ClassType)
def iter_first(sequence):
| 64 | 64 | 67 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | iter_first | iter_first | 53 | 64 | 53 | 53 | 85a184889b5f000e3564718d05131041f46aa8ac | bigcode/the-stack | train |
b70049cedf46566fe6fa81b9 | train | class | class Filename(Template):
"""A template that validates strings as filenames.
Filenames are returned as absolute, tilde-free paths.
Relative paths are relative to the template's `cwd` argument
when it is specified, then the configuration directory (see
the `config_dir` method) if they come from a f... | class Filename(Template):
| """A template that validates strings as filenames.
Filenames are returned as absolute, tilde-free paths.
Relative paths are relative to the template's `cwd` argument
when it is specified, then the configuration directory (see
the `config_dir` method) if they come from a file. Otherwise,
they a... | values that are lists of strings.
Validates both actual YAML string lists and single strings. Strings
can optionally be split on whitespace.
"""
def __init__(self, split=True):
"""Create a new template.
`split` indicates whether, when the underlying value is a single
string, i... | 256 | 256 | 854 | 5 | 251 | maniekmankowski/beets | beets/util/confit.py | Python | Filename | Filename | 1,097 | 1,215 | 1,097 | 1,097 | 425d46b6f288010d2145f1740abedf9231dc3813 | bigcode/the-stack | train |
efbe80f26cbd38d97c75b301 | train | class | class Dumper(yaml.SafeDumper):
"""A PyYAML Dumper that represents OrderedDicts as ordinary mappings
(in order, of course).
"""
# From http://pyyaml.org/attachment/ticket/161/use_ordered_dict.py
def represent_mapping(self, tag, mapping, flow_style=None):
value = []
node = yaml.Mapping... | class Dumper(yaml.SafeDumper):
| """A PyYAML Dumper that represents OrderedDicts as ordinary mappings
(in order, of course).
"""
# From http://pyyaml.org/attachment/ticket/161/use_ordered_dict.py
def represent_mapping(self, tag, mapping, flow_style=None):
value = []
node = yaml.MappingNode(tag, value, flow_style=flo... | ,2002:str', Loader._construct_unicode)
Loader.add_constructor('tag:yaml.org,2002:map', Loader.construct_yaml_map)
Loader.add_constructor('tag:yaml.org,2002:omap', Loader.construct_yaml_map)
def load_yaml(filename):
"""Read a YAML document from a file. If the file cannot be read or
parsed, a ConfigReadError is... | 144 | 144 | 480 | 9 | 135 | maniekmankowski/beets | beets/util/confit.py | Python | Dumper | Dumper | 582 | 636 | 582 | 582 | cb7cf65b840e79714185797ec4528f4b1450bcc0 | bigcode/the-stack | train |
5529271b0a29cf1b3241040c | train | function | def load_yaml(filename):
"""Read a YAML document from a file. If the file cannot be read or
parsed, a ConfigReadError is raised.
"""
try:
with open(filename, 'r') as f:
return yaml.load(f, Loader=Loader)
except (IOError, yaml.error.YAMLError) as exc:
raise ConfigReadError... | def load_yaml(filename):
| """Read a YAML document from a file. If the file cannot be read or
parsed, a ConfigReadError is raised.
"""
try:
with open(filename, 'r') as f:
return yaml.load(f, Loader=Loader)
except (IOError, yaml.error.YAMLError) as exc:
raise ConfigReadError(filename, exc)
| == '%'
Loader.add_constructor('tag:yaml.org,2002:str', Loader._construct_unicode)
Loader.add_constructor('tag:yaml.org,2002:map', Loader.construct_yaml_map)
Loader.add_constructor('tag:yaml.org,2002:omap', Loader.construct_yaml_map)
def load_yaml(filename):
| 64 | 64 | 83 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | load_yaml | load_yaml | 569 | 577 | 569 | 569 | 5d8b71a2bbff20a6f85bce528fbbe808286c8eef | bigcode/the-stack | train |
f823d865081e928ddcf4aa68 | train | class | class Configuration(RootView):
def __init__(self, appname, modname=None, read=True):
"""Create a configuration object by reading the
automatically-discovered config files for the application for a
given name. If `modname` is specified, it should be the import
name of a module whose p... | class Configuration(RootView):
| def __init__(self, appname, modname=None, read=True):
"""Create a configuration object by reading the
automatically-discovered config files for the application for a
given name. If `modname` is specified, it should be the import
name of a module whose package will be searched for a d... | Dumper.represent_list)
def restore_yaml_comments(data, default_data):
"""Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping.
... | 256 | 256 | 1,072 | 6 | 250 | maniekmankowski/beets | beets/util/confit.py | Python | Configuration | Configuration | 679 | 814 | 679 | 679 | 40d39a2f02e3162031cbf9e17429fdb5c3c6b37b | bigcode/the-stack | train |
ef99dc14fca8be2f387bd624 | train | class | class ConfigError(Exception):
"""Base class for exceptions raised when querying a configuration.
"""
| class ConfigError(Exception):
| """Base class for exceptions raised when querying a configuration.
"""
| from an iterable or raise a ValueError if
the iterator generates no values.
"""
it = iter(sequence)
try:
if PY3:
return next(it)
else:
return it.next()
except StopIteration:
raise ValueError()
# Exceptions.
class ConfigError(Exception):
| 64 | 64 | 19 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | ConfigError | ConfigError | 69 | 71 | 69 | 69 | f1c014472c026c9797de31820c9c3779879a83a5 | bigcode/the-stack | train |
abefe28cbabec9361925a091 | train | class | class Number(Template):
"""A numeric type: either an integer or a floating-point number.
"""
def convert(self, value, view):
"""Check that the value is an int or a float.
"""
if isinstance(value, NUMERIC_TYPES):
return value
else:
self.fail(
... | class Number(Template):
| """A numeric type: either an integer or a floating-point number.
"""
def convert(self, value, view):
"""Check that the value is an int or a float.
"""
if isinstance(value, NUMERIC_TYPES):
return value
else:
self.fail(
'must be numeric, ... | , view):
"""Check that the value is an integer. Floats are rounded.
"""
if isinstance(value, int):
return value
elif isinstance(value, float):
return int(value)
else:
self.fail('must be a number', view, True)
class Number(Template):
| 64 | 64 | 91 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | Number | Number | 953 | 966 | 953 | 953 | 24e671d7e2b207ea65f2e5617e8156f57a082d80 | bigcode/the-stack | train |
4a62b89290732c6708844c43 | train | class | class LazyConfig(Configuration):
"""A Configuration at reads files on demand when it is first
accessed. This is appropriate for using as a global config object at
the module level.
"""
def __init__(self, appname, modname=None):
super(LazyConfig, self).__init__(appname, modname, False)
... | class LazyConfig(Configuration):
| """A Configuration at reads files on demand when it is first
accessed. This is appropriate for using as a global config object at
the module level.
"""
def __init__(self, appname, modname=None):
super(LazyConfig, self).__init__(appname, modname, False)
self._materialized = False # H... | ,
default_flow_style=None, indent=4,
width=1000)
# Restore comments to the YAML text.
default_source = None
for source in self.sources:
if source.default:
default_source = source
break
... | 102 | 102 | 343 | 5 | 96 | maniekmankowski/beets | beets/util/confit.py | Python | LazyConfig | LazyConfig | 817 | 858 | 817 | 817 | cc0bac660c3eb3f5e90a6904e6613f456471ad72 | bigcode/the-stack | train |
b7fdb760f5c5c04e9b0adf3d | train | function | def restore_yaml_comments(data, default_data):
"""Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping.
"""
comment_map = dict... | def restore_yaml_comments(data, default_data):
| """Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping.
"""
comment_map = dict()
default_lines = iter(default_data.splitl... | :null', '')
Dumper.add_representer(OrderedDict, Dumper.represent_dict)
Dumper.add_representer(bool, Dumper.represent_bool)
Dumper.add_representer(type(None), Dumper.represent_none)
Dumper.add_representer(list, Dumper.represent_list)
def restore_yaml_comments(data, default_data):
| 72 | 72 | 240 | 9 | 63 | maniekmankowski/beets | beets/util/confit.py | Python | restore_yaml_comments | restore_yaml_comments | 645 | 674 | 645 | 645 | 2f0c238aecdb7b6a4050830e1b7f2b465ad1dc54 | bigcode/the-stack | train |
c05ee37bcc7f51140a0e7413 | train | class | class StrSeq(Template):
"""A template for values that are lists of strings.
Validates both actual YAML string lists and single strings. Strings
can optionally be split on whitespace.
"""
def __init__(self, split=True):
"""Create a new template.
`split` indicates whether, when the u... | class StrSeq(Template):
| """A template for values that are lists of strings.
Validates both actual YAML string lists and single strings. Strings
can optionally be split on whitespace.
"""
def __init__(self, split=True):
"""Create a new template.
`split` indicates whether, when the underlying value is a sin... | {0}, not {1}'.format(
repr(list(self.choices)), repr(value)
),
view
)
if isinstance(self.choices, collections.Mapping):
return self.choices[value]
else:
return value
def __repr__(self):
return 'Choice(... | 78 | 78 | 262 | 6 | 72 | maniekmankowski/beets | beets/util/confit.py | Python | StrSeq | StrSeq | 1,055 | 1,094 | 1,055 | 1,055 | cf00137da548974c4d1e721293517dd281c593cb | bigcode/the-stack | train |
03b0068b4743f07f21c1b86a | train | class | class TypeTemplate(Template):
"""A simple template that checks that a value is an instance of a
desired Python type.
"""
def __init__(self, typ, default=REQUIRED):
"""Create a template that checks that the value is an instance
of `typ`.
"""
super(TypeTemplate, self).__ini... | class TypeTemplate(Template):
| """A simple template that checks that a value is an instance of a
desired Python type.
"""
def __init__(self, typ, default=REQUIRED):
"""Create a template that checks that the value is an instance
of `typ`.
"""
super(TypeTemplate, self).__init__(default)
self.typ ... | (
self.resolve_relative_to(view, template),
path,
)
elif source.filename or self.in_app_dir:
# From defaults: relative to the app's directory.
path = os.path.join(view.root().config_dir(), path)
return os.path.... | 64 | 64 | 143 | 6 | 58 | maniekmankowski/beets | beets/util/confit.py | Python | TypeTemplate | TypeTemplate | 1,218 | 1,239 | 1,218 | 1,218 | 758c31380eff2fc069beaa5e89dc4c929a5ce163 | bigcode/the-stack | train |
bd04c30f62ab6ea268fce792 | train | class | class ConfigTemplateError(ConfigError):
"""Base class for exceptions raised because of an invalid template.
"""
| class ConfigTemplateError(ConfigError):
| """Base class for exceptions raised because of an invalid template.
"""
| requested value could not be found in the configuration trees.
"""
class ConfigValueError(ConfigError):
"""The value in the configuration is illegal."""
class ConfigTypeError(ConfigValueError):
"""The value in the configuration did not match the expected type.
"""
class ConfigTemplateError(ConfigEr... | 63 | 64 | 22 | 7 | 56 | maniekmankowski/beets | beets/util/confit.py | Python | ConfigTemplateError | ConfigTemplateError | 88 | 90 | 88 | 88 | 7c2d371ec9dffa1df4cc2ee8318699ca96613586 | bigcode/the-stack | train |
75a7d2882c790ce2499dbf34 | train | class | class ConfigTypeError(ConfigValueError):
"""The value in the configuration did not match the expected type.
"""
| class ConfigTypeError(ConfigValueError):
| """The value in the configuration did not match the expected type.
"""
| """Base class for exceptions raised when querying a configuration.
"""
class NotFoundError(ConfigError):
"""A requested value could not be found in the configuration trees.
"""
class ConfigValueError(ConfigError):
"""The value in the configuration is illegal."""
class ConfigTypeError(ConfigValueErr... | 63 | 64 | 24 | 8 | 55 | maniekmankowski/beets | beets/util/confit.py | Python | ConfigTypeError | ConfigTypeError | 83 | 85 | 83 | 83 | 714972f5e527d27f0904ffa444ec65821de0ed5c | bigcode/the-stack | train |
7e68e0dab986f2b3e9be04fa | train | class | class Template(object):
"""A value template for configuration fields.
The template works like a type and instructs Confit about how to
interpret a deserialized YAML value. This includes type conversions,
providing a default value, and validating for errors. For example, a
filepath type might expand... | class Template(object):
| """A value template for configuration fields.
The template works like a type and instructs Confit about how to
interpret a deserialized YAML value. This includes type conversions,
providing a default value, and validating for errors. For example, a
filepath type might expand tildes and check that t... | not self._materialized:
# Buffer additions to end.
self._lazy_suffix += self.sources
del self.sources[:]
def set(self, value):
super(LazyConfig, self).set(value)
if not self._materialized:
# Buffer additions to beginning.
self._lazy_prefi... | 156 | 156 | 523 | 4 | 152 | maniekmankowski/beets | beets/util/confit.py | Python | Template | Template | 870 | 936 | 870 | 870 | 2d64529bcebc8f392ee113028f76c06127497cd9 | bigcode/the-stack | train |
1b82a91bd1185993ce384af7 | train | class | class String(Template):
"""A string configuration value template.
"""
def __init__(self, default=REQUIRED, pattern=None):
"""Create a template with the added optional `pattern` argument,
a regular expression string that the value should match.
"""
super(String, self).__init__... | class String(Template):
| """A string configuration value template.
"""
def __init__(self, default=REQUIRED, pattern=None):
"""Create a template with the added optional `pattern` argument,
a regular expression string that the value should match.
"""
super(String, self).__init__(default)
self.p... | .
"""
out = AttrDict()
for key, typ in self.subtemplates.items():
out[key] = typ.value(view[key], self)
return out
def __repr__(self):
return 'MappingTemplate({0})'.format(repr(self.subtemplates))
class String(Template):
| 64 | 64 | 171 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | String | String | 996 | 1,019 | 996 | 996 | d079b8156537587b105553c228fe936591350c8e | bigcode/the-stack | train |
4b00e325c4cc64574ec3cf19 | train | class | class Subview(ConfigView):
"""A subview accessed via a subscript of a parent view."""
def __init__(self, parent, key):
"""Make a subview of a parent view for a given subscript key.
"""
self.parent = parent
self.key = key
# Choose a human-readable name for this view.
... | class Subview(ConfigView):
| """A subview accessed via a subscript of a parent view."""
def __init__(self, parent, key):
"""Make a subview of a parent view for a given subscript key.
"""
self.parent = parent
self.key = key
# Choose a human-readable name for this view.
if isinstance(self.pare... | )
self.name = ROOT_NAME
def add(self, obj):
self.sources.append(ConfigSource.of(obj))
def set(self, value):
self.sources.insert(0, ConfigSource.of(value))
def resolve(self):
return ((dict(s), s) for s in self.sources)
def clear(self):
"""Remove all sources fro... | 97 | 97 | 325 | 6 | 90 | maniekmankowski/beets | beets/util/confit.py | Python | Subview | Subview | 401 | 449 | 401 | 401 | cc3a4f4d8323720a7d5ce0e5f0961c1e65d6c948 | bigcode/the-stack | train |
0b669ba2cba33afd5332911c | train | class | class RootView(ConfigView):
"""The base of a view hierarchy. This view keeps track of the
sources that may be accessed by subviews.
"""
def __init__(self, sources):
"""Create a configuration hierarchy for a list of sources. At
least one source must be provided. The first source in the li... | class RootView(ConfigView):
| """The base of a view hierarchy. This view keeps track of the
sources that may be accessed by subviews.
"""
def __init__(self, sources):
"""Create a configuration hierarchy for a list of sources. At
least one source must be provided. The first source in the list
has the highest p... | deprecated).
def as_filename(self):
return self.get(Filename())
def as_choice(self, choices):
return self.get(Choice(choices))
def as_number(self):
return self.get(Number())
def as_str_seq(self):
return self.get(StrSeq())
class RootView(ConfigView):
| 64 | 64 | 178 | 6 | 58 | maniekmankowski/beets | beets/util/confit.py | Python | RootView | RootView | 372 | 398 | 372 | 372 | 769c38c0ab8aca03d05d4145142ae64d9f86284c | bigcode/the-stack | train |
2515508a2e13f8502815812b | train | class | class AttrDict(dict):
"""A `dict` subclass that can be accessed via attributes (dot
notation) for convenience.
"""
def __getattr__(self, key):
if key in self:
return self[key]
else:
raise AttributeError(key)
| class AttrDict(dict):
| """A `dict` subclass that can be accessed via attributes (dot
notation) for convenience.
"""
def __getattr__(self, key):
if key in self:
return self[key]
else:
raise AttributeError(key)
| (self, value, view):
if not isinstance(value, self.typ):
self.fail(
'must be a {0}, not {1}'.format(
self.typ.__name__,
type(value).__name__,
),
view,
True
)
return value
class... | 64 | 64 | 59 | 5 | 58 | maniekmankowski/beets | beets/util/confit.py | Python | AttrDict | AttrDict | 1,242 | 1,250 | 1,242 | 1,242 | 4ebf27df6861e7e87785efe94221d33c8ac081c8 | bigcode/the-stack | train |
d15b9b5d45544b97d4a629fb | train | class | class ConfigReadError(ConfigError):
"""A configuration file could not be read."""
def __init__(self, filename, reason=None):
self.filename = filename
self.reason = reason
message = 'file {0} could not be read'.format(filename)
if isinstance(reason, yaml.scanner.ScannerError) and... | class ConfigReadError(ConfigError):
| """A configuration file could not be read."""
def __init__(self, filename, reason=None):
self.filename = filename
self.reason = reason
message = 'file {0} could not be read'.format(filename)
if isinstance(reason, yaml.scanner.ScannerError) and \
reason.problem ==... | The value in the configuration is illegal."""
class ConfigTypeError(ConfigValueError):
"""The value in the configuration did not match the expected type.
"""
class ConfigTemplateError(ConfigError):
"""Base class for exceptions raised because of an invalid template.
"""
class ConfigReadError(ConfigEr... | 63 | 64 | 166 | 7 | 56 | maniekmankowski/beets | beets/util/confit.py | Python | ConfigReadError | ConfigReadError | 93 | 111 | 93 | 93 | 4dc04e573e991498f0165eb9c3d71463d849a078 | bigcode/the-stack | train |
248cdb190a1af21e5decf90b | train | class | class Integer(Template):
"""An integer configuration value template.
"""
def convert(self, value, view):
"""Check that the value is an integer. Floats are rounded.
"""
if isinstance(value, int):
return value
elif isinstance(value, float):
return int(va... | class Integer(Template):
| """An integer configuration value template.
"""
def convert(self, value, view):
"""Check that the value is an integer. Floats are rounded.
"""
if isinstance(value, int):
return value
elif isinstance(value, float):
return int(value)
else:
... |
raise exc_class(
'{0}: {1}'.format(view.name, message)
)
def __repr__(self):
return '{0}({1})'.format(
type(self).__name__,
'' if self.default is REQUIRED else repr(self.default),
)
class Integer(Template):
| 64 | 64 | 80 | 5 | 59 | maniekmankowski/beets | beets/util/confit.py | Python | Integer | Integer | 939 | 950 | 939 | 939 | 91d5ebbe3b89eac753fc22ef006b9dc9190e534d | bigcode/the-stack | train |
9182bb154c1bd64e792e3d59 | train | function | def eColOne (yI, obj, num, column, Ns, ree=[]) : # This should be equivalent to actual Lyon et al 4 recycling
y = np.array([i for i in yI])
naq = obj.naq
nsy = obj.nsy
norgy = obj.norgy
stream = np.zero... | def eColOne (yI, obj, num, column, Ns, ree=[]) : # This should be equivalent to actual Lyon et al 4 recycling
| y = np.array([i for i in yI])
naq = obj.naq
nsy = obj.nsy
norgy = obj.norgy
stream = np.zeros(obj.ns)
###############################################################################
count =... | level, pos = get_level(item_num)
next_level = pow(2, level+1) #items in next level
add = next_level-(pow(2, level)-pos)
left = item_num + add
return (left, left+1)[dir=='right']
def get_level(curNum):
'''
helper function to get level and pos of a number in a binar... | 254 | 256 | 1,008 | 34 | 219 | solventx/solventx | solventx/solventx.py | Python | eColOne | eColOne | 572 | 635 | 572 | 573 | cb012b207cb9d3c647384f6da092a1f1a5f077b4 | bigcode/the-stack | train |
60e6549c3a6ddf129e1f3722 | train | function | def get_level(curNum):
'''
helper function to get level and pos of a number in a binary tree
0 level: 0
/ \
1 2 1
/ \ / \
3 4 5 6 2
get_level(2) => 1, 1
get_level(4) => 2, 1
'''
curNum = int(curNum)
level = 0
whil... | def get_level(curNum):
| '''
helper function to get level and pos of a number in a binary tree
0 level: 0
/ \
1 2 1
/ \ / \
3 4 5 6 2
get_level(2) => 1, 1
get_level(4) => 2, 1
'''
curNum = int(curNum)
level = 0
while pow(2, level+1) <= cu... | _num)
next_level = pow(2, level+1) #items in next level
add = next_level-(pow(2, level)-pos)
left = item_num + add
return (left, left+1)[dir=='right']
def get_level(curNum):
| 63 | 64 | 155 | 6 | 57 | solventx/solventx | solventx/solventx.py | Python | get_level | get_level | 549 | 566 | 549 | 549 | 87003678461281171429dc5b8869ebab6d4abff9 | bigcode/the-stack | train |
052697bd824ce54e5b7aa226 | train | function | def combine_dict(a, b):
c = {}
c.update(a)
c.update(b)
return c
| def combine_dict(a, b):
| c = {}
c.update(a)
c.update(b)
return c
| target
# -- end class
#####################################################################################################
#------------------------------HELPER FUNCTIONS------------------------------
#reverse key value pairs
def reverse_dict(D):
return {v: k for k, v in D.items()}
#combi... | 64 | 64 | 21 | 7 | 56 | solventx/solventx | solventx/solventx.py | Python | combine_dict | combine_dict | 475 | 479 | 475 | 475 | 3bfb776c0cebb6445802e2ddf422de201a04a932 | bigcode/the-stack | train |
7f9df5e1ad60b050790d1c50 | train | function | def highest_remaining(values, remove_n_lowest):
'''
values: numpy array containing values of components
'''
if type(values).__module__ == np.__name__: #values = numpy array
vals = values.tolist()
else:
vals = values
inds = [i for i in range(len(vals))]
if remove_n_lowest > len(vals):
indices... | def highest_remaining(values, remove_n_lowest):
| '''
values: numpy array containing values of components
'''
if type(values).__module__ == np.__name__: #values = numpy array
vals = values.tolist()
else:
vals = values
inds = [i for i in range(len(vals))]
if remove_n_lowest > len(vals):
indices = []
elif remove_n_lowest >= 0:
pairs = [... | ) #matrix rows
j = len(d[key]) #matrix cols
s = flatten(d) #1d list of dictionary `d`
return list(np.sum(s.reshape(i, j), axis=0)) #sum cols of s
def highest_remaining(values, remove_n_lowest):
| 64 | 64 | 169 | 10 | 53 | solventx/solventx | solventx/solventx.py | Python | highest_remaining | highest_remaining | 656 | 674 | 656 | 656 | 2481e9ec4acf57f504497274524869b02054d44a | bigcode/the-stack | train |
08fdb303de56a3951b49f2d0 | train | function | def get_parent(var):
'''
takes variable name, determines module number, then returns the column_names
and module number that feeds into that module_num
Extraction-1 -> Extraction-0
Extraction-4 -> Strip-1
Strip-4 -> None
Extraction-0 -> None
'''
name, num = var.split('-')
num = int(num)
... | def get_parent(var):
| '''
takes variable name, determines module number, then returns the column_names
and module number that feeds into that module_num
Extraction-1 -> Extraction-0
Extraction-4 -> Strip-1
Strip-4 -> None
Extraction-0 -> None
'''
name, num = var.split('-')
num = int(num)
if name != 'Extract... | --------------
#reverse key value pairs
def reverse_dict(D):
return {v: k for k, v in D.items()}
#combine a and b and return the new dictionary
def combine_dict(a, b):
c = {}
c.update(a)
c.update(b)
return c
def get_parent(var):
| 64 | 64 | 173 | 5 | 58 | solventx/solventx | solventx/solventx.py | Python | get_parent | get_parent | 482 | 499 | 482 | 482 | 87cc267f3c5f22d09730bfdeee81be8506ab7540 | bigcode/the-stack | train |
72ebced7803cd534d72e6a21 | train | function | def get_sums(d,key):
i = len(d) #matrix rows
j = len(d[key]) #matrix cols
s = flatten(d) #1d list of dictionary `d`
return list(np.sum(s.reshape(i, j), axis=0)) #sum cols of s
| def get_sums(d,key):
| i = len(d) #matrix rows
j = len(d[key]) #matrix cols
s = flatten(d) #1d list of dictionary `d`
return list(np.sum(s.reshape(i, j), axis=0)) #sum cols of s
| yI-y
def flatten(iter):
if type(iter) == dict:
return np.array(list(iter.values())).reshape(1, -1)[0]
elif type(iter) == list:
return np.array(iter).reshape(1, -1)[0]
def get_sums(d,key):
| 64 | 64 | 66 | 7 | 57 | solventx/solventx | solventx/solventx.py | Python | get_sums | get_sums | 646 | 650 | 646 | 646 | e696595555e0e6d5b74b86973ea16f6b5868cd6a | bigcode/the-stack | train |
ced6416c27ebf7d89c543a3a | train | class | class solventx:
coltypes = ['Extraction','Scrub','Strip']
ml2l = 0.001 # mililiter to liter
scale = 1 # volumetric scaling from unit ml/sec
g_p_kg = 1000 # grams to kg
s_p_h = 3600 # seconds to hours
target_conc ... | class solventx:
| coltypes = ['Extraction','Scrub','Strip']
ml2l = 0.001 # mililiter to liter
scale = 1 # volumetric scaling from unit ml/sec
g_p_kg = 1000 # grams to kg
s_p_h = 3600 # seconds to hours
target_conc = 45 #g/L
def __i... |
from scipy.optimize import root
import numpy as np
import cantera as ct
import pandas as pd
from solventx import result_struct as rs
from solventx import utilities
from solventx import config
import operator
import os
class solventx:
| 54 | 256 | 4,710 | 5 | 48 | solventx/solventx | solventx/solventx.py | Python | solventx | solventx | 16 | 459 | 16 | 17 | a2be135332aa588f0bfa1d3938534dc40f12a750 | bigcode/the-stack | train |
2b6794bb8918c4bc9dc8fac4 | train | function | def get_child(var, mod_nums):
'''
takes current module number (var), get child number from
column (coltype), check if child number in mod_nums,
return child otherwise return None
Extraction-1 -> Extraction-4 if it exists
Extraction-0 -> Extraction-2 if it exists
Strip-0 -> Extraction-1 if it ex... | def get_child(var, mod_nums):
| '''
takes current module number (var), get child number from
column (coltype), check if child number in mod_nums,
return child otherwise return None
Extraction-1 -> Extraction-4 if it exists
Extraction-0 -> Extraction-2 if it exists
Strip-0 -> Extraction-1 if it exists
'''
name, num = va... | , ' parent', (f'Extraction-{parentNum}',f'Strip-{parentNum}')[num % 2 == 0])
return (f'Strip-{parentNum}',f'Extraction-{parentNum}')[num % 2 == 0]
def get_child(var, mod_nums):
| 63 | 64 | 139 | 8 | 55 | solventx/solventx | solventx/solventx.py | Python | get_child | get_child | 503 | 523 | 503 | 503 | 3dd246192cdc9d22dbc79a36fc15a955b0769408 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.