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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dd3d1ee88c2948bbaf093a5a | train | function | def month_hardcode_split(pandas_df, month_column='month_n'):
max_month = pandas_df[month_column].max()
pandas_df_copy = pandas_df.copy()
train = pandas_df_copy[pandas_df_copy[month_column] < max_month]
test = pandas_df_copy[pandas_df_copy[month_column] == max_month]
return train, test | def month_hardcode_split(pandas_df, month_column='month_n'):
| max_month = pandas_df[month_column].max()
pandas_df_copy = pandas_df.copy()
train = pandas_df_copy[pandas_df_copy[month_column] < max_month]
test = pandas_df_copy[pandas_df_copy[month_column] == max_month]
return train, test | def month_hardcode_split(pandas_df, month_column='month_n'):
| 16 | 64 | 78 | 16 | 0 | Julia-chan/ml_engineering_example | source/validation.py | Python | month_hardcode_split | month_hardcode_split | 1 | 6 | 1 | 1 | d742b93351c54cfb4adc14548d05f3ad528ce73b | bigcode/the-stack | train |
9a2f8cce3dba117c5dfb1e06 | train | function | def get_host_uptime():
"""Returns the result of calling "uptime"."""
out, err = utils.execute('env', 'LANG=C', 'uptime')
return out
| def get_host_uptime():
| """Returns the result of calling "uptime"."""
out, err = utils.execute('env', 'LANG=C', 'uptime')
return out
| # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import utils
def get_host_uptime():
| 64 | 64 | 40 | 6 | 57 | ewindisch/nova | nova/virt/hostutils.py | Python | get_host_uptime | get_host_uptime | 20 | 23 | 20 | 20 | c21812f482748aaa237a192274f80ef7bf97e3b8 | bigcode/the-stack | train |
a3a9e8ed3819e62ffb48c0ce | train | class | class Migration(migrations.Migration):
dependencies = [
('staff', '0011_auto_20180425_0850'),
]
operations = [
migrations.AlterField(
model_name='attendance',
name='staffs',
field=models.ManyToManyField(to='staff.Staff'),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('staff', '0011_auto_20180425_0850'),
]
operations = [
migrations.AlterField(
model_name='attendance',
name='staffs',
field=models.ManyToManyField(to='staff.Staff'),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 31 | 64 | 67 | 7 | 23 | awemulya/fieldsight-kobocat | onadata/apps/staff/migrations/0012_auto_20180513_1047.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | 444597b860261cbbb019cea83091b7f48501c399 | bigcode/the-stack | train |
af8dfadc650871543d297f5b | train | class | class Places365Dataset(base.BaseDataset):
"""Places365 dataset builder class."""
def __init__(self,
split: str,
seed: Optional[Union[int, tf.Tensor]] = None,
validation_percent: float = 0.0,
shuffle_buffer_size: Optional[int] = None,
num_pa... | class Places365Dataset(base.BaseDataset):
| """Places365 dataset builder class."""
def __init__(self,
split: str,
seed: Optional[Union[int, tf.Tensor]] = None,
validation_percent: float = 0.0,
shuffle_buffer_size: Optional[int] = None,
num_parallel_parser_calls: int = 64,
... | # coding=utf-8
# Copyright 2022 The Uncertainty Baselines Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | 196 | 216 | 723 | 8 | 187 | dvdzhang/uncertainty-baselines | uncertainty_baselines/datasets/places.py | Python | Places365Dataset | Places365Dataset | 26 | 100 | 26 | 26 | 02fc93ba14836862fe213844bd6efc4cc1e4a91e | bigcode/the-stack | train |
135b7b7ac4b8c9c63a6b408f | train | class | class SwappableModelTests(TestCase):
available_apps = [
'swappable_models',
'django.contrib.auth',
'django.contrib.contenttypes',
]
@override_settings(TEST_ARTICLE_MODEL='swappable_models.AlternateArticle')
def test_generated_data(self):
"Permissions and content types a... | class SwappableModelTests(TestCase):
| available_apps = [
'swappable_models',
'django.contrib.auth',
'django.contrib.contenttypes',
]
@override_settings(TEST_ARTICLE_MODEL='swappable_models.AlternateArticle')
def test_generated_data(self):
"Permissions and content types are not created for a swapped model"
... | from __future__ import unicode_literals
from django.utils.six import StringIO
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.test import TestCase, override_settings
from swappable_models.models import Article... | 67 | 108 | 361 | 8 | 58 | PirosB3/django | tests/swappable_models/tests.py | Python | SwappableModelTests | SwappableModelTests | 13 | 53 | 13 | 14 | 60d0fbfb31225cbe302fc2d323c5f78ae6d63fb2 | bigcode/the-stack | train |
acaae38db6bd9e930d32c46a | train | class | class ZoomedScene(MovingCameraScene):
CONFIG = {
"camera_class": MultiCamera,
"zoomed_display_height": 3,
"zoomed_display_width": 3,
"zoomed_display_center": None,
"zoomed_display_corner": UP + RIGHT,
"zoomed_display_corner_buff": DEFAULT_MOBJECT_TO_EDGE_BUFFER,
... | class ZoomedScene(MovingCameraScene):
| CONFIG = {
"camera_class": MultiCamera,
"zoomed_display_height": 3,
"zoomed_display_width": 3,
"zoomed_display_center": None,
"zoomed_display_corner": UP + RIGHT,
"zoomed_display_corner_buff": DEFAULT_MOBJECT_TO_EDGE_BUFFER,
"zoomed_camera_config": {
... | from manimlib.animation.transform import ApplyMethod
from manimlib.camera.moving_camera import MovingCamera
from manimlib.camera.multi_camera import MultiCamera
from manimlib.constants import *
from manimlib.mobject.types.image_mobject import ImageMobjectFromCamera
from manimlib.scene.moving_camera_scene import MovingC... | 116 | 190 | 634 | 9 | 107 | wofeicaoge/manim | manimlib/scene/zoomed_scene.py | Python | ZoomedScene | ZoomedScene | 13 | 90 | 13 | 13 | ca5a837ebc8619ed6087bd997157aef0f0cb253b | bigcode/the-stack | train |
bf48739e7e1d89fe5da9acf2 | train | function | def get_val(msg):
difficulty = input(msg)
try:
difficulty = int(difficulty)
if difficulty > 0:
return difficulty
else:
return get_val(msg)
except ValueError:
return get_val(msg)
| def get_val(msg):
| difficulty = input(msg)
try:
difficulty = int(difficulty)
if difficulty > 0:
return difficulty
else:
return get_val(msg)
except ValueError:
return get_val(msg)
| import random
def get_val(msg):
| 8 | 64 | 52 | 5 | 2 | mccreery/sandbox | python/mastermind.py | Python | get_val | get_val | 3 | 12 | 3 | 3 | 20a393837e5c9d77498c2c0de35edc7d1302757d | bigcode/the-stack | train |
48f49efc7f32d0b5fcb95deb | train | class | class Ui_confirmDialog(object):
def setupUi(self, confirmDialog):
confirmDialog.setObjectName(_fromUtf8("confirmDialog"))
confirmDialog.resize(398, 60)
self.gridLayout = QtGui.QGridLayout(confirmDialog)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.noButton = Qt... | class Ui_confirmDialog(object):
| def setupUi(self, confirmDialog):
confirmDialog.setObjectName(_fromUtf8("confirmDialog"))
confirmDialog.resize(398, 60)
self.gridLayout = QtGui.QGridLayout(confirmDialog)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.noButton = QtGui.QPushButton(confirmDialog)
... | _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(c... | 111 | 111 | 372 | 6 | 105 | xcgspring/XSTAF | XSTAF/ui/ui_confirmDialog.py | Python | Ui_confirmDialog | Ui_confirmDialog | 26 | 51 | 26 | 26 | 04a0294b8639c454ca9b56248ed7b7e31331cabc | bigcode/the-stack | train |
c0f48701f7750ba9434edb85 | train | function | def cnn(net, is_train, cfg):
net = net - 0.5
channels = cfg.base_channels
size = int(net.get_shape()[2])
print('Critic CNN:')
print(' ', str(net.get_shape()))
size /= 2
net = ly.conv2d(
net,
num_outputs=channels,
kernel_size=4,
stride=2,
activation_fn=lrelu,
normaliz... | def cnn(net, is_train, cfg):
| net = net - 0.5
channels = cfg.base_channels
size = int(net.get_shape()[2])
print('Critic CNN:')
print(' ', str(net.get_shape()))
size /= 2
net = ly.conv2d(
net,
num_outputs=channels,
kernel_size=4,
stride=2,
activation_fn=lrelu,
normalizer_fn=None)
print(' ', s... | import tensorflow as tf
import tensorflow.contrib.layers as ly
from .util import lrelu
def cnn(net, is_train, cfg):
| 28 | 69 | 233 | 9 | 18 | Daniel-Bu/exposure | critics.py | Python | cnn | cnn | 6 | 38 | 6 | 6 | f2e1457cf419da6ae91303b457f4104e3d2a9586 | bigcode/the-stack | train |
650523bfdba1aa451afbef19 | train | function | def critic(images, cfg, states=None, is_train=None, reuse=False):
with tf.variable_scope('critic') as scope:
if reuse:
scope.reuse_variables()
if True:
lum = (images[:, :, :, 0] * 0.27 + images[:, :, :, 1] * 0.67 +
images[:, :, :, 2] * 0.06 + 1e-5)[:, :, :]
# luminance and cont... | def critic(images, cfg, states=None, is_train=None, reuse=False):
| with tf.variable_scope('critic') as scope:
if reuse:
scope.reuse_variables()
if True:
lum = (images[:, :, :, 0] * 0.27 + images[:, :, :, 1] * 0.67 +
images[:, :, :, 2] * 0.06 + 1e-5)[:, :, :]
# luminance and contrast
luminance, contrast = tf.nn.moments(lum, axes=[1, 2])
... | print(' ', str(net.get_shape()))
while size > 4:
channels *= 2
size /= 2
net = ly.conv2d(
net,
num_outputs=channels,
kernel_size=4,
stride=2,
activation_fn=lrelu,
normalizer_fn=None,
normalizer_params={
'is_training': is_train,
... | 162 | 162 | 541 | 16 | 146 | Daniel-Bu/exposure | critics.py | Python | critic | critic | 42 | 98 | 42 | 42 | d1734ebd5646d74ffec4a1d631161a9d660297b0 | bigcode/the-stack | train |
40297c2c37612093790e48d8 | train | class | class SubtitleNotFound(Exception):
pass
| class SubtitleNotFound(Exception):
| pass
| class SubtitleNotFound(Exception):
| 6 | 64 | 9 | 6 | 0 | data4goodlab/subs2network | subs2network/exceptions.py | Python | SubtitleNotFound | SubtitleNotFound | 3 | 4 | 3 | 3 | a4a5f793d7304c01ec7479a9c488215552c399d6 | bigcode/the-stack | train |
377fe56f82d277a860598deb | train | class | class CastNotFound(Exception):
pass
| class CastNotFound(Exception):
| pass
|
class SubtitleNotFound(Exception):
pass
class CastNotFound(Exception):
| 16 | 64 | 9 | 6 | 9 | data4goodlab/subs2network | subs2network/exceptions.py | Python | CastNotFound | CastNotFound | 7 | 8 | 7 | 7 | f4d37f6ca429925647af5c16f1ccb7925e3e4026 | bigcode/the-stack | train |
99bdbb8cb6609c7e23c207ef | train | class | class Discriminator(nn.Module):
"""Discriminator, Auxiliary Classifier."""
def __init__(self, preprocess_GAN_mode, input_channel, batch_size=64, image_size=64, conv_dim=64):
super(Discriminator, self).__init__()
self.imsize = image_size
layer1 = []
layer2 = []
layer3 = [... | class Discriminator(nn.Module):
| """Discriminator, Auxiliary Classifier."""
def __init__(self, preprocess_GAN_mode, input_channel, batch_size=64, image_size=64, conv_dim=64):
super(Discriminator, self).__init__()
self.imsize = image_size
layer1 = []
layer2 = []
layer3 = []
last = []
#la... | )
self.l1 = nn.Sequential(*layer1)
self.l2 = nn.Sequential(*layer2)
self.l3 = nn.Sequential(*layer3)
last.append(nn.ConvTranspose2d(curr_dim, 3, 4, 2, 1))
last.append(nn.Tanh())
self.last = nn.Sequential(*last)
self.attn1 = Self_Attn( 128, 'relu')
self.... | 206 | 206 | 687 | 6 | 199 | youngsjjn/MemSeg | model/sagan_models.py | Python | Discriminator | Discriminator | 105 | 170 | 105 | 105 | 06b3b3ea03d7907fc9edb00cb09bc132ab252950 | bigcode/the-stack | train |
a5f4f5746a7286087cf4bc29 | train | class | class Generator(nn.Module):
"""Generator."""
def __init__(self, batch_size, image_size=64, z_dim=100, conv_dim=64):
super(Generator, self).__init__()
self.imsize = image_size
layer1 = []
layer2 = []
layer3 = []
last = []
repeat_num = int(np.log2(self.ims... | class Generator(nn.Module):
| """Generator."""
def __init__(self, batch_size, image_size=64, z_dim=100, conv_dim=64):
super(Generator, self).__init__()
self.imsize = image_size
layer1 = []
layer2 = []
layer3 = []
last = []
repeat_num = int(np.log2(self.imsize)) - 3
mult = 2 *... | ).view(m_batchsize,-1,width*height).permute(0,2,1) # B X CX(N)
proj_key = self.key_conv(x).view(m_batchsize,-1,width*height) # B X C x (*W*H)
energy = torch.bmm(proj_query,proj_key) # transpose check
attention = self.softmax(energy) # BX (N) X (N)
proj_value = self.value_conv(x).view(... | 172 | 172 | 574 | 5 | 166 | youngsjjn/MemSeg | model/sagan_models.py | Python | Generator | Generator | 43 | 102 | 43 | 43 | 16d0577c91635e8e6e112ea7a9102defa9ad419e | bigcode/the-stack | train |
f087a3cbea1b4193d669a517 | train | class | class Self_Attn(nn.Module):
""" Self attention Layer"""
def __init__(self,in_dim,activation):
super(Self_Attn,self).__init__()
self.chanel_in = in_dim
self.activation = activation
self.query_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//8 , kernel_size= ... | class Self_Attn(nn.Module):
| """ Self attention Layer"""
def __init__(self,in_dim,activation):
super(Self_Attn,self).__init__()
self.chanel_in = in_dim
self.activation = activation
self.query_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//8 , kernel_size= 1)
self.key_conv = n... | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from .spectral import SpectralNorm
from torchvision import transforms
import numpy as np
class Self_Attn(nn.Module):
| 49 | 120 | 402 | 7 | 41 | youngsjjn/MemSeg | model/sagan_models.py | Python | Self_Attn | Self_Attn | 9 | 41 | 9 | 9 | 771e0c01af76f6d9422e57e33103bb374d6c2f33 | bigcode/the-stack | train |
35cb0f29fa8d9bee5f6bfb51 | train | class | class Migration(migrations.Migration):
dependencies = [
('api', '0024_auto_20161220_1013'),
]
operations = [
migrations.CreateModel(
name='School',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='I... | class Migration(migrations.Migration):
| dependencies = [
('api', '0024_auto_20161220_1013'),
]
operations = [
migrations.CreateModel(
name='School',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('urn', models.Cha... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-21 11:51
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
| 63 | 64 | 214 | 7 | 55 | alphagov/land-avilability-api | landavailability/api/migrations/0025_school.py | Python | Migration | Migration | 9 | 30 | 9 | 10 | 096f07bc1005aed1c63353b27820118153e3fa48 | bigcode/the-stack | train |
7b0aced77c9b3a1134b56ba9 | train | class | class Users(CRUDMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
email = db.Column(db.String(200), unique=True, nullable=False)
firstname = db.Column(db.String(120), nullable=False)
lastname = db.Column(db.String(120), nullab... | class Users(CRUDMixin, db.Model):
| __tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
email = db.Column(db.String(200), unique=True, nullable=False)
firstname = db.Column(db.String(120), nullable=False)
lastname = db.Column(db.String(120), nullable=False)
password = db.Column... | from app.extensions import db, bcrypt
from app.core.models import CRUDMixin
from datetime import datetime
class Users(CRUDMixin, db.Model):
| 31 | 64 | 200 | 10 | 20 | lwalter/flask-angular-starter | app/user/models.py | Python | Users | Users | 6 | 29 | 6 | 6 | 20d6282d6cd0add2b87958dc3ba3e0a50c87f01c | bigcode/the-stack | train |
6619da1cb5a4e579ef139e9d | train | class | class ResNetBasicStem(nn.Module):
"""
ResNe(X)t 3D stem module.
Performs spatiotemporal Convolution, BN, and Relu following by a
spatiotemporal pooling.
"""
def __init__(
self,
dim_in,
dim_out,
kernel,
stride,
padding,
inplace_relu=Tru... | class ResNetBasicStem(nn.Module):
| """
ResNe(X)t 3D stem module.
Performs spatiotemporal Convolution, BN, and Relu following by a
spatiotemporal pooling.
"""
def __init__(
self,
dim_in,
dim_out,
kernel,
stride,
padding,
inplace_relu=True,
eps=1e-5,
bn_mm... | em(self, dim_in, dim_out):
for pathway in range(len(dim_in)):
stem = ResNetBasicStem(
dim_in[pathway],
dim_out[pathway],
self.kernel[pathway],
self.stride[pathway],
self.padding[pathway],
self.inplace_rel... | 176 | 176 | 589 | 8 | 167 | jingyuanchan/HERO_Video_Feature_Extractor | slowfast/slowfast/models/stem_helper.py | Python | ResNetBasicStem | ResNetBasicStem | 99 | 171 | 99 | 99 | 44a1f3f36d57c1a793ac0b565f389f718ca3d51e | bigcode/the-stack | train |
c972143a1f10f15e5b27aff1 | train | class | class VideoModelStem(nn.Module):
"""
Video 3D stem module. Provides stem operations of Conv, BN, ReLU, MaxPool
on input data tensor for one or multiple pathways.
"""
def __init__(
self,
dim_in,
dim_out,
kernel,
stride,
padding,
inplace_relu=Tr... | class VideoModelStem(nn.Module):
| """
Video 3D stem module. Provides stem operations of Conv, BN, ReLU, MaxPool
on input data tensor for one or multiple pathways.
"""
def __init__(
self,
dim_in,
dim_out,
kernel,
stride,
padding,
inplace_relu=True,
eps=1e-5,
bn_... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""ResNe(X)t 3D stem helper."""
import torch.nn as nn
class VideoModelStem(nn.Module):
| 48 | 201 | 671 | 7 | 40 | jingyuanchan/HERO_Video_Feature_Extractor | slowfast/slowfast/models/stem_helper.py | Python | VideoModelStem | VideoModelStem | 9 | 96 | 9 | 9 | 4edd945b01b753877e042ba2d54d7c8b15fde744 | bigcode/the-stack | train |
722c2e2661f7b22d7ed4f6d3 | train | function | def search_rotated_array(a,k):
low, high = 0, len(a)-1
mid = (low+high)//2
if (a[mid] >= k and a[low] <= k) or (a[mid] <= k and a[high] <= k):
return binary_search(a,k, low, mid)
elif (a[mid] > k and a[low] > k) or (a[mid] < k and a[high] > k):
return binary_search(a,k, mid+1, high)... | def search_rotated_array(a,k):
| low, high = 0, len(a)-1
mid = (low+high)//2
if (a[mid] >= k and a[low] <= k) or (a[mid] <= k and a[high] <= k):
return binary_search(a,k, low, mid)
elif (a[mid] > k and a[low] > k) or (a[mid] < k and a[high] > k):
return binary_search(a,k, mid+1, high)
return -1
| == k:
return mid
elif a[mid] > k:
return binary_search(a,k,low, mid )
else:
return binary_search(a, k, mid+1, high)
else:
return -1
# Wrong implementation
def search_rotated_array(a,k):
| 64 | 64 | 124 | 8 | 55 | ved93/Deliberate-Practice-code-everyday-challenge | code-everyday-challenge/n197_search_sorted_rotated.py | Python | search_rotated_array | search_rotated_array | 24 | 35 | 24 | 24 | 51155ed073a1e6cddd4ac36b9a11b24bce5d3065 | bigcode/the-stack | train |
8a223e8ed51e7917b39da239 | train | function | def binary_search(a,k, low, high):
mid = (low+high)//2
if low <= high:
if a[mid ] == k:
return mid
elif a[mid] > k:
return binary_search(a,k,low, mid )
else:
return binary_search(a, k, mid+1, high)
else:
return -1
| def binary_search(a,k, low, high):
| mid = (low+high)//2
if low <= high:
if a[mid ] == k:
return mid
elif a[mid] > k:
return binary_search(a,k,low, mid )
else:
return binary_search(a, k, mid+1, high)
else:
return -1
|
#n99_search_rotated file
# https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/?ref=leftbar-rightbar
# Wrong implementation
def binary_search(a,k, low, high):
| 52 | 64 | 83 | 10 | 41 | ved93/Deliberate-Practice-code-everyday-challenge | code-everyday-challenge/n197_search_sorted_rotated.py | Python | binary_search | binary_search | 7 | 19 | 7 | 7 | 8ef023f32a8afce5b09685428c77c30a173b02cb | bigcode/the-stack | train |
73e44093dd3e4fdf1f244d5d | train | function | def test_matmul_add():
n = 1024
l = 128
m = 235
A = tvm.placeholder((n, l), name='A')
B = tvm.placeholder((l, m), name='B')
C = cublas.matmul(A, B)
s = tvm.create_schedule(C.op)
def verify(target="cuda"):
if not tvm.module.enabled(target):
print("skip because %s is n... | def test_matmul_add():
| n = 1024
l = 128
m = 235
A = tvm.placeholder((n, l), name='A')
B = tvm.placeholder((l, m), name='B')
C = cublas.matmul(A, B)
s = tvm.create_schedule(C.op)
def verify(target="cuda"):
if not tvm.module.enabled(target):
print("skip because %s is not enabled..." % target... | agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
import numpy as np
from tvm.... | 82 | 82 | 275 | 6 | 75 | mingwayzhang/tvm | tests/python/contrib/test_cublas.py | Python | test_matmul_add | test_matmul_add | 21 | 45 | 21 | 21 | bdb0037b6ae3e0b3f614b1e6da9ef60e4986e8aa | bigcode/the-stack | train |
d231214a0aaec72d1797b810 | train | function | def main():
# initialize testing framework
test = testing_framework()
# run the test model
for idx, dir in enumerate(exdirs):
test.build_mf6_models(build_model, idx, dir)
sim = Simulation(dir, exfunc=eval_results, idxsim=idx)
test.run_mf6(sim)
| def main():
# initialize testing framework
| test = testing_framework()
# run the test model
for idx, dir in enumerate(exdirs):
test.build_mf6_models(build_model, idx, dir)
sim = Simulation(dir, exfunc=eval_results, idxsim=idx)
test.run_mf6(sim)
|
test = testing_framework()
# build the model
test.build_mf6_models(build_model, idx, dir)
# run the test model
test.run_mf6(Simulation(dir, exfunc=eval_results, idxsim=idx))
def main():
# initialize testing framework
| 64 | 64 | 71 | 9 | 55 | kzeiler/modflow6 | autotest/test_gwf_maw06.py | Python | main | main | 312 | 320 | 312 | 313 | a4de919f2e951da349cb93dab64b991350c1c6f9 | bigcode/the-stack | train |
445f92390e58b19c8cbc02d6 | train | function | @pytest.mark.parametrize(
"idx, dir",
list(enumerate(exdirs)),
)
def test_mf6model(idx, dir):
# initialize testing framework
test = testing_framework()
# build the model
test.build_mf6_models(build_model, idx, dir)
# run the test model
test.run_mf6(Simulation(dir, exfunc=eval_results, ... | @pytest.mark.parametrize(
"idx, dir",
list(enumerate(exdirs)),
)
def test_mf6model(idx, dir):
# initialize testing framework
| test = testing_framework()
# build the model
test.build_mf6_models(build_model, idx, dir)
# run the test model
test.run_mf6(Simulation(dir, exfunc=eval_results, idxsim=idx))
| assert np.allclose(qmaw, -qgwf), msg
return
# - No need to change any code below
@pytest.mark.parametrize(
"idx, dir",
list(enumerate(exdirs)),
)
def test_mf6model(idx, dir):
# initialize testing framework
| 64 | 64 | 89 | 35 | 28 | kzeiler/modflow6 | autotest/test_gwf_maw06.py | Python | test_mf6model | test_mf6model | 297 | 309 | 297 | 302 | 59ebbef309086cfa35de321464ab57e888c7af41 | bigcode/the-stack | train |
e93b8096460330a85784fd37 | train | function | def build_model(idx, dir):
nper = 1
perlen = [10.0]
nstp = [100]
tsmult = [1.005]
tdis_rc = []
for i in range(nper):
tdis_rc.append((perlen[i], nstp[i], tsmult[i]))
nouter, ninner = 700, 200
hclose, rclose, relax = 1e-9, 1e-9, 1.0
name = ex[idx]
# build MODFLOW 6 file... | def build_model(idx, dir):
| nper = 1
perlen = [10.0]
nstp = [100]
tsmult = [1.005]
tdis_rc = []
for i in range(nper):
tdis_rc.append((perlen[i], nstp[i], tsmult[i]))
nouter, ninner = 700, 200
hclose, rclose, relax = 1e-9, 1e-9, 1.0
name = ex[idx]
# build MODFLOW 6 files
ws = dir
sim = fl... | = []
for s in ex:
exdirs.append(os.path.join("temp", s))
nlay = 2
nrow = 1
ncol = 1
delc = 1.0
delr = 1.0
gwfarea = delr * delc
top = 2.0
bot = 0.0
aqthick = top - bot
dz = aqthick / float(nlay)
botm = [top - dz * (k + 1) for k in range(nlay)]
ztop = [top - dz * k for k in range(nlay)]
strt_min = aqthick / 8.0... | 256 | 256 | 1,153 | 7 | 249 | kzeiler/modflow6 | autotest/test_gwf_maw06.py | Python | build_model | build_model | 60 | 207 | 60 | 60 | 313a978d8fe83e975b06c1a0869099fa408e9800 | bigcode/the-stack | train |
92a5efcf482bd59cfaa5e0a3 | train | function | def eval_results(sim):
print("evaluating results...")
# calculate volume of water and make sure it is conserved
name = ex[sim.idxsim]
gwfname = "gwf_" + name
fname = gwfname + ".maw.bin"
fname = os.path.join(sim.simpath, fname)
assert os.path.isfile(fname)
bobj = flopy.utils.HeadFile(fn... | def eval_results(sim):
| print("evaluating results...")
# calculate volume of water and make sure it is conserved
name = ex[sim.idxsim]
gwfname = "gwf_" + name
fname = gwfname + ".maw.bin"
fname = os.path.join(sim.simpath, fname)
assert os.path.isfile(fname)
bobj = flopy.utils.HeadFile(fname, text="HEAD")
s... | data,
perioddata=mawperioddata,
pname="MAW-1",
)
opth = "{}.maw.obs".format(gwfname)
obsdata = {
"{}.maw.obs.csv".format(gwfname): [
("whead", "head", (0,)),
]
}
maw.obs.initialize(
filename=opth, digits=20, print_input=True, continuous=obsdata
... | 256 | 256 | 873 | 5 | 250 | kzeiler/modflow6 | autotest/test_gwf_maw06.py | Python | eval_results | eval_results | 210 | 293 | 210 | 210 | a5a307faf1d98fc4df774cae9ebe85a4952315fa | bigcode/the-stack | train |
56137ba9f4a7c0ee7512e3c3 | train | class | class XANESTest(PymatgenTest):
def setUp(self):
self.xanes = XANES.from_dict(spect_data_dict)
def test_e0(self):
self.assertAlmostEqual(24374.508999999998, self.xanes.e0)
def test_normalization(self):
self.xanes.normalize(mode="sum")
self.assertAlmostEqual(1.0, np.sum(self.... | class XANESTest(PymatgenTest):
| def setUp(self):
self.xanes = XANES.from_dict(spect_data_dict)
def test_e0(self):
self.assertAlmostEqual(24374.508999999998, self.xanes.e0)
def test_normalization(self):
self.xanes.normalize(mode="sum")
self.assertAlmostEqual(1.0, np.sum(self.xanes.y))
def test_add_mul... | from monty.json import MontyDecoder
import numpy as np
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..",
"test_files/spectrum_test")
with open(os.path.join(test_dir, 'Pd2O.json')) as fp:
spect_data_dict = json.load(fp, cls=MontyDecoder)
class XANESTest(PymatgenTest... | 85 | 85 | 284 | 11 | 74 | hpatel1567/pymatgen | pymatgen/analysis/xas/tests/test_spectrum.py | Python | XANESTest | XANESTest | 20 | 48 | 20 | 20 | cce356869fb6f71d8c1d885253d5272070cb2595 | bigcode/the-stack | train |
846cd20a3b84074214948db4 | train | function | def truncate(map_data, by_sigma_less_than, scale_by, set_value = 0):
"""
Trunate map inplace by standard deviation (sigma) while scale it with
specified scale, such as volume (scale_by = 1/volume) or sigma
(scale_by = 1/standard_deviation). Input map_data is expected to be unscaled (
right out of FT).
"""
... | def truncate(map_data, by_sigma_less_than, scale_by, set_value = 0):
| """
Trunate map inplace by standard deviation (sigma) while scale it with
specified scale, such as volume (scale_by = 1/volume) or sigma
(scale_by = 1/standard_deviation). Input map_data is expected to be unscaled (
right out of FT).
"""
sigma = statistics(map_data).sigma()
if(sigma == 0):
map_dat... | .double([atom_radius]*1))
v.append((map_data.select(sel)>= cutoff).count(True))
r = flex.min_default(v, None)
if(r == 0): return None
return r
def truncate(map_data, by_sigma_less_than, scale_by, set_value = 0):
| 64 | 64 | 165 | 19 | 44 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | truncate | truncate | 261 | 277 | 261 | 261 | f2545a617fd55dc937cee0626661c32aa7e57df9 | bigcode/the-stack | train |
cd59c69265632ce363e3664e | train | class | class crystal_gridding(object):
def __init__(self, unit_cell,
d_min = None,
resolution_factor = None,
step = None,
symmetry_flags = None,
space_group_info = None,
mandatory_factors = None,
... | class crystal_gridding(object):
| def __init__(self, unit_cell,
d_min = None,
resolution_factor = None,
step = None,
symmetry_flags = None,
space_group_info = None,
mandatory_factors = None,
max_prime = 5,... | bottom_values_sorted[i_lower]
del bottom_values
del bottom_values_sorted
return cutoffp, cutoffm
class peak_list(ext.peak_list):
def __init__(self, data,
tags,
peak_search_level = 1,
max_peaks = 0,
peak_cutoff = None,
... | 215 | 215 | 719 | 6 | 209 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | crystal_gridding | crystal_gridding | 400 | 495 | 400 | 401 | 84676224186ae22fa280691b300f737b5a408014 | bigcode/the-stack | train |
a01d283b3fb2cbfb96de3690 | train | class | class statistics(ext.statistics):
def __init__(self, map):
ext.statistics.__init__(self, map)
| class statistics(ext.statistics):
| def __init__(self, map):
ext.statistics.__init__(self, map)
| _cell = xrs_p1.unit_cell(),
n_real = n_real,
mask_value_inside_molecule = mask_value_inside_molecule,
mask_value_outside_molecule = mask_value_outside_molecule,
radii = atom_radii + solvent_radius)
class statistics(ext.statistics):
| 64 | 64 | 24 | 5 | 59 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | statistics | statistics | 299 | 302 | 299 | 300 | 956a3d2d6e1dcf8925f522e248838689b617faaf | bigcode/the-stack | train |
23e2fca9693db6a703cb3cd3 | train | function | def get_diff_score_towards_periodic(map_data,
minimum_fraction_data_points = None):
'''
Evaluate consistency of high-pass filtered difference map analysis
with that expected for a map that is periodic.
The difference map is difference between the map and the map lacking high-
resolut... | def get_diff_score_towards_periodic(map_data,
minimum_fraction_data_points = None):
| '''
Evaluate consistency of high-pass filtered difference map analysis
with that expected for a map that is periodic.
The difference map is difference between the map and the map lacking high-
resolution terms. This difference map shows only high-frequency
information
A map th... | 5+10 * 1/minimum_fraction_data_points)
ma_with_data.setup_binner(n_bins = n_bins, d_max = 10000.,
d_min = ma_with_data.d_min())
dsd = ma_with_data.d_spacings().data()
ibin_list=list(ma_with_data.binner().range_used())
ibin_list.reverse()
total_data = ma_with_data.size()
minimum_data_points... | 212 | 212 | 707 | 20 | 191 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | get_diff_score_towards_periodic | get_diff_score_towards_periodic | 1,937 | 2,019 | 1,937 | 1,939 | b268eae9b1dce0d9f086cfced51c14442e14b226 | bigcode/the-stack | train |
ea5c8089c74b76264bc4ea12 | train | function | def assert_same_gridding(map_1, map_2,
Sorry_message = "Maps have different gridding."):
f1 = map_1.focus() == map_2.focus()
f2 = map_1.origin() == map_2.origin()
f3 = map_1.all() == map_2.all()
if([f1, f2, f3].count(True)!= 3):
raise Sorry(Sorry_message)
| def assert_same_gridding(map_1, map_2,
Sorry_message = "Maps have different gridding."):
| f1 = map_1.focus() == map_2.focus()
f2 = map_1.origin() == map_2.origin()
f3 = map_1.all() == map_2.all()
if([f1, f2, f3].count(True)!= 3):
raise Sorry(Sorry_message)
| f %8.6f"
for d_min, cc in zip(self.result.d_mins, self.result.ccs):
print(fmt%(d_min, cc), file = log)
def assert_same_gridding(map_1, map_2,
Sorry_message = "Maps have different gridding."):
| 64 | 64 | 95 | 25 | 39 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | assert_same_gridding | assert_same_gridding | 122 | 128 | 122 | 123 | 8b9c66f4a042821c09db25a76b7ee6ca729e01d3 | bigcode/the-stack | train |
5b3c4bd03afc2bbafc3a39d9 | train | function | def value_at_closest_grid_point(map, x_frac):
return map[closest_grid_point(map.accessor(), x_frac)]
| def value_at_closest_grid_point(map, x_frac):
| return map[closest_grid_point(map.accessor(), x_frac)]
| _data,
ncs_object = ncs_object,
sites_cart = sites_cart,
shift_frac = shift_frac,
shift_cart = shift_cart,
original_origin_grid_units = original_origin_grid_units,
original_origin_cart = original_origin_cart)
def value_at_closest_grid_point(map, x_frac):
| 64 | 64 | 26 | 12 | 52 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | value_at_closest_grid_point | value_at_closest_grid_point | 188 | 189 | 188 | 188 | 4b72c20d2f426123536b541ee31cf5e6b0d22cef | bigcode/the-stack | train |
8d0111d4ab70b555845eb7f4 | train | function | def shift_origin_if_needed(map_data = None,
sites_cart = None,
crystal_symmetry = None,
ncs_object = None,
origin_grid_units = None,
n_xyz = None,
):
if not map_data:
assert origin_grid_units and n_xyz
shift_needed = True
else: # usual
shift_needed = not \
(map_data.focus_s... | def shift_origin_if_needed(map_data = None,
sites_cart = None,
crystal_symmetry = None,
ncs_object = None,
origin_grid_units = None,
n_xyz = None,
):
| if not map_data:
assert origin_grid_units and n_xyz
shift_needed = True
else: # usual
shift_needed = not \
(map_data.focus_size_1d() > 0 and map_data.nd() == 3 and
map_data.is_0_based())
shift_frac = None
shift_cart = None
if(shift_needed):
if map_data:
N = map_data.all()
... | %(d_min, cc), file = log)
def assert_same_gridding(map_1, map_2,
Sorry_message = "Maps have different gridding."):
f1 = map_1.focus() == map_2.focus()
f2 = map_1.origin() == map_2.origin()
f3 = map_1.all() == map_2.all()
if([f1, f2, f3].count(True)!= 3):
raise Sorry(Sorry_message)
... | 151 | 151 | 506 | 46 | 105 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | shift_origin_if_needed | shift_origin_if_needed | 130 | 186 | 130 | 137 | 9fd1d23314d160cc28d17d8e05aa4ad1293eb79e | bigcode/the-stack | train |
5dde592b143d0577a5e925c4 | train | function | def as_CObjectZYX(map_unit_cell, first, last, apply_sigma_scaling = True):
return ext.as_CObjectZYX(map_unit_cell, first, last, apply_sigma_scaling)
| def as_CObjectZYX(map_unit_cell, first, last, apply_sigma_scaling = True):
| return ext.as_CObjectZYX(map_unit_cell, first, last, apply_sigma_scaling)
| , peak_search_level, max_peaks, interpolate)
else:
ext.peak_list.__init__(self,
data, tags, peak_search_level, peak_cutoff, max_peaks, interpolate)
def as_CObjectZYX(map_unit_cell, first, last, apply_sigma_scaling = True):
| 64 | 64 | 42 | 21 | 43 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | as_CObjectZYX | as_CObjectZYX | 393 | 394 | 393 | 393 | ced5d18fcd2af155a9b44367ae3421e9e243023a | bigcode/the-stack | train |
31991ca6f40c814e336939c2 | train | function | def atom_radius_as_central_peak_width(element, b_iso, d_min, scattering_table):
"""
Estimate atom radius as half-width of the central peak of Fourier image.
"""
from cctbx import xray, miller
dim = 40.
cs = crystal.symmetry((dim, dim, dim, 90, 90, 90), "P 1")
sp = crystal.special_position_settings(cs)
s... | def atom_radius_as_central_peak_width(element, b_iso, d_min, scattering_table):
| """
Estimate atom radius as half-width of the central peak of Fourier image.
"""
from cctbx import xray, miller
dim = 40.
cs = crystal.symmetry((dim, dim, dim, 90, 90, 90), "P 1")
sp = crystal.special_position_settings(cs)
sc = xray.scatterer(
scattering_type = element,
site = (0, 0, ... | _flag = False,
d_min = d_min,
complex_map = map_box,
conjugate_flag = True,
discard_indices_affected_by_aliasing = True)
n = map_box.all()[0] * map_box.all()[1] * map_box.all()[2]
map_coeffs = cctbx.miller.set(
crystal_symmetry = cs,
anomalous_flag = False,
indices = box_structure_factor... | 134 | 134 | 447 | 19 | 114 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | atom_radius_as_central_peak_width | atom_radius_as_central_peak_width | 1,352 | 1,394 | 1,352 | 1,352 | 0470574998d548af0fe76891dffb34f49668832f | bigcode/the-stack | train |
13349b4964a879a6fcc3d71f | train | function | def is_bounded_by_constant(map_data,
relative_sd_tol = 0.1):
''' Determine if this map is bounded on all sides by values that are
zero or a constant, within relative tolerance of relative_sd_tol to
the SD of the map as a whole
Returns True if map boundary values are nearly constant,
... | def is_bounded_by_constant(map_data,
relative_sd_tol = 0.1):
| ''' Determine if this map is bounded on all sides by values that are
zero or a constant, within relative tolerance of relative_sd_tol to
the SD of the map as a whole
Returns True if map boundary values are nearly constant,
and False if they vary
Requires that map is at origin ... | = log)
pdb_hierarchy.atoms().set_b(bs)
if (method == "rscc_d_min_b"):
pdb_hierarchy.atoms().set_occ(occs)
return pdb_hierarchy
def is_bounded_by_constant(map_data,
relative_sd_tol = 0.1):
| 64 | 64 | 165 | 19 | 44 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | is_bounded_by_constant | is_bounded_by_constant | 1,829 | 1,849 | 1,829 | 1,830 | 372b01418c3036f67b060dc31f89266e33ce26d4 | bigcode/the-stack | train |
f9e018d447f6583dd6dac248 | train | function | def d_min_from_map(map_data, unit_cell, resolution_factor = 1./2.):
a, b, c = unit_cell.parameters()[:3]
nx, ny, nz = map_data.all()
d1, d2, d3 = \
a/nx/resolution_factor, \
b/ny/resolution_factor, \
c/nz/resolution_factor
return max(d1, d2, d3)
| def d_min_from_map(map_data, unit_cell, resolution_factor = 1./2.):
| a, b, c = unit_cell.parameters()[:3]
nx, ny, nz = map_data.all()
d1, d2, d3 = \
a/nx/resolution_factor, \
b/ny/resolution_factor, \
c/nz/resolution_factor
return max(d1, d2, d3)
| max_index = flex.miller_index( [[(i-1)//2 for i in map_data.all()]] )
return uctbx.d_star_sq_as_d(unit_cell.max_d_star_sq( max_index ))
def d_min_from_map(map_data, unit_cell, resolution_factor = 1./2.):
| 64 | 64 | 94 | 20 | 44 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | d_min_from_map | d_min_from_map | 1,308 | 1,315 | 1,308 | 1,308 | 4529353a39ba79dd0a16fd8f3e5d1ad3c6991f63 | bigcode/the-stack | train |
3582ba45504f2bc733c12b25 | train | function | def relative_sd_on_edges(map_data,
skip_if_greater_than = None,
use_maximum = None):
'''
Determine relative SD of values on edges to the map as a whole
Requires that map is at origin (0,0,0)
'''
assert tuple(map_data.origin()) == (0,0,0)
sd_overall = map_data.as_1d().standard_devia... | def relative_sd_on_edges(map_data,
skip_if_greater_than = None,
use_maximum = None):
| '''
Determine relative SD of values on edges to the map as a whole
Requires that map is at origin (0,0,0)
'''
assert tuple(map_data.origin()) == (0,0,0)
sd_overall = map_data.as_1d().standard_deviation_of_the_sample()
all = list(map_data.all())
boundary_data = flex.double()
rel... | 1):
''' Determine if this map is bounded on all sides by values that are
zero or a constant, within relative tolerance of relative_sd_tol to
the SD of the map as a whole
Returns True if map boundary values are nearly constant,
and False if they vary
Requires that map is at ori... | 172 | 172 | 576 | 24 | 147 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | relative_sd_on_edges | relative_sd_on_edges | 1,852 | 1,911 | 1,852 | 1,855 | 493abacfcc851abe541fc5702ae125421c7d8da4 | bigcode/the-stack | train |
7f9f6cbb02c726a6e33451ab | train | function | def peak_volume_estimate(map_data, sites_cart, crystal_symmetry, cutoff,
atom_radius = 1.5):
v = flex.double()
sites_frac = crystal_symmetry.unit_cell().fractionalize(sites_cart)
for sc, sf in zip(sites_cart, sites_frac):
if(map_data.value_at_closest_grid_point(sf)>= cutoff):
sel = grid_indices_ar... | def peak_volume_estimate(map_data, sites_cart, crystal_symmetry, cutoff,
atom_radius = 1.5):
| v = flex.double()
sites_frac = crystal_symmetry.unit_cell().fractionalize(sites_cart)
for sc, sf in zip(sites_cart, sites_frac):
if(map_data.value_at_closest_grid_point(sf)>= cutoff):
sel = grid_indices_around_sites(
unit_cell = crystal_symmetry.unit_cell(),
fft_n_real = map_data.focus(... | smearing_b,
max_peak_scale = max_peak_scale, smearing_span = smearing_span,
use_exp_table = use_exp_table, use_max_map = use_max_map)
def peak_volume_estimate(map_data, sites_cart, crystal_symmetry, cutoff,
atom_radius = 1.5):
| 64 | 64 | 177 | 26 | 38 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | peak_volume_estimate | peak_volume_estimate | 244 | 259 | 244 | 245 | bb2e445ee134bb98c1234c36e58a99bd7c40a021 | bigcode/the-stack | train |
82d50ac0f9af1409104c05e1 | train | function | def principal_axes_of_inertia(
real_map,
site_cart,
unit_cell,
radius):
st = sphericity_tensor(
map_data = real_map,
unit_cell = unit_cell,
radius = radius,
site_frac = unit_cell.fractionalize(site_cart))
es = adptbx.eigensystem(st)
def center_of_mass_():
return center_of_m... | def principal_axes_of_inertia(
real_map,
site_cart,
unit_cell,
radius):
| st = sphericity_tensor(
map_data = real_map,
unit_cell = unit_cell,
radius = radius,
site_frac = unit_cell.fractionalize(site_cart))
es = adptbx.eigensystem(st)
def center_of_mass_():
return center_of_mass(
map_data = real_map, unit_cell = unit_cell, cutoff = 0.1)
def inertia_tensor(... | = %.2f mean = %.2f stddev = %.2f" % \
(prefix, self.min, self.max, self.mean, self.standard_deviation), file = out)
def principal_axes_of_inertia(
real_map,
site_cart,
unit_cell,
radius):
| 64 | 64 | 158 | 22 | 42 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | principal_axes_of_inertia | principal_axes_of_inertia | 1,139 | 1,160 | 1,139 | 1,143 | ffee93ed3a881f33cd326f13f04ac6ed5f9130a6 | bigcode/the-stack | train |
f20327e55208a6481945d1a4 | train | class | class peak_search_parameters(object):
def __init__(self, peak_search_level = 1,
max_peaks = 0,
peak_cutoff = None,
interpolate = True,
min_distance_sym_equiv = None,
general_positions_only = False,
... | class peak_search_parameters(object):
| def __init__(self, peak_search_level = 1,
max_peaks = 0,
peak_cutoff = None,
interpolate = True,
min_distance_sym_equiv = None,
general_positions_only = False,
effective_resolution = None,
... | j[1], k[1]])
return len(self.starts)
def _box_edges(self, n_real_1d, step):
limits = []
for i in range(0, n_real_1d, step): limits.append(i)
limits.append(n_real_1d)
box_1d = []
for i in range(len(limits)):
if(i == 0): box_1d.append([limits[0], limits[1]])
elif(i!=... | 138 | 138 | 462 | 6 | 131 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | peak_search_parameters | peak_search_parameters | 671 | 735 | 671 | 672 | fea900d1950c39da7c2a8f3c2081ee787d5e314b | bigcode/the-stack | train |
a9a46119d652b6ce6928024e | train | function | def map_to_map_coefficients(m, cs, d_min):
import cctbx.miller
fft = fftpack.real_to_complex_3d([i for i in m.all()])
map_box = copy(
m, flex.grid(fft.m_real()).set_focus(m.focus()))
map_box.reshape(flex.grid(fft.m_real()).set_focus(fft.n_real()))
map_box = fft.forward(map_box)
box_structure_factors = s... | def map_to_map_coefficients(m, cs, d_min):
| import cctbx.miller
fft = fftpack.real_to_complex_3d([i for i in m.all()])
map_box = copy(
m, flex.grid(fft.m_real()).set_focus(m.focus()))
map_box.reshape(flex.grid(fft.m_real()).set_focus(fft.n_real()))
map_box = fft.forward(map_box)
box_structure_factors = structure_factors.from_map(
unit_cell = ... | (),
pre_determined_n_real = n_real)
fft_map = map_coeffs.fft_map(
crystal_gridding = cg,
symmetry_flags = use_space_group_symmetry)
fft_map.apply_volume_scaling()
return fft_map.real_map_unpadded()
def map_to_map_coefficients(m, cs, d_min):
| 71 | 71 | 238 | 13 | 58 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | map_to_map_coefficients | map_to_map_coefficients | 1,329 | 1,350 | 1,329 | 1,329 | d4afac10ad7581f648c25e2814dfacc887adb93c | bigcode/the-stack | train |
d7ecc5b0cda09384e2b52de2 | train | class | class peak_list(ext.peak_list):
def __init__(self, data,
tags,
peak_search_level = 1,
max_peaks = 0,
peak_cutoff = None,
interpolate = True):
if (peak_cutoff is None):
ext.peak_list.__init__(self,
... | class peak_list(ext.peak_list):
| def __init__(self, data,
tags,
peak_search_level = 1,
max_peaks = 0,
peak_cutoff = None,
interpolate = True):
if (peak_cutoff is None):
ext.peak_list.__init__(self,
data, tags, peak_search_level,... | )
bottom_values_sorted = bottom_values.select(s)
del s
assert (bottom_values_sorted.size() > i_lower)
cutoffm = bottom_values_sorted[i_lower]
del bottom_values
del bottom_values_sorted
return cutoffp, cutoffm
class peak_list(ext.peak_list):
| 64 | 64 | 114 | 8 | 55 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | peak_list | peak_list | 378 | 391 | 378 | 379 | 86919d4c3d1a14ceb37629c73cb117db0523626c | bigcode/the-stack | train |
c9d343b2bf7b84fc1de04dac | train | class | @bp.inject_into(connectivity)
class _():
def get_blobs_boundaries_tuples(self):
"""
get lists of minimum and maximum coordinates for each connected
region.
returns 2 lists of tuples: first is minimum, second is maximum coordinates.
[(x0, y0, z0), (x1, y1, z1), ...] where 0, 1, ... - number of reg... | @bp.inject_into(connectivity)
class _():
| def get_blobs_boundaries_tuples(self):
"""
get lists of minimum and maximum coordinates for each connected
region.
returns 2 lists of tuples: first is minimum, second is maximum coordinates.
[(x0, y0, z0), (x1, y1, z1), ...] where 0, 1, ... - number of region
"""
boundaries = self.get_blob... | bx import fftpack
from libtbx.test_utils import approx_equal
from cctbx import uctbx
import scitbx.math
debug_peak_cluster_analysis = os.environ.get(
"CCTBX_MAPTBX_DEBUG_PEAK_CLUSTER_ANALYSIS", "")
@bp.inject_into(connectivity)
class _():
| 65 | 66 | 223 | 10 | 55 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | _ | _ | 31 | 50 | 31 | 33 | df664091e5b4d2817f61685f83f46ab69541e3e4 | bigcode/the-stack | train |
32a926eb7b57286f7fe20492 | train | class | class boxes(object):
"""
Split box defined by n_real into boxes where each box is a fraction of the
whole box.
"""
def __init__(self,
n_real,
fraction = None,
log = None,
max_boxes = 2000,
prefix = ""):
self.n_real = n_real
i =... | class boxes(object):
| """
Split box defined by n_real into boxes where each box is a fraction of the
whole box.
"""
def __init__(self,
n_real,
fraction = None,
log = None,
max_boxes = 2000,
prefix = ""):
self.n_real = n_real
i = 0
n_boxes = 1.e+... | _)
self.starts = []
self.ends = []
for i in be[0]:
for j in be[1]:
for k in be[2]:
self.starts.append([i[0], j[0], k[0]])
self.ends.append([i[1], j[1], k[1]])
return len(self.starts)
def _box_edges(self, n_real_1d, step):
limits = []
for i in range(0, n_real_... | 197 | 197 | 657 | 4 | 192 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | boxes | boxes | 600 | 669 | 600 | 600 | 2bdfd74869d36546b916809c0d9b03e6501a07cc | bigcode/the-stack | train |
c5d4b04ad14dca6ea3f8d119 | train | class | class positivity_constrained_density_modification(object):
def __init__(self, f, f_000, n_cycles = 100, resolution_factor = 0.25, d_min = None,
crystal_gridding = None, complete_set = None):
self.f = f
self.d_min = d_min
self.map = None
self.crystal_gridding = crystal_gridding
from ... | class positivity_constrained_density_modification(object):
| def __init__(self, f, f_000, n_cycles = 100, resolution_factor = 0.25, d_min = None,
crystal_gridding = None, complete_set = None):
self.f = f
self.d_min = d_min
self.map = None
self.crystal_gridding = crystal_gridding
from cctbx import miller
if(self.d_min is None): self.d_min ... | , 360, t_angle_sampling_step):
xc, yc, zc = scitbx.math.point_on_sphere(r = r, s_deg = s, t_deg = t,
center = center_cart)
xf, yf, zf = unit_cell.fractionalize([xc, yc, zc])
rho.append(map_data.eight_point_interpolation([xf, yf, zf]))
#rho.append(map_data.tricubic_interpolation... | 134 | 134 | 447 | 9 | 124 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | positivity_constrained_density_modification | positivity_constrained_density_modification | 1,258 | 1,302 | 1,258 | 1,258 | 64373f08b17237df489a7781302939a09ce1ba74 | bigcode/the-stack | train |
bc2eaf05032c3fef737dcd38 | train | function | def ccv(map_1, map_2, modified, centered, cutoff = None, n_bins = 10000):
if(modified):
map_1 = volume_scale(map = map_1, n_bins = n_bins).map_data()
map_2 = volume_scale(map = map_2, n_bins = n_bins).map_data()
if(cutoff is not None):
map_1 = map_1 - cutoff
map_2 = map_2 - cutoff
s1 = map_1 < 0... | def ccv(map_1, map_2, modified, centered, cutoff = None, n_bins = 10000):
| if(modified):
map_1 = volume_scale(map = map_1, n_bins = n_bins).map_data()
map_2 = volume_scale(map = map_2, n_bins = n_bins).map_data()
if(cutoff is not None):
map_1 = map_1 - cutoff
map_2 = map_2 - cutoff
s1 = map_1 < 0
s2 = map_2 < 0
map_1 = map_1.set_selected(s1, 0)
map_2 = map_... | assert small_copy_from_large_map.all() == small_map.all()
corr = flex.linear_correlation(
x = small_map.select(grid_indices),
y = small_copy_from_large_map.select(grid_indices))
if (not corr.is_well_defined()):
return None
return corr.coefficient()
def ccv(map_1, map_2, modified, centered, cutoff =... | 90 | 90 | 300 | 26 | 64 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | ccv | ccv | 1,060 | 1,083 | 1,060 | 1,060 | 541e95a3a906032b1dcac2b02c77a0b69c984789 | bigcode/the-stack | train |
c27f0f73a055b2506603a5b1 | train | function | def map_coefficients_to_map(map_coeffs, crystal_symmetry, n_real):
assert isinstance(map_coeffs.data(), flex.complex_double)
cg = crystal_gridding(
unit_cell = crystal_symmetry.unit_cell(),
space_group_info = crystal_symmetry.space_group_info(),
pre_determined_n_real = n_real)
fft_map... | def map_coefficients_to_map(map_coeffs, crystal_symmetry, n_real):
| assert isinstance(map_coeffs.data(), flex.complex_double)
cg = crystal_gridding(
unit_cell = crystal_symmetry.unit_cell(),
space_group_info = crystal_symmetry.space_group_info(),
pre_determined_n_real = n_real)
fft_map = map_coeffs.fft_map(
crystal_gridding = cg,
symmetry_flag... | 1, d2, d3 = \
a/nx/resolution_factor, \
b/ny/resolution_factor, \
c/nz/resolution_factor
return max(d1, d2, d3)
def map_coefficients_to_map(map_coeffs, crystal_symmetry, n_real):
| 64 | 64 | 118 | 17 | 47 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | map_coefficients_to_map | map_coefficients_to_map | 1,317 | 1,327 | 1,317 | 1,317 | 8632e46c4d08afe9061f5979d81ad9406049dcc8 | bigcode/the-stack | train |
ea2f5f1bb66ef213e0beaecd | train | class | class boxes_by_dimension(object):
def __init__(self,
n_real,
abc,
dim,
log = None,
prefix = ""):
self.n_real = n_real
#
step_1 = abc[0]/n_real[0] # step size along edge
step_2 = abc[1]/n_real[1] # step size along edge
step_... | class boxes_by_dimension(object):
| def __init__(self,
n_real,
abc,
dim,
log = None,
prefix = ""):
self.n_real = n_real
#
step_1 = abc[0]/n_real[0] # step size along edge
step_2 = abc[1]/n_real[1] # step size along edge
step_3 = abc[2]/n_real[2] # step size a... | = parameters.max_peaks(),
peak_cutoff = parameters.peak_cutoff(),
interpolate = parameters.interpolate())
if (parameters.min_distance_sym_equiv() is None):
return grid_peaks
return peak_cluster_analysis(
peak_list = grid_peaks,
special_position_settings = crystal.special_position_... | 169 | 169 | 565 | 6 | 163 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | boxes_by_dimension | boxes_by_dimension | 540 | 598 | 540 | 540 | 97443c68eb0372f0a5d721865d25f884739fe41e | bigcode/the-stack | train |
1da0f8c316717809b4ad69e6 | train | function | def cc_peak(cutoff, map_1 = None, map_2 = None, map_coeffs_1 = None, map_coeffs_2 = None):
"""
Compute CCpeak as described in
Acta Cryst. (2014). D70, 2593-2606
Metrics for comparison of crystallographic maps
A. Urzhumtsev, P. V. Afonine, V. Y. Lunin, T. C. Terwilliger and P. D. Adams
"""
from cctbx... | def cc_peak(cutoff, map_1 = None, map_2 = None, map_coeffs_1 = None, map_coeffs_2 = None):
| """
Compute CCpeak as described in
Acta Cryst. (2014). D70, 2593-2606
Metrics for comparison of crystallographic maps
A. Urzhumtsev, P. V. Afonine, V. Y. Lunin, T. C. Terwilliger and P. D. Adams
"""
from cctbx import miller
assert [map_1, map_2].count(None) in [0, 2]
assert [map_coeffs_1, map_co... | _point = value_at_closest_grid_point
flex.double.value_at_closest_grid_point = value_at_closest_grid_point
flex.double.eight_point_interpolation = eight_point_interpolation
flex.double.eight_point_interpolation_with_gradients = \
eight_point_interpolation_with_gradients
flex.double.quadratic_interpolation_with_gradie... | 146 | 146 | 487 | 35 | 110 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | cc_peak | cc_peak | 201 | 232 | 201 | 201 | 7accd75ff117eac91db5178bbd926baff3c40763 | bigcode/the-stack | train |
be4235149405a8c55a770a01 | train | function | def region_density_correlation(
large_unit_cell,
large_d_min,
large_density_map,
sites_cart,
site_radii,
work_scatterers):
sites_frac_large = large_unit_cell.fractionalize(sites_cart)
large_frac_min = sites_frac_large.min()
large_frac_max = sites_frac_large.max()
large_n_real... | def region_density_correlation(
large_unit_cell,
large_d_min,
large_density_map,
sites_cart,
site_radii,
work_scatterers):
| sites_frac_large = large_unit_cell.fractionalize(sites_cart)
large_frac_min = sites_frac_large.min()
large_frac_max = sites_frac_large.max()
large_n_real = large_density_map.focus()
from scitbx import fftpack
from libtbx.math_utils import ifloor, iceil
large_ucp = large_unit_cell.parameters()
small_n_re... | = True
continue
other_site = other_site_symmetry.exact_site()
dist_info = sgtbx.min_sym_equiv_distance_info(equiv_sites, other_site)
dist = dist_info.dist()
if (dist < self._min_cross_distance):
self._is_processed[i] = True
close_site = dist_info.apply(flex.vec3_double([... | 250 | 250 | 834 | 36 | 213 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | region_density_correlation | region_density_correlation | 984 | 1,058 | 984 | 990 | 96fac09e4857696852a704022c001493fdc3baf2 | bigcode/the-stack | train |
7322123fd5a5ea6ea573431d | train | class | class cluster_site_info(object):
def __init__(self, peak_list_index, grid_index, grid_height, site, height):
self.peak_list_index = peak_list_index
self.grid_index = grid_index
self.grid_height = grid_height
self.site = site
self.height = height
| class cluster_site_info(object):
| def __init__(self, peak_list_index, grid_index, grid_height, site, height):
self.peak_list_index = peak_list_index
self.grid_index = grid_index
self.grid_height = grid_height
self.site = site
self.height = height
| _fraction(self):
return self._cluster_height_fraction
def min_cross_distance(self):
return self._min_cross_distance
def max_clusters(self):
return self._max_clusters
def min_cubicle_edge(self):
return self._min_cubicle_edge
class cluster_site_info(object):
| 64 | 64 | 66 | 6 | 57 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | cluster_site_info | cluster_site_info | 737 | 744 | 737 | 738 | c8fcc3a5affbeddab614018577771af674a5fe0a | bigcode/the-stack | train |
d82b8965c4d045c359983cbd | train | function | def get_edge_score_towards_periodic(map_data,
use_minimum = True):
'''
Measure of whether facing edges have correlated data with correlation
similar to that found for adjacent planes and different than randomly
chosen points
If use_minimum is set, take minimum of values on all pairs of faces... | def get_edge_score_towards_periodic(map_data,
use_minimum = True):
| '''
Measure of whether facing edges have correlated data with correlation
similar to that found for adjacent planes and different than randomly
chosen points
If use_minimum is set, take minimum of values on all pairs of faces
'''
all = list(map_data.all())
one_data = flex.double(... | # High-frequency filter at this resolution
filtered_ma = ma.resolution_filter(d_min = d_min_value)
filtered_map = map_coefficients_to_map(
map_coeffs = filtered_ma,
crystal_symmetry = cs,
n_real = map_data.all())
# Make a difference map to look at only high_freq... | 256 | 256 | 886 | 19 | 236 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | get_edge_score_towards_periodic | get_edge_score_towards_periodic | 2,021 | 2,120 | 2,021 | 2,022 | 1326b021dd2cfc56584151eb82e52d9697852400 | bigcode/the-stack | train |
2b66ba7a613925fcd601f6b8 | train | function | def map_accumulator(n_real, use_max_map, smearing_b = 5, max_peak_scale = 2,
smearing_span = 10, use_exp_table = True):
"""
Good defaults for 2mFo-DFc type maps:
smearing_b = 1, max_peak_scale = 100, smearing_span = 5
"""
return ext.map_accumulator(n_real = n_real, smearing_b = smearing_... | def map_accumulator(n_real, use_max_map, smearing_b = 5, max_peak_scale = 2,
smearing_span = 10, use_exp_table = True):
| """
Good defaults for 2mFo-DFc type maps:
smearing_b = 1, max_peak_scale = 100, smearing_span = 5
"""
return ext.map_accumulator(n_real = n_real, smearing_b = smearing_b,
max_peak_scale = max_peak_scale, smearing_span = smearing_span,
use_exp_table = use_exp_table, use_max_map = use_max_map)
| map_2 = m2_he, cutoff = cutoff)
else:
raise Sorry("Combination of inputs not supported.")
def map_accumulator(n_real, use_max_map, smearing_b = 5, max_peak_scale = 2,
smearing_span = 10, use_exp_table = True):
| 64 | 64 | 133 | 39 | 25 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | map_accumulator | map_accumulator | 234 | 242 | 234 | 235 | 5ad65e5d0db02e0051325e594047a420dccaf99e | bigcode/the-stack | train |
ae0ce16bb617a91500dcf3de | train | function | def sharpen2(map, xray_structure, resolution, file_name_prefix):
from cctbx import miller
fo = miller.structure_factor_box_from_map(
crystal_symmetry = xray_structure.crystal_symmetry(), map = map)
#
fc = fo.structure_factors_from_scatterers(
xray_structure = xray_structure).f_calc()
d_fsc_model = fc.... | def sharpen2(map, xray_structure, resolution, file_name_prefix):
| from cctbx import miller
fo = miller.structure_factor_box_from_map(
crystal_symmetry = xray_structure.crystal_symmetry(), map = map)
#
fc = fo.structure_factors_from_scatterers(
xray_structure = xray_structure).f_calc()
d_fsc_model = fc.d_min_from_fsc(
other = fo, bin_width = 100, fsc_cutoff =... | _inflection_point
else:
i_cut = None
for i in range(ib0.radii.size()):
if(ib0.image_values[i]<= 0):
rad_cut = ib0.radii[i-1]
i_cut = i-1
break
assert i_cut is not None
# this gives a*exp(-b*x**2)
r = scitbx.math.gaussian_fit_1d_analytical(
x = ib0.... | 256 | 256 | 1,006 | 15 | 241 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | sharpen2 | sharpen2 | 1,603 | 1,689 | 1,603 | 1,603 | eecbfa8e8f0c103d510755fe859c342bdd59a624 | bigcode/the-stack | train |
516e58757fc0020a62a34edd | train | function | def loc_res(map,
model, #pdb_hierarchy,
crystal_symmetry,
chunk_size = 10,
soft_mask_radius = 3.,
method = "fsc",
hard_d_min = 1.5,
b_range_low = -200,
b_range_high = 500,
fsc_cutoff = 0.143,
wrappin... | def loc_res(map,
model, #pdb_hierarchy,
crystal_symmetry,
chunk_size = 10,
soft_mask_radius = 3.,
method = "fsc",
hard_d_min = 1.5,
b_range_low = -200,
b_range_high = 500,
fsc_cutoff = 0.143,
wrappin... | assert method in ["fsc", "rscc", "rscc_d_min_b"]
from cctbx import maptbx
from cctbx import miller
import mmtbx.utils
from iotbx.map_model_manager import map_model_manager
mmm = map.as_1d().min_max_mean().as_tuple()
map = map-mmm[2]
map = map/map.sample_standard_deviation()
cg = maptbx.crystal_gridd... | ray_structure = xray_structure,
n_real = map_data.all(),
rad_smooth = 2.0)
map_data = map_data * mask_object.mask_smooth
#
from iotbx import mrcfile
mrcfile.write_ccp4_map(
file_name = "%s.ccp4"%file_name_prefix,
unit_cell = cg.unit_cell(),
space_group = cg.space_group(),
#gr... | 256 | 256 | 1,373 | 95 | 160 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | loc_res | loc_res | 1,691 | 1,827 | 1,691 | 1,703 | 5254ac37799b3498c186c93b624f4ed586e46d5d | bigcode/the-stack | train |
d815252072211b203a39d8c2 | train | function | def smooth_map(map, crystal_symmetry, rad_smooth, method = "exp",
non_negative = True):
from cctbx import miller
assert method in ["exp", "box_average"]
map_smooth = None
if(method == "exp"):
f_map = miller.structure_factor_box_from_map(
map = map,
crystal_symmetry = crystal_sy... | def smooth_map(map, crystal_symmetry, rad_smooth, method = "exp",
non_negative = True):
| from cctbx import miller
assert method in ["exp", "box_average"]
map_smooth = None
if(method == "exp"):
f_map = miller.structure_factor_box_from_map(
map = map,
crystal_symmetry = crystal_symmetry,
include_000 = True)
ddd = f_map.d_spacings().data()
ddd.set_select... | self.regions()
min_boundaries = []
max_boundaries = []
for i in range(len(regs)):
minb = (boundaries[0, i, 0], boundaries[0, i, 1], boundaries[0, i, 2])
maxb = (boundaries[1, i, 0], boundaries[1, i, 1], boundaries[1, i, 2])
min_boundaries.append(minb)
max_boundaries.append(maxb)
... | 141 | 141 | 471 | 24 | 116 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | smooth_map | smooth_map | 52 | 93 | 52 | 53 | d694452f9bdedc1b53607ac8c7cbc2df6ecde52e | bigcode/the-stack | train |
7a656a10def4cee4529c34ce | train | class | class atom_curves(object):
"""
Class-toolkit to compute various 1-atom 1D curves: exact electron density,
Fourier image of specified resolution, etc.
"""
def __init__(self, scattering_type, scattering_table = "wk1995",
scattering_dictionary=None):
adopt_init_args(self, locals())
assert [se... | class atom_curves(object):
| """
Class-toolkit to compute various 1-atom 1D curves: exact electron density,
Fourier image of specified resolution, etc.
"""
def __init__(self, scattering_type, scattering_table = "wk1995",
scattering_dictionary=None):
adopt_init_args(self, locals())
assert [self.scattering_table, self.s... | (),
step = 0.1)
fc = xrs.structure_factors(d_min = d_min, algorithm = "direct").f_calc()
fft_map = miller.fft_map(
crystal_gridding = cg,
fourier_coefficients = fc,
f_000 = xrs.f_000())
fft_map.apply_volume_scaling()
map_data = fft_map.real_map_unpadded()
def se... | 256 | 256 | 2,137 | 6 | 249 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | atom_curves | atom_curves | 1,396 | 1,601 | 1,396 | 1,396 | 8e2686941b0093dba92d33ea924b30fc350f987a | bigcode/the-stack | train |
474483122adc9979731b4e31 | train | function | def get_resolution_where_significant_data_present(ma,
minimum_fraction_data_points=0.1):
# Now filter ma at resolution where there are significant data
sel = ( ma.amplitudes().data() > 1.e-10)
ma_with_data = ma.select(sel)
n_bins = int(0.5+10 * 1/minimum_fraction_data_points)
ma_with_data.setup_b... | def get_resolution_where_significant_data_present(ma,
minimum_fraction_data_points=0.1):
# Now filter ma at resolution where there are significant data
| sel = ( ma.amplitudes().data() > 1.e-10)
ma_with_data = ma.select(sel)
n_bins = int(0.5+10 * 1/minimum_fraction_data_points)
ma_with_data.setup_binner(n_bins = n_bins, d_max = 10000.,
d_min = ma_with_data.d_min())
dsd = ma_with_data.d_spacings().data()
ibin_list=list(ma_with_data.binner().... | maximum for any edge
return relative_sd_on_edges
else: # use overall
return boundary_data.standard_deviation_of_the_sample(
) / max(1.e-10,sd_overall)
def get_resolution_where_significant_data_present(ma,
minimum_fraction_data_points=0.1):
# Now filter ma at resolution where there are s... | 78 | 78 | 260 | 33 | 45 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | get_resolution_where_significant_data_present | get_resolution_where_significant_data_present | 1,913 | 1,935 | 1,913 | 1,915 | 05ab2a5f94240a5c1f4438edcc048041656c3f70 | bigcode/the-stack | train |
09437ea24059d7591f5bb425 | train | class | @bp.inject_into(ext.histogram)
class _():
"""
Injector for extending cctbx.maptbx.histogram
"""
# XXX make a method of scitbx
def get_percentile_cutoffs(self, map, vol_cutoff_plus_percent,
vol_cutoff_minus_percent):
"""
For the double-step filtration in cctbx.miller (used as part of the
pro... | @bp.inject_into(ext.histogram)
class _():
| """
Injector for extending cctbx.maptbx.histogram
"""
# XXX make a method of scitbx
def get_percentile_cutoffs(self, map, vol_cutoff_plus_percent,
vol_cutoff_minus_percent):
"""
For the double-step filtration in cctbx.miller (used as part of the
procedure for replacing missing F-obs in maps)... | _radii + solvent_radius)
class statistics(ext.statistics):
def __init__(self, map):
ext.statistics.__init__(self, map)
@bp.inject_into(ext.statistics)
class _():
def show_summary(self, f = None, prefix = ""):
if (f is None): f = sys.stdout
print(prefix + "max %.6g" % (self.max()), file = f)
prin... | 177 | 177 | 592 | 11 | 166 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | _ | _ | 317 | 376 | 317 | 319 | 380d1db78234433f223e32e55cfbdc1db66aed77 | bigcode/the-stack | train |
9db7acd2fc6879e11650dffc | train | function | def sphericity_by_heuristics(
map_data,
unit_cell,
center_cart,
radius,
s_angle_sampling_step = 20,
t_angle_sampling_step = 20):
points_on_sphere_cart = flex.vec3_double()
for s in range(0, 360, s_angle_sampling_step):
for t in range(0, 360, t_angle_sampling_step):
xc, ... | def sphericity_by_heuristics(
map_data,
unit_cell,
center_cart,
radius,
s_angle_sampling_step = 20,
t_angle_sampling_step = 20):
| points_on_sphere_cart = flex.vec3_double()
for s in range(0, 360, s_angle_sampling_step):
for t in range(0, 360, t_angle_sampling_step):
xc, yc, zc = scitbx.math.point_on_sphere(r = radius, s_deg = s, t_deg = t,
center = center_cart)
points_on_sphere_cart.append([xc, yc, zc])
o = sphericit... | use_scale = True,
anomalous_flag = False,
use_sg = False)
def sphericity_by_heuristics(
map_data,
unit_cell,
center_cart,
radius,
s_angle_sampling_step = 20,
t_angle_sampling_step = 20):
| 64 | 64 | 206 | 42 | 22 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | sphericity_by_heuristics | sphericity_by_heuristics | 1,212 | 1,230 | 1,212 | 1,218 | 1cecd9e52224390ee9bf8bc9d6c88d3b556af78f | bigcode/the-stack | train |
ef69142248dbf492f72bb8ec | train | function | def mask(xray_structure,
n_real,
mask_value_inside_molecule = 0,
mask_value_outside_molecule = 1,
solvent_radius = 0,
atom_radius = None):
xrs_p1 = xray_structure.expand_to_p1(sites_mod_positive = True)
if(atom_radius is None):
from cctbx.masks import vdw_radii_from_... | def mask(xray_structure,
n_real,
mask_value_inside_molecule = 0,
mask_value_outside_molecule = 1,
solvent_radius = 0,
atom_radius = None):
| xrs_p1 = xray_structure.expand_to_p1(sites_mod_positive = True)
if(atom_radius is None):
from cctbx.masks import vdw_radii_from_xray_structure
atom_radii = vdw_radii_from_xray_structure(xray_structure = xrs_p1)
else:
atom_radii = flex.double(xrs_p1.scatterers().size(), atom_radius)
return ext.mask(
... | _sigma_less_than,
scale_by = scale_by,
set_value = set_value)
def mask(xray_structure,
n_real,
mask_value_inside_molecule = 0,
mask_value_outside_molecule = 1,
solvent_radius = 0,
atom_radius = None):
| 64 | 64 | 211 | 44 | 20 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | mask | mask | 279 | 297 | 279 | 284 | c1fb1979fda8874ecda342ded0ea228a0283893f | bigcode/the-stack | train |
24ebf948053f5be8e55f7aed | train | class | class spherical_variance_around_point(object):
def __init__(self,
real_map,
unit_cell,
site_cart,
radius,
n_points = 40,
spline_interpolation = True,
write_sphere_points_to_pdb_file = None):
self.site_cart = site_cart
self.radius = radius
assert n_points>0
sph... | class spherical_variance_around_point(object):
| def __init__(self,
real_map,
unit_cell,
site_cart,
radius,
n_points = 40,
spline_interpolation = True,
write_sphere_points_to_pdb_file = None):
self.site_cart = site_cart
self.radius = radius
assert n_points>0
sphere_points = []
x, y, z = site_cart
# r... | = map_2 < 0
map_1 = map_1.set_selected(s1, 0)
map_2 = map_2.set_selected(s2, 0)
def corr(x, y, centered):
s1 = x > 0
s2 = y > 0
s = s1 | s2
s = s.iselection()
x_ = x.select(s)
y_ = y.select(s)
return flex.linear_correlation(x = x_, y = y_,
subtract_mean = c... | 189 | 189 | 630 | 9 | 180 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | spherical_variance_around_point | spherical_variance_around_point | 1,085 | 1,137 | 1,085 | 1,085 | 4a96684861c75e612f22237c11d32269c6694a96 | bigcode/the-stack | train |
6f1ad31c92e1d86df99a9fe4 | train | function | def map_peak_3d_as_2d(
map_data,
unit_cell,
center_cart,
radius,
step = 0.01,
s_angle_sampling_step = 10,
t_angle_sampling_step = 10):
rho_1d = flex.double()
dist = flex.double()
radius = int(radius*100)+1
step = int(step*100)
for r in range(0, radius, step):
r = ... | def map_peak_3d_as_2d(
map_data,
unit_cell,
center_cart,
radius,
step = 0.01,
s_angle_sampling_step = 10,
t_angle_sampling_step = 10):
| rho_1d = flex.double()
dist = flex.double()
radius = int(radius*100)+1
step = int(step*100)
for r in range(0, radius, step):
r = r/100.
dist.append(r)
rho = flex.double()
for s in range(0, 360, s_angle_sampling_step):
for t in range(0, 360, t_angle_sampling_step):
xc, yc, zc = sc... | _cell)
return group_args(rho = o.rho_min_max_mean(), ccs = o.ccs_min_max_mean())
def map_peak_3d_as_2d(
map_data,
unit_cell,
center_cart,
radius,
step = 0.01,
s_angle_sampling_step = 10,
t_angle_sampling_step = 10):
| 78 | 78 | 263 | 52 | 26 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | map_peak_3d_as_2d | map_peak_3d_as_2d | 1,232 | 1,256 | 1,232 | 1,239 | 909912b5810737c27721b1eed17f668b0d71c847 | bigcode/the-stack | train |
ab8d20b99b9cc242e5464ef7 | train | class | @bp.inject_into(ext.statistics)
class _():
def show_summary(self, f = None, prefix = ""):
if (f is None): f = sys.stdout
print(prefix + "max %.6g" % (self.max()), file = f)
print(prefix + "min %.6g" % (self.min()), file = f)
print(prefix + "mean %.6g" % (self.mean()), file = f)
print(prefix + "si... | @bp.inject_into(ext.statistics)
class _():
| def show_summary(self, f = None, prefix = ""):
if (f is None): f = sys.stdout
print(prefix + "max %.6g" % (self.max()), file = f)
print(prefix + "min %.6g" % (self.min()), file = f)
print(prefix + "mean %.6g" % (self.mean()), file = f)
print(prefix + "sigma %.6g" % (self.sigma()), file = f)
| _molecule,
mask_value_outside_molecule = mask_value_outside_molecule,
radii = atom_radii + solvent_radius)
class statistics(ext.statistics):
def __init__(self, map):
ext.statistics.__init__(self, map)
@bp.inject_into(ext.statistics)
class _():
| 64 | 64 | 113 | 10 | 54 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | _ | _ | 304 | 312 | 304 | 306 | 2d50a784896efce0e3bb51c8e8326fd2ed8f949e | bigcode/the-stack | train |
d3f5da9f24d9cd80eb51f9b8 | train | class | class peak_cluster_analysis(object):
def __init__(self, peak_list,
special_position_settings,
general_positions_only = False,
effective_resolution = None,
significant_height_fraction = None,
cluster_height_fracti... | class peak_cluster_analysis(object):
| def __init__(self, peak_list,
special_position_settings,
general_positions_only = False,
effective_resolution = None,
significant_height_fraction = None,
cluster_height_fraction = None,
min_cr... | _edge
def peak_search_level(self):
return self._peak_search_level
def max_peaks(self):
return self._max_peaks
def peak_cutoff(self):
return self._peak_cutoff
def interpolate(self):
return self._interpolate
def min_distance_sym_equiv(self):
return self._min_distance_sym_equiv
def ge... | 256 | 256 | 2,036 | 6 | 249 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | peak_cluster_analysis | peak_cluster_analysis | 746 | 982 | 746 | 747 | e3211555bca196118fb1f226da8ace655529efb2 | bigcode/the-stack | train |
4c6adf45bbd1423b3e1272e0 | train | function | def get_relative_cc(
boundary_zero_data = None,
boundary_one_data = None,
one_data = None):
cc_boundary_zero_one= flex.linear_correlation(boundary_zero_data,
boundary_one_data).coefficient()
cc_positive_control= flex.linear_correlation(boundary_zero_data,
one_data).coefficient()
... | def get_relative_cc(
boundary_zero_data = None,
boundary_one_data = None,
one_data = None):
| cc_boundary_zero_one= flex.linear_correlation(boundary_zero_data,
boundary_one_data).coefficient()
cc_positive_control= flex.linear_correlation(boundary_zero_data,
one_data).coefficient()
# Make negative control with randomized order of data
one_data_random_perm= one_data.select(
... | _data,
one_data=one_data,)
edge_score_towards_periodic = max(0,min(1,relative_cc ))
return edge_score_towards_periodic
def get_relative_cc(
boundary_zero_data = None,
boundary_one_data = None,
one_data = None):
| 64 | 64 | 213 | 25 | 38 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | get_relative_cc | get_relative_cc | 2,122 | 2,146 | 2,122 | 2,126 | 071f1b6b88dc2f4200a1150b42a98880e3e3b6e6 | bigcode/the-stack | train |
ab2abb55a05068ab0b4c6ad3 | train | function | def is_periodic(map_data,
minimum_fraction_data_points = 0.1,
high_confidence_delta = 0.2,
medium_confidence_delta = 0.25):
'''
Determine if this map is periodic. If values on opposite faces are
about as similar as values on adjacent planes, it is probably periodic.
Two tests ... | def is_periodic(map_data,
minimum_fraction_data_points = 0.1,
high_confidence_delta = 0.2,
medium_confidence_delta = 0.25):
| '''
Determine if this map is periodic. If values on opposite faces are
about as similar as values on adjacent planes, it is probably periodic.
Two tests are used: (1) correlation of facing edges of map and
(2) test whether difference map between original and map without
high r... | order of data
one_data_random_perm= one_data.select(
flex.random_permutation(len(one_data)))
cc_negative_control = flex.linear_correlation(boundary_zero_data,
one_data_random_perm).coefficient()
# Expect that negative controls about zero, positive control high near 1,
# then cc_bound... | 177 | 177 | 592 | 40 | 136 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | is_periodic | is_periodic | 2,148 | 2,209 | 2,148 | 2,152 | 8e88996ee0fc53e075df08316d0afbc75d4fbb2d | bigcode/the-stack | train |
94a27e07c7cc619f7b8793b6 | train | class | class crystal_gridding_tags(crystal_gridding):
def __init__(self, gridding):
crystal_gridding._copy_constructor(self, gridding)
assert gridding.symmetry_flags() is not None
self._tags = grid_tags(dim = self.n_real())
self._tags.build(
space_group_type = self.space_group_info().type(),
sym... | class crystal_gridding_tags(crystal_gridding):
| def __init__(self, gridding):
crystal_gridding._copy_constructor(self, gridding)
assert gridding.symmetry_flags() is not None
self._tags = grid_tags(dim = self.n_real())
self._tags.build(
space_group_type = self.space_group_info().type(),
symmetry_flags = self.symmetry_flags())
assert ... | assert self.space_group_info() is not None
return self.space_group_info().group()
def crystal_symmetry(self):
assert self.space_group_info() is not None
return crystal.symmetry(
unit_cell = self.unit_cell(),
space_group_info = self.space_group_info())
def n_grid_points(self):
result =... | 115 | 115 | 385 | 10 | 105 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | crystal_gridding_tags | crystal_gridding_tags | 497 | 538 | 497 | 498 | f36110246fc503efd537af21412906ffda847407 | bigcode/the-stack | train |
184bb9089410476b6a00a5e5 | train | function | def d_min_corner(map_data, unit_cell):
max_index = flex.miller_index( [[(i-1)//2 for i in map_data.all()]] )
return uctbx.d_star_sq_as_d(unit_cell.max_d_star_sq( max_index ))
| def d_min_corner(map_data, unit_cell):
| max_index = flex.miller_index( [[(i-1)//2 for i in map_data.all()]] )
return uctbx.d_star_sq_as_d(unit_cell.max_d_star_sq( max_index ))
| tbx.test_utils import approx_equal
x, y = self.f, self.f_mod
x, y = x.common_sets(y)
x = abs(x).data()
y = abs(y).data()
assert approx_equal(x, y)
def d_min_corner(map_data, unit_cell):
| 64 | 64 | 55 | 10 | 54 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | d_min_corner | d_min_corner | 1,304 | 1,306 | 1,304 | 1,304 | fc8b1def856f666b60ef9b1085e76da008694bb8 | bigcode/the-stack | train |
d64fff9395a0697f600f8a6f | train | class | class d99(object):
def __init__(self, map = None, f_map = None, crystal_symmetry = None):
adopt_init_args(self, locals())
if(map is not None):
assert f_map is None
assert crystal_symmetry is not None
map = shift_origin_if_needed(map_data = map).map_data
from cctbx import miller
s... | class d99(object):
| def __init__(self, map = None, f_map = None, crystal_symmetry = None):
adopt_init_args(self, locals())
if(map is not None):
assert f_map is None
assert crystal_symmetry is not None
map = shift_origin_if_needed(map_data = map).map_data
from cctbx import miller
self.f_map = miller.... | for i in range(3):
maptbx.map_box_average(
map_data = map_smooth,
index_span = 1)
for i in range(3):
maptbx.map_box_average(
map_data = map_smooth,
cutoff = 0.99,
index_span = 1)
return map_smooth
class d99(object):
| 85 | 85 | 284 | 5 | 79 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | d99 | d99 | 95 | 120 | 95 | 95 | 11445ce2322a8072987df716879e501e6a6da512 | bigcode/the-stack | train |
7be60ae4f713a3919fd8f274 | train | class | class local_scale(object):
def __init__(
self,
crystal_gridding,
crystal_symmetry,
f_map = None,
map_data = None,
miller_array = None,
d_min = None): #XXX = 1: more features and noise
# process inputs
assert [f_map, map_data].count(None) == 1
if(f... | class local_scale(object):
| def __init__(
self,
crystal_gridding,
crystal_symmetry,
f_map = None,
map_data = None,
miller_array = None,
d_min = None): #XXX = 1: more features and noise
# process inputs
assert [f_map, map_data].count(None) == 1
if(f_map is not None):
im... | (
map_data = real_map,
unit_cell = unit_cell,
radius = radius,
site_frac = unit_cell.fractionalize(site_cart))
es = adptbx.eigensystem(st)
def center_of_mass_():
return center_of_mass(
map_data = real_map, unit_cell = unit_cell, cutoff = 0.1)
def inertia_tensor():
return st
def e... | 134 | 134 | 449 | 5 | 129 | dperl-sol/cctbx_project | cctbx/maptbx/__init__.py | Python | local_scale | local_scale | 1,162 | 1,210 | 1,162 | 1,162 | 22edd1e332ec991f636f1121e316bbda5369fbdf | bigcode/the-stack | train |
5e9effb3094105e63c2b734a | train | class | class HalfSpaceTrees(base.AnomalyDetector):
"""Half-Space Trees (HST).
Half-space trees are an online variant of isolation forests. They work well when anomalies are
spread out. However, they do not work well if anomalies are packed together in windows.
By default, this implementation assumes that eac... | class HalfSpaceTrees(base.AnomalyDetector):
| """Half-Space Trees (HST).
Half-space trees are an online variant of isolation forests. They work well when anomalies are
spread out. However, they do not work well if anomalies are packed together in windows.
By default, this implementation assumes that each feature has values that are comprised
... | imits.keys()),
weights=[limits[i][1] - limits[i][0] for i in limits],
)[0]
# Pick a split point; use padding to avoid too narrow a split
a = limits[on][0]
b = limits[on][1]
at = rng.uniform(a + padding * (b - a), b - padding * (b - a))
# Build the left node
tmp = limits[on]
lim... | 256 | 256 | 1,495 | 10 | 246 | mathco-wf/river | river/anomaly/hst.py | Python | HalfSpaceTrees | HalfSpaceTrees | 95 | 272 | 95 | 95 | 4e5643ac9fb5ffdbd74afb6ddc5bdb4c1f67480d | bigcode/the-stack | train |
f94d7cee9d438f8562fc7a40 | train | class | class HSTLeaf(Leaf):
def __repr__(self):
return str(self.r_mass)
| class HSTLeaf(Leaf):
| def __repr__(self):
return str(self.r_mass)
| return left
if value < self.threshold:
return left
return right
def most_common_path(self):
raise NotImplementedError
@property
def repr_split(self):
return f"{self.feature} < {self.threshold:.5f}"
class HSTLeaf(Leaf):
| 63 | 64 | 21 | 7 | 56 | mathco-wf/river | river/anomaly/hst.py | Python | HSTLeaf | HSTLeaf | 54 | 56 | 54 | 54 | 11c33661218ce4edb89f74c25a889954a2a085ca | bigcode/the-stack | train |
d96338709addbaaaa4e45b7f | train | function | def make_padded_tree(limits, height, padding, rng=random, **node_params):
if height == 0:
return HSTLeaf(**node_params)
# Randomly pick a feature
# We weight each feature by the gap between each feature's limits
on = rng.choices(
population=list(limits.keys()),
weights=[limits[... | def make_padded_tree(limits, height, padding, rng=random, **node_params):
| if height == 0:
return HSTLeaf(**node_params)
# Randomly pick a feature
# We weight each feature by the gap between each feature's limits
on = rng.choices(
population=list(limits.keys()),
weights=[limits[i][1] - limits[i][0] for i in limits],
)[0]
# Pick a split point; ... | if value < self.threshold:
return left
return right
def most_common_path(self):
raise NotImplementedError
@property
def repr_split(self):
return f"{self.feature} < {self.threshold:.5f}"
class HSTLeaf(Leaf):
def __repr__(self):
return str(self.r_mas... | 94 | 94 | 315 | 19 | 75 | mathco-wf/river | river/anomaly/hst.py | Python | make_padded_tree | make_padded_tree | 59 | 92 | 59 | 60 | da45b5f1fab41774432842962dd50894bb848bdd | bigcode/the-stack | train |
c991b05082804405d49795e4 | train | class | class HSTBranch(Branch):
def __init__(self, left, right, feature, threshold, l_mass, r_mass):
super().__init__(left, right)
self.feature = feature
self.threshold = threshold
self.l_mass = l_mass
self.r_mass = r_mass
@property
def left(self):
return self.child... | class HSTBranch(Branch):
| def __init__(self, left, right, feature, threshold, l_mass, r_mass):
super().__init__(left, right)
self.feature = feature
self.threshold = threshold
self.l_mass = l_mass
self.r_mass = r_mass
@property
def left(self):
return self.children[0]
@property
... | import collections
import functools
import random
import typing
from river import base
from river.tree.base import Branch, Leaf
__all__ = ["HalfSpaceTrees"]
class HSTBranch(Branch):
| 42 | 71 | 237 | 7 | 35 | mathco-wf/river | river/anomaly/hst.py | Python | HSTBranch | HSTBranch | 12 | 51 | 12 | 12 | 946124d47c4a11abf71ed5dbfd4932dd684a666e | bigcode/the-stack | train |
35ddb5c851653be039ecaec7 | train | class | class TestTinyInt(ProtocolV4Test):
def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestTinyInt, self).setUp()
... | class TestTinyInt(ProtocolV4Test):
| def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestTinyInt, self).setUp()
column = columns.TinyInt
pkey_... | 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestSmallInt, self).setUp()
column = columns.SmallInt
pkey_val = 16768
data_val = 32523
class TestTinyInt(ProtocolV4Test):
| 64 | 64 | 94 | 10 | 53 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestTinyInt | TestTinyInt | 270 | 284 | 270 | 271 | bd2c3723edbac86331223c21dad55f7430afb9c0 | bigcode/the-stack | train |
f7ce18c1be56aec0686c7e3a | train | class | class TestNonBinaryTextIO(BaseColumnIOTest):
column = columns.Text
pkey_val = 'bacon'
data_val = '0xmonkey'
| class TestNonBinaryTextIO(BaseColumnIOTest):
| column = columns.Text
pkey_val = 'bacon'
data_val = '0xmonkey'
| bytes
data_val = bytearray(six.b('eggleston')), uuid4().bytes
class TestTextIO(BaseColumnIOTest):
column = columns.Text
pkey_val = 'bacon'
data_val = 'monkey'
class TestNonBinaryTextIO(BaseColumnIOTest):
| 64 | 64 | 36 | 11 | 53 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestNonBinaryTextIO | TestNonBinaryTextIO | 127 | 131 | 127 | 128 | 4191904c60c6dcfd79ac62fd0bfa71e6295d835d | bigcode/the-stack | train |
b5bbeeddaf7f82deee58ea9d | train | class | class ProtocolV4Test(BaseColumnIOTest):
@classmethod
def setUpClass(cls):
if PROTOCOL_VERSION >= 4:
super(ProtocolV4Test, cls).setUpClass()
@classmethod
def tearDownClass(cls):
if PROTOCOL_VERSION >= 4:
super(ProtocolV4Test, cls).tearDownClass()
| class ProtocolV4Test(BaseColumnIOTest):
@classmethod
| def setUpClass(cls):
if PROTOCOL_VERSION >= 4:
super(ProtocolV4Test, cls).setUpClass()
@classmethod
def tearDownClass(cls):
if PROTOCOL_VERSION >= 4:
super(ProtocolV4Test, cls).tearDownClass()
| 5, '2.4'
data_val = Decimal('0.005'), 3.5, '8'
def comparator_converter(self, val):
return Decimal(repr(val) if isinstance(val, float) else val)
class ProtocolV4Test(BaseColumnIOTest):
@classmethod
| 64 | 64 | 78 | 14 | 50 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | ProtocolV4Test | ProtocolV4Test | 206 | 216 | 206 | 208 | e33803835b85360770e1a8f78c98d8b0c7609ca1 | bigcode/the-stack | train |
d8f4277c24b8780b0f167485 | train | class | class TestBlobIO2(BaseColumnIOTest):
column = columns.Blob
pkey_val = bytearray(six.b('blake')), uuid4().bytes
data_val = bytearray(six.b('eggleston')), uuid4().bytes
| class TestBlobIO2(BaseColumnIOTest):
| column = columns.Blob
pkey_val = bytearray(six.b('blake')), uuid4().bytes
data_val = bytearray(six.b('eggleston')), uuid4().bytes
| key).delete(self.conn)
class TestBlobIO(BaseColumnIOTest):
column = columns.Blob
pkey_val = six.b('blake'), uuid4().bytes
data_val = six.b('eggleston'), uuid4().bytes
class TestBlobIO2(BaseColumnIOTest):
| 64 | 64 | 55 | 10 | 53 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestBlobIO2 | TestBlobIO2 | 113 | 117 | 113 | 114 | 9e059316ff349b5660e7f6861d4096188082e6c9 | bigcode/the-stack | train |
ff7936ba1549a709aa8b7a73 | train | class | class TestBlobIO(BaseColumnIOTest):
column = columns.Blob
pkey_val = six.b('blake'), uuid4().bytes
data_val = six.b('eggleston'), uuid4().bytes
| class TestBlobIO(BaseColumnIOTest):
| column = columns.Blob
pkey_val = six.b('blake'), uuid4().bytes
data_val = six.b('eggleston'), uuid4().bytes
| key == m2.pkey == self.comparator_converter(pkey), self.column
assert m1.data == m2.data == self.comparator_converter(data), self.column
# delete
self._generated_model.filter(pkey=pkey).delete(self.conn)
class TestBlobIO(BaseColumnIOTest):
| 64 | 64 | 48 | 9 | 55 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestBlobIO | TestBlobIO | 106 | 110 | 106 | 107 | 955c1ee8b87128027ca0f135787d308ade63522e | bigcode/the-stack | train |
ca40d34132fe6bab494cb21e | train | class | class TestDecimalIO(BaseColumnIOTest):
column = columns.Decimal
pkey_val = Decimal('1.35'), 5, '2.4'
data_val = Decimal('0.005'), 3.5, '8'
def comparator_converter(self, val):
return Decimal(repr(val) if isinstance(val, float) else val)
| class TestDecimalIO(BaseColumnIOTest):
| column = columns.Decimal
pkey_val = Decimal('1.35'), 5, '2.4'
data_val = Decimal('0.005'), 3.5, '8'
def comparator_converter(self, val):
return Decimal(repr(val) if isinstance(val, float) else val)
|
pkey_val = 4.75
data_val = -1.5
class TestDoubleIO(BaseColumnIOTest):
column = columns.Double
pkey_val = 3.14
data_val = -1982.11
class TestDecimalIO(BaseColumnIOTest):
| 64 | 64 | 76 | 9 | 54 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestDecimalIO | TestDecimalIO | 195 | 203 | 195 | 196 | f64dc7617101d15454f838873230e82f50e7ecc2 | bigcode/the-stack | train |
79a2d8d55d0b10b0dd388392 | train | class | class TestFloatIO(BaseColumnIOTest):
column = columns.Float
pkey_val = 4.75
data_val = -1.5
| class TestFloatIO(BaseColumnIOTest):
| column = columns.Float
pkey_val = 4.75
data_val = -1.5
| ColumnIOTest):
column = columns.TimeUUID
pkey_val = str(uuid1()), uuid1()
data_val = str(uuid1()), uuid1()
def comparator_converter(self, val):
return val if isinstance(val, UUID) else UUID(val)
class TestFloatIO(BaseColumnIOTest):
| 64 | 64 | 34 | 9 | 55 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestFloatIO | TestFloatIO | 179 | 184 | 179 | 180 | 4e88c383998265d00fdc50283653ddafe798c419 | bigcode/the-stack | train |
39be092a263c86996ac2f4f7 | train | class | class TestDate(ProtocolV4Test):
def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestDate, self).setUp()
colum... | class TestDate(ProtocolV4Test):
| def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestDate, self).setUp()
column = columns.Date
now = Date(... | PROTOCOL_VERSION >= 4:
super(ProtocolV4Test, cls).setUpClass()
@classmethod
def tearDownClass(cls):
if PROTOCOL_VERSION >= 4:
super(ProtocolV4Test, cls).tearDownClass()
class TestDate(ProtocolV4Test):
| 64 | 64 | 104 | 9 | 55 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestDate | TestDate | 218 | 233 | 218 | 219 | 5502c0b16649b88d42df8bfa2f11dbef016d922a | bigcode/the-stack | train |
a387696cc5f44ef1c4c506ea | train | class | class TestTimeUUID(BaseColumnIOTest):
column = columns.TimeUUID
pkey_val = str(uuid1()), uuid1()
data_val = str(uuid1()), uuid1()
def comparator_converter(self, val):
return val if isinstance(val, UUID) else UUID(val)
| class TestTimeUUID(BaseColumnIOTest):
| column = columns.TimeUUID
pkey_val = str(uuid1()), uuid1()
data_val = str(uuid1()), uuid1()
def comparator_converter(self, val):
return val if isinstance(val, UUID) else UUID(val)
| (BaseColumnIOTest):
column = columns.UUID
pkey_val = str(uuid4()), uuid4()
data_val = str(uuid4()), uuid4()
def comparator_converter(self, val):
return val if isinstance(val, UUID) else UUID(val)
class TestTimeUUID(BaseColumnIOTest):
| 64 | 64 | 60 | 9 | 55 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestTimeUUID | TestTimeUUID | 168 | 176 | 168 | 169 | 09f381ac48ad15119fcbd5897f4bff5a700bddbb | bigcode/the-stack | train |
d0eaf6a35ff339ebe4820987 | train | class | class TestSmallInt(ProtocolV4Test):
def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestSmallInt, self).setUp()
... | class TestSmallInt(ProtocolV4Test):
| def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestSmallInt, self).setUp()
column = columns.SmallInt
pke... | )
super(TestTime, self).setUp()
column = columns.Time
pkey_val = Time(time(2, 12, 7, 48))
data_val = Time(time(16, 47, 25, 7))
class TestSmallInt(ProtocolV4Test):
| 64 | 64 | 95 | 10 | 54 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestSmallInt | TestSmallInt | 253 | 267 | 253 | 254 | affdacaa72e26ad546470a6a29de8b1656b49c88 | bigcode/the-stack | train |
1aeea9db07316d78796d5489 | train | class | class TestTime(ProtocolV4Test):
def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestTime, self).setUp()
colum... | class TestTime(ProtocolV4Test):
| def setUp(self):
if PROTOCOL_VERSION < 4:
raise unittest.SkipTest(
"Protocol v4 datatypes require native protocol 4+, "
"currently using: {0}".format(PROTOCOL_VERSION)
)
super(TestTime, self).setUp()
column = columns.Time
pkey_val = ... | {0}".format(PROTOCOL_VERSION)
)
super(TestDate, self).setUp()
column = columns.Date
now = Date(datetime.now().date())
pkey_val = now
data_val = Date(now.days_from_epoch + 1)
class TestTime(ProtocolV4Test):
| 64 | 64 | 112 | 9 | 55 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestTime | TestTime | 236 | 250 | 236 | 237 | adf09462cceee753cd9943b110428dd811248d82 | bigcode/the-stack | train |
26d6618bfe85082b2d51d2ae | train | class | class TestUUID(BaseColumnIOTest):
column = columns.UUID
pkey_val = str(uuid4()), uuid4()
data_val = str(uuid4()), uuid4()
def comparator_converter(self, val):
return val if isinstance(val, UUID) else UUID(val)
| class TestUUID(BaseColumnIOTest):
| column = columns.UUID
pkey_val = str(uuid4()), uuid4()
data_val = str(uuid4()), uuid4()
def comparator_converter(self, val):
return val if isinstance(val, UUID) else UUID(val)
| 63) - 1
class TestDateTime(BaseColumnIOTest):
column = columns.DateTime
now = datetime(*datetime.now().timetuple()[:6])
pkey_val = now
data_val = now + timedelta(days=1)
class TestUUID(BaseColumnIOTest):
| 64 | 64 | 58 | 8 | 56 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestUUID | TestUUID | 157 | 165 | 157 | 158 | 1212eac89da684d34f97b261d232ffcbf1aa3c7c | bigcode/the-stack | train |
adfd271a3617d28b4833efac | train | class | class TestDoubleIO(BaseColumnIOTest):
column = columns.Double
pkey_val = 3.14
data_val = -1982.11
| class TestDoubleIO(BaseColumnIOTest):
| column = columns.Double
pkey_val = 3.14
data_val = -1982.11
| def comparator_converter(self, val):
return val if isinstance(val, UUID) else UUID(val)
class TestFloatIO(BaseColumnIOTest):
column = columns.Float
pkey_val = 4.75
data_val = -1.5
class TestDoubleIO(BaseColumnIOTest):
| 64 | 64 | 35 | 9 | 54 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestDoubleIO | TestDoubleIO | 187 | 192 | 187 | 188 | ce4ecb48ec0a1c333675b71f3607ae121a859b3a | bigcode/the-stack | train |
578709153c9e5b04f4caa577 | train | class | class TestBigInt(BaseColumnIOTest):
column = columns.BigInt
pkey_val = 6
data_val = pow(2, 63) - 1
| class TestBigInt(BaseColumnIOTest):
| column = columns.BigInt
pkey_val = 6
data_val = pow(2, 63) - 1
| ):
column = columns.Text
pkey_val = 'bacon'
data_val = '0xmonkey'
class TestInteger(BaseColumnIOTest):
column = columns.Integer
pkey_val = 5
data_val = 6
class TestBigInt(BaseColumnIOTest):
| 64 | 64 | 39 | 9 | 54 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestBigInt | TestBigInt | 141 | 145 | 141 | 142 | 457e45efe60f3148311cb5df8275d898f5602455 | bigcode/the-stack | train |
f71141495ebcaa1d1db652fb | train | class | class BaseColumnIOTest(BaseCassEngTestCase):
"""
Tests that values are come out of cassandra in the format we expect
To test a column type, subclass this test, define the column, and the primary key
and data values you want to test
"""
# The generated test model is assigned here
_generated... | class BaseColumnIOTest(BaseCassEngTestCase):
| """
Tests that values are come out of cassandra in the format we expect
To test a column type, subclass this test, define the column, and the primary key
and data values you want to test
"""
# The generated test model is assigned here
_generated_model = None
# the column we want to te... | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
from datetime import datetime, timedelta, time
from deci... | 151 | 151 | 505 | 11 | 139 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | BaseColumnIOTest | BaseColumnIOTest | 37 | 103 | 37 | 37 | 255128ccde89d0207b0f4133acb5089fcb2a75fb | bigcode/the-stack | train |
ec3353bf92552ea997790c2c | train | class | class TestTextIO(BaseColumnIOTest):
column = columns.Text
pkey_val = 'bacon'
data_val = 'monkey'
| class TestTextIO(BaseColumnIOTest):
| column = columns.Text
pkey_val = 'bacon'
data_val = 'monkey'
| class TestBlobIO2(BaseColumnIOTest):
column = columns.Blob
pkey_val = bytearray(six.b('blake')), uuid4().bytes
data_val = bytearray(six.b('eggleston')), uuid4().bytes
class TestTextIO(BaseColumnIOTest):
| 64 | 64 | 32 | 9 | 54 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestTextIO | TestTextIO | 120 | 124 | 120 | 121 | f7e9ca140e04d27da8d1c53941bdf5529c725f9f | bigcode/the-stack | train |
d0f873411c8523370115633c | train | class | class TestDateTime(BaseColumnIOTest):
column = columns.DateTime
now = datetime(*datetime.now().timetuple()[:6])
pkey_val = now
data_val = now + timedelta(days=1)
| class TestDateTime(BaseColumnIOTest):
| column = columns.DateTime
now = datetime(*datetime.now().timetuple()[:6])
pkey_val = now
data_val = now + timedelta(days=1)
|
pkey_val = 5
data_val = 6
class TestBigInt(BaseColumnIOTest):
column = columns.BigInt
pkey_val = 6
data_val = pow(2, 63) - 1
class TestDateTime(BaseColumnIOTest):
| 64 | 64 | 49 | 9 | 54 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestDateTime | TestDateTime | 148 | 154 | 148 | 149 | 9d56fe767988d0c991b593ab11099b3396620841 | bigcode/the-stack | train |
6eea4aca3c3eacb1cb4ba23b | train | class | class TestInteger(BaseColumnIOTest):
column = columns.Integer
pkey_val = 5
data_val = 6
| class TestInteger(BaseColumnIOTest):
| column = columns.Integer
pkey_val = 5
data_val = 6
| columns.Text
pkey_val = 'bacon'
data_val = 'monkey'
class TestNonBinaryTextIO(BaseColumnIOTest):
column = columns.Text
pkey_val = 'bacon'
data_val = '0xmonkey'
class TestInteger(BaseColumnIOTest):
| 64 | 64 | 29 | 8 | 56 | kimception/cqlmapper | tests/integration/columns/test_value_io.py | Python | TestInteger | TestInteger | 134 | 138 | 134 | 135 | 6e9ca0b3af281d42788a9e43cff201a9ed5bb8f1 | bigcode/the-stack | train |
3a9c06e440c859ed8da111f8 | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('projectmanager', '0005_taskhistory_user'),
]
operations = [
migrations.AddField(
model_name='project',
name='assigned_by',
field=... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('projectmanager', '0005_taskhistory_user'),
]
operations = [
migrations.AddField(
model_name='project',
name='assigned_by',
field=models.ForeignKey(blank=True, null=True,... | # Generated by Django 3.1.1 on 2020-10-08 03:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 64 | 87 | 7 | 43 | GMNaim/Online-Project-Tracking-System | src/projectmanager/migrations/0006_project_assigned_by.py | Python | Migration | Migration | 8 | 21 | 8 | 9 | 69fc08d5d615948970aea00520a5d6143103dde6 | bigcode/the-stack | train |
7f3b0f7760b304883a25e77f | train | function | def test_rate_limiting_sampler():
rate_limiter = RateLimiter(2, 2)
# stop time by overwriting timestamp() function to always return
# the same time
ts = time.time()
rate_limiter.last_tick = ts
with mock.patch('jaeger_client.rate_limiter.RateLimiter.timestamp') \
as mock_time:
... | def test_rate_limiting_sampler():
| rate_limiter = RateLimiter(2, 2)
# stop time by overwriting timestamp() function to always return
# the same time
ts = time.time()
rate_limiter.last_tick = ts
with mock.patch('jaeger_client.rate_limiter.RateLimiter.timestamp') \
as mock_time:
mock_time.side_effect = lambda: t... | # Copyright (c) 2017 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | 162 | 169 | 565 | 7 | 154 | rbtcollins/jaeger-client-python | tests/test_rate_limiter.py | Python | test_rate_limiting_sampler | test_rate_limiting_sampler | 21 | 66 | 21 | 21 | 42af3a43401ac111695a5aa8bd1aee41c7872eb8 | bigcode/the-stack | train |
4aba280e99609faeee6f609b | train | function | def __main():
server.launch()
| def __main():
| server.launch()
| from implementation.server import server
def __main():
| 10 | 64 | 8 | 4 | 5 | PUT-II/artificial-life-project-1 | src/main.py | Python | __main | __main | 4 | 5 | 4 | 4 | 20802e89b465abfc93bcc2b2d24f8c211326f6bc | bigcode/the-stack | train |
39436c763a67c4416dca5f2f | train | function | def get_aws_metadata(headers, provider=None):
if not provider:
provider = boto.provider.get_default()
metadata_prefix = provider.metadata_prefix
metadata = {}
for hkey in headers.keys():
if hkey.lower().startswith(metadata_prefix):
val = urllib.parse.unquote(headers[hkey])
... | def get_aws_metadata(headers, provider=None):
| if not provider:
provider = boto.provider.get_default()
metadata_prefix = provider.metadata_prefix
metadata = {}
for hkey in headers.keys():
if hkey.lower().startswith(metadata_prefix):
val = urllib.parse.unquote(headers[hkey])
if isinstance(val, bytes):
... | for k in metadata.keys():
if k.lower() in boto.s3.key.Key.base_user_settable_fields:
final_headers[k] = metadata[k]
else:
final_headers[metadata_prefix + k] = metadata[k]
return final_headers
def get_aws_metadata(headers, provider=None):
| 64 | 64 | 123 | 10 | 53 | ContextLogic/boto | boto/provider_util.py | Python | get_aws_metadata | get_aws_metadata | 104 | 120 | 104 | 104 | 759edf8d9b69a61602444e16e47d1086c0a8a516 | bigcode/the-stack | train |
2aa9745120e8f4893a27c31d | train | function | def merge_meta(headers, metadata, provider=None):
if not provider:
provider = boto.provider.get_default()
metadata_prefix = provider.metadata_prefix
final_headers = headers.copy()
for k in metadata.keys():
if k.lower() in boto.s3.key.Key.base_user_settable_fields:
final_heade... | def merge_meta(headers, metadata, provider=None):
| if not provider:
provider = boto.provider.get_default()
metadata_prefix = provider.metadata_prefix
final_headers = headers.copy()
for k in metadata.keys():
if k.lower() in boto.s3.key.Key.base_user_settable_fields:
final_headers[k] = metadata[k]
else:
fina... | if len(qsa) > 0:
qsa.sort(key=lambda x: x[0])
qsa = ['='.join(a) for a in qsa]
buf += '?'
buf += '&'.join(qsa)
return buf
def merge_meta(headers, metadata, provider=None):
| 64 | 64 | 92 | 10 | 53 | ContextLogic/boto | boto/provider_util.py | Python | merge_meta | merge_meta | 90 | 101 | 90 | 90 | 286a91e743f973571bc456093ed1d816e9e1dfa1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.