code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/content/{id}/descendant".format(id=content_id), params=params, callback=callback)
def get_content_descendants(self, content_id, expand=None, callback=None)
Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants - for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments. The {@link ContentType}(s) of the descendants returned is specified by the "expand" query ...
3.88593
4.388575
0.885465
params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._service_get_request("rest/api/content/{id}/descendant/{type}" ...
def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None, callback=None)
Returns the direct descendants of a piece of Content, limited to a single descendant type. The {@link ContentType}(s) of the descendants returned is specified by the "type" path parameter in the request. Currently the only supported descendants are comment descendants of non-comment Content. :...
2.425973
2.521995
0.961926
params = {} if prefix: params["prefix"] = prefix if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._service_get_request("rest/api/content/{id}/label".format(id=content_id)...
def get_content_labels(self, content_id, prefix=None, start=None, limit=None, callback=None)
Returns the list of labels on a piece of Content. :param content_id (string): A string containing the id of the labels content container. :param prefix (string): OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}. Default: None. :param start (int...
2.38431
2.523202
0.944954
params = {} if expand: params["expand"] = expand if parent_version: params["parentVersion"] = parent_version if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) if l...
def get_content_comments(self, content_id, expand=None, parent_version=None, start=None, limit=None, location=None, depth=None, callback=None)
Returns the comments associated with a piece of content. :param content_id (string): A string containing the id of the content to retrieve children for. :param expand (string): OPTIONAL: a comma separated list of properties to expand on the children. We can also specify s...
2.068612
1.99958
1.034524
params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) if filename is not None: params["filename"] = filename if media_...
def get_content_attachments(self, content_id, expand=None, start=None, limit=None, filename=None, media_type=None, callback=None)
Returns a paginated list of attachment Content entities within a single container. :param content_id (string): A string containing the id of the attachments content container. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the Attachments returned. ...
1.908807
1.970646
0.96862
params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._service_get_request("rest/api/content/{id}/property".format(id=content_...
def get_content_properties(self, content_id, expand=None, start=None, limit=None, callback=None)
Returns a paginated list of content properties. Content properties are a key / value store of properties attached to a piece of Content. The key is a string, and the value is a JSON-serializable object. :param content_id (string): A string containing the id of the property content container. ...
2.492629
2.618395
0.951968
params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/content/{id}/property/{key}".format(id=content_id, key=property_key), params=params, callback=callback)
def get_content_property_by_key(self, content_id, property_key, expand=None, callback=None)
Returns a content property. :param content_id (string): A string containing the id of the property content container. :param property_key (string): The key associated with the property requested. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the content prop...
3.546215
3.280033
1.081152
params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._service_get_request("rest/api/content/{id}/restriction/byOperation/{opk...
def get_op_restrictions_by_content_operation(self, content_id, operation_key, expand=None, start=None, limit=None, callback=None)
Returns info about all restrictions of given operation. :param content_id (string): The content ID to query on. :param operation_key (string): The operation key to query on. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the content properties. ...
2.598382
2.435685
1.066797
params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._service_get_request("rest/api/longtask", params=params, callback=callba...
def get_long_tasks(self, expand=None, start=None, limit=None, callback=None)
Returns information about all tracked long-running tasks. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the tasks. :param start (int): OPTIONAL: The pagination start count. :param limit (int): OPTIONAL: The pagination return count limit. :param callb...
2.67715
2.741019
0.976699
params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/longtask/{id}".format(id=long_task_id), params=params, callback=callback)
def get_long_task_info(self, long_task_id, expand=None, callback=None)
Returns information about a long-running task. :param long_task_id (string): The key of the task to be returned. :param expand (string): A comma separated list of properties to expand on the task. Default: Empty :param callback: OPTIONAL: The callback to execute on the resulting data, before the...
3.965158
4.009289
0.988993
params = {} if space_key: params["spaceKey"] = space_key if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._servic...
def get_spaces(self, space_key=None, expand=None, start=None, limit=None, callback=None)
Returns information about the spaces present in the Confluence instance. :param space_key (string): OPTIONAL: A list of space keys to filter on. Default: None. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the spaces. Default: Empty ...
2.17417
2.167145
1.003241
params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/space/{key}".format(key=space_key), params=params, callback=callback)
def get_space_information(self, space_key, expand=None, callback=None)
Returns information about a space. :param space_key (string): A string containing the key of the space. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the space. Default: Empty. :param callback: OPTIONAL: The callback to execute on the resulting data, before ...
4.151232
4.65054
0.892634
params = {} if depth: assert depth in {"all", "root"} params["depth"] = depth if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(l...
def get_space_content(self, space_key, depth=None, expand=None, start=None, limit=None, callback=None)
Returns the content in this given space. :param space_key (string): A string containing the key of the space. :param depth (string): OPTIONAL: A string indicating if all content, or just the root content of the space is returned. Default: "all". Valid values: "all", "root"...
2.641445
2.529248
1.04436
assert content_type in ["page", "blogpost"] params = {} if depth: assert depth in {"all", "root"} params["depth"] = depth if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if li...
def get_space_content_by_type(self, space_key, content_type, depth=None, expand=None, start=None, limit=None, callback=None)
Returns the content in this given space with the given type. :param space_key (string): A string containing the key of the space. :param content_type (string): The type of content to return with the space. Valid values: "page", "blogpost". :param depth (string): OPTIONAL: A string indicating if ...
2.526103
2.196569
1.150022
assert isinstance(content_data, dict) and set(content_data.keys()) >= self.NEW_CONTENT_REQUIRED_KEYS return self._service_post_request("rest/api/content", data=json.dumps(content_data), headers={"Content-Type": "application/json"}, callback=callback)
def create_new_content(self, content_data, callback=None)
Creates a new piece of Content. :param content_data (dict): A dictionary representing the data for the new content. Must have keys: "type", "title", "space", "body". :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns. ...
3.84081
4.396417
0.873623
if isinstance(attachments, list): assert all(isinstance(at, dict) and "file" in list(at.keys()) for at in attachments) elif isinstance(attachments, dict): assert "file" in list(attachments.keys()) else: assert False return self._service_post_r...
def create_new_attachment_by_content_id(self, content_id, attachments, callback=None)
Add one or more attachments to a Confluence Content entity, with optional comments. Comments are optional, but if included there must be as many comments as there are files, and the comments must be in the same order as the files. :param content_id (string): A string containing the id of the at...
3.077102
2.80368
1.097522
assert isinstance(label_names, list) assert all(isinstance(ln, dict) and set(ln.keys()) == {"prefix", "name"} for ln in label_names) return self._service_post_request("rest/api/content/{id}/label".format(id=content_id), data=json.dumps(label_name...
def create_new_label_by_content_id(self, content_id, label_names, callback=None)
Adds a list of labels to the specified content. :param content_id (string): A string containing the id of the labels content container. :param label_names (list): A list of labels (strings) to apply to the content. :param callback: OPTIONAL: The callback to execute on the resulting data, before ...
3.427457
3.447147
0.994288
assert isinstance(content_property, dict) assert {"key", "value"} <= set(content_property.keys()) return self._service_post_request("rest/api/content/{id}/property".format(id=content_id), data=json.dumps(content_property), ...
def create_new_content_property(self, content_id, content_property, callback=None)
Creates a new content property. Potentially a duplicate at the REST API level of create_new_property. :param content_id (string): A string containing the id of the property content container. :param new_property_data (dict): A dictionary describing the new property for the content. Must have the...
3.517129
3.344503
1.051615
assert isinstance(space_definition, dict) and {"key", "name", "description"} <= set(space_definition.keys()) return self._service_post_request("rest/api/space", data=json.dumps(space_definition), headers={"Content-Type": "application/json"}, callback=ca...
def create_new_space(self, space_definition, callback=None)
Creates a new Space. The incoming Space does not include an id, but must include a Key and Name, and should include a Description. :param space_definition (dict): The dictionary describing the new space. Must include keys "key", "name", and "description". ...
4.301311
3.94673
1.089842
assert isinstance(content_data, dict) and set(content_data.keys()) >= self.UPDATE_CONTENT_REQUIRED_KEYS return self._service_put_request("rest/api/content/{id}".format(id=content_id), data=json.dumps(content_data), headers={"Content-Type": "application/j...
def update_content_by_id(self, content_data, content_id, callback=None)
Updates a piece of Content, or restores if it is trashed. The body contains the representation of the content. Must include the new version number. To restore a piece of content that has the status of trashed the content must have it's version incremented, and status set to current. No other f...
3.551508
3.664605
0.969138
assert isinstance(new_metadata, dict) and set(new_metadata.keys()) >= self.ATTACHMENT_METADATA_KEYS return self._service_put_request("rest/api/content/{id}/child/attachment/{attachment_id}" "".format(id=content_id, attachment_id=attachment_id), ...
def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None)
Update the non-binary data of an Attachment. This resource can be used to update an attachment's filename, media-type, comment, and parent container. :param content_id (string): A string containing the ID of the attachments content container. :param attachment_id (string): The ID of the attachm...
3.3591
3.205857
1.047801
if isinstance(attachment, dict): assert "file" in list(attachment.keys()) else: assert False return self._service_post_request("rest/api/content/{content_id}/child/attachment/{attachment_id}/data" "".format(content_id=con...
def update_attachment(self, content_id, attachment_id, attachment, callback=None)
Update the binary data of an Attachment, and optionally the comment and the minor edit field. This adds a new version of the attachment, containing the new binary data, filename, and content-type. When updating the binary data of an attachment, the comment related to it together with the field that ...
3.649492
3.453359
1.056795
assert isinstance(new_property_data, dict) and {"key", "value", "version"} <= set(new_property_data.keys()) return self._service_put_request("rest/api/content/{id}/property/{key}".format(id=content_id, key=property_key), data=json.dumps(new_property_data...
def update_property(self, content_id, property_key, new_property_data, callback=None)
Updates a content property. The body contains the representation of the content property. Must include the property id, and the new version number. Attempts to create a new content property if the given version number is 1, just like {@link #create(com.atlassian.confluence.api.model.content.id....
3.032332
2.659455
1.140208
assert isinstance(space_definition, dict) and {"key", "name", "description"} <= set(space_definition.keys()) return self._service_put_request("rest/api/space/{key}".format(key=space_key), data=json.dumps(space_definition), ...
def update_space(self, space_key, space_definition, callback=None)
Updates a Space. Currently only the Space name, description and homepage can be updated. :param space_key (string): The key of the space to update. :param space_definition (dict): The dictionary describing the updated space metadata. This should include "...
3.77868
3.483224
1.084822
assert {old_representation, new_representation} < {"storage", "editor", "view", "export_view"} # TODO: Enforce conversion rules better here. request_data = {"value": str(content_data), "representation": old_representation} return self._service_post_request("rest/api/contentbody/...
def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None)
Converts between content body representations. Not all representations can be converted to/from other formats. Supported conversions: Source Representation | Destination Representation Supported -------------------------------------------------------------- "storage" | ...
5.982897
4.145323
1.443289
params = {} if status: params["status"] = status return self._service_delete_request("rest/api/content/{id}".format(id=content_id), params=params, callback=callback)
def delete_content_by_id(self, content_id, status=None, callback=None)
Trashes or purges a piece of Content, based on its {@link ContentType} and {@link ContentStatus}. :param content_id (string): The ID for the content to remove. :param status (string): OPTIONAL: A status code to query for the location (?) of the content. The REST API sugge...
4.070106
4.738563
0.858933
params = {"name": label_name} return self._service_delete_request("rest/api/content/{id}/label".format(id=content_id), params=params, callback=callback)
def delete_label_by_id(self, content_id, label_name, callback=None)
Deletes a labels to the specified content. There is an alternative form of this delete method that is not implemented. A DELETE request to /rest/api/content/{id}/label/{label} will also delete a label, but is more limited in the label name that can be accepted (and has no real apparent upside)....
4.7196
4.788308
0.985651
return self._service_delete_request("rest/api/content/{id}/property/{key}" "".format(id=content_id, key=property_key), callback=callback)
def delete_property(self, content_id, property_key, callback=None)
Deletes a content property. :param content_id (string): The ID for the content that owns the property to be deleted. :param property_key (string): The name of the property to be deleted. :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns. ...
5.462153
6.324877
0.863598
return self._service_delete_request("rest/api/space/{key}".format(key=space_key), callback=callback)
def delete_space(self, space_key, callback=None)
Deletes a Space. The space is deleted in a long running task, so the space cannot be considered deleted when this method returns. Clients can follow the status link in the response and poll it until the task completes. :param space_key (string): The key of the space to delete. :param c...
7.391082
9.452396
0.781927
if isinstance(sensor, (list, tuple)): for sss in sensor: self.add(sss) return if not isinstance(sensor, Sensor): raise TypeError("pysma.Sensor expected") if sensor.name in self: old = self[sensor.name] self.__...
def add(self, sensor)
Add a sensor, warning if it exists.
3.315703
3.19903
1.036471
params = { 'data': json.dumps(payload), 'headers': {'content-type': 'application/json'}, 'params': {'sid': self.sma_sid} if self.sma_sid else None, } for _ in range(3): try: with async_timeout.timeout(3): ...
def _fetch_json(self, url, payload)
Fetch json data for requests.
3.434712
3.301868
1.040233
body = yield from self._fetch_json(URL_LOGIN, self._new_session_data) self.sma_sid = jmespath.search('result.sid', body) if self.sma_sid: return True msg = 'Could not start session, %s, got {}'.format(body) if body.get('err'): if body.get('err')...
def new_session(self)
Establish a new session.
5.592366
5.385447
1.038422
payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))} if self.sma_sid is None: yield from self.new_session() if self.sma_sid is None: return False body = yield from self._fetch_json(URL_VALUES, payload=payload) # On the f...
def read(self, sensors)
Read a set of keys.
6.370256
6.013276
1.059365
loop = GLib.MainLoop() context = loop.get_context() while True: time.sleep(0.1) if context.pending(): context.iteration() self._manager[ATTR_POSITION] = self._position() try: method, args = self._task_qu...
def run(self)
Run the process. Iterate the GLib main loop and process the task queue.
4.123796
3.760417
1.096633
try: local_path, _ = urllib.request.urlretrieve(uri) metadata = mutagen.File(local_path, easy=True) if metadata.tags: self._tags = metadata.tags title = self._tags.get(TAG_TITLE, []) self._manager[ATTR_TITLE] = title[0] if len(...
def media(self, uri)
Play a media file.
2.37094
2.340418
1.013041
if self.state == STATE_PAUSED: self._player.set_state(Gst.State.PLAYING) self.state = STATE_PLAYING
def play(self)
Change state to playing.
3.493652
2.705338
1.291392
if self.state == STATE_PLAYING: self._player.set_state(Gst.State.PAUSED) self.state = STATE_PAUSED
def pause(self)
Change state to paused.
3.019351
2.547473
1.185234
urllib.request.urlcleanup() self._player.set_state(Gst.State.NULL) self.state = STATE_IDLE self._tags = {}
def stop(self)
Stop pipeline.
8.115884
7.918328
1.024949
if position > self._duration(): return position_ns = position * _NANOSEC_MULT self._manager[ATTR_POSITION] = position self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns)
def set_position(self, position)
Set media position.
11.175039
8.700435
1.284423
self._player.set_property(PROP_VOLUME, volume) self._manager[ATTR_VOLUME] = volume _LOGGER.info('volume set to %.2f', volume)
def set_volume(self, volume)
Set volume.
6.889761
6.539813
1.053511
self._state = state self._manager[ATTR_STATE] = state _LOGGER.info('state changed to %s', state)
def state(self, state)
Set state.
5.693104
5.400805
1.054122
duration = 0 if self.state != STATE_IDLE: resp = self._player.query_duration(_FORMAT_TIME) duration = resp[1] // _NANOSEC_MULT return duration
def _duration(self)
Get media duration.
11.398504
8.93962
1.275055
position = 0 if self.state != STATE_IDLE: resp = self._player.query_position(_FORMAT_TIME) position = resp[1] // _NANOSEC_MULT return position
def _position(self)
Get media position.
11.75124
8.480994
1.385597
self.stop() elif message.type == Gst.MessageType.ERROR: self.stop() err, _ = message.parse_error() _LOGGER.error('%s', err)
def _on_message(self, bus, message): # pylint: disable=unused-argument if message.type == Gst.MessageType.EOS
When a message is received from Gstreamer.
3.759696
3.183815
1.180878
if node.prev_sibling: return node.prev_sibling if node.parent: return get_previous_node(node.parent)
def get_previous_node(node)
Return the node before this node.
2.39384
2.143617
1.116729
kwargs = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'universal_newlines': True } phantom_js_cmd = app_settings['PHANTOMJS_CMD'] if phantom_js_cmd: path = '{0}:{1}'.format( os.getenv('PATH', ''), os.path.dirname(phantom_js_cmd) ) ...
def casperjs_command_kwargs()
will construct kwargs for cmd
2.837064
2.795615
1.014826
method = app_settings['CAPTURE_METHOD'] cmd = app_settings['%s_CMD' % method.upper()] sys_path = os.getenv('PATH', '').split(':') if cmd is None: for binpath in sys_path: cmd = os.path.join(binpath, method) if os.path.exists(cmd): break cmd = [cmd...
def casperjs_command()
Determine which capture engine is specified. Possible options: - casperjs - phantomjs Based on this value, locate the binary of the capture engine. If setting <engine>_CMD is not defined, then look up for ``<engine>`` in shell PATH and build the whole capture command.
3.290105
3.152811
1.043546
if isinstance(stream, six.string_types): output = stream else: with NamedTemporaryFile('wb+', suffix='.%s' % render, delete=False) as f: output = f.name try: cmd = CASPERJS_CMD + [url, output] # Extra command-line options cmd += ['--format=%s' % rend...
def casperjs_capture(stream, url, method=None, width=None, height=None, selector=None, data=None, waitfor=None, size=None, crop=None, render='png', wait=None)
Captures web pages using ``casperjs``
2.652369
2.704067
0.980881
for line in stdout.splitlines(): bits = line.split(':', 1) if len(bits) < 2: bits = ('INFO', bits) level, msg = bits if level == 'FATAL': logger.fatal(msg) raise CaptureError(msg) elif level == 'ERROR': logger.error(msg) ...
def process_casperjs_stdout(stdout)
Parse and digest capture script output.
2.86385
2.783842
1.02874
try: validate = URLValidator() validate(url) except ValidationError: if url.startswith('/'): host = request.get_host() scheme = 'https' if request.is_secure() else 'http' url = '{scheme}://{host}{uri}'.format(scheme=scheme, ...
def parse_url(request, url)
Parse url URL parameter.
2.336911
2.339633
0.998836
formats = { 'jpeg': guess_all_extensions('image/jpeg'), 'png': guess_all_extensions('image/png'), 'gif': guess_all_extensions('image/gif'), 'bmp': guess_all_extensions('image/x-ms-bmp'), 'tiff': guess_all_extensions('image/tiff'), 'xbm': guess_all_extensions('ima...
def parse_render(render)
Parse render URL parameter. >>> parse_render(None) 'png' >>> parse_render('html') 'png' >>> parse_render('png') 'png' >>> parse_render('jpg') 'jpeg' >>> parse_render('gif') 'gif'
2.079441
2.051885
1.013429
try: width_str, height_str = size_raw.lower().split('x') except AttributeError: size = None except ValueError: size = None else: try: width = int(width_str) assert width > 0 except (ValueError, AssertionError): width = None...
def parse_size(size_raw)
Parse size URL parameter. >>> parse_size((100,None)) None >>> parse_size('300x100') (300, 100) >>> parse_size('300x') None >>> parse_size('x100') None >>> parse_size('x') None
2.075894
2.193152
0.946534
try: from PIL import Image except ImportError: import Image img = Image.open(imagefile) size_crop = None img_resized = img if size and crop and crop.lower() == 'true': width_raw, height_raw = img.size width, height = size height_better = int(height_r...
def image_postprocess(imagefile, output, size, crop, render)
Resize and crop captured image, and saves to output. (can be stream or filename)
3.612924
3.585267
1.007714
if app_settings.get('CAPTURE_ROOT_URL'): return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url) return request.build_absolute_uri(url)
def build_absolute_uri(request, url)
Allow to override printing url, not necessarily on the same server instance.
3.899869
3.504387
1.112853
# output stream, as required by casperjs_capture stream = BytesIO() out_f = None # the suffix=.html is a hack for phantomjs which *will* # complain about not being able to open source file # unless it has a 'html' extension. with NamedTemporaryFile(suffix='.html') as render_file: ...
def render_template(template_name, context, format='png', output=None, using=None, **options)
Render a template from django project, and return the file object of the result.
4.358906
4.396521
0.991444
if not callable(fn): raise TypeError('go() requires a function, not %r' % (fn,)) result = [None] error = [] def target(): try: result[0] = fn(*args, **kwargs) except Exception: # Are we in interpreter shutdown? if sys: err...
def go(fn, *args, **kwargs)
Launch an operation on a thread and get a handle to its future result. >>> from time import sleep >>> def print_sleep_print(duration): ... sleep(duration) ... print('hello from background thread') ... sleep(duration) ... print('goodbye from background thread') ... return...
2.726588
3.113205
0.875814
future = go(fn, *args, **kwargs) try: yield future except: # We are raising an exception, just try to clean up the future. exc_info = sys.exc_info() try: # Shorter than normal timeout. future(timeout=1) except: log_message = ('...
def going(fn, *args, **kwargs)
Launch a thread and wait for its result before exiting the code block. >>> with going(lambda: 'return value') as future: ... pass >>> future() # Won't block, the future is ready by now. 'return value' Or discard the result: >>> with going(lambda: "don't care"): ... pass If an...
5.104529
5.431289
0.939838
start = time.time() while True: retval = predicate() if retval: return retval if time.time() - start > timeout: raise AssertionError("Didn't ever %s" % success_description) time.sleep(0.1)
def wait_until(predicate, success_description, timeout=10)
Wait up to 10 seconds (by default) for predicate to be true. E.g.: wait_until(lambda: client.primary == ('a', 1), 'connect to the primary') If the lambda-expression isn't true after 10 seconds, we raise AssertionError("Didn't ever connect to the primary"). Returns the pred...
2.911263
2.534213
1.148784
end = data.index(b"\x00", position) return _utf_8_decode(data[position:end], None, True)[0], end + 1
def _get_c_string(data, position)
Decode a BSON 'C' string to python unicode string.
4.752753
4.40439
1.079095
@functools.wraps(meth) def wrapper(self, *args, **kwargs): with self._lock: return meth(self, *args, **kwargs) return wrapper
def _synchronized(meth)
Call method while holding a lock.
1.929856
1.819408
1.060705
host, port = address for res in set(socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)): family, socktype, proto, _, sock_addr = res sock = socket.socket(family, socktype, prot...
def bind_tcp_socket(address)
Takes (host, port) and returns (socket_object, (host, port)). If the passed-in port is None, bind an unused port and return it.
2.509889
2.460741
1.019973
path, _ = address try: os.unlink(path) except OSError: pass sock = socket.socket(socket.AF_UNIX) sock.bind(path) sock.listen(128) return sock, (path, 0)
def bind_domain_socket(address)
Takes (socket path, 0) and returns (socket_object, (path, 0)).
2.76564
2.170337
1.27429
header = mock_server_receive(client, 16) length = _UNPACK_INT(header[:4])[0] request_id = _UNPACK_INT(header[4:8])[0] opcode = _UNPACK_INT(header[12:])[0] msg_bytes = mock_server_receive(client, length - 16) if opcode not in OPCODES: raise NotImplementedError("Don't know how to unpa...
def mock_server_receive_request(client, server)
Take a client socket and return a Request.
3.259861
3.088865
1.055359
msg = b'' while length: chunk = sock.recv(length) if chunk == b'': raise socket.error(errno.ECONNRESET, 'closed') length -= len(chunk) msg += chunk return msg
def mock_server_receive(sock, length)
Receive `length` bytes from a socket object.
2.868925
2.673882
1.072944
err_msg = "Can't interpret args: " if not args and not kwargs: return [] if not args: # OpReply(ok=1, ismaster=True). return [kwargs] if isinstance(args[0], (int, float, bool)): # server.receives().ok(0, err='uh oh'). if args[1:]: raise_args_err...
def make_docs(*args, **kwargs)
Make the documents for a `Request` or `Reply`. Takes a variety of argument styles, returns a list of dicts. Used by `make_prototype_request` and `make_reply`, which are in turn used by `MockupDB.receives`, `Request.replies`, and so on. See examples in tutorial.
3.745405
3.675189
1.019106
if args and isinstance(args[0], Matcher): if args[1:] or kwargs: raise_args_err("can't interpret args") return args[0] return Matcher(*args, **kwargs)
def make_matcher(*args, **kwargs)
Make a Matcher from a :ref:`message spec <message spec>`: >>> make_matcher() Matcher(Request()) >>> make_matcher({'ismaster': 1}, namespace='admin') Matcher(Request({"ismaster": 1}, namespace="admin")) >>> make_matcher({}, {'_id': 1}) Matcher(Request({}, {"_id": 1})) See more examples in t...
5.468943
6.860385
0.797177
if args and inspect.isclass(args[0]) and issubclass(args[0], Request): request_cls, arg_list = args[0], args[1:] return request_cls(*arg_list, **kwargs) if args and isinstance(args[0], Request): if args[1:] or kwargs: raise_args_err("can't interpret args") return...
def make_prototype_request(*args, **kwargs)
Make a prototype Request for a Matcher.
4.273212
3.940726
1.084372
sio = StringIO() for doc_idx, doc in enumerate(args): if doc_idx > 0: sio.write(u', ') sio.write(text_type(json_util.dumps(doc))) return sio.getvalue()
def docs_repr(*args)
Stringify ordered dicts like a regular ones. Preserve order, remove 'u'-prefix on unicodes in Python 2: >>> print(docs_repr(OrderedDict([(u'_id', 2)]))) {"_id": 2} >>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]), ... OrderedDict([(u'a', 1)]))) {"_id": 2, "a": "b"},...
3.31453
4.375342
0.757548
len_seq1 = len(seq1) if len_seq1 < len(seq0): return False seq1_idx = 0 for i, elem in enumerate(seq0): while seq1_idx < len_seq1: if seq1[seq1_idx] == elem: break seq1_idx += 1 if seq1_idx >= len_seq1 or seq1[seq1_idx] != elem: ...
def seq_match(seq0, seq1)
True if seq0 is a subset of seq1 and their elements are in same order. >>> seq_match([], []) True >>> seq_match([1], [1]) True >>> seq_match([1, 1], [1]) False >>> seq_match([1], [1, 2]) True >>> seq_match([1, 1], [1, 1]) True >>> seq_match([3], [1, 2, 3]) True >>> s...
1.91071
2.079293
0.918922
frame = inspect.currentframe().f_back raise error_class(message + ': ' + format_call(frame))
def raise_args_err(message='bad arguments', error_class=TypeError)
Throw an error with standard message, displaying function call. >>> def f(a, *args, **kwargs): ... raise_args_err() ... >>> f(1, 2, x='y') Traceback (most recent call last): ... TypeError: bad arguments: f(1, 2, x='y')
4.523288
8.408174
0.537963
if uds_path is not None: port = None server = MockupDB(port=port, verbose=verbose, request_timeout=int(1e6), ssl=ssl, auto_ismaster=True, uds_path=uds_path) if all_ok: server.a...
def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB', ssl=False, uds_path=None)
A `MockupDB` that the mongo shell can connect to. Call `~.MockupDB.run` on the returned server, and clean it up with `~.MockupDB.stop`. If ``all_ok`` is True, replies {ok: 1} to anything unmatched by a specific responder.
5.178004
5.770564
0.897313
address = self._client.getpeername() if isinstance(address, tuple): return address[1] # Maybe a Unix domain socket connection. return 0
def client_port(self)
Client connection's TCP port.
7.261181
5.759287
1.260778
matcher = make_matcher(*args, **kwargs) if not matcher.matches(self): raise AssertionError('%r does not match %r' % (self, matcher)) return self
def assert_matches(self, *args, **kwargs)
Assert this matches a :ref:`message spec <message spec>`. Returns self.
3.165516
3.348522
0.945347
kwargs.setdefault('flags', 0) kwargs['flags'] |= REPLY_FLAGS['QueryFailure'] kwargs['$err'] = err self.replies(*args, **kwargs) return True
def fail(self, err='MockupDB query failure', *args, **kwargs)
Reply to a query with the QueryFailure flag and an '$err' key. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
9.033048
4.006847
2.254403
kwargs.setdefault('ok', 0) kwargs['code'] = code kwargs['errmsg'] = errmsg self.replies(*args, **kwargs) return True
def command_err(self, code=1, errmsg='MockupDB command failure', *args, **kwargs)
Error reply to a command. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
5.061357
4.787412
1.057222
if self._server: self._server._log('\t%d\thangup' % self.client_port) self._client.shutdown(socket.SHUT_RDWR) return True
def hangup(self)
Close the connection. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
8.076627
7.633479
1.058053
for doc, other_doc in zip(docs, other_docs): if not self._match_map(doc, other_doc): return False return True
def _matches_docs(self, docs, other_docs)
Overridable method.
3.392057
3.112878
1.089685
reply_msg = make_reply(*args, **kwargs) if self._server: self._server._log('\t%d\t<-- %r' % (self.client_port, reply_msg)) reply_bytes = reply_msg.reply_bytes(self) self._client.sendall(reply_bytes)
def _replies(self, *args, **kwargs)
Overridable method.
4.978093
4.826223
1.031468
payload_document = OrderedDict() flags, = _UNPACK_UINT(msg[:4]) pos = 4 if flags != 0 and flags != 2: raise ValueError('OP_MSG flag must be 0 or 2 not %r' % (flags,)) while pos < len(msg): payload_type, = _UNPACK_BYTE(msg[pos:pos + 1]) ...
def unpack(cls, msg, client, server, request_id)
Parse message and return an `OpMsg`. Takes the client message as bytes, the client and server socket objects, and the client request id.
3.377364
3.311139
1.020001
flags, = _UNPACK_INT(msg[:4]) namespace, pos = _get_c_string(msg, 4) is_command = namespace.endswith('.$cmd') num_to_skip, = _UNPACK_INT(msg[pos:pos + 4]) pos += 4 num_to_return, = _UNPACK_INT(msg[pos:pos + 4]) pos += 4 docs = bson.decode_all(msg[...
def unpack(cls, msg, client, server, request_id)
Parse message and return an `OpQuery` or `Command`. Takes the client message as bytes, the client and server socket objects, and the client request id.
2.85304
2.617948
1.0898
flags, = _UNPACK_INT(msg[:4]) namespace, pos = _get_c_string(msg, 4) num_to_return, = _UNPACK_INT(msg[pos:pos + 4]) pos += 4 cursor_id, = _UNPACK_LONG(msg[pos:pos + 8]) return OpGetMore(namespace=namespace, flags=flags, _client=client, nu...
def unpack(cls, msg, client, server, request_id)
Parse message and return an `OpGetMore`. Takes the client message as bytes, the client and server socket objects, and the client request id.
3.322289
2.638437
1.259189
# Leading 4 bytes are reserved. num_of_cursor_ids, = _UNPACK_INT(msg[4:8]) cursor_ids = [] pos = 8 for _ in range(num_of_cursor_ids): cursor_ids.append(_UNPACK_INT(msg[pos:pos + 4])[0]) pos += 4 return OpKillCursors(_client=client, cursor_...
def unpack(cls, msg, client, server, _)
Parse message and return an `OpKillCursors`. Takes the client message as bytes, the client and server socket objects, and the client request id.
3.804008
2.986022
1.273938
flags, = _UNPACK_INT(msg[:4]) namespace, pos = _get_c_string(msg, 4) docs = bson.decode_all(msg[pos:], CODEC_OPTIONS) return cls(*docs, namespace=namespace, flags=flags, _client=client, request_id=request_id, _server=server)
def unpack(cls, msg, client, server, request_id)
Parse message and return an `OpInsert`. Takes the client message as bytes, the client and server socket objects, and the client request id.
5.57021
5.386612
1.034084
flags = struct.pack("<i", self._flags) cursor_id = struct.pack("<q", self._cursor_id) starting_from = struct.pack("<i", self._starting_from) number_returned = struct.pack("<i", len(self._docs)) reply_id = random.randint(0, 1000000) response_to = request.request_i...
def reply_bytes(self, request)
Take a `Request` and return an OP_REPLY message as bytes.
2.58242
2.433873
1.061033
flags = struct.pack("<I", self._flags) payload_type = struct.pack("<b", 0) payload_data = bson.BSON.encode(self.doc) data = b''.join([flags, payload_type, payload_data]) reply_id = random.randint(0, 1000000) response_to = request.request_id header = str...
def reply_bytes(self, request)
Take a `Request` and return an OP_MSG message as bytes.
3.745632
3.442062
1.088194
request = make_prototype_request(*args, **kwargs) if self._prototype.opcode not in (None, request.opcode): return False if self._prototype.is_command not in (None, request.is_command): return False for name in dir(self._prototype): if name.sta...
def matches(self, *args, **kwargs)
Test if a request matches a :ref:`message spec <message spec>`. Returns ``True`` or ``False``.
4.042343
4.076041
0.991733
self._listening_sock, self._address = ( bind_domain_socket(self._address) if self._uds_path else bind_tcp_socket(self._address)) if self._ssl: certfile = os.path.join(os.path.dirname(__file__), 'server.pem') self._listening_sock = _ss...
def run(self)
Begin serving. Returns the bound port, or 0 for domain socket.
2.828169
2.417098
1.170068
self._stopped = True threads = [self._accept_thread] threads.extend(self._server_threads) self._listening_sock.close() for sock in list(self._server_socks): try: sock.shutdown(socket.SHUT_RDWR) except socket.error: ...
def stop(self)
Stop serving. Always call this to clean up after yourself.
2.823793
2.611894
1.081129
timeout = kwargs.pop('timeout', self._request_timeout) end = time.time() + timeout matcher = Matcher(*args, **kwargs) while not self._stopped: try: # Short timeout so we notice if the server is stopped. request = self._request_q.get(ti...
def receives(self, *args, **kwargs)
Pop the next `Request` and assert it matches. Returns None if the server is stopped. Pass a `Request` or request pattern to specify what client request to expect. See the tutorial for examples. Pass ``timeout`` as a keyword argument to override this server's ``request_timeout``.
3.57702
2.980062
1.200317
timeout = kwargs.pop('timeout', self._request_timeout) end = time.time() + timeout matcher = make_matcher(*args, **kwargs) while not self._stopped: try: # Short timeout so we notice if the server is stopped. request = self._request_q....
def got(self, *args, **kwargs)
Does `.request` match the given :ref:`message spec <message spec>`? >>> s = MockupDB(auto_ismaster=True) >>> port = s.run() >>> s.got(timeout=0) # No request enqueued. False >>> from pymongo import MongoClient >>> client = MongoClient(s.uri) >>> future = go(clie...
4.909713
5.67078
0.865791
return self._insert_responder("top", matcher, *args, **kwargs)
def autoresponds(self, matcher, *args, **kwargs)
Send a canned reply to all matching client requests. ``matcher`` is a `Matcher` or a command name, or an instance of `OpInsert`, `OpQuery`, etc. >>> s = MockupDB() >>> port = s.run() >>> >>> from pymongo import MongoClient >>> client = MongoClient(s.uri)...
13.843985
55.212688
0.250739
return self._insert_responder("bottom", matcher, *args, **kwargs)
def append_responder(self, matcher, *args, **kwargs)
Add a responder of last resort. Like `.autoresponds`, but instead of adding a responder to the top of the stack, add it to the bottom. This responder will be called if no others match.
8.118224
8.546387
0.949901
if self._uds_path: uri = 'mongodb://%s' % (quote_plus(self._uds_path),) else: uri = 'mongodb://%s' % (format_addr(self._address),) return uri + '/?ssl=true' if self._ssl else uri
def uri(self)
Connection string to pass to `~pymongo.mongo_client.MongoClient`.
3.999812
3.631443
1.101439
self._listening_sock.setblocking(0) while not self._stopped and not _shutting_down: try: # Wait a short time to accept. if select.select([self._listening_sock.fileno()], [], [], 1): client, client_addr = self._listening_sock.accept...
def _accept_loop(self)
Accept client connections and spawn a thread for each.
2.785885
2.687992
1.036418
while not self._stopped and not _shutting_down: try: with self._unlock(): request = mock_server_receive_request(client, self) self._requests_count += 1 self._log('%d\t%r' % (request.client_port, request)) ...
def _server_loop(self, client, client_addr)
Read requests from one client socket, 'client'.
4.704101
4.59137
1.024553
try: if SUPPORTS_VERIFY: kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), getattr(settings, "KRB5_REALM", ""), getattr(settings, "KRB5_VERIFY_KDC", True)) else: kerberos.checkPassword(username.lower(), pass...
def check_password(self, username, password)
The actual password checking logic. Separated from the authenticate code from Django for easier updating
3.189688
3.119862
1.022381
from optparse import OptionParser parser = OptionParser('Start mock MongoDB server') parser.add_option('-p', '--port', dest='port', default=27017, help='port on which mock mongod listens') parser.add_option('-q', '--quiet', action='store_false', dest='ver...
def main()
Start an interactive `MockupDB`. Use like ``python -m mockupdb``.
2.710088
2.665233
1.01683
grid = np.exp(-self.distance_grid / (neighborhood ** 2)) return grid.reshape(self.num_neurons, self.num_neurons)[:, :, None]
def _calculate_influence(self, neighborhood)
Pre-calculate the influence for a given value of sigma. The neighborhood has size num_neurons * num_neurons, so for a 30 * 30 map, the neighborhood will be size (900, 900). Parameters ---------- neighborhood : float The neighborhood value. Returns -...
6.459095
6.397538
1.009622
p = [self._grid_distance(i) for i in range(self.num_neurons)] return np.array(p)
def _initialize_distance_grid(self)
Initialize the distance grid by calls to _grid_dist.
6.268858
5.274443
1.188535
# Take every dimension but the first in reverse # then reverse that list again. dimensions = np.cumprod(self.map_dimensions[1::][::-1])[::-1] coord = [] for idx, dim in enumerate(dimensions): if idx != 0: value = (index % dimensions[idx-1]) /...
def _grid_distance(self, index)
Calculate the distance grid for a single index position. This is pre-calculated for fast neighborhood calculations later on (see _calc_influence).
4.090569
4.045826
1.011059