text
stringlengths
5.6k
27.5k
length
int64
4.1k
4.35k
is_long_context
bool
2 classes
metric_val
float64
0.04
0.36
label_metric
stringclasses
1 value
source
stringclasses
1 value
threshold_scale
stringclasses
1 value
def get_imageId_from_fileName(filename, id_iter): """Get imageID from fileName if fileName is int, else return id_iter.""" filename = os.path.splitext(filename)[0] if filename.isdigit(): return int(filename) return id_iter def random_sample_crop(image, boxes): """Random Crop the image a...
4,316
false
0.077669
median
code
normalized
('date', (), {'date': end_period.strftime("%d-%m-%Y"), 'time': end_period.strftime("%H:%M")}) return data def get_procedure_type(methodType): return { 'aboveThresholdUA': 'Відкриті торги', 'belowThreshold': 'Допорогові закупівлі', 'negotiatio...
4,231
false
0.062461
median
code
normalized
self._ycmd_root_directory = None self._ycmd_settings_path = None self._working_directory = None self._python_binary_path = None self._server_idle_suicide_seconds = None self._server_check_interval_seconds = None # additional attributes, can be set via the properties ...
4,174
false
0.102127
median
code
normalized
cinder.volume.drivers.datera.datera_common as datc LOG = logging.getLogger(__name__) d_opts = [ cfg.StrOpt('datera_api_port', default='7717', help='Datera API port.'), cfg.StrOpt('datera_api_version', default='2', deprecated_for_removal=True, ...
4,153
false
0.082591
median
code
normalized
= img.cpu().numpy().copy()[0] # img_numpy = np.transpose(img_numpy, [1, 2, 0]) * [58.395, 57.12, 57.375] + [123.675, 116.28, 103.53] img_numpy = np.transpose(img_numpy, [1, 2, 0]) + [102.9801, 115.9465, 122.7717] img_numpy = img_numpy[:, :, ::-1] img_numpy = img_numpy.astype(np.uint8) ...
4,099
false
0.129034
median
code
normalized
ies: Maximum number of times to try logging in :param session_cookies: Cookies from a previous session (Will default to login if these are invalid) :param logging_level: Configures the `logging level <https://docs.python.org/3/library/logging.html#logging-levels>`_. Defaults to `INFO` :type max_...
4,170
false
0.067564
median
code
normalized
["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"] SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json" GENERATE_GOLDEN = False def test_random_crop_and_resize_op_c(plot=False): """ Test RandomCropAndResize op in c transforms """ logger.info("test_random_crop_and_re...
4,175
true
0.256549
median
code
normalized
dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. Default: if ``None``, uses a global default (see :func:`torch.set_default_tensor_type`). layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. Default: ``torch.strided``. ...
4,193
false
0.144545
median
code
normalized
("Starting factory %r" % self) self.startFactory() self.numPorts = self.numPorts + 1 def doStop(self): """Make sure stopFactory is called. Users should not call this function themselves! """ if self.numPorts == 0: # this shouldn't happen, but does so...
4,188
false
0.087868
median
code
normalized
GET']) def gameRoom(): global games verbose = (False or debugging) argumentsMakeGame = ['name', 'gameName', 'nrOfRounds', 'time', 'newGame'] argumentsJoinGame = ['name', 'gameName', 'newGame'] uniqueID = request.cookies.get('uniqueID') user = clients.find_User_By_uniqueID(uniqueID) if (not...
4,144
false
0.147817
median
code
normalized
contains: - state about the node (whether it's running, etc) - a Python subprocess.Popen object representing the running process - an RPC connection to the node - one or more P2P connections to the node To make things easier for the test writer, any unrecognised messages will be dispatched t...
4,250
false
0.088897
median
code
normalized
model architecture.") flags.DEFINE_string( "input_file", None, "Input TF example files (can be a glob or comma separated).") flags.DEFINE_string( "output_dir", None, "The output directory where the model checkpoints will be written.") ## Other parameters flags.DEFINE_string( "init_checkpoint", N...
4,263
false
0.099081
median
code
normalized
+ [[0], [0], [2.5]]]).T, 1, np.arange(12).reshape(-1, 3)) def test_creation(self): tree = kdtree.KDTree(self.shapes, max_depth=self.max_depth) self.assertEqual(tree.max_depth, self.max_depth) self.assertEqual(tree.surface, self.shapes) def t...
4,208
true
0.234808
median
code
normalized
256, out_channels=64, pooling=False)] layers += [ConvPoolBlock(in_channels=64, out_channels=128, pooling=True)] layers += [ConvPoolBlock(in_channels=128, out_channels=128, pooling=False)] layers += [ConvPoolBlock(in_channels=128, out_channels=192, pooling=True)] layers += [ConvPoolBlock(...
4,261
false
0.105961
median
code
normalized
multiprocessing.get_start_method(allow_none=True) is None: multiprocessing.set_start_method(method='spawn') self.logger = get_logger(name=__name__, save_file=args.log_path / args.run_name) # Checking whether inputs are correct. assert isinstance(model, nn.Module), '`model` must be...
4,181
false
0.088685
median
code
normalized
,,,,,,,,,,,,,,,,,,,,,,,,\ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\ ,,,,,,,,,,,,,,,,,,,,\n\ "* = GCMD controlled: http://gcmd.nasa.gov/learn/keyword_list.html\nThese datasets were reviewed in comparison to GCMD Keyword Version: 8.4.1",\ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\ ...
4,144
false
0.111606
median
code
normalized
import Context from .instrumentlookup import InstrumentLookup from .instrumentvalue import InstrumentValue from .layouts import layouts from .lotsizeconverter import LotSizeConverter, RaisingLotSizeConverter from .marketlookup import MarketLookup from .metadata import Metadata from .token import Instrument, Token from...
4,339
false
0.140568
median
code
normalized
Determine # the # prediction # scores # for transformed testing data.Using the estimated optimal classification threshold, compute accuracy and fairness metrics. # # %% # Load all necessary packages import sys sys.path.append("../") import numpy as np from tqdm import tqdm from aif360.datasets import BinaryLabelD...
4,121
false
0.093652
median
code
normalized
2), (2, 3)), 5: ((0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (2, 3), (3, 4)), 6: ((0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (2, 3), (3, 4), (4, 5)), 7: ((0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)), 8: ((0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (1, 2),...
4,237
false
0.068049
median
code
normalized
ys=None, **kwargs): return gradients(ys, xs, grad_ys, checkpoints='collection', **kwargs) def gradients(ys, xs, grad_ys=None, checkpoints='collection', **kwargs): ''' Authors: Tim Salimans & Yaroslav Bulatov memory efficient gradient implementation inspired by "Training Deep Nets with Sublinear Memory...
4,119
false
0.0769
median
code
normalized
new_checkpoint_dir = FuncCheckpointUtil.create_perm_checkpoint( checkpoint_dir, self.logdir, step=4) assert new_checkpoint_dir == TrainableUtil.find_checkpoint_dir( new_checkpoint_dir) assert os.path.exists(new_checkpoint_dir) assert not FuncCheckpointUtil.is_temp_checkp...
4,312
false
0.147898
median
code
normalized
ingest.py (which converted the old ACLPUB flat XML format) - anthologize.pl in ACLPUB - anthology_xml.py in ACLPUB """ import argparse import iso639 import os import re import readline import shutil import sys import lxml.etree as etree from collections import defaultdict, OrderedDict from datetime import datetime...
4,122
false
0.113726
median
code
normalized
def wrapped(*args, **kw): if TIME: start = time.time() ret = fn(*args, **kw) delta = time.time() - start print(delta, args[1], fn.__name__) return ret else: return fn(*args, **kw) return wrapped class RestObject(object): ...
4,099
false
0.075643
median
code
normalized
to the distributed AMI. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Key-value map of resource tags for the distribution configuration. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. ""...
4,320
true
0.209986
median
code
normalized
icon' ATTR_NAME = 'name' ATTR_OBJECT_ID = 'object_id' ATTR_ORDER = 'order' ATTR_VIEW = 'view' ATTR_VISIBLE = 'visible' SERVICE_SET_VISIBILITY = 'set_visibility' SERVICE_SET = 'set' SERVICE_REMOVE = 'remove' CONTROL_TYPES = vol.In(['hidden', None]) SET_VISIBILITY_SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_EN...
4,246
false
0.100162
median
code
normalized
'double 2'), 4) self.assertEqual(fire.Fire(tc.WithDefaults, 'triple 4'), 12) self.assertEqual(fire.Fire(tc.OldStyleWithDefaults, 'double 2'), 4) self.assertEqual(fire.Fire(tc.OldStyleWithDefaults, 'triple 4'), 12) def testFireNoArgs(self): self.assertEqual(fire.Fire(tc.MixedDefaults, 'ten'), 10) ...
4,251
false
0.099188
median
code
normalized
, 'shape': None, 'kind': 'data', 'data_type': None}, 'placeholder_2_data': {'value': None, 'shape': None, 'kind': 'data', 'data_type': None}, 'placeholder_3_data': {'value': None, 'shape': None, 'kind': 'data', 'data_type': None}, 'placeholder_4_data': {'value': None, 'shape': None, 'kind': 'data', 'data_ty...
4,168
true
0.265103
median
code
normalized
_columns = AnyField('columns') _level = AnyField('level') _errors = StringField('errors') def __init__(self, index=None, columns=None, level=None, errors=None, **kw): super().__init__(_index=index, _columns=columns, _level=level, _errors=errors, **kw) @property ...
4,169
false
0.116911
median
code
normalized
3), dtype=np.uint8) original_rgb = utils.array_to_img(original_rgb_array, scale=False) original_rgb.save(filename_rgb) original_rgba_array = np.array(255 * np.random.rand(100, 100, 4), dtype=np.uint8) original_rgba = utils.array_to_i...
4,346
false
0.129692
median
code
normalized
self.selected = True ''' Catch and handle the view changes ''' return super(SelectableLabel, self).refresh_view_attrs( rv, index, data) def on_touch_down(self, touch): ''' Add selection on touch down ''' if super(SelectableLabel, self).on_touch_down(touch)...
4,204
false
0.091273
median
code
normalized
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re import os import sys imp...
4,321
false
0.095711
median
code
normalized
pipeline (list[dict], optional): Pipeline used for data processing. Defaults to None. classes (tuple[str], optional): Classes used in the dataset. Defaults to None. modality (dict, optional): Modality to specify the sensor data used as input. Defaults to None....
4,219
false
0.138008
median
code
normalized
z = sec2cart(r, alpha, beta) elif mode.lower() in ('dp', 'dpolar'): r, alpha, beta = np.meshgrid(v1, np.deg2rad(v2), np.deg2rad(v3), indexing='ij') x, y, z = dp2cart(r, alpha, beta) if as_list: return np.c_[x.ravel('F'), y.ravel('F'), z.ravel('F')] else: return x, y, z d...
4,287
false
0.037195
median
code
normalized
- self._low) - (self._high - self._close)) / (self._high - self._low) clv = clv.fillna(0.0) # float division by zero ad = clv * self._volume self._ad = ad.cumsum() def acc_dist_index(self) -> pd.Series: """Accumulation/Distribution Index (ADI) Returns: pandas....
4,107
true
0.217775
median
code
normalized
self.ca_crt_path = os.path.join(local_scratch_dir, "test.ca.crt") self.ca_jks_path = os.path.join(local_scratch_dir, "test.ca.jks") self.ca_passwd = "test-ca-passwd" self.truststore_path = os.path.join(local_scratch_dir, "test.truststore.jks") self.truststore_passwd = "test-ts-p...
4,172
false
0.094751
median
code
normalized
(os.path.join(scriptDir, '..', 'extra')) from testutils import * from pprint import pprint # # Args handling # parser = argparse.ArgumentParser() parser.add_argument("--exec", metavar="<interpreter>", default="../build/wasm3") parser.add_argument("--engine", metavar="<engine>") parser.add_argument("--timeout", type...
4,165
false
0.073787
median
code
normalized
_keywords = ["who are you", "who r u", "what is your name"] youtube_keywords = ["play ", "stream ", "queue "] launch_keywords = ["open ", "launch "] search_keywords = ["search ",] wikipedia_keywords = ["wikipedia ", "wiki "] download_music=["download","download music"] reminder_keywords = ["set a reminder"] calc...
4,227
false
0.074836
median
code
normalized
_relu, mode='none', bn=False, dr=None): super(ResBlock, self).__init__() initializer = chainer.initializers.GlorotUniform() initializer_sc = chainer.initializers.GlorotUniform() self.activation = activation self.mode = _downsample if mode == 'down' else _upsample if mode == 'up' ...
4,109
true
0.203794
median
code
normalized
to the key ``ramp_submissions_dir`` of the dictionary created with :func:`ramp_utils.generate_ramp_config`. session : None or :class:`sqlalchemy.orm.Session`, optional The session used to perform some required queries. It is a required argument when interacting with the database outside of ...
4,223
false
0.132262
median
code
normalized
#{ #{ class variables DEFAULT_HEADER_DICT = { 'Accept-Charset': 'Shift_JIS,utf-8;q=0.7,*;q=0.7', 'Accept-Language': 'ja,en-us;q=0.7,en;q=0.3', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36', } DEFAULT_PMA_LOGIN_PARAM_DICT...
4,311
false
0.082804
median
code
normalized
) in block_pairs: labels = {frozenset([(key, label[key]) for key in ctrl_new.inputs.keys()] + [(output, label[output]) for output in ctrl_new.outputs.keys()]) for (x, y, label) in ctrl.transitions.find(b, c)} for q in labels: ctrl_new.transitions...
4,318
false
0.147219
median
code
normalized
None, 'z_source' is used. :param cosmo: instance of astropy.cosmology :param numerical_alpha_class: an instance of a custom class for use in NumericalAlpha() lens model (see documentation in Profiles/numerical_alpha) """ if z_interp_stop is None: z_interp_stop = z_...
4,178
false
0.122208
median
code
normalized
import collections import collections.abc import inspect import sys import traceback from typing import Any, Callable, List, TYPE_CHECKING, Optional, TypeVar, Type, Union import disnake from .core import GroupMixin from .view import StringView from .context import Context from . import errors from .help import HelpC...
4,228
false
0.101976
median
code
normalized
{OUTPUT_PATH}") def do_2nd_preprocess(dataset_split): label_fpath = os.path.join(INPUT_PATH, "labels.txt") labels = get_labels(label_fpath) tokenizer = BertTokenizer.from_pretrained(VOCA, do_lower_case=True) cls_token_id = tokenizer.convert_tokens_to_ids("[CLS]") sep_token_id = tokenizer.convert...
4,178
false
0.090897
median
code
normalized
0)) password = db.Column(db.String(50)) e_mail = db.Column(db.String(50), unique=True, nullable=False) descripcion = db.Column(db.String(1000)) link = db.Column(db.String(200)) foto_de_perfil = db.Column(db.String(400)) class Sigue(db.Model): #id = db.Column(db.Integer, primary_key=True ) ...
4,129
false
0.107155
median
code
normalized
Window Mode self.qtwidget_mode = False # Make empty window self.renWin = vtk.vtkRenderWindow() self.renWin.AddRenderer(self.ren) self.renWin.SetSize(960, 540) self.iren = vtk.vtkRenderWindowInteractor() self.iren.SetInteractorStyle(v...
4,283
false
0.11089
median
code
normalized
_dataset_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.platform import gfile from tensorflow.python.util import deprecation _ACCEPTABLE_CSV_TYPES = (dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64, dtypes.string) def make_csv_dataset( file_pattern, ...
4,134
false
0.142412
median
code
normalized
param n_steps: (int) The number of steps to run for each environment per update (i.e. batch size is n_steps * n_env where n_env is number of environment copies running in parallel) :param vf_coef: (float) Value function coefficient for the loss calculation :param ent_coef: (float) Entropy coefficient fo...
4,202
false
0.076655
median
code
normalized
N_alpha_beta_dict1 = N_alpha_beta T_alpha1 = T_alpha_total #N_i_j_alpha_dict1, R_i_alpha_dict1, N_alpha_beta_dict1, T_alpha1 = \ # analyze.openmm_read_output_file_list([test_output_filename]) N_i_j_alpha_dict2 = {(1, 2): 52, (2, 1): 52} R_i_alpha_dict2 = {1: 1658.696, 2: 198.912} N_a...
4,280
false
0.091215
median
code
normalized
It provides different methods based on inputs from a URL and inputs from a stream. :param str endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). :param credential: Credentials needed for the client to connect to Azure...
4,178
true
0.252033
median
code
normalized
epfl.ch)," \ " Michael Atambo (michaelontita.atambo@unimore.it)." class YamboCalculation(CalcJob): """ AiiDA plugin for the Yambo code. For more information, refer to http://www.yambo-code.org/ https://github.com/yambo-code/yambo-aiida and http://aiida-yambo.readthedocs.io/en/latest/ ...
4,212
false
0.080367
median
code
normalized
self.effect_mirror() elif self.effect == "triangle": frame = self.effect_delaunay_triangle() elif self.effect == "glasses": frame = self.effect_glasses() return frame # --------------- # BABY FACE # --------------- def effect_baby_face(self): ret, frame = self.camera.read() if not ret: ...
4,330
false
0.121962
median
code
normalized
(dt.String(nullable=False), '`string_col`'), ('timestamp', 'CAST(`string_col` AS DateTime)'), ('date', 'CAST(`string_col` AS Date)'), ], ) def test_cast_string_col(alltypes, translate, to_type, expected): expr = alltypes.string_col.cast(to_type) assert translate(expr) == expected @pytest....
4,332
false
0.129719
median
code
normalized
DOUT, shell=ISWIN) except subprocess.CalledProcessError as err: out = err.output.decode(errors="ignore") raise RuntimeError("FFMEG call failed with {}:\n{}".format(err.returncode, out)) # Note that other than with the subprocess calls below, ffmpeg wont hang here. # Worst case Python will s...
4,279
false
0.132809
median
code
normalized
self.resume = resume if not resume: # Fail if experiment_id already exist in runs/ _avoid_overwriting(params["experiment_id"]) # Set device self.device = params["device"] if "cuda" in self.device and not torch.cuda.is_available(): warnings.warn( ...
4,264
false
0.076422
median
code
normalized
help="Training data", required=True) data_grp.add_argument("--val", help="Validation data", required=True) data_grp.add_argument("--embedding", help="h5 file with embedded sequences", required=True) data_grp.add_argument( "--no-augment", action="store_false", dest='augment', ...
4,260
false
0.089275
median
code
normalized
# type: LogicBlockState self._start_enabled = None # type: bool self.player_state_variable = "{}_state".format(self.name) '''player_var: (logic_block)_state desc: A dictionary that stores the internal state of the logic block with the name (logic_block). (In other words, a lo...
4,223
false
0.121272
median
code
normalized
sub-compartments. version_added: "2.9.0" author: Oracle (@oracle) options: compartment_id: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. type: str required: true resource_metric: description...
4,180
false
0.1102
median
code
normalized
that does not sum to one is input""" p = np.ones(4) with pytest.raises(ValueError, match="A valid probability distribution of non-negative"): probs_to_unitary(p) def test_invalid_distribution_negative(self): """Test if a ValueError is raised when a distribution with a negative ...
4,227
false
0.086671
median
code
normalized
k = d.keys() self.assert_(d.has_key('a')) self.assert_(d.has_key('b')) self.assertRaises(TypeError, d.keys, None) def test_values(self): d = {} self.assertEqual(d.values(), []) d = {1:2} self.assertEqual(d.values(), [2]) self.assertRaises(Ty...
4,189
false
0.089703
median
code
normalized
loss = F.cross_entropy(net(x, params), targets, size_average=False) else: loss = F.cross_entropy(net(x), targets, size_average=False) grad = torch.autograd.grad(loss, [x])[0] if metalearner.targeted: x = x.detach() - metalearner.attack_step_size*to...
4,220
true
0.208191
median
code
normalized
that DARTS runs. Default: 50 """ self.window = window self.ev_freq = ev_freq self.epochs = total_epochs self.stop_search = False self.stop_epoch = total_epochs - 1 self.stop_genotype = None self.ev = [] self.ev_local_avg = [] ...
4,134
false
0.075701
median
code
normalized
= Var(within=Reals,bounds=(0,1000),initialize=0) m.x2 = Var(within=Reals,bounds=(0,1000),initialize=0) m.x3 = Var(within=Reals,bounds=(0,1000),initialize=0) m.x4 = Var(within=Reals,bounds=(0,1000),initialize=0) m.x5 = Var(within=Reals,bounds=(0,1000),initialize=0) m.x6 = Var(within=Reals,bounds=(0,1000),initialize=0) ...
4,235
false
0.122544
median
code
normalized
it's not, so # we have to heuristically detect it to validate. if not init_checkpoint: return m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint) if m is None: return model_name = m.group(1) lower_models = [ "uncased_L-24_H-1024_A-16", "uncased_L-12...
4,200
false
0.060067
median
code
normalized
outdir """ # check src file exists if not Path(src).is_file(): log.warning(f"{src} file cannot be accessed") hash_src = get_file_hash(src, buffer="content") filename = PurePath(src).name destpath = Path(outdir) / filename hash_out = "" # get hash and new name if destpat...
4,322
false
0.095612
median
code
normalized
_HYPERCROSS # To use the model, must call initialize_coords before forward pass. # Once data is processed, call clear to reset the model before calling initialize_coords def __init__(self, in_channels, out_channels, config, D=3, **kwargs): super(Res16UNetBase, self).__init__(in_channels, out_channels, config...
4,233
false
0.120735
median
code
normalized
type valid_fraction_feature: (FeatureType, str) :param max_scene_number: Maximum number of reference scenes taken for the creation of the composite. By default, the maximum number of scenes equals the number of time frames :type max_scene_number: int """ def __in...
4,127
false
0.147035
median
code
normalized
# PYTHON ADAPTATION OF MY C++ CODE THAT CAN BE FOUND IN # https://github.com/richardtjornhammar/RichTools/blob/master/src/cluster.cc # AROUND LINE 2345 # AGAIN CONSIDER USING THE C++ VERSION SINCE IT IS ALOT FASTER # HERE WE SPEED IT UP USI...
4,141
false
0.115254
median
code
normalized
self.settings.SUBSCRIPTION_ID RESOURCE_GROUP = resource_group.name PROFILE_NAME = "profilename" CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME = "policyname" ENDPOINT_NAME = "endpoint9527x" CUSTOM_DOMAIN_NAME = "someDomain" ORIGIN_NAME = "origin1" # Profiles_Create[pu...
4,298
true
0.238226
median
code
normalized
CryptCallback = object from bson import _dict_to_bson, decode, encode from bson.codec_options import CodecOptions from bson.binary import (Binary, STANDARD, UUID_SUBTYPE) from bson.errors import BSONError from bson.raw_bson import (DEFAULT_RAW_BSON_OPTIONS, ...
4,263
false
0.100793
median
code
normalized
-collection resource that returns a csv representation of the entire table - if the table has a single primary key, each table record will also appear as a non-collection resource in the table collection using the primary key value as its name. This resource returns a csv representation of the re...
4,301
false
0.12952
median
code
normalized
in range(num_goals)] # pos = np.random.rand(2)*2-1 goals = generate_path(num_goals + 1) pos = goals[0] goals = goals[1:-1] # pos_agent_time_list = [] min_time, min_trajectory, min_path, min_vel_path, successful, pass_vals = pos_agent.find_shortes...
4,159
true
0.226244
median
code
normalized
64], # [6.30154, 50.948329]]) def chi2cdf(chi2,df): ''' Chi square cumulative distribution function ''' return ee.Image(chi2.divide(2)).gammainc(ee.Number(df).divide(2)) def makefeature(data): ''' for exporting as CSV to Drive ''' return ee.Feature(None, {'data': data}) ...
4,133
false
0.096436
median
code
normalized
from xsdata.formats.dataclass.parsers.nodes import WildcardNode from xsdata.formats.dataclass.parsers.utils import ParserUtils from xsdata.models.enums import DataType from xsdata.models.enums import Namespace from xsdata.models.enums import QNames from xsdata.utils.testing import FactoryTestCase from xsdata.utils.test...
4,321
false
0.141317
median
code
normalized
.num_nodes = 1 self.block_heights = {} self.coinbase_key = CECKey() self.coinbase_key.set_secretbytes(bytes("horsebattery")) self.coinbase_pubkey = self.coinbase_key.get_pubkey() self.block_time = int(time.time())+1 self.tip = None self.blocks = {} def run_te...
4,328
false
0.144675
median
code
normalized
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/GettextCommon.py 2014/07/05 09:42:21 garyo" import SCons.Warnings import re ############################################################################# class XgettextToolWarning(SCons.Warnings.Warning): pass class Xg...
4,126
false
0.087969
median
code
normalized
Pads the input such that if it was used in a convolution with 'VALID' padding, the output would have the same dimensions as if the unpadded input was used in a convolution with 'SAME' padding. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. kernel_size: The kernel to be used in th...
4,153
false
0.105046
median
code
normalized
("index.html").generate(), b"header text\nbody text" ) def test_extends(self): loader = DictLoader( { "base.html": """\ <title>{% block title %}default title{% end %}</title> <body>{% block body %}default body{% end %}</body> """, "page.html": """\ {% ext...
4,323
false
0.099952
median
code
normalized
dpdk-host' self.invalid_dpdk_host = 'invalid-host' self.vhu_mode = 'server' self.add_fake_chassis(self.ovs_host) self.add_fake_chassis( self.dpdk_host, external_ids={'datapath-type': 'netdev', 'iface-types': 'dummy,dummy-internal,dpdkvhos...
4,163
false
0.12957
median
code
normalized
self.original_vars = sysconfig._CONFIG_VARS self.old_vars = copy(sysconfig._CONFIG_VARS) def tearDown(self): """Restore sys.path""" sys.path[:] = self.sys_path site.USER_BASE = self.old_base site.USER_SITE = self.old_site site.PREFIXES = self.old_prefixes ...
4,260
false
0.075514
median
code
normalized
Screen, 15) self.assertEqual(AppKit.NSCompositeOverlay, 16) self.assertEqual(AppKit.NSCompositeDarken, 17) self.assertEqual(AppKit.NSCompositeLighten, 18) self.assertEqual(AppKit.NSCompositeColorDodge, 19) self.assertEqual(AppKit.NSCompositeColorBurn, 20) self.assertEqual...
4,170
false
0.103467
median
code
normalized
taxa list (optional if args['--taxa'] is not None: taxa_incorp_list = _load_taxa_incorp_list(args['--taxa'], config) else: taxa_incorp_list = {k:[] for k in config.keys()} ## kde_bd sys.stderr.write('Loading KDE object...\n') KDEs = Utils.load_kde(args['<BD_KDE>']) ...
4,198
false
0.085518
median
code
normalized
package = None monkeypatch.setattr(spack.repo, 'get', find_nothing) with pytest.raises(spack.repo.UnknownPackageError): spec.package pkg.do_uninstall() except Exception: pkg.remove_prefix() raise def mock_remove_prefix(*args): raise MockInstallError( ...
4,198
false
0.108716
median
code
normalized
", ".join(value)}''' if len(value) > 0 else "" def pre_if(self, prefix, condition): return prefix if condition else "" def pre(self, prefix, value): return f'''{prefix}{value}''' if value != None else "" def type_args(self, args): return f'''<{", ".join(args)}>''' if a...
4,178
false
0.100181
median
code
normalized
xx, yy, zz, xy, xz, yz) in the yaw-aligned coorinate system self.add_input('blades_I', np.zeros(6), units='kg*m**2', desc='mass moments of inertia of all blades about hub center') self.add_input('hub_I', np.zeros(6), units='kg*m**2', desc='mass moments of inertia of hub about its center of mass') ...
4,164
false
0.087378
median
code
normalized
AttributeMixin, RequestFieldGroup # noqa from .utils import locate_object, rate_limit_exceeded logger = logging.getLogger(__name__) # TODO: # * Make it generically handle database write failures (updating the http_status to be 5XX) # * Create new error for deadline exceeded and catch it in the same place as writes...
4,260
false
0.079903
median
code
normalized
msg) assert_(abs(derphi1) <= abs(c2*derphi0), "Wolfe 2 failed: " + msg) def assert_armijo(s, phi, c1=1e-4, err_msg=""): """ Check that Armijo condition applies """ phi1 = phi(s) phi0 = phi(0) msg = "s = %s; phi(0) = %s; phi(s) = %s; %s" % (s, phi0, phi1, err_msg) assert_(phi1 <= (1 - ...
4,204
false
0.128079
median
code
normalized
pts = np.array([[5, 15], [15, 15], [15, 20]]) gdf = GeoDataFrame([Point(xy) for xy in pts], columns=["geometry"], crs="EPSG:3857") return gdf @pytest.fixture def pointsoutside_overlap_gdf(): """Create a point GeoDataFrame. Its points are all outside the single rectangle, and its bounds are overlappin...
4,146
false
0.126689
median
code
normalized
("/") datasetname = dir[-1] self.dataset.update(array_tsdict, datasetname) self.master.v_dsname.set(self.dataset.name) self.master.v_tslength.set(self.dataset.tslength) self.master.v_tsnbr.set(self.dataset.size) self.master.v_classnbr.set(len(self.dataset.ClassList)) ...
4,340
false
0.12591
median
code
normalized
token in Keystone. * Transforms the account name to AUTH_%(tenant_name). * Optionally can retrieve and cache secret from keystone to validate signature locally """ import base64 import json from keystoneclient.v3 import client as keystone_client from keystoneauth1 import session as keystone_session from keystonea...
4,243
false
0.102979
median
code
normalized
db.alter_column(u'accounting_softwareplanversion', 'date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True)) # Changing field 'SoftwareProductRate.date_created' db.alter_column(u'accounting_softwareproductrate', 'date_created', self.gf('django.db.models.fields.DateTim...
4,338
true
0.213479
median
code
normalized
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== Tests for vital.types.Ro...
4,297
false
0.118472
median
code
normalized
# tsfm = Transform(params) # transformed_sample = tsfm(sample) # # Observe below how these transforms had to be applied both on the image and # landmarks. # class Rescale(object): """Rescale the image in a sample to a given size. Args: output_size (tuple or tuple): Desired output size. If tup...
4,258
false
0.093856
median
code
normalized
init__(self, request): self.request = request self.owner = owner = request.owner self.owner_id = owner.id self.api_url = os.environ['opn_api_url'] self.change_log = [] # peers is a cache of {peer_id: Peer}. self.peers = {} def download_batch(self, sync_ts_is...
4,105
false
0.125456
median
code
normalized
.pins))} if len(shape.pins) == 1 else { f"{gate.id}.{pin_name}": pin_name for pin_name in shape.pins }, gate.id, gate.pos, gate.custom_data)) return ios @classmethod def from_node(cls, node: Combin...
4,324
false
0.113167
median
code
normalized
argument_string = '' if number_of_strings == 1: argument_string = self._strings[0] elif number_of_strings > 1: argument_string = '{0:s}{1:s}'.format( self._strings[0], ', '.join(self._strings[1:])) return argument_string class FunctionPrototype(object): """Function prototype. ...
4,255
false
0.109595
median
code
normalized
/LeNet_keras.py (x_train, y_train), (x_test, y_test) = cifar10.load_data() y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 # for reproducibility np.rand...
4,212
false
0.0658
median
code
normalized
client_app # Load existing flags flags.adopt_module_key_flags(xds_k8s_testcase) flags.adopt_module_key_flags(xds_url_map_test_resources) # Define urlMap specific flags QPS = flags.DEFINE_integer('qps', default=25, help='The QPS client is sending') # Test configs _URL_MAP_PROPAGATE_TIMEOUT_SEC = 600 # With the per-r...
4,320
false
0.081345
median
code
normalized
:type name: string :param name: The name of the identifier """ def __init__(self, name, member_name=None): #: (``string``) The name of the identifier self.name = name self.member_name = member_name class Action(object): """ A service operation action. :type name: stri...
4,317
false
0.139641
median
code
normalized
"Page Title", "wp:post_name": "page-title", "wp:post_date_gmt": "2017-03-12 17:53:57", "wp:post_modified_gmt": "2018-12-04 11:49:24", "content:encoded": body_html, "wp:post_id": "1000", "wp:post_type": "post", "link": "http://www.examp...
4,274
false
0.086815
median
code
normalized