buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class RequestEntityTooLarge(BadRequest): class InternalServerError(Error): code = 500 reason = "Internal Server Error"
class RequestEntityTooLarge(BadRequest): class InternalServerError(Error): code = 500 reason = "Internal Server Error" class ServerNotImplemented(Error): code = 501 reason = "Not Implemented"
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id, '--quantity', quantity] rc, stderr, stdout = self.module.run_command(args, check_rc=True) e...
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id] if quantity is not None: args.extend(['--quantity', to_native(quantity)]) ...
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, 1 pool_ids[pool_id] = str(quantity) consumer_type = module.params["consumer_type"] consumer_name = module.param...
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, None pool_ids[pool_id] = quantity consumer_type = module.params["consumer_type"] consumer_name = module.params[...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1' ], {'check_rc': True}, ...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6' ], {'check_rc': True}, (0, '', '')
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99747107e9', '--quantity', '1' ], {'check_rc': True}, ...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99747107e9' ], {'check_rc': True}, (0, '', '')
Entitlement Type: Physical '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1' ], {'check_rc': True}, (0, ...
Entitlement Type: Physical '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', ], {'check_rc': True}, (0, '', '')
from thefuck.rules.mkdir_p import match, get_new_command from tests.utils import Command def test_match(): assert match(Command('mkdir foo/bar/baz', stderr='mkdir: foo/bar: No such file or directory'), None) @pytest.mark.parametrize('command', [ Command('mkdir foo/b...
from thefuck.rules.mkdir_p import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command('mkdir foo/bar/baz', stderr='mkdir: foo/bar: No such file or directory'), Command('./bin/hdfs dfs -mkdir foo/bar/baz', stderr='mkdir: `foo/bar/baz\': No such file or directory...
def match(command, settings): @sudo_support def get_new_command(command, settings): return re.sub('^mkdir (.*)', 'mkdir -p \\1', command.script)
def match(command, settings): @sudo_support def get_new_command(command, settings): return re.sub('\\bmkdir (.*)', 'mkdir -p \\1', command.script)
class TestSortedCorrectedCommandsSequence(object): assert set(seq) == {CorrectedCommand('ls', priority=100), CorrectedCommand('ls', side_effect, 300)} class TestCorrectedCommand(object):
class TestSortedCorrectedCommandsSequence(object): assert set(seq) == {CorrectedCommand('ls', priority=100), CorrectedCommand('ls', side_effect, 300)} def test_with_blank(self, settings): seq = SortedCorrectedCommandsSequence(iter([]), settings) assert list(seq) ...
class SortedCorrectedCommandsSequence(object): def _realise(self): """Realises generator, removes duplicates and sorts commands.""" commands = self._remove_duplicates(self._commands) self._cached = [self._cached[0]] + sorted( commands, key=lambda corrected_command: corrected_com...
class SortedCorrectedCommandsSequence(object): def _realise(self): """Realises generator, removes duplicates and sorts commands.""" if self._cached: commands = self._remove_duplicates(self._commands) self._cached = [self._cached[0]] + sorted( commands, key=la...
and Index.__new__. These should not depend on core.internals. """ from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast import numpy as np
and Index.__new__. These should not depend on core.internals. """ from collections import abc from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast import numpy as np
def sanitize_array( # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) else: subarr = _try_cast(data, dtype, copy, raise_cast_failure)
def sanitize_array( # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) elif isinstance(data, abc.Set): raise TypeError("Set type is unordered") else: subarr = _try_cast(data, dtype, copy, ra...
class TestDataFrameConstructorWithDatetimeTZ: expected = DataFrame(array_dim2).astype("datetime64[ns, UTC]") tm.assert_frame_equal(df, expected)
class TestDataFrameConstructorWithDatetimeTZ: expected = DataFrame(array_dim2).astype("datetime64[ns, UTC]") tm.assert_frame_equal(df, expected) def test_construction_from_set_raises(self): # https://github.com/pandas-dev/pandas/issues/32582 msg = "Set type is unordered" wi...
from pathlib import Path from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import force_escape, pprint from django.urls import Resolver404, resolve from django.utils import tim...
from pathlib import Path from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import pprint from django.urls import Resolver404, resolve from django.utils import timezone from dja...
class ExceptionReporter: # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, force_escape(v))) frame['vars'] = frame_vars frames[i] =...
class ExceptionReporter: # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, v)) frame['vars'] = frame_vars frames[i] = frame
class ExceptionReporterTests(SimpleTestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError('Top level') except AttributeError as explicit: try: raise ValueError('Second exception') from explicit ...
class ExceptionReporterTests(SimpleTestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError(mark_safe('<p>Second excep...
class ExceptionReporterTests(SimpleTestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format("Top level"))) self.assertEqual(2, html.count(implic...
class ExceptionReporterTests(SimpleTestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2...
class LocalCache(collections.OrderedDict): self.limit = limit def __setitem__(self, key, value): while len(self) >= self.limit: self.popitem(last=False) super(LocalCache, self).__setitem__(key, value)
class LocalCache(collections.OrderedDict): self.limit = limit def __setitem__(self, key, value): if self.limit: while len(self) >= self.limit: self.popitem(last=False) super(LocalCache, self).__setitem__(key, value)
if six.PY2: else: from collections.abc import Mapping, MutableMapping from scrapy.utils.datatypes import CaselessDict, SequenceExclude __doctests__ = ['scrapy.utils.datatypes']
if six.PY2: else: from collections.abc import Mapping, MutableMapping from scrapy.utils.datatypes import CaselessDict, SequenceExclude, LocalCache __doctests__ = ['scrapy.utils.datatypes']
class SequenceExcludeTest(unittest.TestCase): for v in [-3, "test", 1.1]: self.assertNotIn(v, d) if __name__ == "__main__": unittest.main()
class SequenceExcludeTest(unittest.TestCase): for v in [-3, "test", 1.1]: self.assertNotIn(v, d) class LocalCacheTest(unittest.TestCase): def test_cache_with_limit(self): cache = LocalCache(limit=2) cache['a'] = 1 cache['b'] = 2 cache['c'] = 3 self.asse...
def check_data(self): # If there are more documents available? return self.check_node() def get_data(self): # Construct and return the next document. if self.check_node():
def check_data(self): # If there are more documents available? return self.check_node() def check_state_key(self, key): """Block special attributes/methods from being set in a newly created object, to prevent user-controlled methods from being called during deserialization""...
def construct_undefined(self, node): SafeConstructor.construct_undefined) class FullConstructor(SafeConstructor): def construct_python_str(self, node): return self.construct_scalar(node).encode('utf-8')
def construct_undefined(self, node): SafeConstructor.construct_undefined) class FullConstructor(SafeConstructor): # 'extend' is blacklisted because it is used by # construct_python_object_apply to add `listitems` to a newly generate # python instance def get_state_keys_blacklist(self): ...
def make_python_instance(self, suffix, node, else: return cls(*args, **kwds) def set_python_instance_state(self, instance, state): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else:
def make_python_instance(self, suffix, node, else: return cls(*args, **kwds) def set_python_instance_state(self, instance, state, unsafe=False): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else:
def set_python_instance_state(self, instance, state): if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if hasattr(instance, '__dict__'): instance.__dict__.update(state) elif state: slotstate.update(state) ...
def set_python_instance_state(self, instance, state): if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if hasattr(instance, '__dict__'): if not unsafe and state: for key in state.keys(): self.che...
def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False) return super(UnsafeConstructor, self).make_python_instance( suffix, node, args, kwds, newobj, unsafe=True) UnsafeConstructor.add_multi_constructor( u'tag:yaml.org,2002:python/object/apply:', UnsafeConstructor.c...
def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False) return super(UnsafeConstructor, self).make_python_instance( suffix, node, args, kwds, newobj, unsafe=True) def set_python_instance_state(self, instance, state): return super(UnsafeConstructor, self).set_pyt...
def check_data(self): # If there are more documents available? return self.check_node() def get_data(self): # Construct and return the next document. if self.check_node():
def check_data(self): # If there are more documents available? return self.check_node() def check_state_key(self, key): """Block special attributes/methods from being set in a newly created object, to prevent user-controlled methods from being called during deserialization""...
def construct_undefined(self, node): SafeConstructor.construct_undefined) class FullConstructor(SafeConstructor): def construct_python_str(self, node): return self.construct_scalar(node)
def construct_undefined(self, node): SafeConstructor.construct_undefined) class FullConstructor(SafeConstructor): # 'extend' is blacklisted because it is used by # construct_python_object_apply to add `listitems` to a newly generate # python instance def get_state_keys_blacklist(self): ...
def make_python_instance(self, suffix, node, else: return cls(*args, **kwds) def set_python_instance_state(self, instance, state): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else:
def make_python_instance(self, suffix, node, else: return cls(*args, **kwds) def set_python_instance_state(self, instance, state, unsafe=False): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else:
def set_python_instance_state(self, instance, state): if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if hasattr(instance, '__dict__'): instance.__dict__.update(state) elif state: slotstate.update(state) ...
def set_python_instance_state(self, instance, state): if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if hasattr(instance, '__dict__'): if not unsafe and state: for key in state.keys(): self.che...
def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False) return super(UnsafeConstructor, self).make_python_instance( suffix, node, args, kwds, newobj, unsafe=True) UnsafeConstructor.add_multi_constructor( 'tag:yaml.org,2002:python/object/apply:', UnsafeConstructor.co...
def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False) return super(UnsafeConstructor, self).make_python_instance( suffix, node, args, kwds, newobj, unsafe=True) def set_python_instance_state(self, instance, state): return super(UnsafeConstructor, self).set_pyt...
def _make_objects(): global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \ AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \ NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \ ...
def _make_objects(): global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \ AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \ NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \ ...
def tzname(self, dt): def dst(self, dt): return datetime.timedelta(0) today = datetime.date.today() def _load_code(expression):
def tzname(self, dt): def dst(self, dt): return datetime.timedelta(0) class MyFullLoader(yaml.FullLoader): def get_state_keys_blacklist(self): return super(MyFullLoader, self).get_state_keys_blacklist() + ['^mymethod$', '^wrong_.*$'] today = datetime.date.today() def _...
def test_constructor_types(data_filename, code_filename, verbose=False): test_constructor_types.unittest = ['.data', '.code'] if __name__ == '__main__': import sys, test_constructor sys.modules['test_constructor'] = sys.modules['__main__']
def test_constructor_types(data_filename, code_filename, verbose=False): test_constructor_types.unittest = ['.data', '.code'] def test_subclass_blacklist_types(data_filename, verbose=False): _make_objects() try: yaml.load(open(data_filename, 'rb').read(), MyFullLoader) except yaml.YAMLError as exc...
def _make_objects(): global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \ AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \ NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \ ...
def _make_objects(): global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \ AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \ NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \ ...
def tzname(self, dt): def dst(self, dt): return datetime.timedelta(0) today = datetime.date.today() def _load_code(expression):
def tzname(self, dt): def dst(self, dt): return datetime.timedelta(0) class MyFullLoader(yaml.FullLoader): def get_state_keys_blacklist(self): return super().get_state_keys_blacklist() + ['^mymethod$', '^wrong_.*$'] today = datetime.date.today() def _load_code(expressi...
def test_constructor_types(data_filename, code_filename, verbose=False): test_constructor_types.unittest = ['.data', '.code'] if __name__ == '__main__': import sys, test_constructor sys.modules['test_constructor'] = sys.modules['__main__']
def test_constructor_types(data_filename, code_filename, verbose=False): test_constructor_types.unittest = ['.data', '.code'] def test_subclass_blacklist_types(data_filename, verbose=False): _make_objects() try: yaml.load(open(data_filename, 'rb').read(), MyFullLoader) except yaml.YAMLError as exc...
def __dict__(self): with self.assertRaises(ZeroDivisionError): WorseStruct().__setstate__({}, b'foo') ################################################################ if __name__ == '__main__':
def __dict__(self): with self.assertRaises(ZeroDivisionError): WorseStruct().__setstate__({}, b'foo') def test_parameter_repr(self): from ctypes import ( c_bool, c_char, c_wchar, c_byte, c_ubyte, c_short, ...
def delete(self, req, image_id): % locals()) raise webob.exc.HTTPForbidden(explanation=msg) status = 'deleted' if image['location']: if CONF.delayed_delete: status = 'pending_delete' self.store_api.schedule_delayed_delete_from_...
def delete(self, req, image_id): % locals()) raise webob.exc.HTTPForbidden(explanation=msg) if image['location'] and CONF.delayed_delete: status = 'pending_delete' else: status = 'deleted' try: self.db_api.image_update(req.con...
def test_permissions(self): self.assertEqual(201, response.status_code) image_id = json.loads(response.text)['id'] # TENANT1 should see the image in their list path = self._url('/v2/images') response = requests.get(path, headers=self._headers())
def test_permissions(self): self.assertEqual(201, response.status_code) image_id = json.loads(response.text)['id'] # Upload some image data path = self._url('/v2/images/%s/file' % image_id) headers = self._headers({'Content-Type': 'application/octet-stream'}) response = ...
def test_permissions(self): response = requests.delete(path, headers=headers) self.assertEqual(404, response.status_code) self.stop_servers() def test_tag_lifecycle(self):
def test_permissions(self): response = requests.delete(path, headers=headers) self.assertEqual(404, response.status_code) # Image data should still be present after the failed delete path = self._url('/v2/images/%s/file' % image_id) response = requests.get(path, headers=self._he...
class IOLoop(Configurable): if IOLoop.current(instance=False) is None: self.make_current() elif make_current: if IOLoop.current(instance=False) is None: raise RuntimeError("current IOLoop already exists") self.make_current()
class IOLoop(Configurable): if IOLoop.current(instance=False) is None: self.make_current() elif make_current: if IOLoop.current(instance=False) is not None: raise RuntimeError("current IOLoop already exists") self.make_current()
class TestIOLoop(AsyncTestCase): # automatically set as current. class TestIOLoopCurrent(unittest.TestCase): def setUp(self): self.io_loop = IOLoop() def tearDown(self): self.io_loop.close() def test_current(self): def f(): self.current_io_loop = IOLoop.current() ...
class TestIOLoop(AsyncTestCase): # automatically set as current. class TestIOLoopCurrent(unittest.TestCase): def setUp(self): self.io_loop = None IOLoop.clear_current() def tearDown(self): if self.io_loop is not None: self.io_loop.close() def test_default_current(self):...
Roger E. Masse """ from test.test_support import verbose, unlink import imageop, uu, os def main(use_rgbimg=1): # Create binary test files uu.decode(get_qualified_path('testrgb'+os.extsep+'uue'), 'test'+os.extsep+'rgb')
Roger E. Masse """ from test.test_support import verbose, unlink, run_unittest import imageop, uu, os, unittest SIZES = (1, 2, 3, 4) _VALUES = (1, 2, 2**10, 2**15-1, 2**15, 2**15+1, 2**31-2, 2**31-1) VALUES = tuple( -x for x in reversed(_VALUES) ) + (0,) + _VALUES AAAAA = "A" * 1024 class InputValidationTests(u...
def get_qualified_path(name): if os.path.exists(fullname): return fullname return name # rgbimg (unlike imgfile) is portable to platforms other than SGI. # So we prefer to use it. main(use_rgbimg=1)
def get_qualified_path(name): if os.path.exists(fullname): return fullname return name
def test_colorbar_label(): cbar3 = fig.colorbar(im, orientation='horizontal', label='horizontal cbar') assert cbar3.ax.get_xlabel() == 'horizontal cbar'
def test_colorbar_label(): cbar3 = fig.colorbar(im, orientation='horizontal', label='horizontal cbar') assert cbar3.ax.get_xlabel() == 'horizontal cbar' @pytest.mark.parametrize("clim", [(-20000, 20000), (-32768, 0)]) def test_colorbar_int(clim): # Check that we cast to float early enough to not # ov...
def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): vmin, vmax = vmax, vmin swapped = True maxabsvalue = max(abs(vmin), abs(vmax)) if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny: vmin = -expander
def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): vmin, vmax = vmax, vmin swapped = True # Expand vmin, vmax to float: if they were integer types, they can wrap # around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow. vmin, vmax = map(float, [vmin, ...
def authenticate(self, context, credentials=None, context=context, user_id=creds_ref['user_id']) metadata_ref = self.identity_api.get_metadata( context=context, user_id=user_ref['id'], tenant_id=tenant_ref['id']) catalog_ref...
def authenticate(self, context, credentials=None, context=context, user_id=creds_ref['user_id']) metadata_ref = self.identity_api.get_metadata( context=context, user_id=user_ref['id'], tenant_id=tenant_ref['id']) # TODO(termie): optimi...
def authenticate(self, context, credentials=None, tenant=tenant_ref, metadata=metadata_ref)) # TODO(termie): optimize this call at some point and put it into the # the return for metadata # fill out th...
def authenticate(self, context, credentials=None, tenant=tenant_ref, metadata=metadata_ref)) # TODO(termie): make this a util function or something # TODO(termie): i don't think the ec2 middleware currently expects a ...
class TestUtil(unittest.TestCase): self.assertEqual(unescapeHTML('&#47;'), '/') self.assertEqual(unescapeHTML('&eacute;'), 'é') self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;') # HTML5 entities self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
class TestUtil(unittest.TestCase): self.assertEqual(unescapeHTML('&#47;'), '/') self.assertEqual(unescapeHTML('&eacute;'), 'é') self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;') self.assertEqual(unescapeHTML('&a&quot;'), '&a"') # HTML5 entities self.assertE...
def unescapeHTML(s): assert type(s) == compat_str return re.sub( r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s) def get_subprocess_encoding():
def unescapeHTML(s): assert type(s) == compat_str return re.sub( r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s) def get_subprocess_encoding():
notes: rules. This should work out in most cases, but it is theoretically possible to see spurious changes when target and actual values are semantically identical but lexically distinct. version_added: '2.3' author: - Jiri Tyr (@jtyr)
notes: rules. This should work out in most cases, but it is theoretically possible to see spurious changes when target and actual values are semantically identical but lexically distinct. - "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter handling. The I(...
options: a list of strings (see examples). type: raw required: true params: description: - Additional module parameters. type: dict extends_documentation_fragment: - ldap.documentation '''
options: a list of strings (see examples). type: raw required: true extends_documentation_fragment: - ldap.documentation '''
EXAMPLES = r''' # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password - name: Get rid of an unneeded attribute ldap_attr: dn: uid=jdoe,ou=people,dc=example,dc=com name: shadowExpire values: [] state: exact params: "{{ ldap_auth }}" ''' RETURN = r'''
EXAMPLES = r''' # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password # # In the example below, 'args' is a task keyword, passed at the same level as the module - name: Get rid of an unneeded attribute ldap_attr: dn: uid=jdoe,ou=people,dc=example,dc=com name: shadowEx...
modlist: ''' import traceback from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native, to_bytes
modlist: ''' import traceback from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native, to_bytes
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) # Update module parameters with user's parameters if defined if 'params' in module.params and isinstance(module.params['params'], dict): module.params.update(module.params['par...
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) # For Ansible-2.9.x and below, allow the params module parameter with a warning if LooseVersion(module.ansible_version) < LooseVersion('2.10'): if module.params['params']: ...
notes: rule allowing root to modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in I(bind_dn) and I(bind_pw). version_added: '2.3' author: - Jiri Tyr (@jtyr)
notes: rule allowing root to modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in I(bind_dn) and I(bind_pw). - "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter handling. The I(params) parameter s...
options: - If I(state=present), value or list of values to use when creating the entry. It can either be a string or an actual list of strings. params: description: - List of options which allows to overwrite any of the task or the I(attributes) options. To remove an option, se...
options: - If I(state=present), value or list of values to use when creating the entry. It can either be a string or an actual list of strings. state: description: - The target state of the entry.
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password - name: Get rid of an old entry ldap_entry: dn: ou=stuff,dc=example,dc=com state: absent params: "{{ ldap_auth }}" """
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password # # In the example below, 'args' is a task keyword, passed at the same level as the module - name: Get rid of an old entry ldap_entry: dn: ou=stuff,dc=example,dc=com state: absent args: "{{ ldap_au...
RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.six import string_types
RETURN = """ """ import traceback from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.six import string_types
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) state = module.params['state'] # Check if objectClass is present when needed
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) # For Ansible-2.9.x and below, allow the params module parameter with a warning if LooseVersion(module.ansible_version) < LooseVersion('2.10'): if module.params['params']: ...
def main(): isinstance(module.params['objectClass'], list))): module.fail_json(msg="objectClass must be either a string or a list.") # Update module parameters with user's parameters if defined if 'params' in module.params and isinstance(module.params['params'], dict): for key, ...
def main(): isinstance(module.params['objectClass'], list))): module.fail_json(msg="objectClass must be either a string or a list.") # Instantiate the LdapEntry object ldap = LdapEntry(module)
import functools import inspect import logging import ssl import warnings import requests from requests import adapters try: from requests.packages.urllib3.exceptions import InsecureRequestWarning except ImportError:
import functools import inspect import logging import os import ssl import warnings import requests from requests import adapters from requests.adapters import DEFAULT_POOLBLOCK, DEFAULT_POOLSIZE, DEFAULT_RETRIES try: from requests.packages.urllib3.exceptions import InsecureRequestWarning except ImportError:
def wrapper(self, *args, **kwargs): class SSLContextAdapter(adapters.HTTPAdapter): """Custom SSLContext Adapter for requests """ def init_poolmanager(self, connections, maxsize, block=adapters.DEFAULT_POOLBLOCK, **pool_kwargs): context = ssl.SSLContext(
def wrapper(self, *args, **kwargs): class SSLContextAdapter(adapters.HTTPAdapter): """ Custom SSLContext Adapter for requests """ def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOL...
def init_poolmanager(self, connections, maxsize, if getattr(context, "post_handshake_auth", None) is not None: context.post_handshake_auth = True pool_kwargs['ssl_context'] = context return super().init_poolmanager( connections, maxsize, block, **pool_kwargs
def init_poolmanager(self, connections, maxsize, if getattr(context, "post_handshake_auth", None) is not None: context.post_handshake_auth = True # Load from the system trust store when possible; per documentation # this call could silently fail and refuse to configure any #...
class PKIConnection: def __init__(self, protocol='http', hostname='localhost', port='8080', subsystem=None, accept='application/json', trust_env=None, verify=False): """ Set the parameters for a python-requests based connection to a Dogtag subsystem.
class PKIConnection: def __init__(self, protocol='http', hostname='localhost', port='8080', subsystem=None, accept='application/json', trust_env=None, verify=True, cert_paths=None): """ Set the parameters for a python-requests based connection to a Dogtag s...
def __init__(self, protocol='http', hostname='localhost', port='8080', :param verify: verify TLS/SSL connections and configure CA certs (default: no) :type verify: None, bool, str :return: PKIConnection object. """
def __init__(self, protocol='http', hostname='localhost', port='8080', :param verify: verify TLS/SSL connections and configure CA certs (default: no) :type verify: None, bool, str :param cert_paths: paths to CA certificates / directories in OpenSSL format. (default: None) ...
def __init__(self, protocol='http', hostname='localhost', port='8080', self.serverURI = self.rootURI self.session = requests.Session() self.session.mount("https://", SSLContextAdapter()) self.session.trust_env = trust_env self.session.verify = verify
def __init__(self, protocol='http', hostname='localhost', port='8080', self.serverURI = self.rootURI self.session = requests.Session() self.session.mount("https://", SSLContextAdapter(verify=verify, cert_paths=cert_paths)) self.session.trust_env = trust_env self.session.veri...
class NDFrame(PandasObject, SelectionMixin): data = self.fillna(method=fill_method, limit=limit, axis=axis) rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1 rs = rs.reindex_like(data) if freq is None: mask = isna(com.values_from_object(data)...
class NDFrame(PandasObject, SelectionMixin): data = self.fillna(method=fill_method, limit=limit, axis=axis) rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1 rs = rs.loc[~rs.index.duplicated()] rs = rs.reindex_like(data) if freq is None: ...
class TestTimeSeries: rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled) ) def test_pct_change_shift_over_nas(self): s = Series([1.0, 1.5, np.nan, 2.5, 3.0])
class TestTimeSeries: rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled) ) def test_pct_change_with_duplicate_axis(self): # GH 28664 common_idx = date_range("2019-11-14", periods=5, freq="D") result = Series(range(5), common_idx).pct_change(freq="B") ...
from youtube_dl.utils import ( xpath_with_ns, parse_iso8601, strip_jsonp, ) if sys.version_info < (3, 0):
from youtube_dl.utils import ( xpath_with_ns, parse_iso8601, strip_jsonp, uppercase_escape, ) if sys.version_info < (3, 0):
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) def test_uppercase_escpae(self): self.assertEqual(uppercase_escape(u'aä'), u'aä') self.assertEqual(uppercase_escape(u'\\U0001d550'), u'𝕐') if __name__ == '__main__': unit...
# -*- coding: utf-8 -*- import calendar import contextlib import ctypes import datetime
# -*- coding: utf-8 -*- import calendar import codecs import contextlib import ctypes import datetime
class PagedList(object): def uppercase_escape(s): return re.sub( r'\\U[0-9a-fA-F]{8}', lambda m: m.group(0).decode('unicode-escape'), s) try: struct.pack(u'!I', 0)
class PagedList(object): def uppercase_escape(s): unicode_escape = codecs.getdecoder('unicode_escape') return re.sub( r'\\U[0-9a-fA-F]{8}', lambda m: unicode_escape(m.group(0))[0], s) try: struct.pack(u'!I', 0)
class SSHClient(object): # Salt API should never offer a custom roster! self.opts["__disable_custom_roster"] = disable_custom_roster def _prep_ssh( self, tgt, fun, arg=(), timeout=None, tgt_type="glob", kwarg=None, **kwargs ): """ Prepare the arguments """ ...
class SSHClient(object): # Salt API should never offer a custom roster! self.opts["__disable_custom_roster"] = disable_custom_roster def sanitize_kwargs(self, kwargs): roster_vals = [ ("host", str), ("ssh_user", str), ("ssh_passwd", str), ("ss...
class NetapiSSHClientAuthTest(SSHCase): except AssertionError: self.mod_case.run_function("user.delete", [self.USERA], remove=True) self.skipTest("Could not add user or password, skipping test") def tearDown(self): del self.netapi self.mod_case.run_function("user.del...
class NetapiSSHClientAuthTest(SSHCase): except AssertionError: self.mod_case.run_function("user.delete", [self.USERA], remove=True) self.skipTest("Could not add user or password, skipping test") self.expfile = os.path.join(RUNTIME_VARS.TMP, "exploited") def tearDown(self): ...
class NetapiSSHClientAuthTest(SSHCase): ret = self.netapi.run(low) assert "localhost" in ret assert ret["localhost"]["return"] is True
class NetapiSSHClientAuthTest(SSHCase): ret = self.netapi.run(low) assert "localhost" in ret assert ret["localhost"]["return"] is True def test_ssh_cve_2021_3197_a(self): assert not os.path.exists(self.expfile) low = { "eauth": "auto", "username": sel...
class CentralPlannerScheduler(Scheduler): for task in self._state.get_active_tasks(): self._state.fail_dead_worker_task(task, self._config, assistant_ids) if task.id not in necessary_tasks and self._state.prune(task, self._config): remove_tasks.append(task.id) s...
class CentralPlannerScheduler(Scheduler): for task in self._state.get_active_tasks(): self._state.fail_dead_worker_task(task, self._config, assistant_ids) removed = self._state.prune(task, self._config) if removed and task.id not in necessary_tasks: remove_ta...
class CentralPlannerTest(unittest.TestCase): self.sch.prune() self.assertFalse(list(self.sch.task_list('', ''))) def test_fail_job_from_dead_worker_with_live_assistant(self): self.setTime(0) self.sch.add_task(worker='X', task_id='A')
class CentralPlannerTest(unittest.TestCase): self.sch.prune() self.assertFalse(list(self.sch.task_list('', ''))) def test_re_enable_failed_task_assistant(self): self.setTime(0) self.sch.add_worker('X', [('assistant', True)]) self.sch.add_task(worker='X', task_id='A', status=...
def _find_module_utils(module_name, b_module_data, module_path, module_args, tas # FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it module_json = json.dumps(exec_manifest) b_module_data = exec_wrapper.replace(b"$json_raw = ''", b"$json...
def _find_module_utils(module_name, b_module_data, module_path, module_args, tas # FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it module_json = json.dumps(exec_manifest) # delimit the payload JSON from the wrapper to keep sensitive c...
class ActionModule(ActionBase): exec_data = None # WinRM requires a special wrapper to work with environment variables if self._connection.transport == "winrm": pay = self._connection._create_raw_wrapper_payload(script_cmd, ...
class ActionModule(ActionBase): exec_data = None # WinRM requires a special wrapper to work with environment variables if self._connection.transport == "winrm": pay = self._connection._create_raw_wrapper_payload(script_cmd, env_dict) exec_data = to_byt...
class Connection(ConnectionBase): # starting a new interpreter to save on time b_command = base64.b64decode(cmd.split(" ")[-1]) script = to_text(b_command, 'utf-16-le') display.vvv("PSRP: EXEC %s" % script, host=self._psrp_host) else: # in other cases ...
class Connection(ConnectionBase): # starting a new interpreter to save on time b_command = base64.b64decode(cmd.split(" ")[-1]) script = to_text(b_command, 'utf-16-le') in_data = to_text(in_data, errors="surrogate_or_strict", nonstring="passthru") display.vvv(...
import traceback import json import tempfile import subprocess HAVE_KERBEROS = False try:
import traceback import json import tempfile import subprocess import xml.etree.ElementTree as ET HAVE_KERBEROS = False try:
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc, st...
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML\r\n") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc...
import base64 import os import re import shlex from ansible.errors import AnsibleError from ansible.module_utils._text import to_text
import base64 import os import re import shlex import pkgutil from ansible.errors import AnsibleError from ansible.module_utils._text import to_text
begin { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output # NB: do not adjust the following line- it is replaced when doing non-streamed module output $json_raw...
begin { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output # only init and stream in $json_raw if it wasn't set by the enclosing scope if (-not $(Get-Variable "j...
namespace AnsibleBecome $become_exec_wrapper = { chcp.com 65001 > $null $ProgressPreference = "SilentlyContinue" $exec_wrapper_str = [System.Console]::In.ReadToEnd() $exec_wrapper = [ScriptBlock]::Create($exec_wrapper_str) &$exec_wrapper } $exec_wrapper = {
namespace AnsibleBecome $become_exec_wrapper = { chcp.com 65001 > $null $ProgressPreference = "SilentlyContinue" $raw = [System.Console]::In.ReadToEnd() $split_parts = $raw.Split(@("`0`0`0`0"), 0) If (-not $split_parts.Length -eq 2) { throw "invalid payload" } $json_raw = $split_parts[1] &([...
$exec_wrapper = { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output. Do not change this as it is set become before being passed to the # become process. $json_ra...
$exec_wrapper = { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output. Do not change this as it is set become before being passed to the # become process. if (-no...
Function Run($payload) { # wrapper which calls our read wrapper passed through stdin. Cannot use 'powershell -' as # the $ErrorActionPreference is always set to Stop and cannot be changed $payload_string = $payload | ConvertTo-Json -Depth 99 -Compress $exec_wrapper = $exec_wrapper.ToString().Replace('$j...
Function Run($payload) { # wrapper which calls our read wrapper passed through stdin. Cannot use 'powershell -' as # the $ErrorActionPreference is always set to Stop and cannot be changed $payload_string = $payload | ConvertTo-Json -Depth 99 -Compress $exec_wrapper = $exec_wrapper.ToString() + "`0`0`0`0...
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): # pipelining bypass if cmd == '': return '-' # non-pipelining
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): bootstrap_wrapper = pkgutil.get_data("ansible.executor.powershell", "bootstrap_wrapper.ps1") # pipelining bypass if cmd == '': retur...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): cmd_parts[0] = '"%s.ps1"' % self._unquote(cmd_parts[0]) cmd_parts.insert(0, '&') ...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): # we're running a module via the bootstrap wrapper cmd_parts[0] = '"%s.ps1"' ...
WRONGCERT = data_file("XXXnonexisting.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") def handle_error(prefix):
WRONGCERT = data_file("XXXnonexisting.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") NULLBYTECERT = data_file("nullbytecert.pem") def handle_error(prefix):
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_DER_to_PEM(self): with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f: pem = f.read()
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_parse_cert_CVE_2013_4073(self): p = ssl._ssl._test_decode_cert(NULLBYTECERT) if support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") subject...
def fail(cert, hostname): fail(cert, 'foo.a.com') fail(cert, 'bar.foo.com') # Slightly fake real-world example cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT', 'subject': ((('commonName', 'linuxfrz.org'),),),
def fail(cert, hostname): fail(cert, 'foo.a.com') fail(cert, 'bar.foo.com') # NULL bytes are bad, CVE-2013-4073 cert = {'subject': ((('commonName', 'null.python.org\x00example.org'),),)} ok(cert, 'null.python.org\x00example.org') # or raise an error...
class DataFrame(NDFrame): # ---------------------------------------------------------------------- # Arithmetic / combination related def _combine_frame(self, other, func, fill_value=None, level=None): # at this point we have `self._indexed_same(other)` if fill_value is None:
class DataFrame(NDFrame): # ---------------------------------------------------------------------- # Arithmetic / combination related def _combine_frame(self, other: "DataFrame", func, fill_value=None): # at this point we have `self._indexed_same(other)` if fill_value is None:
class DataFrame(NDFrame): return new_data def _combine_match_index(self, other, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func):
class DataFrame(NDFrame): return new_data def _combine_match_index(self, other: Series, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func):
class DataFrame(NDFrame): new_data = ops.dispatch_to_series(self, other, func) else: # fastpath --> operate directly on values with np.errstate(all="ignore"): new_data = func(self.values.T, other.values).T return new_data def _construct_result(sel...
class DataFrame(NDFrame): new_data = ops.dispatch_to_series(self, other, func) else: # fastpath --> operate directly on values other_vals = other.values.reshape(-1, 1) with np.errstate(all="ignore"): new_data = func(self.values, other_vals) ...
def mask_zero_div_zero(x, y, result): return result if zmask.any(): shape = result.shape # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask nan_mask = (zmask & (x == 0)).ravel() with np.errstate(invalid="ignor...
def mask_zero_div_zero(x, y, result): return result if zmask.any(): # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask nan_mask = zmask & (x == 0) with np.errstate(invalid="ignore"): neginf_mask = (zpos_ma...
class TestFrameFlexComparisons: class TestFrameFlexArithmetic: def test_df_add_td64_columnwise(self): # GH 22534 Check that column-wise addition broadcasts correctly dti = pd.date_range("2016-01-01", periods=10)
class TestFrameFlexComparisons: class TestFrameFlexArithmetic: def test_floordiv_axis0(self): # make sure we df.floordiv(ser, axis=0) matches column-wise result arr = np.arange(3) ser = pd.Series(arr) df = pd.DataFrame({"A": ser, "B": ser}) result = df.floordiv(ser, axis=0...
default 'raise' """ from pandas import DataFrame sarray = fields.build_isocalendar_sarray(self.asi8) iso_calendar_df = DataFrame( sarray, columns=["year", "week", "day"], dtype="UInt32" )
default 'raise' """ from pandas import DataFrame if self.tz is not None and not timezones.is_utc(self.tz): values = self._local_timestamps() else: values = self.asi8 sarray = fields.build_isocalendar_sarray(values) iso_calendar_df = DataFrame( ...
def test_iter_readonly(): arr.setflags(write=False) dti = pd.to_datetime(arr) list(dti)
def test_iter_readonly(): arr.setflags(write=False) dti = pd.to_datetime(arr) list(dti) def test_isocalendar_returns_correct_values_close_to_new_year_with_tz(): # GH 6538: Check that DatetimeIndex and its TimeStamp elements # return the same weekofyear accessor close to new year w/ tz dates = ...