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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
488385e73175768a0afbe626 | train | function | def process_results(result_folder):
test_results = []
additional_files = []
# Just upload all files from result_folder.
# If task provides processed results, then it's responsible for content of result_folder.
if os.path.exists(result_folder):
test_files = [f for f in os.listdir(result_folde... | def process_results(result_folder):
| test_results = []
additional_files = []
# Just upload all files from result_folder.
# If task provides processed results, then it's responsible for content of result_folder.
if os.path.exists(result_folder):
test_files = [f for f in os.listdir(result_folder) if os.path.isfile(os.path.join(re... | ["CLICKHOUSE_TESTS_RESULT_PATH"] = result_path
my_env["CLICKHOUSE_TESTS_BASE_CONFIG_DIR"] = f"{repo_path}/programs/server"
my_env["CLICKHOUSE_TESTS_JSON_PARAMS_PATH"] = os.path.join(work_path, "params.json")
my_env["CLICKHOUSE_TESTS_RUNNER_RESTART_DOCKER"] = '0'
return my_env
def process_results(result... | 88 | 88 | 296 | 6 | 81 | zhangjmruc/ClickHouse | tests/ci/integration_test_check.py | Python | process_results | process_results | 68 | 95 | 68 | 68 | ad37147029c60d07e98bc39f0ec0ea84e71b8110 | bigcode/the-stack | train |
d62dff7e2cbdbe85ab056e3f | train | function | def get_json_params_dict(check_name, pr_info, docker_images):
return {
'context_name': check_name,
'commit': pr_info.sha,
'pull_request': pr_info.number,
'pr_info': {'changed_files' : list(pr_info.changed_files)},
'docker_images_with_versions': docker_images,
'shuffle... | def get_json_params_dict(check_name, pr_info, docker_images):
| return {
'context_name': check_name,
'commit': pr_info.sha,
'pull_request': pr_info.number,
'pr_info': {'changed_files' : list(pr_info.changed_files)},
'docker_images_with_versions': docker_images,
'shuffle_test_groups': False,
'use_tmpfs': False,
'dis... | -client",
"yandex/clickhouse-postgresql-java-client",
"yandex/clickhouse-integration-test",
"yandex/clickhouse-kerberos-kdc",
"yandex/clickhouse-integration-helper",
]
def get_json_params_dict(check_name, pr_info, docker_images):
| 64 | 64 | 94 | 14 | 50 | zhangjmruc/ClickHouse | tests/ci/integration_test_check.py | Python | get_json_params_dict | get_json_params_dict | 37 | 47 | 37 | 37 | 7baea2c3d6b14b7ef2e218a8f70e27bddf6479c9 | bigcode/the-stack | train |
eda55caffea9feb70fdfc256 | train | function | def generate_report() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('sample_name', help='The sample name or id for which the QC metrics apply')
parser.add_argument('metrics_dir', help='The directory to search for metric files, often a cromwell run directory')
parser.add_argument('outpu... | def generate_report() -> None:
| parser = argparse.ArgumentParser()
parser.add_argument('sample_name', help='The sample name or id for which the QC metrics apply')
parser.add_argument('metrics_dir', help='The directory to search for metric files, often a cromwell run directory')
parser.add_argument('output_file', help='File path to sto... | import argparse
import os.path
from .threshold_file_parser import ThresholdFileParser
from .qc_validator import QcValidator
from .metrics import AvailableMetrics
from .report_generator import ReportGenerator
def generate_report() -> None:
| 48 | 67 | 224 | 7 | 40 | tmooney/qc-metric-aggregator | process_metrics/__main__.py | Python | generate_report | generate_report | 9 | 30 | 9 | 9 | 8dd1b2f801d339905dfc1e0d4b8d8df1fc94a600 | bigcode/the-stack | train |
c4395defff90354f98090039 | train | function | def random_cwalk( printer, climits, steps):
"""
Generates a random motion based on the printer volume and input limits
Movements are differentiated by a time interval
Movements are relative to the center of the build plate
printer --> Print volume of the printer (x_max, y_max, z_max)
... | def random_cwalk( printer, climits, steps):
| """
Generates a random motion based on the printer volume and input limits
Movements are differentiated by a time interval
Movements are relative to the center of the build plate
printer --> Print volume of the printer (x_max, y_max, z_max)
limits --> Maximum travel for the random ... | generate positions
for j in range( 0, len(rm) ):
position[i,j] = limits[j]*rm[j] + offsets[j]
#return
return position, offsets, limits, printer
# -------------------------------------------------------------------------------------- #
def random_cwalk( printer, climits, steps):
| 63 | 64 | 212 | 12 | 51 | pd3d/magneto | Software/Python/motion/paths.py | Python | random_cwalk | random_cwalk | 119 | 143 | 119 | 119 | 1a2c38a54d70b58a848bb5aa56a6ace12852c9cd | bigcode/the-stack | train |
936b836d4ec8a92cf2e79df3 | train | function | def helix():
"""
Generates a default parametric helix obtained from the matplotlib examples
"""
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(0, 2*np.pi, 100)
z = np.linspace(0, 1, 100)
r = z + 1
x = r * np.sin(theta)
... | def helix():
| """
Generates a default parametric helix obtained from the matplotlib examples
"""
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(0, 2*np.pi, 100)
z = np.linspace(0, 1, 100)
r = z + 1
x = r * np.sin(theta)
y = r * np... | D functions generating 3D paths
Fluvio L Lobo Fenoglietto
"""
"""
Import Modules and Libraries
"""
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
# -------------------------------------------------------------------------------------- #
def helix(... | 64 | 64 | 145 | 4 | 60 | pd3d/magneto | Software/Python/motion/paths.py | Python | helix | helix | 19 | 36 | 19 | 19 | e1b967945022dcfe1d99e313d9e73867ad8efaab | bigcode/the-stack | train |
6f4e72435c05f485b538e8fe | train | function | def prog_helix( max_x, max_y, max_z ):
"""
Generates a helix based on the maximum ranges in x, y, and z, given by;
x --> ( -max_x, max_x )
y --> ( -max_y, max_y )
z --> ( 0, max_z )
"""
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection=... | def prog_helix( max_x, max_y, max_z ):
| """
Generates a helix based on the maximum ranges in x, y, and z, given by;
x --> ( -max_x, max_x )
y --> ( -max_y, max_y )
z --> ( 0, max_z )
"""
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
z = np.linspace(0, max_z, 500... | x = np.cos(t)
y = np.sin(t)
ax.plot(x, y, t, label='parametric curve')
ax.legend()
plt.show()
return x, y, t
# -------------------------------------------------------------------------------------- #
def prog_helix( max_x, max_y, max_z ):
| 64 | 64 | 169 | 15 | 49 | pd3d/magneto | Software/Python/motion/paths.py | Python | prog_helix | prog_helix | 61 | 79 | 61 | 61 | fd6b2e0c12d5a3bc2e20acc4b50f2fd896655c38 | bigcode/the-stack | train |
93186d258c05799d0bf9543a | train | function | def unit_helix():
"""
Generates a unit helix
"""
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
t = np.linspace(0, 1, 1000)
#z = np.linspace(0, 1, 100)
#r = z + 1
x = np.cos(t)
y = np.sin(t)
ax.plot(x, y, t, label='parametric curv... | def unit_helix():
| """
Generates a unit helix
"""
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
t = np.linspace(0, 1, 1000)
#z = np.linspace(0, 1, 100)
#r = z + 1
x = np.cos(t)
y = np.sin(t)
ax.plot(x, y, t, label='parametric curve')
ax.legend(... | x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
return x, y, z, r, theta
# -------------------------------------------------------------------------------------- #
def unit_helix():
| 64 | 64 | 133 | 6 | 58 | pd3d/magneto | Software/Python/motion/paths.py | Python | unit_helix | unit_helix | 39 | 58 | 39 | 39 | c3a8bab7b9ec05af05d5a193c9c89b427b7d89a1 | bigcode/the-stack | train |
9036903543685d7e1187a1bf | train | function | def random_cwalkwr( printer, climits, steps):
"""
Random Center Walk with Retraction
Random motion based on the printer volume and input limits
Movements are relative to the center of the build plate
Random movements are followed by a retraction to the origin
printer --> ... | def random_cwalkwr( printer, climits, steps):
| """
Random Center Walk with Retraction
Random motion based on the printer volume and input limits
Movements are relative to the center of the build plate
Random movements are followed by a retraction to the origin
printer --> Print volume of the printer (x_max, y_max, z_m... | = np.zeros((steps, 3))
for i in range( 0, steps ):
# generate random multipliers
rm = np.random.rand(3,1) - np.random.rand(3,1)
# generate positions
for j in range( 0, len(rm) ):
position[i,j] = climits[j]*rm[j]
#return
return position, climits, printer
#... | 110 | 110 | 369 | 13 | 97 | pd3d/magneto | Software/Python/motion/paths.py | Python | random_cwalkwr | random_cwalkwr | 146 | 181 | 146 | 146 | a4e3a85132dd8555133bd61be3d04759e0385f52 | bigcode/the-stack | train |
6506c6ec7d41592127fef9ae | train | function | def random_walk( printer, limits, steps):
"""
Generates a random motion based on the printer volume and input limits
Movements are differentiated by a time interval
printer --> Print volume of the printer (x_max, y_max, z_max)
limits --> Maximum travel for the random walk (x_limit, y_l... | def random_walk( printer, limits, steps):
| """
Generates a random motion based on the printer volume and input limits
Movements are differentiated by a time interval
printer --> Print volume of the printer (x_max, y_max, z_max)
limits --> Maximum travel for the random walk (x_limit, y_limit, z_limit)
steps --> Numbe... | = fig.gca(projection='3d')
z = np.linspace(0, max_z, 5000)
x = max_x*np.cos(z)
y = max_y*np.sin(z)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
return x, y, z
# -------------------------------------------------------------------------------------- #
def random_wa... | 89 | 89 | 297 | 10 | 79 | pd3d/magneto | Software/Python/motion/paths.py | Python | random_walk | random_walk | 82 | 116 | 82 | 82 | 24581a643d902d6b4c494124a4df778720edf634 | bigcode/the-stack | train |
ba77aaab072d75fc4aa6ca51 | train | class | class SubDictReader():
def __init__(self, stringPathToThisItemsSubDictionary, simDefinition):
'''
Example stringPathToThisItemsSubDictionary = 'Rocket.Stage1.Nosecone' if we're initializing a nosecone object
'''
self.simDefDictPathToReadFrom = stringPathToThisItemsSubDictionary
... | class SubDictReader():
| def __init__(self, stringPathToThisItemsSubDictionary, simDefinition):
'''
Example stringPathToThisItemsSubDictionary = 'Rocket.Stage1.Nosecone' if we're initializing a nosecone object
'''
self.simDefDictPathToReadFrom = stringPathToThisItemsSubDictionary
self.simDefiniti... | '''
Wrapper class to read from a specific sub-dictionary in a SimDefinition.
'''
from distutils.util import strtobool
from typing import List, Union
from MAPLEAF.Motion import Vector
__all__ = [ "SubDictReader" ]
class SubDictReader():
| 59 | 256 | 997 | 5 | 54 | henrystoldt/MAPLEAF | MAPLEAF/IO/subDictReader.py | Python | SubDictReader | SubDictReader | 12 | 121 | 12 | 13 | 852ba8ae33865027a9a64aebae6c5c3fa0783401 | bigcode/the-stack | train |
285b88fdeedb93555662d1de | train | class | class TestVm(zstack_header.ZstackObject):
def __init__(self):
self.vm = None
self.state = None
self.delete_policy = None
self.delete_delay_time = None
def __repr__(self):
if self.vm:
return '%s-%s' % (self.__class__.__name__, self.vm.uuid)
return '%s... | class TestVm(zstack_header.ZstackObject):
| def __init__(self):
self.vm = None
self.state = None
self.delete_policy = None
self.delete_delay_time = None
def __repr__(self):
if self.vm:
return '%s-%s' % (self.__class__.__name__, self.vm.uuid)
return '%s-None' % self.__class__.__name__
def c... | ibinding.inventory as inventory
import zstackwoodpecker.header.header as zstack_header
RUNNING = inventory.RUNNING
STOPPED = inventory.STOPPED
DESTROYED = inventory.DESTROYED
EXPUNGED = 'EXPUNGED'
VOLUME_BANDWIDTH = 'volumeTotalBandwidth'
VOLUME_IOPS = 'volumeTotalIops'
NETWORK_OUTBOUND_BANDWIDTH = 'networkOutboundBa... | 97 | 97 | 324 | 10 | 87 | KevinDavidMitnick/zstack-woodpecker | zstackwoodpecker/zstackwoodpecker/header/vm.py | Python | TestVm | TestVm | 13 | 78 | 13 | 14 | d88b138f468fad8893c0ae2a576f1113aa664c15 | bigcode/the-stack | train |
a5b8c8dfcdad90be1faedf5d | train | class | class Solution:
def numSub(self, s: str) -> int:
cnt = 0
res = 0
for i in s:
if i == '1':
cnt += 1
else:
res += cnt * (cnt +1) /2
cnt = 0
if cnt > 0:
res += cnt * (cnt + 1)/ 2
res %= 1e9+7
... | class Solution:
| def numSub(self, s: str) -> int:
cnt = 0
res = 0
for i in s:
if i == '1':
cnt += 1
else:
res += cnt * (cnt +1) /2
cnt = 0
if cnt > 0:
res += cnt * (cnt + 1)/ 2
res %= 1e9+7
return int(... | class Solution:
| 3 | 64 | 105 | 3 | 0 | zdyxry/LeetCode | math/1513_number_of_substrings_with_only_1s/1513_number_of_substrings_with_only_1s.py | Python | Solution | Solution | 1 | 14 | 1 | 1 | f6fe1f22e67a7b3c2704b48a27370431ef13f46b | bigcode/the-stack | train |
82d9955b3ec02354dc8def90 | train | class | class ObjectDetection_20class(object):
def __init__(self, method='opencv_dnn'):
if method == 'opencv_dnn':
prototxt_file = '../models/MobileNetSSD_deploy.prototxt'
model_file = '../models/MobileNetSSD_deploy.caffemodel'
self.net = cv2.dnn.readNetFromCaffe(prototxt_file, ... | class ObjectDetection_20class(object):
| def __init__(self, method='opencv_dnn'):
if method == 'opencv_dnn':
prototxt_file = '../models/MobileNetSSD_deploy.prototxt'
model_file = '../models/MobileNetSSD_deploy.caffemodel'
self.net = cv2.dnn.readNetFromCaffe(prototxt_file, model_file)
self.inference_e... | import cv2
import numpy as np
class ObjectDetection_20class(object):
| 17 | 142 | 474 | 8 | 8 | YipengChen/HappyAI | base_ai/object_detection_ai.py | Python | ObjectDetection_20class | ObjectDetection_20class | 4 | 35 | 4 | 5 | e15d5283cd179635b48851fa93b2565263b1fc7b | bigcode/the-stack | train |
e1d4da85a8d935a30671e540 | train | class | class ObjectDetection_80class(object):
def __init__(self, method='opencv_dnn', model_name='yolov4-tiny', confidence_threshold=0.25, nms_threshold=0.4):
if method == 'opencv_dnn':
if model_name == 'yolov4-tiny':
cfg_file = '../models/yolov4-tiny.cfg'
weights_file ... | class ObjectDetection_80class(object):
| def __init__(self, method='opencv_dnn', model_name='yolov4-tiny', confidence_threshold=0.25, nms_threshold=0.4):
if method == 'opencv_dnn':
if model_name == 'yolov4-tiny':
cfg_file = '../models/yolov4-tiny.cfg'
weights_file = '../models/yolov4-tiny.weights'
... | int(results[0, 0, i, 1])
start_x, start_y, end_x, end_y = (results[0, 0, i, 3:7] * np.array([w, h, w, h])).astype(np.int)
label = "{}: {:.2f}%".format(self.classes[idx], confidence * 100)
cv2.rectangle(image, (start_x, start_y), (end_x, end_y), self.colors[idx], 2)
... | 155 | 155 | 518 | 8 | 146 | YipengChen/HappyAI | base_ai/object_detection_ai.py | Python | ObjectDetection_80class | ObjectDetection_80class | 38 | 75 | 38 | 39 | 996b52bd100ae4c9701e6ae1b30cc33b5b1187f9 | bigcode/the-stack | train |
fd01742a5e7ae371e955c65c | train | class | class RidgeEnsemble:
def __init__(self, ridges):
assert type(ridges) == list
self.ridges = ridges
def predict(self, x):
predictions = np.zeros(len(x))
for ridge in self.ridges:
predictions += ridge.predict(x)
predictions /= len(self.ridges)
return... | class RidgeEnsemble:
| def __init__(self, ridges):
assert type(ridges) == list
self.ridges = ridges
def predict(self, x):
predictions = np.zeros(len(x))
for ridge in self.ridges:
predictions += ridge.predict(x)
predictions /= len(self.ridges)
return predictions
| '''
Ensembles ridge regression models to do grid-level predictions with equal voting from each model
'''
import numpy as np
class RidgeEnsemble:
| 30 | 64 | 74 | 5 | 24 | edwardoughton/taddle | utils/ridge_ensemble.py | Python | RidgeEnsemble | RidgeEnsemble | 5 | 15 | 5 | 5 | 228f587d168aee5e60cd4c2d049bfe72df78ad3c | bigcode/the-stack | train |
2598b75671c068f9a032fd87 | train | function | def parse():
parser = argparse.ArgumentParser()
parser.add_argument('indexedfeaturesjar',help='indexedcorpus jarfile')
for (k,v) in sorted(AF.featuresets.items()):
parser.add_argument('--' + k,nargs='*',help=v)
args = parser.parse_args()
return args
| def parse():
| parser = argparse.ArgumentParser()
parser.add_argument('indexedfeaturesjar',help='indexedcorpus jarfile')
for (k,v) in sorted(AF.featuresets.items()):
parser.add_argument('--' + k,nargs='*',help=v)
args = parser.parse_args()
return args
| as UF
from scs.jbc.retrieval.IndexJar import IndexJar
from scs.jbc.similarity.SearchTerms import SearchTerms
from scs.jbc.similarity.FindSimilar import FindSimilar
import scs.jbc.cmdline.algorithms.AlgorithmicFeaturesRecorder as AF
def parse():
| 64 | 64 | 67 | 3 | 60 | kestreltechnology/kt-semantic-code-search | scs/jbc/cmdline/algorithms/chj_search.py | Python | parse | parse | 45 | 51 | 45 | 45 | a357690bc32e071633855488ddab31302e0c25bd | bigcode/the-stack | train |
e7fbaf0c7e5803f81c9eee48 | train | function | @contextmanager
def timing():
t0 = time.time()
yield
print('Completed in ' + str(time.time() - t0) + ' secs')
| @contextmanager
def timing():
| t0 = time.time()
yield
print('Completed in ' + str(time.time() - t0) + ' secs')
| parser.add_argument('indexedfeaturesjar',help='indexedcorpus jarfile')
for (k,v) in sorted(AF.featuresets.items()):
parser.add_argument('--' + k,nargs='*',help=v)
args = parser.parse_args()
return args
@contextmanager
def timing():
| 64 | 64 | 36 | 7 | 56 | kestreltechnology/kt-semantic-code-search | scs/jbc/cmdline/algorithms/chj_search.py | Python | timing | timing | 53 | 57 | 53 | 54 | 1fe03f820be635e442e7a44de05e7a578f999fb3 | bigcode/the-stack | train |
6caef7fdbb742b5ef127361a | train | function | def unf_pb_Valko_MPaa(rsb_m3m3=100, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
"""
bubble point pressure calculation according to Valko McCain (2002) correlation
:param rsb_m3m3: solution ration at bubble point, must be given, m3/m3
:param gamma_oil: specific oil density (by water)
:param gamma_g... | def unf_pb_Valko_MPaa(rsb_m3m3=100, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
| """
bubble point pressure calculation according to Valko McCain (2002) correlation
:param rsb_m3m3: solution ration at bubble point, must be given, m3/m3
:param gamma_oil: specific oil density (by water)
:param gamma_gas: specific gas density (by air)
:param t_K: temperature, K
:return:... | .where(rsb_m3m3 < min_rsb, min_rsb, rsb_m3m3)
yg = 1.225 + 0.001648 * t_K - 1.769 / gamma_oil # gas molar fraction
pb_MPaa = 0.5197 * (rsb_m3m3 / gamma_gas) ** 0.83 * 10 ** yg
# for low rsb values, we set the asymptotics Pb = 1 atma at Rsb = 0
# for large rsb values do not correct what the corre... | 225 | 225 | 750 | 38 | 186 | unifloc/neftpy | neftpy/upvt.py | Python | unf_pb_Valko_MPaa | unf_pb_Valko_MPaa | 50 | 95 | 50 | 50 | 2b5629a81effe7cae06f5180dc59ec2cd324cf7f | bigcode/the-stack | train |
e2cf02315409efb5ef1d365d | train | function | def unf_compressibility_oil_VB_1Mpa(rs_m3m3, t_K, gamma_oil, p_MPaa, gamma_gas=0.6): # TODO above bubble point!!
"""
Oil compressibility according to Vasquez & Beggs (1980) correlation
:param rs_m3m3: solution gas-oil ratio, m3m3
:param t_K: temperature, K
:param gamma_oil: specific oil density... | def unf_compressibility_oil_VB_1Mpa(rs_m3m3, t_K, gamma_oil, p_MPaa, gamma_gas=0.6): # TODO above bubble point!!
| """
Oil compressibility according to Vasquez & Beggs (1980) correlation
:param rs_m3m3: solution gas-oil ratio, m3m3
:param t_K: temperature, K
:param gamma_oil: specific oil density (by water)
:param p_MPaa: pressure, MPaa
:param gamma_gas: specific gas density (by air)
:return: co... | ) + 0.449 * np.log(rsb_scfstb))
co_1MPa = uc.compr_1psi_2_1MPa(co_1psi)# * 10 ** 5 # TODO надо разобраться и исправить
return co_1MPa
def unf_compressibility_oil_VB_1Mpa(rs_m3m3, t_K, gamma_oil, p_MPaa, gamma_gas=0.6): # TODO above bubble point!!
| 106 | 106 | 354 | 44 | 61 | unifloc/neftpy | neftpy/upvt.py | Python | unf_compressibility_oil_VB_1Mpa | unf_compressibility_oil_VB_1Mpa | 386 | 410 | 386 | 386 | d5d8cc5742597f99e35e1014ff56c1383d741028 | bigcode/the-stack | train |
dbd18e4c586c4c4082e49f8b | train | function | def unf_oil_viscosity_Beggs_VB_cP(deadoilviscosity_cP, rs_m3m3, p_MPaa, pb_MPaa):
"""
Function for calculating the viscosity at any pressure
:param deadoilviscosity_cP: dead oil viscosity,cP
:param rs_m3m3: solution gas-oil ratio, m3m3
:param p_MPaa: pressure, MPaa
:param pb_MPaa: bubble po... | def unf_oil_viscosity_Beggs_VB_cP(deadoilviscosity_cP, rs_m3m3, p_MPaa, pb_MPaa):
| """
Function for calculating the viscosity at any pressure
:param deadoilviscosity_cP: dead oil viscosity,cP
:param rs_m3m3: solution gas-oil ratio, m3m3
:param p_MPaa: pressure, MPaa
:param pb_MPaa: bubble point pressure, MPaa
:return: oil viscosity,cP
"""
saturatedviscosi... | = bubblepointviscosity_cP * (p_psia / pb_psia) ** m
return viscosity_cP
def unf_oil_viscosity_Beggs_VB_cP(deadoilviscosity_cP, rs_m3m3, p_MPaa, pb_MPaa):
| 64 | 64 | 211 | 37 | 26 | unifloc/neftpy | neftpy/upvt.py | Python | unf_oil_viscosity_Beggs_VB_cP | unf_oil_viscosity_Beggs_VB_cP | 534 | 549 | 534 | 534 | 04ce17a23bd7b558464b4ad2ae3a5b7334fde5a4 | bigcode/the-stack | train |
9373eb32014d280543d9e8c7 | train | function | def unf_bo_below_pb_m3m3(rho_oil_st_kgm3=820, rs_m3m3=100, rho_oil_insitu_kgm3=700, gamma_gas=0.8):
"""
Oil Formation Volume Factor according McCain correlation for pressure below bubble point pressure
:param rho_oil_st_kgm3: density of stock-tank oil, kgm3
:param rs_m3m3: solution gas-oil ratio, m... | def unf_bo_below_pb_m3m3(rho_oil_st_kgm3=820, rs_m3m3=100, rho_oil_insitu_kgm3=700, gamma_gas=0.8):
| """
Oil Formation Volume Factor according McCain correlation for pressure below bubble point pressure
:param rho_oil_st_kgm3: density of stock-tank oil, kgm3
:param rs_m3m3: solution gas-oil ratio, m3m3
:param rho_oil_insitu_kgm3: Oil density at reservoir conditions, kgm3
:param gamma_gas: ... | m3, bob_m3m3 * np.exp(compr_o_1MPa * (pb_MPaa - p_MPaa)))
def unf_bo_below_pb_m3m3(rho_oil_st_kgm3=820, rs_m3m3=100, rho_oil_insitu_kgm3=700, gamma_gas=0.8):
| 78 | 78 | 261 | 50 | 28 | unifloc/neftpy | neftpy/upvt.py | Python | unf_bo_below_pb_m3m3 | unf_bo_below_pb_m3m3 | 242 | 256 | 242 | 242 | 9ed52434f75dc6a4d9eea6e5b06e35788b5d64eb | bigcode/the-stack | train |
fdccd8a96671ec95f69a8c13 | train | function | def unf_rs_Velarde_m3m3(p_MPaa=1, pb_MPaa=10, rsb_m3m3=100., gamma_oil=0.86, gamma_gas=0.6, t_K=350):
"""
Solution Gas-oil ratio calculation according to Velarde McCain (1999) correlation
:param p_MPaa: pressure, MPa
:param pb_MPaa: buble point pressure, MPa
:param rsb_m3m3: gas-oil ratio at th... | def unf_rs_Velarde_m3m3(p_MPaa=1, pb_MPaa=10, rsb_m3m3=100., gamma_oil=0.86, gamma_gas=0.6, t_K=350):
| """
Solution Gas-oil ratio calculation according to Velarde McCain (1999) correlation
:param p_MPaa: pressure, MPa
:param pb_MPaa: buble point pressure, MPa
:param rsb_m3m3: gas-oil ratio at the bubble point pressure, m3/m3
:param gamma_oil: specific oil density (by water)
:param gamma_... | rs_m3m3 = np.where(pb_MPaa * rsb_m3m3 == 0,
gamma_gas * (1.92 * p_MPaa / 10 ** yg(t_K, gamma_oil)) ** 1.204,
np.where(p_MPaa < pb_MPaa,
rsb_m3m3 * np.divide(p_MPaa, pb_MPaa,
where=pb... | 175 | 175 | 585 | 52 | 122 | unifloc/neftpy | neftpy/upvt.py | Python | unf_rs_Velarde_m3m3 | unf_rs_Velarde_m3m3 | 135 | 172 | 135 | 135 | 6b4f7d1d5aa0f20e62439d787fc971c89cca7605 | bigcode/the-stack | train |
3cb595133cf33933708c394e | train | function | def unf_compessibility_oil_VB_1MPa_vba(rsb_m3m3, t_k, gamma_oil, gamma_gas):
co_1atm = (28.1 * rsb_m3m3 + 30.6 * t_k - 1180 * gamma_gas + 1784 / gamma_oil - 10910)
return 1/uc.atm_2_bar(1/co_1atm)/10 #*))) **когда не дружишь с математикой ***когда слишком много времени потратил на uniflocpy
| def unf_compessibility_oil_VB_1MPa_vba(rsb_m3m3, t_k, gamma_oil, gamma_gas):
| co_1atm = (28.1 * rsb_m3m3 + 30.6 * t_k - 1180 * gamma_gas + 1784 / gamma_oil - 10910)
return 1/uc.atm_2_bar(1/co_1atm)/10 #*))) **когда не дружишь с математикой ***когда слишком много времени потратил на uniflocpy
| 0 * gamma_gas + 12.61 * api) / (1e5 * p_psia)),
0.0
)
def unf_compessibility_oil_VB_1MPa_vba(rsb_m3m3, t_k, gamma_oil, gamma_gas):
| 64 | 64 | 126 | 33 | 31 | unifloc/neftpy | neftpy/upvt.py | Python | unf_compessibility_oil_VB_1MPa_vba | unf_compessibility_oil_VB_1MPa_vba | 412 | 414 | 412 | 412 | 7e932f092ea1d1e771dc98f4c8ca6dfb2c847041 | bigcode/the-stack | train |
68b66c990186f353e6bba5ed | train | function | def unf_compressibility_saturated_oil_McCain_1Mpa(p_MPa=1, pb_MPa=10, t_K=300, gamma_oil=0.86, rsb_m3m3=100):
"""
Oil compressibility below bubble point (saturated oil)
:param p_mpa:
:param pb_mpa:
:param t_k:
:param gamma_oil:
:param rsb_m3m3:
:return:
ref1 https://www.researc... | def unf_compressibility_saturated_oil_McCain_1Mpa(p_MPa=1, pb_MPa=10, t_K=300, gamma_oil=0.86, rsb_m3m3=100):
| """
Oil compressibility below bubble point (saturated oil)
:param p_mpa:
:param pb_mpa:
:param t_k:
:param gamma_oil:
:param rsb_m3m3:
:return:
ref1 https://www.researchgate.net/publication/
254529353_The_Oil_Compressibility_Below_Bubble_Point_Pressure_Revisited_-_Formulati... | нас, уже есть в fvf_oil степень с co
return np.where(p_MPaa > pb_MPaa, po * np.exp(co_1MPa * (p_MPaa - pb_MPaa)), po)
"""
====================================================================================================
Корреляции расчета сжимаемости нефти
===========================================... | 117 | 117 | 390 | 50 | 67 | unifloc/neftpy | neftpy/upvt.py | Python | unf_compressibility_saturated_oil_McCain_1Mpa | unf_compressibility_saturated_oil_McCain_1Mpa | 359 | 383 | 359 | 359 | c4acd63ace75cc13e45450717bbee2d6306ea5ae | bigcode/the-stack | train |
739bb1f117532c767f46cb58 | train | function | def unf_pb_Standing_MPaa(rsb_m3m3=100, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
"""
bubble point pressure calculation according to Standing (1947) correlation
:param rsb_m3m3: solution ration at bubble point, must be given, m3/m3
:param gamma_oil: specific oil density (by water)
:param gamma_ga... | def unf_pb_Standing_MPaa(rsb_m3m3=100, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
| """
bubble point pressure calculation according to Standing (1947) correlation
:param rsb_m3m3: solution ration at bubble point, must be given, m3/m3
:param gamma_oil: specific oil density (by water)
:param gamma_gas: specific gas density (by air)
:param t_K: temperature, K
:return: bub... | functions based on Black Oil PVT model for petroleum engineering calculations
Rinat Khabibullin
revision from 13/05/2022
Unifloc_VBA and unifloc_py refactoring
"""
import numpy as np
import neftpy.uconvert as uc
import scipy.optimize as opt
"""
=====================================================================... | 129 | 129 | 430 | 37 | 91 | unifloc/neftpy | neftpy/upvt.py | Python | unf_pb_Standing_MPaa | unf_pb_Standing_MPaa | 21 | 47 | 21 | 21 | 8f76af8b9c11091f8e5973c759b2f1364135b64b | bigcode/the-stack | train |
a575e5740ebde71d502879a4 | train | function | def unf_density_oil_Standing(p_MPaa=1, pb_MPaa=10, co_1MPa=3e-3, rs_m3m3=10, bo_m3m3=1.1, gamma_gas=0.8, gamma_oil=0.86):
"""
Oil density according Standing correlation.
:param p_MPaa: pressure, MPaa
:param pb_MPaa: bubble point pressure, MPaa
:param co_1MPa: coefficient of isothermal compressi... | def unf_density_oil_Standing(p_MPaa=1, pb_MPaa=10, co_1MPa=3e-3, rs_m3m3=10, bo_m3m3=1.1, gamma_gas=0.8, gamma_oil=0.86):
| """
Oil density according Standing correlation.
:param p_MPaa: pressure, MPaa
:param pb_MPaa: bubble point pressure, MPaa
:param co_1MPa: coefficient of isothermal compressibility, 1/MPa
:param rs_m3m3: solution gas-oil ratio, m3m3
:param bo_m3m3: oil formation volume factor, m3m3
:... | ia)),
ro_or)
ro_or = uc.lbft3_2_kgm3(ro_or)
return ro_or
def unf_density_oil_Standing(p_MPaa=1, pb_MPaa=10, co_1MPa=3e-3, rs_m3m3=10, bo_m3m3=1.1, gamma_gas=0.8, gamma_oil=0.86):
| 92 | 93 | 310 | 64 | 27 | unifloc/neftpy | neftpy/upvt.py | Python | unf_density_oil_Standing | unf_density_oil_Standing | 332 | 351 | 332 | 332 | 97fa165874d3f6bcb07228d3a813a4d69b39126e | bigcode/the-stack | train |
4757e1bed9c368bb82b268b8 | train | function | def unf_undersaturatedoilviscosity_VB_cP(p_MPaa, pb_MPaa, bubblepointviscosity_cP):
"""
Viscosity correlation for pressure above bubble point
:param p_MPaa: pressure, MPaa
:param pb_MPaa: bubble point pressure, MPaa
:param bubblepointviscosity_cP: oil viscosity at bubble point pressure, cP
... | def unf_undersaturatedoilviscosity_VB_cP(p_MPaa, pb_MPaa, bubblepointviscosity_cP):
| """
Viscosity correlation for pressure above bubble point
:param p_MPaa: pressure, MPaa
:param pb_MPaa: bubble point pressure, MPaa
:param bubblepointviscosity_cP: oil viscosity at bubble point pressure, cP
:return: oil viscosity,cP
ref2 Vazquez, M. and Beggs, H.D. 1980. Correlations f... | 5.44 * (rs_scfstb + 150) ** (-0.338)
viscosity_cP = a * deadoilviscosity_cP ** b
return viscosity_cP
def unf_undersaturatedoilviscosity_VB_cP(p_MPaa, pb_MPaa, bubblepointviscosity_cP):
| 74 | 74 | 248 | 29 | 44 | unifloc/neftpy | neftpy/upvt.py | Python | unf_undersaturatedoilviscosity_VB_cP | unf_undersaturatedoilviscosity_VB_cP | 515 | 532 | 515 | 515 | 109057eb2de7557e41afb6b6b6636ef09630b598 | bigcode/the-stack | train |
1f5e49488e20112948aaa92f | train | function | def unf_thermal_conductivity_oil_Cragoe_WmK(gamma_oil, t_C):
"""
Oil thermal conductivity Cragoe correlation for 273 < T < 423 K
:param gamma_oil: specific oil density(by water)
:param t_c: temperature in C
:return: thermal conductivity in SI - wt / m K
ref1 Das D. K., Nerella S., Kulkarni... | def unf_thermal_conductivity_oil_Cragoe_WmK(gamma_oil, t_C):
| """
Oil thermal conductivity Cragoe correlation for 273 < T < 423 K
:param gamma_oil: specific oil density(by water)
:param t_c: temperature in C
:return: thermal conductivity in SI - wt / m K
ref1 Das D. K., Nerella S., Kulkarni D. Thermal properties of petroleum and gas-to-liquid product... | t_F) / gamma_oil ** (0.5))
return uc.btulbmF_2_kJkgK(heat_capacity_oil_btulbmF) * 1000
def unf_thermal_conductivity_oil_Cragoe_WmK(gamma_oil, t_C):
| 64 | 64 | 191 | 23 | 40 | unifloc/neftpy | neftpy/upvt.py | Python | unf_thermal_conductivity_oil_Cragoe_WmK | unf_thermal_conductivity_oil_Cragoe_WmK | 569 | 580 | 569 | 569 | 43d00de0c150d04d9abc3d2a3f0daf9d26ca0250 | bigcode/the-stack | train |
57f4e878ce00532fbca35fa9 | train | function | def unf_bo_saturated_Standing_m3m3(rs_m3m3=100, gamma_gas=0.8, gamma_oil=0.86, t_K=300):
"""
Oil Formation Volume Factor according Standing equation at bubble point pressure
:param rs_m3m3: solution gas-oil ratio, m3m3
:param gamma_gas: specific gas density (by air)
:param gamma_oil: specific o... | def unf_bo_saturated_Standing_m3m3(rs_m3m3=100, gamma_gas=0.8, gamma_oil=0.86, t_K=300):
| """
Oil Formation Volume Factor according Standing equation at bubble point pressure
:param rs_m3m3: solution gas-oil ratio, m3m3
:param gamma_gas: specific gas density (by air)
:param gamma_oil: specific oil density (by water)
:param t_K: temperature, K
:return: formation volume factor... | 3 + 1.22044505587208 * rs_m3m3 * gamma_gas) / rho_oil_insitu_kgm3
return bo
def unf_bo_saturated_Standing_m3m3(rs_m3m3=100, gamma_gas=0.8, gamma_oil=0.86, t_K=300):
| 76 | 76 | 254 | 40 | 35 | unifloc/neftpy | neftpy/upvt.py | Python | unf_bo_saturated_Standing_m3m3 | unf_bo_saturated_Standing_m3m3 | 258 | 274 | 258 | 258 | e346412db39a2bd768ad7a870ea5573b092c382b | bigcode/the-stack | train |
470511746ae553a2293efa31 | train | function | def unf_density_oil_Mccain(p_MPaa=1, pb_MPaa=10, co_1MPa=3e-3, rs_m3m3=10, gamma_gas=0.86, t_K=300, gamma_oil=0.86, gamma_gassp = 0):
"""
Oil density according Standing, M.B., 1977; Witte, T.W., Jr., 1987; and McCain, W.D., Jr. and Hill, N.C.,
1995 correlation.
:param p_MPaa: pressure, MPaa
:pa... | def unf_density_oil_Mccain(p_MPaa=1, pb_MPaa=10, co_1MPa=3e-3, rs_m3m3=10, gamma_gas=0.86, t_K=300, gamma_oil=0.86, gamma_gassp = 0):
| """
Oil density according Standing, M.B., 1977; Witte, T.W., Jr., 1987; and McCain, W.D., Jr. and Hill, N.C.,
1995 correlation.
:param p_MPaa: pressure, MPaa
:param pb_MPaa: bubble point pressure, MPaa
:param co_1MPa: coefficient of isothermal compressibility, 1/MPa
:param rs_m3m3: solu... | density (by air)
:param gamma_oil: specific oil density (by water)
:param t_K: temperature, K
:return: formation volume factor at bubble point pressure bo,m3m3
ref1 Volumetric and phase behavior of oil field hydrocarbon systems / M.B. Standing Standing, M. B. 1981
"""
rs_scfstb = uc.m3m3_2_sc... | 256 | 256 | 865 | 68 | 188 | unifloc/neftpy | neftpy/upvt.py | Python | unf_density_oil_Mccain | unf_density_oil_Mccain | 283 | 328 | 283 | 283 | 3ff2542886196c54ae8eb3499c15e7ea6e081c62 | bigcode/the-stack | train |
7dbde4170a4ee87eb6c79672 | train | function | def unf_bo_above_pb_m3m3(bob_m3m3=1.2, compr_o_1MPa=3e-3, pb_MPaa=10, p_MPaa=1):
"""
Oil Formation Volume Factor according equation for pressure above bubble point pressure
:param bob_m3m3: formation volume factor at bubble point pressure, m3m3
:param compr_o_1MPa: weighted-average oil compressibil... | def unf_bo_above_pb_m3m3(bob_m3m3=1.2, compr_o_1MPa=3e-3, pb_MPaa=10, p_MPaa=1):
| """
Oil Formation Volume Factor according equation for pressure above bubble point pressure
:param bob_m3m3: formation volume factor at bubble point pressure, m3m3
:param compr_o_1MPa: weighted-average oil compressibility from bubblepoint pressure to a higher pressure of interest,1/MPa
:param p... | 0
)
)
return uc.scfstb_2_m3m3(rsb)
"""
====================================================================================================
Корреляции расчета объемного коэффициента нефти (Oil Formation Volume Factor FVF)
============================================... | 93 | 93 | 311 | 45 | 48 | unifloc/neftpy | neftpy/upvt.py | Python | unf_bo_above_pb_m3m3 | unf_bo_above_pb_m3m3 | 220 | 240 | 220 | 220 | cf119b569be67d445626f315df22078e4dd8194b | bigcode/the-stack | train |
289d16bc2a220320f1874f7b | train | function | def unf_rs_Standing_m3m3(p_MPaa=1, pb_MPaa=10, rsb_m3m3=100, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
"""
Gas-oil ratio calculation inverse of Standing (1947) correlation for bubble point pressure
:param p_MPaa: pressure, MPa
:param pb_MPaa: buble point pressure, MPa
:param rsb_m3m3: gas-oil ra... | def unf_rs_Standing_m3m3(p_MPaa=1, pb_MPaa=10, rsb_m3m3=100, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
| """
Gas-oil ratio calculation inverse of Standing (1947) correlation for bubble point pressure
:param p_MPaa: pressure, MPa
:param pb_MPaa: buble point pressure, MPa
:param rsb_m3m3: gas-oil ratio at the bubble point pressure, m3/m3
:param gamma_oil: specific oil density (by water)
:par... |
np.where(rsb_old > max_rsb,
(pb_MPaa - 0.1013) * rsb_old / max_rsb + 0.1013,
pb_MPaa)
)
return pb_MPaa
"""
===========================================================================================... | 135 | 135 | 453 | 51 | 83 | unifloc/neftpy | neftpy/upvt.py | Python | unf_rs_Standing_m3m3 | unf_rs_Standing_m3m3 | 104 | 133 | 104 | 104 | 630600838f22ddc682760b3d2a89dd3b4c00b5db | bigcode/the-stack | train |
e1e5cdaf11624d7a4bde2071 | train | function | def unf_rsb_Mccain_m3m3(rsp_m3m3=10, gamma_oil=0.86, psp_MPaa=0.0, tsp_K=0.0):
"""
Solution Gas-oil ratio at bubble point pressure calculation according to McCain (2002) correlation
taking into account the gas losses at separator and stock tank
:param rsp_m3m3: separator producing gas-oil ratio, m3... | def unf_rsb_Mccain_m3m3(rsp_m3m3=10, gamma_oil=0.86, psp_MPaa=0.0, tsp_K=0.0):
| """
Solution Gas-oil ratio at bubble point pressure calculation according to McCain (2002) correlation
taking into account the gas losses at separator and stock tank
:param rsp_m3m3: separator producing gas-oil ratio, m3m3
:param gamma_oil: specific oil density(by water)
:param psp_MPaa: pr... | 213 * _pb_ ** 0.047094 / ( gamma_gas**1.48548 * _go_**0.164741 * _t_**0.09133)
rs_m3m3 = np.where(pr <= 0,
0.0,
np.where( pr < 1,
(a1 * pr ** a2 + (1 - a1) * pr ** a3) * rsb_m3m3,
rsb_m3m3
... | 166 | 166 | 556 | 44 | 121 | unifloc/neftpy | neftpy/upvt.py | Python | unf_rsb_Mccain_m3m3 | unf_rsb_Mccain_m3m3 | 174 | 212 | 174 | 174 | ac45e0ce1d39a56c159601d428320a461e5c8eb1 | bigcode/the-stack | train |
3fa6bff36d069754a68c0df6 | train | function | def unf_heat_capacity_oil_Gambill_JkgC(gamma_oil, t_C):
"""
Oil heat capacity in SI. Gambill correlation
:param gamma_oil: specific oil density(by water)
:param t_c: temperature in C
:return: heat capacity in SI - JkgC
ref1 Book: Brill J. P., Mukherjee H. K. Multiphase flow in wells. –
... | def unf_heat_capacity_oil_Gambill_JkgC(gamma_oil, t_C):
| """
Oil heat capacity in SI. Gambill correlation
:param gamma_oil: specific oil density(by water)
:param t_c: temperature in C
:return: heat capacity in SI - JkgC
ref1 Book: Brill J. P., Mukherjee H. K. Multiphase flow in wells. –
Society of Petroleum Engineers, 1999. – Т. 17. in Page ... | <= pb_MPaa,
saturatedviscosity_cP,
unf_undersaturatedoilviscosity_VB_cP(p_MPaa, pb_MPaa, saturatedviscosity_cP)
)
def unf_heat_capacity_oil_Gambill_JkgC(gamma_oil, t_C):
| 64 | 64 | 192 | 20 | 44 | unifloc/neftpy | neftpy/upvt.py | Python | unf_heat_capacity_oil_Gambill_JkgC | unf_heat_capacity_oil_Gambill_JkgC | 552 | 566 | 552 | 552 | da92ec0810899569423323e4021e6214cadf4943 | bigcode/the-stack | train |
766f9cdf9a543de19863e713 | train | function | def unf_saturatedoilviscosity_Beggs_cP(deadoilviscosity_cP, rs_m3m3):
"""
Correlation for oil viscosity for pressure below bubble point (for pb!!!)
:param deadoilviscosity_cP: dead oil viscosity,cP
:param rs_m3m3: solution gas-oil ratio, m3m3
:return: oil viscosity,cP
ref1 Beggs, H.D. and ... | def unf_saturatedoilviscosity_Beggs_cP(deadoilviscosity_cP, rs_m3m3):
| """
Correlation for oil viscosity for pressure below bubble point (for pb!!!)
:param deadoilviscosity_cP: dead oil viscosity,cP
:param rs_m3m3: solution gas-oil ratio, m3m3
:return: oil viscosity,cP
ref1 Beggs, H.D. and Robinson, J.R. “Estimating the Viscosity of Crude Oil Systems.”
Jo... | (t_K)
c = 10 ** (3.0324 - 0.02023 * api) * t_F ** (-1.163)
return 10 ** c - 1
def unf_saturatedoilviscosity_Beggs_cP(deadoilviscosity_cP, rs_m3m3):
| 71 | 71 | 238 | 28 | 42 | unifloc/neftpy | neftpy/upvt.py | Python | unf_saturatedoilviscosity_Beggs_cP | unf_saturatedoilviscosity_Beggs_cP | 496 | 512 | 496 | 496 | 5380e1d0d5ebe3c4ff034c89236ca8dc5a8221d8 | bigcode/the-stack | train |
a2c89bff420be232b8cebbce | train | function | def unf_deadoilviscosity_Beggs_cP(gamma_oil, t_K):
"""
Correlation for dead oil viscosity
:param gamma_oil: specific oil density (by water)
:param t_K: temperature, K
:return: dead oil viscosity,cP
ref1 Beggs, H.D. and Robinson, J.R. “Estimating the Viscosity of Crude Oil Systems.”
Jou... | def unf_deadoilviscosity_Beggs_cP(gamma_oil, t_K):
| """
Correlation for dead oil viscosity
:param gamma_oil: specific oil density (by water)
:param t_K: temperature, K
:return: dead oil viscosity,cP
ref1 Beggs, H.D. and Robinson, J.R. “Estimating the Viscosity of Crude Oil Systems.”
Journal of Petroleum Technology. Vol. 27, No. 9 (1975)... | assp >= 0,
1.066 * gamma_gassp,
0
)
)
"""
====================================================================================================
Корреляции расчета вязкости нефти
====================================... | 64 | 64 | 181 | 21 | 43 | unifloc/neftpy | neftpy/upvt.py | Python | unf_deadoilviscosity_Beggs_cP | unf_deadoilviscosity_Beggs_cP | 479 | 494 | 479 | 479 | 6fb2fad855d35406b895c3f76cb160ee9dfddc49 | bigcode/the-stack | train |
96afe2e0187caa4d432f401c | train | function | def unf_gamma_gas_Mccain(rsp_m3m3, rst_m3m3, gamma_gassp=0.8, gamma_oil=0.86, psp_MPaa=0, tsp_K=0):
"""
Correlation for weighted-average specific gravities of surface gases
:param rsp_m3m3: separator producing gas-oil ratio, m3m3
:param rst_m3m3: stock-tank producing gas-oil ratio, m3m3
:param ... | def unf_gamma_gas_Mccain(rsp_m3m3, rst_m3m3, gamma_gassp=0.8, gamma_oil=0.86, psp_MPaa=0, tsp_K=0):
| """
Correlation for weighted-average specific gravities of surface gases
:param rsp_m3m3: separator producing gas-oil ratio, m3m3
:param rst_m3m3: stock-tank producing gas-oil ratio, m3m3
:param gamma_gassp: separator gas specific gravity
:param gamma_oil: specific oil density(by water)
... | _2_1MPa( (-1433 + 5 * rs_scfstb + 17.2 * t_F - 1180 * gamma_gas + 12.61 * api) / (1e5 * p_psia)),
0.0
)
def unf_compessibility_oil_VB_1MPa_vba(rsb_m3m3, t_k, gamma_oil, gamma_gas):
co_1atm = (28.1 * rsb_m3m3 + 30.6 * t_k - 1180 * gamma_gas + 1784 / gamma_oil - 10910)
ret... | 256 | 256 | 899 | 50 | 206 | unifloc/neftpy | neftpy/upvt.py | Python | unf_gamma_gas_Mccain | unf_gamma_gas_Mccain | 421 | 469 | 421 | 421 | df80dd12496bf0e1e2d86f5ea2e389e6b853c16c | bigcode/the-stack | train |
88a8416f019f4d29ed397ece | train | function | def multi_bracket_validation(str):
open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue o... | def multi_bracket_validation(str):
| open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue or i != queue.pop():
return... | def multi_bracket_validation(str):
| 8 | 64 | 106 | 8 | 0 | doaa-1996/Data-structures-and-algorithms1 | challenges/multi_bracket_validation/multi_bracket_validation/multi_bracket_validation.py | Python | multi_bracket_validation | multi_bracket_validation | 1 | 17 | 1 | 2 | 4031aaf33615d1759741d8f76f4d8943d478266e | bigcode/the-stack | train |
7dc035b3294461d3ee0de1d0 | train | function | def weightOfEvidence(origProb, margProb):
return math.log2(odds(origProb)) - math.log2(odds(margProb))
| def weightOfEvidence(origProb, margProb):
| return math.log2(odds(origProb)) - math.log2(odds(margProb))
| variance.npy'
fnTranslationInvarianceTexts = '../data/translationInvarianceTexts.pickle'
gtText = 'are'
distribution = 'histogram' # 'histogram' or 'uniform'
def odds(val):
return val / (1 - val)
def weightOfEvidence(origProb, margProb):
| 64 | 64 | 31 | 10 | 54 | quocpp/RTH | src/analyze.py | Python | weightOfEvidence | weightOfEvidence | 32 | 33 | 32 | 32 | 031eb8b48a3a124337a457d041e12cb88b7316fb | bigcode/the-stack | train |
1b19067d243ba568e905afe9 | train | function | def analyzePixelRelevance():
"simplified implementation of paper: Zintgraf et al - Visualizing Deep Neural Network Decisions: Prediction Difference Analysis"
# setup model
model = Model(open(Constants.fnCharList).read(), DecoderType.BestPath, mustRestore=True)
# read image and specify ground-truth text
img = c... | def analyzePixelRelevance():
| "simplified implementation of paper: Zintgraf et al - Visualizing Deep Neural Network Decisions: Prediction Difference Analysis"
# setup model
model = Model(open(Constants.fnCharList).read(), DecoderType.BestPath, mustRestore=True)
# read image and specify ground-truth text
img = cv2.imread(Constants.fnAnalyze... |
from SamplePreprocessor import preprocess
# constants like filepaths
class Constants:
"filenames and paths to data"
fnCharList = '../model/charList.txt'
fnAnalyze = '../data/analyze.png'
fnPixelRelevance = '../data/pixelRelevance.npy'
fnTranslationInvariance = '../data/translationInvariance.npy'
fnTranslationI... | 160 | 161 | 539 | 6 | 154 | quocpp/RTH | src/analyze.py | Python | analyzePixelRelevance | analyzePixelRelevance | 36 | 87 | 36 | 36 | ede2b996abd0d770334fae007ca2be1677e59d62 | bigcode/the-stack | train |
446fa0c3a4fa0ab990a918f2 | train | function | def odds(val):
return val / (1 - val)
| def odds(val):
| return val / (1 - val)
| '../data/pixelRelevance.npy'
fnTranslationInvariance = '../data/translationInvariance.npy'
fnTranslationInvarianceTexts = '../data/translationInvarianceTexts.pickle'
gtText = 'are'
distribution = 'histogram' # 'histogram' or 'uniform'
def odds(val):
| 64 | 64 | 12 | 4 | 60 | quocpp/RTH | src/analyze.py | Python | odds | odds | 28 | 29 | 28 | 28 | 473567a3df85db96f87f3a247991b810751c9bc0 | bigcode/the-stack | train |
7ed97240bf9525315fcffa2c | train | function | def analyzeTranslationInvariance():
# setup model
model = Model(open(Constants.fnCharList).read(), DecoderType.BestPath, mustRestore=True)
# read image and specify ground-truth text
img = cv2.imread(Constants.fnAnalyze, cv2.IMREAD_GRAYSCALE)
img1 = preprocess(cv2.imread(Constants.fnAnalyze, cv2.IMREAD_GRAYSCALE)... | def analyzeTranslationInvariance():
# setup model
| model = Model(open(Constants.fnCharList).read(), DecoderType.BestPath, mustRestore=True)
# read image and specify ground-truth text
img = cv2.imread(Constants.fnAnalyze, cv2.IMREAD_GRAYSCALE)
img1 = preprocess(cv2.imread(Constants.fnAnalyze, cv2.IMREAD_GRAYSCALE), Model.imgSize)
(w, h) = img.shape
#assert Mod... | ] * pixelProb[i] for i in range(len(grayValues))])
pixelRelevance[x, y] = weightOfEvidence(origProb, margProb)
print(x, y, pixelRelevance[x, y], origProb, margProb)
np.save(Constants.fnPixelRelevance, pixelRelevance)
def analyzeTranslationInvariance():
# setup model
| 80 | 80 | 269 | 11 | 69 | quocpp/RTH | src/analyze.py | Python | analyzeTranslationInvariance | analyzeTranslationInvariance | 90 | 117 | 90 | 91 | bc9d25a1c3bff25761d028bfd4b59d20c8deb586 | bigcode/the-stack | train |
9c2189a162fb0c99b7773ccd | train | function | def showResults():
# 1. pixel relevance
pixelRelevance = np.load(Constants.fnPixelRelevance)
plt.figure('Pixel relevance')
plt.imshow(pixelRelevance, cmap=plt.cm.jet, vmin=-0.25, vmax=0.25)
plt.colorbar()
img = cv2.imread(Constants.fnAnalyze, cv2.IMREAD_GRAYSCALE)
plt.imshow(img, cmap=plt.cm.gray, alpha=.4)
... | def showResults():
# 1. pixel relevance
| pixelRelevance = np.load(Constants.fnPixelRelevance)
plt.figure('Pixel relevance')
plt.imshow(pixelRelevance, cmap=plt.cm.jet, vmin=-0.25, vmax=0.25)
plt.colorbar()
img = cv2.imread(Constants.fnAnalyze, cv2.IMREAD_GRAYSCALE)
plt.imshow(img, cmap=plt.cm.gray, alpha=.4)
# 2. translation invariance
probs = ... | Batch(batch, calcProbability=True, probabilityOfGT=True)
# save results to file
f = open(Constants.fnTranslationInvarianceTexts, 'wb')
pickle.dump(texts, f)
f.close()
np.save(Constants.fnTranslationInvariance, probs)
def showResults():
# 1. pixel relevance
| 67 | 67 | 224 | 12 | 55 | quocpp/RTH | src/analyze.py | Python | showResults | showResults | 120 | 147 | 120 | 121 | 55d0ed4c0a68bb99bc966dde1993feeae322ae4b | bigcode/the-stack | train |
f3e5c36e19da99f0807ca08d | train | class | class Constants:
"filenames and paths to data"
fnCharList = '../model/charList.txt'
fnAnalyze = '../data/analyze.png'
fnPixelRelevance = '../data/pixelRelevance.npy'
fnTranslationInvariance = '../data/translationInvariance.npy'
fnTranslationInvarianceTexts = '../data/translationInvarianceTexts.pickle'
gtText = '... | class Constants:
| "filenames and paths to data"
fnCharList = '../model/charList.txt'
fnAnalyze = '../data/analyze.png'
fnPixelRelevance = '../data/pixelRelevance.npy'
fnTranslationInvariance = '../data/translationInvariance.npy'
fnTranslationInvarianceTexts = '../data/translationInvarianceTexts.pickle'
gtText = 'are'
distributio... | __future__ import print_function
import sys
import math
import pickle
import copy
import numpy as np
import cv2
import matplotlib.pyplot as plt
from DataLoader import Batch
from Model import Model, DecoderType
from SamplePreprocessor import preprocess
# constants like filepaths
class Constants:
| 64 | 64 | 97 | 3 | 60 | quocpp/RTH | src/analyze.py | Python | Constants | Constants | 17 | 25 | 17 | 17 | abcc7f44f3a187bb55768ddbcd8184f2662de774 | bigcode/the-stack | train |
23514ccb73ef2aee9e1cc76b | train | function | def sentence_segmentation(transcript: List[EditToken]) -> List[List[EditToken]]:
"""Segments a transcript into sentences
Args:
transcript (List[EditToken]): Transcript to segment
Returns:
List[List[EditToken]]: Segmented transcript. Each list of tokens is a separate sentence
"""
# 0. Add a separ... | def sentence_segmentation(transcript: List[EditToken]) -> List[List[EditToken]]:
| """Segments a transcript into sentences
Args:
transcript (List[EditToken]): Transcript to segment
Returns:
List[List[EditToken]]: Segmented transcript. Each list of tokens is a separate sentence
"""
# 0. Add a separator between tokens
transcript[0].start_pos = 0
for token, next_token in zip(... | :
return TimelineChange(self.start_time, self.end_time, duration_ratio)
def __len__(self) -> int:
return len(self.text)
def spacy_nlp(text: str, pipes: List[str]) -> spacy.tokens.Doc:
"""Runs spaCy on a provided text. This function uses a static instance of spaCy language, so it is
initialized only onc... | 235 | 235 | 785 | 19 | 216 | Exepp/SpeechLess | src/speechless/processing/tokenization.py | Python | sentence_segmentation | sentence_segmentation | 77 | 157 | 77 | 77 | db773bd7aa8463911ca5f6ae0c5161b385d85004 | bigcode/the-stack | train |
9527bd41dccdae016e198a95 | train | class | class EditToken:
TEXT_SUB_PATTERNS = re.compile(r'(\[[^\]]*\])|' # text in []
r'(\([^\)]*\))') # text in ()
WHITESPACE_SUB_PATTERNS = re.compile(r'(^\s+)|' # whitespaces at the beginning
r'(\s+$)|' # whitespaces at the end
... | class EditToken:
| TEXT_SUB_PATTERNS = re.compile(r'(\[[^\]]*\])|' # text in []
r'(\([^\)]*\))') # text in ()
WHITESPACE_SUB_PATTERNS = re.compile(r'(^\s+)|' # whitespaces at the beginning
r'(\s+$)|' # whitespaces at the end
... |
import re
import spacy
from typing import List
from math import inf
from speechless.edit_context import TimelineChange
from speechless.utils.math import ranges_of_truth
TOKEN_SEPARATOR = ' '
SENTENCE_SEPARATOR = '.' + TOKEN_SEPARATOR
SENTENCE_SEPARATOR_VALID_SET = {SENTENCE_SEPARATOR, '?' + TOKEN_SEPARATOR, '!' + T... | 129 | 129 | 432 | 4 | 125 | Exepp/SpeechLess | src/speechless/processing/tokenization.py | Python | EditToken | EditToken | 21 | 56 | 21 | 21 | 65f8a4a5739e7f161de85077b6d0ac5c8203d091 | bigcode/the-stack | train |
f62bcd49476e0029435a184a | train | function | def make_timeline_changes(tokens: List[EditToken],
duration_ratio: float = 0.0) -> List[TimelineChange]:
"""Create list of timeline changes ready for modification
Args:
tokens (List[EditToken]): List of labeled tokens
duration_ratio (float): Duration ratio for the timeline cha... | def make_timeline_changes(tokens: List[EditToken],
duration_ratio: float = 0.0) -> List[TimelineChange]:
| """Create list of timeline changes ready for modification
Args:
tokens (List[EditToken]): List of labeled tokens
duration_ratio (float): Duration ratio for the timeline changes
Returns:
List[TimelineChanges]: List of changes, with intervals between words
and before first and after last w... | positions of tokens
tokens = [token for sentence in sentences for token in sentence]
for token, next_token in zip(tokens[:-1], tokens[1:]):
next_token.start_pos = token.start_pos + len(token)
return sentences
def make_timeline_changes(tokens: List[EditToken],
duration_ratio: float ... | 81 | 81 | 270 | 29 | 51 | Exepp/SpeechLess | src/speechless/processing/tokenization.py | Python | make_timeline_changes | make_timeline_changes | 160 | 184 | 160 | 161 | d7605bc50d20a0731efff168bd72b0bb91dce046 | bigcode/the-stack | train |
b42e7b44c5c3c38c09c86bcb | train | function | def spacy_nlp(text: str, pipes: List[str]) -> spacy.tokens.Doc:
"""Runs spaCy on a provided text. This function uses a static instance of spaCy language, so it is
initialized only once.
Args:
text (str): Text to process
pipes (List[str]): Which spaCy's pipes to use
Returns:
spacy.tokens.Doc:... | def spacy_nlp(text: str, pipes: List[str]) -> spacy.tokens.Doc:
| """Runs spaCy on a provided text. This function uses a static instance of spaCy language, so it is
initialized only once.
Args:
text (str): Text to process
pipes (List[str]): Which spaCy's pipes to use
Returns:
spacy.tokens.Doc: spaCy document generated from the text
"""
if not hasattr(s... | imeline_change(self, duration_ratio: float) -> TimelineChange:
return TimelineChange(self.start_time, self.end_time, duration_ratio)
def __len__(self) -> int:
return len(self.text)
def spacy_nlp(text: str, pipes: List[str]) -> spacy.tokens.Doc:
| 64 | 64 | 184 | 20 | 44 | Exepp/SpeechLess | src/speechless/processing/tokenization.py | Python | spacy_nlp | spacy_nlp | 59 | 74 | 59 | 59 | 99ef089486443b73ca707cf989a0b26112ad3e2b | bigcode/the-stack | train |
2aa6f7f09b42b67a3231bc97 | train | function | @jit.unroll_safe
def prepare_args(space, rawfunctype, args_w, start_index):
# replaces struct/union arguments with ptr-to-struct/union arguments
locs = rawfunctype.nostruct_locs
fargs = rawfunctype.nostruct_ctype.fargs
for i in range(start_index, len(locs)):
if locs[i] != 'A':
contin... | @jit.unroll_safe
def prepare_args(space, rawfunctype, args_w, start_index):
# replaces struct/union arguments with ptr-to-struct/union arguments
| locs = rawfunctype.nostruct_locs
fargs = rawfunctype.nostruct_ctype.fargs
for i in range(start_index, len(locs)):
if locs[i] != 'A':
continue
w_arg = args_w[i]
farg = fargs[i] # <ptr to struct/union>
assert isinstance(farg, W_CTypePtrOrArray)
if isins... | , self.modulename)
return space.wrap(doc)
def descr_get(self, space, w_obj, w_type=None):
# never bind anything, but a __get__ is still present so that
# pydoc displays useful information (namely, the __repr__)
return self
@jit.unroll_safe
def prepare_args(space, rawfunctype, args_w... | 101 | 101 | 337 | 37 | 63 | microvm/pypy-mu | pypy/module/_cffi_backend/wrapper.py | Python | prepare_args | prepare_args | 109 | 134 | 109 | 111 | 5cebbaeb775cf28d47056ddb0a53ec8ba465c701 | bigcode/the-stack | train |
7e011267a1047f18fa82167a | train | class | class W_FunctionWrapper(W_Root):
"""A wrapper around a real W_CData which points to a function
generated in the C code. The real W_CData has got no struct/union
argument (only pointers to it), and no struct/union return type
(it is replaced by a hidden pointer as first argument). This
wrapper is c... | class W_FunctionWrapper(W_Root):
| """A wrapper around a real W_CData which points to a function
generated in the C code. The real W_CData has got no struct/union
argument (only pointers to it), and no struct/union return type
(it is replaced by a hidden pointer as first argument). This
wrapper is callable, and the arguments it exp... | from pypy.interpreter.error import oefmt
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.typedef import TypeDef, interp_attrproperty
from pypy.interpreter.typedef import GetSetProperty
from pypy.interpreter.gateway import interp2app
from rpython.rlib import jit
from pypy.module._cffi_backend.cda... | 180 | 256 | 939 | 8 | 171 | microvm/pypy-mu | pypy/module/_cffi_backend/wrapper.py | Python | W_FunctionWrapper | W_FunctionWrapper | 16 | 106 | 16 | 16 | 9b8ae8a80f571ff013cc0194b43dcbb0f489fabd | bigcode/the-stack | train |
8ffa2ad3f62f390247d096f0 | train | function | def main(use_ilqr):
"""
Arguments:
use_ilqr:
True iLQR control
False PID control
"""
np.random.rand(0)
dt = 0.02
dynamics = PendulumDynamics()
cost = PendulumCost()
T = 40 # MPC Horizon
control_T = 10 # Plan update interval for receding horizon
iter_ma... | def main(use_ilqr):
| """
Arguments:
use_ilqr:
True iLQR control
False PID control
"""
np.random.rand(0)
dt = 0.02
dynamics = PendulumDynamics()
cost = PendulumCost()
T = 40 # MPC Horizon
control_T = 10 # Plan update interval for receding horizon
iter_max = 20
num_steps... | Writer
from pendulum import PendulumDynamics, PendulumCost, PendulumRenderer
class PendulumObservation(object):
def __init__(self):
# Jacobian calculation with automatic differentiation
self.x = jacobian(self.value, 0)
def value(self, x):
return x
class PendulumEnvRecorder(... | 255 | 256 | 935 | 6 | 248 | shigeyukioba/matchernet | demo/pendulum_control/main_parallel.py | Python | main | main | 46 | 140 | 46 | 46 | b7d4d8a09b4a06d7aecbb2fe401c8f5c01cc1d50 | bigcode/the-stack | train |
5fdf20e217c99930f226216f | train | class | class PendulumEnvRecorder(object):
def __init__(self, recording_frame_size):
self.recording_frame_size = recording_frame_size
self.current_frame = 0
def record(self, x, u):
if self.current_frame == 0:
self.renderer = PendulumRenderer(image_width=256)
self... | class PendulumEnvRecorder(object):
| def __init__(self, recording_frame_size):
self.recording_frame_size = recording_frame_size
self.current_frame = 0
def record(self, x, u):
if self.current_frame == 0:
self.renderer = PendulumRenderer(image_width=256)
self.movie = MovieWriter("out.mov", (25... | ulumDynamics, PendulumCost, PendulumRenderer
class PendulumObservation(object):
def __init__(self):
# Jacobian calculation with automatic differentiation
self.x = jacobian(self.value, 0)
def value(self, x):
return x
class PendulumEnvRecorder(object):
| 64 | 64 | 185 | 7 | 56 | shigeyukioba/matchernet | demo/pendulum_control/main_parallel.py | Python | PendulumEnvRecorder | PendulumEnvRecorder | 24 | 43 | 24 | 24 | 821dd933f18e59217601766307e85f5affe5a69d | bigcode/the-stack | train |
cbef9e054cbfd5f941964092 | train | class | class PendulumObservation(object):
def __init__(self):
# Jacobian calculation with automatic differentiation
self.x = jacobian(self.value, 0)
def value(self, x):
return x
| class PendulumObservation(object):
| def __init__(self):
# Jacobian calculation with automatic differentiation
self.x = jacobian(self.value, 0)
def value(self, x):
return x
| from matchernet import MPCEnvBundle, MatcherController, MatcherILQR, BundlePlan, BundleFixedPlan, BundleEKFWithController, MatcherEKF, MPCEnv, MovieWriter, AnimGIFWriter
from pendulum import PendulumDynamics, PendulumCost, PendulumRenderer
class PendulumObservation(object):
| 64 | 64 | 46 | 6 | 57 | shigeyukioba/matchernet | demo/pendulum_control/main_parallel.py | Python | PendulumObservation | PendulumObservation | 15 | 21 | 15 | 15 | c8b84d1a59bfd5187f9d42cf984b7a0e06ce4854 | bigcode/the-stack | train |
cec4d96a068530f6b6dfefae | train | class | class DatabaseClient(BaseDatabaseClient):
executable_name = 'impala-shell'
def runshell(self):
settings_dict = self.connection.settings_dict
args = [self.executable_name]
db = settings_dict['OPTIONS'].get('db', settings_dict['NAME'])
user = settings_dict['OPTIONS'].get('user', s... | class DatabaseClient(BaseDatabaseClient):
| executable_name = 'impala-shell'
def runshell(self):
settings_dict = self.connection.settings_dict
args = [self.executable_name]
db = settings_dict['OPTIONS'].get('db', settings_dict['NAME'])
user = settings_dict['OPTIONS'].get('user', settings_dict['USER'])
passwd = set... | import os
import sys
from django.db.backends.base.client import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
| 24 | 69 | 231 | 7 | 16 | drinksober/django-impala-backend | django_impala_backend/client.py | Python | DatabaseClient | DatabaseClient | 7 | 33 | 7 | 7 | 1d7ca30100295dc058172a2b13887da251744782 | bigcode/the-stack | train |
eb50d36e103df0631c8fabdf | train | function | @pytest.mark.parametrize(
"landpoints,bbox,n_files_should",
# 15 cells, 4 with out landpoints, 1 grid file
[(True, True, 15-4+1), (False, True, 15+1)],
)
def test_reshuffle(landpoints, bbox, n_files_should):
if bbox is True:
bbox = ["41.125", "11.125", "63.875", "23.875"]
inpath = os... | @pytest.mark.parametrize(
"landpoints,bbox,n_files_should",
# 15 cells, 4 with out landpoints, 1 grid file
[(True, True, 15-4+1), (False, True, 15+1)],
)
def test_reshuffle(landpoints, bbox, n_files_should):
| if bbox is True:
bbox = ["41.125", "11.125", "63.875", "23.875"]
inpath = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"test-data",
"img2ts_test",
"netcdf",
)
startdate = "2016-01-01T03:00"
enddate = "2016-01-01T21:00"
parameters = [... | import os
import glob
import tempfile
import numpy as np
import numpy.testing as nptest
from gldas.reshuffle import main
from gldas.interface import GLDASTs
from tempfile import TemporaryDirectory
import pytest
@pytest.mark.parametrize(
"landpoints,bbox,n_files_should",
# 15 cells, 4 with out la... | 123 | 160 | 536 | 72 | 50 | wpreimes/gldas | tests/test_reshuffle.py | Python | test_reshuffle | test_reshuffle | 15 | 63 | 15 | 20 | 184260aa0fa6f5f3238f90264bffb2291ca37e9a | bigcode/the-stack | train |
0fd4028a62ef533a063cc531 | train | class | class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None: return True
return self.dfs(root.left, root.right)
def dfs(self, t1, t2):
if t1 == None and t2 == None:
return True
if t1 == None or t2 == None:
return False
if t1.val != t2.val:
return False
r... | class Solution:
| def isSymmetric(self, root: TreeNode) -> bool:
if root == None: return True
return self.dfs(root.left, root.right)
def dfs(self, t1, t2):
if t1 == None and t2 == None:
return True
if t1 == None or t2 == None:
return False
if t1.val != t2.val:
return False
return self.dfs(t... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
| 47 | 64 | 120 | 3 | 43 | MDGSF/interviews | python-leetcode/sw_28.py | Python | Solution | Solution | 8 | 20 | 8 | 8 | 429bc54da36ba50fc143d334bfe0eeac153d3eaf | bigcode/the-stack | train |
2219a1952df0a572bff2c19d | train | class | class ExecutableEndEvent(Element):
def __init__(self, type, **kwargs):
self._type = type
super(ExecutableEndEvent, self).__init__(**kwargs)
def type(self):
return self._type
| class ExecutableEndEvent(Element):
| def __init__(self, type, **kwargs):
self._type = type
super(ExecutableEndEvent, self).__init__(**kwargs)
def type(self):
return self._type
|
__all__ = ["EmptyEndEvent", "EmptyStartEvent", "ExecutableEndEvent"]
class EmptyStartEvent(Element):
def type(self):
return PE.EmptyStartEvent
class EmptyEndEvent(Element):
def type(self):
return PE.EmptyEndEvent
class ExecutableEndEvent(Element):
| 64 | 64 | 51 | 7 | 56 | ZhuoZhuoCrayon/bk-nodeman | pipeline/builder/flow/event.py | Python | ExecutableEndEvent | ExecutableEndEvent | 29 | 35 | 29 | 29 | bd17f5abb9a3702b9d07c72089c054d96568ff26 | bigcode/the-stack | train |
bd3947273e55851c8b7cd802 | train | class | class EmptyEndEvent(Element):
def type(self):
return PE.EmptyEndEvent
| class EmptyEndEvent(Element):
| def type(self):
return PE.EmptyEndEvent
| governing permissions and limitations under the License.
"""
from pipeline.builder.flow.base import * # noqa
__all__ = ["EmptyEndEvent", "EmptyStartEvent", "ExecutableEndEvent"]
class EmptyStartEvent(Element):
def type(self):
return PE.EmptyStartEvent
class EmptyEndEvent(Element):
| 64 | 64 | 18 | 6 | 57 | ZhuoZhuoCrayon/bk-nodeman | pipeline/builder/flow/event.py | Python | EmptyEndEvent | EmptyEndEvent | 24 | 26 | 24 | 24 | ea4a086988d760509ef54c98a5cdd8262c80fd2d | bigcode/the-stack | train |
a486f6a00841732d654c1839 | train | class | class EmptyStartEvent(Element):
def type(self):
return PE.EmptyStartEvent
| class EmptyStartEvent(Element):
| def type(self):
return PE.EmptyStartEvent
| CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from pipeline.builder.flow.base import * # noqa
__all__ = ["EmptyEndEvent", "EmptyStartEvent", "ExecutableEndEvent"]
class EmptyStartEvent(Element):
| 63 | 64 | 18 | 6 | 57 | ZhuoZhuoCrayon/bk-nodeman | pipeline/builder/flow/event.py | Python | EmptyStartEvent | EmptyStartEvent | 19 | 21 | 19 | 19 | 01f12443eebe3c668591e0333725afaa0541c4b4 | bigcode/the-stack | train |
f9443d42f05d3ffbc5d8e523 | train | function | def nop(it, *a, **k):
print("[progress bar disabled]")
return it
| def nop(it, *a, **k):
| print("[progress bar disabled]")
return it
| ``Beginning script execution...", end=" ")
# Ignore numpy version warning
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="Using a non-tuple sequence")
# Disable progress bar output
import tqdm
def nop(it, *a, **k):
| 64 | 64 | 21 | 10 | 53 | yosefmiller/lightkurve-website | python/master.py | Python | nop | nop | 12 | 14 | 12 | 12 | 5bf91e3617c718b52b5887719f64ec3307e0bab5 | bigcode/the-stack | train |
d375a18c11fcf6f299c5d2df | train | class | class Attention(Layer):
def __init__(self, attention_size, **kwargs):
self.attention_size = attention_size
super(Attention, self).__init__(**kwargs)
def build(self, input_shape):
# W: (EMBED_SIZE, ATTENTION_SIZE)
# b: (ATTENTION_SIZE, 1)
# u: (ATTENTION_SIZE, 1)
... | class Attention(Layer):
| def __init__(self, attention_size, **kwargs):
self.attention_size = attention_size
super(Attention, self).__init__(**kwargs)
def build(self, input_shape):
# W: (EMBED_SIZE, ATTENTION_SIZE)
# b: (ATTENTION_SIZE, 1)
# u: (ATTENTION_SIZE, 1)
self.W = self.add_weight... | bc = BertClient()
# 定义随机矩阵
embedding_matrix = np.random.uniform(size=(vocab_size + 1, 768))
print("构建embedding_matrix...")
for word, index in small_word_index.items():
try:
word_vector = bc.encode([word])
embedding_matrix[index] = word_vector
# print("Word: [", index, "]")
except:
... | 132 | 132 | 440 | 5 | 126 | Yeolnim/CCL2020 | model/bert_han.py | Python | Attention | Attention | 66 | 108 | 66 | 66 | 6e70b287960cc269122e6e041d474f4b4ba44acf | bigcode/the-stack | train |
d01e01bbef8b1db9b36aa6bd | train | class | @pytest.mark.noparallel(reason='uses daemon, failing in parallel to other tests, updates account')
class TestAbacusRSE(unittest.TestCase):
account = 'root'
scope = 'mock'
rse = 'MOCK4'
file_sizes = 2
vo = {}
@classmethod
def setUpClass(cls):
cls.upload_client = UploadClient()
... | @pytest.mark.noparallel(reason='uses daemon, failing in parallel to other tests, updates account')
class TestAbacusRSE(unittest.TestCase):
| account = 'root'
scope = 'mock'
rse = 'MOCK4'
file_sizes = 2
vo = {}
@classmethod
def setUpClass(cls):
cls.upload_client = UploadClient()
cls.session = get_session()
if config_get_bool('common', 'multi_vo', raise_exception=False, default=False):
cls.vo =... | - Benedikt Ziemons <benedikt.ziemons@cern.ch>, 2020-2021
# - Simon Fayer <simon.fayer05@imperial.ac.uk>, 2021
import os
import unittest
import pytest
from rucio.client.uploadclient import UploadClient
from rucio.common.config import config_get_bool
from rucio.common.utils import generate_uuid
from rucio.core.rse im... | 228 | 228 | 760 | 31 | 196 | rcarpa/rucio | lib/rucio/tests/test_abacus_rse.py | Python | TestAbacusRSE | TestAbacusRSE | 44 | 104 | 44 | 45 | 1dff1007471d5ab45694bb28979f057af5c2cee1 | bigcode/the-stack | train |
7bd922ade387e6f8af776313 | train | class | class wavesexchange(Exchange):
def describe(self):
return self.deep_extend(super(wavesexchange, self).describe(), {
'id': 'wavesexchange',
'name': 'Waves.Exchange',
'countries': ['CH'], # Switzerland
'rateLimit': 500,
'certified': True,
... | class wavesexchange(Exchange):
| def describe(self):
return self.deep_extend(super(wavesexchange, self).describe(), {
'id': 'wavesexchange',
'name': 'Waves.Exchange',
'countries': ['CH'], # Switzerland
'rateLimit': 500,
'certified': True,
'pro': False,
'ha... | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import A... | 186 | 256 | 20,068 | 6 | 179 | AidanSSS/ccxt | python/ccxt/async_support/wavesexchange.py | Python | wavesexchange | wavesexchange | 22 | 1,796 | 22 | 23 | a632d2fcd92b5f2213f385105de01f170a02fa31 | bigcode/the-stack | train |
8d22158135c9c1fe543b0496 | train | function | def get_data(file):
f=codecs.open(file, 'rb')
soup= BeautifulSoup(f.read(), 'lxml')
#find social media links
for a in soup.find_all('a', href=True):
if re.search('t.me',a['href']):
print(a['href'])
elif re.search('facebook.com/',a['href']):
print(a['href'])
elif re.search('twitter.com/', a['href']):
... | def get_data(file):
| f=codecs.open(file, 'rb')
soup= BeautifulSoup(f.read(), 'lxml')
#find social media links
for a in soup.find_all('a', href=True):
if re.search('t.me',a['href']):
print(a['href'])
elif re.search('facebook.com/',a['href']):
print(a['href'])
elif re.search('twitter.com/', a['href']):
print(a['href'])
... | from bs4 import BeautifulSoup
from pathlib import Path
import re
import os
import codecs
folder = Path('{Path to directory}/Online-Ponzi-Schemes/data/hyip_website_archive/').rglob('*.html')
def get_data(file):
| 55 | 64 | 141 | 5 | 50 | sharad1126/Online-Ponzi-Schemes | code/parse_archive.py | Python | get_data | get_data | 9 | 26 | 9 | 9 | 4e2b77caa01faa6859a0ac74592d5df97340cf5b | bigcode/the-stack | train |
a70323b917ae7f18c72ca8e1 | train | function | def format_rendering_stats_definition(request, candidate_values_pool, log_file=None):
for request_block in request.definition:
primitive = request_block[0]
default_val = request_block[1]
# Handling dynamic primitives that need fresh rendering every time
if primitive == "restler_fuzza... | def format_rendering_stats_definition(request, candidate_values_pool, log_file=None):
| for request_block in request.definition:
primitive = request_block[0]
default_val = request_block[1]
# Handling dynamic primitives that need fresh rendering every time
if primitive == "restler_fuzzable_uuid4":
values = [primitives.restler_fuzzable_uuid4]
# Handle ... | rendered_requests_valid_status
testing_summary['num_fully_valid'] = num_fully_valid
testing_summary['num_sequence_failures'] = num_sequence_failures
testing_summary['num_invalid_by_failed_resource_creations'] = num_invalid_by_failed_resource_creations
testing_summary['total_object_creat... | 149 | 149 | 497 | 16 | 133 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | format_rendering_stats_definition | format_rendering_stats_definition | 696 | 748 | 696 | 696 | bdb38cd7f9a95098609c50921e5edd9b60a2cdec | bigcode/the-stack | train |
528c3304d5149a4ce61d14eb | train | function | def print_async_results(req_data, message):
""" Prints the results of an async resource creation
@param req_data: The request data that was sent
@type req_data: Str
@param message: The message to print
@type message: Str
@return: None
@rtype : None
"""
ASYNC_LOG = os.path.join(L... | def print_async_results(req_data, message):
| """ Prints the results of an async resource creation
@param req_data: The request data that was sent
@type req_data: Str
@param message: The message to print
@type message: Str
@return: None
@rtype : None
"""
ASYNC_LOG = os.path.join(LOGS_DIR, "async_log.txt")
req_data = re... | }.{thread_id!s}'
copyfile(testcaseslogs,
os.path.join(TIME_MACHINE, f"{os.path.basename(testcaseslogs)}.{counter}"))
except Exception:
pass
except Exception as error:
print("Exception copying:", error)
def print_async_results(req_data, message):
| 64 | 64 | 137 | 9 | 55 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | print_async_results | print_async_results | 523 | 541 | 523 | 523 | 5da40f28ae167f8d07b6e2a3454d2c743bbefeea | bigcode/the-stack | train |
7a378c608a9f06b1b273109f | train | function | def build_logfile_path(logname, logType, threadId, log_num=1):
""" Helper to create a logfile path incorporating the thread ID in the filename before the file type suffix.
@param logname: The valid base path without the thread Id.
@type logname: Str
@param logType: The type of log (e.g. fuzzing)
@... | def build_logfile_path(logname, logType, threadId, log_num=1):
| """ Helper to create a logfile path incorporating the thread ID in the filename before the file type suffix.
@param logname: The valid base path without the thread Id.
@type logname: Str
@param logType: The type of log (e.g. fuzzing)
@type logType: Str
@param threadId: The thread id to be in... | ing.txt')
global GARBAGE_COLLECTOR_LOGS
GARBAGE_COLLECTOR_LOGS = os.path.join(LOGS_DIR, 'garbage_collector.txt')
os.makedirs(LOGS_DIR)
def build_logfile_path(logname, logType, threadId, log_num=1):
| 64 | 64 | 203 | 19 | 45 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | build_logfile_path | build_logfile_path | 149 | 166 | 149 | 149 | 448240a768c37faa969760e9e982572dc744971f | bigcode/the-stack | train |
56a50d6b05d5ecc4b4769a77 | train | function | def garbage_collector_logging(msg):
""" Helper to log garbage collection stats.
@param msg: The message to log.
@type msg: Str
@return: None
@rtype : None
"""
thread_id = threading.current_thread().ident
filename = build_logfile_path(GARBAGE_COLLECTOR_LOGS, LOG_TYPE_GC, str(thread_id... | def garbage_collector_logging(msg):
| """ Helper to log garbage collection stats.
@param msg: The message to log.
@type msg: Str
@return: None
@rtype : None
"""
thread_id = threading.current_thread().ident
filename = build_logfile_path(GARBAGE_COLLECTOR_LOGS, LOG_TYPE_GC, str(thread_id))
if not os.path.exists(os.path... |
"""
global SETTINGS_NO_TOKENS_IN_LOGS
from engine.core.request_utilities import replace_auth_token
if SETTINGS_NO_TOKENS_IN_LOGS:
data = replace_auth_token(data, '_OMITTED_AUTH_TOKEN_')
return data
def garbage_collector_logging(msg):
| 64 | 64 | 134 | 7 | 56 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | garbage_collector_logging | garbage_collector_logging | 183 | 201 | 183 | 183 | bb181195adb60d3ad296c71c6965b0387ca84b71 | bigcode/the-stack | train |
d45f5e52afd7f8f4cade8e09 | train | function | def create_network_log(log_name):
""" Creates a new network log type
@param log_name: The name of the log - will be included in filename
@type log_name: Str
@return: None
@rtype : None
"""
thread_id = threading.current_thread().ident
if thread_id not in Network_Logs:
Network_... | def create_network_log(log_name):
| """ Creates a new network log type
@param log_name: The name of the log - will be included in filename
@type log_name: Str
@return: None
@rtype : None
"""
thread_id = threading.current_thread().ident
if thread_id not in Network_Logs:
Network_Logs[thread_id] = NetworkLog(log_n... | , "a+") as f:
print(data, file=f)
f.flush()
except Exception as err:
print(f"Exception writing to main log: {err!s}")
finally:
main_lock.release()
if print_to_console:
print(data)
def create_network_log(log_name):
| 64 | 64 | 114 | 7 | 57 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | create_network_log | create_network_log | 226 | 240 | 226 | 226 | a4d76c9222b4d5d27b2c4b936012c285565f92e8 | bigcode/the-stack | train |
33fde75a910943391ccd806c | train | function | def print_request_rendering_stats_never_rendered_requests(fuzzing_requests,
candidate_values_pool,
fuzzing_monitor):
""" Prints to file statistics for request renderings.
@param fuzzing_requests:... | def print_request_rendering_stats_never_rendered_requests(fuzzing_requests,
candidate_values_pool,
fuzzing_monitor):
| """ Prints to file statistics for request renderings.
@param fuzzing_requests: The collection of requests to be fuzzed
@type fuzzing_requests: FuzzingRequestCollection
@param candidate_values_pool: The global pool of candidate values
@type candidate_values_pool: CandidateValuesPool
@param fuz... | 0:
return
print(f"\tRequest: {ind}", file=log_file)
format_rendering_stats_definition(request, candidate_values_pool, log_file)
print("-------------------------\n", file=log_file)
log_file.flush()
def print_request_rendering_stats_never_rendered_requests(fuzzin... | 79 | 79 | 264 | 26 | 53 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | print_request_rendering_stats_never_rendered_requests | print_request_rendering_stats_never_rendered_requests | 819 | 849 | 819 | 821 | 645b14a020b30e9202db59c27dae02bdc09add73 | bigcode/the-stack | train |
37268203c9f2aec3e9835ac0 | train | function | def no_tokens_in_logs():
""" Do not print token data in logs
@return: None
@rtype: None
"""
global SETTINGS_NO_TOKENS_IN_LOGS
SETTINGS_NO_TOKENS_IN_LOGS = True
return
| def no_tokens_in_logs():
| """ Do not print token data in logs
@return: None
@rtype: None
"""
global SETTINGS_NO_TOKENS_IN_LOGS
SETTINGS_NO_TOKENS_IN_LOGS = True
return
| _name, self._thread_id, self._current_log_num)
with open(self._current_log_path, 'a+', encoding='utf-8') as log_file:
print(data, file=log_file)
log_file.flush()
os.fsync(log_file.fileno())
def no_tokens_in_logs():
| 64 | 64 | 56 | 6 | 58 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | no_tokens_in_logs | no_tokens_in_logs | 104 | 111 | 104 | 104 | d65f318d85298b32bbc323510d6fe2863090637d | bigcode/the-stack | train |
3f83c8d28d481ab965cbc035 | train | function | def print_spec_coverage(fuzzing_requests):
""" Prints the speccov run summary in json format
@param fuzzing_requests: The fuzzing request collection
@type fuzzing_requests: FuzzingRequests
@return: None
@rtype : None
"""
from engine.core.requests import FailureInformation
# Sort the ... | def print_spec_coverage(fuzzing_requests):
| """ Prints the speccov run summary in json format
@param fuzzing_requests: The fuzzing request collection
@type fuzzing_requests: FuzzingRequests
@return: None
@rtype : None
"""
from engine.core.requests import FailureInformation
# Sort the requests by request_order
spec_list = f... |
@rtype : None
"""
with open(REQUEST_RENDERING_LOGS, "a+") as log_file:
print(f"\n{formatting.timestamp()}: \tNever Rendered requests:", file=log_file)
for ind, request in enumerate(fuzzing_requests):
if fuzzing_monitor.is_fully_rendered_request(request):
contin... | 147 | 147 | 492 | 10 | 137 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | print_spec_coverage | print_spec_coverage | 851 | 897 | 851 | 851 | 963b3e8954984764ae0dd26e62a32d4c5dceea35 | bigcode/the-stack | train |
9df99805c4c49487c81e1202 | train | function | def print_req_collection_stats(req_collection, candidate_values_pool):
""" Prints request collection evolution stats.
@param req_collection: A collection of requests.
@type req_collection: FuzzingRequestCollection class object.
@param candidate_values_pool: The shared global pool of candidate values
... | def print_req_collection_stats(req_collection, candidate_values_pool):
| """ Prints request collection evolution stats.
@param req_collection: A collection of requests.
@type req_collection: FuzzingRequestCollection class object.
@param candidate_values_pool: The shared global pool of candidate values
@type candidate_values_pool: CandidateValuesPool
@return: Non... | Str
@param message: The message to print
@type message: Str
@return: None
@rtype : None
"""
ASYNC_LOG = os.path.join(LOGS_DIR, "async_log.txt")
req_data = remove_tokens_from_logs(req_data)
with open(ASYNC_LOG, "a+") as f:
print(repr(req_data), file=f)
print(f"{messa... | 109 | 109 | 366 | 12 | 97 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | print_req_collection_stats | print_req_collection_stats | 543 | 584 | 543 | 543 | dc96aacc7351a2b64bd01d8c8943a0e4e15fb4b2 | bigcode/the-stack | train |
5ca9add5d4ac973ad5a2dd3b | train | function | def raw_network_logging(data):
""" Helper to log network traffic transfered over sockets.
@param data: The data paylod to be logged.
@type data: Str
@return: None
@rtype : None
"""
if data is None:
# This case may occur when converting the response payload does not have a string
... | def raw_network_logging(data):
| """ Helper to log network traffic transfered over sockets.
@param data: The data paylod to be logged.
@type data: Str
@return: None
@rtype : None
"""
if data is None:
# This case may occur when converting the response payload does not have a string
# representation. As a ... | _name: Str
@return: None
@rtype : None
"""
thread_id = threading.current_thread().ident
if thread_id not in Network_Logs:
Network_Logs[thread_id] = NetworkLog(log_name, thread_id)
else:
raise Exception(f"Network log with thread id {thread_id} already exists.")
def raw_network_l... | 81 | 81 | 273 | 6 | 75 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | raw_network_logging | raw_network_logging | 242 | 272 | 242 | 242 | 3783b51def10bcfba2d2387977f08c1f68b97581 | bigcode/the-stack | train |
d5045170f9f295d72fc7c200 | train | function | def remove_tokens_from_logs(data):
""" If the no-tokens-in-logs setting is set, this function will attempt to
find the token in the data string and replace it with _OMITTED_AUTH_TOKEN_
@type data: Str
@return: The data with the token removed
@rtype : Str
"""
global SETTINGS_NO_TOKENS_IN_L... | def remove_tokens_from_logs(data):
| """ If the no-tokens-in-logs setting is set, this function will attempt to
find the token in the data string and replace it with _OMITTED_AUTH_TOKEN_
@type data: Str
@return: The data with the token removed
@rtype : Str
"""
global SETTINGS_NO_TOKENS_IN_LOGS
from engine.core.request_ut... | return: Formatted logfile path
@rtype : Str
"""
typeStart = logname.rfind(".txt")
return f"{logname[:typeStart]}.{logType}.{threadId!s}.{log_num!s}{logname[typeStart:]}"
def remove_tokens_from_logs(data):
| 63 | 64 | 127 | 7 | 56 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | remove_tokens_from_logs | remove_tokens_from_logs | 168 | 181 | 168 | 168 | 854fcf1d139143773ceb580bade773bce7079996 | bigcode/the-stack | train |
e1afad4573950067d2d77275 | train | function | def create_experiment_dir():
""" creates the unique EXPERIMENT_DIR directory where results are saved
@return: None
@rtype: None
"""
global EXPERIMENT_DIR
adder = 0
while True:
EXPERIMENT_DIR = os.path.join(os.getcwd(), 'RestlerResults', f'experiment{(os.getpid() + adder)!s}')
... | def create_experiment_dir():
| """ creates the unique EXPERIMENT_DIR directory where results are saved
@return: None
@rtype: None
"""
global EXPERIMENT_DIR
adder = 0
while True:
EXPERIMENT_DIR = os.path.join(os.getcwd(), 'RestlerResults', f'experiment{(os.getpid() + adder)!s}')
if not os.path.isdir(EXPERIM... | )
with open(self._current_log_path, 'a+', encoding='utf-8') as log_file:
print(data, file=log_file)
log_file.flush()
os.fsync(log_file.fileno())
def no_tokens_in_logs():
""" Do not print token data in logs
@return: None
@rtype: None
"""
global SETTINGS_N... | 108 | 108 | 362 | 6 | 101 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | create_experiment_dir | create_experiment_dir | 113 | 147 | 113 | 113 | 5500c0881346c406adfe6361715806d055300354 | bigcode/the-stack | train |
c37ae95896871a90fcbbf74c | train | function | def print_generation_stats(req_collection, fuzzing_monitor, global_lock, final=False):
""" Prints global generation's statistics.
@param req_collection: The requests collection.
@type req_collection: RequestCollection class object.
@param fuzzing_monitor: The global fuzzing monitor
@type fuzzing_... | def print_generation_stats(req_collection, fuzzing_monitor, global_lock, final=False):
| """ Prints global generation's statistics.
@param req_collection: The requests collection.
@type req_collection: RequestCollection class object.
@param fuzzing_monitor: The global fuzzing monitor
@type fuzzing_monitor: FuzzingMonitor
@param global_lock: Lock object used for sync of more than ... | timestamp = formatting.timestamp()
print_memory_consumption.invocations += 1
lcov = 0
avg_val = statistics.mean([r.num_combinations(req_collection.candidate_values_pool)\
for r in req_collection])
write_to_main(
f"MARKER, {print_memory_consumption.invocations}, "
f"... | 240 | 240 | 802 | 17 | 222 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | print_generation_stats | print_generation_stats | 626 | 694 | 626 | 626 | 091313da129ffa1974aeec909d70d1e6d68b973f | bigcode/the-stack | train |
8d0dd4cbc6eae17ad126241b | train | function | def print_memory_consumption(req_collection, fuzzing_monitor, fuzzing_mode, generation):
""" Prints global generation's memory consumption statistics.
@param req_collection: The requests collection.
@type req_collection: RequestCollection class object.
@param fuzzing_monitor: The global fuzzing monito... | def print_memory_consumption(req_collection, fuzzing_monitor, fuzzing_mode, generation):
| """ Prints global generation's memory consumption statistics.
@param req_collection: The requests collection.
@type req_collection: RequestCollection class object.
@param fuzzing_monitor: The global fuzzing monitor
@type fuzzing_monitor: FuzzingMonitor
@param fuzzing_mode: The current fuzzing... | val = max([r.num_combinations(candidate_values_pool)\
for r in req_collection])
data += f"{timestamp}: Max Value Combinations per Request: {val}\n"
val = 0
for r in req_collection:
val += len(r.produces)
val += len(r.consumes)
data += f"{timestamp}: Total dependenc... | 107 | 107 | 357 | 18 | 89 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | print_memory_consumption | print_memory_consumption | 586 | 621 | 586 | 586 | 0907eda783c8a83a6648f70ca03644d118f0a1b0 | bigcode/the-stack | train |
f4f4366a968bcf5bde246705 | train | function | def custom_network_logging(sequence, candidate_values_pool, **kwargs):
""" Helper to log (in a more civilized manner) the template of the request
which will be subsequently rendered with the respective feasible value
combinations.
@param sequence: The sequence to be logged.
@type sequence: Sequenc... | def custom_network_logging(sequence, candidate_values_pool, **kwargs):
| """ Helper to log (in a more civilized manner) the template of the request
which will be subsequently rendered with the respective feasible value
combinations.
@param sequence: The sequence to be logged.
@type sequence: Sequence class object.
@param candidate_values_pool: the pool of values fo... | @type data: Str
@return: None
@rtype : None
"""
if data is None:
# This case may occur when converting the response payload does not have a string
# representation. As a workaround, print text to the log so that it contains
# a received response.
data = '_OMITTED_U... | 255 | 255 | 851 | 13 | 242 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | custom_network_logging | custom_network_logging | 274 | 357 | 274 | 274 | 987f2c4bb8f32f87fee28164bb7c8734df59b859 | bigcode/the-stack | train |
20eac4affbec4d059e58f85b | train | function | def copy_stats(counter):
"""
@param counter: Increment over time (every ten minutes) of logging.
@type counter: Int
@return: None
@rtype : None
"""
return
if not os.path.exists(TIME_MACHINE):
try:
os.makedirs(TIME_MACHINE)
except OSError:
prin... | def copy_stats(counter):
| """
@param counter: Increment over time (every ten minutes) of logging.
@type counter: Int
@return: None
@rtype : None
"""
return
if not os.path.exists(TIME_MACHINE):
try:
os.makedirs(TIME_MACHINE)
except OSError:
print(f"Exception Cannot Crea... | )
print(f"Hash: {Bugs_Logged[bucket_hash].bug_hash}", file=log_file)
for request in bug_bucket.sequence:
for payload in list(map(lambda x: x[1], request.definition)):
print(repr(payload)[1:-1], end='', file=log_file)
print(f... | 105 | 105 | 351 | 5 | 100 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | copy_stats | copy_stats | 478 | 521 | 478 | 478 | 1833b0b782f109960b2068e637efd1d4936d265b | bigcode/the-stack | train |
8a6677831e9214cb2ede95ef | train | function | def write_to_main(data: str, print_to_console: bool=False):
""" Writes to the main log
@param data: The data to write
@param print_to_console: If true, print to console as well as log
@return: None
"""
try:
main_lock.acquire()
with open(MAIN_LOGS, "a+") as f:
print... | def write_to_main(data: str, print_to_console: bool=False):
| """ Writes to the main log
@param data: The data to write
@param print_to_console: If true, print to console as well as log
@return: None
"""
try:
main_lock.acquire()
with open(MAIN_LOGS, "a+") as f:
print(data, file=f)
f.flush()
except Exception as... | try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
with open(filename, "a+") as log_file:
print(msg, file=log_file)
main_lock = threading.Semaphore(1)
def write_to_main(data: str, print_to_console: bool=False):
| 64 | 64 | 131 | 15 | 49 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | write_to_main | write_to_main | 204 | 224 | 204 | 204 | 94e90a9094e84415d9b91e0c1857710782f168ba | bigcode/the-stack | train |
333340e505788ca799965374 | train | class | class NetworkLog(object):
""" Implements logic for creating, chunking, and writing to network logs """
_MaxLogSize = 1024*1024*100 # = 100MB
def __init__(self, log_name, thread_id):
""" NetworkLog constructor
@param thread_id: The thread ID of the thread writing to this log
@type t... | class NetworkLog(object):
| """ Implements logic for creating, chunking, and writing to network logs """
_MaxLogSize = 1024*1024*100 # = 100MB
def __init__(self, log_name, thread_id):
""" NetworkLog constructor
@param thread_id: The thread ID of the thread writing to this log
@type thread_id: Int
"""
... | the replay.
REPLAY_REQUEST_INDICATOR = '-> '
# This symbol indicates additional information tied to a request in the bug
# bucket log to be used when replaying logs
BUG_LOG_NOTIFICATION_ICON = '! '
# Collection of NetworkLog objects identified by their thread ID
Network_Logs = dict()
LOG_TYPE_TESTING = 'testing'
LO... | 103 | 103 | 344 | 5 | 98 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | NetworkLog | NetworkLog | 66 | 102 | 66 | 66 | 8ed404f83bf0580ce4215877cc7e5fe10592a11d | bigcode/the-stack | train |
c7d8ae5b814d9bae0c112a33 | train | function | def print_request_rendering_stats(candidate_values_pool, fuzzing_requests, fuzzing_monitor, num_rendered_requests, generation, global_lock):
""" Prints to file statistics for request renderings.
@param candidate_values_pool: The global pool of candidate values
@type candidate_values_pool: CandidateValuesP... | def print_request_rendering_stats(candidate_values_pool, fuzzing_requests, fuzzing_monitor, num_rendered_requests, generation, global_lock):
| """ Prints to file statistics for request renderings.
@param candidate_values_pool: The global pool of candidate values
@type candidate_values_pool: CandidateValuesPool
@param fuzzing_requests: The collection of requests to be fuzzed.
@type fuzzing_requests: FuzzingRequestCollection class object.... | _payload_uuid4_suffix":
current_fuzzable_tag = default_val
values = candidate_values_pool.get_candidate_values(primitive, request_id=request.request_id, tag=current_fuzzable_tag)
default_val = values[0]
# Handle all the rest
else:
values = candidate_values... | 193 | 194 | 647 | 28 | 165 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | print_request_rendering_stats | print_request_rendering_stats | 750 | 816 | 750 | 750 | cc621cbc6b03d46b82bbbec847bfccc0580e58eb | bigcode/the-stack | train |
17655152efd533295991859e | train | function | def update_bug_buckets(bug_buckets, bug_request_data, bug_hash, additional_log_str=None):
"""
@param bug_buckets: Dictionary containing bug bucket information
@type bug_buckets: Dict
@param bug_request_data: The list of request data that was sent to create the bug
@type bug_request_data: List[Sent... | def update_bug_buckets(bug_buckets, bug_request_data, bug_hash, additional_log_str=None):
| """
@param bug_buckets: Dictionary containing bug bucket information
@type bug_buckets: Dict
@param bug_request_data: The list of request data that was sent to create the bug
@type bug_request_data: List[SentRequestData]
@param bug_hash: The unique hash for this bug
@type bug_hash: Str
... | _values_pool.get_candidate_values(primitive, request_id=request.request_id, tag=current_fuzzable_tag, quoted=quoted)
default_val = values[0]
# Handle all the rest
else:
values = candidate_values_pool.get_fuzzable_values(primitive, default_val, request.request_id, ... | 256 | 256 | 1,320 | 22 | 234 | reggieag/restler-fuzzer | restler/utils/logger.py | Python | update_bug_buckets | update_bug_buckets | 366 | 476 | 366 | 366 | 195266ce4c85a49721bc90f3d8cdd7ad01e82590 | bigcode/the-stack | train |
5e2c9468b9e48ca3ba9d1c8f | train | function | def create_skill():
return SocketMessage()
| def create_skill():
| return SocketMessage()
| import MycroftSkill, intent_file_handler
class SocketMessage(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('message.socket.intent')
def handle_message_socket(self, message):
self.speak_dialog('message.socket')
def create_skill():
| 64 | 64 | 9 | 4 | 60 | Gnizich/socket-message-skill | __init__.py | Python | create_skill | create_skill | 13 | 14 | 13 | 13 | b7a104ff6b4c2899bdb632505f3eddcadde8bf42 | bigcode/the-stack | train |
a61118ee46fd13b4a0bf8992 | train | class | class SocketMessage(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('message.socket.intent')
def handle_message_socket(self, message):
self.speak_dialog('message.socket')
| class SocketMessage(MycroftSkill):
| def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('message.socket.intent')
def handle_message_socket(self, message):
self.speak_dialog('message.socket')
| from mycroft import MycroftSkill, intent_file_handler
class SocketMessage(MycroftSkill):
| 19 | 64 | 51 | 7 | 11 | Gnizich/socket-message-skill | __init__.py | Python | SocketMessage | SocketMessage | 4 | 10 | 4 | 4 | cea08a165d5820d8a58e1e3e9d6839535c66c912 | bigcode/the-stack | train |
4b43ab6b938d133712b6ecd2 | train | class | class InfobloxExtattrManager(object):
# Make database connections
MC = MongoConnector.MongoConnector()
APIH = APIHelper.APIHelper()
IH = InfobloxHelper.InfobloxHelper()
iblox_extattr_collection = MC.get_infoblox_extattr_connection()
zone_queried = None
record_type = None
next_page_id = ... | class InfobloxExtattrManager(object):
# Make database connections
| MC = MongoConnector.MongoConnector()
APIH = APIHelper.APIHelper()
IH = InfobloxHelper.InfobloxHelper()
iblox_extattr_collection = MC.get_infoblox_extattr_connection()
zone_queried = None
record_type = None
next_page_id = None
_logger = None
def _log(self):
"""
Get ... | "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 in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANT... | 256 | 256 | 1,770 | 15 | 240 | babushka1999/Marinus | python3_cron_scripts/libs3/InfobloxExtattrManager.py | Python | InfobloxExtattrManager | InfobloxExtattrManager | 37 | 230 | 37 | 38 | c76b93df57e02bf7c3c7792df9445f9ddb0549c0 | bigcode/the-stack | train |
a1190238961f4fb427fb5210 | train | class | class TestOPSExpression(object):
@pytest.mark.parametrize('equation, expected', [
('Eq(u,3*a - 4**a)', 'void OPS_Kernel_0(ACC<float> & ut0)\n'
'{\n ut0(0) = -2.97015324253729F;\n}'),
('Eq(u, u.dxl)',
'void OPS_Kernel_0(ACC<float> & ut0, const float *h_x)\n'
'{\n float r... | class TestOPSExpression(object):
@pytest.mark.parametrize('equation, expected', [
('Eq(u,3*a - 4**a)', 'void OPS_Kernel_0(ACC<float> & ut0)\n'
'{\n ut0(0) = -2.97015324253729F;\n}'),
('Eq(u, u.dxl)',
'void OPS_Kernel_0(ACC<float> & ut0, const float *h_x)\n'
'{\n float r... | def test_kernel_generation(self, equation, expected):
"""
Test OPS generated expressions for 1, 2 and 3 space dimensions.
Parameters
----------
equation : str
A string with a Eq to be evaluated.
expected : str
Expected expression to be generat... | class TestOPSExpression(object):
@pytest.mark.parametrize('equation, expected', [
('Eq(u,3*a - 4**a)', 'void OPS_Kernel_0(ACC<float> & ut0)\n'
'{\n ut0(0) = -2.97015324253729F;\n}'),
('Eq(u, u.dxl)',
'void OPS_Kernel_0(ACC<float> & ut0, const float *h_x)\n'
'{\n float r... | 947 | 256 | 3,982 | 947 | 0 | CavalcanteLucas/devito | tests/test_ops.py | Python | TestOPSExpression | TestOPSExpression | 25 | 304 | 25 | 63 | 108c4f4509f607b8b61741d8f06900049363c1bd | bigcode/the-stack | train |
f929ff94969920e151d53720 | train | class | class DocBlueprintMixin:
"""Extend Api to serve the spec in a dedicated blueprint."""
def _register_doc_blueprint(self):
"""Register a blueprint in the application to expose the spec
Doc Blueprint contains routes to
- json spec file
- spec UI (ReDoc, Swagger UI).
"""
... | class DocBlueprintMixin:
| """Extend Api to serve the spec in a dedicated blueprint."""
def _register_doc_blueprint(self):
"""Register a blueprint in the application to expose the spec
Doc Blueprint contains routes to
- json spec file
- spec UI (ReDoc, Swagger UI).
"""
api_url = self._app... | """API specification using Open API"""
import json
import flask
from flask import current_app
import apispec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_rest_api.exceptions import OpenAPIVersionNotSpecified
from .plugins import FlaskPlugin
def _add_leading_slash(string):
"""Add leading sla... | 96 | 256 | 1,351 | 5 | 90 | vjm/flask-rest-api | flask_rest_api/spec/__init__.py | Python | DocBlueprintMixin | DocBlueprintMixin | 19 | 165 | 19 | 19 | 37a81e5eeabd8a6d6f1642c426ae050b173384e8 | bigcode/the-stack | train |
df14b5001abd1442cf73035f | train | function | def _add_leading_slash(string):
"""Add leading slash to a string if there is None"""
return string if string.startswith('/') else '/' + string
| def _add_leading_slash(string):
| """Add leading slash to a string if there is None"""
return string if string.startswith('/') else '/' + string
| specification using Open API"""
import json
import flask
from flask import current_app
import apispec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_rest_api.exceptions import OpenAPIVersionNotSpecified
from .plugins import FlaskPlugin
def _add_leading_slash(string):
| 64 | 64 | 34 | 9 | 54 | vjm/flask-rest-api | flask_rest_api/spec/__init__.py | Python | _add_leading_slash | _add_leading_slash | 14 | 16 | 14 | 14 | e07b3d5884c1d99fa62992a5507e68ae7698d041 | bigcode/the-stack | train |
6b6d33a193f7bd2e2ef4c1c5 | train | class | class APISpecMixin(DocBlueprintMixin):
"""Add APISpec related features to Api class"""
def _init_spec(
self, *, flask_plugin=None, marshmallow_plugin=None,
extra_plugins=None, openapi_version=None, **options
):
# Plugins
self.flask_plugin = flask_plugin or FlaskPlugi... | class APISpecMixin(DocBlueprintMixin):
| """Add APISpec related features to Api class"""
def _init_spec(
self, *, flask_plugin=None, marshmallow_plugin=None,
extra_plugins=None, openapi_version=None, **options
):
# Plugins
self.flask_plugin = flask_plugin or FlaskPlugin()
self.ma_plugin = marshmallo... | )
def _openapi_json(self):
"""Serve JSON spec file"""
# We don't use Flask.jsonify here as it would sort the keys
# alphabetically while we want to preserve the order.
return current_app.response_class(
json.dumps(self.spec.to_dict(), indent=2),
mimetype='app... | 256 | 256 | 918 | 10 | 246 | vjm/flask-rest-api | flask_rest_api/spec/__init__.py | Python | APISpecMixin | APISpecMixin | 168 | 281 | 168 | 168 | 98af10dadd030af4ab7b9c326481143372b2736c | bigcode/the-stack | train |
02ae67faf979664ce98e1298 | train | class | class MapzenAPI(object):
"""Python Client for Mapzen APIs"""
DEFAULT_VERSION = 'v1'
SEARCH_BASE_URL = 'https://search.mapzen.com'
BASE_PARAMS = ('sources', 'layers', 'boundary_country')
# Autocomplete endpoint
AUTOCOMPLETE_API_BASEURL = SEARCH_BASE_URL
AUTOCOMPLETE_API_ENDPOINT = 'autocompl... | class MapzenAPI(object):
| """Python Client for Mapzen APIs"""
DEFAULT_VERSION = 'v1'
SEARCH_BASE_URL = 'https://search.mapzen.com'
BASE_PARAMS = ('sources', 'layers', 'boundary_country')
# Autocomplete endpoint
AUTOCOMPLETE_API_BASEURL = SEARCH_BASE_URL
AUTOCOMPLETE_API_ENDPOINT = 'autocomplete'
AUTOCOMPLETE_API... | import json
from six.moves.urllib.error import HTTPError
from six.moves.urllib.request import Request, urlopen
from six.moves.urllib.parse import urlencode
from six import iteritems, string_types
from mapzen.exceptions import MapzenError, MapzenRateLimitError, MapzenKeyError
__author__ = 'duydo'
def check_not_empt... | 101 | 256 | 2,408 | 6 | 95 | duydo/python-mapzen | mapzen/api.py | Python | MapzenAPI | MapzenAPI | 19 | 245 | 19 | 19 | 7637f6bbdad8b5d837ad13e634bf2a5d8ffe5d2e | bigcode/the-stack | train |
024c64a8b5d94e4ffdf2bb1d | train | function | def check_not_empty(reference, message=None):
if reference:
return reference
raise ValueError(message)
| def check_not_empty(reference, message=None):
| if reference:
return reference
raise ValueError(message)
| urllib.request import Request, urlopen
from six.moves.urllib.parse import urlencode
from six import iteritems, string_types
from mapzen.exceptions import MapzenError, MapzenRateLimitError, MapzenKeyError
__author__ = 'duydo'
def check_not_empty(reference, message=None):
| 64 | 64 | 23 | 9 | 55 | duydo/python-mapzen | mapzen/api.py | Python | check_not_empty | check_not_empty | 13 | 16 | 13 | 13 | 26b76a4d4a3f5d3b9df4a7ae4048a5207de8b496 | bigcode/the-stack | train |
f904274871909b8064f9ce02 | train | class | class TwoArrayMedianTests(unittest.TestCase):
@given(st.lists(st.integers()).map(sorted), st.lists(st.integers()).map(sorted))
@example([-3, 0], [-1, -1])
@example([], [0])
@example([], [0, 1])
@example([0], [1])
@example([0, 2], [0, 1])
@example([-1, -1], [0, 0])
@example([-2, -2, 0, 0,... | class TwoArrayMedianTests(unittest.TestCase):
@given(st.lists(st.integers()).map(sorted), st.lists(st.integers()).map(sorted))
@example([-3, 0], [-1, -1])
@example([], [0])
@example([], [0, 1])
@example([0], [1])
@example([0, 2], [0, 1])
@example([-1, -1], [0, 0])
@example([-2, -2, 0, 0,... | def test_case(self, l1, l2):
assume(len(l1) + len(l2) > 0)
m = median(sorted(l1 + l2))
self.assertEqual(m, find_media_sorted_arrays(l1, l2))
| class TwoArrayMedianTests(unittest.TestCase):
@given(st.lists(st.integers()).map(sorted), st.lists(st.integers()).map(sorted))
@example([-3, 0], [-1, -1])
@example([], [0])
@example([], [0, 1])
@example([0], [1])
@example([0, 2], [0, 1])
@example([-1, -1], [0, 0])
@example([-2, -2, 0, 0,... | 289 | 102 | 343 | 289 | 0 | domartynov/problems | two_array_median_tests.py | Python | TwoArrayMedianTests | TwoArrayMedianTests | 7 | 25 | 7 | 21 | 1f40881194189ea436f7b381e8cd61c8b00ac32f | bigcode/the-stack | train |
a6174a43db7564eae9ede47d | train | function | @hooks.register('register_log_actions')
def register_workflow_log_actions(actions):
def workflow_start_message(data):
try:
return _("'%(workflow)s' started. Next step '%(task)s'") % {
'workflow': data['workflow']['title'],
'task': data['workflow']['next']['title']... | @hooks.register('register_log_actions')
def register_workflow_log_actions(actions):
| def workflow_start_message(data):
try:
return _("'%(workflow)s' started. Next step '%(task)s'") % {
'workflow': data['workflow']['title'],
'task': data['workflow']['next']['title'],
}
except (KeyError, TypeError):
return _('Workflow... | )
actions.register_action('wagtail.comments.create', _('Add comment'), create_comment_message)
actions.register_action('wagtail.comments.edit', _('Edit comment'), edit_comment_message)
actions.register_action('wagtail.comments.delete', _('Delete comment'), delete_comment_message)
actions.register_action... | 158 | 158 | 528 | 16 | 142 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | register_workflow_log_actions | register_workflow_log_actions | 333 | 391 | 333 | 334 | 986020b083e9adf560fa14de950ed5831b3a4ecb | bigcode/the-stack | train |
dedca234e21905446442375d | train | function | @hooks.register('register_permissions')
def register_workflow_permissions():
return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_workflow', 'change_workflow', 'delete_workflow']
)
| @hooks.register('register_permissions')
def register_workflow_permissions():
| return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_workflow', 'change_workflow', 'delete_workflow']
)
| ul')
@hooks.register('register_permissions')
def register_collection_permissions():
return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_collection', 'change_collection', 'delete_collection']
)
@hooks.register('register_permissions')
def register_workflow... | 64 | 64 | 53 | 13 | 51 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | register_workflow_permissions | register_workflow_permissions | 67 | 72 | 67 | 68 | e42c0af41d3bd8de90cc9d13ef692c992042cc56 | bigcode/the-stack | train |
221acd0f35ac563d7aa0c117 | train | function | def require_wagtail_login(next):
login_url = getattr(settings, 'WAGTAIL_FRONTEND_LOGIN_URL', reverse('wagtailcore_login'))
return redirect_to_login(next, login_url)
| def require_wagtail_login(next):
| login_url = getattr(settings, 'WAGTAIL_FRONTEND_LOGIN_URL', reverse('wagtailcore_login'))
return redirect_to_login(next, login_url)
| import reverse
from django.utils.text import capfirst
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
from wagtail.core import hooks
from wagtail.core.models import PageViewRestriction
from wagtail.core.rich_text.pages import PageLinkHandler
def require_wagtail_login(ne... | 64 | 64 | 42 | 8 | 55 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | require_wagtail_login | require_wagtail_login | 14 | 16 | 14 | 14 | 5981c887d644c5d77f4dabb5c2c223375d540ca9 | bigcode/the-stack | train |
5d6ce17d8e184edbfb7cde5c | train | function | @hooks.register('register_permissions')
def register_collection_permissions():
return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_collection', 'change_collection', 'delete_collection']
)
| @hooks.register('register_permissions')
def register_collection_permissions():
| return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_collection', 'change_collection', 'delete_collection']
)
| LinkHandler)
features.default_features.append('bold')
features.default_features.append('italic')
features.default_features.extend(['h2', 'h3', 'h4'])
features.default_features.append('ol')
features.default_features.append('ul')
@hooks.register('register_permissions')
def register_collection_per... | 64 | 64 | 49 | 12 | 52 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | register_collection_permissions | register_collection_permissions | 59 | 64 | 59 | 60 | 5bc7cd9bba8abf682ec5faaac9255672236c6bae | bigcode/the-stack | train |
c92bcc86873442d4243be704 | train | function | @hooks.register('describe_collection_contents')
def describe_collection_children(collection):
descendant_count = collection.get_descendants().count()
if descendant_count:
url = reverse('wagtailadmin_collections:index')
return {
'count': descendant_count,
'count_text': nge... | @hooks.register('describe_collection_contents')
def describe_collection_children(collection):
| descendant_count = collection.get_descendants().count()
if descendant_count:
url = reverse('wagtailadmin_collections:index')
return {
'count': descendant_count,
'count_text': ngettext(
"%(count)s descendant collection",
"%(count)s descendan... | )
@hooks.register('register_permissions')
def register_task_permissions():
return Permission.objects.filter(
content_type__app_label='wagtailcore',
codename__in=['add_task', 'change_task', 'delete_task']
)
@hooks.register('describe_collection_contents')
def describe_collection_children(collec... | 64 | 64 | 98 | 14 | 50 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | describe_collection_children | describe_collection_children | 83 | 96 | 83 | 84 | 89f2e4bfe4d39947b3cb5990b04a3ae7ad99e416 | bigcode/the-stack | train |
7a8a9a89629c33285f9252db | train | function | @hooks.register('register_rich_text_features')
def register_core_features(features):
features.default_features.append('hr')
features.default_features.append('link')
features.register_link_type(PageLinkHandler)
features.default_features.append('bold')
features.default_features.append('italic')
... | @hooks.register('register_rich_text_features')
def register_core_features(features):
| features.default_features.append('hr')
features.default_features.append('link')
features.register_link_type(PageLinkHandler)
features.default_features.append('bold')
features.default_features.append('italic')
features.default_features.extend(['h2', 'h3', 'h4'])
features.default_features... | return page.serve_password_required_response(request, form, action_url)
elif restriction.restriction_type in [PageViewRestriction.LOGIN, PageViewRestriction.GROUPS]:
return require_wagtail_login(next=request.get_full_path())
@hooks.register('register_rich_text_features')
def register_core_... | 64 | 64 | 90 | 16 | 48 | shreyashsrivastava/wagtail | wagtail/core/wagtail_hooks.py | Python | register_core_features | register_core_features | 41 | 56 | 41 | 42 | 6e3e2c0db8fe9f59a9954040b204959042ce7095 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.