text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|>@patch.object(upwork.Client, "delete")
def test_delete_by_contract(mocked_method):
snapshots.Api(upwork.Client).delete_by_contract("1234", "1234")
mocked_method.assert_called_with("/team/v3/snapshots/contracts/1234/1234")<|fim_prefix|># repo: upwork/python-upwork path: /tests/routers/test_snapsho... | code_fim | hard | {
"lang": "python",
"repo": "upwork/python-upwork",
"path": "/tests/routers/test_snapshots.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@patch.object(upwork.Client, "delete")
def test_delete_by_contract(mocked_method):
snapshots.Api(upwork.Client).delete_by_contract("1234", "1234")
mocked_method.assert_called_with("/team/v3/snapshots/contracts/1234/1234")<|fim_prefix|># repo: upwork/python-upwork path: /tests/routers/test_snapsh... | code_fim | hard | {
"lang": "python",
"repo": "upwork/python-upwork",
"path": "/tests/routers/test_snapshots.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input().strip())
for q_itr in range(q):
s = input()
result = anagram(s)
fptr.write(str(result) + '\n')
fptr.close()<|fim_prefix|># repo: mxdzi/hackerrank path: /problem_solving/alg... | code_fim | hard | {
"lang": "python",
"repo": "mxdzi/hackerrank",
"path": "/problem_solving/algorithms/strings/q18_anagram.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mxdzi/hackerrank path: /problem_solving/algorithms/strings/q18_anagram.py
#!/bin/python3
import math
import os
import random
import re
import sys
<|fim_suffix|> return sum((c2 - c1).values())
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input().s... | code_fim | hard | {
"lang": "python",
"repo": "mxdzi/hackerrank",
"path": "/problem_solving/algorithms/strings/q18_anagram.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def anagram(s):
from collections import Counter
# Write your code here
if len(s) % 2 == 1:
return -1
s1 = s[:len(s) // 2]
s2 = s[len(s) // 2:]
c1 = Counter(s1)
c2 = Counter(s2)
return sum((c2 - c1).values())
if __name__ == '__main__':
fptr = open(os.environ... | code_fim | medium | {
"lang": "python",
"repo": "mxdzi/hackerrank",
"path": "/problem_solving/algorithms/strings/q18_anagram.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == '__main__':
soln = Solution()
arr = [3, 1, 3, 2, 2]
print(soln.largestRectangleArea(arr))<|fim_prefix|># repo: wyaadarsh/LeetCode-Solutions path: /Python3/0084-Largest-Rectangle-in-Histogram/soln.py
class Solution:
def largestRectangleArea(self, heights):
<|fim_middle|> ... | code_fim | hard | {
"lang": "python",
"repo": "wyaadarsh/LeetCode-Solutions",
"path": "/Python3/0084-Largest-Rectangle-in-Histogram/soln.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wyaadarsh/LeetCode-Solutions path: /Python3/0084-Largest-Rectangle-in-Histogram/soln.py
class Solution:
def largestRectangleArea(self, heights):
<|fim_suffix|>
if __name__ == '__main__':
soln = Solution()
arr = [3, 1, 3, 2, 2]
print(soln.largestRectangleArea(arr))<|fim_middle|> ... | code_fim | hard | {
"lang": "python",
"repo": "wyaadarsh/LeetCode-Solutions",
"path": "/Python3/0084-Largest-Rectangle-in-Histogram/soln.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: HBPVIS/nest-in-situ-vis path: /pyniv/src/testing/__init__.py
#-------------------------------------------------------------------------------
# nest in situ vis
#
# Copyright (c) 2017-2018 RWTH Aachen University, Germany,
# Virtual Reality & Immersive Visualisation Group.
#-----------------------... | code_fim | medium | {
"lang": "python",
"repo": "HBPVIS/nest-in-situ-vis",
"path": "/pyniv/src/testing/__init__.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>ANY_TIMES = [ANY_TIME, ANOTHER_TIME, THIRD_TIME];
ANY_TIMES_STRING = [ANY_TIME_STRING, ANOTHER_TIME_STRING, THIRD_TIME_STRING];
ANY_ATTRIBUTES = [ANY_ATTRIBUTE, ANOTHER_ATTRIBUTE, THIRD_ATTRIBUTE];
ANY_IDS = [ANY_ID, ANOTHER_ID, THIRD_ID];
ANY_IDS_STRING = [ANY_ID_STRING, ANOTHER_ID_STRING, THIRD_ID_STRIN... | code_fim | medium | {
"lang": "python",
"repo": "HBPVIS/nest-in-situ-vis",
"path": "/pyniv/src/testing/__init__.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: daturkel/dotfiles path: /deploy
#!/usr/bin/env python
from string import Template
import toml
import pathlib
import os
import shutil
import fire
import re
class Deploy:
def __init__(self):
with open("config.toml") as config_file:
self.config = toml.load(config_file)
... | code_fim | hard | {
"lang": "python",
"repo": "daturkel/dotfiles",
"path": "/deploy",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def _ignore_files(self, directory, files):
return [f for f in files if os.path.isfile(os.path.join(directory, f))]
def dispatch(self, project, profile, prefix_project=True):
if isinstance(profile, str):
profiles = [profile]
else:
profiles = profile
... | code_fim | hard | {
"lang": "python",
"repo": "daturkel/dotfiles",
"path": "/deploy",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@pytest.mark.skip(reason="Yet to implement")
def test_event_payload_construction():
pass
@pytest.mark.skip(reason="Yet to implement")
def test_stringified_message():
pass
@pytest.mark.skip(reason="Yet to implement")
def test_reconstruction_of_event_from_message():
pass
@pytest.mark.skip... | code_fim | hard | {
"lang": "python",
"repo": "proteanhq/protean",
"path": "/tests/event/test_serialization.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: proteanhq/protean path: /tests/event/test_serialization.py
from uuid import UUID, uuid4
import pytest
from tests.event.elements import PersonAdded
<|fim_suffix|>
@pytest.mark.skip(reason="Yet to implement")
def test_reconstruction_of_event_from_message():
pass
@pytest.mark.skip(reason="Y... | code_fim | hard | {
"lang": "python",
"repo": "proteanhq/protean",
"path": "/tests/event/test_serialization.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> pass
@pytest.mark.skip(reason="Yet to implement")
def test_event_payload_construction():
pass
@pytest.mark.skip(reason="Yet to implement")
def test_stringified_message():
pass
@pytest.mark.skip(reason="Yet to implement")
def test_reconstruction_of_event_from_message():
pass
@pytest... | code_fim | medium | {
"lang": "python",
"repo": "proteanhq/protean",
"path": "/tests/event/test_serialization.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ritututeja/HAMR_xi path: /util/combineTwoConditions_manyByMany.py
#!/bin/python2.7
#
# Copyright (c) 2016 University of Pennsylvania
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to de... | code_fim | hard | {
"lang": "python",
"repo": "ritututeja/HAMR_xi",
"path": "/util/combineTwoConditions_manyByMany.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>#assign weights to each element of pie chart
weights = [str(0.5/len(args.a_mods_filenames))]*len(args.a_mods_filenames)+[str(0.5/len(args.b_mods_filenames))]*len(args.b_mods_filenames) #all A samples will occupy half of pie chart
weights_output = ",".join(weights)
#print to temporary bed6 file
combinedM... | code_fim | hard | {
"lang": "python",
"repo": "ritututeja/HAMR_xi",
"path": "/util/combineTwoConditions_manyByMany.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Colin-b/layabase path: /tests/test_mongo_controller_index_unique.py
import pytest
import layabase
import layabase.mongo
@pytest.fixture
def controller():
class TestCollection:
__collection_name__ = "test"
id = layabase.mongo.Column(index_type=layabase.mongo.IndexType.Uniqu... | code_fim | medium | {
"lang": "python",
"repo": "Colin-b/layabase",
"path": "/tests/test_mongo_controller_index_unique.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> controller: layabase.CRUDController,
):
assert controller.post_many(
[{"id": "test1", "id2": "test1"}, {"id": "test1", "id2": "test2"}]
) == [{"id": "test1", "id2": "test1"}, {"id": "test1", "id2": "test2"}]
# It should never be declared without a PK in this case but as there is no... | code_fim | hard | {
"lang": "python",
"repo": "Colin-b/layabase",
"path": "/tests/test_mongo_controller_index_unique.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def test_put_many_without_primary_key_and_unique_index_update(
controller: layabase.CRUDController,
):
assert controller.post_many(
[{"id": "test1", "id2": "test1"}, {"id": "test1", "id2": "test2"}]
) == [{"id": "test1", "id2": "test1"}, {"id": "test1", "id2": "test2"}]
# It should... | code_fim | hard | {
"lang": "python",
"repo": "Colin-b/layabase",
"path": "/tests/test_mongo_controller_index_unique.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #: GradingProjectSurvey which belongs to this group.
grading_survey = db.ReferenceProperty(
reference_class=grading_project_survey_model.GradingProjectSurvey,
required=True, collection_name='gsoc_grading_survey_groups')
#: non-required ProjectSurvey that belongs to this group.
student... | code_fim | hard | {
"lang": "python",
"repo": "sambitgaan/nupic.son",
"path": "/app/soc/modules/gsoc/models/grading_survey_group.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> A GradingSurvey group can also work with only a GradingProjectSurvey defined.
The GradingSurveyGroup can have several GradingRecords attached to it. These
will contain matching SurveyRecords for the surveys set in this group, of
course only if they are filled in.
"""
#: Name to give to this ... | code_fim | hard | {
"lang": "python",
"repo": "sambitgaan/nupic.son",
"path": "/app/soc/modules/gsoc/models/grading_survey_group.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sambitgaan/nupic.son path: /app/soc/modules/gsoc/models/grading_survey_group.py
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
... | code_fim | hard | {
"lang": "python",
"repo": "sambitgaan/nupic.son",
"path": "/app/soc/modules/gsoc/models/grading_survey_group.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Perkov/soloact path: /soloact/data/annotations_chords.py
import os
import yaml
import xml.etree.ElementTree as ET
import pandas as pd
import json
import fnmatch
import glob
import argparse
import sox
import re
from pprint import pprint
def write_annotation(paths):
"""
Writing meta annot... | code_fim | hard | {
"lang": "python",
"repo": "Perkov/soloact",
"path": "/soloact/data/annotations_chords.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> for chord, segment in strategy_config.items():
for s, pitch_components in segment.items():
[*bindings], [*components] = zip(*[(records.get((model, pitch + x)), str(pitch + x)) for x in pitch_components])
if any([fn is None for fn in bindings]) is False:
... | code_fim | hard | {
"lang": "python",
"repo": "Perkov/soloact",
"path": "/soloact/data/annotations_chords.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # @ParamType aRankComm
# @ParamType aGraph
# @ParamType aConn
def betweenessComp(self, aRankComm, aGraph, aConn):
pass
# @ParamType aRankComm
# @ParamType aGraph
# @ParamType aConn
def closenessComp(self, aRankComm, aGraph, aConn):
pass
def __init__(self):
self.___vertexId = None
... | code_fim | hard | {
"lang": "python",
"repo": "ruchiraPeiris/Heft",
"path": "/Executor/RankGraph.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ruchiraPeiris/Heft path: /Executor/RankGraph.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import Graph
class RankGraph(Graph):
# @ParamType aRankComm
# @ParamType aGraph
# @ParamType aConn
def indegreeComp(self, aRankComm, aGraph, aConn):
pass
# @ParamType aRankComm
# @ParamType aGr... | code_fim | medium | {
"lang": "python",
"repo": "ruchiraPeiris/Heft",
"path": "/Executor/RankGraph.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: m-pilia/mli path: /test/test_repl.py
import io
import unittest
import unittest.mock as mock
import mli._repl
def mock_input(values):
def fun(*args, **kwargs):
if not hasattr(fun, 'count'):
fun.count = 0
else:
fun.count += 1
return values[fun.... | code_fim | hard | {
"lang": "python",
"repo": "m-pilia/mli",
"path": "/test/test_repl.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.source = mock.Mock(side_effect=lambda e, b: f'result {e}')
@mock.patch('builtins.input', side_effect=mock_input(['x', 'exit']))
def test_one_statement(self, mi):
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
mli._repl.repl(self.source)
... | code_fim | hard | {
"lang": "python",
"repo": "m-pilia/mli",
"path": "/test/test_repl.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def setUp(self):
self.source = mock.Mock(side_effect=lambda e, b: f'result {e}')
@mock.patch('builtins.input', side_effect=mock_input(['x', 'exit']))
def test_one_statement(self, mi):
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
mli._repl.repl... | code_fim | medium | {
"lang": "python",
"repo": "m-pilia/mli",
"path": "/test/test_repl.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> filename = 'ensemble_submission_{}_{}.csv'.format(ensemble_file.split('.')[0],
datetime.now().strftime('_%Y_%m_%d_%H_%M_%S'))
header_ = ','.join(['image_name', 'Type_1', 'Type_2', 'Type_3'])
with open(os.path.join('./submission', filename), 'w') as f_csv:
f_csv.write(header_+'\... | code_fim | hard | {
"lang": "python",
"repo": "wangg12/intel-cervical-cancer",
"path": "/ensemble_scores.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> file_score_dict = {}
for line in ensemble_list:
if not line in file_score_dict.keys():
scores, image_names = load_scores(line)
file_score_dict[line] = scores
# ensemble, currently average, TODO: weighted or learnable
final_scores = sum(file_score_dict.values())/float(len(file_sco... | code_fim | hard | {
"lang": "python",
"repo": "wangg12/intel-cervical-cancer",
"path": "/ensemble_scores.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wangg12/intel-cervical-cancer path: /ensemble_scores.py
from __future__ import print_function, division
import argparse
import os
import sys
import numpy as np
from datetime import datetime
def load_scores(score_path):
f = open(score_path, 'r')
i = 0
scores = []
image_names = []
for li... | code_fim | hard | {
"lang": "python",
"repo": "wangg12/intel-cervical-cancer",
"path": "/ensemble_scores.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: baduy9x/vantix_hometest path: /problem_1.py
def find_mode(arr):
if len(arr) == 1:
return arr
last_item = None
count = 1
max_appear = 0
result = []
<|fim_suffix|>if __name__ == "__main__":
arr = [1,2,3,3,3,3,4,4,5,5,6,6,6,6]
print(find_mode(arr))<|fim_middle|>... | code_fim | hard | {
"lang": "python",
"repo": "baduy9x/vantix_hometest",
"path": "/problem_1.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
if __name__ == "__main__":
arr = [1,2,3,3,3,3,4,4,5,5,6,6,6,6]
print(find_mode(arr))<|fim_prefix|># repo: baduy9x/vantix_hometest path: /problem_1.py
def find_mode(arr):
if len(arr) == 1:
return arr
last_item = None
count = 1
max_appear = 0
result = []
for item ... | code_fim | medium | {
"lang": "python",
"repo": "baduy9x/vantix_hometest",
"path": "/problem_1.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>vdjdb_clean = vdjdb_filter[['cdr3a',
'cdr3b',
'dataset',
'epitope',
'epitope_gene',
'epitope_species',
'ja',
'jb',
'mhc',
'va',
'vb',
'pmhc',
'donor',
'is_second_alpha_chain',
'db',
'mhc_trim',
'match_cdr',
'species']]
#bind the 3 df together
big_db_df = pd.concat([conga_paired, mcpas_cl... | code_fim | hard | {
"lang": "python",
"repo": "nealpsmith/conga",
"path": "/scripts/generate_merged_tcr_db.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>#split into human and mouse
human_df = big_db_df[big_db_df['species'].isin(['Human','HomoSapiens'])].copy()
mouse_df = big_db_df[big_db_df['species'].isin(['Mouse','MusMusculus'])].copy()
#annotate the mhc class type
human_mhc_class = []
for l in human_df.itertuples():
if isinstance(l.mhc, str):
... | code_fim | hard | {
"lang": "python",
"repo": "nealpsmith/conga",
"path": "/scripts/generate_merged_tcr_db.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nealpsmith/conga path: /scripts/generate_merged_tcr_db.py
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 10:13:08 2021
@author: sschattg
This script is used to parse the mcpas and vdj-db databases and append them to the current paired TCR database package with conga.
These database files can ... | code_fim | hard | {
"lang": "python",
"repo": "nealpsmith/conga",
"path": "/scripts/generate_merged_tcr_db.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: djf604/youngvoices path: /youngvoices/quiz.py
def quiz():
# Collect answers from the quiz page
example = field("example")
example2 = field("example2")
<|fim_suffix|> global _post
global _user
_post = request.POST
_user = request.user
_user.profile.num_quizes_taken ... | code_fim | medium | {
"lang": "python",
"repo": "djf604/youngvoices",
"path": "/youngvoices/quiz.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return _post.get(field_name, '')
def add_score(score):
_user.profile.total_score += score
_user.profile.save()<|fim_prefix|># repo: djf604/youngvoices path: /youngvoices/quiz.py
def quiz():
# Collect answers from the quiz page
example = field("example")
example2 = field("example2"... | code_fim | hard | {
"lang": "python",
"repo": "djf604/youngvoices",
"path": "/youngvoices/quiz.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # y = softmax(x)
y = Softmax(x, axis)
# y' = y * (1 - y)
y_neg = akg.lang.ascend.vmuls(y, akg.tvm.const(-1.0, dtype=dtype))
y_neg_add1 = akg.lang.ascend.vadds(y_neg, akg.tvm.const(1.0, dtype=dtype))
y_grad = akg.lang.ascend.vmul(y, y_neg_add1)
# dx = dy * y'
dx = akg.lan... | code_fim | hard | {
"lang": "python",
"repo": "mindspore-ai/akg",
"path": "/tests/common/test_op/ascend/softmax_grad.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mindspore-ai/akg path: /tests/common/test_op/ascend/softmax_grad.py
# Copyright 2019-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#... | code_fim | hard | {
"lang": "python",
"repo": "mindspore-ai/akg",
"path": "/tests/common/test_op/ascend/softmax_grad.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> hash_key = str((tuple(key), dtype))
return ct_util.set_dims_by_key(hash_key, softmax_grad_set_dim_map), hash_key
@ct_util.reg_set_dim_func(softmax_grad_set_dim_func)
def softmax_grad(x, dy, axis):
"""
Computes gradients of softmax.
Args:
x(akg.tvm.Tensor): Tensor of type flo... | code_fim | hard | {
"lang": "python",
"repo": "mindspore-ai/akg",
"path": "/tests/common/test_op/ascend/softmax_grad.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> logchunk = LogChunk(
id=UUID(hex='33846695b2774b29a71795a009e8168a'),
source_id=UUID(hex='0b61b8a47ec844918d372d5741187b1c'),
source=LogSource(id=UUID(hex='0b61b8a47ec844918d372d5741187b1c')),
offset=10,
size=7,
text='\x1b[0;36mnotice: foo bar',
... | code_fim | medium | {
"lang": "python",
"repo": "getsentry/changes",
"path": "/tests/changes/api/serializer/models/test_logchunk.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: getsentry/changes path: /tests/changes/api/serializer/models/test_logchunk.py
from datetime import datetime
from uuid import UUID
from changes.api.serializer import serialize
from changes.models.log import LogSource, LogChunk
<|fim_suffix|> logchunk = LogChunk(
id=UUID(hex='33846695b... | code_fim | medium | {
"lang": "python",
"repo": "getsentry/changes",
"path": "/tests/changes/api/serializer/models/test_logchunk.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: linmingchih/HowtoSim_Script path: /2020/moveBondwire.py
import os, sys, re, clr
import math, cmath
import collections
import json
win64_dir = oDesktop.GetExeDir()
dll_dir = os.path.join(win64_dir, 'common/IronPython/DLLs')
sys.path.append(dll_dir)
clr.AddReference('IronPython.Wpf')
impo... | code_fim | hard | {
"lang": "python",
"repo": "linmingchih/HowtoSim_Script",
"path": "/2020/moveBondwire.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def profile_cb_SelectionChanged(self, sender, e):
AddWarningMessage(str(self.profiles[self.profile_cb.SelectedValue]))
oEditor.Select(self.profiles[self.profile_cb.SelectedValue])
'''
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'moveBondw... | code_fim | hard | {
"lang": "python",
"repo": "linmingchih/HowtoSim_Script",
"path": "/2020/moveBondwire.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mosquito/aiormq path: /tests/conftest.py
import asyncio
import gc
import logging
import os
import tracemalloc
import pamqp
import pytest
from aiomisc_pytest import TCPProxy
from yarl import URL
from aiormq import Connection
def cert_path(*args):
return os.path.join(
os.path.abspat... | code_fim | hard | {
"lang": "python",
"repo": "mosquito/aiormq",
"path": "/tests/conftest.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>@pytest.fixture()
async def proxy(tcp_proxy, localhost, amqp_url: URL):
port = amqp_url.port or 5672 if amqp_url.scheme == "amqp" else 5671
async with tcp_proxy(amqp_url.host, port) as proxy:
yield proxy
@pytest.fixture
async def proxy_connection(proxy: TCPProxy, amqp_url: URL, loop):
... | code_fim | hard | {
"lang": "python",
"repo": "mosquito/aiormq",
"path": "/tests/conftest.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sophieball/toxicity-detector path: /main/train_polite_score.py
# Lint as: python3
"""
Use logistic regression to prect the politeness score
"""
<|fim_suffix|>[training_data, _] = receive_data.receive_data()
training_data = training_data.dropna()
convo_politeness.cross_validate(training_data)<|fi... | code_fim | hard | {
"lang": "python",
"repo": "sophieball/toxicity-detector",
"path": "/main/train_polite_score.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>[training_data, _] = receive_data.receive_data()
training_data = training_data.dropna()
convo_politeness.cross_validate(training_data)<|fim_prefix|># repo: sophieball/toxicity-detector path: /main/train_polite_score.py
# Lint as: python3
"""
Use logistic regression to prect the politeness score
"""
<|fi... | code_fim | hard | {
"lang": "python",
"repo": "sophieball/toxicity-detector",
"path": "/main/train_polite_score.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: talk2shruthivs/sana.protocol_builder path: /src-backend/api/models.py
from django.db import models
from django.contrib.auth.models import User
class Procedure(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
version = models.CharField... | code_fim | hard | {
"lang": "python",
"repo": "talk2shruthivs/sana.protocol_builder",
"path": "/src-backend/api/models.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> display_index = models.PositiveIntegerField()
procedure = models.ForeignKey(Procedure, related_name='pages')
last_modified = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def save(self, **kwargs):
super(Page, self).save()
self.p... | code_fim | medium | {
"lang": "python",
"repo": "talk2shruthivs/sana.protocol_builder",
"path": "/src-backend/api/models.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> class Meta:
app_label = 'api'
ordering = ['procedure', 'display_index']
class Element(models.Model):
TYPES = (
('SELECT', 'SELECT'),
('MULTI_SELECT', 'MULTI_SELECT'),
('RADIO', 'RADIO'),
('GPS', 'GPS'),
('SOUND', 'SOUND'),
('PICTURE... | code_fim | medium | {
"lang": "python",
"repo": "talk2shruthivs/sana.protocol_builder",
"path": "/src-backend/api/models.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> sha256[11:7:-1] + sha256[15:11:-1]
print(id0.encode("hex"))<|fim_prefix|># repo: zoogie/seedminer_toolbox path: /id0convert.py
import os,sys,hashlib
with open(sys.argv[1],"rb") as f:
msed=f.read(0x120)
keyy=msed[0x110:0x120]
sha256=hashlib.sha25<|fim_middle|>6(keyy).digest()[:0x10]
id0=sha256[3::-... | code_fim | medium | {
"lang": "python",
"repo": "zoogie/seedminer_toolbox",
"path": "/id0convert.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zoogie/seedminer_toolbox path: /id0convert.py
import os,sys,hashlib
with open(sys.argv[1],"rb") as f:
msed=f.read(0x120)
keyy=msed[0x110:0x120]
sha256=hashlib.sha25<|fim_suffix|> sha256[11:7:-1] + sha256[15:11:-1]
print(id0.encode("hex"))<|fim_middle|>6(keyy).digest()[:0x10]
id0=sha256[3::-... | code_fim | medium | {
"lang": "python",
"repo": "zoogie/seedminer_toolbox",
"path": "/id0convert.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: fakegit/recipy path: /recipyGui/tests/test_controller.py
import unittest
from recipyGui.controller import search_database
from recipyCommon import utils
class TestController(unittest.TestCase):
def setUp(self):
self.db = utils.open_or_create_db()
def test_search_database_with_... | code_fim | hard | {
"lang": "python",
"repo": "fakegit/recipy",
"path": "/recipyGui/tests/test_controller.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.assertEquals(results, self.db.all())
def test_search_database_with_nonexistent_result_returns_nothing(self):
query = 'some_result_that_couldnt_possibly_exist_qwertyuiopoiuytrewq'
results = search_database(self.db, query=query)
self.assertEquals(results, [])
... | code_fim | hard | {
"lang": "python",
"repo": "fakegit/recipy",
"path": "/recipyGui/tests/test_controller.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # TODO: try to put in a test for windows style paths like 'C:/Users/blabla'
# this is difficult to replicate in a test since it only seems to work from the gui entry form<|fim_prefix|># repo: fakegit/recipy path: /recipyGui/tests/test_controller.py
import unittest
from recipyGui.controller impor... | code_fim | hard | {
"lang": "python",
"repo": "fakegit/recipy",
"path": "/recipyGui/tests/test_controller.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self,
n,
channel_name
):
i = 0
while i < n:
yield self.public_cint_input(channel_name)
i += 1
def public_cint_output(
self,
c,
channel_name
):
return c.public_output(self.ch... | code_fim | hard | {
"lang": "python",
"repo": "vlaskinvlad/SCALE-MAMBA",
"path": "/common/channels.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: vlaskinvlad/SCALE-MAMBA path: /common/channels.py
from Compiler.types import (
sint,
cint,
regint,
)
from Compiler.library import (
open_channel,
close_channel,
)
class ChannelManager(object):
def __init__(
self,
player_dict,
channel_d... | code_fim | hard | {
"lang": "python",
"repo": "vlaskinvlad/SCALE-MAMBA",
"path": "/common/channels.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def wall_f(x):
if x < r_cut:
r = x
sign = 1
elif x > L-r_cut:
r = L-x
sign = -1
else:
return 0
return sign*3*(3*r**-10 - r**-4)
grav = float(args.gravity)
bond_l = float(args.bond_l)
def f(x, y, theta):
c_th = math.cos(theta)
s_th = math.... | code_fim | hard | {
"lang": "python",
"repo": "pdebuyl/active_polar_2d",
"path": "/examples/run.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pdebuyl/active_polar_2d path: /examples/run.py
#!/usr/bin/env python3
"""Execute a Langevin simulation"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int)
parser.add_argument('--steps', type=int, default=2**11)
parser.add_argument('--gamma', type=float,... | code_fim | hard | {
"lang": "python",
"repo": "pdebuyl/active_polar_2d",
"path": "/examples/run.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>plt.figure()
ax1 = plt.subplot(311)
plt.plot(y, x)
plt.ylabel(r'$x$')
ax2 = plt.subplot(312)
plt.plot(t, np.mod(theta, 2*np.pi)/np.pi)
plt.ylabel(r'$\theta/\pi$')
ax3 = plt.subplot(325)
plt.hist(x, normed=True, bins=32)
ax4 = plt.subplot(326)
plt.hist(np.mod(theta, 2*np.pi), normed=True, bins=32)
plt.... | code_fim | hard | {
"lang": "python",
"repo": "pdebuyl/active_polar_2d",
"path": "/examples/run.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> :param default_version: The default version of this MatrixTable resource (must to be in the `versions` dict)
:param versions: A dict of version name -> MatrixTableResource.
"""
def __init__(self, default_version: str, versions: Dict[str, MatrixTableResource]):
super().__init__(def... | code_fim | hard | {
"lang": "python",
"repo": "fengpku/gnomad_methods",
"path": "/gnomad/resources/resource_utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: fengpku/gnomad_methods path: /gnomad/resources/resource_utils.py
import logging
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional
import hail as hl
from hail.linalg import BlockMatrix
logger = logging.getLogger("gnomad.resources")
# Resource classes
cl... | code_fim | hard | {
"lang": "python",
"repo": "fengpku/gnomad_methods",
"path": "/gnomad/resources/resource_utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: egor43/PyImageComparsion path: /image_comparsion/compare_tools.py
"""
Модуль предоставляет инструменты сравнения изображений
author: https://github.com/egor43
"""
from . import constants
from . import image_metrick
from . import helpers
def hash_match_rates(base_img_hashes, comparable... | code_fim | hard | {
"lang": "python",
"repo": "egor43/PyImageComparsion",
"path": "/image_comparsion/compare_tools.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Определение схожести двух изображений по average hash и wavelet hash.
Params:
base_img - базовое изображение
comparable_img - сравниваемое изображение
match_threshold_hash_percent - порог совпадения хешей с которого
... | code_fim | hard | {
"lang": "python",
"repo": "egor43/PyImageComparsion",
"path": "/image_comparsion/compare_tools.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> match_threshold_orb_percent=constants.MATCH_THRESHOLD_ORB_PERCENT,
*, with_orb_comparsion=True):
"""
Группировка похожих изображений.
Возвращает генератор.
Params:
images - последовательность изображений
... | code_fim | hard | {
"lang": "python",
"repo": "egor43/PyImageComparsion",
"path": "/image_comparsion/compare_tools.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: llimllib/bostonmarathon path: /maps/makejson.py
import json
import csv
meta = json.load(file("country_meta.json"))
pop = csv.reader(file("country_pop.csv"))
<|fim_suffix|> tempdata[row[1]]['population'] = int(row[2].replace(",", ""))
outdata = {}
for key, val in tempdata.iteritems():
if... | code_fim | hard | {
"lang": "python",
"repo": "llimllib/bostonmarathon",
"path": "/maps/makejson.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>outdata = {}
for key, val in tempdata.iteritems():
if not 'population' in val:
print "skipping", key
continue
outdata[val["id"]] = {
"name": val['name'],
"three": val['three'],
"population": val["population"]
}
fout = file("countrydata.json", 'w')
fout.... | code_fim | hard | {
"lang": "python",
"repo": "llimllib/bostonmarathon",
"path": "/maps/makejson.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>headers = pop.next()
for row in pop:
row = [s.decode("utf8") for s in row]
#assert row[1] in tempdata, "{} not in tempdata".format(row[1].encode('utf8'))
if not row[1] in tempdata: continue
tempdata[row[1]]['population'] = int(row[2].replace(",", ""))
outdata = {}
for key, val in tempdat... | code_fim | hard | {
"lang": "python",
"repo": "llimllib/bostonmarathon",
"path": "/maps/makejson.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: laygond/Juggle-Deep-Tools path: /sample_code/deepergooglenet/train.py
# train.py
import matplotlib
matplotlib.use("Agg")
import json
import argparse
import keras.backend as K
from tensorflow.keras.models import load_model
from tensorflow.keras.optimizers import load_model
from tensorflow.keras.o... | code_fim | hard | {
"lang": "python",
"repo": "laygond/Juggle-Deep-Tools",
"path": "/sample_code/deepergooglenet/train.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> optimizer = Adam(1e-3)
model.compule(
loss = "categorical_crossentropy", optimizer = optimizer,
metrics = ["acc"]
)
# otherwise, load the checkpoint from disk
else:
print("[INFO] loading {}...".format(args["model"]))
model = load_model(args["model"])
# udate the le... | code_fim | hard | {
"lang": "python",
"repo": "laygond/Juggle-Deep-Tools",
"path": "/sample_code/deepergooglenet/train.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> obsdate = dateutil.parser.parse(head['DATE-OBS'])
exptime = head['EXPTIME']
objectname = head['OBJECT']
# determine the total number of saturated pixels
saturation = (data>=65535).sum()
# find the 95% quantile
quantile95 = np.sort(data.flatten())[... | code_fim | hard | {
"lang": "python",
"repo": "rbkuhn/gamse",
"path": "/gamse/pipelines/feros.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rbkuhn/gamse path: /gamse/pipelines/feros.py
import os
import dateutil.parser
import astropy.io.fits as fits
def make_obslog(path):
# scan the raw files
fname_lst = sorted(os.listdir(path))
names = ('frameid', 'fileid', 'objectname', 'exptime', 'obsdate',
'saturatio... | code_fim | hard | {
"lang": "python",
"repo": "rbkuhn/gamse",
"path": "/gamse/pipelines/feros.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> objectname = head['OBJECT']
# determine the total number of saturated pixels
saturation = (data>=65535).sum()
# find the 95% quantile
quantile95 = np.sort(data.flatten())[int(data.size*0.95)]
logdata[0].append(frameid)
logdata[1].append(fileid)
... | code_fim | hard | {
"lang": "python",
"repo": "rbkuhn/gamse",
"path": "/gamse/pipelines/feros.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: qinyanhao/LokiHub path: /TransportationBot/Line/intent/Loki_departure_time.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Loki module for departure_time
Input:
inputSTR str,
utterance str,
args str[],
resultDICT dict
Output... | code_fim | hard | {
"lang": "python",
"repo": "qinyanhao/LokiHub",
"path": "/TransportationBot/Line/intent/Loki_departure_time.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if utterance == "[下午][三點][五十][之後]":
# write your code here
datetime = timeSTRConvert(args[1] + args[2])['time']
time_STR = datetime[0][0]["datetime"][-8:-3]
resultDICT['departure_time'] = format_convert(args[0], time_STR)
pass
if utterance == "[下午][三點][五十分]... | code_fim | hard | {
"lang": "python",
"repo": "qinyanhao/LokiHub",
"path": "/TransportationBot/Line/intent/Loki_departure_time.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if utterance == "[七點][四十六分]往台南":
# write your code here
datetime = timeSTRConvert(args[0]+args[1])["time"]
dt = datetime[0][0]["datetime"][-8:-3] #抓articutAPI中time的時間(後八格)
resultDICT['departure_time'] = format_identifier(dt)
pass
if utterance == "[三十分]出發":
... | code_fim | hard | {
"lang": "python",
"repo": "qinyanhao/LokiHub",
"path": "/TransportationBot/Line/intent/Loki_departure_time.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: MV487/panda3dstudio path: /src/gui/dialogs/progress_dialog.py
from ..dialog import *
class ProgressBarFrame(Widget):
def __init__(self, parent):
gfx_ids = {"": Skin.atlas.gfx_ids["progress_bar"]["frame"]}
Widget.__init__(self, "progress_bar_frame", parent, gfx_ids, has_mo... | code_fim | hard | {
"lang": "python",
"repo": "MV487/panda3dstudio",
"path": "/src/gui/dialogs/progress_dialog.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> frame.set_progress_bar(self)
self._rate = 0.
self._progress = 0.
@property
def frame(self):
return self.parent
def set_rate(self, rate):
if not self._rate:
self._rate = rate
def __update_card_image(self):
image = self.get_i... | code_fim | hard | {
"lang": "python",
"repo": "MV487/panda3dstudio",
"path": "/src/gui/dialogs/progress_dialog.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> if self._rate:
self._progress = min(1., self._progress + self._rate)
sizer_cell = self.sizer_cell
sizer_cell.proportions = (self._progress, 0.)
sizer = sizer_cell.sizer
space_cell = sizer.cells[1]
space_cell.proportions = (1. ... | code_fim | hard | {
"lang": "python",
"repo": "MV487/panda3dstudio",
"path": "/src/gui/dialogs/progress_dialog.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|># this function handles the DB update and DB query to confirm the status change
def fixit(self):
cnxn = pyodbc.connect("Driver={SQL Server};"
"Server=<ip>;"
"Database=<db name>;"
"uid=<>; pwd=<>")
... | code_fim | hard | {
"lang": "python",
"repo": "MTBriles/DUPSUID_APP",
"path": "/dupsuid.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> cnxn = pyodbc.connect("Driver={SQL Server};"
"Server=<ip>;"
"Database=<db name>;"
"uid=<>; pwd=<>")
cursor = cnxn.cursor()
cursor.execute('SELECT exceptionTypeCd, accessionNumber FROM [St... | code_fim | hard | {
"lang": "python",
"repo": "MTBriles/DUPSUID_APP",
"path": "/dupsuid.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: MTBriles/DUPSUID_APP path: /dupsuid.py
# you will need tkinter, pyodbc, and base64 if you dont have them already.
from tkinter import *
import pyodbc
import base64, sys
image_string = <insertBase64texthere>
# main window with all needed functions in the class
class Main:
def __... | code_fim | hard | {
"lang": "python",
"repo": "MTBriles/DUPSUID_APP",
"path": "/dupsuid.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def on_close(event):
print('Closed Figure!')
global close_by_user
close_by_user = True
def VisualizeDataset(Dataset):
global close_by_user
close_by_user = False
fig = plt.figure()
fig.canvas.mpl_connect('close_event', on_close)
n_samples = Dataset.shape[0]
for n in ra... | code_fim | medium | {
"lang": "python",
"repo": "anyou-jiang/20210703",
"path": "/VisualizeDataset.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: anyou-jiang/20210703 path: /VisualizeDataset.py
import matplotlib.pyplot as plt
from ShowPose import ShowPose
close_by_user = False
def on_close(event):
<|fim_suffix|> n_samples = Dataset.shape[0]
for n in range(n_samples):
pose = Dataset[n]
img = ShowPose(pose)
p... | code_fim | hard | {
"lang": "python",
"repo": "anyou-jiang/20210703",
"path": "/VisualizeDataset.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: BkrmDahal/utilpy path: /tests/utilspy_test.py
import unittest
from ..utilpy import utils
class Testutils(unittest.TestCase):
<|fim_suffix|> self.soup = utils.page_soup("https://twitter.com")
self.len = len(self.soup.get_text())
self.assertGreater(self.len, 100)
def t... | code_fim | medium | {
"lang": "python",
"repo": "BkrmDahal/utilpy",
"path": "/tests/utilspy_test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_walk_directory(self):
self.files = utils.walk_directory(".")
self.assertIsNotNone(self.files)
if __name__ == "__main__":
unittest.main()<|fim_prefix|># repo: BkrmDahal/utilpy path: /tests/utilspy_test.py
import unittest
from ..utilpy import utils
class Testutils(unitt... | code_fim | hard | {
"lang": "python",
"repo": "BkrmDahal/utilpy",
"path": "/tests/utilspy_test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def get_field_values(field_config, data_in):
fields = {}
for (key, value) in field_config.items():
try:
key_conf = key.split(":")
key = key_conf[0]
key_type = key_conf[1]
# val = Tree(data_in).execute('$.' + value)
val = get_value... | code_fim | hard | {
"lang": "python",
"repo": "SENERGY-Platform/kafka2InfluxDB",
"path": "/lib/lib.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>class Kafka2Influx:
def __init__(self,
consumer,
topic,
influx_client: InfluxDBClient,
data_filter_id_mapping,
data_filter_id,
data_measurement,
data_time_mapping,
f... | code_fim | hard | {
"lang": "python",
"repo": "SENERGY-Platform/kafka2InfluxDB",
"path": "/lib/lib.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: SENERGY-Platform/kafka2InfluxDB path: /lib/lib.py
# Copyright 2020 InfAI (CC SES)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... | code_fim | hard | {
"lang": "python",
"repo": "SENERGY-Platform/kafka2InfluxDB",
"path": "/lib/lib.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Pathoschild/smapi-mod-dump path: /source/Lasting Conversation Topics/games/game_kerbalspaceprogram.py
from os import path
from pathlib import Path
import mobase
from ..basic_features import BasicGameSaveGameInfo
from ..basic_features.basic_save_game_info import BasicGameSaveGame
from ..basic_ga... | code_fim | hard | {
"lang": "python",
"repo": "Pathoschild/smapi-mod-dump",
"path": "/source/Lasting Conversation Topics/games/game_kerbalspaceprogram.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def init(self, organizer):
super().init(organizer)
self._featureMap[mobase.SaveGameInfo] = BasicGameSaveGameInfo(
lambda s: str(
Path(s).parent.joinpath("banners").joinpath(f"{Path(s).stem}.png")
)
)
return True
def listSaves... | code_fim | hard | {
"lang": "python",
"repo": "Pathoschild/smapi-mod-dump",
"path": "/source/Lasting Conversation Topics/games/game_kerbalspaceprogram.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class TestCheckIsPrimeNumber(TestCase):
def test_with_prime_numbers(self):
self.assertTrue(_check_is_prime_number(5))
self.assertTrue(_check_is_prime_number(97))
self.assertTrue(_check_is_prime_number(89))
def test_with_numbers_that_are_not_prime(self):
self.asser... | code_fim | hard | {
"lang": "python",
"repo": "Risoko/RSA-Encryption",
"path": "/main/rsa_encryption/tests/test_prime_number_tools.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Risoko/RSA-Encryption path: /main/rsa_encryption/tests/test_prime_number_tools.py
from unittest import TestCase, main
from rsa_encryption.tools.prime_numbers_tools import (
_get_number_divisiors, _check_is_prime_number, get_two_numbers_prime
)
class TestGetNumberDivisiors(TestCase):
... | code_fim | hard | {
"lang": "python",
"repo": "Risoko/RSA-Encryption",
"path": "/main/rsa_encryption/tests/test_prime_number_tools.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_with_prime_numbers(self):
self.assertTrue(_check_is_prime_number(5))
self.assertTrue(_check_is_prime_number(97))
self.assertTrue(_check_is_prime_number(89))
def test_with_numbers_that_are_not_prime(self):
self.assertFalse(_check_is_prime_number(6))
... | code_fim | hard | {
"lang": "python",
"repo": "Risoko/RSA-Encryption",
"path": "/main/rsa_encryption/tests/test_prime_number_tools.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: qlik-oss/core-grpc-prometheus-connector path: /src/prom.py
import requests
import connector_pb2
from datetime import timezone, datetime
scrape_timestamp = None
def build_metadata(results):
"""
Builds up the MetaData object needed by engine to figure out which fields
the data contain.
""... | code_fim | hard | {
"lang": "python",
"repo": "qlik-oss/core-grpc-prometheus-connector",
"path": "/src/prom.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return metadata
def set_value(result, fieldName, chunk):
is_string = True
value = None
if fieldName == 'name':
# we normalize the metric name from __name__
value = result['metric'].get('__name__', '')
elif fieldName == 'timestamp':
# timestamp is the first value from each metric, a... | code_fim | hard | {
"lang": "python",
"repo": "qlik-oss/core-grpc-prometheus-connector",
"path": "/src/prom.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def fetch(prom_url, query_expr):
"""
Fetch data from Prometheus, transform it, and return gRPC-compatible
data structures.
"""
global scrape_timestamp
scrape_timestamp = int(datetime.now(tz=timezone.utc).timestamp() * 1000)
response = requests.get(prom_url, params={ 'query': query_expr })
... | code_fim | hard | {
"lang": "python",
"repo": "qlik-oss/core-grpc-prometheus-connector",
"path": "/src/prom.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.