uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
1b06c74271840abc04d859c1
train
class
class LDAPTestSetup(unit.TestCase): """Common setup for LDAP tests.""" def setUp(self): super(LDAPTestSetup, self).setUp() self.ldapdb = self.useFixture(ldapdb.LDAPDatabase()) self.load_backends() self.load_fixtures(default_fixtures)
class LDAPTestSetup(unit.TestCase):
"""Common setup for LDAP tests.""" def setUp(self): super(LDAPTestSetup, self).setUp() self.ldapdb = self.useFixture(ldapdb.LDAPDatabase()) self.load_backends() self.load_fixtures(default_fixtures)
Resource LDAP has been removed') def test_check_hierarchy_depth(self): self.skip_test_overrides('Resource LDAP has been removed') def test_list_projects_for_alternate_domain(self): self.skip_test_overrides('N/A: LDAP does not support multiple domains') class LDAPTestSetup(unit.TestCase):
64
64
67
8
56
jiwanlimbu/aura
keystone/tests/unit/test_backend_ldap.py
Python
LDAPTestSetup
LDAPTestSetup
300
307
300
300
227e87c74eae06a2b5fe8d3dda1af71dc024d5d4
bigcode/the-stack
train
6ca6a759112ca8f19c3768cb
train
class
class BaseMultiLDAPandSQLIdentity(object): """Mixin class with support methods for domain-specific config testing.""" def create_users_across_domains(self): """Create a set of users, each with a role on their own domain.""" # We also will check that the right number of id mappings get created ...
class BaseMultiLDAPandSQLIdentity(object):
"""Mixin class with support methods for domain-specific config testing.""" def create_users_across_domains(self): """Create a set of users, each with a role on their own domain.""" # We also will check that the right number of id mappings get created initial_mappings = len(mapping_sql.l...
appings({'public_id': user1['id']}) self.id_mapping_api.purge_mappings({'public_id': user2['id']}) # We should no longer be able to get these users via their old IDs self.assertRaises(exception.UserNotFound, self.identity_api.get_user, user1['...
220
220
734
9
211
jiwanlimbu/aura
keystone/tests/unit/test_backend_ldap.py
Python
BaseMultiLDAPandSQLIdentity
BaseMultiLDAPandSQLIdentity
2,181
2,267
2,181
2,181
ca3050387a44814cad332150d24973aca55e0fc1
bigcode/the-stack
train
e96c79810783e43b32754482
train
function
def create_group_container(identity_api): # Create the groups base entry (ou=Groups,cn=example,cn=com) group_api = identity_api.driver.group conn = group_api.get_connection() dn = 'ou=Groups,cn=example,cn=com' conn.add_s(dn, [('objectclass', ['organizationalUnit']), ('ou', ['Grou...
def create_group_container(identity_api): # Create the groups base entry (ou=Groups,cn=example,cn=com)
group_api = identity_api.driver.group conn = group_api.get_connection() dn = 'ou=Groups,cn=example,cn=com' conn.add_s(dn, [('objectclass', ['organizationalUnit']), ('ou', ['Groups'])])
_assert_equal(expected_cls, observed_cls, subsystem, domain) else: raise ValueError('%r is not an expected value for entrypoint name' % entrypoint_name) def create_group_container(identity_api): # Create the groups base entry (ou=Groups,cn=example,cn=com)
64
64
82
26
38
jiwanlimbu/aura
keystone/tests/unit/test_backend_ldap.py
Python
create_group_container
create_group_container
114
120
114
115
884020c3045dbc7e0fae5add26ce6e52ef60c7df
bigcode/the-stack
train
c77cc9e53aff077b174ab215
train
class
class LDAPMatchingRuleInChainTests(LDAPTestSetup): def setUp(self): self.useFixture(database.Database()) super(LDAPMatchingRuleInChainTests, self).setUp() _assert_backends(self, identity='ldap') group = unit.new_group_ref(domain_id=CONF.identity.default_domain_id) self.grou...
class LDAPMatchingRuleInChainTests(LDAPTestSetup):
def setUp(self): self.useFixture(database.Database()) super(LDAPMatchingRuleInChainTests, self).setUp() _assert_backends(self, identity='ldap') group = unit.new_group_ref(domain_id=CONF.identity.default_domain_id) self.group = self.identity_api.create_group(group) u...
_inexact_filtered(self): # The LDAP identity driver currently does not support filtering on the # listing users for a given group, so will fail this test. super(LdapFilterTests, self).test_list_users_in_group_inexact_filtered() @wip('Not supported by LDAP identity driver') ...
134
134
449
12
122
jiwanlimbu/aura
keystone/tests/unit/test_backend_ldap.py
Python
LDAPMatchingRuleInChainTests
LDAPMatchingRuleInChainTests
3,126
3,180
3,126
3,127
99824fee2e50818dd8b6dde916087b66340c4987
bigcode/the-stack
train
3c83f1b38418eb55903d0385
train
class
class DomainSpecificSQLIdentity(DomainSpecificLDAPandSQLIdentity): """Class to test simplest use of domain-specific SQL driver. The simplest use of an SQL domain-specific backend is when it is used to augment the standard case when LDAP is the default driver defined in the main config file. This would ...
class DomainSpecificSQLIdentity(DomainSpecificLDAPandSQLIdentity):
"""Class to test simplest use of domain-specific SQL driver. The simplest use of an SQL domain-specific backend is when it is used to augment the standard case when LDAP is the default driver defined in the main config file. This would allow, for example, service users to be stored in SQL while LDA...
With this restricted multi LDAP class, tests that use multiple # domains and identity, are still not supported self.assertRaises( exception.DomainNotFound, super(BaseLDAPIdentity, self).test_delete_domain_with_project_api) def test_create_project_with_domain_id_and_without_...
243
243
810
13
230
jiwanlimbu/aura
keystone/tests/unit/test_backend_ldap.py
Python
DomainSpecificSQLIdentity
DomainSpecificSQLIdentity
3,005
3,093
3,005
3,005
27514444e380907f3e8990c1134a610997926f64
bigcode/the-stack
train
f02880d8f171da84daaf3fef
train
class
class LdapIdentityWithMapping( BaseLDAPIdentity, unit.SQLDriverOverrides, unit.TestCase): """Class to test mapping of default LDAP backend. The default configuration is not to enable mapping when using a single backend LDAP driver. However, a cloud provider might want to enable the mapping, he...
class LdapIdentityWithMapping( BaseLDAPIdentity, unit.SQLDriverOverrides, unit.TestCase):
"""Class to test mapping of default LDAP backend. The default configuration is not to enable mapping when using a single backend LDAP driver. However, a cloud provider might want to enable the mapping, hence hiding the LDAP IDs from any clients of keystone. Setting backward_compatible_ids to False...
# rather than going through the manager. group_api = self.identity_api.driver.group group_ref = group_api.get(new_group['id']) mod = (ldap.MOD_ADD, group_api.member_attribute, new_user['id']) conn = group_api.get_connection() conn.modify_s(group_ref['dn'], [mod]) ...
190
190
636
21
169
jiwanlimbu/aura
keystone/tests/unit/test_backend_ldap.py
Python
LdapIdentityWithMapping
LdapIdentityWithMapping
2,107
2,178
2,107
2,108
c5e8f57ee032a8edf8319cdd8decd60c835979a6
bigcode/the-stack
train
2654deb0af43493b1cb3a606
train
function
def test_2D_rosenbrock_frozen(): opti = asb.Opti() # set up an optimization environment # Define optimization variables x = opti.variable(init_guess=1) y = opti.variable(init_guess=0, freeze=True) # Define objective f = (a - x) ** 2 + b * (y - x ** 2) ** 2 opti.minimize(f) # Optimize...
def test_2D_rosenbrock_frozen():
opti = asb.Opti() # set up an optimization environment # Define optimization variables x = opti.variable(init_guess=1) y = opti.variable(init_guess=0, freeze=True) # Define objective f = (a - x) ** 2 + b * (y - x ** 2) ** 2 opti.minimize(f) # Optimize sol = opti.solve() asse...
odal for all N. opti.minimize(objective) sol = opti.solve() # solve for i in range(N): assert sol.value(x[i]) == pytest.approx(1, abs=1e-4) def test_2D_rosenbrock_frozen():
64
64
174
12
52
msberk/AeroSandbox
aerosandbox/optimization/test_optimization/test_opti_rosenbrock.py
Python
test_2D_rosenbrock_frozen
test_2D_rosenbrock_frozen
87
103
87
87
00367ce0a7dd97071d0a9556b560ace15b194e67
bigcode/the-stack
train
04f0d6c357bc0b2a05504e26
train
function
def test_2D_rosenbrock(): # 2-dimensional rosenbrock opti = asb.Opti() # set up an optimization environment # Define optimization variables x = opti.variable(init_guess=0) y = opti.variable(init_guess=0) # Define objective f = (a - x) ** 2 + b * (y - x ** 2) ** 2 opti.minimize(f) # ...
def test_2D_rosenbrock(): # 2-dimensional rosenbrock
opti = asb.Opti() # set up an optimization environment # Define optimization variables x = opti.variable(init_guess=0) y = opti.variable(init_guess=0) # Define objective f = (a - x) ** 2 + b * (y - x ** 2) ** 2 opti.minimize(f) # Optimize sol = opti.solve() for i in [x, y]: ...
[i+1]-x[i]**2)**2 + (1-x[i])**2) for i in [1, N-1] """ # Constants a = 1 b = 100 def test_2D_rosenbrock(): # 2-dimensional rosenbrock
64
64
144
20
43
msberk/AeroSandbox
aerosandbox/optimization/test_optimization/test_opti_rosenbrock.py
Python
test_2D_rosenbrock
test_2D_rosenbrock
25
40
25
25
4e0c1e0eb7c3e6882fee56691ca912d3052830af
bigcode/the-stack
train
c0927c6d77afbb99beb4575c
train
function
def test_ND_rosenbrock_constrained(N=10): # N-dimensional rosenbrock # Problem is unimodal for N=2, N=3, and N>=8. Bimodal for 4<=N<=7. Global min is always a vector of ones. opti = asb.Opti() # set up an optimization environment x = opti.variable(init_guess=1, n_vars=N) # vector of variables obje...
def test_ND_rosenbrock_constrained(N=10): # N-dimensional rosenbrock # Problem is unimodal for N=2, N=3, and N>=8. Bimodal for 4<=N<=7. Global min is always a vector of ones.
opti = asb.Opti() # set up an optimization environment x = opti.variable(init_guess=1, n_vars=N) # vector of variables objective = 0 for i in range(N - 1): objective += 100 * (x[i + 1] - x[i] ** 2) ** 2 + (1 - x[i]) ** 2 opti.subject_to(x >= 0) # Keeps design space unimodal for all N. ...
-2 ) def test_ND_rosenbrock_constrained(N=10): # N-dimensional rosenbrock # Problem is unimodal for N=2, N=3, and N>=8. Bimodal for 4<=N<=7. Global min is always a vector of ones.
66
66
221
63
3
msberk/AeroSandbox
aerosandbox/optimization/test_optimization/test_opti_rosenbrock.py
Python
test_ND_rosenbrock_constrained
test_ND_rosenbrock_constrained
66
84
66
68
4af5f803e1730e405a2d57e9e53a1de3fa2da38a
bigcode/the-stack
train
6eb1b108d73fd9d75b2436af
train
function
def test_2D_rosenbrock_circle_constrained(): # 2-dimensional rosenbrock, constrained to be within the unit circle. opti = asb.Opti() # set up an optimization environment # Define optimization variables x = opti.variable(init_guess=0) y = opti.variable(init_guess=0) # Define constraints opti....
def test_2D_rosenbrock_circle_constrained(): # 2-dimensional rosenbrock, constrained to be within the unit circle.
opti = asb.Opti() # set up an optimization environment # Define optimization variables x = opti.variable(init_guess=0) y = opti.variable(init_guess=0) # Define constraints opti.subject_to(x ** 2 + y ** 2 <= 1) # Define objective f = (a - x) ** 2 + b * (y - x ** 2) ** 2 opti.minim...
opti.solve() for i in [x, y]: assert sol.value(i) == pytest.approx(1, abs=1e-4) def test_2D_rosenbrock_circle_constrained(): # 2-dimensional rosenbrock, constrained to be within the unit circle.
64
64
199
31
33
msberk/AeroSandbox
aerosandbox/optimization/test_optimization/test_opti_rosenbrock.py
Python
test_2D_rosenbrock_circle_constrained
test_2D_rosenbrock_circle_constrained
43
62
43
43
b13ae7414112c4a8ff2cf0adacb3766e9def0a72
bigcode/the-stack
train
ccca98ccef51936ab0e2204e
train
function
def _recognize_fan_count(img: Image) -> int: cv_img = imagetools.cv_image(img.convert("L")) cv_img = imagetools.level( cv_img, np.percentile(cv_img, 1), np.percentile(cv_img, 90) ) _, binary_img = cv2.threshold(cv_img, 50, 255, cv2.THRESH_BINARY_INV) if os.getenv("DEBUG") == __name__: ...
def _recognize_fan_count(img: Image) -> int:
cv_img = imagetools.cv_image(img.convert("L")) cv_img = imagetools.level( cv_img, np.percentile(cv_img, 1), np.percentile(cv_img, 90) ) _, binary_img = cv2.threshold(cv_img, 50, 255, cv2.THRESH_BINARY_INV) if os.getenv("DEBUG") == __name__: cv2.imshow("cv_img", cv_img) cv2.im...
((170, 81, 255), rgb_color) > 0.9: return Context.MOOD_VERY_BAD raise ValueError("_recognize_mood: unknown mood color: %s" % (rgb_color,)) def _recognize_fan_count(img: Image) -> int:
63
64
159
14
50
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
_recognize_fan_count
_recognize_fan_count
86
98
86
86
db872f9a1f82be42414db522b8ebb55a550fdbae
bigcode/the-stack
train
3420c094ee914c3b76d6b79e
train
class
class g: context_class: Type[Context]
class g:
context_class: Type[Context]
, List, Set, Text, Tuple, Type import cast_unknown as cast import cv2 import numpy as np from PIL.Image import Image from PIL.Image import fromarray as image_from_array from .. import imagetools, ocr, template, templates, mathtools class g:
64
64
11
3
60
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
g
g
17
18
17
17
26c6d2a1ce8f282868046d349647b66b3d72a74f
bigcode/the-stack
train
3255c5126ef74499464b6b82
train
function
def _recognize_conditions(img: Image) -> Set[int]: ret: Set[int] = set() for tmpl, _ in template.match( img, *_CONDITION_TEMPLATES.keys(), ): ret.add(_CONDITION_TEMPLATES[tmpl.name]) return ret
def _recognize_conditions(img: Image) -> Set[int]:
ret: Set[int] = set() for tmpl, _ in template.match( img, *_CONDITION_TEMPLATES.keys(), ): ret.add(_CONDITION_TEMPLATES[tmpl.name]) return ret
expected_score g.context_class = Context _CONDITION_TEMPLATES = { templates.SINGLE_MODE_CONDITION_HEADACHE: Context.CONDITION_HEADACHE, templates.SINGLE_MODE_CONDITION_OVERWEIGHT: Context.CONDITION_OVERWEIGHT, } def _recognize_conditions(img: Image) -> Set[int]:
64
64
62
13
51
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
_recognize_conditions
_recognize_conditions
412
419
412
412
5c93f1d8d5cdc4ca0ca6a2582f424199ce10b520
bigcode/the-stack
train
e432793a22d812bcb91b04e3
train
function
def _recognize_status(img: Image) -> Tuple[int, Text]: cv_img = imagetools.cv_image(imagetools.resize(img.convert("L"), height=64)) cv_img = imagetools.level( cv_img, np.percentile(cv_img, 5), np.percentile(cv_img, 95) ) cv_img = cv2.copyMakeBorder(cv_img, 4, 4, 4, 4, cv2.BORDER_CONSTANT, value=...
def _recognize_status(img: Image) -> Tuple[int, Text]:
cv_img = imagetools.cv_image(imagetools.resize(img.convert("L"), height=64)) cv_img = imagetools.level( cv_img, np.percentile(cv_img, 5), np.percentile(cv_img, 95) ) cv_img = cv2.copyMakeBorder(cv_img, 4, 4, 4, 4, cv2.BORDER_CONSTANT, value=(255,)) blurred_img = cv2.medianBlur(cv_img, 7) ...
binary_img = cv2.threshold(cv_img, 50, 255, cv2.THRESH_BINARY_INV) if os.getenv("DEBUG") == __name__: cv2.imshow("cv_img", cv_img) cv2.imshow("binary_img", binary_img) cv2.waitKey() cv2.destroyAllWindows() text = ocr.text(imagetools.pil_image(binary_img)) return int(text.rst...
111
111
370
15
96
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
_recognize_status
_recognize_status
101
134
101
101
05650ddadb2a613026a7a78f40d8ef9770255729
bigcode/the-stack
train
7bc899496e1a7ebc7f276293
train
function
def _recognize_property(img: Image) -> int: max_match = imagetools.constant_color_key( imagetools.cv_image(img), (210, 249, 255), threshold=0.95, ) if np.average(max_match) > 5: return 1200 cv_img = np.asarray(img.convert("L")) cv_img = imagetools.level( cv_i...
def _recognize_property(img: Image) -> int:
max_match = imagetools.constant_color_key( imagetools.cv_image(img), (210, 249, 255), threshold=0.95, ) if np.average(max_match) > 5: return 1200 cv_img = np.asarray(img.convert("L")) cv_img = imagetools.level( cv_img, np.percentile(cv_img, 10), np.percentile...
ocr.text(imagetools.pil_image(text_img)) for i in Context.ALL_STATUSES: if i[1] == text: return i raise ValueError("_recognize_status: unknown status: %s" % text) def _recognize_property(img: Image) -> int:
64
64
214
12
52
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
_recognize_property
_recognize_property
137
158
137
137
2ce00beb98f1853de6ecbeaefcd7f8f0a286e6f1
bigcode/the-stack
train
3ad692e5b5a7ad97fe3ee385
train
function
def _recognize_vitality(img: Image) -> float: cv_img = np.asarray(img) def _is_empty(v: np.ndarray) -> bool: assert v.shape == (3,), v.shape return ( imagetools.compare_color((118, 117, 118), (int(v[0]), int(v[1]), int(v[2]))) > 0.99 ) return 1 - np.average(...
def _recognize_vitality(img: Image) -> float:
cv_img = np.asarray(img) def _is_empty(v: np.ndarray) -> bool: assert v.shape == (3,), v.shape return ( imagetools.compare_color((118, 117, 118), (int(v[0]), int(v[1]), int(v[2]))) > 0.99 ) return 1 - np.average(np.apply_along_axis(_is_empty, 1, cv_img[0, :]...
"シニア級": 3}[year_text] month = int(month_text[:-1]) date = {"前半": 1, "後半": 2}[date_text] return (year, month, date) def _recognize_vitality(img: Image) -> float:
64
64
115
14
50
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
_recognize_vitality
_recognize_vitality
59
69
59
59
a6f3300cc8c00c33b6ff5b2f62c6e692ebaf910a
bigcode/the-stack
train
8cbf49f812fd8e91189f21c4
train
class
class Context: MOOD_VERY_BAD = (0.8, 0.95) MOOD_BAD = (0.9, 0.98) MOOD_NORMAL = (1.0, 1.0) MOOD_GOOD = (1.1, 1.05) MOOD_VERY_GOOD = (1.2, 1.1) CONDITION_HEADACHE = 1 CONDITION_OVERWEIGHT = 2 STATUS_S = (8, "S") STATUS_A = (7, "A") STATUS_B = (6, "B") STATUS_C = (5, "C") ...
class Context:
MOOD_VERY_BAD = (0.8, 0.95) MOOD_BAD = (0.9, 0.98) MOOD_NORMAL = (1.0, 1.0) MOOD_GOOD = (1.1, 1.05) MOOD_VERY_GOOD = (1.2, 1.1) CONDITION_HEADACHE = 1 CONDITION_OVERWEIGHT = 2 STATUS_S = (8, "S") STATUS_A = (7, "A") STATUS_B = (6, "B") STATUS_C = (5, "C") STATUS_D = (4,...
i in Context.ALL_STATUSES: if i[1] == text: return i raise ValueError("_recognize_status: unknown status: %s" % text) def _recognize_property(img: Image) -> int: max_match = imagetools.constant_color_key( imagetools.cv_image(img), (210, 249, 255), threshold=0.95, ...
255
256
2,522
3
252
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
Context
Context
161
401
161
161
cd0bacb5a75427949929b67f74b7bac73401bcd9
bigcode/the-stack
train
68e02157029af78a6c777e48
train
function
def _recognize_mood(rgb_color: Tuple[int, int, int]) -> Tuple[float, float]: if imagetools.compare_color((250, 68, 126), rgb_color) > 0.9: return Context.MOOD_VERY_GOOD if imagetools.compare_color((255, 124, 57), rgb_color) > 0.9: return Context.MOOD_GOOD if imagetools.compare_color((255, 16...
def _recognize_mood(rgb_color: Tuple[int, int, int]) -> Tuple[float, float]:
if imagetools.compare_color((250, 68, 126), rgb_color) > 0.9: return Context.MOOD_VERY_GOOD if imagetools.compare_color((255, 124, 57), rgb_color) > 0.9: return Context.MOOD_GOOD if imagetools.compare_color((255, 162, 0), rgb_color) > 0.9: return Context.MOOD_NORMAL if imagetools...
int(v[2]))) > 0.99 ) return 1 - np.average(np.apply_along_axis(_is_empty, 1, cv_img[0, :])) def _recognize_mood(rgb_color: Tuple[int, int, int]) -> Tuple[float, float]:
63
64
211
23
40
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
_recognize_mood
_recognize_mood
72
83
72
72
7cd45c8ea9325407ea9d4185d6ee37c67612eff7
bigcode/the-stack
train
9310dc08219b6f19c02506e9
train
function
def _ocr_date(img: Image) -> Tuple[int, int, int]: img = imagetools.resize(img, height=32) cv_img = np.asarray(img.convert("L")) cv_img = imagetools.level( cv_img, np.array(10), np.array(240), ) sharpened_img = imagetools.sharpen(cv_img) sharpened_img = imagetools.mix(sha...
def _ocr_date(img: Image) -> Tuple[int, int, int]:
img = imagetools.resize(img, height=32) cv_img = np.asarray(img.convert("L")) cv_img = imagetools.level( cv_img, np.array(10), np.array(240), ) sharpened_img = imagetools.sharpen(cv_img) sharpened_img = imagetools.mix(sharpened_img, cv_img, 0.5) _, binary_img = cv2.th...
# -*- coding=UTF-8 -*- # pyright: strict from __future__ import annotations import os from typing import Callable, List, Set, Text, Tuple, Type import cast_unknown as cast import cv2 import numpy as np from PIL.Image import Image from PIL.Image import fromarray as image_from_array from .. import imagetools, ocr, tem...
115
120
403
16
99
gitter-badger/auto-derby
auto_derby/single_mode/context.py
Python
_ocr_date
_ocr_date
21
56
21
21
98ebf998c95d9b94c83c904de02e3cb9f7529800
bigcode/the-stack
train
251437b8cdf6c762fba346a4
train
class
class APIUnitTestServicesDnsmasqRestart(unit_test_framework.APIUnitTest): uri = "/api/v1/services/dnsmasq/restart" post_tests = [ { "name": "Restart the dnsmasq service", "resp_time": 5 # Allow 5 seconds for dnsmasq to restart } ]
class APIUnitTestServicesDnsmasqRestart(unit_test_framework.APIUnitTest):
uri = "/api/v1/services/dnsmasq/restart" post_tests = [ { "name": "Restart the dnsmasq service", "resp_time": 5 # Allow 5 seconds for dnsmasq to restart } ]
License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unit_test_framework class APIUnitTestServicesDnsmasqRestart(unit_test_framework.APIUnitTe...
64
64
74
16
47
jaredhendrickson13/pfsense-api
tests/test_api_v1_services_dnsmasq_restart.py
Python
APIUnitTestServicesDnsmasqRestart
APIUnitTestServicesDnsmasqRestart
17
24
17
17
edc99cc3ce86f827215c23e12bd0e5e7fa18b032
bigcode/the-stack
train
ea7d56808ef5cde16fb19c24
train
function
def tr(string): translation = QCoreApplication.translate("General", string) return translation
def tr(string):
translation = QCoreApplication.translate("General", string) return translation
QObject except: from PySide.QtCore import QCoreApplication, QLocale, QTranslator, QObject # Translation. translations_folder = os.path.join(app_folder, "translations") translator = QTranslator(QCoreApplication.instance()) translator.load(app_locale, translations_folder) _translator = QObject() def tr(string):
64
64
20
4
60
neurodiverseEsoteric/nimbus
lib/translate.py
Python
tr
tr
27
29
27
27
15f2882b1441742e8001d084bb121272d47035f8
bigcode/the-stack
train
6ec475d5f5b7e9fee74aff40
train
function
def translate(string): return tr(string)
def translate(string):
return tr(string)
, QObject # Translation. translations_folder = os.path.join(app_folder, "translations") translator = QTranslator(QCoreApplication.instance()) translator.load(app_locale, translations_folder) _translator = QObject() def tr(string): translation = QCoreApplication.translate("General", string) return translation...
64
64
9
4
59
neurodiverseEsoteric/nimbus
lib/translate.py
Python
translate
translate
31
32
31
31
888939ccc463629c82e0903134c63b0246af82d2
bigcode/the-stack
train
0f333f098f8d3a6a00ae8aef
train
class
class Settings: #游戏设置类 def __init__(self): self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230,230,230)
class Settings: #游戏设置类
def __init__(self): self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230,230,230)
class Settings: #游戏设置类
9
64
45
9
0
OctopodaMeng/LearningPython
settings.py
Python
Settings
Settings
1
6
1
2
5023ed3cc5dee2bd0e5f029bf55417b022cc072f
bigcode/the-stack
train
077ed5b74db315a29a00e96c
train
function
def update_version(): with open(f"{os.path.dirname(__file__)}/covid-blockchain-gui/package.json") as f: data = json.load(f) version: str = "0.0" output = subprocess.run(["covid", "version"], capture_output=True) if output.returncode == 0: version = str(output.stdout.strip(), "utf-8") ...
def update_version():
with open(f"{os.path.dirname(__file__)}/covid-blockchain-gui/package.json") as f: data = json.load(f) version: str = "0.0" output = subprocess.run(["covid", "version"], capture_output=True) if output.returncode == 0: version = str(output.stdout.strip(), "utf-8") data["version"] = m...
) local = v.local version = "{0}.{1}.{2}".format(major, minor, patch) if prerelease: version += "-{0}".format(prerelease) if local: version += "+{0}".format(local) return version def update_version():
64
64
133
4
59
grayfallstown/covid-blockchain
installhelper.py
Python
update_version
update_version
49
61
49
49
bca47f5a2959a3624fe840111cc64707e8e138e7
bigcode/the-stack
train
e433c55dd84575d6622e14c3
train
function
def make_semver(version_str): v = parse_version(version_str) major = v._version.release[0] try: minor = v._version.release[1] except IndexError: minor = 0 try: patch = v._version.release[2] except IndexError: patch = 0 prerelease = [] if v._version.pre: ...
def make_semver(version_str):
v = parse_version(version_str) major = v._version.release[0] try: minor = v._version.release[1] except IndexError: minor = 0 try: patch = v._version.release[2] except IndexError: patch = 0 prerelease = [] if v._version.pre: prerelease.append("".jo...
from pkg_resources import parse_version # # The following function is borrowed from # https://github.com/inveniosoftware/invenio-assets/blob/maint-1.0/invenio_assets/npm.py # Copyright (C) 2015-2018 CERN. # def make_semver(version_str):
64
64
198
7
57
grayfallstown/covid-blockchain
installhelper.py
Python
make_semver
make_semver
18
46
18
18
0ac8fd6eb6f0dc947a6d0f8ec788eb317e0adf0f
bigcode/the-stack
train
a5117aee4e7efa9db4674445
train
function
def to_binary(decimal_value: str): """ Returns Binary format of the decimal value param """ new_decimal = decimal_value.split('.') value_list = [] result_decimals_list = [] try: for value in new_decimal: try: if value[0] == '0' and len(value) > 1: ...
def to_binary(decimal_value: str):
""" Returns Binary format of the decimal value param """ new_decimal = decimal_value.split('.') value_list = [] result_decimals_list = [] try: for value in new_decimal: try: if value[0] == '0' and len(value) > 1: return print("No Decimal With L...
# A function to convert dotted decimal value to binary value def to_binary(decimal_value: str):
20
124
416
8
11
ShedrackGodson/pySubnet
dotted_decimal_to_binary.py
Python
to_binary
to_binary
2
52
2
2
4ca9d584402d34b86508f22900b17c26348521c8
bigcode/the-stack
train
308afcb530d473f0c62c041a
train
function
def _do_handshake(socket, worker_id): logger.debug("Sending hello") socket.send(b"HELO IAM " + worker_id.encode("utf-8")) logger.debug("Awaiting confirmation of hello recieved") assert socket.recv() == b"HAY" logger.debug("Got hello. Going into task loop")
def _do_handshake(socket, worker_id):
logger.debug("Sending hello") socket.send(b"HELO IAM " + worker_id.encode("utf-8")) logger.debug("Awaiting confirmation of hello recieved") assert socket.recv() == b"HAY" logger.debug("Got hello. Going into task loop")
.dumps(exc_value) except pickle.PicklingError: exc_value = ExceptionPicklingError("{}: {}".format( str(type(exc_value)), str(exc_value))) return b"ONO " + pickle.dumps((task_id, exc_trace, exc_value)) def _do_handshake(socket, worker_id):
64
64
68
10
54
ndevenish/drmaa_futures
drmaa_futures/slave.py
Python
_do_handshake
_do_handshake
61
66
61
61
646bae232bcac2b99548d91b8963b6dda37be4a0
bigcode/the-stack
train
e81b8bbd8568d145700b960b
train
function
def run_slave(server_url, worker_id, timeout=30): """Run a slave instance and connect it to a specific master URL. :param str server_url: The server string to use to connect :param str worker_if: The worker ID to use when communicating :param timeout: The time (in seconds) to wait with no jobs before terminati...
def run_slave(server_url, worker_id, timeout=30):
"""Run a slave instance and connect it to a specific master URL. :param str server_url: The server string to use to connect :param str worker_if: The worker ID to use when communicating :param timeout: The time (in seconds) to wait with no jobs before terminating """ logger.debug("Running slave {} connect ...
Awaiting confirmation of hello recieved") assert socket.recv() == b"HAY" logger.debug("Got hello. Going into task loop") def _handle_task(socket, data): """Handle a reply asking us to do a task""" try: (task_id, task_function) = pickle.loads(data) logger.debug("Got task %s (%d bytes)", task_id, len(da...
176
176
589
13
162
ndevenish/drmaa_futures
drmaa_futures/slave.py
Python
run_slave
run_slave
84
143
84
84
30ec2d40a0d44a8e6db7414e9e0e2d041dc0f1a6
bigcode/the-stack
train
5cf0408528685fc813586dcd
train
class
class TaskSystemExit(Exception): """For when the task raised a SystemExit exception, trying to quit"""
class TaskSystemExit(Exception):
"""For when the task raised a SystemExit exception, trying to quit"""
""" Running a slave instance. """ import logging import sys import time import traceback import dill as pickle import zmq logger = logging.getLogger(__name__) class ExceptionPicklingError(Exception): """Represent an error attempting to pickle the result of a task""" class TaskSystemExit(Exception):
64
64
22
6
58
ndevenish/drmaa_futures
drmaa_futures/slave.py
Python
TaskSystemExit
TaskSystemExit
21
22
21
21
ae04c0ce1663afdef3f42c0dd720ee7962a6b7d5
bigcode/the-stack
train
3871d7c2916fc4751f39d79a
train
class
class ExceptionPicklingError(Exception): """Represent an error attempting to pickle the result of a task"""
class ExceptionPicklingError(Exception):
"""Represent an error attempting to pickle the result of a task"""
# coding: utf-8 """ Running a slave instance. """ import logging import sys import time import traceback import dill as pickle import zmq logger = logging.getLogger(__name__) class ExceptionPicklingError(Exception):
50
64
21
7
43
ndevenish/drmaa_futures
drmaa_futures/slave.py
Python
ExceptionPicklingError
ExceptionPicklingError
17
18
17
17
f297046833c6c0a98a00b0aad497642172326c4b
bigcode/the-stack
train
b0542536cc4ca3cbcb448c77
train
function
def _handle_task(socket, data): """Handle a reply asking us to do a task""" try: (task_id, task_function) = pickle.loads(data) logger.debug("Got task %s (%d bytes)", task_id, len(data)) return do_task(task_id, task_function) except KeyboardInterrupt as exc: # This is a special case; try to tell th...
def _handle_task(socket, data):
"""Handle a reply asking us to do a task""" try: (task_id, task_function) = pickle.loads(data) logger.debug("Got task %s (%d bytes)", task_id, len(data)) return do_task(task_id, task_function) except KeyboardInterrupt as exc: # This is a special case; try to tell the master that we failed # to...
.debug("Sending hello") socket.send(b"HELO IAM " + worker_id.encode("utf-8")) logger.debug("Awaiting confirmation of hello recieved") assert socket.recv() == b"HAY" logger.debug("Got hello. Going into task loop") def _handle_task(socket, data):
64
64
134
8
56
ndevenish/drmaa_futures
drmaa_futures/slave.py
Python
_handle_task
_handle_task
69
81
69
69
8f1da0b1967b67d860dd2bb57374cc565a2bd131
bigcode/the-stack
train
78e72f7884b616ed3d317ac4
train
function
def do_task(task_id, task_function): """Do a task, as specified in a pickle bundle. :arg byte data: The pickle-data to load :returns: Pickle data of the result, or an exception """ try: logger.debug("Running task with ID {}".format(task_id)) # Run whatever task we've been given result = task_func...
def do_task(task_id, task_function):
"""Do a task, as specified in a pickle bundle. :arg byte data: The pickle-data to load :returns: Pickle data of the result, or an exception """ try: logger.debug("Running task with ID {}".format(task_id)) # Run whatever task we've been given result = task_function() logger.debug("Completed ta...
# coding: utf-8 """ Running a slave instance. """ import logging import sys import time import traceback import dill as pickle import zmq logger = logging.getLogger(__name__) class ExceptionPicklingError(Exception): """Represent an error attempting to pickle the result of a task""" class TaskSystemExit(Excepti...
95
100
336
9
86
ndevenish/drmaa_futures
drmaa_futures/slave.py
Python
do_task
do_task
25
58
25
25
faf1c203a627b7274cf7e5f0f1d54972e0c9310d
bigcode/the-stack
train
ef08dc9e20d94511e2030c20
train
function
def aesthetify(string): for c in string: c = ord(c) if c in PRINTABLE_ASCII: c += 0xFF00 - 0x20 elif c == ord(" "): c = 0x3000 yield chr(c)
def aesthetify(string):
for c in string: c = ord(c) if c in PRINTABLE_ASCII: c += 0xFF00 - 0x20 elif c == ord(" "): c = 0x3000 yield chr(c)
the License. # # Ported for Lord-Userbot By liualvinas/Alvin from telethon import events from userbot import CMD_HELP from userbot.events import register PRINTABLE_ASCII = range(0x21, 0x7F) def aesthetify(string):
64
64
63
6
58
Necan03/MiamiUserbot
userbot/modules/aeshtetic.py
Python
aesthetify
aesthetify
16
23
16
16
3f97d7aa80ee11f7c92dd3dcfaa54330842f472e
bigcode/the-stack
train
5b54c819adac84c490dbfabb
train
function
@register(outgoing=True, pattern=r"^\.ae(?: |$)(.*)") async def _(event): if event.fwd_from: return text = event.pattern_match.group(1) text = "".join(aesthetify(text)) await event.edit(text=text, parse_mode=None, link_preview=False) raise events.StopPropagation
@register(outgoing=True, pattern=r"^\.ae(?: |$)(.*)") async def _(event):
if event.fwd_from: return text = event.pattern_match.group(1) text = "".join(aesthetify(text)) await event.edit(text=text, parse_mode=None, link_preview=False) raise events.StopPropagation
PRINTABLE_ASCII: c += 0xFF00 - 0x20 elif c == ord(" "): c = 0x3000 yield chr(c) @register(outgoing=True, pattern=r"^\.ae(?: |$)(.*)") async def _(event):
64
64
75
23
41
Necan03/MiamiUserbot
userbot/modules/aeshtetic.py
Python
_
_
26
33
26
27
05448f6147f3b21815b970482036a7bbf251a9b1
bigcode/the-stack
train
629821f589f03bac15020e7a
train
class
class UpdateBotWebhookJSONQuery(TLObject): # type: ignore """This object is a constructor of the base type :obj:`~pyrogram.raw.base.Update`. Details: - Layer: ``126`` - ID: ``0x9b9240a6`` Parameters: query_id: ``int`` ``64-bit`` data: :obj:`DataJSON <pyrogram.raw.base.Data...
class UpdateBotWebhookJSONQuery(TLObject): # type: ignore
"""This object is a constructor of the base type :obj:`~pyrogram.raw.base.Update`. Details: - Layer: ``126`` - ID: ``0x9b9240a6`` Parameters: query_id: ``int`` ``64-bit`` data: :obj:`DataJSON <pyrogram.raw.base.DataJSON>` timeout: ``int`` ``32-bit`` """ __s...
from typing import List, Union, Any # # # # # # # # # # # # # # # # # # # # # # # # # !!! WARNING !!! # # This is a generated file! # # All changes made in this file will be lost! # # # # # # # # # # # # # # # # # # # # # # # # # class UpdateBotWebhookJSONQuery(TLObject): ...
101
102
341
15
86
D1ne2021/jjhhhjj
venv/Lib/site-packages/pyrogram/raw/types/update_bot_webhook_json_query.py
Python
UpdateBotWebhookJSONQuery
UpdateBotWebhookJSONQuery
33
80
33
33
9fd232b86db9791069e1501c562ea597334de895
bigcode/the-stack
train
a19af970306c84e51f2142cb
train
class
class User: """ Documents the user login initial details""" def __init__(self,full_name,username,email,password): self.full_name = full_name self.username = username self.email = email self.password = password user_details=[] def save_user(self): """ Save function for the new user's ...
class User:
""" Documents the user login initial details""" def __init__(self,full_name,username,email,password): self.full_name = full_name self.username = username self.email = email self.password = password user_details=[] def save_user(self): """ Save function for the new user's details""" ...
class User:
3
73
244
3
0
mwikalikyalo/password-locker
user.py
Python
User
User
1
38
1
1
b559ac5fd1347c60ea6678bbf1ecbe04548853db
bigcode/the-stack
train
c6572f1439cd28034c10e017
train
class
class JSONWebTokenAuthenticationMixin: authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated]
class JSONWebTokenAuthenticationMixin:
authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated]
from rest_framework.permissions import IsAuthenticated from app.apis.mixins import TokenAuthentication class JSONWebTokenAuthenticationMixin:
25
64
23
7
17
dakzh/cookiecutter-django-api
{{cookiecutter.project_slug}}/app/authentication/mixins.py
Python
JSONWebTokenAuthenticationMixin
JSONWebTokenAuthenticationMixin
6
8
6
6
cc232c8afb86f40d15a73294bede33d618c06940
bigcode/the-stack
train
185fb7a12823bb213d2e245b
train
function
def run_single_experiment(cfg, diffinit, seed, replace_index): t0 = time() # how we convert the cfg into a path and such is defined in ExperimentIdentifier exp = ExperimentIdentifier(seed=seed, replace_index=replace_index, diffinit=diffinit) exp.init_from_cfg(cfg) exp.ensure_directory_exists(verbose...
def run_single_experiment(cfg, diffinit, seed, replace_index):
t0 = time() # how we convert the cfg into a path and such is defined in ExperimentIdentifier exp = ExperimentIdentifier(seed=seed, replace_index=replace_index, diffinit=diffinit) exp.init_from_cfg(cfg) exp.ensure_directory_exists(verbose=True) path_stub = exp.path_stub() print('Running exper...
(f'These are: {replaces}') candidate_seeds = [x for x in range(99999) if x not in known_seeds] new_seeds = np.random.choice(candidate_seeds, num_seeds, replace=False) pairs = list(product(new_seeds, replaces)) return pairs def run_single_experiment(cfg, diffinit, seed, replace_index):
82
82
275
15
66
microsoft/intrinsic-private-sgd
aDPSGD/run_experiment.py
Python
run_single_experiment
run_single_experiment
84
108
84
84
c66b8325e04aa11cd225b25b8bde20731f5cdb2f
bigcode/the-stack
train
6347fa8de87e65238e688a24
train
function
def find_gaps_in_grid(cfg) -> list: """ We want to have run every seed against every replace index. This will look at what we've already run and identify missing pairs. """ df = get_available_results(cfg['cfg_name'], cfg['model']['architecture'], replace_index=None, se...
def find_gaps_in_grid(cfg) -> list:
""" We want to have run every seed against every replace index. This will look at what we've already run and identify missing pairs. """ df = get_available_results(cfg['cfg_name'], cfg['model']['architecture'], replace_index=None, seed=None, diffinit=True) xtab = p...
from model_utils import build_model, prep_for_training, train_model from data_utils import load_data from results_utils import ExperimentIdentifier, get_available_results from cfg_utils import load_cfg, get_model_init_path from experiment_metadata import get_dataset_size def find_gaps_in_grid(cfg) -> list:
64
64
180
11
52
microsoft/intrinsic-private-sgd
aDPSGD/run_experiment.py
Python
find_gaps_in_grid
find_gaps_in_grid
18
31
18
18
8dd6f4e2941021146789a089149c4362792d08e3
bigcode/the-stack
train
a0ed0134072914cdea9a9bce
train
function
def add_new_seeds_to_grid(cfg, num_seeds: int, num_replaces: int) -> list: """ Specifically run more seeds. First get existing seeds and replaces. Sample new seeds, then run new seeds for each existing replace. """ df = get_available_results(cfg['cfg_name'], cfg['model']['architecture'], ...
def add_new_seeds_to_grid(cfg, num_seeds: int, num_replaces: int) -> list:
""" Specifically run more seeds. First get existing seeds and replaces. Sample new seeds, then run new seeds for each existing replace. """ df = get_available_results(cfg['cfg_name'], cfg['model']['architecture'], replace_index=None, seed=None, diffinit=True) k...
get_dataset_size(cfg['data']) candidate_replaces = [x for x in range(N) if x not in known_replaces] new_replaces = np.random.choice(candidate_replaces, num_replaces, replace=False) pairs = list(product(new_seeds, new_replaces)) return pairs def add_new_seeds_to_grid(cfg, num_seeds: int, num_replaces: ...
88
88
294
24
63
microsoft/intrinsic-private-sgd
aDPSGD/run_experiment.py
Python
add_new_seeds_to_grid
add_new_seeds_to_grid
57
81
57
57
0015840992627d37030c5aa4573d6f09913f1be3
bigcode/the-stack
train
dd4d2aad42442d89348ac959
train
function
def propose_seeds_and_replaces(cfg, num_seeds, num_replaces) -> list: """ We want to run num_seeds *new* seeds and num_replaces *new* replaces. This function will look at what we've already run, and propose new pairs. If we haven't run any experiments yet, this will just create a "new" grid. """ ...
def propose_seeds_and_replaces(cfg, num_seeds, num_replaces) -> list:
""" We want to run num_seeds *new* seeds and num_replaces *new* replaces. This function will look at what we've already run, and propose new pairs. If we haven't run any experiments yet, this will just create a "new" grid. """ df = get_available_results(cfg['cfg_name'], cfg['model']['architectu...
1]) for x in np.array(xtab_miss).T] print(f'Identified {len(missing_pairs)} missing pairs:\n{missing_pairs}') print('WARNING: This might be a large number!') return missing_pairs def propose_seeds_and_replaces(cfg, num_seeds, num_replaces) -> list:
72
72
240
20
51
microsoft/intrinsic-private-sgd
aDPSGD/run_experiment.py
Python
propose_seeds_and_replaces
propose_seeds_and_replaces
34
54
34
34
0cda0c49cd9a3d838b44244137ad81b7229aba64
bigcode/the-stack
train
68a518f128344620390e7f97
train
class
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class SlurmAdapterTest(PymatgenTest): """Test suite for Slurm adapter.""" QDICT = yaml.safe_load("""\ priority: 5 queue: qtype: slurm qname: Oban qparams: account: user_account mail_user: user@mail.com limits: timelimit...
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class SlurmAdapterTest(PymatgenTest):
"""Test suite for Slurm adapter.""" QDICT = yaml.safe_load("""\ priority: 5 queue: qtype: slurm qname: Oban qparams: account: user_account mail_user: user@mail.com limits: timelimit: 10:00 min_cores: 3 max_cores: 16 job: mpi_runner: mpirun mpi_runner_options: --bind-to None # pre_r...
.omp_threads) == (1, 1) assert qad.priority == 1 and qad.num_launches == 0 and qad.last_launch is None qad.set_omp_threads(1) assert qad.has_omp s = qad.get_script_str("job_name", "/launch_dir", "executable", "qout_path", "qerr_path", stdin="stdin", stdou...
184
184
614
27
157
frssp/pymatgen
pymatgen/io/abinit/tests/test_qadapters.py
Python
SlurmAdapterTest
SlurmAdapterTest
217
297
217
218
340c7e1c4ade1816649073cd620005f0de38a593
bigcode/the-stack
train
fe157e4a826fd45f1c7f5436
train
class
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class QadapterTest(PymatgenTest): QDICT = yaml.safe_load("""\ priority: 1 queue: qtype: slurm qname: Oban limits: timelimit: 2:00 min_cores: 1 max_cores: 24 #condition: {"$eq": {omp_threads: 2}} job: modules: ...
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class QadapterTest(PymatgenTest):
QDICT = yaml.safe_load("""\ priority: 1 queue: qtype: slurm qname: Oban limits: timelimit: 2:00 min_cores: 1 max_cores: 24 #condition: {"$eq": {omp_threads: 2}} job: modules: - intel/compilerpro/13.0.1.117 - fftw3/intel/3.3 shell_env: PATH: /home/user/tmp_inte...
60, 60*60, 60, 1 aequal = self.assertEqual slurm_parse_timestr = qu.slurm_parse_timestr # "days-hours", aequal(slurm_parse_timestr("2-1"), 2*days + hours) # "days-hours:minutes", aequal(slurm_parse_timestr("2-1:1"), 2*days + hours + minutes) # "days-hours:minute...
256
256
1,354
26
230
frssp/pymatgen
pymatgen/io/abinit/tests/test_qadapters.py
Python
QadapterTest
QadapterTest
38
165
38
39
dfc208cab970157385582744adf1c09957dbe081
bigcode/the-stack
train
b50784a6b564bcd5f177558a
train
class
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class PbsProadapterTest(PymatgenTest): """Test suite for PbsPro adapter.""" QDICT = yaml.safe_load("""\ priority: 1 queue: qtype: pbspro qname: fat qparams: group_list: naps limits: timelimit: 0:0:10 min_cores: ...
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class PbsProadapterTest(PymatgenTest):
"""Test suite for PbsPro adapter.""" QDICT = yaml.safe_load("""\ priority: 1 queue: qtype: pbspro qname: fat qparams: group_list: naps limits: timelimit: 0:0:10 min_cores: 3 max_cores: 200 job: mpi_runner: mpirun hardware: num_nodes: 100 sockets_per_node: 2 cores_...
) self.assertMultiLineEqual(s, """\ #!/bin/bash #SBATCH --partition=Oban #SBATCH --job-name=job_name #SBATCH --ntasks=4 #SBATCH --mem-per-cpu=1024 #SBATCH --time=0-0:10:0 #SBATCH --account=user_account #SBATCH --mail-user=user@mail.com #SBATCH --output=qout_path #SBATCH --error=qerr_path cd /launch_dir # Setup...
256
256
1,637
28
227
frssp/pymatgen
pymatgen/io/abinit/tests/test_qadapters.py
Python
PbsProadapterTest
PbsProadapterTest
303
458
303
304
d002c195973498ba0631edabf036b96b1e970263
bigcode/the-stack
train
7bf76eafd95c7703499ef80b
train
class
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class ShellAdapterTest(PymatgenTest): """Test suite for Shell adapter.""" QDICT = yaml.safe_load("""\ priority: 1 queue: qname: localhost qtype: shell job: mpi_runner: /home/local/bin/mpirun pre_run: - "source ~/env...
@unittest.skipIf(sys.platform.startswith("win"), "Skipping for Windows") class ShellAdapterTest(PymatgenTest):
"""Test suite for Shell adapter.""" QDICT = yaml.safe_load("""\ priority: 1 queue: qname: localhost qtype: shell job: mpi_runner: /home/local/bin/mpirun pre_run: - "source ~/env1.sh" limits: timelimit: 10:00 min_cores: 1 max_cores: 1 hardware: num_nodes: 1 sockets_per...
() # Test if one can register a customized class. class MyAdapter(SlurmAdapter): QTYPE = "myslurm" SlurmAdapter.register(MyAdapter) assert issubclass(MyAdapter, QueueAdapter) self.QDICT["queue"]["qtype"] = "myslurm" qad = make_qadapter(**self.QDICT) ...
111
111
372
26
85
frssp/pymatgen
pymatgen/io/abinit/tests/test_qadapters.py
Python
ShellAdapterTest
ShellAdapterTest
168
214
168
169
3853e3fbd44a8298600b55925b95c45bc6c40e2e
bigcode/the-stack
train
7f8f3e70faadadfa3ad44c74
train
class
class ParseTimestr(PymatgenTest): def test_slurm_parse_timestr(self): days, hours, minutes, secs = 24*60*60, 60*60, 60, 1 aequal = self.assertEqual slurm_parse_timestr = qu.slurm_parse_timestr # "days-hours", aequal(slurm_parse_timestr("2-1"), 2*days + hours) # "day...
class ParseTimestr(PymatgenTest):
def test_slurm_parse_timestr(self): days, hours, minutes, secs = 24*60*60, 60*60, 60, 1 aequal = self.assertEqual slurm_parse_timestr = qu.slurm_parse_timestr # "days-hours", aequal(slurm_parse_timestr("2-1"), 2*days + hours) # "days-hours:minutes", aequal(s...
from pymatgen.util.testing import PymatgenTest from pymatgen.io.abinit.tasks import ParalConf from pymatgen.io.abinit.qadapters import * from pymatgen.io.abinit.qadapters import QueueAdapter, SlurmAdapter from pymatgen.io.abinit import qutils as qu class ParseTimestr(PymatgenTest):
79
79
264
10
68
frssp/pymatgen
pymatgen/io/abinit/tests/test_qadapters.py
Python
ParseTimestr
ParseTimestr
17
35
17
17
38e0f1704c7be211a0ffe84452c2bcb1a9041ae1
bigcode/the-stack
train
1785b80bfe77b8ee787eb14d
train
class
class Delta4Report(ParserBase): """Custom Delta4 report parser""" def __init__(self): """Initialize SNCPatientCustom class""" ParserBase.__init__(self) self.report_type = "Delta4" self.columns = [ "Patient Name", "Patient ID", "Plan Date", ...
class Delta4Report(ParserBase):
"""Custom Delta4 report parser""" def __init__(self): """Initialize SNCPatientCustom class""" ParserBase.__init__(self) self.report_type = "Delta4" self.columns = [ "Patient Name", "Patient ID", "Plan Date", "Plan Name", ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # delta4.py """Delta4 QA report parser""" # # Copyright (c) 2020 Dan Cutright # This file is part of IQDM-PDF, released under a MIT license. # See the file LICENSE included with this distribution from IQDMPDF.parsers.generic import ParserBase from IQDMPDF.pdf_reader i...
98
256
2,581
7
90
IQDM/IQDM-PDF
IQDMPDF/parsers/delta4.py
Python
Delta4Report
Delta4Report
15
409
15
15
24230babd60d0aa2aafdd00c96b1c958fb5511fc
bigcode/the-stack
train
c7cb05087669ea82c10e9397
train
function
def p_command(p): """ command : INC | DEC | SHL | SHR | OUT | IN | loop """ if isinstance(p[1], str): p[0] = Command(p[1]) else: p[0] = p[1]
def p_command(p):
""" command : INC | DEC | SHL | SHR | OUT | IN | loop """ if isinstance(p[1], str): p[0] = Command(p[1]) else: p[0] = p[1]
p[0] = Commands() p[0].commands = [p[1]] return if not p[1]: p[1] = Commands() p[1].commands.append(p[2]) p[0] = p[1] def p_command(p):
64
64
72
5
59
OorjaRungta/wisdom
writerscript/interpreter.py
Python
p_command
p_command
68
81
68
68
651dee08946f26193755cb80decff77fd1796520
bigcode/the-stack
train
ff41fed9b5e5706cf40cc76c
train
function
def t_newline(t): r"\n+" t.lexer.lineno += len(t.value)
def t_newline(t):
r"\n+" t.lexer.lineno += len(t.value)
= r'5' t_DEC = r'6' t_SHL = r'10' t_SHR = r'9' t_OUT = r'12' t_IN = r'11' t_OPEN_LOOP = r'7' t_CLOSE_LOOP = r'8' def t_newline(t):
64
64
23
6
58
OorjaRungta/wisdom
writerscript/interpreter.py
Python
t_newline
t_newline
39
41
39
39
62800b3988ccaaf2bae0b9f7a3f3a5bd2d13c154
bigcode/the-stack
train
ec43107eb27d86ebe5eaddcd
train
function
def p_commands(p): """ commands : command | commands command """ if len(p) == 2: p[0] = Commands() p[0].commands = [p[1]] return if not p[1]: p[1] = Commands() p[1].commands.append(p[2]) p[0] = p[1]
def p_commands(p):
""" commands : command | commands command """ if len(p) == 2: p[0] = Commands() p[0].commands = [p[1]] return if not p[1]: p[1] = Commands() p[1].commands.append(p[2]) p[0] = p[1]
t_OPEN_LOOP = r'7' t_CLOSE_LOOP = r'8' def t_newline(t): r"\n+" t.lexer.lineno += len(t.value) t_ignore = " \t" def t_error(t): t.lexer.skip(1) def p_commands(p):
64
64
87
5
59
OorjaRungta/wisdom
writerscript/interpreter.py
Python
p_commands
p_commands
51
65
51
51
afdb48f4a8946bbdb4d7c6eaadc02e382386676a
bigcode/the-stack
train
9187707ca635b1282d37c385
train
class
class Commands: def __init__(self): self.commands = [] def run(self, program): tempvar=[] for command in self.commands: command.run(program) def __str__(self): return "".join([str(command) for command in self.commands])
class Commands:
def __init__(self): self.commands = [] def run(self, program): tempvar=[] for command in self.commands: command.run(program) def __str__(self): return "".join([str(command) for command in self.commands])
commands = self.parse(self.source) commands.run(self) def parse(self, source): lexer = lex.lex() parser = yacc.yacc(debug=False, write_tables=False) return parser.parse(source) def __str__(self): return str(self.parse(self.source)) class Commands:
64
64
59
3
61
OorjaRungta/wisdom
writerscript/interpreter.py
Python
Commands
Commands
114
124
114
114
177509ea1f79f8343d6b7377b25609d39eac00ee
bigcode/the-stack
train
19476ba08a66bddf69001afe
train
class
class Loop: def __init__(self, commands): self.commands = commands def run(self, program): while program.data[program.location] != 0: self.commands.run(program) def __str__(self): return t_OPEN_LOOP + str(self.commands) + t_CLOSE_LOOP
class Loop:
def __init__(self, commands): self.commands = commands def run(self, program): while program.data[program.location] != 0: self.commands.run(program) def __str__(self): return t_OPEN_LOOP + str(self.commands) + t_CLOSE_LOOP
exit(-1) else: program.data[program.location]=RIN except Exception: print("\nError (x_x) : I/O Exception, Exiting.") program.data = None exit(-1) def __str__(self): return self.command class Loop:
64
64
65
3
60
OorjaRungta/wisdom
writerscript/interpreter.py
Python
Loop
Loop
182
191
182
182
e1efcdab5073ed0499ee32ae94c3a6fa613c6440
bigcode/the-stack
train
0dae1dc0995a6062105d6a61
train
class
class Command: def __init__(self, command): self.command = command self.CHARGOT='' def run(self, program): if isinstance(self.command, Loop): self.command.run(program) if self.command == t_INC: if program.data[program.location] >= 255: pr...
class Command:
def __init__(self, command): self.command = command self.CHARGOT='' def run(self, program): if isinstance(self.command, Loop): self.command.run(program) if self.command == t_INC: if program.data[program.location] >= 255: program.data[prog...
, source): lexer = lex.lex() parser = yacc.yacc(debug=False, write_tables=False) return parser.parse(source) def __str__(self): return str(self.parse(self.source)) class Commands: def __init__(self): self.commands = [] def run(self, program): tempvar=[] ...
105
105
351
3
102
OorjaRungta/wisdom
writerscript/interpreter.py
Python
Command
Command
127
179
127
127
d2ab40c9efaecfce8a957e3536061f7bb59eb69a
bigcode/the-stack
train
4b45ca263c0fb8cbb3d92d5d
train
function
def p_loop(p): """ loop : OPEN_LOOP commands CLOSE_LOOP """ p[0] = Loop(p[2])
def p_loop(p):
""" loop : OPEN_LOOP commands CLOSE_LOOP """ p[0] = Loop(p[2])
| DEC | SHL | SHR | OUT | IN | loop """ if isinstance(p[1], str): p[0] = Command(p[1]) else: p[0] = p[1] def p_loop(p):
64
64
29
5
59
OorjaRungta/wisdom
writerscript/interpreter.py
Python
p_loop
p_loop
84
88
84
84
534a98483a715d89ec57138e9c39fc49297553fe
bigcode/the-stack
train
9ba6a25338ad1de9e2960dcd
train
function
def p_error(p): print("Syntax error in input!")
def p_error(p):
print("Syntax error in input!")
(p[1], str): p[0] = Command(p[1]) else: p[0] = p[1] def p_loop(p): """ loop : OPEN_LOOP commands CLOSE_LOOP """ p[0] = Loop(p[2]) def p_error(p):
64
64
13
5
59
OorjaRungta/wisdom
writerscript/interpreter.py
Python
p_error
p_error
91
92
91
91
26bfac592ac4574e3220d205d1af4dd9cd5a622d
bigcode/the-stack
train
4fac3fa6e1e44e1397bd17b9
train
function
def t_error(t): t.lexer.skip(1)
def t_error(t):
t.lexer.skip(1)
_OUT = r'12' t_IN = r'11' t_OPEN_LOOP = r'7' t_CLOSE_LOOP = r'8' def t_newline(t): r"\n+" t.lexer.lineno += len(t.value) t_ignore = " \t" def t_error(t):
64
64
13
5
59
OorjaRungta/wisdom
writerscript/interpreter.py
Python
t_error
t_error
47
48
47
47
0204bf6f2d642efe93b2c12dc6868f0579641f1c
bigcode/the-stack
train
d8d2bcb549b63e3e83082136
train
class
class WriterScriptProgram: def __init__(self, source): self.source = source def run(self): self.data = [0] * 1000 self.location = 0 commands = self.parse(self.source) commands.run(self) def parse(self, source): lexer = lex.lex() parser = yacc.yacc(de...
class WriterScriptProgram:
def __init__(self, source): self.source = source def run(self): self.data = [0] * 1000 self.location = 0 commands = self.parse(self.source) commands.run(self) def parse(self, source): lexer = lex.lex() parser = yacc.yacc(debug=False, write_tables=Fal...
[1]) else: p[0] = p[1] def p_loop(p): """ loop : OPEN_LOOP commands CLOSE_LOOP """ p[0] = Loop(p[2]) def p_error(p): print("Syntax error in input!") class WriterScriptProgram:
63
64
104
5
58
OorjaRungta/wisdom
writerscript/interpreter.py
Python
WriterScriptProgram
WriterScriptProgram
95
111
95
95
ef81a833606dd309e53027f276785e1585156fd6
bigcode/the-stack
train
bbfbd4c823bad9f18b10be9b
train
class
class Document(BaseModel, UpdateMethods): """ Document Mapping class. Fields: - `id` - MongoDB document ObjectID "_id" field. Mapped to the PydanticObjectId class Inherited from: - Pydantic BaseModel - [UpdateMethods](https://roman-right.github.io/beanie/api/interfaces/#aggregatemeth...
class Document(BaseModel, UpdateMethods):
""" Document Mapping class. Fields: - `id` - MongoDB document ObjectID "_id" field. Mapped to the PydanticObjectId class Inherited from: - Pydantic BaseModel - [UpdateMethods](https://roman-right.github.io/beanie/api/interfaces/#aggregatemethods) """ id: Optional[PydanticObj...
PydanticObjectId, ExpressionField, Link, LinkInfo, LinkTypes, WriteRules, DeleteRules, ) from beanie.odm.interfaces.update import ( UpdateMethods, ) from beanie.odm.models import ( InspectionResult, InspectionStatuses, InspectionError, ) from beanie.odm.operators.find.compari...
256
256
8,730
8
248
sanders41/beanie
beanie/odm/documents.py
Python
Document
Document
86
1,257
86
86
985181a2dd36bdafd64fde1d3c919af4d9685424
bigcode/the-stack
train
638c1a268eff4f3a85366681
train
class
class Scanner(QWidget): motorChanging=pyqtSignal(float) #Signal emitted on motor changing position motorChanged=pyqtSignal(int) #Signal emitted on motor start or stopped moving scalerCounting=pyqtSignal(int) #Signal to detect Scaler Counting slitMoving=pyqtSignal(float) slitMoved=pyqtSignal(bool) ...
class Scanner(QWidget):
motorChanging=pyqtSignal(float) #Signal emitted on motor changing position motorChanged=pyqtSignal(int) #Signal emitted on motor start or stopped moving scalerCounting=pyqtSignal(int) #Signal to detect Scaler Counting slitMoving=pyqtSignal(float) slitMoved=pyqtSignal(bool) def __init__(self...
import pyqtgraph as pg from epics import caget, caput, camonitor, camonitor_clear from PyQt5.QtWidgets import QWidget, QVBoxLayout, QApplication, QLabel, QTableWidget, QListWidget, QCheckBox, QComboBox, QLineEdit, QPushButton, QMessageBox, QFileDialog,QAbstractItemView from PyQt5.QtCore import QObject, pyqtSignal, Qt f...
152
256
12,938
4
147
prjemian/XAnoS
scanner.py
Python
Scanner
Scanner
16
1,237
16
16
9f97bf628e67ca86cc5eeb3b8b562c6fab015679
bigcode/the-stack
train
115d20c3755e87dc88a440bc
train
function
def upgrade(): ''' Upgrade the database to this revision ''' schema = context.get_context().version_table_schema if context.get_context().version_table_schema else '' if context.get_context().dialect.name == 'oracle': add_column('rules', sa.Column('ignore_account_limit', sa.Boolean(name='R...
def upgrade():
''' Upgrade the database to this revision ''' schema = context.get_context().version_table_schema if context.get_context().version_table_schema else '' if context.get_context().dialect.name == 'oracle': add_column('rules', sa.Column('ignore_account_limit', sa.Boolean(name='RULES_IGNORE_ACC...
ig <mario.lassnig@cern.ch>, 2019 ''' asynchronous rules and rule approval ''' import sqlalchemy as sa from alembic import context, op from alembic.op import (add_column, create_check_constraint, drop_constraint, drop_column) # Alembic revision identifiers revision = '1d96f484df21' down_rev...
90
90
300
3
87
elichad/rucio
lib/rucio/db/sqla/migrate_repo/versions/1d96f484df21_asynchronous_rules_and_rule_approval.py
Python
upgrade
upgrade
34
53
34
34
58db61919ad1f96abfbae24c62b1e89eb08f96ea
bigcode/the-stack
train
4cbd5ebe14dfcf8e73c4033d
train
function
def downgrade(): ''' Downgrade the database to the previous revision ''' schema = context.get_context().version_table_schema + '.' if context.get_context().version_table_schema else '' if context.get_context().dialect.name == 'oracle': drop_column('rules', 'ignore_account_limit') d...
def downgrade():
''' Downgrade the database to the previous revision ''' schema = context.get_context().version_table_schema + '.' if context.get_context().version_table_schema else '' if context.get_context().dialect.name == 'oracle': drop_column('rules', 'ignore_account_limit') drop_constraint('R...
().dialect.name == 'mysql': add_column('rules', sa.Column('ignore_account_limit', sa.Boolean(name='RULES_IGNORE_ACCOUNT_LIMIT_CHK'), default=False), schema=schema) create_check_constraint('RULES_STATE_CHK', 'rules', "state IN ('S', 'R', 'U', 'O', 'W', 'I')") def downgrade():
78
79
265
3
76
elichad/rucio
lib/rucio/db/sqla/migrate_repo/versions/1d96f484df21_asynchronous_rules_and_rule_approval.py
Python
downgrade
downgrade
56
75
56
56
1e7e3c765546986dc7c1cc4f9a7c58df8a7f5c68
bigcode/the-stack
train
52237f910e229c93942d1616
train
class
class S3FileMetaModel(IdentifierMixin): s3_key: str file_name: str file_size: int deleted: bool class Config: orm_mode = True
class S3FileMetaModel(IdentifierMixin):
s3_key: str file_name: str file_size: int deleted: bool class Config: orm_mode = True
UpdatedByUserMixin, IdentifierMixin class S3FileMetaCreateModel(CreatedAndUpdatedByUserMixin): path: str # folders within s3 for file context, will prefix the key file_name: str file_size: int class S3FileMetaModel(IdentifierMixin):
64
64
44
10
53
wattlecloud/foundation-server
core/src/wattle/core/models/py/s3.py
Python
S3FileMetaModel
S3FileMetaModel
10
17
10
10
b88c893597dbbf3982ec008ea36932cbb124a384
bigcode/the-stack
train
d6ac2856ef60525f4b625cda
train
class
class S3FileMetaCreateModel(CreatedAndUpdatedByUserMixin): path: str # folders within s3 for file context, will prefix the key file_name: str file_size: int
class S3FileMetaCreateModel(CreatedAndUpdatedByUserMixin):
path: str # folders within s3 for file context, will prefix the key file_name: str file_size: int
from wattle.core.models.py.common import CreatedAndUpdatedByUserMixin, IdentifierMixin class S3FileMetaCreateModel(CreatedAndUpdatedByUserMixin):
33
64
46
15
17
wattlecloud/foundation-server
core/src/wattle/core/models/py/s3.py
Python
S3FileMetaCreateModel
S3FileMetaCreateModel
4
7
4
4
571078331df31514f95cae08ce914e92ce1da3dd
bigcode/the-stack
train
f7ce08696a44b7dad82136a8
train
class
class Property(ApartachoModel): has_furnished = models.BooleanField( verbose_name='furnished', default=False, help_text='Set to true when the property have furnished.', ) price = models.DecimalField( verbose_name='price', max_digits=12, decimal_places=2, ...
class Property(ApartachoModel):
has_furnished = models.BooleanField( verbose_name='furnished', default=False, help_text='Set to true when the property have furnished.', ) price = models.DecimalField( verbose_name='price', max_digits=12, decimal_places=2, help_text='Set to price tota...
"""Property model.""" from django.db import models # Utilities from apartacho.utils.models import ApartachoModel from apartacho.users.models import User from apartacho.addresses.models import Address OFFERS_TYPES = [ (1, 'Alquiler-Arriendo'), (2, 'Venta'), ] SERVICE_TYPES = [ (1, 'Apartamento'), (2, ...
89
230
769
7
82
cenavia/skylynx
backend_final/apartacho/properties/models.py
Python
Property
Property
20
153
20
21
79181969715ed9065527a3abed03ae8f1d20307b
bigcode/the-stack
train
e1e5aa97f29658ea159a907c
train
function
def Rss(S, k): k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k1*k4/k2/k3 + 0*S
def Rss(S, k):
k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k1*k4/k2/k3 + 0*S
from plotter import * def Rss(S, k):
12
64
82
7
5
TemnosHD/biosensing
bokeh/diagram1d/main.py
Python
Rss
Rss
3
8
3
3
aaa225507209915ab57b033891f1efa05c66814b
bigcode/the-stack
train
fcc8a09e0b3f34308caada84
train
function
def Xss(S, k): k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k3*S/k4
def Xss(S, k):
k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k3*S/k4
= k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k1*k4/k2/k3 + 0*S def Xss(S, k):
64
64
75
7
56
TemnosHD/biosensing
bokeh/diagram1d/main.py
Python
Xss
Xss
10
15
10
10
91c10b9d404d1c8aa8660706455f84304b8ca827
bigcode/the-stack
train
94abeba3d7a6e7feef1f6cc0
train
function
def depletion(R, S, k): k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k2*Xss(S, k)*R
def depletion(R, S, k):
k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k2*Xss(S, k)*R
k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k3*S/k4 def depletion(R, S, k):
64
64
81
8
55
TemnosHD/biosensing
bokeh/diagram1d/main.py
Python
depletion
depletion
17
22
17
17
ed6aef03865b7e77ae8e6b093b0e05e3eafd06a9
bigcode/the-stack
train
2eaf6dc801209355198d55be
train
function
def aggregation(R, S, k): k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k1*S + 0*R
def aggregation(R, S, k):
k1 = k['value'][k['name']=='k1'] k2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k1*S + 0*R
2 = k['value'][k['name']=='k2'] k3 = k['value'][k['name']=='k3'] k4 = k['value'][k['name']=='k4'] return k2*Xss(S, k)*R def aggregation(R, S, k):
64
64
79
8
55
TemnosHD/biosensing
bokeh/diagram1d/main.py
Python
aggregation
aggregation
24
29
24
24
220a9fc46ae55c6c475a3a10bf9429b358322345
bigcode/the-stack
train
e3cecced4feb71962af651a9
train
function
def main_slaver(): global SPARE_SLAVER_TTL args = argparse_slaver() if args.verbose and args.quiet: print("-v and -q should not appear together") exit(1) communicate_addr = split_host(args.master) target_addr = split_host(args.target) set_secretkey(args.secretkey) SPARE_...
def main_slaver():
global SPARE_SLAVER_TTL args = argparse_slaver() if args.verbose and args.quiet: print("-v and -q should not appear together") exit(1) communicate_addr = split_host(args.master) target_addr = split_host(args.target) set_secretkey(args.secretkey) SPARE_SLAVER_TTL = args.S...
aver TCP connections count, default is 5. " "which is enough for more than 800 concurrency. " "while working connections are always unlimited") parser.add_argument('--ssl', action='store_true', help='[experimental] try using ssl for data encryption. ' ...
81
81
272
5
76
cls1997/shootback
slaver.py
Python
main_slaver
main_slaver
356
392
356
356
0b3c15e743e7648944c45e68dac94d3a4015d373
bigcode/the-stack
train
ca8b56fb29410acff8af31b0
train
class
class Slaver(object): """ slaver socket阶段 连接master->等待->心跳(重复)--->握手-->正式传输数据->退出 """ def __init__(self, communicate_addr, target_addr, max_spare_count=5, ssl=False): self.communicate_addr = communicate_addr self.target_addr = target_addr self.max_spare_count = max_spare...
class Slaver(object):
""" slaver socket阶段 连接master->等待->心跳(重复)--->握手-->正式传输数据->退出 """ def __init__(self, communicate_addr, target_addr, max_spare_count=5, ssl=False): self.communicate_addr = communicate_addr self.target_addr = target_addr self.max_spare_count = max_spare_count self.s...
#!/usr/bin/env python3 # coding=utf-8 from __future__ import print_function, unicode_literals, division, absolute_import from common_func import * __author__ = "Aploium <i@z.codes>" __website__ = "https://github.com/aploium/shootback" class Slaver(object):
69
256
2,243
5
64
cls1997/shootback
slaver.py
Python
Slaver
Slaver
11
291
11
11
2bcb53aaac8df508e95cb79ab93842229b693c4a
bigcode/the-stack
train
4430ea5ffcb6f89f1ae14984
train
function
def argparse_slaver(): import argparse parser = argparse.ArgumentParser( description="""shootback {ver}-slaver A fast and reliable reverse TCP tunnel (this is slaver) Help access local-network service from Internet. https://github.com/aploium/shootback""".format(ver=version_info()), epilog=""" E...
def argparse_slaver():
import argparse parser = argparse.ArgumentParser( description="""shootback {ver}-slaver A fast and reliable reverse TCP tunnel (this is slaver) Help access local-network service from Internet. https://github.com/aploium/shootback""".format(ver=version_info()), epilog=""" Example1: tunnel local s...
,) ) t.daemon = True t.start() log.info("connected to master[{}] at {} total: {}".format( fmt_addr(conn_slaver.getpeername()), fmt_addr(conn_slaver.getsockname()), len(self.s...
222
222
743
5
217
cls1997/shootback
slaver.py
Python
argparse_slaver
argparse_slaver
305
353
305
305
e5453cf1a2c58bfd147069ed83007dc7009b6021
bigcode/the-stack
train
1b887b8edbe226da2ac70475
train
function
def run_slaver(communicate_addr, target_addr, max_spare_count=5, ssl=False): log.info("running as slaver, master addr: {} target: {}".format( fmt_addr(communicate_addr), fmt_addr(target_addr) )) Slaver(communicate_addr, target_addr, max_spare_count=max_spare_count, ssl=ssl, ...
def run_slaver(communicate_addr, target_addr, max_spare_count=5, ssl=False):
log.info("running as slaver, master addr: {} target: {}".format( fmt_addr(communicate_addr), fmt_addr(target_addr) )) Slaver(communicate_addr, target_addr, max_spare_count=max_spare_count, ssl=ssl, ).serve_forever()
time.sleep(err_delay) if err_delay < max_err_delay: err_delay += 1 continue # set err_delay if everything is ok err_delay = 0 def run_slaver(communicate_addr, target_addr, max_spare_count=5, ssl=False):
64
64
87
22
41
cls1997/shootback
slaver.py
Python
run_slaver
run_slaver
294
302
294
294
a1a1dcbc57e38ac3e973d6c94934f111915a7efa
bigcode/the-stack
train
b4964b540b04257f1530dcff
train
function
def download_url(url, filename, headers): """Download a file from `url` to `filename`.""" ensure_dirs(filename) response = requests.get(url, headers=headers, stream=True) if response.status_code == 200: with open(filename, 'wb') as f: for chunk in response.iter_content(16 * 1024): ...
def download_url(url, filename, headers):
"""Download a file from `url` to `filename`.""" ensure_dirs(filename) response = requests.get(url, headers=headers, stream=True) if response.status_code == 200: with open(filename, 'wb') as f: for chunk in response.iter_content(16 * 1024): f.write(chunk) else: ...
if is_zip: unpack_zipfile(filename) os.remove(filename) def ensure_dirs(filename): """Make sure the directories exist for `filename`.""" dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname) def download_url(url, filen...
64
64
98
9
55
kelupa/TestTravisRead
ci/appveyor-download.py
Python
download_url
download_url
73
82
73
73
3662ff182f6e06256f9fa976d33c8de9fc54ba32
bigcode/the-stack
train
846bf1b45fbfda71e8694fe3
train
function
def ensure_dirs(filename): """Make sure the directories exist for `filename`.""" dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname)
def ensure_dirs(filename):
"""Make sure the directories exist for `filename`.""" dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname)
artifact['size'])) url = "https://ci.appveyor.com/api/buildjobs/{}/artifacts/{}".format(job['jobId'], filename) download_url(url, filename, make_auth_headers()) if is_zip: unpack_zipfile(filename) os.remove(filename) def ensure_dirs(filename):
64
64
40
5
59
kelupa/TestTravisRead
ci/appveyor-download.py
Python
ensure_dirs
ensure_dirs
66
70
66
66
88ad87b598973f2de55fa909017503e6a4e21b86
bigcode/the-stack
train
527d796c3e122ce9f5008409
train
function
def make_auth_headers(): """Make the authentication headers needed to use the Appveyor API.""" path = os.path.expanduser("~/.appveyor.token") if not os.path.exists(path): raise RuntimeError( "Please create a file named `.appveyor.token` in your home directory. " "You can get ...
def make_auth_headers():
"""Make the authentication headers needed to use the Appveyor API.""" path = os.path.expanduser("~/.appveyor.token") if not os.path.exists(path): raise RuntimeError( "Please create a file named `.appveyor.token` in your home directory. " "You can get the token from https://ci...
under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt """ from __future__ import unicode_literals import argparse import os import zipfile import requests def make_auth_headers():
64
64
119
5
58
kelupa/TestTravisRead
ci/appveyor-download.py
Python
make_auth_headers
make_auth_headers
18
32
18
18
76503428ece80e5ef2451be58d89300e00670a27
bigcode/the-stack
train
c29cd4ddbf5101a3ccc50cd1
train
function
def unpack_zipfile(filename): """Unpack a zipfile, using the names in the zip.""" with open(filename, 'rb') as fzip: z = zipfile.ZipFile(fzip) for name in z.namelist(): print(u" extracting {}".format(name)) ensure_dirs(name) z.extract(name)
def unpack_zipfile(filename):
"""Unpack a zipfile, using the names in the zip.""" with open(filename, 'rb') as fzip: z = zipfile.ZipFile(fzip) for name in z.namelist(): print(u" extracting {}".format(name)) ensure_dirs(name) z.extract(name)
) if response.status_code == 200: with open(filename, 'wb') as f: for chunk in response.iter_content(16 * 1024): f.write(chunk) else: print(u" Error downloading {}: {}".format(url, response)) def unpack_zipfile(filename):
64
64
72
6
58
kelupa/TestTravisRead
ci/appveyor-download.py
Python
unpack_zipfile
unpack_zipfile
85
92
85
85
d6f572419359264ed8cb3ab48ffd22a0e7770dde
bigcode/the-stack
train
ed6136f8ac0b7a80df8ee0d9
train
function
def download_latest_artifacts(account_project, build_id): """Download all the artifacts from the latest build.""" if build_id is None: url = "https://ci.appveyor.com/api/projects/{}".format(account_project) else: url = "https://ci.appveyor.com/api/projects/{}/build/{}".format(account_project...
def download_latest_artifacts(account_project, build_id):
"""Download all the artifacts from the latest build.""" if build_id is None: url = "https://ci.appveyor.com/api/projects/{}".format(account_project) else: url = "https://ci.appveyor.com/api/projects/{}/build/{}".format(account_project, build_id) build = requests.get(url, headers=make_aut...
os.path.exists(path): raise RuntimeError( "Please create a file named `.appveyor.token` in your home directory. " "You can get the token from https://ci.appveyor.com/api-token" ) with open(path) as f: token = f.read().strip() headers = { 'Authorization':...
94
94
314
11
82
kelupa/TestTravisRead
ci/appveyor-download.py
Python
download_latest_artifacts
download_latest_artifacts
35
63
35
35
b4b402cce52a3ef660d95b8560b36150f2f837c1
bigcode/the-stack
train
940ef1fd4ef1c241172cae07
train
function
def application(environ, start_response): ctype = 'text/plain' if environ['PATH_INFO'] == '/health': response_body = "1" elif environ['PATH_INFO'] == '/env': response_body = ['%s: %s' % (key, value) for key, value in sorted(environ.items())] response_body...
def application(environ, start_response):
ctype = 'text/plain' if environ['PATH_INFO'] == '/health': response_body = "1" elif environ['PATH_INFO'] == '/env': response_body = ['%s: %s' % (key, value) for key, value in sorted(environ.items())] response_body = '\n'.join(response_body) else: ...
#!/usr/bin/python import os virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/' virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: execfile(virtualenv, dict(__file__=virtualenv)) except IOError: pass # # IMPORTANT: Put any additional includes below this line. If placed above this...
111
256
23,620
8
103
Benxxen/pythonwetter
wsgi.py
Python
application
application
15
298
15
16
2b17abf4b6205e57b0925f98a73438a488fac469
bigcode/the-stack
train
1fb7c3abd488a3e1e8f04b1b
train
class
class RHSaveSurveyAnswers(RHSubmitSurveyBase): def _check_access(self): RHSubmitSurveyBase._check_access(self) if not self.survey.partial_completion or not session.user: raise Forbidden def _process(self): pending_answers = {k: v for k, v in request.form.lists() if k.startsw...
class RHSaveSurveyAnswers(RHSubmitSurveyBase):
def _check_access(self): RHSubmitSurveyBase._check_access(self) if not self.survey.partial_completion or not session.user: raise Forbidden def _process(self): pending_answers = {k: v for k, v in request.form.lists() if k.startswith('question_')} if not self.submissio...
.is_anonymous = survey.anonymous for question in survey.questions: answer = SurveyAnswer(question=question, data=getattr(form, f'question_{question.id}').data) self.submission.answers.append(answer) return self.submission class RHSaveSurveyAnswers(RHSubmitSurveyBase):
64
64
124
11
52
salevajo/indico
indico/modules/events/surveys/controllers/display.py
Python
RHSaveSurveyAnswers
RHSaveSurveyAnswers
139
150
139
139
94068dba1db91767c073141fa8aecf0859261814
bigcode/the-stack
train
79fac867dcc0b6086da0d9bd
train
class
class RHSurveyList(RHSurveyBaseDisplay): def _process(self): surveys = (query_active_surveys(self.event) .options(joinedload('questions'), joinedload('submissions')) .all()) if _can_redirect_to_single_survey(surveys): retu...
class RHSurveyList(RHSurveyBaseDisplay):
def _process(self): surveys = (query_active_surveys(self.event) .options(joinedload('questions'), joinedload('submissions')) .all()) if _can_redirect_to_single_survey(surveys): return redirect(url_for('.display_survey_form...
_survey_submitted(surveys[0]) class RHSurveyBaseDisplay(RHDisplayEventBase): @property def view_class(self): return WPDisplaySurveyConference if self.event.type_ == EventType.conference else WPDisplaySurveySimpleEvent class RHSurveyList(RHSurveyBaseDisplay):
64
64
126
10
53
salevajo/indico
indico/modules/events/surveys/controllers/display.py
Python
RHSurveyList
RHSurveyList
43
55
43
43
0346feca93501587045ad3d39f2a3eec0e79771e
bigcode/the-stack
train
64b8b94441102ec5e833be48
train
function
def _can_redirect_to_single_survey(surveys): # Make sure redirection to first survey does not happen before login if user is required. if not session.user and len(surveys) == 1 and surveys[0].is_active and surveys[0].require_user: return False return len(surveys) == 1 and surveys[0].is_active and n...
def _can_redirect_to_single_survey(surveys): # Make sure redirection to first survey does not happen before login if user is required.
if not session.user and len(surveys) == 1 and surveys[0].is_active and surveys[0].require_user: return False return len(surveys) == 1 and surveys[0].is_active and not was_survey_submitted(surveys[0])
Event from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for def _can_redirect_to_single_survey(surveys): # Make sure redirection to first survey does not happen before login if user is required.
64
64
94
31
32
salevajo/indico
indico/modules/events/surveys/controllers/display.py
Python
_can_redirect_to_single_survey
_can_redirect_to_single_survey
29
34
29
30
4610d20404931ef3d8c7483ba22ca6f3bbd47caf
bigcode/the-stack
train
2e85bb60f6d7ecbac962a4b6
train
class
class RHSubmitSurvey(RHSubmitSurveyBase): def _process(self): form = self._make_form() if form.validate_on_submit(): submission = self._save_answers(form) if submission.is_anonymous and submission.user: submission.user = None self.survey.anonym...
class RHSubmitSurvey(RHSubmitSurveyBase):
def _process(self): form = self._make_form() if form.validate_on_submit(): submission = self._save_answers(form) if submission.is_anonymous and submission.user: submission.user = None self.survey.anonymous_submissions.append(AnonymousSurveySubm...
sections').joinedload('children')) .one()) self.submission = (session.user.survey_submissions.filter_by(survey=self.survey, is_submitted=False).first() if session.user else None) if not self.survey.is_active: flash(_('This survey is not activ...
128
128
428
10
118
salevajo/indico
indico/modules/events/surveys/controllers/display.py
Python
RHSubmitSurvey
RHSubmitSurvey
91
136
91
91
44bbea248ec9cb6c94ae7fcae5bb8e72b7df1f85
bigcode/the-stack
train
0504fff2c4585f231b8ff674
train
class
class RHSurveyBaseDisplay(RHDisplayEventBase): @property def view_class(self): return WPDisplaySurveyConference if self.event.type_ == EventType.conference else WPDisplaySurveySimpleEvent
class RHSurveyBaseDisplay(RHDisplayEventBase): @property
def view_class(self): return WPDisplaySurveyConference if self.event.type_ == EventType.conference else WPDisplaySurveySimpleEvent
and surveys[0].is_active and surveys[0].require_user: return False return len(surveys) == 1 and surveys[0].is_active and not was_survey_submitted(surveys[0]) class RHSurveyBaseDisplay(RHDisplayEventBase): @property
64
64
44
15
49
salevajo/indico
indico/modules/events/surveys/controllers/display.py
Python
RHSurveyBaseDisplay
RHSurveyBaseDisplay
37
40
37
38
b4486cb61c5b284cbdb194abf2909bd0895a65bd
bigcode/the-stack
train
bf0c821bb50d3c17e66e3704
train
class
class RHSubmitSurveyBase(RHSurveyBaseDisplay): normalize_url_spec = { 'locators': { lambda self: self.survey } } def _check_access(self): RHSurveyBaseDisplay._check_access(self) if self.survey.require_user and not session.user: raise Forbidden(respons...
class RHSubmitSurveyBase(RHSurveyBaseDisplay):
normalize_url_spec = { 'locators': { lambda self: self.survey } } def _check_access(self): RHSurveyBaseDisplay._check_access(self) if self.survey.require_user and not session.user: raise Forbidden(response=redirect_to_login(reason=_('You are trying to...
')) .all()) if _can_redirect_to_single_survey(surveys): return redirect(url_for('.display_survey_form', surveys[0])) return self.view_class.render_template('display/survey_list.html', self.event, surveys=surveys, states=Surve...
95
95
318
11
84
salevajo/indico
indico/modules/events/surveys/controllers/display.py
Python
RHSubmitSurveyBase
RHSubmitSurveyBase
58
88
58
58
a8d64a3ad630069cf0464c78938fb6b7465d7fa6
bigcode/the-stack
train
f2f1839733f430fecbd44c39
train
class
class DatasetSchemaTest(unittest.TestCase): def test_feature_spec_unsupported_dtype(self): with self.assertRaisesRegexp(ValueError, 'invalid dtype'): sch.Schema({ 'fixed_float': sch.ColumnSchema( tf.float64, [], sch.FixedColumnRepresentation()) }) def test_manually_create_s...
class DatasetSchemaTest(unittest.TestCase):
def test_feature_spec_unsupported_dtype(self): with self.assertRaisesRegexp(ValueError, 'invalid dtype'): sch.Schema({ 'fixed_float': sch.ColumnSchema( tf.float64, [], sch.FixedColumnRepresentation()) }) def test_manually_create_schema(self): schema = test_common.get_man...
either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for dataset_metadata. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # GOOGLE-INITIALIZATION import tensorflow a...
104
104
347
8
95
redpoint13/transform
tensorflow_transform/tf_metadata/dataset_schema_test.py
Python
DatasetSchemaTest
DatasetSchemaTest
30
71
30
31
5df35fee9de78cd263aa840861041e59eb90179b
bigcode/the-stack
train
c480cba627fd8f6c88699cac
train
function
def retry_on_exception(exception_type): def do_retry_on_exception(func): @wraps(func) def retry(*args, **kwargs): return RetryFunc(exception_type).go(func, *args, **kwargs) return retry return do_retry_on_exception
def retry_on_exception(exception_type):
def do_retry_on_exception(func): @wraps(func) def retry(*args, **kwargs): return RetryFunc(exception_type).go(func, *args, **kwargs) return retry return do_retry_on_exception
retry_func = RetryFunc(OsbsResponseException, should_retry_cb=should_retry_cb, retry_times=OS_NOT_FOUND_MAX_RETRIES, retry_delay=OS_NOT_FOUND_MAX_WAIT) return retry_func.go(func, *args, **kwargs) return retry def retry_on_exception(exception_ty...
64
64
57
7
56
hjmodi/osbs-client
osbs/utils/__init__.py
Python
retry_on_exception
retry_on_exception
580
588
580
580
78e44821899fcfdb3ce0d16a0cc1a964578c9524
bigcode/the-stack
train
3d84effd4c1c4a38095f8242
train
function
def buildconfig_update(orig, new, remove_nonexistent_keys=False): """Performs update of given `orig` BuildConfig with values from `new` BuildConfig. Both BuildConfigs have to be represented as `dict`s. This function: - adds all key/value pairs to `orig` from `new` that are missing - replaces values...
def buildconfig_update(orig, new, remove_nonexistent_keys=False):
"""Performs update of given `orig` BuildConfig with values from `new` BuildConfig. Both BuildConfigs have to be represented as `dict`s. This function: - adds all key/value pairs to `orig` from `new` that are missing - replaces values in `orig` for keys that are in both - removes key/value pairs...
iggers') is not None def clean_triggers(orig, new): if not has_triggers(new) and has_triggers(orig): orig['spec']['triggers'] = [t for t in orig['spec']['triggers'] if t.get('type', None) != 'ImageChange'] def buildconfig_update(orig, new, remove_nonexistent_keys=False)...
77
77
259
14
63
hjmodi/osbs-client
osbs/utils/__init__.py
Python
buildconfig_update
buildconfig_update
174
197
174
174
afe88ab3d68e36f1be58d6d9e3ecd2242d86ca15
bigcode/the-stack
train
80747119946f4201c6afec8f
train
function
def graceful_chain_del(d, *args): if not d: return for arg in args[:-1]: try: d = d[arg] except (IndexError, KeyError): return try: del d[args[-1]] except (IndexError, KeyError): pass
def graceful_chain_del(d, *args):
if not d: return for arg in args[:-1]: try: d = d[arg] except (IndexError, KeyError): return try: del d[args[-1]] except (IndexError, KeyError): pass
_chain_get(d, *args): if not d: return None t = copy.deepcopy(d) for arg in args: try: t = t[arg] except (IndexError, KeyError): return None return t def graceful_chain_del(d, *args):
64
64
69
9
54
hjmodi/osbs-client
osbs/utils/__init__.py
Python
graceful_chain_del
graceful_chain_del
150
161
150
150
4c2a0a813b5c22bc84f7668c4886e3d307fd87cf
bigcode/the-stack
train
e69dbb1b49ed920e905199bd
train
function
def clone_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the rep...
def clone_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None):
""" clone provided git repo to target_dir, optionally checkout provided commit :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git c...
:param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD """ tmpdir = tempfile...
167
167
559
31
136
hjmodi/osbs-client
osbs/utils/__init__.py
Python
clone_git_repo
clone_git_repo
223
277
223
224
39b384090eb3faed93b146c7fd8ae9a8b1062c64
bigcode/the-stack
train
d39090f61d2b7b970196a9d9
train
function
def wrap_name_from_git(prefix, suffix, *args, **kwargs): """ wraps the result of make_name_from_git in a suffix and postfix adding separators for each. see docstring for make_name_from_git for a full list of parameters """ # 64 is maximum length allowed by OpenShift # 2 is the number of das...
def wrap_name_from_git(prefix, suffix, *args, **kwargs):
""" wraps the result of make_name_from_git in a suffix and postfix adding separators for each. see docstring for make_name_from_git for a full list of parameters """ # 64 is maximum length allowed by OpenShift # 2 is the number of dashes that will be added prefix = ''.join(filter(VALID_...
_size] limit = limit - len(hash_str) - 1 sanitized = sanitize_strings_for_openshift(repo, branch, limit, separator, False) return separator.join(filter(None, (sanitized, hash_str))) def wrap_name_from_git(prefix, suffix, *args, **kwargs):
63
64
176
15
48
hjmodi/osbs-client
osbs/utils/__init__.py
Python
wrap_name_from_git
wrap_name_from_git
490
503
490
490
d67511902d2bea367434affd42d30bac3685f736
bigcode/the-stack
train
a8ccc6f6f0129f89600bbb46
train
function
def utcnow(): """ Return current time in UTC. This function is created to make mocking in unit tests easier. """ return datetime.utcnow()
def utcnow():
""" Return current time in UTC. This function is created to make mocking in unit tests easier. """ return datetime.utcnow()
# format Origin provides). Note that this will fail to parse # valid ISO8601 timestamps not in this exact format. time_tuple = strptime(rfc3339, '%Y-%m-%dT%H:%M:%SZ') return timegm(time_tuple) def utcnow():
64
64
33
4
60
hjmodi/osbs-client
osbs/utils/__init__.py
Python
utcnow
utcnow
402
408
402
402
1d7e928ac0b6cc35cc35acb296df321064266e9e
bigcode/the-stack
train
f2e64fbe052d96e17bba62d6
train
function
@contextlib.contextmanager def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit yield the ClonedRepoData and delete the repo when finished ...
@contextlib.contextmanager def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None):
""" clone provided git repo to target_dir, optionally checkout provided commit yield the ClonedRepoData and delete the repo when finished :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 ...
dict) and isinstance(v, dict): buildconfig_update(orig[k], v, remove_nonexistent_keys) else: orig[k] = v @contextlib.contextmanager def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None):
69
69
233
37
31
hjmodi/osbs-client
osbs/utils/__init__.py
Python
checkout_git_repo
checkout_git_repo
200
220
200
202
3d7a5a3254f6a9894826c6cb17e08e3deaa140fd
bigcode/the-stack
train
9a39bd1dab1a3e1072a12442
train
function
def git_repo_humanish_part_from_uri(git_uri): git_uri = git_uri.rstrip('/') if git_uri.endswith("/.git"): git_uri = git_uri[:-5] elif git_uri.endswith(".git"): git_uri = git_uri[:-4] return os.path.basename(git_uri)
def git_repo_humanish_part_from_uri(git_uri):
git_uri = git_uri.rstrip('/') if git_uri.endswith("/.git"): git_uri = git_uri[:-5] elif git_uri.endswith(".git"): git_uri = git_uri[:-4] return os.path.basename(git_uri)
_path=code_dir, depth=depth) tags_config = AdditionalTagsConfig(dir_path=code_dir, tags=config.container.get('tags', set())) repo_info = RepoInfo(dfp, config, tags_config) return repo_info def git_repo_humanish_part_from_uri(git_uri):
64
64
65
13
50
hjmodi/osbs-client
osbs/utils/__init__.py
Python
git_repo_humanish_part_from_uri
git_repo_humanish_part_from_uri
369
376
369
369
5cf4bb6c2cd9b815b746c4f9c992c8f7528805a0
bigcode/the-stack
train
14b0e7c27df193837c2fac48
train
class
class RetryFunc(object): def __init__(self, exception_type, should_retry_cb=None, retry_times=OS_CONFLICT_MAX_RETRIES, retry_delay=OS_CONFLICT_WAIT): self.exception_type = exception_type self.should_retry_cb = should_retry_cb or (lambda ex: True) self.retry_times = retry_ti...
class RetryFunc(object):
def __init__(self, exception_type, should_retry_cb=None, retry_times=OS_CONFLICT_MAX_RETRIES, retry_delay=OS_CONFLICT_WAIT): self.exception_type = exception_type self.should_retry_cb = should_retry_cb or (lambda ex: True) self.retry_times = retry_times self.retry_de...
retry def retry_on_exception(exception_type): def do_retry_on_exception(func): @wraps(func) def retry(*args, **kwargs): return RetryFunc(exception_type).go(func, *args, **kwargs) return retry return do_retry_on_exception class RetryFunc(object):
64
64
193
5
58
hjmodi/osbs-client
osbs/utils/__init__.py
Python
RetryFunc
RetryFunc
591
610
591
591
ddd8fe0f379448a9d4a9399bffa15e009bab2426
bigcode/the-stack
train
95eb99f3b107ab51a1d1f582
train
function
def retry_on_conflict(func): @wraps(func) def retry(*args, **kwargs): # Only retry when OsbsResponseException was raised due to a conflict def should_retry_cb(ex): return ex.status_code == http_client.CONFLICT retry_func = RetryFunc(OsbsResponseException, should_retry_cb=sho...
def retry_on_conflict(func): @wraps(func)
def retry(*args, **kwargs): # Only retry when OsbsResponseException was raised due to a conflict def should_retry_cb(ex): return ex.status_code == http_client.CONFLICT retry_func = RetryFunc(OsbsResponseException, should_retry_cb=should_retry_cb) return retry_func.go(fun...
(parts) < 3: parts += [0] * (3 - len(parts)) major, minor, micro = parts[:3] cleaned_version = '{}.{}.{}'.format(major, minor, micro) return cleaned_version def retry_on_conflict(func): @wraps(func)
64
64
93
13
50
hjmodi/osbs-client
osbs/utils/__init__.py
Python
retry_on_conflict
retry_on_conflict
537
547
537
538
c94a680d87568661e9cc7d9936e197bdc14ddfac
bigcode/the-stack
train
e6dee2aa3f84d9c907fa8dc4
train
function
def get_instance_token_file_name(instance): """Return the token file name for the given instance.""" return '{}/.osbs/{}.token'.format(os.path.expanduser('~'), instance)
def get_instance_token_file_name(instance):
"""Return the token file name for the given instance.""" return '{}/.osbs/{}.token'.format(os.path.expanduser('~'), instance)
kwargs['limit'] = kwargs.get('limit', 64) - len(prefix) - len(suffix) - 2 name_from_git = make_name_from_git(*args, **kwargs) return '-'.join([prefix, name_from_git, suffix]) def get_instance_token_file_name(instance):
64
64
41
8
56
hjmodi/osbs-client
osbs/utils/__init__.py
Python
get_instance_token_file_name
get_instance_token_file_name
506
508
506
506
873636f18bbcb88769dace6253688793ec66d79e
bigcode/the-stack
train
b6766d78763bd002f44a482f
train
class
class TarReader(object): TarFile = namedtuple('TarFile', ['filename', 'fileobj']) def __init__(self, infile): mode = "r|bz2" if hasattr(infile, "read"): self.tarfile = tarfile.open(fileobj=infile, mode=mode) else: self.tarfile = tarfile.open(name=infile, mode=mod...
class TarReader(object):
TarFile = namedtuple('TarFile', ['filename', 'fileobj']) def __init__(self, infile): mode = "r|bz2" if hasattr(infile, "read"): self.tarfile = tarfile.open(fileobj=infile, mode=mode) else: self.tarfile = tarfile.open(name=infile, mode=mode) def __iter__(self...
_file(self, name, content): buf = BytesIO(content) arcname = os.path.join(self.directory, name) ti = tarfile.TarInfo(arcname) ti.size = len(content) self.tarfile.addfile(ti, fileobj=buf) class TarReader(object):
64
64
177
5
59
hjmodi/osbs-client
osbs/utils/__init__.py
Python
TarReader
TarReader
110
135
110
110
6fc7e869c3d600f70ac21c533388b6e2109a52f2
bigcode/the-stack
train
0e5d17901f961c33cabfaf26
train
function
def clean_triggers(orig, new): if not has_triggers(new) and has_triggers(orig): orig['spec']['triggers'] = [t for t in orig['spec']['triggers'] if t.get('type', None) != 'ImageChange']
def clean_triggers(orig, new):
if not has_triggers(new) and has_triggers(orig): orig['spec']['triggers'] = [t for t in orig['spec']['triggers'] if t.get('type', None) != 'ImageChange']
, KeyError): return try: del d[args[-1]] except (IndexError, KeyError): pass def has_triggers(build_config): return graceful_chain_get(build_config, 'spec', 'triggers') is not None def clean_triggers(orig, new):
64
64
57
8
55
hjmodi/osbs-client
osbs/utils/__init__.py
Python
clean_triggers
clean_triggers
168
171
168
168
41bf4382e86924c9e4cf933392af3eba0f61370f
bigcode/the-stack
train
d77806d0a2e3b7f7167a3f8e
train
function
def get_repo_info(git_uri, git_ref, git_branch=None, depth=None): with checkout_git_repo(git_uri, commit=git_ref, branch=git_branch, depth=depth) as code_dir_info: code_dir = code_dir_info.repo_path depth = code_dir_info.commit_depth dfp = DockerfileParser(os.path....
def get_repo_info(git_uri, git_ref, git_branch=None, depth=None):
with checkout_git_repo(git_uri, commit=git_ref, branch=git_branch, depth=depth) as code_dir_info: code_dir = code_dir_info.repo_path depth = code_dir_info.commit_depth dfp = DockerfileParser(os.path.join(code_dir), cache_content=True) config = RepoConfigura...
("Ignoring resourcequota error") else: raise def looks_like_git_hash(git_ref): return all(ch in string.hexdigits for ch in git_ref) and len(git_ref) == 40 def get_repo_info(git_uri, git_ref, git_branch=None, depth=None):
64
64
160
18
45
hjmodi/osbs-client
osbs/utils/__init__.py
Python
get_repo_info
get_repo_info
355
366
355
355
e042d7475b6f6b00ab364b570559886222e30600
bigcode/the-stack
train
7446481ccc653886a3ea48b8
train
function
def retry_on_not_found(func): @wraps(func) def retry(*args, **kwargs): # Only retry when OsbsResponseException was raised due to not found def should_retry_cb(ex): return ex.status_code == http_client.NOT_FOUND retry_func = RetryFunc(OsbsResponseException, should_retry_cb=sh...
def retry_on_not_found(func): @wraps(func)
def retry(*args, **kwargs): # Only retry when OsbsResponseException was raised due to not found def should_retry_cb(ex): return ex.status_code == http_client.NOT_FOUND retry_func = RetryFunc(OsbsResponseException, should_retry_cb=should_retry_cb, r...
_cb(ex): return ex.status_code == http_client.CONFLICT retry_func = RetryFunc(OsbsResponseException, should_retry_cb=should_retry_cb) return retry_func.go(func, *args, **kwargs) return retry def retry_on_not_found(func): @wraps(func)
64
64
114
13
50
hjmodi/osbs-client
osbs/utils/__init__.py
Python
retry_on_not_found
retry_on_not_found
550
562
550
551
35768faad2d8b155360a94026c821001fb2f9f46
bigcode/the-stack
train