Dataset Viewer
Auto-converted to Parquet Duplicate
uid
stringlengths
24
24
category
stringclasses
2 values
granularity
stringclasses
1 value
prefix
stringlengths
144
1.47k
suffix
stringlengths
29
63.3k
content
stringlengths
49
63.4k
repo
stringlengths
12
70
path
stringlengths
6
104
5d73787af03aafb3d1fe8f80
function
simple
import SysTest from mapproxy.test.image import is_png, is_transparent, tmp_image from mapproxy.test.http import mock_httpd from mapproxy.test.system.test_wms import is_111_capa, is_130_capa, ns130 @pytest.fixture(scope="module") def config_file():
return "scalehints.yaml"
@pytest.fixture(scope="module") def config_file(): return "scalehints.yaml"
cunha17/mapproxy
mapproxy/test/system/test_scalehints.py
fb17ee4a8a7c8f0ed70b077e
function
simple
def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr(): check_repr("Zstd(level=3)") def test_backwards_compatibility():
check_backwards_compatibility(Zstd.codec_id, arrays, codecs)
def test_backwards_compatibility(): check_backwards_compatibility(Zstd.codec_id, arrays, codecs)
Czaki/numcodecs
numcodecs/tests/test_zstd.py
04f4a5a52c80dadc52944e35
function
simple
np.random.randint(-2**63, -2**63 + 20, size=1000, dtype='i8').view('m8[m]'), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec) def test_config():
for codec in codecs: check_config(codec)
def test_config(): for codec in codecs: check_config(codec)
Czaki/numcodecs
numcodecs/tests/test_zstd.py
bf41843a67add1135149e55d
function
simple
, size=1000, dtype='i8').view('m8[m]'), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr():
check_repr("Zstd(level=3)")
def test_repr(): check_repr("Zstd(level=3)")
Czaki/numcodecs
numcodecs/tests/test_zstd.py
987169e042d7e4bad4dcf4b8
function
simple
(codec) def test_repr(): check_repr("Zstd(level=3)") def test_backwards_compatibility(): check_backwards_compatibility(Zstd.codec_id, arrays, codecs) def test_err_decode_object_buffer(): check_err_decode_object_buffer(Zstd()) def test_err_encode_object_buffer():
check_err_encode_object_buffer(Zstd())
def test_err_encode_object_buffer(): check_err_encode_object_buffer(Zstd())
Czaki/numcodecs
numcodecs/tests/test_zstd.py
c49f8e4cd5fb4bc0a9896287
function
simple
, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr(): check_repr("Zstd(level=3)") def test_backwards_compatibility(): check_backwards_compatibility(Zstd.codec_id, arrays, codecs) def test_err_decode_object_buffer():
check_err_decode_object_buffer(Zstd())
def test_err_decode_object_buffer(): check_err_decode_object_buffer(Zstd())
Czaki/numcodecs
numcodecs/tests/test_zstd.py
865e8ec9ecb72716140cbae6
function
simple
2**63 + 20, size=1000, dtype='i8').view('M8[m]'), np.random.randint(-2**63, -2**63 + 20, size=1000, dtype='i8').view('m8[m]'), ] def test_encode_decode():
for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec)
def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec)
Czaki/numcodecs
numcodecs/tests/test_zstd.py
18c7ccd1a501d03e90732b43
function
simple
# express or implied. See the License for the specific language governing # permissions and limitations under the License. from typing import Tuple, List import pytest import torch import numpy as np from pts.distributions import PiecewiseLinear from pts.modules import PiecewiseLinearOutput def empirical_cdf( ...
""" Calculate the empirical cdf from the given samples. Parameters ---------- samples Tensor of samples of shape (num_samples, batch_shape) Returns ------- Tensor Empirically calculated cdf values. shape (num_bins, batch_shape) Tensor Bin edges corresponding t...
def empirical_cdf( samples: np.ndarray, num_bins: int = 100 ) -> Tuple[np.ndarray, np.ndarray]: """ Calculate the empirical cdf from the given samples. Parameters ---------- samples Tensor of samples of shape (num_samples, batch_shape) Returns ------- Tensor Empirical...
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
f13e235733865a4d5ac41f01
function
simple
.0])).numpy().item() == 1.0 expected_crps = np.array([1.0 + 2.0 / 3.0]) assert np.allclose(distr.crps(torch.Tensor([-2.0])).numpy(), expected_crps) assert np.allclose(distr.crps(torch.Tensor([2.0])).numpy(), expected_crps) def test_robustness():
distr_out = PiecewiseLinearOutput(num_pieces=10) args_proj = distr_out.get_args_proj(in_features=30) net_out = torch.normal(mean=0.0, size=(1000, 30), std=1e2) gamma, slopes, knot_spacings = args_proj(net_out) distr = distr_out.distribution((gamma, slopes, knot_spacings)) # compute the 1-quant...
def test_robustness(): distr_out = PiecewiseLinearOutput(num_pieces=10) args_proj = distr_out.get_args_proj(in_features=30) net_out = torch.normal(mean=0.0, size=(1000, 30), std=1e2) gamma, slopes, knot_spacings = args_proj(net_out) distr = distr_out.distribution((gamma, slopes, knot_spacings)) ...
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
1eb411f3d0aee315155f9219
function
simple
shape when num_samples # is not None is correct samples = distr.sample((num_samples,)) assert samples.shape == (num_samples, *batch_shape) assert distr.quantile_internal(samples, dim=0).shape == (num_samples, *batch_shape,) def test_simple_symmetric():
gamma = torch.Tensor([-1.0]) slopes = torch.Tensor([[2.0, 2.0]]) knot_spacings = torch.Tensor([[0.5, 0.5]]) distr = PiecewiseLinear(gamma=gamma, slopes=slopes, knot_spacings=knot_spacings) assert distr.cdf(torch.Tensor([-2.0])).numpy().item() == 0.0 assert distr.cdf(torch.Tensor([+2.0])).numpy...
def test_simple_symmetric(): gamma = torch.Tensor([-1.0]) slopes = torch.Tensor([[2.0, 2.0]]) knot_spacings = torch.Tensor([[0.5, 0.5]]) distr = PiecewiseLinear(gamma=gamma, slopes=slopes, knot_spacings=knot_spacings) assert distr.cdf(torch.Tensor([-2.0])).numpy().item() == 0.0 assert distr.cd...
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
245e028bd69dcce924e3a928
function
simple
'close' else: self.type = None class Enum(object): """A group of constants""" def __init__(self, name): self.name = name self.constants = [] self.comment = '' class UnsupportedParameterError(Exception): pass def _join_lines(source):
"""Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source)
def _join_lines(source): """Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source)
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
df71c0743a6463b18a04c2f8
function
simple
_qs from aiohttp import ClientSession from aiohttp.client_exceptions import ClientError, ClientResponseError from aiohttp.streams import StreamReader from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE from yarl import URL RETYPE = type(re.compile("")) def mock_stream(data):
"""Mock a stream with data.""" protocol = mock.Mock(_reading_paused=False) stream = StreamReader(protocol) stream.feed_data(data) stream.feed_eof() return stream
def mock_stream(data): """Mock a stream with data.""" protocol = mock.Mock(_reading_paused=False) stream = StreamReader(protocol) stream.feed_data(data) stream.feed_eof() return stream
boralyl/pytest-homeassistant
pytest_homeassistant/aiohttp_mock.py
645c1430d95fd81011090b7d
function
simple
request_info = mock.Mock(real_url="http://example.com") raise ClientResponseError( request_info=request_info, history=None, code=self.status, headers=self.headers, ) def close(self): """Mock close.""" @con...
"""Context manager to mock aiohttp client.""" mocker = AiohttpClientMocker() def create_session(hass, *args): session = mocker.create_session(hass.loop) async def close_session(event): """Close session.""" await session.close() hass.bus.async_listen_once(EV...
@contextmanager def mock_aiohttp_client(): """Context manager to mock aiohttp client.""" mocker = AiohttpClientMocker() def create_session(hass, *args): session = mocker.create_session(hass.loop) async def close_session(event): """Close session.""" await session.clo...
boralyl/pytest-homeassistant
pytest_homeassistant/aiohttp_mock.py
fc1644108fef17234732f843
function
simple
, exception): return text("Payload Too Large from error_handler.", 413) response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Payload Too Large from error_handler." def test_payload_too_large_at_data_received_default(app):
app.config.REQUEST_MAX_SIZE = 1 @app.route("/1") async def handler2(request): return text("OK") response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Error: Payload Too Large"
def test_payload_too_large_at_data_received_default(app): app.config.REQUEST_MAX_SIZE = 1 @app.route("/1") async def handler2(request): return text("OK") response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Error: Payload Too...
sliderSun/sanic
tests/test_payload_too_large.py
0c799f8bf7fa06f562908a2f
function
simple
app.route("/1") async def handler2(request): return text("OK") response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Error: Payload Too Large" def test_payload_too_large_at_on_header_default(app):
app.config.REQUEST_MAX_SIZE = 500 @app.post("/1") async def handler3(request): return text("OK") data = "a" * 1000 response = app.test_client.post("/1", gather_request=False, data=data) assert response.status == 413 assert response.text == "Error: Payload Too Large"
def test_payload_too_large_at_on_header_default(app): app.config.REQUEST_MAX_SIZE = 500 @app.post("/1") async def handler3(request): return text("OK") data = "a" * 1000 response = app.test_client.post("/1", gather_request=False, data=data) assert response.status == 413 assert respo...
sliderSun/sanic
tests/test_payload_too_large.py
aba4a5bf6101c7132f38669d
function
simple
, [y_true, y_pred], tf.float32) return loss def distance_metric(vec1, vec2): # euclidean distance distance = np.square(vec1-vec2) distance = np.sum(distance) return distance def deep_metric_loss_py(y_true, y_pred):
pos_embedding = y_pred[y_true>0] neg_embedding = y_pred[y_true==0] pos_distance = 0 count = 0 for i in range(len(pos_embedding)): for k in range(i + 1, len(pos_embedding)): pos_distance += distance_metric(pos_embedding[i], pos_embedding[k]) count+=1 pos_distance...
def deep_metric_loss_py(y_true, y_pred): pos_embedding = y_pred[y_true>0] neg_embedding = y_pred[y_true==0] pos_distance = 0 count = 0 for i in range(len(pos_embedding)): for k in range(i + 1, len(pos_embedding)): pos_distance += distance_metric(pos_embedding[i], pos_embedding[...
KerrWu/fewShotPASI
utils/loss.py
3a4bcbb4e55bc23ddb4a34f6
function
simple
target) grc.codegen(opt_mod["main"]) except tvm.TVMError: compiler = relay.vm.VMCompiler() if params: compiler.set_params(params) compiler.lower(mod, target=target) def extract_from_program(mod, params, target, target_host=None, ops=None):
""" Extract tuning tasks from a relay program. This function is the single program version of extract_from_multiple_program. Parameters ---------- mod: tvm.IRModule or relay.function.Function The module or function to tune params: dict of str to numpy array The associated param...
def extract_from_program(mod, params, target, target_host=None, ops=None): """ Extract tuning tasks from a relay program. This function is the single program version of extract_from_multiple_program. Parameters ---------- mod: tvm.IRModule or relay.function.Function The module or function ...
heweiwill/incubator-tvm
python/tvm/autotvm/task/relay_integration.py
09c8931fd30901662c5d2eca
function
simple
% copy-paste of implementation by @MerryMercy """ import threading import logging import tvm from .task import create from .topi_integration import TaskExtractEnv logger = logging.getLogger('autotvm') # TODO(moreau89) find a more elegant way to lower for VTAs def _lower(mod, target, params):
""" Helper to lower VTA properly. """ # pylint: disable=import-outside-toplevel from tvm import relay from tvm.relay.backend import graph_runtime_codegen if hasattr(target, 'device_name') and target.device_name == "vta": with relay.build_config(opt_level=3, disabled_pass={"AlterOpLayout...
def _lower(mod, target, params): """ Helper to lower VTA properly. """ # pylint: disable=import-outside-toplevel from tvm import relay from tvm.relay.backend import graph_runtime_codegen if hasattr(target, 'device_name') and target.device_name == "vta": with relay....
heweiwill/incubator-tvm
python/tvm/autotvm/task/relay_integration.py
d8fa9e3f247116483f4ee5e9
function
simple
params: dict of str to numpy array The associated parameters of the program target: tvm.target.Target The compilation target target_host: tvm.target.Target The host compilation target ops: List[relay.op.Op] or None List of relay ops to be tuned. If not specified, all tunable...
""" Extract tuning tasks from multiple relay programs. This function collects tuning tasks by building a list of programs with a "tracing" target and tracing all the calls to topi. Parameters ---------- mods: List[tvm.IRModule] or List[relay.function.Function] The list of modules or fu...
def extract_from_multiple_program(mods, params, target, target_host=None, ops=None): """ Extract tuning tasks from multiple relay programs. This function collects tuning tasks by building a list of programs with a "tracing" target and tracing all the calls to topi. Parameters ---------- mods: ...
heweiwill/incubator-tvm
python/tvm/autotvm/task/relay_integration.py
393d4f7108a0654a2f529411
function
simple
orch.utils.pytorch_util import set_gpu_mode import argparse import joblib import uuid import json from robolearn.utils.logging import logger from robolearn_gym_envs.pybullet import Pusher2D3DofGoalCompoEnv from robolearn_gym_envs.pybullet import CogimonLocomotionBulletEnv filename = str(uuid.uuid4()) def simulate_po...
data = joblib.load(args.file) if args.deterministic: print('Using the deterministic version of the policy.') policy = data['policy'] else: print('Using the stochastic policy.') policy = data['exploration_policy'] # env = data['env'] # env = NormalizedBoxEnv(gym.make(...
def simulate_policy(args): data = joblib.load(args.file) if args.deterministic: print('Using the deterministic version of the policy.') policy = data['policy'] else: print('Using the stochastic policy.') policy = data['exploration_policy'] # env = data['env'] # env =...
domingoesteban/robolearn
scripts/sim_policy_robolearn.py
4e7be0590a796c085eb51148
function
simple
_id][word_id] label = data[1][word_id] doc_encoded_labels.append(int(label)) last_word_id = word_id labels.append(doc_encoded_labels) tokenized_inputs["labels"] = labels return tokenized_inputs def to_dataset(data,stride=0):
labels, token_type_ids, input_ids, attention_masks = [],[],[],[] for item in tqdm(data): result = tokenize_and_align_data(item,stride=stride) labels += result['labels'] input_ids += result['input_ids'] attention_masks += result['attention_mask'] return Dataset...
def to_dataset(data,stride=0): labels, token_type_ids, input_ids, attention_masks = [],[],[],[] for item in tqdm(data): result = tokenize_and_align_data(item,stride=stride) labels += result['labels'] input_ids += result['input_ids'] attention_masks += result['atte...
jordimas/fullstop-deep-punctuation-prediction
baseline_xlm-roberta.py
8eb35bb7ee7cf373ed3fcbf5
function
simple
(train_data,stride=100) del train_data print("tokenize validation data") val_data = val_data[:int(len(val_data)*data_factor)] # limit data to x% tokenized_dataset_val = to_dataset(val_data) del val_data ## metrics def compute_metrics_sklearn(pred):
mask = np.less(pred.label_ids,0) # mask out -100 values labels = ma.masked_array(pred.label_ids,mask).compressed() preds = ma.masked_array(pred.predictions.argmax(-1),mask).compressed() precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='binary') acc = accuracy...
def compute_metrics_sklearn(pred): mask = np.less(pred.label_ids,0) # mask out -100 values labels = ma.masked_array(pred.label_ids,mask).compressed() preds = ma.masked_array(pred.predictions.argmax(-1),mask).compressed() precision, recall, f1, _ = precision_recall_fscore_support(labels, preds,...
jordimas/fullstop-deep-punctuation-prediction
baseline_xlm-roberta.py
768d720e2302e015b354c177
function
simple
_data.zip","train","fr") train_data += load("data/sepp_nlg_2021_train_dev_data.zip","train","it") random.shuffle(train_data) random.shuffle(val_data) ## tokenize data tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, strip_accent=False) def tokenize_and_align_data(data,stride=0):
tokenizer_settings = {'is_split_into_words':True,'return_offsets_mapping':True, 'padding':False, 'truncation':True, 'stride':stride, 'max_length':tokenizer.model_max_length, 'return_overflowing_tokens':True} tokenized_inputs = tokenizer(data[0], **tokeni...
def tokenize_and_align_data(data,stride=0): tokenizer_settings = {'is_split_into_words':True,'return_offsets_mapping':True, 'padding':False, 'truncation':True, 'stride':stride, 'max_length':tokenizer.model_max_length, 'return_overflowing_tokens':True} to...
jordimas/fullstop-deep-punctuation-prediction
baseline_xlm-roberta.py
e18c0857362b509847373a1e
function
simple
.MAP_PLASMID_PATH.keys() if k.startswith('Lox')] index_kw = {'mod_keys':batch.MAP_MOD_TYPE.keys(), 'assembly_keys':batch.MAP_ASSEMBLY_METHOD.keys(), 'marker_keys':marker_keys} @app.route('/', methods=['GET', 'POST']) def index():
return render_template('index.html', **index_kw)
@app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html', **index_kw)
thomasvstevens/locusmod
app.py
244566e86cbd5f3b1d6061e6
function
simple
_idt_csv() b.write_plasmids_zip(request.form['start_plasmids']) b.write_loci_zip() rows = b.list_operations() return render_template('download.html', files=files, rows=rows) return render_template('index.html', **index_kw) def test():
with app.test_request_context('/', method='GET'): assert request.path == '/' assert request.method == 'GET' with app.test_request_context('/', method='POST'): assert request.path == '/download' assert request.method == 'POST'
def test(): with app.test_request_context('/', method='GET'): assert request.path == '/' assert request.method == 'GET' with app.test_request_context('/', method='POST'): assert request.path == '/download' assert request.method == 'POST'
thomasvstevens/locusmod
app.py
4b0405c130f304380bfe2a15
function
simple
.keys(), 'assembly_keys':batch.MAP_ASSEMBLY_METHOD.keys(), 'marker_keys':marker_keys} @app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html', **index_kw) @app.route('/download', methods=['GET', 'POST']) def download():
if request.method == 'POST': batch_kw = {k:v for k,v in request.form.items() if not k.startswith('start')} b = batch.Batch(**batch_kw) shutil.rmtree(batch.paths.OUTPUT_PREFIX) os.mkdir(batch.paths.OUTPUT_PREFIX) b.write_primers_csv() b.assign_numbers(r...
@app.route('/download', methods=['GET', 'POST']) def download(): if request.method == 'POST': batch_kw = {k:v for k,v in request.form.items() if not k.startswith('start')} b = batch.Batch(**batch_kw) shutil.rmtree(batch.paths.OUTPUT_PREFIX) os.mkdir(batch.paths.OUTPUT...
thomasvstevens/locusmod
app.py
c126a9199ba723fb7f18f508
function
simple
ply.github.com" name = os.environ["GITHUB_ACTOR"] return email, name def get_repo_url(token, github_repository): return "https://x-access-token:%s@github.com/%s" % (token, github_repository) def checkout_branch(git, remote_exists, branch):
if remote_exists: print("Checking out branch '%s'" % branch) git.stash("--include-untracked") git.checkout(branch) try: git.stash("pop") except BaseException: git.checkout("--theirs", ".") git.reset() else: print("Creating new b...
def checkout_branch(git, remote_exists, branch): if remote_exists: print("Checking out branch '%s'" % branch) git.stash("--include-untracked") git.checkout(branch) try: git.stash("pop") except BaseException: git.checkout("--theirs", ".") gi...
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
0c916ae1c3886d05db7e3f8a
function
simple
.stash("pop") except BaseException: git.checkout("--theirs", ".") git.reset() else: print("Creating new branch '%s'" % branch) git.checkout("HEAD", b=branch) def push_changes(git, token, github_repository, branch, commit_message):
git.add("-A") print("author_name=%s, author_email=%s, committer_name=%s, committer_email=%s" % ( author_name, author_email, committer_name, committer_email)) git.commit(m=commit_message, author="%s <%s>" %(author_name, author_email), committer_name=committer_name, commi...
def push_changes(git, token, github_repository, branch, commit_message): git.add("-A") print("author_name=%s, author_email=%s, committer_name=%s, committer_email=%s" % ( author_name, author_email, committer_name, committer_email)) git.commit(m=commit_message, author="%s <%s>" %(author_name, author_e...
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
6744bdb411ba38d6fbfdcc00
function
simple
_EVENT_NAME"]) print(json.dumps(github_event, sort_keys=True, indent=2)) return github_event def get_head_short_sha1(repo): return repo.git.rev_parse("--short", "HEAD") def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits): return "".join(random.choice(chars) for _ in range(size))
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
2146dbb827eb9430ada58eff
function
simple
committer_name, committer_email=committer_email) repo_url = get_repo_url(token, github_repository) return git.push("-f", repo_url, f"HEAD:refs/heads/{branch}") def cs_string_to_list(str): # Split the comma separated string into a list
l = [i.strip() for i in str.split(",")] # Remove empty strings return list(filter(None, l))
def cs_string_to_list(str): # Split the comma separated string into a list l = [i.strip() for i in str.split(",")] # Remove empty strings return list(filter(None, l))
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
a884e25d9d9c6fec791d62c0
function
simple
# Split the comma separated string into a list l = [i.strip() for i in str.split(",")] # Remove empty strings return list(filter(None, l)) def create_project_card(github_repo, project_name, project_column_name, pull_request): # Locate the project by name
project = None for project_item in github_repo.get_projects("all"): if project_item.name == project_name: project = project_item break if not project: print("::warning::Project not found. Unable to create project card.") return # Locate the column by nam...
def create_project_card(github_repo, project_name, project_column_name, pull_request): # Locate the project by name project = None for project_item in github_repo.get_projects("all"): if project_item.name == project_name: project = project_item break if not project: ...
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
7e70cacd8fc52ee0b529f290
function
simple
_event def get_head_short_sha1(repo): return repo.git.rev_parse("--short", "HEAD") def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits): return "".join(random.choice(chars) for _ in range(size)) def remote_branch_exists(repo, branch):
for ref in repo.remotes.origin.refs: if ref.name == ("origin/%s" % branch): return True return False
def remote_branch_exists(repo, branch): for ref in repo.remotes.origin.refs: if ref.name == ("origin/%s" % branch): return True return False
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
1f66f1c8bea218bfa4d6f3e2
function
simple
): return "".join(random.choice(chars) for _ in range(size)) def remote_branch_exists(repo, branch): for ref in repo.remotes.origin.refs: if ref.name == ("origin/%s" % branch): return True return False def get_author_default(event_name, event_data):
if event_name == "push": email = "{head_commit[author][email]}".format(**event_data) name = "{head_commit[author][name]}".format(**event_data) else: email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com" name = os.environ["GITHUB_ACTOR"] return email, name
def get_author_default(event_name, event_data): if event_name == "push": email = "{head_commit[author][email]}".format(**event_data) name = "{head_commit[author][name]}".format(**event_data) else: email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com" name = os.environ[...
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
b9ab27fbf51a7cbb7944b6bd
function
simple
= "{head_commit[author][name]}".format(**event_data) else: email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com" name = os.environ["GITHUB_ACTOR"] return email, name def get_repo_url(token, github_repository):
return "https://x-access-token:%s@github.com/%s" % (token, github_repository)
def get_repo_url(token, github_repository): return "https://x-access-token:%s@github.com/%s" % (token, github_repository)
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
bf947ae6e3f62729a9dc2704
function
simple
_event_path) as f: github_event = json.load(f) if bool(os.environ.get("DEBUG_EVENT")): print(os.environ["GITHUB_EVENT_NAME"]) print(json.dumps(github_event, sort_keys=True, indent=2)) return github_event def get_head_short_sha1(repo):
return repo.git.rev_parse("--short", "HEAD")
def get_head_short_sha1(repo): return repo.git.rev_parse("--short", "HEAD")
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
aec8ed00bcee01f89ce1866a
function
simple
to show the support site with the open browser dialog.") Debug.Log("Failed to show the support site with the open browser dialog.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__) def _VisitNeonOceanSite (_connection: int = None) -> None:
try: Generic.ShowOpenBrowserDialog(Websites.GetNOMainURL()) except: output = commands.CheatOutput(_connection) output("Failed to show the NeonOcean site with the open browser dialog.") Debug.Log("Failed to show the NeonOcean site with the open browser dialog.", This.Mod.Namespace, Debug.LogLevels.Exception, ...
def _VisitNeonOceanSite (_connection: int = None) -> None: try: Generic.ShowOpenBrowserDialog(Websites.GetNOMainURL()) except: output = commands.CheatOutput(_connection) output("Failed to show the NeonOcean site with the open browser dialog.") Debug.Log("Failed to show the NeonOcean site with the open browse...
NeonOcean/Order
Python/NeonOcean.S4.Order/NeonOcean/S4/Order/Console/Interactions/Global.py
eab9cdc4323666966e5e0c39
function
simple
import Debug, LoadingShared, This, Websites from NeonOcean.S4.Order.Console import Command from NeonOcean.S4.Order.UI import Generic from sims4 import commands SupportNeonOceanCommand: Command.ConsoleCommand VisitNeonOceanSiteCommand: Command.ConsoleCommand def _Setup () -> None:
global SupportNeonOceanCommand, VisitNeonOceanSiteCommand commandPrefix = This.Mod.Namespace.lower() + ".global" # type: str # noinspection SpellCheckingInspection SupportNeonOceanCommand = Command.ConsoleCommand(_SupportNeonOcean, commandPrefix + ".support_neonocean") # noinspection SpellCheckingInspection Vi...
def _Setup () -> None: global SupportNeonOceanCommand, VisitNeonOceanSiteCommand commandPrefix = This.Mod.Namespace.lower() + ".global" # type: str # noinspection SpellCheckingInspection SupportNeonOceanCommand = Command.ConsoleCommand(_SupportNeonOcean, commandPrefix + ".support_neonocean") # noinspection Spel...
NeonOcean/Order
Python/NeonOcean.S4.Order/NeonOcean/S4/Order/Console/Interactions/Global.py
8fff3d3675c8bac133737682
function
simple
_neonocean_site") def _OnStart (cause: LoadingShared.LoadingCauses) -> None: if cause: pass SupportNeonOceanCommand.RegisterCommand() VisitNeonOceanSiteCommand.RegisterCommand() def _OnStop (cause: LoadingShared.UnloadingCauses) -> None:
if cause: pass SupportNeonOceanCommand.UnregisterCommand() VisitNeonOceanSiteCommand.UnregisterCommand()
def _OnStop (cause: LoadingShared.UnloadingCauses) -> None: if cause: pass SupportNeonOceanCommand.UnregisterCommand() VisitNeonOceanSiteCommand.UnregisterCommand()
NeonOcean/Order
Python/NeonOcean.S4.Order/NeonOcean/S4/Order/Console/Interactions/Global.py
98ffafc76b7aaf8e954fddd9
function
simple
Command.RegisterCommand() def _OnStop (cause: LoadingShared.UnloadingCauses) -> None: if cause: pass SupportNeonOceanCommand.UnregisterCommand() VisitNeonOceanSiteCommand.UnregisterCommand() def _SupportNeonOcean (_connection: int = None) -> None:
try: Generic.ShowOpenBrowserDialog(Websites.GetNOSupportURL()) except: output = commands.CheatOutput(_connection) output("Failed to show the support site with the open browser dialog.") Debug.Log("Failed to show the support site with the open browser dialog.", This.Mod.Namespace, Debug.LogLevels.Exception, g...
def _SupportNeonOcean (_connection: int = None) -> None: try: Generic.ShowOpenBrowserDialog(Websites.GetNOSupportURL()) except: output = commands.CheatOutput(_connection) output("Failed to show the support site with the open browser dialog.") Debug.Log("Failed to show the support site with the open browser d...
NeonOcean/Order
Python/NeonOcean.S4.Order/NeonOcean/S4/Order/Console/Interactions/Global.py
ced351305cac7d93f19d88d6
function
simple
Ocean, commandPrefix + ".support_neonocean") # noinspection SpellCheckingInspection VisitNeonOceanSiteCommand = Command.ConsoleCommand(_VisitNeonOceanSite, commandPrefix + ".visit_neonocean_site") def _OnStart (cause: LoadingShared.LoadingCauses) -> None:
if cause: pass SupportNeonOceanCommand.RegisterCommand() VisitNeonOceanSiteCommand.RegisterCommand()
def _OnStart (cause: LoadingShared.LoadingCauses) -> None: if cause: pass SupportNeonOceanCommand.RegisterCommand() VisitNeonOceanSiteCommand.RegisterCommand()
NeonOcean/Order
Python/NeonOcean.S4.Order/NeonOcean/S4/Order/Console/Interactions/Global.py
ab889d99789242588bf079a6
function
simple
assert result == 7 def test_can_find_highest_consecutive_list_sum_in_a_list(): result = highest_sum_list([3,5,3,4,6,7,4], 4) assert result == 21 def test_shuld_return_0_if_lis_is_empty():
result = highest_sum_list([],5) assert result == 0
def test_shuld_return_0_if_lis_is_empty(): result = highest_sum_list([],5) assert result == 0
mamaz/learn-stuffs-with-python
sliding_window/sliding_window_test.py
4e841b2b4aede8b7487885f0
function
simple
# We'll just put reasonable uniform priors on all the parameters. if not all(b[0] < v < b[1] for v, b in zip(p, bounds)): return -np.inf return 0 # The "foreground" linear likelihood: def lnlike_fg(p):
m, b, _, M, lnV = p model = m * x + b return -0.5 * (((model - y) / yerr) ** 2 + 2 * np.log(yerr))
def lnlike_fg(p): m, b, _, M, lnV = p model = m * x + b return -0.5 * (((model - y) / yerr) ** 2 + 2 * np.log(yerr))
fschmnn/pymuse
scripts/mcmc_outlier_pruning.py
7121141e5e67442debdb82f2
function
simple
like_bg(p): _, _, Q, M, lnV = p var = np.exp(lnV) + yerr**2 return -0.5 * ((M - y) ** 2 / var + np.log(var)) # Full probabilistic model. def lnprob(p):
m, b, Q, M, lnV = p # First check the prior. lp = lnprior(p) if not np.isfinite(lp): return -np.inf, None # Compute the vector of foreground likelihoods and include the q prior. ll_fg = lnlike_fg(p) arg1 = ll_fg + np.log(Q) # Compute the vector of background likeli...
def lnprob(p): m, b, Q, M, lnV = p # First check the prior. lp = lnprior(p) if not np.isfinite(lp): return -np.inf, None # Compute the vector of foreground likelihoods and include the q prior. ll_fg = lnlike_fg(p) arg1 = ll_fg + np.log(Q) # Compute the vector of ba...
fschmnn/pymuse
scripts/mcmc_outlier_pruning.py
8a4226981003971ae407b256
function
simple
m, b, _, M, lnV = p model = m * x + b return -0.5 * (((model - y) / yerr) ** 2 + 2 * np.log(yerr)) # The "background" outlier likelihood: def lnlike_bg(p):
_, _, Q, M, lnV = p var = np.exp(lnV) + yerr**2 return -0.5 * ((M - y) ** 2 / var + np.log(var))
def lnlike_bg(p): _, _, Q, M, lnV = p var = np.exp(lnV) + yerr**2 return -0.5 * ((M - y) ** 2 / var + np.log(var))
fschmnn/pymuse
scripts/mcmc_outlier_pruning.py
5758eda709cb6a9f3c3b59ce
function
simple
0.1, 1.9), (-0.9, 0.9), (0, 1), (-2.4, 2.4), (-7.2, 5.2)] def lnprior(p): # We'll just put reasonable uniform priors on all the parameters.
if not all(b[0] < v < b[1] for v, b in zip(p, bounds)): return -np.inf return 0
def lnprior(p): # We'll just put reasonable uniform priors on all the parameters. if not all(b[0] < v < b[1] for v, b in zip(p, bounds)): return -np.inf return 0
fschmnn/pymuse
scripts/mcmc_outlier_pruning.py
39ac77b657d6a3d2269f9ddf
function
simple
def freeze_as_str(path): """Freeze the given `path` and all .py scripts within it as a string, which will be compiled upon import. """ freeze_internal(KIND_AS_STR, path, None, 0) def freeze_as_mpy(path, script=None, opt=0):
"""Freeze the input (see above) by first compiling the .py scripts to .mpy files, then freezing the resulting .mpy files. """ freeze_internal(KIND_AS_MPY, path, script, opt)
def freeze_as_mpy(path, script=None, opt=0): """Freeze the input (see above) by first compiling the .py scripts to .mpy files, then freezing the resulting .mpy files. """ freeze_internal(KIND_AS_MPY, path, script, opt)
ljk53/micropython
tools/makemanifest.py
cc871602fca731e516d09043
function
simple
(path): ts_newest = 0 for dirpath, dirnames, filenames in os.walk(path, followlinks=True): for f in filenames: ts_newest = max(ts_newest, get_timestamp(os.path.join(dirpath, f))) return ts_newest def mkdir(filename):
path = os.path.dirname(filename) if not os.path.isdir(path): os.makedirs(path)
def mkdir(filename): path = os.path.dirname(filename) if not os.path.isdir(path): os.makedirs(path)
ljk53/micropython
tools/makemanifest.py
52804faf06b3dc73179a7a99
function
simple
, script, opt) ########################################################################### # Internal implementation KIND_AUTO = 0 KIND_AS_STR = 1 KIND_AS_MPY = 2 KIND_MPY = 3 VARS = {} manifest_list = [] class FreezeError(Exception): pass def system(cmd):
try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return 0, output except subprocess.CalledProcessError as er: return -1, er.output
def system(cmd): try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return 0, output except subprocess.CalledProcessError as er: return -1, er.output
ljk53/micropython
tools/makemanifest.py
e5ccf5d24b2fbeace5d5b3bc
function
simple
(Exception): pass def system(cmd): try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return 0, output except subprocess.CalledProcessError as er: return -1, er.output def convert_path(path): # Perform variable substituion.
for name, value in VARS.items(): path = path.replace("$({})".format(name), value) # Convert to absolute path (so that future operations don't rely on # still being chdir'ed). return os.path.abspath(path)
def convert_path(path): # Perform variable substituion. for name, value in VARS.items(): path = path.replace("$({})".format(name), value) # Convert to absolute path (so that future operations don't rely on # still being chdir'ed). return os.path.abspath(path)
ljk53/micropython
tools/makemanifest.py
def95016bcf1bacdaa324dfe
function
simple
CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import print_function import sys import os import subprocess ########################################################################### # Public functions to be use...
"""Include another manifest. The manifest argument can be a string (filename) or an iterable of strings. Relative paths are resolved with respect to the current manifest file. """ if not isinstance(manifest, str): for m in manifest: include(m) else: manifest = ...
def include(manifest): """Include another manifest. The manifest argument can be a string (filename) or an iterable of strings. Relative paths are resolved with respect to the current manifest file. """ if not isinstance(manifest, str): for m in manifest: include(m) el...
ljk53/micropython
tools/makemanifest.py
bbccba9a0d982e34d78b7f54
function
simple
, str): for m in manifest: include(m) else: manifest = convert_path(manifest) with open(manifest) as f: # Make paths relative to this manifest file while processing it. # Applies to includes and input files. prev_cwd = os.getcwd() o...
"""Freeze the input, automatically determining its type. A .py script will be compiled to a .mpy first then frozen, and a .mpy file will be frozen directly. `path` must be a directory, which is the base directory to search for files from. When importing the resulting frozen modules, the name of ...
def freeze(path, script=None, opt=0): """Freeze the input, automatically determining its type. A .py script will be compiled to a .mpy first then frozen, and a .mpy file will be frozen directly. `path` must be a directory, which is the base directory to search for files from. When importing the r...
ljk53/micropython
tools/makemanifest.py
eea9250a735bc40b10149de5
function
simple
return os.path.abspath(path) def get_timestamp(path, default=None): try: stat = os.stat(path) return stat.st_mtime except OSError: if default is None: raise FreezeError("cannot stat {}".format(path)) return default def get_timestamp_newest(path):
ts_newest = 0 for dirpath, dirnames, filenames in os.walk(path, followlinks=True): for f in filenames: ts_newest = max(ts_newest, get_timestamp(os.path.join(dirpath, f))) return ts_newest
def get_timestamp_newest(path): ts_newest = 0 for dirpath, dirnames, filenames in os.walk(path, followlinks=True): for f in filenames: ts_newest = max(ts_newest, get_timestamp(os.path.join(dirpath, f))) return ts_newest
ljk53/micropython
tools/makemanifest.py
05c9cd6c3daeecb28c7659cb
function
simple
ion. for name, value in VARS.items(): path = path.replace("$({})".format(name), value) # Convert to absolute path (so that future operations don't rely on # still being chdir'ed). return os.path.abspath(path) def get_timestamp(path, default=None):
try: stat = os.stat(path) return stat.st_mtime except OSError: if default is None: raise FreezeError("cannot stat {}".format(path)) return default
def get_timestamp(path, default=None): try: stat = os.stat(path) return stat.st_mtime except OSError: if default is None: raise FreezeError("cannot stat {}".format(path)) return default
ljk53/micropython
tools/makemanifest.py
e8eddfc1108364cbf1b43211
function
simple
`script` is a directory then all files in that directory will be frozen. `opt` is the optimisation level to pass to mpy-cross when compiling .py to .mpy. """ freeze_internal(KIND_AUTO, path, script, opt) def freeze_as_str(path):
"""Freeze the given `path` and all .py scripts within it as a string, which will be compiled upon import. """ freeze_internal(KIND_AS_STR, path, None, 0)
def freeze_as_str(path): """Freeze the given `path` and all .py scripts within it as a string, which will be compiled upon import. """ freeze_internal(KIND_AS_STR, path, None, 0)
ljk53/micropython
tools/makemanifest.py
d5f64fbc161a2c86daf742da
function
simple
): """Freeze the input (see above) by first compiling the .py scripts to .mpy files, then freezing the resulting .mpy files. """ freeze_internal(KIND_AS_MPY, path, script, opt) def freeze_mpy(path, script=None, opt=0):
"""Freeze the input (see above), which must be .mpy files that are frozen directly. """ freeze_internal(KIND_MPY, path, script, opt)
def freeze_mpy(path, script=None, opt=0): """Freeze the input (see above), which must be .mpy files that are frozen directly. """ freeze_internal(KIND_MPY, path, script, opt)
ljk53/micropython
tools/makemanifest.py
e5db5ad37e281654f67cd0c8
function
simple
def example_database(): spanner_client = spanner.Client() instance = spanner_client.instance(SPANNER_INSTANCE) database = instance.database('my-database-id') if not database.exists(): database.create() yield def test_quickstart(capsys, patch_instance, example_database):
quickstart.run_quickstart() out, _ = capsys.readouterr() assert '[1]' in out
def test_quickstart(capsys, patch_instance, example_database): quickstart.run_quickstart() out, _ = capsys.readouterr() assert '[1]' in out
yshalabi/python-docs-samples
spanner/cloud-client/quickstart_test.py
1716494b8c239c12e91bc6bb
function
simple
.instance def new_instance(self, unused_instance_name): return original_instance(self, SPANNER_INSTANCE) instance_patch = mock.patch( 'google.cloud.spanner.Client.instance', side_effect=new_instance, autospec=True) with instance_patch: yield @pytest.fixture def e...
spanner_client = spanner.Client() instance = spanner_client.instance(SPANNER_INSTANCE) database = instance.database('my-database-id') if not database.exists(): database.create() yield
@pytest.fixture def example_database(): spanner_client = spanner.Client() instance = spanner_client.instance(SPANNER_INSTANCE) database = instance.database('my-database-id') if not database.exists(): database.create() yield
yshalabi/python-docs-samples
spanner/cloud-client/quickstart_test.py
ea0b70705564da154ba5428d
function
simple
ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from google.cloud import spanner import mock import pytest import quickstart SPANNER_INSTANCE = os.environ['SPANNER_INSTANCE'] @pytest.fixture def patch_instance()...
original_instance = spanner.Client.instance def new_instance(self, unused_instance_name): return original_instance(self, SPANNER_INSTANCE) instance_patch = mock.patch( 'google.cloud.spanner.Client.instance', side_effect=new_instance, autospec=True) with instance_patch:...
@pytest.fixture def patch_instance(): original_instance = spanner.Client.instance def new_instance(self, unused_instance_name): return original_instance(self, SPANNER_INSTANCE) instance_patch = mock.patch( 'google.cloud.spanner.Client.instance', side_effect=new_instance, au...
yshalabi/python-docs-samples
spanner/cloud-client/quickstart_test.py
fbe2bebb82ce2ced52a0bb3a
function
simple
_TAG _LOGGER = _logging.getLogger(_MODULENAME) _LOGGER.debug('Something invoked :: {0}.'.format(_MODULENAME)) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- def createSettings(org='Amazon_Lumberyard', app='DCCsi',...
"""Sets up a settings .ini Returns a QSettings instance""" settings_folder = '{org}//{app}'.format(org=org, app=app) settings_name = '{tool}-{type}'.format(tool=tool, type=type) settings = QtCore.QSettings(QtCore.QSettings.IniFormat, QtCore.QSettings.UserScope, ...
def createSettings(org='Amazon_Lumberyard', app='DCCsi', tool='azpy', type='default'): """Sets up a settings .ini Returns a QSettings instance""" settings_folder = '{org}//{app}'.format(org=org, app=app) settings_name = '{tool}-{type}'.format(tool=tool, type=type) settings = Qt...
cypherdotXd/o3de
Gems/AtomLyIntegration/TechnicalArt/DccScriptingInterface/azpy/shared/ui/qt_settings.py
e7a2d639bdf1d3d010859768
function
simple
for i in frutas: lista_frutas.append(i) for i in numeros: lista_numeros.append(i) #Retornar una lista con los numero negativos """ Entradas: lista-list-->lista Salidas lista-list-->lista """ def eliminar_un_caracter(lista,elemento):
auxilar=[] for i in lista: a=i.replace(elemento,"") auxilar.append(a) return auxilar
def eliminar_un_caracter(lista,elemento): auxilar=[] for i in lista: a=i.replace(elemento,"") auxilar.append(a) return auxilar
DiegoC386/Taller-de-Funciones
Ejercicio_9.py
2abd21cdf0bde037493259d3
function
simple
""" Entradas: lista-list-->lista Salidas lista-list-->lista """ def eliminar_un_caracter(lista,elemento): auxilar=[] for i in lista: a=i.replace(elemento,"") auxilar.append(a) return auxilar def numeros_negativos(lista):
aux=[] for i in lista: if(float(i)<=0): aux.append(i) return aux
def numeros_negativos(lista): aux=[] for i in lista: if(float(i)<=0): aux.append(i) return aux
DiegoC386/Taller-de-Funciones
Ejercicio_9.py
864f609d343fc5fa41b6d16a
function
simple
.listdir()[0]) tar.close() u.close() stat = os.system('./configure --prefix=%s --disable-shared' % tdir) if stat != 0: return 0 stat = os.system('make') if stat != 0: return 0 stat = os.system('make install') if stat != 0: return 0 return(os.path.join(tdir,'include'), os.pa...
from numpy.distutils.misc_util import Configuration global tdir incdirs,libdirs,libs = get_gsl_info() tdir = None # if we need a temporary dir, this will be it if incdirs is None: print("I couldn't run the GNU Scientific Library (GSL) gsl-config script.") print("Would you like me to down...
def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration global tdir incdirs,libdirs,libs = get_gsl_info() tdir = None # if we need a temporary dir, this will be it if incdirs is None: print("I couldn't run the GNU Scientific Library (GSL) gsl-co...
emirkmo/snpy
snpy/CSPtemp/setup_old.py
11c663beb223caeceb5a1625
function
simple
cflags = p.readline(); p.close() cflags = cflags.split() for item in cflags: if item[0:2] == '-I': inc_dirs.append(item[2:]) return(inc_dirs, lib_dirs, libraries) def get_temp_GSL():
import urllib.request, urllib.parse, urllib.error, tarfile, io,tempfile global tdir u = urllib.request.urlopen('ftp://ftp.gnu.org/gnu/gsl/gsl-1.8.tar.gz') f = io.StringIO(u.read()) tar = tarfile.open(fileobj=f) tdir = tempfile.mkdtemp() cwd = os.pwd() os.chdir(tdir) tar.extractall() os.chd...
def get_temp_GSL(): import urllib.request, urllib.parse, urllib.error, tarfile, io,tempfile global tdir u = urllib.request.urlopen('ftp://ftp.gnu.org/gnu/gsl/gsl-1.8.tar.gz') f = io.StringIO(u.read()) tar = tarfile.open(fileobj=f) tdir = tempfile.mkdtemp() cwd = os.pwd() os.chdir(tdir) tar.ex...
emirkmo/snpy
snpy/CSPtemp/setup_old.py
e5fea7dde38b0227da374def
function
simple
"; "dataflow" for "dataflow" engine') def _add_environment_args(parser): """Add common environment args.""" parser.add_argument('-e', action='append', help="set environment variable e.g. VAR=value") def build_image_impl(image_name, no_cache=False, pull=False):
"""Build image.""" proj_is_base_image = is_base_image(image_name) if proj_is_base_image: image_project = 'oss-fuzz-base' dockerfile_dir = os.path.join('infra', 'base-images', image_name) else: image_project = 'oss-fuzz' if not check_project_exists(image_name): return False dockerfile...
def build_image_impl(image_name, no_cache=False, pull=False): """Build image.""" proj_is_base_image = is_base_image(image_name) if proj_is_base_image: image_project = 'oss-fuzz-base' dockerfile_dir = os.path.join('infra', 'base-images', image_name) else: image_project = 'oss-fuzz' if not check_...
devtty1er/oss-fuzz
infra/helper.py
4762b9ff80bccec4126f9b23
function
simple
)) def check_project_exists(project_name): """Checks if a project exists.""" if not os.path.exists(_get_project_dir(project_name)): print(project_name, 'does not exist', file=sys.stderr) return False return True def _check_fuzzer_exists(project_name, fuzzer_name):
"""Checks if a fuzzer exists.""" command = ['docker', 'run', '--rm'] command.extend(['-v', '%s:/out' % _get_output_dir(project_name)]) command.append('ubuntu:16.04') command.extend(['/bin/bash', '-c', 'test -f /out/%s' % fuzzer_name]) try: subprocess.check_call(command) except subprocess.CalledProce...
def _check_fuzzer_exists(project_name, fuzzer_name): """Checks if a fuzzer exists.""" command = ['docker', 'run', '--rm'] command.extend(['-v', '%s:/out' % _get_output_dir(project_name)]) command.append('ubuntu:16.04') command.extend(['/bin/bash', '-c', 'test -f /out/%s' % fuzzer_name]) try: subproces...
devtty1er/oss-fuzz
infra/helper.py
3afd9463a1645ceb11f6e1c6
function
simple
'%s:/out' % _get_output_dir(args.project_name), '-t', 'gcr.io/oss-fuzz-base/base-runner', 'run_fuzzer', args.fuzzer_name, ] + args.fuzzer_args return docker_run(run_args) def reproduce(args):
"""Reproduce a specific test case from a specific project.""" return reproduce_impl(args.project_name, args.fuzzer_name, args.valgrind, args.e, args.fuzzer_args, args.testcase_path)
def reproduce(args): """Reproduce a specific test case from a specific project.""" return reproduce_impl(args.project_name, args.fuzzer_name, args.valgrind, args.e, args.fuzzer_args, args.testcase_path)
devtty1er/oss-fuzz
infra/helper.py
c95e691a5df21695b3de2e80
function
simple
subprocess.check_call(command) os.remove(archive_path) else: # Sync the working corpus copy if a minimized backup is not available. corpus_url = CORPUS_URL_FORMAT.format(project_name=project_name, fuzz_target=fuzz_target) command = ['gsutil', '-m', '-q', '...
"""Download most recent corpora from GCS for the given project.""" if not check_project_exists(args.project_name): return 1 try: with open(os.devnull, 'w') as stdout: subprocess.check_call(['gsutil', '--version'], stdout=stdout) except OSError: print( 'ERROR: gsutil not found. Please ...
def download_corpora(args): """Download most recent corpora from GCS for the given project.""" if not check_project_exists(args.project_name): return 1 try: with open(os.devnull, 'w') as stdout: subprocess.check_call(['gsutil', '--version'], stdout=stdout) except OSError: print( 'ERRO...
devtty1er/oss-fuzz
infra/helper.py
2fdf51e8fa15a86aa4c23209
function
simple
command.append('--pull') command.extend(build_args) print('Running:', _get_command_string(command)) try: subprocess.check_call(command) except subprocess.CalledProcessError: print('docker build failed.', file=sys.stderr) return False return True def docker_pull(image):
"""Call `docker pull`.""" command = ['docker', 'pull', image] print('Running:', _get_command_string(command)) try: subprocess.check_call(command) except subprocess.CalledProcessError: print('docker pull failed.', file=sys.stderr) return False return True
def docker_pull(image): """Call `docker pull`.""" command = ['docker', 'pull', image] print('Running:', _get_command_string(command)) try: subprocess.check_call(command) except subprocess.CalledProcessError: print('docker pull failed.', file=sys.stderr) return False return True
devtty1er/oss-fuzz
infra/helper.py
0f059ccf7d32492e830eeca1
function
simple
the given project.""" dockerfile_path = get_dockerfile_path(project_name) with open(dockerfile_path) as file_handle: lines = file_handle.readlines() return workdir_from_lines(lines, default=os.path.join('/src', project_name)) def docker_run(run_args, print_output=True):
"""Call `docker run`.""" command = ['docker', 'run', '--rm', '--privileged'] # Support environments with a TTY. if sys.stdin.isatty(): command.append('-i') command.extend(run_args) print('Running:', _get_command_string(command)) stdout = None if not print_output: stdout = open(os.devnull, 'w'...
def docker_run(run_args, print_output=True): """Call `docker run`.""" command = ['docker', 'run', '--rm', '--privileged'] # Support environments with a TTY. if sys.stdin.isatty(): command.append('-i') command.extend(run_args) print('Running:', _get_command_string(command)) stdout = None if not pr...
devtty1er/oss-fuzz
infra/helper.py
5b17bfd7c717f812dc561bdd
function
simple
return os.path.join(BUILD_DIR, 'out', project_name) def _get_work_dir(project_name=''): """Returns path to /work directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'work', project_name) def _get_project_language(project_name):
"""Returns project language.""" project_yaml_path = os.path.join(OSS_FUZZ_DIR, 'projects', project_name, 'project.yaml') with open(project_yaml_path) as file_handle: content = file_handle.read() for line in content.splitlines(): match = PROJECT_LANGUAGE_REGEX.match...
def _get_project_language(project_name): """Returns project language.""" project_yaml_path = os.path.join(OSS_FUZZ_DIR, 'projects', project_name, 'project.yaml') with open(project_yaml_path) as file_handle: content = file_handle.read() for line in content.splitlines(): ...
devtty1er/oss-fuzz
infra/helper.py
ad624741c2d08b454d37ff06
function
simple
a shell escaped command string.""" return ' '.join(pipes.quote(part) for part in command) def _get_project_dir(project_name): """Returns path to the project.""" return os.path.join(OSS_FUZZ_DIR, 'projects', project_name) def get_dockerfile_path(project_name):
"""Returns path to the project Dockerfile.""" return os.path.join(_get_project_dir(project_name), 'Dockerfile')
def get_dockerfile_path(project_name): """Returns path to the project Dockerfile.""" return os.path.join(_get_project_dir(project_name), 'Dockerfile')
devtty1er/oss-fuzz
infra/helper.py
a73f7b78c8010f46223cb6a7
function
simple
uzz_target: run_args.append(args.fuzz_target) exit_code = docker_run(run_args) if exit_code == 0: print('Successfully generated clang code coverage report.') else: print('Failed to generate clang code coverage report.') return exit_code def run_fuzzer(args):
"""Runs a fuzzer in the container.""" if not check_project_exists(args.project_name): return 1 if not _check_fuzzer_exists(args.project_name, args.fuzzer_name): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, 'SANITIZER=' + args.sanitizer, 'RUN_FUZZER_MODE=interactive', ] if a...
def run_fuzzer(args): """Runs a fuzzer in the container.""" if not check_project_exists(args.project_name): return 1 if not _check_fuzzer_exists(args.project_name, args.fuzzer_name): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, 'SANITIZER=' + args.sanitizer, 'RUN_FUZZER_MODE=int...
devtty1er/oss-fuzz
infra/helper.py
9b1ed29b939fc59b2ef8e707
function
simple
_get_fuzz_targets(project_name): """Return names of fuzz targest build in the project's /out directory.""" fuzz_targets = [] for name in os.listdir(_get_output_dir(project_name)): if name.startswith('afl-'): continue path = os.path.join(_get_output_dir(project_name), name) if os.path.isfile(pa...
"""Download the latest corpus for the given fuzz target.""" corpus_dir = os.path.join(base_corpus_dir, fuzz_target) if not os.path.exists(corpus_dir): os.makedirs(corpus_dir) if not fuzz_target.startswith(project_name): fuzz_target = '%s_%s' % (project_name, fuzz_target) corpus_backup_url = CORPUS_B...
def _get_latest_corpus(project_name, fuzz_target, base_corpus_dir): """Download the latest corpus for the given fuzz target.""" corpus_dir = os.path.join(base_corpus_dir, fuzz_target) if not os.path.exists(corpus_dir): os.makedirs(corpus_dir) if not fuzz_target.startswith(project_name): fuzz_target = '...
devtty1er/oss-fuzz
infra/helper.py
2185291fb4ca626693ea2594
function
simple
(_get_project_dir(project_name), 'Dockerfile') def _get_corpus_dir(project_name=''): """Returns path to /corpus directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'corpus', project_name) def _get_output_dir(project_name=''):
"""Returns path to /out directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'out', project_name)
def _get_output_dir(project_name=''): """Returns path to /out directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'out', project_name)
devtty1er/oss-fuzz
infra/helper.py
b712dff63587c914a728ef59
function
simple
.group(1) workdir = workdir.replace('$SRC', '/src') if not os.path.isabs(workdir): workdir = os.path.join('/src', workdir) return os.path.normpath(workdir) return default def _workdir_from_dockerfile(project_name):
"""Parse WORKDIR from the Dockerfile for the given project.""" dockerfile_path = get_dockerfile_path(project_name) with open(dockerfile_path) as file_handle: lines = file_handle.readlines() return workdir_from_lines(lines, default=os.path.join('/src', project_name))
def _workdir_from_dockerfile(project_name): """Parse WORKDIR from the Dockerfile for the given project.""" dockerfile_path = get_dockerfile_path(project_name) with open(dockerfile_path) as file_handle: lines = file_handle.readlines() return workdir_from_lines(lines, default=os.path.join('/src', project_na...
devtty1er/oss-fuzz
infra/helper.py
7ff97daf949531580fa3101d
function
simple
_out_dir, '-v', '%s:/work' % project_work_dir ] + _env_to_docker_args(env) + ['gcr.io/oss-fuzz-base/base-msan-builder', 'patch_build.py', '/out']) return 0 def build_fuzzers(args):
"""Build fuzzers.""" return build_fuzzers_impl(args.project_name, args.clean, args.engine, args.sanitizer, args.architecture, args.e, args.source_path)
def build_fuzzers(args): """Build fuzzers.""" return build_fuzzers_impl(args.project_name, args.clean, args.engine, args.sanitizer, args.architecture, args.e, args.source_path)
devtty1er/oss-fuzz
infra/helper.py
6d6fb2ea0c62b98f02d56bfc
function
simple
if args.command == 'pull_images': return pull_images(args) return 0 def is_base_image(image_name): """Checks if the image name is a base image.""" return os.path.exists(os.path.join('infra', 'base-images', image_name)) def check_project_exists(project_name):
"""Checks if a project exists.""" if not os.path.exists(_get_project_dir(project_name)): print(project_name, 'does not exist', file=sys.stderr) return False return True
def check_project_exists(project_name): """Checks if a project exists.""" if not os.path.exists(_get_project_dir(project_name)): print(project_name, 'does not exist', file=sys.stderr) return False return True
devtty1er/oss-fuzz
infra/helper.py
da7bdc9f6955595c4b48e735
function
simple
, 'does not seem to exist. Please run build_fuzzers first.', file=sys.stderr) return False return True def _get_absolute_path(path): """Returns absolute path with user expansion.""" return os.path.abspath(os.path.expanduser(path)) def _get_command_string(command):
"""Returns a shell escaped command string.""" return ' '.join(pipes.quote(part) for part in command)
def _get_command_string(command): """Returns a shell escaped command string.""" return ' '.join(pipes.quote(part) for part in command)
devtty1er/oss-fuzz
infra/helper.py
c600e98b073754220dd83327
function
simple
not print_output: stdout = open(os.devnull, 'w') try: subprocess.check_call(command, stdout=stdout, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as error: return error.returncode return 0 def docker_build(build_args, pull=False):
"""Call `docker build`.""" command = ['docker', 'build'] if pull: command.append('--pull') command.extend(build_args) print('Running:', _get_command_string(command)) try: subprocess.check_call(command) except subprocess.CalledProcessError: print('docker build failed.', file=sys.stderr) r...
def docker_build(build_args, pull=False): """Call `docker build`.""" command = ['docker', 'build'] if pull: command.append('--pull') command.extend(build_args) print('Running:', _get_command_string(command)) try: subprocess.check_call(command) except subprocess.CalledProcessError: print('doc...
devtty1er/oss-fuzz
infra/helper.py
48c8b93a88d362f3b065190d
function
simple
.command == 'coverage': return coverage(args) if args.command == 'reproduce': return reproduce(args) if args.command == 'shell': return shell(args) if args.command == 'pull_images': return pull_images(args) return 0 def is_base_image(image_name):
"""Checks if the image name is a base image.""" return os.path.exists(os.path.join('infra', 'base-images', image_name))
def is_base_image(image_name): """Checks if the image name is a base image.""" return os.path.exists(os.path.join('infra', 'base-images', image_name))
devtty1er/oss-fuzz
infra/helper.py
0e60c5222087f54fc5ac59fe
function
simple
return reproduce_impl(args.project_name, args.fuzzer_name, args.valgrind, args.e, args.fuzzer_args, args.testcase_path) def reproduce_impl( # pylint: disable=too-many-arguments project_name, fuzzer_name, valgrind, env_to_add, fuzzer_args, testcase_path, runner=doc...
"""Reproduces a testcase in the container.""" if not check_project_exists(project_name): return err_result if not _check_fuzzer_exists(project_name, fuzzer_name): return err_result debugger = '' env = [] image_name = 'base-runner' if valgrind: debugger = 'valgrind --tool=memcheck --track-or...
def reproduce_impl( # pylint: disable=too-many-arguments project_name, fuzzer_name, valgrind, env_to_add, fuzzer_args, testcase_path, runner=docker_run, err_result=1): """Reproduces a testcase in the container.""" if not check_project_exists(project_name): return err_result i...
devtty1er/oss-fuzz
infra/helper.py
cc96d439dc4b37868e252709
function
simple
'-v', '%s:/out' % _get_output_dir(project_name), '-v', '%s:/testcase' % _get_absolute_path(testcase_path), '-t', 'gcr.io/oss-fuzz-base/%s' % image_name, 'reproduce', fuzzer_name, '-runs=100', ] + fuzzer_args return runner(run_args) def generate(args):
"""Generate empty project files.""" if len(args.project_name) > MAX_PROJECT_NAME_LENGTH: print('Project name needs to be less than or equal to %d characters.' % MAX_PROJECT_NAME_LENGTH, file=sys.stderr) return 1 if not VALID_PROJECT_NAME_REGEX.match(args.project_name): print('Inva...
def generate(args): """Generate empty project files.""" if len(args.project_name) > MAX_PROJECT_NAME_LENGTH: print('Project name needs to be less than or equal to %d characters.' % MAX_PROJECT_NAME_LENGTH, file=sys.stderr) return 1 if not VALID_PROJECT_NAME_REGEX.match(args.project_na...
devtty1er/oss-fuzz
infra/helper.py
29b23d3b60d65e5190a632fb
function
simple
file_handle.write(templates.DOCKER_TEMPLATE % template_args) build_sh_path = os.path.join(directory, 'build.sh') with open(build_sh_path, 'w') as file_handle: file_handle.write(templates.BUILD_TEMPLATE % template_args) os.chmod(build_sh_path, 0o755) return 0 def shell(args):
"""Runs a shell within a docker image.""" if not build_image_impl(args.project_name): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, 'SANITIZER=' + args.sanitizer, 'ARCHITECTURE=' + args.architecture, ] if args.e: env += args.e if is_base_image(args.project_name): image_p...
def shell(args): """Runs a shell within a docker image.""" if not build_image_impl(args.project_name): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, 'SANITIZER=' + args.sanitizer, 'ARCHITECTURE=' + args.architecture, ] if args.e: env += args.e if is_base_image(args.project_n...
devtty1er/oss-fuzz
infra/helper.py
ec49abdc6985b47aeb69901c
function
simple
_path) as file_handle: content = file_handle.read() for line in content.splitlines(): match = PROJECT_LANGUAGE_REGEX.match(line) if match: return match.group(1) return None def _add_architecture_args(parser, choices=('x86_64', 'i386')):
"""Add common architecture args.""" parser.add_argument('--architecture', default='x86_64', choices=choices)
def _add_architecture_args(parser, choices=('x86_64', 'i386')): """Add common architecture args.""" parser.add_argument('--architecture', default='x86_64', choices=choices)
devtty1er/oss-fuzz
infra/helper.py
b670808387685abfd06171c4
function
simple
get_absolute_path(path): """Returns absolute path with user expansion.""" return os.path.abspath(os.path.expanduser(path)) def _get_command_string(command): """Returns a shell escaped command string.""" return ' '.join(pipes.quote(part) for part in command) def _get_project_dir(project_name):
"""Returns path to the project.""" return os.path.join(OSS_FUZZ_DIR, 'projects', project_name)
def _get_project_dir(project_name): """Returns path to the project.""" return os.path.join(OSS_FUZZ_DIR, 'projects', project_name)
devtty1er/oss-fuzz
infra/helper.py
a1ae39cd409a29ca99529597
function
simple
args.fuzzer_name)] else: run_args.append('test_all') exit_code = docker_run(run_args) if exit_code == 0: print('Check build passed.') else: print('Check build failed.') return exit_code def _get_fuzz_targets(project_name):
"""Return names of fuzz targest build in the project's /out directory.""" fuzz_targets = [] for name in os.listdir(_get_output_dir(project_name)): if name.startswith('afl-'): continue path = os.path.join(_get_output_dir(project_name), name) if os.path.isfile(path) and os.access(path, os.X_OK): ...
def _get_fuzz_targets(project_name): """Return names of fuzz targest build in the project's /out directory.""" fuzz_targets = [] for name in os.listdir(_get_output_dir(project_name)): if name.startswith('afl-'): continue path = os.path.join(_get_output_dir(project_name), name) if os.path.isfile...
devtty1er/oss-fuzz
infra/helper.py
b3ee341ee37025b3face0e58
function
simple
no_cache: build_args.append('--no-cache') build_args += [ '-t', 'gcr.io/%s/%s' % (image_project, image_name), dockerfile_dir ] return docker_build(build_args, pull=pull) def _env_to_docker_args(env_list):
"""Turn envirnoment variable list into docker arguments.""" return sum([['-e', v] for v in env_list], [])
def _env_to_docker_args(env_list): """Turn envirnoment variable list into docker arguments.""" return sum([['-e', v] for v in env_list], [])
devtty1er/oss-fuzz
infra/helper.py
03ac15a5f3c9a62d27fd610c
function
simple
_list): """Turn envirnoment variable list into docker arguments.""" return sum([['-e', v] for v in env_list], []) WORKDIR_REGEX = re.compile(r'\s*WORKDIR\s*([^\s]+)') def workdir_from_lines(lines, default='/src'):
"""Get the WORKDIR from the given lines.""" for line in reversed(lines): # reversed to get last WORKDIR. match = re.match(WORKDIR_REGEX, line) if match: workdir = match.group(1) workdir = workdir.replace('$SRC', '/src') if not os.path.isabs(workdir): workdir = os.path.join('/src'...
def workdir_from_lines(lines, default='/src'): """Get the WORKDIR from the given lines.""" for line in reversed(lines): # reversed to get last WORKDIR. match = re.match(WORKDIR_REGEX, line) if match: workdir = match.group(1) workdir = workdir.replace('$SRC', '/src') if not os.path.isabs(...
devtty1er/oss-fuzz
infra/helper.py
2f6e99c88df02d4862102216
function
simple
_dir, '-v', '%s:/work' % _get_work_dir(args.project_name), '-t', 'gcr.io/%s/%s' % (image_project, args.project_name), '/bin/bash' ]) docker_run(run_args) return 0 def pull_images(_):
"""Pull base images.""" for base_image in BASE_IMAGES: if not docker_pull(base_image): return 1 return 0
def pull_images(_): """Pull base images.""" for base_image in BASE_IMAGES: if not docker_pull(base_image): return 1 return 0
devtty1er/oss-fuzz
infra/helper.py
39f3fb942dd7660109a733e1
function
simple
% fuzzer_name]) try: subprocess.check_call(command) except subprocess.CalledProcessError: print(fuzzer_name, 'does not seem to exist. Please run build_fuzzers first.', file=sys.stderr) return False return True def _get_absolute_path(path):
"""Returns absolute path with user expansion.""" return os.path.abspath(os.path.expanduser(path))
def _get_absolute_path(path): """Returns absolute path with user expansion.""" return os.path.abspath(os.path.expanduser(path))
devtty1er/oss-fuzz
infra/helper.py
cd51302c61211df68fc839a5
function
simple
.""" return os.path.join(OSS_FUZZ_DIR, 'projects', project_name) def get_dockerfile_path(project_name): """Returns path to the project Dockerfile.""" return os.path.join(_get_project_dir(project_name), 'Dockerfile') def _get_corpus_dir(project_name=''):
"""Returns path to /corpus directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'corpus', project_name)
def _get_corpus_dir(project_name=''): """Returns path to /corpus directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'corpus', project_name)
devtty1er/oss-fuzz
infra/helper.py
5c9a39836fa7b476b24fb72a
function
simple
86_64', 'i386')): """Add common architecture args.""" parser.add_argument('--architecture', default='x86_64', choices=choices) def _add_engine_args(parser, choices=('libfuzzer', 'afl', 'honggfuzz', 'dataflow', 'none')):
"""Add common engine args.""" parser.add_argument('--engine', default='libfuzzer', choices=choices)
def _add_engine_args(parser, choices=('libfuzzer', 'afl', 'honggfuzz', 'dataflow', 'none')): """Add common engine args.""" parser.add_argument('--engine', default='libfuzzer', choices=choices)
devtty1er/oss-fuzz
infra/helper.py
3191dae59da2d416a80ca844
function
simple
os.path.join(BUILD_DIR, 'corpus', project_name) def _get_output_dir(project_name=''): """Returns path to /out directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'out', project_name) def _get_work_dir(project_name=''):
"""Returns path to /work directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'work', project_name)
def _get_work_dir(project_name=''): """Returns path to /work directory for the given project (if specified).""" return os.path.join(BUILD_DIR, 'work', project_name)
devtty1er/oss-fuzz
infra/helper.py
67e5ead669fc3683eaa100e7
function
simple
uzz-base/base-msan-builder', 'patch_build.py', '/out']) return 0 def build_fuzzers(args): """Build fuzzers.""" return build_fuzzers_impl(args.project_name, args.clean, args.engine, args.sanitizer, args.architecture, args.e, args.source_path) def check_b...
"""Checks that fuzzers in the container execute without errors.""" if not check_project_exists(args.project_name): return 1 if (args.fuzzer_name and not _check_fuzzer_exists(args.project_name, args.fuzzer_name)): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, 'SANITIZER=' + args.s...
def check_build(args): """Checks that fuzzers in the container execute without errors.""" if not check_project_exists(args.project_name): return 1 if (args.fuzzer_name and not _check_fuzzer_exists(args.project_name, args.fuzzer_name)): return 1 env = [ 'FUZZING_ENGINE=' + args.engine, ...
devtty1er/oss-fuzz
infra/helper.py
b2259e6f9b7c3781752845f4
function
simple
.""" command = ['docker', 'pull', image] print('Running:', _get_command_string(command)) try: subprocess.check_call(command) except subprocess.CalledProcessError: print('docker pull failed.', file=sys.stderr) return False return True def build_image(args):
"""Build docker image.""" if args.pull and args.no_pull: print('Incompatible arguments --pull and --no-pull.') return 1 if args.pull: pull = True elif args.no_pull: pull = False else: y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/N): ') pull = y_or_n.lower() == 'y...
def build_image(args): """Build docker image.""" if args.pull and args.no_pull: print('Incompatible arguments --pull and --no-pull.') return 1 if args.pull: pull = True elif args.no_pull: pull = False else: y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/N): ') pull...
devtty1er/oss-fuzz
infra/helper.py
3cc531f0f80140b6b714a33e
function
simple
undefined', 'coverage', 'dataflow')): """Add common sanitizer args.""" parser.add_argument( '--sanitizer', default=None, choices=choices, help='the default is "address"; "dataflow" for "dataflow" engine') def _add_environment_args(parser):
"""Add common environment args.""" parser.add_argument('-e', action='append', help="set environment variable e.g. VAR=value")
def _add_environment_args(parser): """Add common environment args.""" parser.add_argument('-e', action='append', help="set environment variable e.g. VAR=value")
devtty1er/oss-fuzz
infra/helper.py
5fdcc63270500818bf9624a7
function
simple
honggfuzz', 'dataflow', 'none')): """Add common engine args.""" parser.add_argument('--engine', default='libfuzzer', choices=choices) def _add_sanitizer_args(parser, choices=('address', 'memory', 'undefined', 'coverage', 'dataf...
"""Add common sanitizer args.""" parser.add_argument( '--sanitizer', default=None, choices=choices, help='the default is "address"; "dataflow" for "dataflow" engine')
def _add_sanitizer_args(parser, choices=('address', 'memory', 'undefined', 'coverage', 'dataflow')): """Add common sanitizer args.""" parser.add_argument( '--sanitizer', default=None, choices=choices, help='the default is "address"; "d...
devtty1er/oss-fuzz
infra/helper.py
d9ae5d7a3b02ef68fb6d8f03
function
simple
as plt """Script to preprocess the omniglot dataset and pickle it into an array that's easy to index my character type""" data_path = os.path.join('data/') train_folder = os.path.join(data_path, 'images_background') valpath = os.path.join(data_path, 'images_evaluation') save_path = 'data/' lang_dict = {} def ...
if not os.path.exists(path): print("unzipping") os.chdir(data_path) os.system("unzip {}".format(path+".zip")) X = [] y = [] cat_dict = {} lang_dict = {} curr_y = n # we load every alphabet seperately so we can isolate them later for alphabet in os.listdir(path): ...
def loadimgs(path, n=0): # if data not already unzipped, unzip it. if not os.path.exists(path): print("unzipping") os.chdir(data_path) os.system("unzip {}".format(path+".zip")) X = [] y = [] cat_dict = {} lang_dict = {} curr_y = n # we load every alphabet seperate...
rahulgurnani/Siamese-Networks
load_data.py
80c471b0f20e59a56396ac23
function
simple
break else: if 'seg.' in img_name: gt_name = img_name break gt_name = os.path.join(patient_dir, gt_name) full_gt_names.append(gt_name) return full_gt_names def get_segmentation_names(seg_folder, patient_names_fi...
with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_seg_names = [] for patient_name in patient_names: seg_name = os.path.join(seg_folder, patient_name + '.nii.gz') full_seg_names.append(seg_name) return ful...
def get_segmentation_names(seg_folder, patient_names_file): with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_seg_names = [] for patient_name in patient_names: seg_name = os.path.join(seg_folder, patient_name + '.nii...
MohamedHeshamMustafa/Brain-Tumor-Automatic-Detection-and-Segmentation-
util/evaluation.py
2e268dcdf7196f2113749079
function
simple
= f.readlines() patient_names = [x.strip() for x in content] full_seg_names = [] for patient_name in patient_names: seg_name = os.path.join(seg_folder, patient_name + '.nii.gz') full_seg_names.append(seg_name) return full_seg_names def dice_of_brats_data_set(gt_names, seg_names...
assert(len(gt_names) == len(seg_names)) dice_all_data = [] for i in range(len(gt_names)): g_volume = load_3d_volume_as_array(gt_names[i]) s_volume = load_3d_volume_as_array(seg_names[i]) dice_one_volume = [] if(type_idx ==0): # whole tumor temp_dice = binary_dice3...
def dice_of_brats_data_set(gt_names, seg_names, type_idx): assert(len(gt_names) == len(seg_names)) dice_all_data = [] for i in range(len(gt_names)): g_volume = load_3d_volume_as_array(gt_names[i]) s_volume = load_3d_volume_as_array(seg_names[i]) dice_one_volume = [] if(type_i...
MohamedHeshamMustafa/Brain-Tumor-Automatic-Detection-and-Segmentation-
util/evaluation.py
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
10