nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
ghostop14/sparrow-wifi
4b8289773ea4304872062f65a6ffc9352612b08e
sparrowdialogs.py
python
BluetoothDialog.showNTContextMenu
(self, pos)
[]
def showNTContextMenu(self, pos): curRow = self.bluetoothTable.currentRow() if curRow == -1: return self.ntRightClickMenu.exec_(self.bluetoothTable.mapToGlobal(pos))
[ "def", "showNTContextMenu", "(", "self", ",", "pos", ")", ":", "curRow", "=", "self", ".", "bluetoothTable", ".", "currentRow", "(", ")", "if", "curRow", "==", "-", "1", ":", "return", "self", ".", "ntRightClickMenu", ".", "exec_", "(", "self", ".", "b...
https://github.com/ghostop14/sparrow-wifi/blob/4b8289773ea4304872062f65a6ffc9352612b08e/sparrowdialogs.py#L1415-L1421
hanskrupakar/COCO-Style-Dataset-Generator-GUI
35c095a815a6ef97d2e820d175bf46e32e59f40b
coco_dataset_generator/gui/poly_editor.py
python
PolygonInteractor.get_ind_under_point
(self, event)
return ind
get the index of the vertex under point if within epsilon tolerance
get the index of the vertex under point if within epsilon tolerance
[ "get", "the", "index", "of", "the", "vertex", "under", "point", "if", "within", "epsilon", "tolerance" ]
def get_ind_under_point(self, event): 'get the index of the vertex under point if within epsilon tolerance' # display coords xy = np.asarray(self.poly.xy) xyt = self.poly.get_transform().transform(xy) xt, yt = xyt[:, 0], xyt[:, 1] d = np.hypot(xt - event.x, yt - event.y) indseq, = np.nonzero(d == d.min()) ind = indseq[0] if d[ind] >= self.epsilon: ind = None return ind
[ "def", "get_ind_under_point", "(", "self", ",", "event", ")", ":", "# display coords", "xy", "=", "np", ".", "asarray", "(", "self", ".", "poly", ".", "xy", ")", "xyt", "=", "self", ".", "poly", ".", "get_transform", "(", ")", ".", "transform", "(", ...
https://github.com/hanskrupakar/COCO-Style-Dataset-Generator-GUI/blob/35c095a815a6ef97d2e820d175bf46e32e59f40b/coco_dataset_generator/gui/poly_editor.py#L91-L105
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/util/data.py
python
Data.copy_template_set_ctx
(self, ctx)
return Data(**kwargs)
:param ControlFlowContext ctx: :return: new Data instance :rtype: Data
:param ControlFlowContext ctx: :return: new Data instance :rtype: Data
[ ":", "param", "ControlFlowContext", "ctx", ":", ":", "return", ":", "new", "Data", "instance", ":", "rtype", ":", "Data" ]
def copy_template_set_ctx(self, ctx): """ :param ControlFlowContext ctx: :return: new Data instance :rtype: Data """ kwargs = self.get_kwargs() kwargs["control_flow_ctx"] = ctx return Data(**kwargs)
[ "def", "copy_template_set_ctx", "(", "self", ",", "ctx", ")", ":", "kwargs", "=", "self", ".", "get_kwargs", "(", ")", "kwargs", "[", "\"control_flow_ctx\"", "]", "=", "ctx", "return", "Data", "(", "*", "*", "kwargs", ")" ]
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/util/data.py#L3820-L3828
travisgoodspeed/goodfet
1750cc1e8588af5470385e52fa098ca7364c2863
contrib/hoder/GoodFETMCPCAN_ted.py
python
GoodFETMCPCAN.poke8
(self,adr,val)
return val
Poke a value into RAM. Untested
Poke a value into RAM. Untested
[ "Poke", "a", "value", "into", "RAM", ".", "Untested" ]
def poke8(self,adr,val): """Poke a value into RAM. Untested""" self.SPItrans([0x02,adr&0xFF,val&0xFF]); newval=self.peek8(adr); if newval!=val: print "Failed to poke %02x to %02x. Got %02x." % (adr,val,newval); print "Are you not in idle mode?"; return val;
[ "def", "poke8", "(", "self", ",", "adr", ",", "val", ")", ":", "self", ".", "SPItrans", "(", "[", "0x02", ",", "adr", "&", "0xFF", ",", "val", "&", "0xFF", "]", ")", "newval", "=", "self", ".", "peek8", "(", "adr", ")", "if", "newval", "!=", ...
https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/contrib/hoder/GoodFETMCPCAN_ted.py#L282-L289
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/flowchart/Flowchart.py
python
Flowchart.saveState
(self)
return state
Return a serializable data structure representing the current state of this flowchart.
Return a serializable data structure representing the current state of this flowchart.
[ "Return", "a", "serializable", "data", "structure", "representing", "the", "current", "state", "of", "this", "flowchart", "." ]
def saveState(self): """Return a serializable data structure representing the current state of this flowchart. """ state = Node.saveState(self) state['nodes'] = [] state['connects'] = [] for name, node in self._nodes.items(): cls = type(node) if hasattr(cls, 'nodeName'): clsName = cls.nodeName pos = node.graphicsItem().pos() ns = {'class': clsName, 'name': name, 'pos': (pos.x(), pos.y()), 'state': node.saveState()} state['nodes'].append(ns) conn = self.listConnections() for a, b in conn: state['connects'].append((a.node().name(), a.name(), b.node().name(), b.name())) state['inputNode'] = self.inputNode.saveState() state['outputNode'] = self.outputNode.saveState() return state
[ "def", "saveState", "(", "self", ")", ":", "state", "=", "Node", ".", "saveState", "(", "self", ")", "state", "[", "'nodes'", "]", "=", "[", "]", "state", "[", "'connects'", "]", "=", "[", "]", "for", "name", ",", "node", "in", "self", ".", "_nod...
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/flowchart/Flowchart.py#L447-L469
aliyun/aliyun-oss-python-sdk
5f2afa0928a58c7c1cc6317ac147f3637481f6fd
oss2/models.py
python
InventoryConfiguration.__init__
(self, inventory_id=None, is_enabled=None, included_object_versions=None, inventory_filter=None, inventory_destination=None, inventory_schedule=None, optional_fields=None)
[]
def __init__(self, inventory_id=None, is_enabled=None, included_object_versions=None, inventory_filter=None, inventory_destination=None, inventory_schedule=None, optional_fields=None): self.inventory_id = inventory_id self.is_enabled = is_enabled self.included_object_versions = included_object_versions self.inventory_filter = inventory_filter self.inventory_destination = inventory_destination self.inventory_schedule = inventory_schedule self.optional_fields = optional_fields or []
[ "def", "__init__", "(", "self", ",", "inventory_id", "=", "None", ",", "is_enabled", "=", "None", ",", "included_object_versions", "=", "None", ",", "inventory_filter", "=", "None", ",", "inventory_destination", "=", "None", ",", "inventory_schedule", "=", "None...
https://github.com/aliyun/aliyun-oss-python-sdk/blob/5f2afa0928a58c7c1cc6317ac147f3637481f6fd/oss2/models.py#L1835-L1850
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
AdminAlertGeneralStateEnum.is_dismissed
(self)
return self._tag == 'dismissed'
Check if the union tag is ``dismissed``. :rtype: bool
Check if the union tag is ``dismissed``.
[ "Check", "if", "the", "union", "tag", "is", "dismissed", "." ]
def is_dismissed(self): """ Check if the union tag is ``dismissed``. :rtype: bool """ return self._tag == 'dismissed'
[ "def", "is_dismissed", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'dismissed'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L1200-L1206
regel/loudml
0008baef02259a8ae81dd210d3f91a51ffc9ed9f
loudml/mongo.py
python
MongoBucket.insert_times_data
( self, ts, data, tags=None, *args, **kwargs )
Insert data
Insert data
[ "Insert", "data" ]
def insert_times_data( self, ts, data, tags=None, *args, **kwargs ): """ Insert data """ ts = make_ts(ts) data = data.copy() data[self.timestamp_field] = ts self.insert_data(data, tags=tags)
[ "def", "insert_times_data", "(", "self", ",", "ts", ",", "data", ",", "tags", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ts", "=", "make_ts", "(", "ts", ")", "data", "=", "data", ".", "copy", "(", ")", "data", "[", "self...
https://github.com/regel/loudml/blob/0008baef02259a8ae81dd210d3f91a51ffc9ed9f/loudml/mongo.py#L180-L196
QCoDeS/Qcodes
3cda2cef44812e2aa4672781f2423bf5f816f9f9
qcodes/dataset/linked_datasets/links.py
python
links_to_str
(links: List[Link])
return output
Convert a list of links to string. Note that this is the output that gets stored in the DB file
Convert a list of links to string. Note that this is the output that gets stored in the DB file
[ "Convert", "a", "list", "of", "links", "to", "string", ".", "Note", "that", "this", "is", "the", "output", "that", "gets", "stored", "in", "the", "DB", "file" ]
def links_to_str(links: List[Link]) -> str: """ Convert a list of links to string. Note that this is the output that gets stored in the DB file """ output = json.dumps([link_to_str(link) for link in links]) return output
[ "def", "links_to_str", "(", "links", ":", "List", "[", "Link", "]", ")", "->", "str", ":", "output", "=", "json", ".", "dumps", "(", "[", "link_to_str", "(", "link", ")", "for", "link", "in", "links", "]", ")", "return", "output" ]
https://github.com/QCoDeS/Qcodes/blob/3cda2cef44812e2aa4672781f2423bf5f816f9f9/qcodes/dataset/linked_datasets/links.py#L65-L71
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
func_t.is_far
(self, *args)
return _idaapi.func_t_is_far(self, *args)
is_far(self) -> bool
is_far(self) -> bool
[ "is_far", "(", "self", ")", "-", ">", "bool" ]
def is_far(self, *args): """ is_far(self) -> bool """ return _idaapi.func_t_is_far(self, *args)
[ "def", "is_far", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "func_t_is_far", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L27421-L27425
chaoss/grimoirelab-perceval
ba19bfd5e40bffdd422ca8e68526326b47f97491
perceval/backends/core/gitter.py
python
Gitter.fetch_items
(self, category, **kwargs)
Fetch the messages. :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
Fetch the messages.
[ "Fetch", "the", "messages", "." ]
def fetch_items(self, category, **kwargs): """Fetch the messages. :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.debug("Get Gitter message paginated items of room: %s from date: %s", self.room, from_date) from_date = str_to_datetime(from_date).timestamp() fetching = True before_id = None num_msgs = 0 page = 0 room = urijoin(self.group, self.room) self.room_id = self.client.get_room_id(room) if not self.room_id: msg = "Room id not found for room %s" % room logger.error(msg) raise BackendError(cause=msg) logger.debug("Room id of room: %s is %s", self.room, self.room_id) while fetching: page += 1 logger.debug("Page: %i" % page) message_group = self.client.message_page(self.room_id, before_id) message_group = message_group.json() if not message_group: fetching = False continue for raw_message in message_group: if str_to_datetime(raw_message['sent']).timestamp() > from_date: num_msgs += 1 yield raw_message else: fetching = False before_id = message_group[0]['id'] logger.debug("Fetch process completed: %s messages fetched", num_msgs)
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "logger", ".", "debug", "(", "\"Get Gitter message paginated items of room: %s from date: %s\"", ",", "self", ".", "room", ...
https://github.com/chaoss/grimoirelab-perceval/blob/ba19bfd5e40bffdd422ca8e68526326b47f97491/perceval/backends/core/gitter.py#L127-L177
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/vision/beta/serving/detection.py
python
DetectionModule.serve
(self, images: tf.Tensor)
return final_outputs
Cast image to float and run inference. Args: images: uint8 Tensor of shape [batch_size, None, None, 3] Returns: Tensor holding detection output logits.
Cast image to float and run inference.
[ "Cast", "image", "to", "float", "and", "run", "inference", "." ]
def serve(self, images: tf.Tensor): """Cast image to float and run inference. Args: images: uint8 Tensor of shape [batch_size, None, None, 3] Returns: Tensor holding detection output logits. """ # Skip image preprocessing when input_type is tflite so it is compatible # with TFLite quantization. if self._input_type != 'tflite': images, anchor_boxes, image_info = self.preprocess(images) else: with tf.device('cpu:0'): anchor_boxes = self._build_anchor_boxes() # image_info is a 3D tensor of shape [batch_size, 4, 2]. It is in the # format of [[original_height, original_width], # [desired_height, desired_width], [y_scale, x_scale], # [y_offset, x_offset]]. When input_type is tflite, input image is # supposed to be preprocessed already. image_info = tf.convert_to_tensor([[ self._input_image_size, self._input_image_size, [1.0, 1.0], [0, 0] ]], dtype=tf.float32) input_image_shape = image_info[:, 1, :] # To overcome keras.Model extra limitation to save a model with layers that # have multiple inputs, we use `model.call` here to trigger the forward # path. Note that, this disables some keras magics happens in `__call__`. detections = self.model.call( images=images, image_shape=input_image_shape, anchor_boxes=anchor_boxes, training=False) if self.params.task.model.detection_generator.apply_nms: # For RetinaNet model, apply export_config. # TODO(huizhongc): Add export_config to fasterrcnn and maskrcnn as needed. if isinstance(self.params.task.model, configs.retinanet.RetinaNet): export_config = self.params.task.export_config # Normalize detection box coordinates to [0, 1]. if export_config.output_normalized_coordinates: detection_boxes = ( detections['detection_boxes'] / tf.tile(image_info[:, 2:3, :], [1, 1, 2])) detections['detection_boxes'] = box_ops.normalize_boxes( detection_boxes, image_info[:, 0:1, :]) # Cast num_detections and detection_classes to float. This allows the # model inference to work on chain (go/chain) as chain requires floating # point outputs. if export_config.cast_num_detections_to_float: detections['num_detections'] = tf.cast( detections['num_detections'], dtype=tf.float32) if export_config.cast_detection_classes_to_float: detections['detection_classes'] = tf.cast( detections['detection_classes'], dtype=tf.float32) final_outputs = { 'detection_boxes': detections['detection_boxes'], 'detection_scores': detections['detection_scores'], 'detection_classes': detections['detection_classes'], 'num_detections': detections['num_detections'] } else: final_outputs = { 'decoded_boxes': detections['decoded_boxes'], 'decoded_box_scores': detections['decoded_box_scores'] } if 'detection_masks' in detections.keys(): final_outputs['detection_masks'] = detections['detection_masks'] final_outputs.update({'image_info': image_info}) return final_outputs
[ "def", "serve", "(", "self", ",", "images", ":", "tf", ".", "Tensor", ")", ":", "# Skip image preprocessing when input_type is tflite so it is compatible", "# with TFLite quantization.", "if", "self", ".", "_input_type", "!=", "'tflite'", ":", "images", ",", "anchor_box...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/vision/beta/serving/detection.py#L131-L206
prompt-toolkit/pyvim
210816b4b1d2dc00606ec924dda29e49ac4cd87c
pyvim/editor.py
python
Editor.show_message
(self, message)
Set a warning message. The layout will render it as a "pop-up" at the bottom.
Set a warning message. The layout will render it as a "pop-up" at the bottom.
[ "Set", "a", "warning", "message", ".", "The", "layout", "will", "render", "it", "as", "a", "pop", "-", "up", "at", "the", "bottom", "." ]
def show_message(self, message): """ Set a warning message. The layout will render it as a "pop-up" at the bottom. """ self.message = message
[ "def", "show_message", "(", "self", ",", "message", ")", ":", "self", ".", "message", "=", "message" ]
https://github.com/prompt-toolkit/pyvim/blob/210816b4b1d2dc00606ec924dda29e49ac4cd87c/pyvim/editor.py#L212-L217
veegee/guv
d7bac2ca6a73cc2059969af08223b82f3e187922
guv/greenthread.py
python
sleep
(seconds=0)
Yield control to the hub until at least `seconds` have elapsed :param float seconds: time to sleep for
Yield control to the hub until at least `seconds` have elapsed
[ "Yield", "control", "to", "the", "hub", "until", "at", "least", "seconds", "have", "elapsed" ]
def sleep(seconds=0): """Yield control to the hub until at least `seconds` have elapsed :param float seconds: time to sleep for """ hub = hubs.get_hub() current = greenlet.getcurrent() assert hub is not current, 'do not call blocking functions from the hub' timer = hub.schedule_call_global(seconds, current.switch) try: hub.switch() finally: timer.cancel()
[ "def", "sleep", "(", "seconds", "=", "0", ")", ":", "hub", "=", "hubs", ".", "get_hub", "(", ")", "current", "=", "greenlet", ".", "getcurrent", "(", ")", "assert", "hub", "is", "not", "current", ",", "'do not call blocking functions from the hub'", "timer",...
https://github.com/veegee/guv/blob/d7bac2ca6a73cc2059969af08223b82f3e187922/guv/greenthread.py#L11-L23
awslabs/aws-ec2rescue-linux
8ecf40e7ea0d2563dac057235803fca2221029d2
lib/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.__eq__
(self, other)
return dict.__eq__(self, other)
od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.
od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.
[ "od", ".", "__eq__", "(", "y", ")", "<", "==", ">", "od", "==", "y", ".", "Comparison", "to", "another", "OD", "is", "order", "-", "sensitive", "while", "comparison", "to", "a", "regular", "mapping", "is", "order", "-", "insensitive", "." ]
def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return len(self)==len(other) and self.items() == other.items() return dict.__eq__(self, other)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "OrderedDict", ")", ":", "return", "len", "(", "self", ")", "==", "len", "(", "other", ")", "and", "self", ".", "items", "(", ")", "==", "other", ".", "i...
https://github.com/awslabs/aws-ec2rescue-linux/blob/8ecf40e7ea0d2563dac057235803fca2221029d2/lib/requests/packages/urllib3/packages/ordered_dict.py#L235-L242
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py
python
Iface.get_role_grants_for_principal
(self, request)
Parameters: - request
Parameters: - request
[ "Parameters", ":", "-", "request" ]
def get_role_grants_for_principal(self, request): """ Parameters: - request """ pass
[ "def", "get_role_grants_for_principal", "(", "self", ",", "request", ")", ":", "pass" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py#L1030-L1036
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/util/BeautifulSoup.py
python
PageElement.findPreviousSiblings
(self, name=None, attrs={}, text=None, limit=None, **kwargs)
return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs)
Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.
Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.
[ "Returns", "the", "siblings", "of", "this", "Tag", "that", "match", "the", "given", "criteria", "and", "appear", "before", "this", "Tag", "in", "the", "document", "." ]
def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs)
[ "def", "findPreviousSiblings", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs",...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/util/BeautifulSoup.py#L259-L264
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/program_enrollments/api/writing.py
python
change_program_enrollment_status
(program_enrollment, new_status)
return program_enrollment.status
Update a program enrollment with a new status. Arguments: program_enrollment (ProgramEnrollment) status (str): from ProgramCourseEnrollmentStatuses Returns: str String from ProgramOperationStatuses.
Update a program enrollment with a new status.
[ "Update", "a", "program", "enrollment", "with", "a", "new", "status", "." ]
def change_program_enrollment_status(program_enrollment, new_status): """ Update a program enrollment with a new status. Arguments: program_enrollment (ProgramEnrollment) status (str): from ProgramCourseEnrollmentStatuses Returns: str String from ProgramOperationStatuses. """ if new_status not in ProgramEnrollmentStatuses.__ALL__: return ProgramOpStatuses.INVALID_STATUS program_enrollment.status = new_status program_enrollment.save() return program_enrollment.status
[ "def", "change_program_enrollment_status", "(", "program_enrollment", ",", "new_status", ")", ":", "if", "new_status", "not", "in", "ProgramEnrollmentStatuses", ".", "__ALL__", ":", "return", "ProgramOpStatuses", ".", "INVALID_STATUS", "program_enrollment", ".", "status",...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/program_enrollments/api/writing.py#L153-L168
OpenMDAO/OpenMDAO
f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd
openmdao/devtools/iprofile.py
python
_iter_raw_prof_file
(rawname)
Returns an iterator of (funcpath, count, elapsed_time) from a raw profile data file.
Returns an iterator of (funcpath, count, elapsed_time) from a raw profile data file.
[ "Returns", "an", "iterator", "of", "(", "funcpath", "count", "elapsed_time", ")", "from", "a", "raw", "profile", "data", "file", "." ]
def _iter_raw_prof_file(rawname): """ Returns an iterator of (funcpath, count, elapsed_time) from a raw profile data file. """ with open(rawname, 'r') as f: for line in f: path, count, elapsed = line.split() yield path, int(count), float(elapsed)
[ "def", "_iter_raw_prof_file", "(", "rawname", ")", ":", "with", "open", "(", "rawname", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "path", ",", "count", ",", "elapsed", "=", "line", ".", "split", "(", ")", "yield", "path", ",",...
https://github.com/OpenMDAO/OpenMDAO/blob/f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd/openmdao/devtools/iprofile.py#L210-L218
hezhangsprinter/DCPDN
4f27d1940512dd7637a88aaba40d5d5f5fb3ff74
models/dehaze22.py
python
D1.__init__
(self, nc, ndf, hidden_size)
self.deconv1 = nn.Sequential(nn.Conv2d(ndf,nc,kernel_size=3,stride=1,padding=1), nn.Tanh())
self.deconv1 = nn.Sequential(nn.Conv2d(ndf,nc,kernel_size=3,stride=1,padding=1), nn.Tanh())
[ "self", ".", "deconv1", "=", "nn", ".", "Sequential", "(", "nn", ".", "Conv2d", "(", "ndf", "nc", "kernel_size", "=", "3", "stride", "=", "1", "padding", "=", "1", ")", "nn", ".", "Tanh", "()", ")" ]
def __init__(self, nc, ndf, hidden_size): super(D1, self).__init__() # 256 self.conv1 = nn.Sequential(nn.Conv2d(nc,ndf,kernel_size=3,stride=1,padding=1), nn.ELU(True)) # 256 self.conv2 = conv_block(ndf,ndf) # 128 self.conv3 = conv_block(ndf, ndf*2) # 64 self.conv4 = conv_block(ndf*2, ndf*3) # 32 self.encode = nn.Conv2d(ndf*3, hidden_size, kernel_size=1,stride=1,padding=0) self.decode = nn.Conv2d(hidden_size, ndf, kernel_size=1,stride=1,padding=0) # 32 self.deconv4 = deconv_block(ndf, ndf) # 64 self.deconv3 = deconv_block(ndf, ndf) # 128 self.deconv2 = deconv_block(ndf, ndf) # 256 self.deconv1 = nn.Sequential(nn.Conv2d(ndf,ndf,kernel_size=3,stride=1,padding=1), nn.ELU(True), nn.Conv2d(ndf,ndf,kernel_size=3,stride=1,padding=1), nn.ELU(True), nn.Conv2d(ndf, nc, kernel_size=3, stride=1, padding=1), nn.Tanh()) """ self.deconv1 = nn.Sequential(nn.Conv2d(ndf,nc,kernel_size=3,stride=1,padding=1), nn.Tanh()) """
[ "def", "__init__", "(", "self", ",", "nc", ",", "ndf", ",", "hidden_size", ")", ":", "super", "(", "D1", ",", "self", ")", ".", "__init__", "(", ")", "# 256", "self", ".", "conv1", "=", "nn", ".", "Sequential", "(", "nn", ".", "Conv2d", "(", "nc"...
https://github.com/hezhangsprinter/DCPDN/blob/4f27d1940512dd7637a88aaba40d5d5f5fb3ff74/models/dehaze22.py#L69-L100
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/PassiveTotal/Integrations/PassiveTotal_v2/PassiveTotal_v2.py
python
get_host_attribute_context_data
(records: List[Dict[str, Any]])
return standard_results, custom_ec
Prepares context data for get components and get trackers command :param records: API response :return: standard entry command results list and custom entry context
Prepares context data for get components and get trackers command
[ "Prepares", "context", "data", "for", "get", "components", "and", "get", "trackers", "command" ]
def get_host_attribute_context_data(records: List[Dict[str, Any]]) -> Tuple[list, list]: """ Prepares context data for get components and get trackers command :param records: API response :return: standard entry command results list and custom entry context """ custom_ec = createContext(data=records, removeNull=True) standard_results: List[CommandResults] = [] for record in records: if record.get('hostname'): hostname = record.get('hostname') dbot_score = Common.DBotScore(indicator=hostname, indicator_type=DBotScoreType.DOMAIN, integration_name=INTEGRATION_NAME, score=Common.DBotScore.NONE) if auto_detect_indicator_type(hostname) == FeedIndicatorType.Domain: domain_ioc = Common.Domain(domain=hostname, dbot_score=dbot_score) # add standard output with standard readable output standard_results.append(CommandResults( indicator=domain_ioc, readable_output=tableToMarkdown('', domain_ioc.to_context().get(Common.Domain.CONTEXT_PATH)) )) elif record.get('address'): address = record.get('address') dbot_score = Common.DBotScore(indicator=address, indicator_type=DBotScoreType.IP, integration_name=INTEGRATION_NAME, score=Common.DBotScore.NONE) if auto_detect_indicator_type(address) == FeedIndicatorType.IP: ip_ioc = Common.IP(ip=address, dbot_score=dbot_score) # add standard output with standard readable output standard_results.append(CommandResults( indicator=ip_ioc, readable_output=tableToMarkdown('', ip_ioc.to_context().get(Common.IP.CONTEXT_PATH)) )) return standard_results, custom_ec
[ "def", "get_host_attribute_context_data", "(", "records", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "Tuple", "[", "list", ",", "list", "]", ":", "custom_ec", "=", "createContext", "(", "data", "=", "records", ",", "removeNull...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/PassiveTotal/Integrations/PassiveTotal_v2/PassiveTotal_v2.py#L261-L294
xmunoz/sodapy
8a815a7ac3f4d955f0ac7f9b525c8755584179b4
sodapy/socrata.py
python
Socrata._perform_update
(self, method, resource, payload)
return response
Execute the update task.
Execute the update task.
[ "Execute", "the", "update", "task", "." ]
def _perform_update(self, method, resource, payload): """ Execute the update task. """ if isinstance(payload, (dict, list)): response = self._perform_request(method, resource, data=json.dumps(payload)) elif isinstance(payload, IOBase): headers = { "content-type": "text/csv", } response = self._perform_request( method, resource, data=payload, headers=headers ) else: raise Exception( "Unrecognized payload {}. Currently only list-, dictionary-," " and file-types are supported.".format(type(payload)) ) return response
[ "def", "_perform_update", "(", "self", ",", "method", ",", "resource", ",", "payload", ")", ":", "if", "isinstance", "(", "payload", ",", "(", "dict", ",", "list", ")", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "method", ",", "re...
https://github.com/xmunoz/sodapy/blob/8a815a7ac3f4d955f0ac7f9b525c8755584179b4/sodapy/socrata.py#L495-L515
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/docs/service.py
python
DocumentQuery.ToUri
(self)
return new_feed
Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Document List feed.
Generates a URI from the query parameters set in the object.
[ "Generates", "a", "URI", "from", "the", "query", "parameters", "set", "in", "the", "object", "." ]
def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Document List feed. """ old_feed = self.feed self.feed = '/'.join([old_feed, self.visibility, self.projection]) new_feed = gdata.service.Query.ToUri(self) self.feed = old_feed return new_feed
[ "def", "ToUri", "(", "self", ")", ":", "old_feed", "=", "self", ".", "feed", "self", ".", "feed", "=", "'/'", ".", "join", "(", "[", "old_feed", ",", "self", ".", "visibility", ",", "self", ".", "projection", "]", ")", "new_feed", "=", "gdata", "."...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/docs/service.py#L545-L556
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/form_processor/migrations/0036_cleanup_models.py
python
_alter_to_uuid_sql_forawd
(model, field)
return 'ALTER TABLE "form_processor_{model}" ALTER COLUMN "{field}" TYPE uuid USING {field}::uuid'.format( model=model, field=field )
[]
def _alter_to_uuid_sql_forawd(model, field): return 'ALTER TABLE "form_processor_{model}" ALTER COLUMN "{field}" TYPE uuid USING {field}::uuid'.format( model=model, field=field )
[ "def", "_alter_to_uuid_sql_forawd", "(", "model", ",", "field", ")", ":", "return", "'ALTER TABLE \"form_processor_{model}\" ALTER COLUMN \"{field}\" TYPE uuid USING {field}::uuid'", ".", "format", "(", "model", "=", "model", ",", "field", "=", "field", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/form_processor/migrations/0036_cleanup_models.py#L8-L11
plkmo/BERT-Relation-Extraction
06075620fccb044785f5fd319e8d06df9af15b50
src/model/ALBERT/tokenization_albert.py
python
AlbertTokenizer.save_vocabulary
(self, save_directory)
return (out_vocab_file,)
Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory.
Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory.
[ "Save", "the", "sentencepiece", "vocabulary", "(", "copy", "original", "file", ")", "and", "special", "tokens", "file", "to", "a", "directory", "." ]
def save_vocabulary(self, save_directory): """ Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory. """ if not os.path.isdir(save_directory): logger.error("Vocabulary path ({}) should be a directory".format(save_directory)) return out_vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES["vocab_file"]) if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): copyfile(self.vocab_file, out_vocab_file) return (out_vocab_file,)
[ "def", "save_vocabulary", "(", "self", ",", "save_directory", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "save_directory", ")", ":", "logger", ".", "error", "(", "\"Vocabulary path ({}) should be a directory\"", ".", "format", "(", "save_direct...
https://github.com/plkmo/BERT-Relation-Extraction/blob/06075620fccb044785f5fd319e8d06df9af15b50/src/model/ALBERT/tokenization_albert.py#L245-L257
NaturalHistoryMuseum/inselect
196a3ae2a0ed4e2c7cb667aaba9a6be1bcd90ca6
inselect/gui/views/metadata.py
python
FormContainer._create_field_control
(self, field, template)
Returns a QWidget for editing field, validated using template
Returns a QWidget for editing field, validated using template
[ "Returns", "a", "QWidget", "for", "editing", "field", "validated", "using", "template" ]
def _create_field_control(self, field, template): """Returns a QWidget for editing field, validated using template """ if 'countryCode' == field.name: return CountryComboBox(template) elif 'language' == field.name: return LanguageComboBox(template) elif field.fixed_value: return FixedValueControl(field.fixed_value) elif field.choices: combo = ChoicesFieldComboBox(field.name, template, labels=field.choices) return combo elif field.choices_with_data: choices = field.choices_with_data combo = ChoicesWithDataFieldComboBox(field.name, template, labels=iter(choices.keys()), values=iter(choices.values())) return combo else: # Not using Qt's very restrictive QValidator scheme edit = FieldEdit(field.name, template) return edit
[ "def", "_create_field_control", "(", "self", ",", "field", ",", "template", ")", ":", "if", "'countryCode'", "==", "field", ".", "name", ":", "return", "CountryComboBox", "(", "template", ")", "elif", "'language'", "==", "field", ".", "name", ":", "return", ...
https://github.com/NaturalHistoryMuseum/inselect/blob/196a3ae2a0ed4e2c7cb667aaba9a6be1bcd90ca6/inselect/gui/views/metadata.py#L223-L245
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/pysaml2-4.9.0/src/saml2/sigver.py
python
_make_vals
(val, klass, seccont, klass_inst=None, prop=None, part=False, base64encode=False, elements_to_sign=None)
Creates a class instance with a specified value, the specified class instance may be a value on a property in a defined class instance. :param val: The value :param klass: The value class :param klass_inst: The class instance which has a property on which what this function returns is a value. :param prop: The property which the value should be assigned to. :param part: If the value is one of a possible list of values it should be handled slightly different compared to if it isn't. :return: Value class instance
Creates a class instance with a specified value, the specified class instance may be a value on a property in a defined class instance.
[ "Creates", "a", "class", "instance", "with", "a", "specified", "value", "the", "specified", "class", "instance", "may", "be", "a", "value", "on", "a", "property", "in", "a", "defined", "class", "instance", "." ]
def _make_vals(val, klass, seccont, klass_inst=None, prop=None, part=False, base64encode=False, elements_to_sign=None): """ Creates a class instance with a specified value, the specified class instance may be a value on a property in a defined class instance. :param val: The value :param klass: The value class :param klass_inst: The class instance which has a property on which what this function returns is a value. :param prop: The property which the value should be assigned to. :param part: If the value is one of a possible list of values it should be handled slightly different compared to if it isn't. :return: Value class instance """ cinst = None if isinstance(val, dict): cinst = _instance(klass, val, seccont, base64encode=base64encode, elements_to_sign=elements_to_sign) else: try: cinst = klass().set_text(val) except ValueError: if not part: cis = [ _make_vals( sval, klass, seccont, klass_inst, prop, True, base64encode, elements_to_sign) for sval in val ] setattr(klass_inst, prop, cis) else: raise if part: return cinst else: if cinst: cis = [cinst] setattr(klass_inst, prop, cis)
[ "def", "_make_vals", "(", "val", ",", "klass", ",", "seccont", ",", "klass_inst", "=", "None", ",", "prop", "=", "None", ",", "part", "=", "False", ",", "base64encode", "=", "False", ",", "elements_to_sign", "=", "None", ")", ":", "cinst", "=", "None",...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pysaml2-4.9.0/src/saml2/sigver.py#L214-L260
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/poplib.py
python
POP3.list
(self, which=None)
return self._longcmd('LIST')
Request listing, return result. Result without a message number argument is in form ['response', ['mesg_num octets', ...], octets]. Result when a message number argument is given is a single response: the "scan listing" for that message.
Request listing, return result.
[ "Request", "listing", "return", "result", "." ]
def list(self, which=None): """Request listing, return result. Result without a message number argument is in form ['response', ['mesg_num octets', ...], octets]. Result when a message number argument is given is a single response: the "scan listing" for that message. """ if which is not None: return self._shortcmd('LIST %s' % which) return self._longcmd('LIST')
[ "def", "list", "(", "self", ",", "which", "=", "None", ")", ":", "if", "which", "is", "not", "None", ":", "return", "self", ".", "_shortcmd", "(", "'LIST %s'", "%", "which", ")", "return", "self", ".", "_longcmd", "(", "'LIST'", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/poplib.py#L205-L216
deeptools/deepTools
ac42d29c298c026aa0c53c9db2553087ebc86b97
deeptools/multiBamSummary.py
python
main
(args=None)
1. get read counts at different positions either all of same length or from genomic regions from the BED file 2. save data for further plotting
1. get read counts at different positions either all of same length or from genomic regions from the BED file
[ "1", ".", "get", "read", "counts", "at", "different", "positions", "either", "all", "of", "same", "length", "or", "from", "genomic", "regions", "from", "the", "BED", "file" ]
def main(args=None): """ 1. get read counts at different positions either all of same length or from genomic regions from the BED file 2. save data for further plotting """ args = process_args(args) if 'BED' in args: bed_regions = args.BED else: bed_regions = None if len(args.bamfiles) == 1 and not (args.outRawCounts or args.scalingFactors): sys.stderr.write("You've input a single BAM file and not specified " "--outRawCounts or --scalingFactors. The resulting output will NOT be " "useful with any deepTools program!\n") stepsize = args.binSize + args.distanceBetweenBins c = countR.CountReadsPerBin( args.bamfiles, args.binSize, numberOfSamples=None, genomeChunkSize=args.genomeChunkSize, numberOfProcessors=args.numberOfProcessors, verbose=args.verbose, region=args.region, bedFile=bed_regions, blackListFileName=args.blackListFileName, extendReads=args.extendReads, minMappingQuality=args.minMappingQuality, ignoreDuplicates=args.ignoreDuplicates, center_read=args.centerReads, samFlag_include=args.samFlagInclude, samFlag_exclude=args.samFlagExclude, minFragmentLength=args.minFragmentLength, maxFragmentLength=args.maxFragmentLength, stepSize=stepsize, zerosToNans=False, out_file_for_raw_data=args.outRawCounts) num_reads_per_bin = c.run(allArgs=args) sys.stderr.write("Number of bins " "found: {}\n".format(num_reads_per_bin.shape[0])) if num_reads_per_bin.shape[0] < 2: exit("ERROR: too few non zero bins found.\n" "If using --region please check that this " "region is covered by reads.\n") # numpy will append .npz to the file name if we don't do this... if args.outFileName: f = open(args.outFileName, "wb") np.savez_compressed(f, matrix=num_reads_per_bin, labels=args.labels) f.close() if args.scalingFactors: f = open(args.scalingFactors, 'w') f.write("sample\tscalingFactor\n") scalingFactors = countR.estimateSizeFactors(num_reads_per_bin) for sample, scalingFactor in zip(args.labels, scalingFactors): f.write("{}\t{:6.4f}\n".format(sample, scalingFactor)) f.close() if args.outRawCounts: # append to the generated file the # labels header = "#'chr'\t'start'\t'end'\t" header += "'" + "'\t'".join(args.labels) + "'\n" f = open(args.outRawCounts, 'r+') content = f.read() f.seek(0, 0) f.write(header + content) f.close()
[ "def", "main", "(", "args", "=", "None", ")", ":", "args", "=", "process_args", "(", "args", ")", "if", "'BED'", "in", "args", ":", "bed_regions", "=", "args", ".", "BED", "else", ":", "bed_regions", "=", "None", "if", "len", "(", "args", ".", "bam...
https://github.com/deeptools/deepTools/blob/ac42d29c298c026aa0c53c9db2553087ebc86b97/deeptools/multiBamSummary.py#L207-L285
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/nad/media_player.py
python
NAD.update
(self)
Retrieve latest state.
Retrieve latest state.
[ "Retrieve", "latest", "state", "." ]
def update(self) -> None: """Retrieve latest state.""" power_state = self._nad_receiver.main_power("?") if not power_state: self._state = None return self._state = ( STATE_ON if self._nad_receiver.main_power("?") == "On" else STATE_OFF ) if self._state == STATE_ON: self._mute = self._nad_receiver.main_mute("?") == "On" volume = self._nad_receiver.main_volume("?") # Some receivers cannot report the volume, e.g. C 356BEE, # instead they only support stepping the volume up or down self._volume = self.calc_volume(volume) if volume is not None else None self._source = self._source_dict.get(self._nad_receiver.main_source("?"))
[ "def", "update", "(", "self", ")", "->", "None", ":", "power_state", "=", "self", ".", "_nad_receiver", ".", "main_power", "(", "\"?\"", ")", "if", "not", "power_state", ":", "self", ".", "_state", "=", "None", "return", "self", ".", "_state", "=", "("...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/nad/media_player.py#L188-L204
ceph/ceph-ansible
583e60af84180f0414d67ee52c3ec7cd64ddb4dd
library/radosgw_realm.py
python
pre_generate_radosgw_cmd
(container_image=None)
return cmd
Generate radosgw-admin prefix comaand
Generate radosgw-admin prefix comaand
[ "Generate", "radosgw", "-", "admin", "prefix", "comaand" ]
def pre_generate_radosgw_cmd(container_image=None): ''' Generate radosgw-admin prefix comaand ''' if container_image: cmd = container_exec('radosgw-admin', container_image) else: cmd = ['radosgw-admin'] return cmd
[ "def", "pre_generate_radosgw_cmd", "(", "container_image", "=", "None", ")", ":", "if", "container_image", ":", "cmd", "=", "container_exec", "(", "'radosgw-admin'", ",", "container_image", ")", "else", ":", "cmd", "=", "[", "'radosgw-admin'", "]", "return", "cm...
https://github.com/ceph/ceph-ansible/blob/583e60af84180f0414d67ee52c3ec7cd64ddb4dd/library/radosgw_realm.py#L131-L140
openai/imitation
8a2ed905e2ac54bda0f71e5ee364e90568e6d031
policyopt/thutil.py
python
categorical_kl
(logprobs1_B_A, logprobs2_B_A, name=None)
return kl_B
KL divergence between categorical distributions, specified as log probabilities
KL divergence between categorical distributions, specified as log probabilities
[ "KL", "divergence", "between", "categorical", "distributions", "specified", "as", "log", "probabilities" ]
def categorical_kl(logprobs1_B_A, logprobs2_B_A, name=None): '''KL divergence between categorical distributions, specified as log probabilities''' kl_B = (tensor.exp(logprobs1_B_A) * (logprobs1_B_A - logprobs2_B_A)).sum(axis=1) return kl_B
[ "def", "categorical_kl", "(", "logprobs1_B_A", ",", "logprobs2_B_A", ",", "name", "=", "None", ")", ":", "kl_B", "=", "(", "tensor", ".", "exp", "(", "logprobs1_B_A", ")", "*", "(", "logprobs1_B_A", "-", "logprobs2_B_A", ")", ")", ".", "sum", "(", "axis"...
https://github.com/openai/imitation/blob/8a2ed905e2ac54bda0f71e5ee364e90568e6d031/policyopt/thutil.py#L60-L63
hzy46/Deep-Learning-21-Examples
15c2d9edccad090cd67b033f24a43c544e5cba3e
chapter_5/research/object_detection/utils/np_box_list.py
python
BoxList._is_valid_boxes
(self, data)
return True
Check whether data fullfills the format of N*[ymin, xmin, ymax, xmin]. Args: data: a numpy array of shape [N, 4] representing box coordinates Returns: a boolean indicating whether all ymax of boxes are equal or greater than ymin, and all xmax of boxes are equal or greater than xmin.
Check whether data fullfills the format of N*[ymin, xmin, ymax, xmin].
[ "Check", "whether", "data", "fullfills", "the", "format", "of", "N", "*", "[", "ymin", "xmin", "ymax", "xmin", "]", "." ]
def _is_valid_boxes(self, data): """Check whether data fullfills the format of N*[ymin, xmin, ymax, xmin]. Args: data: a numpy array of shape [N, 4] representing box coordinates Returns: a boolean indicating whether all ymax of boxes are equal or greater than ymin, and all xmax of boxes are equal or greater than xmin. """ if data.shape[0] > 0: for i in moves.range(data.shape[0]): if data[i, 0] > data[i, 2] or data[i, 1] > data[i, 3]: return False return True
[ "def", "_is_valid_boxes", "(", "self", ",", "data", ")", ":", "if", "data", ".", "shape", "[", "0", "]", ">", "0", ":", "for", "i", "in", "moves", ".", "range", "(", "data", ".", "shape", "[", "0", "]", ")", ":", "if", "data", "[", "i", ",", ...
https://github.com/hzy46/Deep-Learning-21-Examples/blob/15c2d9edccad090cd67b033f24a43c544e5cba3e/chapter_5/research/object_detection/utils/np_box_list.py#L120-L134
lxdock/lxdock
f71006d130bc8b53603eea36a546003495437493
lxdock/logging.py
python
_AtleastErrorFilter.filter
(self, record)
return record.levelno >= logging.ERROR
[]
def filter(self, record): return record.levelno >= logging.ERROR
[ "def", "filter", "(", "self", ",", "record", ")", ":", "return", "record", ".", "levelno", ">=", "logging", ".", "ERROR" ]
https://github.com/lxdock/lxdock/blob/f71006d130bc8b53603eea36a546003495437493/lxdock/logging.py#L22-L23
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/distutils/file_util.py
python
_copy_file_contents
(src, dst, buffer_size=16*1024)
Copy the file 'src' to 'dst'. Both must be filenames. Any error opening either file, reading from 'src', or writing to 'dst', raises DistutilsFileError. Data is read/written in chunks of 'buffer_size' bytes (default 16k). No attempt is made to handle anything apart from regular files.
Copy the file 'src' to 'dst'.
[ "Copy", "the", "file", "src", "to", "dst", "." ]
def _copy_file_contents(src, dst, buffer_size=16*1024): """Copy the file 'src' to 'dst'. Both must be filenames. Any error opening either file, reading from 'src', or writing to 'dst', raises DistutilsFileError. Data is read/written in chunks of 'buffer_size' bytes (default 16k). No attempt is made to handle anything apart from regular files. """ # Stolen from shutil module in the standard library, but with # custom error-handling added. fsrc = None fdst = None try: try: fsrc = open(src, 'rb') except os.error, (errno, errstr): raise DistutilsFileError("could not open '%s': %s" % (src, errstr)) if os.path.exists(dst): try: os.unlink(dst) except os.error, (errno, errstr): raise DistutilsFileError( "could not delete '%s': %s" % (dst, errstr)) try: fdst = open(dst, 'wb') except os.error, (errno, errstr): raise DistutilsFileError( "could not create '%s': %s" % (dst, errstr)) while 1: try: buf = fsrc.read(buffer_size) except os.error, (errno, errstr): raise DistutilsFileError( "could not read from '%s': %s" % (src, errstr)) if not buf: break try: fdst.write(buf) except os.error, (errno, errstr): raise DistutilsFileError( "could not write to '%s': %s" % (dst, errstr)) finally: if fdst: fdst.close() if fsrc: fsrc.close()
[ "def", "_copy_file_contents", "(", "src", ",", "dst", ",", "buffer_size", "=", "16", "*", "1024", ")", ":", "# Stolen from shutil module in the standard library, but with", "# custom error-handling added.", "fsrc", "=", "None", "fdst", "=", "None", "try", ":", "try", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/distutils/file_util.py#L18-L69
snapcore/snapcraft
b81550376df7f2d0dfe65f7bfb006a3107252450
snapcraft/cli/snapcraftctl/_runner.py
python
build
()
Run the 'build' step of the calling part's lifecycle
Run the 'build' step of the calling part's lifecycle
[ "Run", "the", "build", "step", "of", "the", "calling", "part", "s", "lifecycle" ]
def build(): """Run the 'build' step of the calling part's lifecycle""" _call_function("build")
[ "def", "build", "(", ")", ":", "_call_function", "(", "\"build\"", ")" ]
https://github.com/snapcore/snapcraft/blob/b81550376df7f2d0dfe65f7bfb006a3107252450/snapcraft/cli/snapcraftctl/_runner.py#L53-L55
VLSIDA/OpenRAM
f66aac3264598eeae31225c62b6a4af52412d407
compiler/base/hierarchy_spice.py
python
spice.analytical_delay
(self, corner, slew, load=0.0)
return delay_data(corner_delay, corner_slew)
Inform users undefined delay module while building new modules
Inform users undefined delay module while building new modules
[ "Inform", "users", "undefined", "delay", "module", "while", "building", "new", "modules" ]
def analytical_delay(self, corner, slew, load=0.0): """Inform users undefined delay module while building new modules""" # FIXME: Slew is not used in the model right now. # Can be added heuristically as linear factor relative_cap = logical_effort.convert_farad_to_relative_c(load) stage_effort = self.get_stage_effort(relative_cap) # If it fails, then keep running with a valid object. if not stage_effort: return delay_data(0.0, 0.0) abs_delay = stage_effort.get_absolute_delay() corner_delay = self.apply_corners_analytically(abs_delay, corner) SLEW_APPROXIMATION = 0.1 corner_slew = SLEW_APPROXIMATION * corner_delay return delay_data(corner_delay, corner_slew)
[ "def", "analytical_delay", "(", "self", ",", "corner", ",", "slew", ",", "load", "=", "0.0", ")", ":", "# FIXME: Slew is not used in the model right now.", "# Can be added heuristically as linear factor", "relative_cap", "=", "logical_effort", ".", "convert_farad_to_relative_...
https://github.com/VLSIDA/OpenRAM/blob/f66aac3264598eeae31225c62b6a4af52412d407/compiler/base/hierarchy_spice.py#L440-L456
emcconville/wand
03682680c351645f16c3b8ea23bde79fbb270305
wand/image.py
python
BaseImage.histogram
(self)
return HistogramDict(self)
(:class:`HistogramDict`) The mapping that represents the histogram. Keys are :class:`~wand.color.Color` objects, and values are the number of pixels. .. tip:: True-color photos can have millions of color values. If performance is more valuable than accuracy, remember to :meth:`quantize` the image before generating a :class:`HistogramDict`. with Image(filename='hd_photo.jpg') as img: img.quantize(255, 'RGB', 0, False, False) hist = img.histogram .. versionadded:: 0.3.0
(:class:`HistogramDict`) The mapping that represents the histogram. Keys are :class:`~wand.color.Color` objects, and values are the number of pixels.
[ "(", ":", "class", ":", "HistogramDict", ")", "The", "mapping", "that", "represents", "the", "histogram", ".", "Keys", "are", ":", "class", ":", "~wand", ".", "color", ".", "Color", "objects", "and", "values", "are", "the", "number", "of", "pixels", "." ...
def histogram(self): """(:class:`HistogramDict`) The mapping that represents the histogram. Keys are :class:`~wand.color.Color` objects, and values are the number of pixels. .. tip:: True-color photos can have millions of color values. If performance is more valuable than accuracy, remember to :meth:`quantize` the image before generating a :class:`HistogramDict`. with Image(filename='hd_photo.jpg') as img: img.quantize(255, 'RGB', 0, False, False) hist = img.histogram .. versionadded:: 0.3.0 """ return HistogramDict(self)
[ "def", "histogram", "(", "self", ")", ":", "return", "HistogramDict", "(", "self", ")" ]
https://github.com/emcconville/wand/blob/03682680c351645f16c3b8ea23bde79fbb270305/wand/image.py#L1959-L1977
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.2/django/db/models/sql/compiler.py
python
SQLCompiler.quote_name_unless_alias
(self, name)
return r
A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL).
A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL).
[ "A", "wrapper", "around", "connection", ".", "ops", ".", "quote_name", "that", "doesn", "t", "quote", "aliases", "for", "table", "names", ".", "This", "avoids", "problems", "with", "some", "SQL", "dialects", "that", "treat", "quoted", "strings", "specially", ...
def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ((name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r
[ "def", "quote_name_unless_alias", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "quote_cache", ":", "return", "self", ".", "quote_cache", "[", "name", "]", "if", "(", "(", "name", "in", "self", ".", "query", ".", "alias_map", "an...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/db/models/sql/compiler.py#L31-L45
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet/nets/e2e_asr_common.py
python
ErrorCalculator.__call__
(self, ys_hat, ys_pad, is_ctc=False)
return cer, wer
Calculate sentence-level WER/CER score. :param torch.Tensor ys_hat: prediction (batch, seqlen) :param torch.Tensor ys_pad: reference (batch, seqlen) :param bool is_ctc: calculate CER score for CTC :return: sentence-level WER score :rtype float :return: sentence-level CER score :rtype float
Calculate sentence-level WER/CER score.
[ "Calculate", "sentence", "-", "level", "WER", "/", "CER", "score", "." ]
def __call__(self, ys_hat, ys_pad, is_ctc=False): """Calculate sentence-level WER/CER score. :param torch.Tensor ys_hat: prediction (batch, seqlen) :param torch.Tensor ys_pad: reference (batch, seqlen) :param bool is_ctc: calculate CER score for CTC :return: sentence-level WER score :rtype float :return: sentence-level CER score :rtype float """ cer, wer = None, None if is_ctc: return self.calculate_cer_ctc(ys_hat, ys_pad) elif not self.report_cer and not self.report_wer: return cer, wer seqs_hat, seqs_true = self.convert_to_char(ys_hat, ys_pad) if self.report_cer: cer = self.calculate_cer(seqs_hat, seqs_true) if self.report_wer: wer = self.calculate_wer(seqs_hat, seqs_true) return cer, wer
[ "def", "__call__", "(", "self", ",", "ys_hat", ",", "ys_pad", ",", "is_ctc", "=", "False", ")", ":", "cer", ",", "wer", "=", "None", ",", "None", "if", "is_ctc", ":", "return", "self", ".", "calculate_cer_ctc", "(", "ys_hat", ",", "ys_pad", ")", "eli...
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/nets/e2e_asr_common.py#L129-L152
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/proxy/v1/service/__init__.py
python
ServiceInstance.date_updated
(self)
return self._properties['date_updated']
:returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime
:returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime
[ ":", "returns", ":", "The", "ISO", "8601", "date", "and", "time", "in", "GMT", "when", "the", "resource", "was", "last", "updated", ":", "rtype", ":", "datetime" ]
def date_updated(self): """ :returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime """ return self._properties['date_updated']
[ "def", "date_updated", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'date_updated'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/proxy/v1/service/__init__.py#L499-L504
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/layout/geo/_lataxis.py
python
Lataxis.gridwidth
(self)
return self["gridwidth"]
Sets the graticule's stroke width (in px). The 'gridwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the graticule's stroke width (in px). The 'gridwidth' property is a number and may be specified as: - An int or float in the interval [0, inf]
[ "Sets", "the", "graticule", "s", "stroke", "width", "(", "in", "px", ")", ".", "The", "gridwidth", "property", "is", "a", "number", "and", "may", "be", "specified", "as", ":", "-", "An", "int", "or", "float", "in", "the", "interval", "[", "0", "inf",...
def gridwidth(self): """ Sets the graticule's stroke width (in px). The 'gridwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["gridwidth"]
[ "def", "gridwidth", "(", "self", ")", ":", "return", "self", "[", "\"gridwidth\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/layout/geo/_lataxis.py#L95-L106
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/flask/cli.py
python
find_app_by_string
(script_info, module, app_name)
Checks if the given string is a variable name or a function. If it is a function, it checks for specified arguments and whether it takes a ``script_info`` argument and calls the function with the appropriate arguments.
Checks if the given string is a variable name or a function. If it is a function, it checks for specified arguments and whether it takes a ``script_info`` argument and calls the function with the appropriate arguments.
[ "Checks", "if", "the", "given", "string", "is", "a", "variable", "name", "or", "a", "function", ".", "If", "it", "is", "a", "function", "it", "checks", "for", "specified", "arguments", "and", "whether", "it", "takes", "a", "script_info", "argument", "and",...
def find_app_by_string(script_info, module, app_name): """Checks if the given string is a variable name or a function. If it is a function, it checks for specified arguments and whether it takes a ``script_info`` argument and calls the function with the appropriate arguments. """ from flask import Flask match = re.match(r'^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$', app_name) if not match: raise NoAppException( '"{name}" is not a valid variable name or function ' 'expression.'.format(name=app_name) ) name, args = match.groups() try: attr = getattr(module, name) except AttributeError as e: raise NoAppException(e.args[0]) if inspect.isfunction(attr): if args: try: args = ast.literal_eval('({args},)'.format(args=args)) except (ValueError, SyntaxError)as e: raise NoAppException( 'Could not parse the arguments in ' '"{app_name}".'.format(e=e, app_name=app_name) ) else: args = () try: app = call_factory(script_info, attr, args) except TypeError as e: if not _called_with_wrong_args(attr): raise raise NoAppException( '{e}\nThe factory "{app_name}" in module "{module}" could not ' 'be called with the specified arguments.'.format( e=e, app_name=app_name, module=module.__name__ ) ) else: app = attr if isinstance(app, Flask): return app raise NoAppException( 'A valid Flask application was not obtained from ' '"{module}:{app_name}".'.format( module=module.__name__, app_name=app_name ) )
[ "def", "find_app_by_string", "(", "script_info", ",", "module", ",", "app_name", ")", ":", "from", "flask", "import", "Flask", "match", "=", "re", ".", "match", "(", "r'^ *([^ ()]+) *(?:\\((.*?) *,? *\\))? *$'", ",", "app_name", ")", "if", "not", "match", ":", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/flask/cli.py#L143-L200
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/hyperelliptic_curves/hyperelliptic_finite_field.py
python
HyperellipticCurve_finite_field.Cartier_matrix
(self)
return M
r""" INPUT: - ``E`` : Hyperelliptic Curve of the form `y^2 = f(x)` over a finite field, `\GF{q}` OUTPUT: - ``M``: The matrix `M = (c_{pi-j})`, where `c_i` are the coefficients of `f(x)^{(p-1)/2} = \sum c_i x^i` REFERENCES: N. Yui. On the Jacobian varieties of hyperelliptic curves over fields of characteristic `p > 2`. EXAMPLES:: sage: K.<x>=GF(9,'x')[] sage: C=HyperellipticCurve(x^7-1,0) sage: C.Cartier_matrix() [0 0 2] [0 0 0] [0 1 0] sage: K.<x>=GF(49,'x')[] sage: C=HyperellipticCurve(x^5+1,0) sage: C.Cartier_matrix() [0 3] [0 0] sage: P.<x>=GF(9,'a')[] sage: E=HyperellipticCurve(x^29+1,0) sage: E.Cartier_matrix() [0 0 1 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 1 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 1 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 1 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 1 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 1 0] TESTS:: sage: K.<x>=GF(2,'x')[] sage: C=HyperellipticCurve(x^7-1,x) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: p must be odd sage: K.<x>=GF(5,'x')[] sage: C=HyperellipticCurve(x^7-1,4) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: E must be of the form y^2 = f(x) sage: K.<x>=GF(5,'x')[] sage: C=HyperellipticCurve(x^8-1,0) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: In this implementation the degree of f must be odd sage: K.<x>=GF(5,'x')[] sage: C=HyperellipticCurve(x^5+1,0,check_squarefree=False) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: curve is not smooth
r""" INPUT:
[ "r", "INPUT", ":" ]
def Cartier_matrix(self): r""" INPUT: - ``E`` : Hyperelliptic Curve of the form `y^2 = f(x)` over a finite field, `\GF{q}` OUTPUT: - ``M``: The matrix `M = (c_{pi-j})`, where `c_i` are the coefficients of `f(x)^{(p-1)/2} = \sum c_i x^i` REFERENCES: N. Yui. On the Jacobian varieties of hyperelliptic curves over fields of characteristic `p > 2`. EXAMPLES:: sage: K.<x>=GF(9,'x')[] sage: C=HyperellipticCurve(x^7-1,0) sage: C.Cartier_matrix() [0 0 2] [0 0 0] [0 1 0] sage: K.<x>=GF(49,'x')[] sage: C=HyperellipticCurve(x^5+1,0) sage: C.Cartier_matrix() [0 3] [0 0] sage: P.<x>=GF(9,'a')[] sage: E=HyperellipticCurve(x^29+1,0) sage: E.Cartier_matrix() [0 0 1 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 1 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 1 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 1 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 1 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 1 0] TESTS:: sage: K.<x>=GF(2,'x')[] sage: C=HyperellipticCurve(x^7-1,x) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: p must be odd sage: K.<x>=GF(5,'x')[] sage: C=HyperellipticCurve(x^7-1,4) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: E must be of the form y^2 = f(x) sage: K.<x>=GF(5,'x')[] sage: C=HyperellipticCurve(x^8-1,0) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: In this implementation the degree of f must be odd sage: K.<x>=GF(5,'x')[] sage: C=HyperellipticCurve(x^5+1,0,check_squarefree=False) sage: C.Cartier_matrix() Traceback (most recent call last): ... ValueError: curve is not smooth """ #checking first that Cartier matrix is not already cached. Since #it can be called by either Hasse_Witt or a_number. #This way it does not matter which function is called first #in the code. # Trac Ticket #11115: Why shall we waste time by studying # the cache manually? We only need to check whether the cached # data belong to self. M, Coeffs,g, Fq, p, E= self._Cartier_matrix_cached() if E!=self: self._Cartier_matrix_cached.clear_cache() M, Coeffs,g, Fq, p, E= self._Cartier_matrix_cached() return M
[ "def", "Cartier_matrix", "(", "self", ")", ":", "#checking first that Cartier matrix is not already cached. Since", "#it can be called by either Hasse_Witt or a_number.", "#This way it does not matter which function is called first", "#in the code.", "# Trac Ticket #11115: Why shall we waste tim...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/hyperelliptic_curves/hyperelliptic_finite_field.py#L1555-L1643
mtianyan/VueDjangoAntdProBookShop
fd8fa2151c81edde2f8b8e6df8e1ddd799f940c2
third_party/social_core/storage.py
python
UserMixin.user_exists
(cls, *args, **kwargs)
Return True/False if a User instance exists with the given arguments. Arguments are directly passed to filter() manager method.
Return True/False if a User instance exists with the given arguments. Arguments are directly passed to filter() manager method.
[ "Return", "True", "/", "False", "if", "a", "User", "instance", "exists", "with", "the", "given", "arguments", ".", "Arguments", "are", "directly", "passed", "to", "filter", "()", "manager", "method", "." ]
def user_exists(cls, *args, **kwargs): """ Return True/False if a User instance exists with the given arguments. Arguments are directly passed to filter() manager method. """ raise NotImplementedError('Implement in subclass')
[ "def", "user_exists", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'Implement in subclass'", ")" ]
https://github.com/mtianyan/VueDjangoAntdProBookShop/blob/fd8fa2151c81edde2f8b8e6df8e1ddd799f940c2/third_party/social_core/storage.py#L155-L160
benedekrozemberczki/littleballoffur
dbfec92c0ead8c5da134c9aead7987c7a36234b4
littleballoffur/edge_sampling/randomedgesamplerwithpartialinduction.py
python
RandomEdgeSamplerWithPartialInduction.sample
(self, graph: Union[NXGraph, NKGraph])
return new_graph
Sampling edges randomly with partial induction. Arg types: * **graph** *(NetworkX or NetworKit graph)* - The graph to be sampled from. Return types: * **new_graph** *(NetworkX or NetworKit graph)* - The graph of sampled edges.
Sampling edges randomly with partial induction.
[ "Sampling", "edges", "randomly", "with", "partial", "induction", "." ]
def sample(self, graph: Union[NXGraph, NKGraph]) -> Union[NXGraph, NKGraph]: """ Sampling edges randomly with partial induction. Arg types: * **graph** *(NetworkX or NetworKit graph)* - The graph to be sampled from. Return types: * **new_graph** *(NetworkX or NetworKit graph)* - The graph of sampled edges. """ self._deploy_backend(graph) self._create_initial_set(graph) self._sample_edges() new_graph = self.backend.graph_from_edgelist(self._edges) return new_graph
[ "def", "sample", "(", "self", ",", "graph", ":", "Union", "[", "NXGraph", ",", "NKGraph", "]", ")", "->", "Union", "[", "NXGraph", ",", "NKGraph", "]", ":", "self", ".", "_deploy_backend", "(", "graph", ")", "self", ".", "_create_initial_set", "(", "gr...
https://github.com/benedekrozemberczki/littleballoffur/blob/dbfec92c0ead8c5da134c9aead7987c7a36234b4/littleballoffur/edge_sampling/randomedgesamplerwithpartialinduction.py#L64-L78
m-rtijn/mpu6050
0626053a5e1182f4951b78b8326691a9223a5f7d
mpu6050/mpu6050.py
python
mpu6050.set_filter_range
(self, filter_range=FILTER_BW_256)
return self.bus.write_byte_data(self.address, self.MPU_CONFIG, EXT_SYNC_SET | filter_range)
Sets the low-pass bandpass filter frequency
Sets the low-pass bandpass filter frequency
[ "Sets", "the", "low", "-", "pass", "bandpass", "filter", "frequency" ]
def set_filter_range(self, filter_range=FILTER_BW_256): """Sets the low-pass bandpass filter frequency""" # Keep the current EXT_SYNC_SET configuration in bits 3, 4, 5 in the MPU_CONFIG register EXT_SYNC_SET = self.bus.read_byte_data(self.address, self.MPU_CONFIG) & 0b00111000 return self.bus.write_byte_data(self.address, self.MPU_CONFIG, EXT_SYNC_SET | filter_range)
[ "def", "set_filter_range", "(", "self", ",", "filter_range", "=", "FILTER_BW_256", ")", ":", "# Keep the current EXT_SYNC_SET configuration in bits 3, 4, 5 in the MPU_CONFIG register", "EXT_SYNC_SET", "=", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "addres...
https://github.com/m-rtijn/mpu6050/blob/0626053a5e1182f4951b78b8326691a9223a5f7d/mpu6050/mpu6050.py#L194-L198
moloch--/RootTheBox
097272332b9f9b7e2df31ca0823ed10c7b66ac81
models/WallOfSheep.py
python
WallOfSheep.by_victim_id
(cls, _id)
return dbsession.query(cls).filter_by(victim_id=_id).all()
Returns all entries for a _id
Returns all entries for a _id
[ "Returns", "all", "entries", "for", "a", "_id" ]
def by_victim_id(cls, _id): """ Returns all entries for a _id """ return dbsession.query(cls).filter_by(victim_id=_id).all()
[ "def", "by_victim_id", "(", "cls", ",", "_id", ")", ":", "return", "dbsession", ".", "query", "(", "cls", ")", ".", "filter_by", "(", "victim_id", "=", "_id", ")", ".", "all", "(", ")" ]
https://github.com/moloch--/RootTheBox/blob/097272332b9f9b7e2df31ca0823ed10c7b66ac81/models/WallOfSheep.py#L63-L65
marcua/tweeql
eb8c61fb001e0b9755929f3b19be9fa16358187e
old/redis/client.py
python
Redis.sunion
(self, keys, *args)
return self.format_inline('SUNION', *keys)
Return the union of sets specifiued by ``keys``
Return the union of sets specifiued by ``keys``
[ "Return", "the", "union", "of", "sets", "specifiued", "by", "keys" ]
def sunion(self, keys, *args): "Return the union of sets specifiued by ``keys``" keys = list_or_args('sunion', keys, args) return self.format_inline('SUNION', *keys)
[ "def", "sunion", "(", "self", ",", "keys", ",", "*", "args", ")", ":", "keys", "=", "list_or_args", "(", "'sunion'", ",", "keys", ",", "args", ")", "return", "self", ".", "format_inline", "(", "'SUNION'", ",", "*", "keys", ")" ]
https://github.com/marcua/tweeql/blob/eb8c61fb001e0b9755929f3b19be9fa16358187e/old/redis/client.py#L795-L798
axnsan12/drf-yasg
d9700dbf8cc80d725a7db485c2d4446c19c29840
src/drf_yasg/codecs.py
python
_OpenAPICodec.generate_swagger_object
(self, swagger)
return swagger.as_odict()
Generates the root Swagger object. :param openapi.Swagger swagger: Swagger spec object as generated by :class:`.OpenAPISchemaGenerator` :return: swagger spec as dict :rtype: OrderedDict
Generates the root Swagger object.
[ "Generates", "the", "root", "Swagger", "object", "." ]
def generate_swagger_object(self, swagger): """Generates the root Swagger object. :param openapi.Swagger swagger: Swagger spec object as generated by :class:`.OpenAPISchemaGenerator` :return: swagger spec as dict :rtype: OrderedDict """ return swagger.as_odict()
[ "def", "generate_swagger_object", "(", "self", ",", "swagger", ")", ":", "return", "swagger", ".", "as_odict", "(", ")" ]
https://github.com/axnsan12/drf-yasg/blob/d9700dbf8cc80d725a7db485c2d4446c19c29840/src/drf_yasg/codecs.py#L97-L104
google/coursebuilder-core
08f809db3226d9269e30d5edd0edd33bd22041f4
coursebuilder/models/models.py
python
StudentPreferencesDTO.show_hooks
(self)
return self.dict.get('show_hooks', True)
Show controls to permit editing of HTML inclusions (hook points). On course pages, there are various locations (hook points) at which HTML content is inserted. Turn this setting on to see those locations with controls that permit an admin to edit that HTML, and off to see the content as a student would. Returns: True when admin wants to see edit controls, False when he doesn't.
Show controls to permit editing of HTML inclusions (hook points).
[ "Show", "controls", "to", "permit", "editing", "of", "HTML", "inclusions", "(", "hook", "points", ")", "." ]
def show_hooks(self): """Show controls to permit editing of HTML inclusions (hook points). On course pages, there are various locations (hook points) at which HTML content is inserted. Turn this setting on to see those locations with controls that permit an admin to edit that HTML, and off to see the content as a student would. Returns: True when admin wants to see edit controls, False when he doesn't. """ return self.dict.get('show_hooks', True)
[ "def", "show_hooks", "(", "self", ")", ":", "return", "self", ".", "dict", ".", "get", "(", "'show_hooks'", ",", "True", ")" ]
https://github.com/google/coursebuilder-core/blob/08f809db3226d9269e30d5edd0edd33bd22041f4/coursebuilder/models/models.py#L2659-L2670
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/Django/django/utils/dateformat.py
python
DateFormat.Y
(self)
return self.data.year
Year, 4 digits; e.g. '1999
Year, 4 digits; e.g. '1999
[ "Year", "4", "digits", ";", "e", ".", "g", ".", "1999" ]
def Y(self): "Year, 4 digits; e.g. '1999'" return self.data.year
[ "def", "Y", "(", "self", ")", ":", "return", "self", ".", "data", ".", "year" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/Django/django/utils/dateformat.py#L283-L285
BerkeleyAutomation/meshrender
25b6fb711ef7a7871a5908459e6be5c76a04b631
meshrender/viewer.py
python
SceneViewer._load_shaders
(self, vertex_shader, fragment_shader)
return shader
Load and compile shaders from strings.
Load and compile shaders from strings.
[ "Load", "and", "compile", "shaders", "from", "strings", "." ]
def _load_shaders(self, vertex_shader, fragment_shader): """Load and compile shaders from strings. """ shader = shaders.compileProgram( shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER) ) return shader
[ "def", "_load_shaders", "(", "self", ",", "vertex_shader", ",", "fragment_shader", ")", ":", "shader", "=", "shaders", ".", "compileProgram", "(", "shaders", ".", "compileShader", "(", "vertex_shader", ",", "GL_VERTEX_SHADER", ")", ",", "shaders", ".", "compileS...
https://github.com/BerkeleyAutomation/meshrender/blob/25b6fb711ef7a7871a5908459e6be5c76a04b631/meshrender/viewer.py#L536-L544
deepinsight/insightface
c0b25f998a649f662c7136eb389abcacd7900e9d
python-package/insightface/thirdparty/face3d/morphable_model/morphabel_model.py
python
MorphabelModel.fit
(self, x, X_ind, max_iter = 4, isShow = False)
return fitted_sp, fitted_ep, s, angles, t
fit 3dmm & pose parameters Args: x: (n, 2) image points X_ind: (n,) corresponding Model vertex indices max_iter: iteration isShow: whether to reserve middle results for show Returns: fitted_sp: (n_sp, 1). shape parameters fitted_ep: (n_ep, 1). exp parameters s, angles, t
fit 3dmm & pose parameters Args: x: (n, 2) image points X_ind: (n,) corresponding Model vertex indices max_iter: iteration isShow: whether to reserve middle results for show Returns: fitted_sp: (n_sp, 1). shape parameters fitted_ep: (n_ep, 1). exp parameters s, angles, t
[ "fit", "3dmm", "&", "pose", "parameters", "Args", ":", "x", ":", "(", "n", "2", ")", "image", "points", "X_ind", ":", "(", "n", ")", "corresponding", "Model", "vertex", "indices", "max_iter", ":", "iteration", "isShow", ":", "whether", "to", "reserve", ...
def fit(self, x, X_ind, max_iter = 4, isShow = False): ''' fit 3dmm & pose parameters Args: x: (n, 2) image points X_ind: (n,) corresponding Model vertex indices max_iter: iteration isShow: whether to reserve middle results for show Returns: fitted_sp: (n_sp, 1). shape parameters fitted_ep: (n_ep, 1). exp parameters s, angles, t ''' if isShow: fitted_sp, fitted_ep, s, R, t = fit.fit_points_for_show(x, X_ind, self.model, n_sp = self.n_shape_para, n_ep = self.n_exp_para, max_iter = max_iter) angles = np.zeros((R.shape[0], 3)) for i in range(R.shape[0]): angles[i] = mesh.transform.matrix2angle(R[i]) else: fitted_sp, fitted_ep, s, R, t = fit.fit_points(x, X_ind, self.model, n_sp = self.n_shape_para, n_ep = self.n_exp_para, max_iter = max_iter) angles = mesh.transform.matrix2angle(R) return fitted_sp, fitted_ep, s, angles, t
[ "def", "fit", "(", "self", ",", "x", ",", "X_ind", ",", "max_iter", "=", "4", ",", "isShow", "=", "False", ")", ":", "if", "isShow", ":", "fitted_sp", ",", "fitted_ep", ",", "s", ",", "R", ",", "t", "=", "fit", ".", "fit_points_for_show", "(", "x...
https://github.com/deepinsight/insightface/blob/c0b25f998a649f662c7136eb389abcacd7900e9d/python-package/insightface/thirdparty/face3d/morphable_model/morphabel_model.py#L121-L141
graphql-python/graphql-core
9ea9c3705d6826322027d9bb539d37c5b25f7af9
src/graphql/language/parser.py
python
Parser.parse_argument_defs
(self)
return self.optional_many( TokenKind.PAREN_L, self.parse_input_value_def, TokenKind.PAREN_R )
ArgumentsDefinition: (InputValueDefinition+)
ArgumentsDefinition: (InputValueDefinition+)
[ "ArgumentsDefinition", ":", "(", "InputValueDefinition", "+", ")" ]
def parse_argument_defs(self) -> List[InputValueDefinitionNode]: """ArgumentsDefinition: (InputValueDefinition+)""" return self.optional_many( TokenKind.PAREN_L, self.parse_input_value_def, TokenKind.PAREN_R )
[ "def", "parse_argument_defs", "(", "self", ")", "->", "List", "[", "InputValueDefinitionNode", "]", ":", "return", "self", ".", "optional_many", "(", "TokenKind", ".", "PAREN_L", ",", "self", ".", "parse_input_value_def", ",", "TokenKind", ".", "PAREN_R", ")" ]
https://github.com/graphql-python/graphql-core/blob/9ea9c3705d6826322027d9bb539d37c5b25f7af9/src/graphql/language/parser.py#L720-L724
KDD-OpenSource/DeepADoTS
88c38320141a1062301cc9255f3e0fc111f55e80
src/evaluation/evaluator.py
python
Evaluator.threshold
(self, score)
return np.nanmean(score) + 2 * np.nanstd(score)
[]
def threshold(self, score): return np.nanmean(score) + 2 * np.nanstd(score)
[ "def", "threshold", "(", "self", ",", "score", ")", ":", "return", "np", ".", "nanmean", "(", "score", ")", "+", "2", "*", "np", ".", "nanstd", "(", "score", ")" ]
https://github.com/KDD-OpenSource/DeepADoTS/blob/88c38320141a1062301cc9255f3e0fc111f55e80/src/evaluation/evaluator.py#L595-L596
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/dns/rdtypes/dsbase.py
python
DSBase.to_text
(self, origin=None, relativize=True, **kw)
return '%d %d %d %s' % (self.key_tag, self.algorithm, self.digest_type, dns.rdata._hexify(self.digest, chunksize=128))
[]
def to_text(self, origin=None, relativize=True, **kw): return '%d %d %d %s' % (self.key_tag, self.algorithm, self.digest_type, dns.rdata._hexify(self.digest, chunksize=128))
[ "def", "to_text", "(", "self", ",", "origin", "=", "None", ",", "relativize", "=", "True", ",", "*", "*", "kw", ")", ":", "return", "'%d %d %d %s'", "%", "(", "self", ".", "key_tag", ",", "self", ".", "algorithm", ",", "self", ".", "digest_type", ","...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dns/rdtypes/dsbase.py#L40-L44
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/envs/mujoco_env.py
python
MujocoEnv.get_current_obs
(self)
return self._get_full_obs()
[]
def get_current_obs(self): return self._get_full_obs()
[ "def", "get_current_obs", "(", "self", ")", ":", "return", "self", ".", "_get_full_obs", "(", ")" ]
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/envs/mujoco_env.py#L110-L111
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/lib2to3/btm_utils.py
python
get_characteristic_subpattern
(subpatterns)
return max(subpatterns, key=len)
Picks the most characteristic from a list of linear patterns Current order used is: names > common_names > common_chars
Picks the most characteristic from a list of linear patterns Current order used is: names > common_names > common_chars
[ "Picks", "the", "most", "characteristic", "from", "a", "list", "of", "linear", "patterns", "Current", "order", "used", "is", ":", "names", ">", "common_names", ">", "common_chars" ]
def get_characteristic_subpattern(subpatterns): """Picks the most characteristic from a list of linear patterns Current order used is: names > common_names > common_chars """ if not isinstance(subpatterns, list): return subpatterns if len(subpatterns)==1: return subpatterns[0] # first pick out the ones containing variable names subpatterns_with_names = [] subpatterns_with_common_names = [] common_names = ['in', 'for', 'if' , 'not', 'None'] subpatterns_with_common_chars = [] common_chars = "[]().,:" for subpattern in subpatterns: if any(rec_test(subpattern, lambda x: type(x) is str)): if any(rec_test(subpattern, lambda x: isinstance(x, str) and x in common_chars)): subpatterns_with_common_chars.append(subpattern) elif any(rec_test(subpattern, lambda x: isinstance(x, str) and x in common_names)): subpatterns_with_common_names.append(subpattern) else: subpatterns_with_names.append(subpattern) if subpatterns_with_names: subpatterns = subpatterns_with_names elif subpatterns_with_common_names: subpatterns = subpatterns_with_common_names elif subpatterns_with_common_chars: subpatterns = subpatterns_with_common_chars # of the remaining subpatterns pick out the longest one return max(subpatterns, key=len)
[ "def", "get_characteristic_subpattern", "(", "subpatterns", ")", ":", "if", "not", "isinstance", "(", "subpatterns", ",", "list", ")", ":", "return", "subpatterns", "if", "len", "(", "subpatterns", ")", "==", "1", ":", "return", "subpatterns", "[", "0", "]",...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/lib2to3/btm_utils.py#L237-L272
javayhu/Gank-Alfred-Workflow
aca39bd0c7bc0c494eee204e10bca61dab760ab7
source/workflow/workflow.py
python
Workflow._call_security
(self, action, service, account, *args)
return output
Call the ``security`` CLI app that provides access to keychains. May raise `PasswordNotFound`, `PasswordExists` or `KeychainError` exceptions (the first two are subclasses of `KeychainError`). :param action: The ``security`` action to call, e.g. ``add-generic-password`` :type action: ``unicode`` :param service: Name of the service. :type service: ``unicode`` :param account: name of the account the password is for, e.g. "Pinboard" :type account: ``unicode`` :param password: the password to secure :type password: ``unicode`` :param *args: list of command line arguments to be passed to ``security`` :type *args: `list` or `tuple` :returns: ``(retcode, output)``. ``retcode`` is an `int`, ``output`` a ``unicode`` string. :rtype: `tuple` (`int`, ``unicode``)
Call the ``security`` CLI app that provides access to keychains.
[ "Call", "the", "security", "CLI", "app", "that", "provides", "access", "to", "keychains", "." ]
def _call_security(self, action, service, account, *args): """Call the ``security`` CLI app that provides access to keychains. May raise `PasswordNotFound`, `PasswordExists` or `KeychainError` exceptions (the first two are subclasses of `KeychainError`). :param action: The ``security`` action to call, e.g. ``add-generic-password`` :type action: ``unicode`` :param service: Name of the service. :type service: ``unicode`` :param account: name of the account the password is for, e.g. "Pinboard" :type account: ``unicode`` :param password: the password to secure :type password: ``unicode`` :param *args: list of command line arguments to be passed to ``security`` :type *args: `list` or `tuple` :returns: ``(retcode, output)``. ``retcode`` is an `int`, ``output`` a ``unicode`` string. :rtype: `tuple` (`int`, ``unicode``) """ cmd = ['security', action, '-s', service, '-a', account] + list(args) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) retcode, output = p.wait(), p.stdout.read().strip().decode('utf-8') if retcode == 44: # password does not exist raise PasswordNotFound() elif retcode == 45: # password already exists raise PasswordExists() elif retcode > 0: err = KeychainError('Unknown Keychain error : %s' % output) err.retcode = retcode raise err return output
[ "def", "_call_security", "(", "self", ",", "action", ",", "service", ",", "account", ",", "*", "args", ")", ":", "cmd", "=", "[", "'security'", ",", "action", ",", "'-s'", ",", "service", ",", "'-a'", ",", "account", "]", "+", "list", "(", "args", ...
https://github.com/javayhu/Gank-Alfred-Workflow/blob/aca39bd0c7bc0c494eee204e10bca61dab760ab7/source/workflow/workflow.py#L2896-L2934
keon/algorithms
23d4e85a506eaeaff315e855be12f8dbe47a7ec3
algorithms/map/hashtable.py
python
ResizableHashTable.__init__
(self)
[]
def __init__(self): super().__init__(self.MIN_SIZE)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", "self", ".", "MIN_SIZE", ")" ]
https://github.com/keon/algorithms/blob/23d4e85a506eaeaff315e855be12f8dbe47a7ec3/algorithms/map/hashtable.py#L102-L103
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/api/core_api.py
python
CoreApi.get_api_versions_with_http_info
(self, **kwargs)
return self.api_client.call_api( '/api/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIVersions', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
get_api_versions # noqa: E501 get available API versions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_versions_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1APIVersions, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread.
get_api_versions # noqa: E501
[ "get_api_versions", "#", "noqa", ":", "E501" ]
def get_api_versions_with_http_info(self, **kwargs): # noqa: E501 """get_api_versions # noqa: E501 get available API versions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_versions_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1APIVersions, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_versions" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/api/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIVersions', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "get_api_versions_with_http_info", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "local_var_params", "=", "locals", "(", ")", "all_params", "=", "[", "]", "all_params", ".", "extend", "(", "[", "'async_req'", ",", "'_return_http_data_onl...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api/core_api.py#L63-L142
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/_pydecimal.py
python
Decimal.__rfloordiv__
(self, other, context=None)
return other.__floordiv__(self, context=context)
Swaps self/other and returns __floordiv__.
Swaps self/other and returns __floordiv__.
[ "Swaps", "self", "/", "other", "and", "returns", "__floordiv__", "." ]
def __rfloordiv__(self, other, context=None): """Swaps self/other and returns __floordiv__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__floordiv__(self, context=context)
[ "def", "__rfloordiv__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "return", "other", ".", "__floordiv__", "(", "self",...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/_pydecimal.py#L1640-L1645
microsoft/debugpy
be8dd607f6837244e0b565345e497aff7a0c08bf
src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_api.py
python
PyDevdAPI.reapply_breakpoints
(self, py_db)
Reapplies all the received breakpoints as they were received by the API (so, new translations are applied).
Reapplies all the received breakpoints as they were received by the API (so, new translations are applied).
[ "Reapplies", "all", "the", "received", "breakpoints", "as", "they", "were", "received", "by", "the", "API", "(", "so", "new", "translations", "are", "applied", ")", "." ]
def reapply_breakpoints(self, py_db): ''' Reapplies all the received breakpoints as they were received by the API (so, new translations are applied). ''' pydev_log.debug('Reapplying breakpoints.') items = dict_items(py_db.api_received_breakpoints) # Create a copy with items to reapply. self.remove_all_breakpoints(py_db, '*') for _key, val in items: _new_filename, api_add_breakpoint_params = val self.add_breakpoint(py_db, *api_add_breakpoint_params)
[ "def", "reapply_breakpoints", "(", "self", ",", "py_db", ")", ":", "pydev_log", ".", "debug", "(", "'Reapplying breakpoints.'", ")", "items", "=", "dict_items", "(", "py_db", ".", "api_received_breakpoints", ")", "# Create a copy with items to reapply.", "self", ".", ...
https://github.com/microsoft/debugpy/blob/be8dd607f6837244e0b565345e497aff7a0c08bf/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_api.py#L575-L585
angeladai/ScanComplete
7ab7b48e5688b3b71c99bdb64b3424e06b064312
src/reader.py
python
ReadSceneBlocksLevel
(data_filepattern, train_samples, dim_block, height_block, stored_dim_block, stored_height_block, is_base_level, hierarchy_level, num_quant_levels, params, quantize=False, shuffle=True, num_epochs=None)
return (input_blocks, target_blocks, target_sem_blocks, target_lo_blocks, target_sem_lo_blocks)
Reads a batch of block examples from the SSTable files. Args: data_filepattern: String matching input files. train_samples: Train on previous model predictions. dim_block: x/z dimension of train block. height_block: y dimension of train block. stored_dim_block: Stored data x/z dimension (high-resolution). stored_height_block: Stored data y dimension (high-resolution). is_base_level: Whether there are no previous hierarchy levels. hierarchy_level: hierarchy level (1 is finest). num_quant_levels: Number of quantization bins (if used). params: Parameter dictionary. quantize: Whether to quantize data. shuffle: Whether to shuffle. num_epochs: Number of times to go over the input. Returns: 5-D tensor input batches of shape [batch_size, dim_input, height_input, dim_input, 2], dtype tf.float32. 5-D tensor target batches of shape [batch_size, dim_target, height_target, dim_target, 2], dtype tf.float32. 5-D tensor target semantics batches of shape [batch_size, dim_target, height_target, dim_target], dtype tf.uint8. (optionally) 5-D tensor low-resolution target batches of shape [batch_size, dim_target//2, height_target//2, dim_target//2, 2], dtype tf.float32. (optionally) 5-D tensor low-resolution target semantics batches of shape [batch_size, dim_target//2, height_target//2, dim_target//2], dtype tf.uint8.
Reads a batch of block examples from the SSTable files.
[ "Reads", "a", "batch", "of", "block", "examples", "from", "the", "SSTable", "files", "." ]
def ReadSceneBlocksLevel(data_filepattern, train_samples, dim_block, height_block, stored_dim_block, stored_height_block, is_base_level, hierarchy_level, num_quant_levels, params, quantize=False, shuffle=True, num_epochs=None): """Reads a batch of block examples from the SSTable files. Args: data_filepattern: String matching input files. train_samples: Train on previous model predictions. dim_block: x/z dimension of train block. height_block: y dimension of train block. stored_dim_block: Stored data x/z dimension (high-resolution). stored_height_block: Stored data y dimension (high-resolution). is_base_level: Whether there are no previous hierarchy levels. hierarchy_level: hierarchy level (1 is finest). num_quant_levels: Number of quantization bins (if used). params: Parameter dictionary. quantize: Whether to quantize data. shuffle: Whether to shuffle. num_epochs: Number of times to go over the input. Returns: 5-D tensor input batches of shape [batch_size, dim_input, height_input, dim_input, 2], dtype tf.float32. 5-D tensor target batches of shape [batch_size, dim_target, height_target, dim_target, 2], dtype tf.float32. 5-D tensor target semantics batches of shape [batch_size, dim_target, height_target, dim_target], dtype tf.uint8. (optionally) 5-D tensor low-resolution target batches of shape [batch_size, dim_target//2, height_target//2, dim_target//2, 2], dtype tf.float32. (optionally) 5-D tensor low-resolution target semantics batches of shape [batch_size, dim_target//2, height_target//2, dim_target//2], dtype tf.uint8. """ assert (stored_dim_block >= dim_block and stored_height_block >= height_block) read_target_lo = not is_base_level _, examples, samples_lo, samples_sem_lo = _ReadBlockExample( data_filepattern, train_samples=train_samples, hierarchy_level=hierarchy_level, is_base_level=is_base_level, shuffle=shuffle, num_epochs=num_epochs, stored_dim_block=stored_dim_block, stored_height_block=stored_height_block) # jitter height (must be even) jitter = (np.random.random_integers( low=0, high=_HEIGHT_JITTER[hierarchy_level - 1]) // 2) * 2 # extract relevant portion of data block as per input/target dim key_input = _RESOLUTIONS[hierarchy_level - 1] + '_' + _INPUT_FEATURE key_target = _RESOLUTIONS[hierarchy_level - 1] + '_' + _TARGET_FEATURE key_target_sem = _RESOLUTIONS[hierarchy_level - 1] + '_' + _TARGET_SEM_FEATURE #key_input = 'input_sdf' #key_target = 'target_df' #key_target_sem = 'target_sem' input_sdf_blocks = examples[key_input] input_sdf_blocks = preprocessor.extract_block( input_sdf_blocks, dim_block, height_block, dim_block, 1, jitter) input_blocks = preprocessor.preprocess_sdf(input_sdf_blocks, constants.TRUNCATION) target_df_blocks = examples[key_target] target_df_blocks = preprocessor.extract_block( target_df_blocks, dim_block, height_block, dim_block, 1, jitter) target_blocks = preprocessor.preprocess_target_sdf( target_df_blocks, num_quant_levels, constants.TRUNCATION, quantize) if read_target_lo: if train_samples: target_lo_blocks = samples_lo else: key_target_lo = _RESOLUTIONS[hierarchy_level] + '_' + _TARGET_FEATURE target_lo_blocks = examples[key_target_lo] target_lo_blocks = preprocessor.extract_block( target_lo_blocks, dim_block // 2, height_block // 2, dim_block // 2, 1, jitter // 2) target_lo_blocks = preprocessor.preprocess_target_sdf( target_lo_blocks, num_quant_levels, constants.TRUNCATION, quantize) target_sem_blocks = tf.decode_raw(examples[key_target_sem], tf.uint8) target_sem_blocks = tf.reshape( target_sem_blocks, [stored_dim_block, stored_height_block, stored_dim_block]) target_sem_blocks = preprocessor.extract_block( target_sem_blocks, dim_block, height_block, dim_block, 1, jitter) target_sem_blocks = preprocessor.preprocess_target_sem(target_sem_blocks) if read_target_lo: if train_samples: target_sem_lo_blocks = tf.decode_raw(samples_sem_lo, tf.uint8) else: key_target_sem_lo = ( _RESOLUTIONS[hierarchy_level] + '_' + _TARGET_SEM_FEATURE) target_sem_lo_blocks = tf.decode_raw(examples[key_target_sem_lo], tf.uint8) target_sem_lo_blocks = tf.reshape(target_sem_lo_blocks, [ stored_dim_block // 2, stored_height_block // 2, stored_dim_block // 2 ]) target_sem_lo_blocks = preprocessor.extract_block( target_sem_lo_blocks, dim_block // 2, height_block // 2, dim_block // 2, 1, jitter // 2) if not train_samples: target_sem_lo_blocks = preprocessor.preprocess_target_sem( target_sem_lo_blocks) blocks = [input_blocks, target_blocks, target_sem_blocks] if read_target_lo: blocks.append(target_lo_blocks) blocks.append(target_sem_lo_blocks) if shuffle: batched = tf.train.shuffle_batch( blocks, batch_size=params['batch_size'], num_threads=64, capacity=params['batch_size'] * 100, min_after_dequeue=params['batch_size'] * 4) else: batched = tf.train.batch( blocks, batch_size=params['batch_size'], num_threads=16, capacity=params['batch_size']) input_blocks = batched[0] target_blocks = batched[1] target_sem_blocks = batched[2] target_lo_blocks = None target_sem_lo_blocks = None if read_target_lo: target_lo_blocks = batched[3] target_sem_lo_blocks = batched[4] return (input_blocks, target_blocks, target_sem_blocks, target_lo_blocks, target_sem_lo_blocks)
[ "def", "ReadSceneBlocksLevel", "(", "data_filepattern", ",", "train_samples", ",", "dim_block", ",", "height_block", ",", "stored_dim_block", ",", "stored_height_block", ",", "is_base_level", ",", "hierarchy_level", ",", "num_quant_levels", ",", "params", ",", "quantize...
https://github.com/angeladai/ScanComplete/blob/7ab7b48e5688b3b71c99bdb64b3424e06b064312/src/reader.py#L16-L164
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/lxml/html/html5parser.py
python
fromstring
(html, guess_charset=None, parser=None)
return body
Parse the html, returning a single element/document. This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document. 'base_url' will set the document's base_url attribute (and the tree's docinfo.URL) If `guess_charset` is true, or if the input is not Unicode but a byte string, the `chardet` library will perform charset guessing on the string.
Parse the html, returning a single element/document.
[ "Parse", "the", "html", "returning", "a", "single", "element", "/", "document", "." ]
def fromstring(html, guess_charset=None, parser=None): """Parse the html, returning a single element/document. This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document. 'base_url' will set the document's base_url attribute (and the tree's docinfo.URL) If `guess_charset` is true, or if the input is not Unicode but a byte string, the `chardet` library will perform charset guessing on the string. """ if not isinstance(html, _strings): raise TypeError('string required') doc = document_fromstring(html, parser=parser, guess_charset=guess_charset) # document starts with doctype or <html>, full document! start = html[:50] if isinstance(start, bytes): # Allow text comparison in python3. # Decode as ascii, that also covers latin-1 and utf-8 for the # characters we need. start = start.decode('ascii', 'replace') start = start.lstrip().lower() if start.startswith('<html') or start.startswith('<!doctype'): return doc head = _find_tag(doc, 'head') # if the head is not empty we have a full document if len(head): return doc body = _find_tag(doc, 'body') # The body has just one element, so it was probably a single # element passed in if (len(body) == 1 and (not body.text or not body.text.strip()) and (not body[-1].tail or not body[-1].tail.strip())): return body[0] # Now we have a body which represents a bunch of tags which have the # content that was passed in. We will create a fake container, which # is the body tag, except <body> implies too much structure. if _contains_block_level_tag(body): body.tag = 'div' else: body.tag = 'span' return body
[ "def", "fromstring", "(", "html", ",", "guess_charset", "=", "None", ",", "parser", "=", "None", ")", ":", "if", "not", "isinstance", "(", "html", ",", "_strings", ")", ":", "raise", "TypeError", "(", "'string required'", ")", "doc", "=", "document_fromstr...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/lxml/html/html5parser.py#L157-L208
ijkguo/mx-rcnn
e556bb4e0209c2ce55386be8f701115538c3f010
symimdb/coco.py
python
coco._write_coco_results
(self, _coco, detections)
example results [{"image_id": 42, "category_id": 18, "bbox": [258.15,41.29,348.26,243.78], "score": 0.236}, ...]
example results [{"image_id": 42, "category_id": 18, "bbox": [258.15,41.29,348.26,243.78], "score": 0.236}, ...]
[ "example", "results", "[", "{", "image_id", ":", "42", "category_id", ":", "18", "bbox", ":", "[", "258", ".", "15", "41", ".", "29", "348", ".", "26", "243", ".", "78", "]", "score", ":", "0", ".", "236", "}", "...", "]" ]
def _write_coco_results(self, _coco, detections): """ example results [{"image_id": 42, "category_id": 18, "bbox": [258.15,41.29,348.26,243.78], "score": 0.236}, ...] """ cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())] class_to_coco_ind = dict(zip(cats, _coco.getCatIds())) results = [] for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue logger.info('collecting %s results (%d/%d)' % (cls, cls_ind, self.num_classes - 1)) coco_cat_id = class_to_coco_ind[cls] results.extend(self._coco_results_one_category(detections[cls_ind], coco_cat_id)) logger.info('writing results json to %s' % self._result_file) with open(self._result_file, 'w') as f: json.dump(results, f, sort_keys=True, indent=4)
[ "def", "_write_coco_results", "(", "self", ",", "_coco", ",", "detections", ")", ":", "cats", "=", "[", "cat", "[", "'name'", "]", "for", "cat", "in", "_coco", ".", "loadCats", "(", "_coco", ".", "getCatIds", "(", ")", ")", "]", "class_to_coco_ind", "=...
https://github.com/ijkguo/mx-rcnn/blob/e556bb4e0209c2ce55386be8f701115538c3f010/symimdb/coco.py#L115-L133
garethdmm/gryphon
73e19fa2d0b64c3fc7dac9e0036fc92e25e5b694
gryphon/lib/assets.py
python
transaction_position_query
(db, amount_field, currency_field, transaction_type=None, start_time=None, end_time=None, include_pending=False, exchange_ids=[])
return query_result_to_position(result)
This sums up a transaction Money field which can have multiple currencies. Takes an optional transaction_type to filter on deposits or withdrawals Returns a multi-currency Position object
This sums up a transaction Money field which can have multiple currencies.
[ "This", "sums", "up", "a", "transaction", "Money", "field", "which", "can", "have", "multiple", "currencies", "." ]
def transaction_position_query(db, amount_field, currency_field, transaction_type=None, start_time=None, end_time=None, include_pending=False, exchange_ids=[]): """ This sums up a transaction Money field which can have multiple currencies. Takes an optional transaction_type to filter on deposits or withdrawals Returns a multi-currency Position object """ # See comment on trade_position_query above query = db.query(currency_field, func.sum(amount_field)) if include_pending: query = query.filter(or_( Transaction.transaction_status == Transaction.COMPLETED, Transaction.transaction_status == Transaction.IN_TRANSIT, )) else: query = query.filter(Transaction.transaction_status == Transaction.COMPLETED) if transaction_type: query = query.filter(Transaction.transaction_type == transaction_type) if start_time: # when include_pending is True we treat all transactions as being completed # on their creation time (i.e. instantly) if include_pending: query = query.filter(Transaction.time_created > start_time) else: query = query.filter(or_( and_( Transaction.time_completed != None, Transaction.time_completed > start_time, ), and_( Transaction.time_completed == None, Transaction.time_created > start_time, ), )) if end_time: if include_pending: query = query.filter(Transaction.time_created <= end_time) else: # We include transactions in the ledger based on when they were completed, # not created. This is an issue because we only started recording # time_completed on 2015-10-08. So for these pre-time_completed # transactions we use their time_created instead. query = query.filter(or_( and_( Transaction.time_completed != None, Transaction.time_completed <= end_time, ), and_( Transaction.time_completed == None, Transaction.time_created <= end_time, ), )) if exchange_ids: query = query.filter(Transaction.exchange_id.in_(exchange_ids)) query = query.group_by(currency_field) result = query.all() return query_result_to_position(result)
[ "def", "transaction_position_query", "(", "db", ",", "amount_field", ",", "currency_field", ",", "transaction_type", "=", "None", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "include_pending", "=", "False", ",", "exchange_ids", "=", "[", ...
https://github.com/garethdmm/gryphon/blob/73e19fa2d0b64c3fc7dac9e0036fc92e25e5b694/gryphon/lib/assets.py#L325-L390
tenpy/tenpy
bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff
tenpy/networks/site.py
python
Site.multiply_operators
(self, operators)
return op
Multiply local operators (possibly given by their names) together. Parameters ---------- operators : list of {str | :class:`~tenpy.linalg.np_conserved.Array`} List of valid operator names (to be translated with :meth:`get_op`) or directly on-site operators in the form of npc arrays with ``'p', 'p*'`` label. The operators are multiplied left-to-right. Returns ------- combined_operator : :class:`~tenpy.linalg.np_conserved.Array` The product of the given `operators` in a left-to-right multiplication following the usual mathematical convention. For example, if ``operators=['Sz', 'Sp', 'Sx']``, the final operator is equivalent to ``site.get_op('Sz Sp Sx')``, with the ``'Sx'`` operator acting first on any physical state.
Multiply local operators (possibly given by their names) together.
[ "Multiply", "local", "operators", "(", "possibly", "given", "by", "their", "names", ")", "together", "." ]
def multiply_operators(self, operators): """Multiply local operators (possibly given by their names) together. Parameters ---------- operators : list of {str | :class:`~tenpy.linalg.np_conserved.Array`} List of valid operator names (to be translated with :meth:`get_op`) or directly on-site operators in the form of npc arrays with ``'p', 'p*'`` label. The operators are multiplied left-to-right. Returns ------- combined_operator : :class:`~tenpy.linalg.np_conserved.Array` The product of the given `operators` in a left-to-right multiplication following the usual mathematical convention. For example, if ``operators=['Sz', 'Sp', 'Sx']``, the final operator is equivalent to ``site.get_op('Sz Sp Sx')``, with the ``'Sx'`` operator acting first on any physical state. """ if len(operators) == 0: return self.Id op = operators[0] if isinstance(op, str): op = self.get_op(op) for next_op in operators[1:]: if isinstance(next_op, str): next_op = self.get_op(next_op) op = npc.tensordot(op, next_op, axes=['p*', 'p']) return op
[ "def", "multiply_operators", "(", "self", ",", "operators", ")", ":", "if", "len", "(", "operators", ")", "==", "0", ":", "return", "self", ".", "Id", "op", "=", "operators", "[", "0", "]", "if", "isinstance", "(", "op", ",", "str", ")", ":", "op",...
https://github.com/tenpy/tenpy/blob/bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff/tenpy/networks/site.py#L440-L467
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/http/client.py
python
HTTPMessage.getallmatchingheaders
(self, name)
return lst
Find all header lines matching a given header name. Look through the list of headers and find all lines matching a given header name (and their continuation lines). A list of the lines is returned, without interpretation. If the header does not occur, an empty list is returned. If the header occurs multiple times, all occurrences are returned. Case is not important in the header name.
Find all header lines matching a given header name.
[ "Find", "all", "header", "lines", "matching", "a", "given", "header", "name", "." ]
def getallmatchingheaders(self, name): """Find all header lines matching a given header name. Look through the list of headers and find all lines matching a given header name (and their continuation lines). A list of the lines is returned, without interpretation. If the header does not occur, an empty list is returned. If the header occurs multiple times, all occurrences are returned. Case is not important in the header name. """ name = name.lower() + ':' n = len(name) lst = [] hit = 0 for line in self.keys(): if line[:n].lower() == name: hit = 1 elif not line[:1].isspace(): hit = 0 if hit: lst.append(line) return lst
[ "def", "getallmatchingheaders", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "+", "':'", "n", "=", "len", "(", "name", ")", "lst", "=", "[", "]", "hit", "=", "0", "for", "line", "in", "self", ".", "keys", "("...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/http/client.py#L156-L177
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/tensorflow/model.py
python
TensorFlowPredictor.regress
(self, data)
return self._classify_or_regress(data, "regress")
Placeholder docstring.
Placeholder docstring.
[ "Placeholder", "docstring", "." ]
def regress(self, data): """Placeholder docstring.""" return self._classify_or_regress(data, "regress")
[ "def", "regress", "(", "self", ",", "data", ")", ":", "return", "self", ".", "_classify_or_regress", "(", "data", ",", "\"regress\"", ")" ]
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/tensorflow/model.py#L81-L83
scikit-video/scikit-video
87c7113a84b50679d9853ba81ba34b557f516b05
skvideo/utils/xmltodict.py
python
parse
(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', **kwargs)
return handler.item
Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like object. If `xml_attribs` is `True`, element attributes are put in the dictionary among regular child elements, using `@` as a prefix to avoid collisions. If set to `False`, they are just ignored. Simple example:: >>> import xmltodict >>> doc = xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a> ... \"\"\") >>> doc['a']['@prop'] u'x' >>> doc['a']['b'] [u'1', u'2'] If `item_depth` is `0`, the function returns a dictionary for the root element (default behavior). Otherwise, it calls `item_callback` every time an item at the specified depth is found and returns `None` in the end (streaming mode). The callback function receives two parameters: the `path` from the document root to the item (name-attribs pairs), and the `item` (dict). If the callback's return value is false-ish, parsing will be stopped with the :class:`ParsingInterrupted` exception. Streaming example:: >>> def handle(path, item): ... print 'path:%s item:%s' % (path, item) ... return True ... >>> xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a>\"\"\", item_depth=2, item_callback=handle) path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1 path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2 The optional argument `postprocessor` is a function that takes `path`, `key` and `value` as positional arguments and returns a new `(key, value)` pair where both `key` and `value` may have changed. Usage example:: >>> def postprocessor(path, key, value): ... try: ... return key + ':int', int(value) ... except (ValueError, TypeError): ... return key, value >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>', ... postprocessor=postprocessor) OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))]) You can pass an alternate version of `expat` (such as `defusedexpat`) by using the `expat` parameter. E.g: >>> import defusedexpat >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat) OrderedDict([(u'a', u'hello')]) You can use the force_list argument to force lists to be created even when there is only a single child of a given level of hierarchy. The force_list argument is a tuple of keys. If the key for a given level of hierarchy is in the force_list argument, that level of hierarchy will have a list as a child (even if there is only one sub-element). The index_keys operation takes precendence over this. This is applied after any user-supplied postprocessor has already run. For example, given this input: <servers> <server> <name>host1</name> <os>Linux</os> <interfaces> <interface> <name>em0</name> <ip_address>10.0.0.1</ip_address> </interface> </interfaces> </server> </servers> If called with force_list=('interface',), it will produce this dictionary: {'servers': {'server': {'name': 'host1', 'os': 'Linux'}, 'interfaces': {'interface': [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } }
Parse the given XML input and convert it into a dictionary.
[ "Parse", "the", "given", "XML", "input", "and", "convert", "it", "into", "a", "dictionary", "." ]
def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', **kwargs): """Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like object. If `xml_attribs` is `True`, element attributes are put in the dictionary among regular child elements, using `@` as a prefix to avoid collisions. If set to `False`, they are just ignored. Simple example:: >>> import xmltodict >>> doc = xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a> ... \"\"\") >>> doc['a']['@prop'] u'x' >>> doc['a']['b'] [u'1', u'2'] If `item_depth` is `0`, the function returns a dictionary for the root element (default behavior). Otherwise, it calls `item_callback` every time an item at the specified depth is found and returns `None` in the end (streaming mode). The callback function receives two parameters: the `path` from the document root to the item (name-attribs pairs), and the `item` (dict). If the callback's return value is false-ish, parsing will be stopped with the :class:`ParsingInterrupted` exception. Streaming example:: >>> def handle(path, item): ... print 'path:%s item:%s' % (path, item) ... return True ... >>> xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a>\"\"\", item_depth=2, item_callback=handle) path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1 path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2 The optional argument `postprocessor` is a function that takes `path`, `key` and `value` as positional arguments and returns a new `(key, value)` pair where both `key` and `value` may have changed. Usage example:: >>> def postprocessor(path, key, value): ... try: ... return key + ':int', int(value) ... except (ValueError, TypeError): ... return key, value >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>', ... postprocessor=postprocessor) OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))]) You can pass an alternate version of `expat` (such as `defusedexpat`) by using the `expat` parameter. E.g: >>> import defusedexpat >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat) OrderedDict([(u'a', u'hello')]) You can use the force_list argument to force lists to be created even when there is only a single child of a given level of hierarchy. The force_list argument is a tuple of keys. If the key for a given level of hierarchy is in the force_list argument, that level of hierarchy will have a list as a child (even if there is only one sub-element). The index_keys operation takes precendence over this. This is applied after any user-supplied postprocessor has already run. For example, given this input: <servers> <server> <name>host1</name> <os>Linux</os> <interfaces> <interface> <name>em0</name> <ip_address>10.0.0.1</ip_address> </interface> </interfaces> </server> </servers> If called with force_list=('interface',), it will produce this dictionary: {'servers': {'server': {'name': 'host1', 'os': 'Linux'}, 'interfaces': {'interface': [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } } """ handler = _DictSAXHandler(namespace_separator=namespace_separator, **kwargs) if isinstance(xml_input, _unicode): if not encoding: encoding = 'utf-8' xml_input = xml_input.encode(encoding) if not process_namespaces: namespace_separator = None parser = expat.ParserCreate( encoding, namespace_separator ) try: parser.ordered_attributes = True except AttributeError: # Jython's expat does not support ordered_attributes pass parser.StartElementHandler = handler.startElement parser.EndElementHandler = handler.endElement parser.CharacterDataHandler = handler.characters parser.buffer_text = True try: parser.ParseFile(xml_input) except (TypeError, AttributeError): parser.Parse(xml_input, True) return handler.item
[ "def", "parse", "(", "xml_input", ",", "encoding", "=", "None", ",", "expat", "=", "expat", ",", "process_namespaces", "=", "False", ",", "namespace_separator", "=", "':'", ",", "*", "*", "kwargs", ")", ":", "handler", "=", "_DictSAXHandler", "(", "namespa...
https://github.com/scikit-video/scikit-video/blob/87c7113a84b50679d9853ba81ba34b557f516b05/skvideo/utils/xmltodict.py#L176-L301
rucio/rucio
6d0d358e04f5431f0b9a98ae40f31af0ddff4833
lib/rucio/client/dq2client.py
python
DQ2Client.getDatasetSize
(self, dsn, scope)
return size
Used to get the dataset size @param dsn: is the dataset name. @param scope: is the dataset scope. B{Exceptions:} - DataIdentifierNotFound is raised in case the dataset name doesn't exist. @return: Size as integer
Used to get the dataset size
[ "Used", "to", "get", "the", "dataset", "size" ]
def getDatasetSize(self, dsn, scope): """ Used to get the dataset size @param dsn: is the dataset name. @param scope: is the dataset scope. B{Exceptions:} - DataIdentifierNotFound is raised in case the dataset name doesn't exist. @return: Size as integer """ size = 0 for f in self.client.list_files(scope=scope, name=dsn): size += f['bytes'] return size
[ "def", "getDatasetSize", "(", "self", ",", "dsn", ",", "scope", ")", ":", "size", "=", "0", "for", "f", "in", "self", ".", "client", ".", "list_files", "(", "scope", "=", "scope", ",", "name", "=", "dsn", ")", ":", "size", "+=", "f", "[", "'bytes...
https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/client/dq2client.py#L336-L351
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/mysql/db_system_client_composite_operations.py
python
DbSystemClientCompositeOperations.delete_analytics_cluster_and_wait_for_state
(self, db_system_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={})
Calls :py:func:`~oci.mysql.DbSystemClient.delete_analytics_cluster` and waits for the :py:class:`~oci.mysql.models.WorkRequest` to enter the given state(s). :param str db_system_id: (required) The DB System `OCID`__. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.mysql.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.mysql.DbSystemClient.delete_analytics_cluster` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
Calls :py:func:`~oci.mysql.DbSystemClient.delete_analytics_cluster` and waits for the :py:class:`~oci.mysql.models.WorkRequest` to enter the given state(s).
[ "Calls", ":", "py", ":", "func", ":", "~oci", ".", "mysql", ".", "DbSystemClient", ".", "delete_analytics_cluster", "and", "waits", "for", "the", ":", "py", ":", "class", ":", "~oci", ".", "mysql", ".", "models", ".", "WorkRequest", "to", "enter", "the",...
def delete_analytics_cluster_and_wait_for_state(self, db_system_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.mysql.DbSystemClient.delete_analytics_cluster` and waits for the :py:class:`~oci.mysql.models.WorkRequest` to enter the given state(s). :param str db_system_id: (required) The DB System `OCID`__. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.mysql.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.mysql.DbSystemClient.delete_analytics_cluster` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = None try: operation_result = self.client.delete_analytics_cluster(db_system_id, **operation_kwargs) except oci.exceptions.ServiceError as e: if e.status == 404: return WAIT_RESOURCE_NOT_FOUND else: raise e if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
[ "def", "delete_analytics_cluster_and_wait_for_state", "(", "self", ",", "db_system_id", ",", "wait_for_states", "=", "[", "]", ",", "operation_kwargs", "=", "{", "}", ",", "waiter_kwargs", "=", "{", "}", ")", ":", "operation_result", "=", "None", "try", ":", "...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/mysql/db_system_client_composite_operations.py#L150-L196
facebookresearch/ParlAI
e4d59c30eef44f1f67105961b82a83fd28d7d78b
parlai/agents/rag/modules.py
python
RagModel.seq2seq_forward_pass
( self, xs: torch.LongTensor, ys: torch.LongTensor )
return logits, preds, encoder_states
Simulate a standard seq2seq encoder/decoder forward pass. Used in thorough decoding. :param xs: input tokens :param ys: teacher forced decoder outputs :return (logits, preds, encoder_states): logits: token output distribution preds: max probability token at each output position encoder_states: output states from the encoder
Simulate a standard seq2seq encoder/decoder forward pass.
[ "Simulate", "a", "standard", "seq2seq", "encoder", "/", "decoder", "forward", "pass", "." ]
def seq2seq_forward_pass( self, xs: torch.LongTensor, ys: torch.LongTensor ) -> Tuple[torch.Tensor, torch.Tensor, Tuple[Any, ...]]: """ Simulate a standard seq2seq encoder/decoder forward pass. Used in thorough decoding. :param xs: input tokens :param ys: teacher forced decoder outputs :return (logits, preds, encoder_states): logits: token output distribution preds: max probability token at each output position encoder_states: output states from the encoder """ encoder_states = self.seq2seq_encoder(xs) # type: ignore bsz = ys.size(0) seqlen = ys.size(1) inputs = ys.narrow(1, 0, seqlen - 1) dec_inputs = self._rag_model_interface.get_initial_forced_decoder_input( bsz, inputs, n_docs=1, start_idx=self.START_IDX, end_idx=self.END_IDX, input_turns_cnt=None, ) latent, _ = self.seq2seq_decoder( dec_inputs, encoder_states, None ) # type: ignore logits = self.decoder_output(latent) _, preds = logits.max(dim=-1) return logits, preds, encoder_states
[ "def", "seq2seq_forward_pass", "(", "self", ",", "xs", ":", "torch", ".", "LongTensor", ",", "ys", ":", "torch", ".", "LongTensor", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", ",", "Tuple", "[", "Any", ",", "...", "]...
https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/agents/rag/modules.py#L238-L273
xmengli/H-DenseUNet
06cc436a43196310fe933d114a353839907cc176
Keras-2.0.8/keras/backend/theano_backend.py
python
batch_flatten
(x)
return y
Turn a n-D tensor into a 2D tensor where the first dimension is conserved.
Turn a n-D tensor into a 2D tensor where the first dimension is conserved.
[ "Turn", "a", "n", "-", "D", "tensor", "into", "a", "2D", "tensor", "where", "the", "first", "dimension", "is", "conserved", "." ]
def batch_flatten(x): """Turn a n-D tensor into a 2D tensor where the first dimension is conserved. """ y = T.reshape(x, (x.shape[0], T.prod(x.shape[1:]))) if hasattr(x, '_keras_shape'): if None in x._keras_shape[1:]: y._keras_shape = (x._keras_shape[0], None) else: y._keras_shape = (x._keras_shape[0], np.prod(x._keras_shape[1:])) return y
[ "def", "batch_flatten", "(", "x", ")", ":", "y", "=", "T", ".", "reshape", "(", "x", ",", "(", "x", ".", "shape", "[", "0", "]", ",", "T", ".", "prod", "(", "x", ".", "shape", "[", "1", ":", "]", ")", ")", ")", "if", "hasattr", "(", "x", ...
https://github.com/xmengli/H-DenseUNet/blob/06cc436a43196310fe933d114a353839907cc176/Keras-2.0.8/keras/backend/theano_backend.py#L993-L1003
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/campaign_experiment_service/transports/grpc.py
python
CampaignExperimentServiceGrpcTransport.__init__
( self, *, host: str = "googleads.googleapis.com", credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, )
Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason.
Instantiate the transport.
[ "Instantiate", "the", "transport", "." ]
def __init__( self, *, host: str = "googleads.googleapis.com", credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, )
[ "def", "__init__", "(", "self", ",", "*", ",", "host", ":", "str", "=", "\"googleads.googleapis.com\"", ",", "credentials", ":", "credentials", ".", "Credentials", "=", "None", ",", "credentials_file", ":", "str", "=", "None", ",", "scopes", ":", "Sequence",...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/campaign_experiment_service/transports/grpc.py#L60-L188
biolab/orange2
db40a9449cb45b507d63dcd5739b223f9cffb8e6
Orange/OrangeCanvas/scheme/scheme.py
python
Scheme.annotations
(self)
return list(self.__annotations)
A list of all annotations (:class:`.BaseSchemeAnnotation`) in the scheme.
A list of all annotations (:class:`.BaseSchemeAnnotation`) in the scheme.
[ "A", "list", "of", "all", "annotations", "(", ":", "class", ":", ".", "BaseSchemeAnnotation", ")", "in", "the", "scheme", "." ]
def annotations(self): """ A list of all annotations (:class:`.BaseSchemeAnnotation`) in the scheme. """ return list(self.__annotations)
[ "def", "annotations", "(", "self", ")", ":", "return", "list", "(", "self", ".", "__annotations", ")" ]
https://github.com/biolab/orange2/blob/db40a9449cb45b507d63dcd5739b223f9cffb8e6/Orange/OrangeCanvas/scheme/scheme.py#L121-L127
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/compute/manager.py
python
ComputeManager.host_maintenance_mode
(self, context, host, mode)
return self.driver.host_maintenance_mode(host, mode)
Start/Stop host maintenance window. On start, it triggers guest VMs evacuation.
Start/Stop host maintenance window. On start, it triggers guest VMs evacuation.
[ "Start", "/", "Stop", "host", "maintenance", "window", ".", "On", "start", "it", "triggers", "guest", "VMs", "evacuation", "." ]
def host_maintenance_mode(self, context, host, mode): """Start/Stop host maintenance window. On start, it triggers guest VMs evacuation.""" return self.driver.host_maintenance_mode(host, mode)
[ "def", "host_maintenance_mode", "(", "self", ",", "context", ",", "host", ",", "mode", ")", ":", "return", "self", ".", "driver", ".", "host_maintenance_mode", "(", "host", ",", "mode", ")" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/compute/manager.py#L2595-L2598
haiwen/seahub
e92fcd44e3e46260597d8faa9347cb8222b8b10d
scripts/build/build-pro.py
python
check_targz_src_no_version
(proj, srcdir)
[]
def check_targz_src_no_version(proj, srcdir): src_tarball = os.path.join(srcdir, '%s.tar.gz' % proj) if not os.path.exists(src_tarball): error('%s not exists' % src_tarball)
[ "def", "check_targz_src_no_version", "(", "proj", ",", "srcdir", ")", ":", "src_tarball", "=", "os", ".", "path", ".", "join", "(", "srcdir", ",", "'%s.tar.gz'", "%", "proj", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "src_tarball", ")", ...
https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/scripts/build/build-pro.py#L358-L361
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/set/src/core/scapy.py
python
Dot1Q.default_payload_class
(self, pay)
return Raw
[]
def default_payload_class(self, pay): if self.type <= 1500: return LLC return Raw
[ "def", "default_payload_class", "(", "self", ",", "pay", ")", ":", "if", "self", ".", "type", "<=", "1500", ":", "return", "LLC", "return", "Raw" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/set/src/core/scapy.py#L6129-L6132
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
python
rename_partition_result.__repr__
(self)
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
[]
def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
[ "def", "__repr__", "(", "self", ")", ":", "L", "=", "[", "'%s=%r'", "%", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", "]", "return", "'%s(%s)'", "%", "(", "self", ".", "__class_...
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L23158-L23161
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/hardware/crs/bits.py
python
DisplayPlusPlusTouch.getTouchEvent
(self, N=0, distance=None, t=None, type=None)
return value
Scans the touch log to return the Nth touch event. You need to run getTouchLog before you run this function. Returns as list of Dict like structures with members time, x, y, and dir time is the time stamp of the event. x and y are the x and y locations of the event. direction is the type of event: 'touched', 'released' These values can be read as a structure: res=getTouchResponses(3) res[0].dir, res[0].x, res[0].time or dictionary res[0]['dir'], res[0]['x'], res[0]['time'] Example: bits.startTouchLog() while not event: #do some processing continue bits.stopTouchLog() bits.getTouchLog() res=bits.getTouchEvent(N=10, distance=20, time=0.001, type='touched') print(res.time) Will extract the 10th touch events (ingnoreing releases) that are 20 pixels and 1 ms apart.
Scans the touch log to return the Nth touch event. You need to run getTouchLog before you run this function. Returns as list of Dict like structures with members time, x, y, and dir time is the time stamp of the event. x and y are the x and y locations of the event. direction is the type of event: 'touched', 'released' These values can be read as a structure: res=getTouchResponses(3) res[0].dir, res[0].x, res[0].time or dictionary res[0]['dir'], res[0]['x'], res[0]['time'] Example: bits.startTouchLog() while not event: #do some processing continue bits.stopTouchLog() bits.getTouchLog() res=bits.getTouchEvent(N=10, distance=20, time=0.001, type='touched') print(res.time) Will extract the 10th touch events (ingnoreing releases) that are 20 pixels and 1 ms apart.
[ "Scans", "the", "touch", "log", "to", "return", "the", "Nth", "touch", "event", ".", "You", "need", "to", "run", "getTouchLog", "before", "you", "run", "this", "function", ".", "Returns", "as", "list", "of", "Dict", "like", "structures", "with", "members",...
def getTouchEvent(self, N=0, distance=None, t=None, type=None): """ Scans the touch log to return the Nth touch event. You need to run getTouchLog before you run this function. Returns as list of Dict like structures with members time, x, y, and dir time is the time stamp of the event. x and y are the x and y locations of the event. direction is the type of event: 'touched', 'released' These values can be read as a structure: res=getTouchResponses(3) res[0].dir, res[0].x, res[0].time or dictionary res[0]['dir'], res[0]['x'], res[0]['time'] Example: bits.startTouchLog() while not event: #do some processing continue bits.stopTouchLog() bits.getTouchLog() res=bits.getTouchEvent(N=10, distance=20, time=0.001, type='touched') print(res.time) Will extract the 10th touch events (ingnoreing releases) that are 20 pixels and 1 ms apart. """ values = self.getTouchEvents(distance, t, type) value = values[N] return value
[ "def", "getTouchEvent", "(", "self", ",", "N", "=", "0", ",", "distance", "=", "None", ",", "t", "=", "None", ",", "type", "=", "None", ")", ":", "values", "=", "self", ".", "getTouchEvents", "(", "distance", ",", "t", ",", "type", ")", "value", ...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/hardware/crs/bits.py#L5187-L5219
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/core/management/base.py
python
AppCommand.add_arguments
(self, parser)
[]
def add_arguments(self, parser): parser.add_argument('args', metavar='app_label', nargs='+', help='One or more application label.')
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'args'", ",", "metavar", "=", "'app_label'", ",", "nargs", "=", "'+'", ",", "help", "=", "'One or more application label.'", ")" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/core/management/base.py#L465-L466
aws/aws-sam-cli
2aa7bf01b2e0b0864ef63b1898a8b30577443acc
samcli/lib/bootstrap/companion_stack/data_types.py
python
CompanionStack.escaped_parent_stack_name
(self)
return self._escaped_parent_stack_name
Parent stack name with only alphanumeric characters
Parent stack name with only alphanumeric characters
[ "Parent", "stack", "name", "with", "only", "alphanumeric", "characters" ]
def escaped_parent_stack_name(self) -> str: """ Parent stack name with only alphanumeric characters """ return self._escaped_parent_stack_name
[ "def", "escaped_parent_stack_name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_escaped_parent_stack_name" ]
https://github.com/aws/aws-sam-cli/blob/2aa7bf01b2e0b0864ef63b1898a8b30577443acc/samcli/lib/bootstrap/companion_stack/data_types.py#L38-L42
mongodb/mongo-python-driver
c760f900f2e4109a247c2ffc8ad3549362007772
pymongo/pool.py
python
SocketInfo.add_server_api
(self, command)
Add server_api parameters.
Add server_api parameters.
[ "Add", "server_api", "parameters", "." ]
def add_server_api(self, command): """Add server_api parameters.""" if self.opts.server_api: _add_to_command(command, self.opts.server_api)
[ "def", "add_server_api", "(", "self", ",", "command", ")", ":", "if", "self", ".", "opts", ".", "server_api", ":", "_add_to_command", "(", "command", ",", "self", ".", "opts", ".", "server_api", ")" ]
https://github.com/mongodb/mongo-python-driver/blob/c760f900f2e4109a247c2ffc8ad3549362007772/pymongo/pool.py#L850-L853
zaxlct/imooc-django
daf1ced745d3d21989e8191b658c293a511b37fd
extra_apps/xadmin/views/dashboard.py
python
ModelChoiceField.__deepcopy__
(self, memo)
return result
[]
def __deepcopy__(self, memo): result = forms.Field.__deepcopy__(self, memo) return result
[ "def", "__deepcopy__", "(", "self", ",", "memo", ")", ":", "result", "=", "forms", ".", "Field", ".", "__deepcopy__", "(", "self", ",", "memo", ")", "return", "result" ]
https://github.com/zaxlct/imooc-django/blob/daf1ced745d3d21989e8191b658c293a511b37fd/extra_apps/xadmin/views/dashboard.py#L285-L287
Azure/azure-linux-extensions
a42ef718c746abab2b3c6a21da87b29e76364558
VMEncryption/main/ResourceDiskUtil.py
python
ResourceDiskUtil._configure_fstab
(self)
return True
remove resource disk from /etc/fstab if present
remove resource disk from /etc/fstab if present
[ "remove", "resource", "disk", "from", "/", "etc", "/", "fstab", "if", "present" ]
def _configure_fstab(self): """ remove resource disk from /etc/fstab if present """ cmd = "sed -i.bak '/azure_resource-part1/d' /etc/fstab" if self.executor.ExecuteInBash(cmd) != CommonVariables.process_success: self.logger.log(msg="Failed to configure resource disk entry of /etc/fstab", level=CommonVariables.WarningLevel) return False return True
[ "def", "_configure_fstab", "(", "self", ")", ":", "cmd", "=", "\"sed -i.bak '/azure_resource-part1/d' /etc/fstab\"", "if", "self", ".", "executor", ".", "ExecuteInBash", "(", "cmd", ")", "!=", "CommonVariables", ".", "process_success", ":", "self", ".", "logger", ...
https://github.com/Azure/azure-linux-extensions/blob/a42ef718c746abab2b3c6a21da87b29e76364558/VMEncryption/main/ResourceDiskUtil.py#L114-L120
chipmuenk/pyfda
665310b8548a940a575c0e5ff4bba94608d9ac26
pyfda/libs/tree_builder.py
python
Tree_Builder.build_fil_tree
(self, fc, rt_dict, fil_tree=None)
return fil_tree
Read attributes (ft, rt, rt:fo) from filter class fc) Attributes are stored in the design method classes in the format (example from ``common.py``) .. code-block:: python self.ft = 'IIR' self.rt_dict = { 'LP': {'man':{'fo': ('a','N'), 'msg': ('a', r"<br /><b>Note:</b> Read this!"), 'fspecs': ('a','F_C'), 'tspecs': ('u', {'frq':('u','F_PB','F_SB'), 'amp':('u','A_PB','A_SB')}) }, 'min':{'fo': ('d','N'), 'fspecs': ('d','F_C'), 'tspecs': ('a', {'frq':('a','F_PB','F_SB'), 'amp':('a','A_PB','A_SB')}) } }, 'HP': {'man':{'fo': ('a','N'), 'fspecs': ('a','F_C'), 'tspecs': ('u', {'frq':('u','F_SB','F_PB'), 'amp':('u','A_SB','A_PB')}) }, 'min':{'fo': ('d','N'), 'fspecs': ('d','F_C'), 'tspecs': ('a', {'frq':('a','F_SB','F_PB'), 'amp':('a','A_SB','A_PB')}) } } } Build a dictionary of all filter combinations with the following hierarchy: response types -> filter types -> filter classes -> filter order rt (e.g. 'LP') ft (e.g. 'IIR') fc (e.g. 'cheby1') fo ('min' or 'man') All attributes found for fc are arranged in a dict, e.g. for ``cheby1.LPman`` and ``cheby1.LPmin``, listing the parameters to be displayed and whether they are active, unused, disabled or invisible for each subwidget: .. code-block:: python 'LP':{ 'IIR':{ 'Cheby1':{ 'man':{'fo': ('a','N'), 'msg': ('a', r"<br /><b>Note:</b> Read this!"), 'fspecs': ('a','F_C'), 'tspecs': ('u', {'frq':('u','F_PB','F_SB'), 'amp':('u','A_PB','A_SB')}) }, 'min':{'fo': ('d','N'), 'fspecs': ('d','F_C'), 'tspecs': ('a', {'frq':('a','F_PB','F_SB'), 'amp':('a','A_PB','A_SB')}) } } } }, ... Finally, the whole structure is frozen recursively to avoid inadvertedly changing the filter tree. For a full example, see the default filter tree ``fb.fil_tree`` defined in ``filterbroker.py``. Parameters ---------- None Returns ------- dict filter tree
Read attributes (ft, rt, rt:fo) from filter class fc) Attributes are stored in the design method classes in the format (example from ``common.py``)
[ "Read", "attributes", "(", "ft", "rt", "rt", ":", "fo", ")", "from", "filter", "class", "fc", ")", "Attributes", "are", "stored", "in", "the", "design", "method", "classes", "in", "the", "format", "(", "example", "from", "common", ".", "py", ")" ]
def build_fil_tree(self, fc, rt_dict, fil_tree=None): """ Read attributes (ft, rt, rt:fo) from filter class fc) Attributes are stored in the design method classes in the format (example from ``common.py``) .. code-block:: python self.ft = 'IIR' self.rt_dict = { 'LP': {'man':{'fo': ('a','N'), 'msg': ('a', r"<br /><b>Note:</b> Read this!"), 'fspecs': ('a','F_C'), 'tspecs': ('u', {'frq':('u','F_PB','F_SB'), 'amp':('u','A_PB','A_SB')}) }, 'min':{'fo': ('d','N'), 'fspecs': ('d','F_C'), 'tspecs': ('a', {'frq':('a','F_PB','F_SB'), 'amp':('a','A_PB','A_SB')}) } }, 'HP': {'man':{'fo': ('a','N'), 'fspecs': ('a','F_C'), 'tspecs': ('u', {'frq':('u','F_SB','F_PB'), 'amp':('u','A_SB','A_PB')}) }, 'min':{'fo': ('d','N'), 'fspecs': ('d','F_C'), 'tspecs': ('a', {'frq':('a','F_SB','F_PB'), 'amp':('a','A_SB','A_PB')}) } } } Build a dictionary of all filter combinations with the following hierarchy: response types -> filter types -> filter classes -> filter order rt (e.g. 'LP') ft (e.g. 'IIR') fc (e.g. 'cheby1') fo ('min' or 'man') All attributes found for fc are arranged in a dict, e.g. for ``cheby1.LPman`` and ``cheby1.LPmin``, listing the parameters to be displayed and whether they are active, unused, disabled or invisible for each subwidget: .. code-block:: python 'LP':{ 'IIR':{ 'Cheby1':{ 'man':{'fo': ('a','N'), 'msg': ('a', r"<br /><b>Note:</b> Read this!"), 'fspecs': ('a','F_C'), 'tspecs': ('u', {'frq':('u','F_PB','F_SB'), 'amp':('u','A_PB','A_SB')}) }, 'min':{'fo': ('d','N'), 'fspecs': ('d','F_C'), 'tspecs': ('a', {'frq':('a','F_PB','F_SB'), 'amp':('a','A_PB','A_SB')}) } } } }, ... Finally, the whole structure is frozen recursively to avoid inadvertedly changing the filter tree. For a full example, see the default filter tree ``fb.fil_tree`` defined in ``filterbroker.py``. Parameters ---------- None Returns ------- dict filter tree """ if not fil_tree: fil_tree = {} ft = ff.fil_inst.ft # get filter type (e.g. 'FIR') for rt in rt_dict: # iterate over all response types if rt == 'COM': # handle common info later continue if rt not in fil_tree: # is response type already in dict? fil_tree.update({rt: {}}) # no, create it if ft not in fil_tree[rt]: # filter type already in dict[rt]? fil_tree[rt].update({ft: {}}) # no, create it if fc not in fil_tree[rt][ft]: # filter class already in dict[rt][ft]? fil_tree[rt][ft].update({fc: {}}) # no, create it # now append all the individual 'min' / 'man' subwidget infos to fc: fil_tree[rt][ft][fc].update(rt_dict[rt]) if 'COM' in rt_dict: # Now handle common info for fo in rt_dict[rt]: # iterate over 'min' / 'max' if fo in rt_dict['COM']: # and add common info first merge_dicts(fil_tree[rt][ft][fc][fo], rt_dict['COM'][fo], mode='add2') return fil_tree
[ "def", "build_fil_tree", "(", "self", ",", "fc", ",", "rt_dict", ",", "fil_tree", "=", "None", ")", ":", "if", "not", "fil_tree", ":", "fil_tree", "=", "{", "}", "ft", "=", "ff", ".", "fil_inst", ".", "ft", "# get filter type (e.g. 'FIR')", "for", "rt", ...
https://github.com/chipmuenk/pyfda/blob/665310b8548a940a575c0e5ff4bba94608d9ac26/pyfda/libs/tree_builder.py#L600-L709
openstack/nova
b49b7663e1c3073917d5844b81d38db8e86d05c4
nova/virt/libvirt/volume/fibrechannel.py
python
LibvirtFibreChannelVolumeDriver.disconnect_volume
(self, connection_info, instance)
Detach the volume from instance_name.
Detach the volume from instance_name.
[ "Detach", "the", "volume", "from", "instance_name", "." ]
def disconnect_volume(self, connection_info, instance): """Detach the volume from instance_name.""" LOG.debug("calling os-brick to detach FC Volume", instance=instance) # TODO(walter-boring) eliminated the need for preserving # multipath_id. Use scsi_id instead of multipath -ll # This will then eliminate the need to pass anything in # the 2nd param of disconnect_volume and be consistent # with the rest of the connectors. self.connector.disconnect_volume(connection_info['data'], connection_info['data']) LOG.debug("Disconnected FC Volume", instance=instance) super(LibvirtFibreChannelVolumeDriver, self).disconnect_volume(connection_info, instance)
[ "def", "disconnect_volume", "(", "self", ",", "connection_info", ",", "instance", ")", ":", "LOG", ".", "debug", "(", "\"calling os-brick to detach FC Volume\"", ",", "instance", "=", "instance", ")", "# TODO(walter-boring) eliminated the need for preserving", "# multipath_...
https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/virt/libvirt/volume/fibrechannel.py#L62-L76
littlecodersh/ItChat
d5ce5db32ca15cef8eefa548a438a9fcc4502a6d
itchat/components/login.py
python
web_init
(self)
return dic
[]
def web_init(self): url = '%s/webwxinit' % self.loginInfo['url'] params = { 'r': int(-time.time() / 1579), 'pass_ticket': self.loginInfo['pass_ticket'], } data = { 'BaseRequest': self.loginInfo['BaseRequest'], } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT, } r = self.s.post(url, params=params, data=json.dumps(data), headers=headers) dic = json.loads(r.content.decode('utf-8', 'replace')) # deal with login info utils.emoji_formatter(dic['User'], 'NickName') self.loginInfo['InviteStartCount'] = int(dic['InviteStartCount']) self.loginInfo['User'] = wrap_user_dict(utils.struct_friend_info(dic['User'])) self.memberList.append(self.loginInfo['User']) self.loginInfo['SyncKey'] = dic['SyncKey'] self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val']) for item in dic['SyncKey']['List']]) self.storageClass.userName = dic['User']['UserName'] self.storageClass.nickName = dic['User']['NickName'] # deal with contact list returned when init contactList = dic.get('ContactList', []) chatroomList, otherList = [], [] for m in contactList: if m['Sex'] != 0: otherList.append(m) elif '@@' in m['UserName']: m['MemberList'] = [] # don't let dirty info pollute the list chatroomList.append(m) elif '@' in m['UserName']: # mp will be dealt in update_local_friends as well otherList.append(m) if chatroomList: update_local_chatrooms(self, chatroomList) if otherList: update_local_friends(self, otherList) return dic
[ "def", "web_init", "(", "self", ")", ":", "url", "=", "'%s/webwxinit'", "%", "self", ".", "loginInfo", "[", "'url'", "]", "params", "=", "{", "'r'", ":", "int", "(", "-", "time", ".", "time", "(", ")", "/", "1579", ")", ",", "'pass_ticket'", ":", ...
https://github.com/littlecodersh/ItChat/blob/d5ce5db32ca15cef8eefa548a438a9fcc4502a6d/itchat/components/login.py#L188-L225
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/src/gdata/tlslite/Session.py
python
Session.valid
(self)
return self.resumable or self.sharedKey
If this session can be used for session resumption. @rtype: bool @return: If this session can be used for session resumption.
If this session can be used for session resumption.
[ "If", "this", "session", "can", "be", "used", "for", "session", "resumption", "." ]
def valid(self): """If this session can be used for session resumption. @rtype: bool @return: If this session can be used for session resumption. """ return self.resumable or self.sharedKey
[ "def", "valid", "(", "self", ")", ":", "return", "self", ".", "resumable", "or", "self", ".", "sharedKey" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/gdata/tlslite/Session.py#L76-L82
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/quadratic_forms/quadratic_form__automorphisms.py
python
_compute_automorphisms
(self)
Call PARI to compute the automorphism group of the quadratic form. This uses :pari:`qfauto`. OUTPUT: None, this just caches the result. TESTS:: sage: DiagonalQuadraticForm(ZZ, [-1,1,1])._compute_automorphisms() Traceback (most recent call last): ... ValueError: not a definite form in QuadraticForm.automorphisms() sage: DiagonalQuadraticForm(GF(5), [1,1,1])._compute_automorphisms() Traceback (most recent call last): ... NotImplementedError: computing the automorphism group of a quadratic form is only supported over ZZ
Call PARI to compute the automorphism group of the quadratic form.
[ "Call", "PARI", "to", "compute", "the", "automorphism", "group", "of", "the", "quadratic", "form", "." ]
def _compute_automorphisms(self): """ Call PARI to compute the automorphism group of the quadratic form. This uses :pari:`qfauto`. OUTPUT: None, this just caches the result. TESTS:: sage: DiagonalQuadraticForm(ZZ, [-1,1,1])._compute_automorphisms() Traceback (most recent call last): ... ValueError: not a definite form in QuadraticForm.automorphisms() sage: DiagonalQuadraticForm(GF(5), [1,1,1])._compute_automorphisms() Traceback (most recent call last): ... NotImplementedError: computing the automorphism group of a quadratic form is only supported over ZZ """ if self.base_ring() is not ZZ: raise NotImplementedError("computing the automorphism group of a quadratic form is only supported over ZZ") if not self.is_definite(): raise ValueError("not a definite form in QuadraticForm.automorphisms()") if hasattr(self, "__automorphisms_pari"): return A = self.__pari__().qfauto() self.__number_of_automorphisms = A[0] self.__automorphisms_pari = A[1]
[ "def", "_compute_automorphisms", "(", "self", ")", ":", "if", "self", ".", "base_ring", "(", ")", "is", "not", "ZZ", ":", "raise", "NotImplementedError", "(", "\"computing the automorphism group of a quadratic form is only supported over ZZ\"", ")", "if", "not", "self",...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/quadratic_forms/quadratic_form__automorphisms.py#L260-L289
inducer/pudb
82a0017982f20917c17989a0cb2b71c54ee90ba7
pudb/debugger.py
python
Debugger.user_return
(self, frame, return_value)
This function is called when a return trap is set here.
This function is called when a return trap is set here.
[ "This", "function", "is", "called", "when", "a", "return", "trap", "is", "set", "here", "." ]
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" if frame.f_code.co_name != "<module>": frame.f_locals["__return__"] = return_value if self._wait_for_mainpyfile: if (self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno <= 0): return self._wait_for_mainpyfile = False self.bottom_frame = frame if "__exc_tuple__" not in frame.f_locals: self.interaction(frame)
[ "def", "user_return", "(", "self", ",", "frame", ",", "return_value", ")", ":", "if", "frame", ".", "f_code", ".", "co_name", "!=", "\"<module>\"", ":", "frame", ".", "f_locals", "[", "\"__return__\"", "]", "=", "return_value", "if", "self", ".", "_wait_fo...
https://github.com/inducer/pudb/blob/82a0017982f20917c17989a0cb2b71c54ee90ba7/pudb/debugger.py#L459-L472
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
varloc_t._consume_scattered
(self, *args)
return _idaapi.varloc_t__consume_scattered(self, *args)
_consume_scattered(self, p) -> bool
_consume_scattered(self, p) -> bool
[ "_consume_scattered", "(", "self", "p", ")", "-", ">", "bool" ]
def _consume_scattered(self, *args): """ _consume_scattered(self, p) -> bool """ return _idaapi.varloc_t__consume_scattered(self, *args)
[ "def", "_consume_scattered", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "varloc_t__consume_scattered", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L32249-L32253
noxrepo/pox
5f82461e01f8822bd7336603b361bff4ffbd2380
pox/datapaths/switch.py
python
SoftwareSwitchBase._rx_packet_out
(self, packet_out, connection)
Handles packet_outs
Handles packet_outs
[ "Handles", "packet_outs" ]
def _rx_packet_out (self, packet_out, connection): """ Handles packet_outs """ self.log.debug("Packet out details: %s", packet_out.show()) if packet_out.data: self._process_actions_for_packet(packet_out.actions, packet_out.data, packet_out.in_port, packet_out) elif packet_out.buffer_id is not None: self._process_actions_for_packet_from_buffer(packet_out.actions, packet_out.buffer_id, packet_out) else: self.log.warn("packet_out: No data and no buffer_id -- " "don't know what to send")
[ "def", "_rx_packet_out", "(", "self", ",", "packet_out", ",", "connection", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Packet out details: %s\"", ",", "packet_out", ".", "show", "(", ")", ")", "if", "packet_out", ".", "data", ":", "self", ".", "...
https://github.com/noxrepo/pox/blob/5f82461e01f8822bd7336603b361bff4ffbd2380/pox/datapaths/switch.py#L312-L327
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/valuation/trivial_valuation.py
python
TrivialValuationFactory.create_key
(self, domain)
return domain,
r""" Create a key that identifies this valuation. EXAMPLES:: sage: valuations.TrivialValuation(QQ) is valuations.TrivialValuation(QQ) # indirect doctest True
r""" Create a key that identifies this valuation.
[ "r", "Create", "a", "key", "that", "identifies", "this", "valuation", "." ]
def create_key(self, domain): r""" Create a key that identifies this valuation. EXAMPLES:: sage: valuations.TrivialValuation(QQ) is valuations.TrivialValuation(QQ) # indirect doctest True """ return domain,
[ "def", "create_key", "(", "self", ",", "domain", ")", ":", "return", "domain", "," ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/valuation/trivial_valuation.py#L56-L66
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
citrix_hypervisor/datadog_checks/citrix_hypervisor/config_models/shared.py
python
SharedConfig._initial_validation
(cls, values)
return validation.core.initialize_config(getattr(validators, 'initialize_shared', identity)(values))
[]
def _initial_validation(cls, values): return validation.core.initialize_config(getattr(validators, 'initialize_shared', identity)(values))
[ "def", "_initial_validation", "(", "cls", ",", "values", ")", ":", "return", "validation", ".", "core", ".", "initialize_config", "(", "getattr", "(", "validators", ",", "'initialize_shared'", ",", "identity", ")", "(", "values", ")", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/citrix_hypervisor/datadog_checks/citrix_hypervisor/config_models/shared.py#L41-L42
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/werkzeug/debug/tbtools.py
python
Frame.get_annotated_lines
(self)
return lines
Helper function that returns lines with extra information.
Helper function that returns lines with extra information.
[ "Helper", "function", "that", "returns", "lines", "with", "extra", "information", "." ]
def get_annotated_lines(self): """Helper function that returns lines with extra information.""" lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)] # find function definition and mark lines if hasattr(self.code, "co_firstlineno"): lineno = self.code.co_firstlineno - 1 while lineno > 0: if _funcdef_re.match(lines[lineno].code): break lineno -= 1 try: offset = len(inspect.getblock([x.code + "\n" for x in lines[lineno:]])) except TokenError: offset = 0 for line in lines[lineno : lineno + offset]: line.in_frame = True # mark current line try: lines[self.lineno - 1].current = True except IndexError: pass return lines
[ "def", "get_annotated_lines", "(", "self", ")", ":", "lines", "=", "[", "Line", "(", "idx", "+", "1", ",", "x", ")", "for", "idx", ",", "x", "in", "enumerate", "(", "self", ".", "sourcelines", ")", "]", "# find function definition and mark lines", "if", ...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/werkzeug/debug/tbtools.py#L524-L548
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/naming.py
python
ConventionDict._key_referred_table_name
(self)
return reftable
[]
def _key_referred_table_name(self): fk = self.const.elements[0] refs = fk.target_fullname.split(".") if len(refs) == 3: refschema, reftable, refcol = refs else: reftable, refcol = refs return reftable
[ "def", "_key_referred_table_name", "(", "self", ")", ":", "fk", "=", "self", ".", "const", ".", "elements", "[", "0", "]", "refs", "=", "fk", ".", "target_fullname", ".", "split", "(", "\".\"", ")", "if", "len", "(", "refs", ")", "==", "3", ":", "r...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/naming.py#L57-L64