repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
project-rig/rig | rig/machine_control/bmp_controller.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/bmp_controller.py#L125-L145 | def send_scp(self, *args, **kwargs):
"""Transmit an SCP Packet to a specific board.
Automatically determines the appropriate connection to use.
See the arguments for
:py:meth:`~rig.machine_control.scp_connection.SCPConnection` for
details.
Parameters
----------
cabinet : int
frame : int
board : int
"""
# Retrieve contextual arguments from the keyword arguments. The
# context system ensures that these values are present.
cabinet = kwargs.pop("cabinet")
frame = kwargs.pop("frame")
board = kwargs.pop("board")
return self._send_scp(cabinet, frame, board, *args, **kwargs) | [
"def",
"send_scp",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Retrieve contextual arguments from the keyword arguments. The",
"# context system ensures that these values are present.",
"cabinet",
"=",
"kwargs",
".",
"pop",
"(",
"\"cabinet\"",
")... | Transmit an SCP Packet to a specific board.
Automatically determines the appropriate connection to use.
See the arguments for
:py:meth:`~rig.machine_control.scp_connection.SCPConnection` for
details.
Parameters
----------
cabinet : int
frame : int
board : int | [
"Transmit",
"an",
"SCP",
"Packet",
"to",
"a",
"specific",
"board",
"."
] | python | train |
DataDog/integrations-core | ntp/datadog_checks/ntp/ntp.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/ntp/datadog_checks/ntp/ntp.py#L23-L36 | def _get_service_port(self, instance):
"""
Get the ntp server port
"""
host = instance.get('host', DEFAULT_HOST)
port = instance.get('port', DEFAULT_PORT)
# default port is the name of the service but lookup would fail
# if the /etc/services file is missing. In that case, fallback to numeric
try:
socket.getaddrinfo(host, port)
except socket.gaierror:
port = DEFAULT_PORT_NUM
return port | [
"def",
"_get_service_port",
"(",
"self",
",",
"instance",
")",
":",
"host",
"=",
"instance",
".",
"get",
"(",
"'host'",
",",
"DEFAULT_HOST",
")",
"port",
"=",
"instance",
".",
"get",
"(",
"'port'",
",",
"DEFAULT_PORT",
")",
"# default port is the name of the s... | Get the ntp server port | [
"Get",
"the",
"ntp",
"server",
"port"
] | python | train |
eruvanos/openbrokerapi | openbrokerapi/service_broker.py | https://github.com/eruvanos/openbrokerapi/blob/29d514e5932f2eac27e03995dd41c8cecf40bb10/openbrokerapi/service_broker.py#L296-L306 | def update(self, instance_id: str, details: UpdateDetails, async_allowed: bool) -> UpdateServiceSpec:
"""
Further readings `CF Broker API#Update <https://docs.cloudfoundry.org/services/api.html#updating_service_instance>`_
:param instance_id: Instance id provided by the platform
:param details: Details about the service to update
:param async_allowed: Client allows async creation
:rtype: UpdateServiceSpec
:raises ErrAsyncRequired: If async is required but not supported
"""
raise NotImplementedError() | [
"def",
"update",
"(",
"self",
",",
"instance_id",
":",
"str",
",",
"details",
":",
"UpdateDetails",
",",
"async_allowed",
":",
"bool",
")",
"->",
"UpdateServiceSpec",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Further readings `CF Broker API#Update <https://docs.cloudfoundry.org/services/api.html#updating_service_instance>`_
:param instance_id: Instance id provided by the platform
:param details: Details about the service to update
:param async_allowed: Client allows async creation
:rtype: UpdateServiceSpec
:raises ErrAsyncRequired: If async is required but not supported | [
"Further",
"readings",
"CF",
"Broker",
"API#Update",
"<https",
":",
"//",
"docs",
".",
"cloudfoundry",
".",
"org",
"/",
"services",
"/",
"api",
".",
"html#updating_service_instance",
">",
"_"
] | python | train |
gwastro/pycbc-glue | pycbc_glue/segments.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1141-L1152 | def all_intersects_all(self, other):
"""
Returns True if self and other have the same keys, and each
segmentlist intersects the corresponding segmentlist in the
other; returns False if this is not the case or if either
dictionary is empty.
See also:
.intersects(), .all_intersects(), .intersects_all()
"""
return set(self) == set(other) and all(other[key].intersects(value) for key, value in self.iteritems()) and bool(self) | [
"def",
"all_intersects_all",
"(",
"self",
",",
"other",
")",
":",
"return",
"set",
"(",
"self",
")",
"==",
"set",
"(",
"other",
")",
"and",
"all",
"(",
"other",
"[",
"key",
"]",
".",
"intersects",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in"... | Returns True if self and other have the same keys, and each
segmentlist intersects the corresponding segmentlist in the
other; returns False if this is not the case or if either
dictionary is empty.
See also:
.intersects(), .all_intersects(), .intersects_all() | [
"Returns",
"True",
"if",
"self",
"and",
"other",
"have",
"the",
"same",
"keys",
"and",
"each",
"segmentlist",
"intersects",
"the",
"corresponding",
"segmentlist",
"in",
"the",
"other",
";",
"returns",
"False",
"if",
"this",
"is",
"not",
"the",
"case",
"or",
... | python | train |
openpaperwork/paperwork-backend | paperwork_backend/img/page.py | https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/img/page.py#L95-L120 | def __get_boxes(self):
"""
Get all the word boxes of this page.
"""
boxfile = self.__box_path
try:
box_builder = pyocr.builders.LineBoxBuilder()
with self.fs.open(boxfile, 'r') as file_desc:
boxes = box_builder.read_file(file_desc)
if boxes != []:
return boxes
# fallback: old format: word boxes
# shouldn't be used anymore ...
box_builder = pyocr.builders.WordBoxBuilder()
with self.fs.open(boxfile, 'r') as file_desc:
boxes = box_builder.read_file(file_desc)
if len(boxes) <= 0:
return []
logger.warning("WARNING: Doc %s uses old box format" %
(str(self.doc)))
return [pyocr.builders.LineBox(boxes, boxes[0].position)]
except IOError as exc:
logger.error("Unable to get boxes for '%s': %s"
% (self.doc.docid, exc))
return [] | [
"def",
"__get_boxes",
"(",
"self",
")",
":",
"boxfile",
"=",
"self",
".",
"__box_path",
"try",
":",
"box_builder",
"=",
"pyocr",
".",
"builders",
".",
"LineBoxBuilder",
"(",
")",
"with",
"self",
".",
"fs",
".",
"open",
"(",
"boxfile",
",",
"'r'",
")",
... | Get all the word boxes of this page. | [
"Get",
"all",
"the",
"word",
"boxes",
"of",
"this",
"page",
"."
] | python | train |
jantman/awslimitchecker | awslimitchecker/services/elb.py | https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/awslimitchecker/services/elb.py#L225-L249 | def _update_usage_for_nlb(self, conn, nlb_arn, nlb_name):
"""
Update usage for a single NLB.
:param conn: elbv2 API connection
:type conn: :py:class:`ElasticLoadBalancing.Client`
:param nlb_arn: Load Balancer ARN
:type nlb_arn: str
:param nlb_name: Load Balancer Name
:type nlb_name: str
"""
logger.debug('Updating usage for NLB %s', nlb_arn)
listeners = paginate_dict(
conn.describe_listeners,
LoadBalancerArn=nlb_arn,
alc_marker_path=['NextMarker'],
alc_data_path=['Listeners'],
alc_marker_param='Marker'
)['Listeners']
self.limits[
'Listeners per network load balancer']._add_current_usage(
len(listeners),
aws_type='AWS::ElasticLoadBalancingV2::NetworkLoadBalancer',
resource_id=nlb_name
) | [
"def",
"_update_usage_for_nlb",
"(",
"self",
",",
"conn",
",",
"nlb_arn",
",",
"nlb_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Updating usage for NLB %s'",
",",
"nlb_arn",
")",
"listeners",
"=",
"paginate_dict",
"(",
"conn",
".",
"describe_listeners",
",",
... | Update usage for a single NLB.
:param conn: elbv2 API connection
:type conn: :py:class:`ElasticLoadBalancing.Client`
:param nlb_arn: Load Balancer ARN
:type nlb_arn: str
:param nlb_name: Load Balancer Name
:type nlb_name: str | [
"Update",
"usage",
"for",
"a",
"single",
"NLB",
"."
] | python | train |
mohamedattahri/PyXMLi | pyxmli/__init__.py | https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/__init__.py#L624-L632 | def __set_identifier(self, value):
'''
Sets the ID of the invoice.
@param value:str
'''
if not value or not len(value):
raise ValueError("Invalid invoice ID")
self.__identifier = value | [
"def",
"__set_identifier",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"not",
"len",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid invoice ID\"",
")",
"self",
".",
"__identifier",
"=",
"value"
] | Sets the ID of the invoice.
@param value:str | [
"Sets",
"the",
"ID",
"of",
"the",
"invoice",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/zmq/session.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L438-L492 | def serialize(self, msg, ident=None):
"""Serialize the message components to bytes.
This is roughly the inverse of unserialize. The serialize/unserialize
methods work with full message lists, whereas pack/unpack work with
the individual message parts in the message list.
Parameters
----------
msg : dict or Message
The nexted message dict as returned by the self.msg method.
Returns
-------
msg_list : list
The list of bytes objects to be sent with the format:
[ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content,
buffer1,buffer2,...]. In this list, the p_* entities are
the packed or serialized versions, so if JSON is used, these
are utf8 encoded JSON strings.
"""
content = msg.get('content', {})
if content is None:
content = self.none
elif isinstance(content, dict):
content = self.pack(content)
elif isinstance(content, bytes):
# content is already packed, as in a relayed message
pass
elif isinstance(content, unicode):
# should be bytes, but JSON often spits out unicode
content = content.encode('utf8')
else:
raise TypeError("Content incorrect type: %s"%type(content))
real_message = [self.pack(msg['header']),
self.pack(msg['parent_header']),
content
]
to_send = []
if isinstance(ident, list):
# accept list of idents
to_send.extend(ident)
elif ident is not None:
to_send.append(ident)
to_send.append(DELIM)
signature = self.sign(real_message)
to_send.append(signature)
to_send.extend(real_message)
return to_send | [
"def",
"serialize",
"(",
"self",
",",
"msg",
",",
"ident",
"=",
"None",
")",
":",
"content",
"=",
"msg",
".",
"get",
"(",
"'content'",
",",
"{",
"}",
")",
"if",
"content",
"is",
"None",
":",
"content",
"=",
"self",
".",
"none",
"elif",
"isinstance"... | Serialize the message components to bytes.
This is roughly the inverse of unserialize. The serialize/unserialize
methods work with full message lists, whereas pack/unpack work with
the individual message parts in the message list.
Parameters
----------
msg : dict or Message
The nexted message dict as returned by the self.msg method.
Returns
-------
msg_list : list
The list of bytes objects to be sent with the format:
[ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content,
buffer1,buffer2,...]. In this list, the p_* entities are
the packed or serialized versions, so if JSON is used, these
are utf8 encoded JSON strings. | [
"Serialize",
"the",
"message",
"components",
"to",
"bytes",
"."
] | python | test |
prompt-toolkit/pymux | pymux/client/posix.py | https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/client/posix.py#L160-L173 | def _process_stdin(self):
"""
Received data on stdin. Read and send to server.
"""
with nonblocking(sys.stdin.fileno()):
data = self._stdin_reader.read()
# Send input in chunks of 4k.
step = 4056
for i in range(0, len(data), step):
self._send_packet({
'cmd': 'in',
'data': data[i:i + step],
}) | [
"def",
"_process_stdin",
"(",
"self",
")",
":",
"with",
"nonblocking",
"(",
"sys",
".",
"stdin",
".",
"fileno",
"(",
")",
")",
":",
"data",
"=",
"self",
".",
"_stdin_reader",
".",
"read",
"(",
")",
"# Send input in chunks of 4k.",
"step",
"=",
"4056",
"f... | Received data on stdin. Read and send to server. | [
"Received",
"data",
"on",
"stdin",
".",
"Read",
"and",
"send",
"to",
"server",
"."
] | python | train |
tcalmant/ipopo | pelix/ipopo/handlers/provides.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L154-L187 | def _field_controller_generator(self):
"""
Generates the methods called by the injected controller
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
"""
Retrieves the controller value, from the iPOPO dictionaries
:param name: The property name
:return: The property value
"""
return stored_instance.get_controller_state(name)
def set_value(self, name, new_value):
# pylint: disable=W0613
"""
Sets the property value and trigger an update event
:param name: The property name
:param new_value: The new property value
"""
# Get the previous value
old_value = stored_instance.get_controller_state(name)
if new_value != old_value:
# Update the controller state
stored_instance.set_controller_state(name, new_value)
return new_value
return get_value, set_value | [
"def",
"_field_controller_generator",
"(",
"self",
")",
":",
"# Local variable, to avoid messing with \"self\"",
"stored_instance",
"=",
"self",
".",
"_ipopo_instance",
"def",
"get_value",
"(",
"self",
",",
"name",
")",
":",
"# pylint: disable=W0613",
"\"\"\"\n R... | Generates the methods called by the injected controller | [
"Generates",
"the",
"methods",
"called",
"by",
"the",
"injected",
"controller"
] | python | train |
mukulhase/WebWhatsapp-Wrapper | sample/flask/webapi.py | https://github.com/mukulhase/WebWhatsapp-Wrapper/blob/81b918ee4e0cd0cb563807a72baa167f670d70cb/sample/flask/webapi.py#L518-L527 | def get_unread_messages():
"""Get all unread messages"""
mark_seen = request.args.get('mark_seen', True)
unread_msg = g.driver.get_unread()
if mark_seen:
for msg in unread_msg:
msg.chat.send_seen()
return jsonify(unread_msg) | [
"def",
"get_unread_messages",
"(",
")",
":",
"mark_seen",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'mark_seen'",
",",
"True",
")",
"unread_msg",
"=",
"g",
".",
"driver",
".",
"get_unread",
"(",
")",
"if",
"mark_seen",
":",
"for",
"msg",
"in",
"un... | Get all unread messages | [
"Get",
"all",
"unread",
"messages"
] | python | train |
numenta/nupic | examples/opf/experiments/missing_record/make_datasets.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/experiments/missing_record/make_datasets.py#L35-L110 | def _generateSimple(filename="simple.csv", numSequences=1, elementsPerSeq=3,
numRepeats=10):
""" Generate a simple dataset. This contains a bunch of non-overlapping
sequences.
At the end of the dataset, we introduce missing records so that test
code can insure that the model didn't get confused by them.
Parameters:
----------------------------------------------------
filename: name of the file to produce, including extension. It will
be created in a 'datasets' sub-directory within the
directory containing this script.
numSequences: how many sequences to generate
elementsPerSeq: length of each sequence
numRepeats: how many times to repeat each sequence in the output
"""
# Create the output file
scriptDir = os.path.dirname(__file__)
pathname = os.path.join(scriptDir, 'datasets', filename)
print "Creating %s..." % (pathname)
fields = [('timestamp', 'datetime', 'T'),
('field1', 'string', ''),
('field2', 'float', '')]
outFile = FileRecordStream(pathname, write=True, fields=fields)
# Create the sequences
sequences = []
for i in range(numSequences):
seq = [x for x in range(i*elementsPerSeq, (i+1)*elementsPerSeq)]
sequences.append(seq)
# Write out the sequences in random order
seqIdxs = []
for i in range(numRepeats):
seqIdxs += range(numSequences)
random.shuffle(seqIdxs)
# Put 1 hour between each record
timestamp = datetime.datetime(year=2012, month=1, day=1, hour=0, minute=0,
second=0)
timeDelta = datetime.timedelta(hours=1)
# Write out the sequences without missing records
for seqIdx in seqIdxs:
seq = sequences[seqIdx]
for x in seq:
outFile.appendRecord([timestamp, str(x), x])
timestamp += timeDelta
# Now, write some out with missing records
for seqIdx in seqIdxs:
seq = sequences[seqIdx]
for i,x in enumerate(seq):
if i != 1:
outFile.appendRecord([timestamp, str(x), x])
timestamp += timeDelta
for seqIdx in seqIdxs:
seq = sequences[seqIdx]
for i,x in enumerate(seq):
if i != 1:
outFile.appendRecord([timestamp, str(x), x])
timestamp += timeDelta
# Write out some more of the sequences *without* missing records
for seqIdx in seqIdxs:
seq = sequences[seqIdx]
for x in seq:
outFile.appendRecord([timestamp, str(x), x])
timestamp += timeDelta
outFile.close() | [
"def",
"_generateSimple",
"(",
"filename",
"=",
"\"simple.csv\"",
",",
"numSequences",
"=",
"1",
",",
"elementsPerSeq",
"=",
"3",
",",
"numRepeats",
"=",
"10",
")",
":",
"# Create the output file",
"scriptDir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"_... | Generate a simple dataset. This contains a bunch of non-overlapping
sequences.
At the end of the dataset, we introduce missing records so that test
code can insure that the model didn't get confused by them.
Parameters:
----------------------------------------------------
filename: name of the file to produce, including extension. It will
be created in a 'datasets' sub-directory within the
directory containing this script.
numSequences: how many sequences to generate
elementsPerSeq: length of each sequence
numRepeats: how many times to repeat each sequence in the output | [
"Generate",
"a",
"simple",
"dataset",
".",
"This",
"contains",
"a",
"bunch",
"of",
"non",
"-",
"overlapping",
"sequences",
".",
"At",
"the",
"end",
"of",
"the",
"dataset",
"we",
"introduce",
"missing",
"records",
"so",
"that",
"test",
"code",
"can",
"insur... | python | valid |
NetEaseGame/ATX | atx/cmds/tkgui.py | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/cmds/tkgui.py#L41-L58 | def insert_code(filename, code, save=True, marker='# ATX CODE END'):
""" Auto append code """
content = ''
found = False
for line in open(filename, 'rb'):
if not found and line.strip() == marker:
found = True
cnt = line.find(marker)
content += line[:cnt] + code
content += line
if not found:
if not content.endswith('\n'):
content += '\n'
content += code + marker + '\n'
if save:
with open(filename, 'wb') as f:
f.write(content)
return content | [
"def",
"insert_code",
"(",
"filename",
",",
"code",
",",
"save",
"=",
"True",
",",
"marker",
"=",
"'# ATX CODE END'",
")",
":",
"content",
"=",
"''",
"found",
"=",
"False",
"for",
"line",
"in",
"open",
"(",
"filename",
",",
"'rb'",
")",
":",
"if",
"n... | Auto append code | [
"Auto",
"append",
"code"
] | python | train |
hydraplatform/hydra-base | hydra_base/db/model.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L909-L928 | def add_group(self, name, desc, status):
"""
Add a new group to a network.
"""
existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first()
if existing_group is not None:
raise HydraError("A resource group with name %s is already in network %s"%(name, self.id))
group_i = ResourceGroup()
group_i.name = name
group_i.description = desc
group_i.status = status
get_session().add(group_i)
self.resourcegroups.append(group_i)
return group_i | [
"def",
"add_group",
"(",
"self",
",",
"name",
",",
"desc",
",",
"status",
")",
":",
"existing_group",
"=",
"get_session",
"(",
")",
".",
"query",
"(",
"ResourceGroup",
")",
".",
"filter",
"(",
"ResourceGroup",
".",
"name",
"==",
"name",
",",
"ResourceGro... | Add a new group to a network. | [
"Add",
"a",
"new",
"group",
"to",
"a",
"network",
"."
] | python | train |
saltstack/salt | salt/modules/xml.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xml.py#L85-L103 | def set_attribute(file, element, key, value):
'''
Set the requested attribute key and value for matched xpath element.
CLI Example:
.. code-block:: bash
salt '*' xml.set_attribute /tmp/test.xml ".//element[@id='3']" editedby "gal"
'''
try:
root = ET.parse(file)
element = root.find(element)
except AttributeError:
log.error("Unable to find element matching %s", element)
return False
element.set(key, str(value))
root.write(file)
return True | [
"def",
"set_attribute",
"(",
"file",
",",
"element",
",",
"key",
",",
"value",
")",
":",
"try",
":",
"root",
"=",
"ET",
".",
"parse",
"(",
"file",
")",
"element",
"=",
"root",
".",
"find",
"(",
"element",
")",
"except",
"AttributeError",
":",
"log",
... | Set the requested attribute key and value for matched xpath element.
CLI Example:
.. code-block:: bash
salt '*' xml.set_attribute /tmp/test.xml ".//element[@id='3']" editedby "gal" | [
"Set",
"the",
"requested",
"attribute",
"key",
"and",
"value",
"for",
"matched",
"xpath",
"element",
"."
] | python | train |
mcocdawc/chemcoord | src/chemcoord/internal_coordinates/_zmat_class_core.py | https://github.com/mcocdawc/chemcoord/blob/95561ce387c142227c38fb14a1d182179aef8f5f/src/chemcoord/internal_coordinates/_zmat_class_core.py#L663-L778 | def get_grad_cartesian(self, as_function=True, chain=True,
drop_auto_dummies=True):
r"""Return the gradient for the transformation to a Cartesian.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Zmat`, which contain the
applied distortions in Zmatrix space.
In this case the user does not have to worry about indexing and
correct application of the tensor product.
Basically this is the function
:func:`zmat_functions.apply_grad_cartesian_tensor`
with partially replaced arguments.
If ``as_function`` is False, a ``(3, n, n, 3)`` tensor is returned,
which contains the values of the derivatives.
Since a ``n * 3`` matrix is deriven after a ``n * 3``
matrix, it is important to specify the used rules for indexing the
resulting tensor.
The rule is very simple: The indices of the numerator are used first
then the indices of the denominator get swapped and appended:
.. math::
\left(
\frac{\partial \mathbf{Y}}{\partial \mathbf{X}}
\right)_{i, j, k, l}
=
\frac{\partial \mathbf{Y}_{i, j}}{\partial \mathbf{X}_{l, k}}
Applying this rule to an example function:
.. math::
f \colon \mathbb{R}^3 \rightarrow \mathbb{R}
Gives as derivative the known row-vector gradient:
.. math::
(\nabla f)_{1, i}
=
\frac{\partial f}{\partial x_i} \qquad i \in \{1, 2, 3\}
.. note::
The row wise alignment of the zmat files makes sense for these
CSV like files.
But it is mathematically advantageous and
sometimes (depending on the memory layout) numerically better
to use a column wise alignment of the coordinates.
In this function the resulting tensor assumes a ``3 * n`` array
for the coordinates.
If
.. math::
\mathbf{C}_{i, j} &\qquad 1 \leq i \leq 3, \quad 1 \leq j \leq n \\
\mathbf{X}_{i, j} &\qquad 1 \leq i \leq 3, \quad 1 \leq j \leq n
denote the positions in Zmatrix and cartesian space,
The complete tensor may be written as:
.. math::
\left(
\frac{\partial \mathbf{X}}{\partial \mathbf{C}}
\right)_{i, j, k, l}
=
\frac{\partial \mathbf{X}_{i, j}}{\partial \mathbf{C}_{l, k}}
Args:
construction_table (pandas.DataFrame):
as_function (bool): Return a tensor or
:func:`xyz_functions.apply_grad_zmat_tensor`
with partially replaced arguments.
chain (bool):
drop_auto_dummies (bool): Drop automatically created
dummies from the gradient.
This means, that only changes in regularly placed atoms are
considered for the gradient.
Returns:
(func, :class:`numpy.ndarray`): Depending on ``as_function``
return a tensor or
:func:`~chemcoord.zmat_functions.apply_grad_cartesian_tensor`
with partially replaced arguments.
"""
zmat = self.change_numbering()
c_table = zmat.loc[:, ['b', 'a', 'd']]
c_table = c_table.replace(constants.int_label).values.T
C = zmat.loc[:, ['bond', 'angle', 'dihedral']].values.T
if C.dtype == np.dtype('i8'):
C = C.astype('f8')
C[[1, 2], :] = np.radians(C[[1, 2], :])
grad_X = transformation.get_grad_X(C, c_table, chain=chain)
if drop_auto_dummies:
def drop_dummies(grad_X, zmolecule):
rename = dict(zip(zmolecule.index, range(len(zmolecule))))
dummies = [rename[v['dummy_d']] for v in
self._metadata['has_dummies'].values()]
excluded = np.full(grad_X.shape[1], True)
excluded[dummies] = False
coord_rows = np.full(3, True)
selection = np.ix_(coord_rows, excluded, excluded, coord_rows)
return grad_X[selection]
grad_X = drop_dummies(grad_X, self)
if as_function:
from chemcoord.internal_coordinates.zmat_functions import (
apply_grad_cartesian_tensor)
return partial(apply_grad_cartesian_tensor, grad_X)
else:
return grad_X | [
"def",
"get_grad_cartesian",
"(",
"self",
",",
"as_function",
"=",
"True",
",",
"chain",
"=",
"True",
",",
"drop_auto_dummies",
"=",
"True",
")",
":",
"zmat",
"=",
"self",
".",
"change_numbering",
"(",
")",
"c_table",
"=",
"zmat",
".",
"loc",
"[",
":",
... | r"""Return the gradient for the transformation to a Cartesian.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Zmat`, which contain the
applied distortions in Zmatrix space.
In this case the user does not have to worry about indexing and
correct application of the tensor product.
Basically this is the function
:func:`zmat_functions.apply_grad_cartesian_tensor`
with partially replaced arguments.
If ``as_function`` is False, a ``(3, n, n, 3)`` tensor is returned,
which contains the values of the derivatives.
Since a ``n * 3`` matrix is deriven after a ``n * 3``
matrix, it is important to specify the used rules for indexing the
resulting tensor.
The rule is very simple: The indices of the numerator are used first
then the indices of the denominator get swapped and appended:
.. math::
\left(
\frac{\partial \mathbf{Y}}{\partial \mathbf{X}}
\right)_{i, j, k, l}
=
\frac{\partial \mathbf{Y}_{i, j}}{\partial \mathbf{X}_{l, k}}
Applying this rule to an example function:
.. math::
f \colon \mathbb{R}^3 \rightarrow \mathbb{R}
Gives as derivative the known row-vector gradient:
.. math::
(\nabla f)_{1, i}
=
\frac{\partial f}{\partial x_i} \qquad i \in \{1, 2, 3\}
.. note::
The row wise alignment of the zmat files makes sense for these
CSV like files.
But it is mathematically advantageous and
sometimes (depending on the memory layout) numerically better
to use a column wise alignment of the coordinates.
In this function the resulting tensor assumes a ``3 * n`` array
for the coordinates.
If
.. math::
\mathbf{C}_{i, j} &\qquad 1 \leq i \leq 3, \quad 1 \leq j \leq n \\
\mathbf{X}_{i, j} &\qquad 1 \leq i \leq 3, \quad 1 \leq j \leq n
denote the positions in Zmatrix and cartesian space,
The complete tensor may be written as:
.. math::
\left(
\frac{\partial \mathbf{X}}{\partial \mathbf{C}}
\right)_{i, j, k, l}
=
\frac{\partial \mathbf{X}_{i, j}}{\partial \mathbf{C}_{l, k}}
Args:
construction_table (pandas.DataFrame):
as_function (bool): Return a tensor or
:func:`xyz_functions.apply_grad_zmat_tensor`
with partially replaced arguments.
chain (bool):
drop_auto_dummies (bool): Drop automatically created
dummies from the gradient.
This means, that only changes in regularly placed atoms are
considered for the gradient.
Returns:
(func, :class:`numpy.ndarray`): Depending on ``as_function``
return a tensor or
:func:`~chemcoord.zmat_functions.apply_grad_cartesian_tensor`
with partially replaced arguments. | [
"r",
"Return",
"the",
"gradient",
"for",
"the",
"transformation",
"to",
"a",
"Cartesian",
"."
] | python | train |
jstitch/MambuPy | MambuPy/rest/mambustruct.py | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L837-L878 | def setCustomField(mambuentity, customfield="", *args, **kwargs):
"""Modifies the customField field for the given object with
something related to the value of the given field.
If the dataType == "USER_LINK" then instead of using the value
of the CF, it will be a MambuUser object.
Same if dataType == "CLIENT_LINK", but with a MambuClient.
Default case: just uses the same value the CF already had.
Returns the number of requests done to Mambu.
"""
from . import mambuuser
from . import mambuclient
try:
customFieldValue = mambuentity[customfield]
# find the dataType customfield by name or id
datatype = [ l['customField']['dataType'] for l in mambuentity[mambuentity.customFieldName] if (l['name'] == customfield or l['id'] == customfield) ][0]
except IndexError as ierr:
# if no customfield found with the given name, assume it is a
# grouped custom field, name must have an index suffix that must
# be removed
try:
# find the dataType customfield by name or id
datatype = [ l['customField']['dataType'] for l in mambuentity[mambuentity.customFieldName] if (l['name'] == customfield.split('_')[0] or l['id'] == customfield.split('_')[0]) ][0]
except IndexError:
err = MambuError("Object %s has no custom field '%s'" % (mambuentity['id'], customfield))
raise err
except AttributeError:
err = MambuError("Object does not have a custom field to set")
raise err
if datatype == "USER_LINK":
mambuentity[customfield] = mambuuser.MambuUser(entid=customFieldValue, *args, **kwargs)
elif datatype == "CLIENT_LINK":
mambuentity[customfield] = mambuclient.MambuClient(entid=customFieldValue, *args, **kwargs)
else:
mambuentity[customfield] = customFieldValue
return 0
return 1 | [
"def",
"setCustomField",
"(",
"mambuentity",
",",
"customfield",
"=",
"\"\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"import",
"mambuuser",
"from",
".",
"import",
"mambuclient",
"try",
":",
"customFieldValue",
"=",
"mambuentity",
... | Modifies the customField field for the given object with
something related to the value of the given field.
If the dataType == "USER_LINK" then instead of using the value
of the CF, it will be a MambuUser object.
Same if dataType == "CLIENT_LINK", but with a MambuClient.
Default case: just uses the same value the CF already had.
Returns the number of requests done to Mambu. | [
"Modifies",
"the",
"customField",
"field",
"for",
"the",
"given",
"object",
"with",
"something",
"related",
"to",
"the",
"value",
"of",
"the",
"given",
"field",
"."
] | python | train |
neurosynth/neurosynth | neurosynth/analysis/decode.py | https://github.com/neurosynth/neurosynth/blob/948ce7edce15d7df693446e76834e0c23bfe8f11/neurosynth/analysis/decode.py#L216-L219 | def _dot_product(self, imgs_to_decode):
""" Decoding using the dot product.
"""
return np.dot(imgs_to_decode.T, self.feature_images).T | [
"def",
"_dot_product",
"(",
"self",
",",
"imgs_to_decode",
")",
":",
"return",
"np",
".",
"dot",
"(",
"imgs_to_decode",
".",
"T",
",",
"self",
".",
"feature_images",
")",
".",
"T"
] | Decoding using the dot product. | [
"Decoding",
"using",
"the",
"dot",
"product",
"."
] | python | test |
NoviceLive/pat | pat/utils.py | https://github.com/NoviceLive/pat/blob/bd223fc5e758213662befbebdf9538f3fbf58ad6/pat/utils.py#L49-L57 | def window(seq, count=2):
"""Slide window."""
iseq = iter(seq)
result = tuple(islice(iseq, count))
if len(result) == count:
yield result
for elem in iseq:
result = result[1:] + (elem,)
yield result | [
"def",
"window",
"(",
"seq",
",",
"count",
"=",
"2",
")",
":",
"iseq",
"=",
"iter",
"(",
"seq",
")",
"result",
"=",
"tuple",
"(",
"islice",
"(",
"iseq",
",",
"count",
")",
")",
"if",
"len",
"(",
"result",
")",
"==",
"count",
":",
"yield",
"resu... | Slide window. | [
"Slide",
"window",
"."
] | python | train |
edx/edx-enterprise | enterprise/utils.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L715-L730 | def is_course_run_enrollable(course_run):
"""
Return true if the course run is enrollable, false otherwise.
We look for the following criteria:
- end is greater than now OR null
- enrollment_start is less than now OR null
- enrollment_end is greater than now OR null
"""
now = datetime.datetime.now(pytz.UTC)
end = parse_datetime_handle_invalid(course_run.get('end'))
enrollment_start = parse_datetime_handle_invalid(course_run.get('enrollment_start'))
enrollment_end = parse_datetime_handle_invalid(course_run.get('enrollment_end'))
return (not end or end > now) and \
(not enrollment_start or enrollment_start < now) and \
(not enrollment_end or enrollment_end > now) | [
"def",
"is_course_run_enrollable",
"(",
"course_run",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"pytz",
".",
"UTC",
")",
"end",
"=",
"parse_datetime_handle_invalid",
"(",
"course_run",
".",
"get",
"(",
"'end'",
")",
")",
"enrollment... | Return true if the course run is enrollable, false otherwise.
We look for the following criteria:
- end is greater than now OR null
- enrollment_start is less than now OR null
- enrollment_end is greater than now OR null | [
"Return",
"true",
"if",
"the",
"course",
"run",
"is",
"enrollable",
"false",
"otherwise",
"."
] | python | valid |
tchellomello/python-amcrest | src/amcrest/ptz.py | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/ptz.py#L210-L221 | def go_to_preset(self, action=None, channel=0, preset_point_number=1):
"""
Params:
action - start or stop
channel - channel number
preset_point_number - preset point number
"""
ret = self.command(
'ptz.cgi?action={0}&channel={1}&code=GotoPreset&arg1=0'
'&arg2={2}&arg3=0'.format(action, channel, preset_point_number)
)
return ret.content.decode('utf-8') | [
"def",
"go_to_preset",
"(",
"self",
",",
"action",
"=",
"None",
",",
"channel",
"=",
"0",
",",
"preset_point_number",
"=",
"1",
")",
":",
"ret",
"=",
"self",
".",
"command",
"(",
"'ptz.cgi?action={0}&channel={1}&code=GotoPreset&arg1=0'",
"'&arg2={2}&arg3=0'",
".",... | Params:
action - start or stop
channel - channel number
preset_point_number - preset point number | [
"Params",
":",
"action",
"-",
"start",
"or",
"stop",
"channel",
"-",
"channel",
"number",
"preset_point_number",
"-",
"preset",
"point",
"number"
] | python | train |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L47-L60 | def publish_page(page, languages):
"""
Publish a CMS page in all given languages.
"""
for language_code, lang_name in iter_languages(languages):
url = page.get_absolute_url()
if page.publisher_is_draft:
page.publish(language_code)
log.info('page "%s" published in %s: %s', page, lang_name, url)
else:
log.info('published page "%s" already exists in %s: %s', page,
lang_name, url)
return page.reload() | [
"def",
"publish_page",
"(",
"page",
",",
"languages",
")",
":",
"for",
"language_code",
",",
"lang_name",
"in",
"iter_languages",
"(",
"languages",
")",
":",
"url",
"=",
"page",
".",
"get_absolute_url",
"(",
")",
"if",
"page",
".",
"publisher_is_draft",
":",... | Publish a CMS page in all given languages. | [
"Publish",
"a",
"CMS",
"page",
"in",
"all",
"given",
"languages",
"."
] | python | train |
genepattern/genepattern-notebook | genepattern/remote_widgets.py | https://github.com/genepattern/genepattern-notebook/blob/953168bd08c5332412438cbc5bb59993a07a6911/genepattern/remote_widgets.py#L23-L51 | def register(self, server, username, password):
"""
Register a new GenePattern server session for the provided
server, username and password. Return the session.
:param server:
:param username:
:param password:
:return:
"""
# Create the session
session = gp.GPServer(server, username, password)
# Validate username if not empty
valid_username = username != "" and username is not None
# Validate that the server is not already registered
index = self._get_index(server)
new_server = index == -1
# Add the new session to the list
if valid_username and new_server:
self.sessions.append(session)
# Replace old session is one exists
if valid_username and not new_server:
self.sessions[index] = session
return session | [
"def",
"register",
"(",
"self",
",",
"server",
",",
"username",
",",
"password",
")",
":",
"# Create the session",
"session",
"=",
"gp",
".",
"GPServer",
"(",
"server",
",",
"username",
",",
"password",
")",
"# Validate username if not empty",
"valid_username",
... | Register a new GenePattern server session for the provided
server, username and password. Return the session.
:param server:
:param username:
:param password:
:return: | [
"Register",
"a",
"new",
"GenePattern",
"server",
"session",
"for",
"the",
"provided",
"server",
"username",
"and",
"password",
".",
"Return",
"the",
"session",
".",
":",
"param",
"server",
":",
":",
"param",
"username",
":",
":",
"param",
"password",
":",
... | python | valid |
python-cmd2/cmd2 | cmd2/cmd2.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L194-L241 | def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve_quotes: bool = False) -> \
Callable[[argparse.Namespace, List], Optional[bool]]:
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given
instance of argparse.ArgumentParser, but also returning unknown args as a list.
:param argparser: unique instance of ArgumentParser
:param preserve_quotes: if True, then arguments passed to argparse maintain their quotes
:return: function that gets passed argparse-parsed args in a Namespace and a list of unknown argument strings
A member called __statement__ is added to the Namespace to provide command functions access to the
Statement object. This can be useful if the command function needs to know the command line.
"""
import functools
# noinspection PyProtectedMember
def arg_decorator(func: Callable):
@functools.wraps(func)
def cmd_wrapper(cmd2_instance, statement: Union[Statement, str]):
statement, parsed_arglist = cmd2_instance.statement_parser.get_command_arg_list(command_name,
statement,
preserve_quotes)
try:
args, unknown = argparser.parse_known_args(parsed_arglist)
except SystemExit:
return
else:
setattr(args, '__statement__', statement)
return func(cmd2_instance, args, unknown)
# argparser defaults the program name to sys.argv[0]
# we want it to be the name of our command
command_name = func.__name__[len(COMMAND_FUNC_PREFIX):]
argparser.prog = command_name
# If the description has not been set, then use the method docstring if one exists
if argparser.description is None and func.__doc__:
argparser.description = func.__doc__
# Set the command's help text as argparser.description (which can be None)
cmd_wrapper.__doc__ = argparser.description
# Mark this function as having an argparse ArgumentParser
setattr(cmd_wrapper, 'argparser', argparser)
return cmd_wrapper
return arg_decorator | [
"def",
"with_argparser_and_unknown_args",
"(",
"argparser",
":",
"argparse",
".",
"ArgumentParser",
",",
"preserve_quotes",
":",
"bool",
"=",
"False",
")",
"->",
"Callable",
"[",
"[",
"argparse",
".",
"Namespace",
",",
"List",
"]",
",",
"Optional",
"[",
"bool"... | A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given
instance of argparse.ArgumentParser, but also returning unknown args as a list.
:param argparser: unique instance of ArgumentParser
:param preserve_quotes: if True, then arguments passed to argparse maintain their quotes
:return: function that gets passed argparse-parsed args in a Namespace and a list of unknown argument strings
A member called __statement__ is added to the Namespace to provide command functions access to the
Statement object. This can be useful if the command function needs to know the command line. | [
"A",
"decorator",
"to",
"alter",
"a",
"cmd2",
"method",
"to",
"populate",
"its",
"args",
"argument",
"by",
"parsing",
"arguments",
"with",
"the",
"given",
"instance",
"of",
"argparse",
".",
"ArgumentParser",
"but",
"also",
"returning",
"unknown",
"args",
"as",... | python | train |
ybrs/pydisque | pydisque/client.py | https://github.com/ybrs/pydisque/blob/ea5ce1576b66398c1cce32cad0f15709b1ea8df8/pydisque/client.py#L402-L415 | def show(self, job_id, return_dict=False):
"""
Describe the job.
:param job_id:
"""
rtn = self.execute_command('SHOW', job_id)
if return_dict:
grouped = self._grouper(rtn, 2)
rtn = dict((a, b) for a, b in grouped)
return rtn | [
"def",
"show",
"(",
"self",
",",
"job_id",
",",
"return_dict",
"=",
"False",
")",
":",
"rtn",
"=",
"self",
".",
"execute_command",
"(",
"'SHOW'",
",",
"job_id",
")",
"if",
"return_dict",
":",
"grouped",
"=",
"self",
".",
"_grouper",
"(",
"rtn",
",",
... | Describe the job.
:param job_id: | [
"Describe",
"the",
"job",
"."
] | python | train |
jobovy/galpy | galpy/util/bovy_coords.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_coords.py#L1991-L2037 | def Rz_to_lambdanu(R,z,ac=5.,Delta=1.):
"""
NAME:
Rz_to_lambdanu
PURPOSE:
calculate the prolate spheroidal coordinates (lambda,nu) from
galactocentric cylindrical coordinates (R,z)
by solving eq. (2.2) in Dejonghe & de Zeeuw (1988a) for (lambda,nu):
R^2 = (l+a) * (n+a) / (a-g)
z^2 = (l+g) * (n+g) / (g-a)
Delta^2 = g-a
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
ac - axis ratio of the coordinate surfaces
(a/c) = sqrt(-a) / sqrt(-g) (default: 5.)
Delta - focal distance that defines the spheroidal coordinate system (default: 1.)
Delta=sqrt(g-a)
OUTPUT:
(lambda,nu)
HISTORY:
2015-02-13 - Written - Trick (MPIA)
"""
g = Delta**2 / (1.-ac**2)
a = g - Delta**2
term = R**2 + z**2 - a - g
discr = (R**2 + z**2 - Delta**2)**2 + (4. * Delta**2 * R**2)
l = 0.5 * (term + nu.sqrt(discr))
n = 0.5 * (term - nu.sqrt(discr))
if isinstance(z,float) and z == 0.:
l = R**2 - a
n = -g
elif isinstance(z,nu.ndarray) and nu.sum(z == 0.) > 0:
if isinstance(R,float): l[z==0.] = R**2 - a
if isinstance(R,sc.ndarray): l[z==0.] = R[z==0.]**2 - a
n[z==0.] = -g
return (l,n) | [
"def",
"Rz_to_lambdanu",
"(",
"R",
",",
"z",
",",
"ac",
"=",
"5.",
",",
"Delta",
"=",
"1.",
")",
":",
"g",
"=",
"Delta",
"**",
"2",
"/",
"(",
"1.",
"-",
"ac",
"**",
"2",
")",
"a",
"=",
"g",
"-",
"Delta",
"**",
"2",
"term",
"=",
"R",
"**",... | NAME:
Rz_to_lambdanu
PURPOSE:
calculate the prolate spheroidal coordinates (lambda,nu) from
galactocentric cylindrical coordinates (R,z)
by solving eq. (2.2) in Dejonghe & de Zeeuw (1988a) for (lambda,nu):
R^2 = (l+a) * (n+a) / (a-g)
z^2 = (l+g) * (n+g) / (g-a)
Delta^2 = g-a
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
ac - axis ratio of the coordinate surfaces
(a/c) = sqrt(-a) / sqrt(-g) (default: 5.)
Delta - focal distance that defines the spheroidal coordinate system (default: 1.)
Delta=sqrt(g-a)
OUTPUT:
(lambda,nu)
HISTORY:
2015-02-13 - Written - Trick (MPIA) | [
"NAME",
":"
] | python | train |
mitsei/dlkit | dlkit/json_/repository/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/objects.py#L948-L960 | def clear_distribute_compositions(self):
"""Removes the distribution rights.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.clear_group_template
if (self.get_distribute_compositions_metadata().is_read_only() or
self.get_distribute_compositions_metadata().is_required()):
raise errors.NoAccess()
self._my_map['distributeCompositions'] = self._distribute_compositions_default | [
"def",
"clear_distribute_compositions",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.clear_group_template",
"if",
"(",
"self",
".",
"get_distribute_compositions_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
".",
"get... | Removes the distribution rights.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | [
"Removes",
"the",
"distribution",
"rights",
"."
] | python | train |
unt-libraries/pyuntl | pyuntl/untl_structure.py | https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untl_structure.py#L358-L369 | def create_xml_string(self):
"""Create a UNTL document in a string from a UNTL metadata
root object.
untl_xml_string = metadata_root_object.create_xml_string()
"""
root = self.create_xml()
xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(
root, pretty_print=True
)
return xml | [
"def",
"create_xml_string",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"create_xml",
"(",
")",
"xml",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'",
"+",
"tostring",
"(",
"root",
",",
"pretty_print",
"=",
"True",
")",
"return",
"xml"
] | Create a UNTL document in a string from a UNTL metadata
root object.
untl_xml_string = metadata_root_object.create_xml_string() | [
"Create",
"a",
"UNTL",
"document",
"in",
"a",
"string",
"from",
"a",
"UNTL",
"metadata",
"root",
"object",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/edwards_fah_2013a.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/edwards_fah_2013a.py#L219-L227 | def _compute_mean(self, C, mag, term_dist_r):
"""
compute mean
"""
return (self._compute_term_1(C, mag) +
self._compute_term_2(C, mag, term_dist_r) +
self._compute_term_3(C, mag, term_dist_r) +
self._compute_term_4(C, mag, term_dist_r) +
self._compute_term_5(C, mag, term_dist_r)) | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"term_dist_r",
")",
":",
"return",
"(",
"self",
".",
"_compute_term_1",
"(",
"C",
",",
"mag",
")",
"+",
"self",
".",
"_compute_term_2",
"(",
"C",
",",
"mag",
",",
"term_dist_r",
")",
"+"... | compute mean | [
"compute",
"mean"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L145-L204 | def block_layer(inputs,
filters,
blocks,
strides,
is_training,
name,
row_blocks_dim=None,
col_blocks_dim=None):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[batch, channels, height, width]`.
filters: `int` number of filters for the first convolution of the layer.
blocks: `int` number of blocks contained in the layer.
strides: `int` stride to use for the first convolution of the layer. If
greater than 1, this layer will downsample the input.
is_training: `bool` for whether the model is training.
name: `str`name for the Tensor output of the block layer.
row_blocks_dim: a mtf.Dimension, row dimension which is
spatially partitioned along mesh axis
col_blocks_dim: a mtf.Dimension, row dimension which is
spatially partitioned along mesh axis
Returns:
The output `Tensor` of the block layer.
"""
with tf.variable_scope(name, default_name="block_layer"):
# Only the first block per block_layer uses projection_shortcut and strides
def projection_shortcut(inputs, kernel):
"""Project identity branch."""
inputs = mtf.conv2d_with_blocks(
inputs,
kernel,
strides=strides,
padding="SAME",
h_blocks_dim=None, w_blocks_dim=col_blocks_dim)
return batch_norm_relu(
inputs, is_training, relu=False)
inputs = bottleneck_block(
inputs,
filters,
is_training,
strides=strides,
projection_shortcut=projection_shortcut,
row_blocks_dim=row_blocks_dim,
col_blocks_dim=col_blocks_dim)
for i in range(1, blocks):
with tf.variable_scope("bottleneck_%d" % i):
inputs = bottleneck_block(
inputs,
filters,
is_training,
strides=[1, 1, 1, 1],
projection_shortcut=None,
row_blocks_dim=row_blocks_dim,
col_blocks_dim=col_blocks_dim)
return inputs | [
"def",
"block_layer",
"(",
"inputs",
",",
"filters",
",",
"blocks",
",",
"strides",
",",
"is_training",
",",
"name",
",",
"row_blocks_dim",
"=",
"None",
",",
"col_blocks_dim",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
... | Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[batch, channels, height, width]`.
filters: `int` number of filters for the first convolution of the layer.
blocks: `int` number of blocks contained in the layer.
strides: `int` stride to use for the first convolution of the layer. If
greater than 1, this layer will downsample the input.
is_training: `bool` for whether the model is training.
name: `str`name for the Tensor output of the block layer.
row_blocks_dim: a mtf.Dimension, row dimension which is
spatially partitioned along mesh axis
col_blocks_dim: a mtf.Dimension, row dimension which is
spatially partitioned along mesh axis
Returns:
The output `Tensor` of the block layer. | [
"Creates",
"one",
"layer",
"of",
"blocks",
"for",
"the",
"ResNet",
"model",
"."
] | python | train |
vpelletier/python-libusb1 | usb1/__init__.py | https://github.com/vpelletier/python-libusb1/blob/740c9778e28523e4ec3543415d95f5400ae0fa24/usb1/__init__.py#L1118-L1127 | def unregister(self, fd):
"""
Unregister an USB-unrelated fd from poller.
Convenience method.
"""
if fd in self.__fd_set:
raise ValueError(
'This fd is a special USB event fd, it must stay registered.'
)
self.__poller.unregister(fd) | [
"def",
"unregister",
"(",
"self",
",",
"fd",
")",
":",
"if",
"fd",
"in",
"self",
".",
"__fd_set",
":",
"raise",
"ValueError",
"(",
"'This fd is a special USB event fd, it must stay registered.'",
")",
"self",
".",
"__poller",
".",
"unregister",
"(",
"fd",
")"
] | Unregister an USB-unrelated fd from poller.
Convenience method. | [
"Unregister",
"an",
"USB",
"-",
"unrelated",
"fd",
"from",
"poller",
".",
"Convenience",
"method",
"."
] | python | train |
RedHatInsights/insights-core | insights/specs/default.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/specs/default.py#L121-L131 | def tomcat_base(broker):
"""Path: Tomcat base path"""
ps = broker[DefaultSpecs.ps_auxww].content
results = []
findall = re.compile(r"\-Dcatalina\.base=(\S+)").findall
for p in ps:
found = findall(p)
if found:
# Only get the path which is absolute
results.extend(f for f in found if f[0] == '/')
return list(set(results)) | [
"def",
"tomcat_base",
"(",
"broker",
")",
":",
"ps",
"=",
"broker",
"[",
"DefaultSpecs",
".",
"ps_auxww",
"]",
".",
"content",
"results",
"=",
"[",
"]",
"findall",
"=",
"re",
".",
"compile",
"(",
"r\"\\-Dcatalina\\.base=(\\S+)\"",
")",
".",
"findall",
"for... | Path: Tomcat base path | [
"Path",
":",
"Tomcat",
"base",
"path"
] | python | train |
pybel/pybel | src/pybel/cli.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L421-L429 | def prune(manager: Manager):
"""Prune nodes not belonging to any edges."""
nodes_to_delete = [
node
for node in tqdm(manager.session.query(Node), total=manager.count_nodes())
if not node.networks
]
manager.session.delete(nodes_to_delete)
manager.session.commit() | [
"def",
"prune",
"(",
"manager",
":",
"Manager",
")",
":",
"nodes_to_delete",
"=",
"[",
"node",
"for",
"node",
"in",
"tqdm",
"(",
"manager",
".",
"session",
".",
"query",
"(",
"Node",
")",
",",
"total",
"=",
"manager",
".",
"count_nodes",
"(",
")",
")... | Prune nodes not belonging to any edges. | [
"Prune",
"nodes",
"not",
"belonging",
"to",
"any",
"edges",
"."
] | python | train |
mrcagney/gtfstk | gtfstk/validators.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/validators.py#L138-L181 | def check_for_required_columns(
problems: List, table: str, df: DataFrame
) -> List:
"""
Check that the given GTFS table has the required columns.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or ``'warning'``;
``'error'`` means the GTFS is violated;
``'warning'`` means there is a problem but it is not a
GTFS violation
2. A message (string) that describes the problem
3. A GTFS table name, e.g. ``'routes'``, in which the problem
occurs
4. A list of rows (integers) of the table's DataFrame where the
problem occurs
table : string
Name of a GTFS table
df : DataFrame
The GTFS table corresponding to ``table``
Returns
-------
list
The ``problems`` list extended as follows.
Check that the DataFrame contains the colums required by GTFS
and append to the problems list one error for each column
missing.
"""
r = cs.GTFS_REF
req_columns = r.loc[
(r["table"] == table) & r["column_required"], "column"
].values
for col in req_columns:
if col not in df.columns:
problems.append(["error", f"Missing column {col}", table, []])
return problems | [
"def",
"check_for_required_columns",
"(",
"problems",
":",
"List",
",",
"table",
":",
"str",
",",
"df",
":",
"DataFrame",
")",
"->",
"List",
":",
"r",
"=",
"cs",
".",
"GTFS_REF",
"req_columns",
"=",
"r",
".",
"loc",
"[",
"(",
"r",
"[",
"\"table\"",
"... | Check that the given GTFS table has the required columns.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or ``'warning'``;
``'error'`` means the GTFS is violated;
``'warning'`` means there is a problem but it is not a
GTFS violation
2. A message (string) that describes the problem
3. A GTFS table name, e.g. ``'routes'``, in which the problem
occurs
4. A list of rows (integers) of the table's DataFrame where the
problem occurs
table : string
Name of a GTFS table
df : DataFrame
The GTFS table corresponding to ``table``
Returns
-------
list
The ``problems`` list extended as follows.
Check that the DataFrame contains the colums required by GTFS
and append to the problems list one error for each column
missing. | [
"Check",
"that",
"the",
"given",
"GTFS",
"table",
"has",
"the",
"required",
"columns",
"."
] | python | train |
estnltk/estnltk | estnltk/mw_verbs/verbchain_nom_vinf_extender.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/mw_verbs/verbchain_nom_vinf_extender.py#L120-L130 | def extendChainsInSentence( self, sentence, foundChains ):
''' Rakendab meetodit self.extendChainsInClause() antud lause igal osalausel.
'''
# 1) Preprocessing
clauses = getClausesByClauseIDs( sentence )
# 2) Extend verb chains in each clause
allDetectedVerbChains = []
for clauseID in clauses:
clause = clauses[clauseID]
self.extendChainsInClause(clause, clauseID, foundChains) | [
"def",
"extendChainsInSentence",
"(",
"self",
",",
"sentence",
",",
"foundChains",
")",
":",
"# 1) Preprocessing\r",
"clauses",
"=",
"getClausesByClauseIDs",
"(",
"sentence",
")",
"# 2) Extend verb chains in each clause\r",
"allDetectedVerbChains",
"=",
"[",
"]",
"for",
... | Rakendab meetodit self.extendChainsInClause() antud lause igal osalausel. | [
"Rakendab",
"meetodit",
"self",
".",
"extendChainsInClause",
"()",
"antud",
"lause",
"igal",
"osalausel",
"."
] | python | train |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L1214-L1220 | def append(self, data, size):
"""
Append user-supplied data to chunk, return resulting chunk size. If the
data would exceeded the available space, it is truncated. If you want to
grow the chunk to accommodate new data, use the zchunk_extend method.
"""
return lib.zchunk_append(self._as_parameter_, data, size) | [
"def",
"append",
"(",
"self",
",",
"data",
",",
"size",
")",
":",
"return",
"lib",
".",
"zchunk_append",
"(",
"self",
".",
"_as_parameter_",
",",
"data",
",",
"size",
")"
] | Append user-supplied data to chunk, return resulting chunk size. If the
data would exceeded the available space, it is truncated. If you want to
grow the chunk to accommodate new data, use the zchunk_extend method. | [
"Append",
"user",
"-",
"supplied",
"data",
"to",
"chunk",
"return",
"resulting",
"chunk",
"size",
".",
"If",
"the",
"data",
"would",
"exceeded",
"the",
"available",
"space",
"it",
"is",
"truncated",
".",
"If",
"you",
"want",
"to",
"grow",
"the",
"chunk",
... | python | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L39-L47 | def dump(self):
"""Serialize this object."""
return {
'target': str(self.target),
'data': base64.b64encode(self.data).decode('utf-8'),
'var_id': self.var_id,
'valid': self.valid
} | [
"def",
"dump",
"(",
"self",
")",
":",
"return",
"{",
"'target'",
":",
"str",
"(",
"self",
".",
"target",
")",
",",
"'data'",
":",
"base64",
".",
"b64encode",
"(",
"self",
".",
"data",
")",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"'var_id'",
":",
... | Serialize this object. | [
"Serialize",
"this",
"object",
"."
] | python | train |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L3339-L3346 | def getVideoStreamTextureGL(self, hTrackedCamera, eFrameType, nFrameHeaderSize):
"""Access a shared GL texture for the specified tracked camera stream"""
fn = self.function_table.getVideoStreamTextureGL
pglTextureId = glUInt_t()
pFrameHeader = CameraVideoStreamFrameHeader_t()
result = fn(hTrackedCamera, eFrameType, byref(pglTextureId), byref(pFrameHeader), nFrameHeaderSize)
return result, pglTextureId, pFrameHeader | [
"def",
"getVideoStreamTextureGL",
"(",
"self",
",",
"hTrackedCamera",
",",
"eFrameType",
",",
"nFrameHeaderSize",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getVideoStreamTextureGL",
"pglTextureId",
"=",
"glUInt_t",
"(",
")",
"pFrameHeader",
"=",
"C... | Access a shared GL texture for the specified tracked camera stream | [
"Access",
"a",
"shared",
"GL",
"texture",
"for",
"the",
"specified",
"tracked",
"camera",
"stream"
] | python | train |
alfred82santa/dirty-models | dirty_models/models.py | https://github.com/alfred82santa/dirty-models/blob/354becdb751b21f673515eae928c256c7e923c50/dirty_models/models.py#L494-L499 | def clear(self):
"""
Clears all the data in the object, keeping original data
"""
self.__modified_data__ = {}
self.__deleted_fields__ = [field for field in self.__original_data__.keys()] | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"__modified_data__",
"=",
"{",
"}",
"self",
".",
"__deleted_fields__",
"=",
"[",
"field",
"for",
"field",
"in",
"self",
".",
"__original_data__",
".",
"keys",
"(",
")",
"]"
] | Clears all the data in the object, keeping original data | [
"Clears",
"all",
"the",
"data",
"in",
"the",
"object",
"keeping",
"original",
"data"
] | python | train |
jnrbsn/daemonocle | daemonocle/core.py | https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L395-L421 | def _run(self):
"""Run the worker function with some custom exception handling."""
try:
# Run the worker
self.worker()
except SystemExit as ex:
# sys.exit() was called
if isinstance(ex.code, int):
if ex.code is not None and ex.code != 0:
# A custom exit code was specified
self._shutdown(
'Exiting with non-zero exit code {exitcode}'.format(
exitcode=ex.code),
ex.code)
else:
# A message was passed to sys.exit()
self._shutdown(
'Exiting with message: {msg}'.format(msg=ex.code), 1)
except Exception as ex:
if self.detach:
self._shutdown('Dying due to unhandled {cls}: {msg}'.format(
cls=ex.__class__.__name__, msg=str(ex)), 127)
else:
# We're not detached so just raise the exception
raise
self._shutdown('Shutting down normally') | [
"def",
"_run",
"(",
"self",
")",
":",
"try",
":",
"# Run the worker",
"self",
".",
"worker",
"(",
")",
"except",
"SystemExit",
"as",
"ex",
":",
"# sys.exit() was called",
"if",
"isinstance",
"(",
"ex",
".",
"code",
",",
"int",
")",
":",
"if",
"ex",
"."... | Run the worker function with some custom exception handling. | [
"Run",
"the",
"worker",
"function",
"with",
"some",
"custom",
"exception",
"handling",
"."
] | python | train |
mcieslik-mctp/papy | src/papy/core.py | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L631-L648 | def load(self, filename):
"""
Instanciates (loads) pipeline from a source code file.
Arguments:
- filename(``path``) location of the pipeline source code.
"""
dir_name = os.path.dirname(filename)
mod_name = os.path.basename(filename).split('.')[0]
self.filename = mod_name
sys.path.insert(0, dir_name)
mod = __import__(mod_name)
sys.path.remove(dir_name) # do not pollute the path.
pipers, xtras, pipes = mod.pipeline()
self.add_pipers(pipers, xtras)
self.add_pipes(pipes) | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"mod_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"... | Instanciates (loads) pipeline from a source code file.
Arguments:
- filename(``path``) location of the pipeline source code. | [
"Instanciates",
"(",
"loads",
")",
"pipeline",
"from",
"a",
"source",
"code",
"file",
".",
"Arguments",
":",
"-",
"filename",
"(",
"path",
")",
"location",
"of",
"the",
"pipeline",
"source",
"code",
"."
] | python | train |
mlenzen/collections-extended | collections_extended/range_map.py | https://github.com/mlenzen/collections-extended/blob/ee9e86f6bbef442dbebcb3a5970642c5c969e2cf/collections_extended/range_map.py#L348-L353 | def empty(self, start=None, stop=None):
"""Empty the range from start to stop.
Like delete, but no Error is raised if the entire range isn't mapped.
"""
self.set(NOT_SET, start=start, stop=stop) | [
"def",
"empty",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"self",
".",
"set",
"(",
"NOT_SET",
",",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
")"
] | Empty the range from start to stop.
Like delete, but no Error is raised if the entire range isn't mapped. | [
"Empty",
"the",
"range",
"from",
"start",
"to",
"stop",
"."
] | python | train |
reincubate/ricloud | ricloud/utils.py | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L90-L102 | def print_prompt_values(values, message=None, sub_attr=None):
"""Prints prompt title and choices with a bit of formatting."""
if message:
prompt_message(message)
for index, entry in enumerate(values):
if sub_attr:
line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr))
else:
line = '{:2d}: {}'.format(index, utf8(entry))
with indent(3):
print_message(line) | [
"def",
"print_prompt_values",
"(",
"values",
",",
"message",
"=",
"None",
",",
"sub_attr",
"=",
"None",
")",
":",
"if",
"message",
":",
"prompt_message",
"(",
"message",
")",
"for",
"index",
",",
"entry",
"in",
"enumerate",
"(",
"values",
")",
":",
"if",... | Prints prompt title and choices with a bit of formatting. | [
"Prints",
"prompt",
"title",
"and",
"choices",
"with",
"a",
"bit",
"of",
"formatting",
"."
] | python | train |
scopus-api/scopus | scopus/scopus_search.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/scopus_search.py#L196-L200 | def _join(lst, key, sep=";"):
"""Auxiliary function to join same elements of a list of dictionaries if
the elements are not None.
"""
return sep.join([d[key] for d in lst if d[key]]) | [
"def",
"_join",
"(",
"lst",
",",
"key",
",",
"sep",
"=",
"\";\"",
")",
":",
"return",
"sep",
".",
"join",
"(",
"[",
"d",
"[",
"key",
"]",
"for",
"d",
"in",
"lst",
"if",
"d",
"[",
"key",
"]",
"]",
")"
] | Auxiliary function to join same elements of a list of dictionaries if
the elements are not None. | [
"Auxiliary",
"function",
"to",
"join",
"same",
"elements",
"of",
"a",
"list",
"of",
"dictionaries",
"if",
"the",
"elements",
"are",
"not",
"None",
"."
] | python | train |
mailgun/talon | talon/quotations.py | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L601-L609 | def is_splitter(line):
'''
Returns Matcher object if provided string is a splitter and
None otherwise.
'''
for pattern in SPLITTER_PATTERNS:
matcher = re.match(pattern, line)
if matcher:
return matcher | [
"def",
"is_splitter",
"(",
"line",
")",
":",
"for",
"pattern",
"in",
"SPLITTER_PATTERNS",
":",
"matcher",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"line",
")",
"if",
"matcher",
":",
"return",
"matcher"
] | Returns Matcher object if provided string is a splitter and
None otherwise. | [
"Returns",
"Matcher",
"object",
"if",
"provided",
"string",
"is",
"a",
"splitter",
"and",
"None",
"otherwise",
"."
] | python | train |
markovmodel/PyEMMA | pyemma/_ext/variational/estimators/moments.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/moments.py#L386-L401 | def _M2_dense(X, Y, weights=None, diag_only=False):
""" 2nd moment matrix using dense matrix computations.
This function is encapsulated such that we can make easy modifications of the basic algorithms
"""
if weights is not None:
if diag_only:
return np.sum(weights[:, None] * X * Y, axis=0)
else:
return np.dot((weights[:, None] * X).T, Y)
else:
if diag_only:
return np.sum(X * Y, axis=0)
else:
return np.dot(X.T, Y) | [
"def",
"_M2_dense",
"(",
"X",
",",
"Y",
",",
"weights",
"=",
"None",
",",
"diag_only",
"=",
"False",
")",
":",
"if",
"weights",
"is",
"not",
"None",
":",
"if",
"diag_only",
":",
"return",
"np",
".",
"sum",
"(",
"weights",
"[",
":",
",",
"None",
"... | 2nd moment matrix using dense matrix computations.
This function is encapsulated such that we can make easy modifications of the basic algorithms | [
"2nd",
"moment",
"matrix",
"using",
"dense",
"matrix",
"computations",
"."
] | python | train |
google/tangent | tangent/utils.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/utils.py#L700-L722 | def push_stack(stack, substack, op_id):
"""Proxy of push, where we know we're pushing a stack onto a stack.
Used when differentiating call trees,where sub-functions get their own stack.
See push() for more.
Args:
stack: The stack object, which must support appending values.
substack: The stack to append.
op_id: A unique variable that is also passed into the corresponding pop.
Allows optimization passes to track pairs of pushes and pops.
Raises:
ValueError: If a non-stack value for `substack` is passed.
"""
if substack is not None and not isinstance(substack, Stack):
raise ValueError(
'Substack should be type tangent.Stack or None, instead found %s' %
type(substack))
if __debug__:
stack.append((substack, op_id))
else:
stack.append(substack) | [
"def",
"push_stack",
"(",
"stack",
",",
"substack",
",",
"op_id",
")",
":",
"if",
"substack",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"substack",
",",
"Stack",
")",
":",
"raise",
"ValueError",
"(",
"'Substack should be type tangent.Stack or None, i... | Proxy of push, where we know we're pushing a stack onto a stack.
Used when differentiating call trees,where sub-functions get their own stack.
See push() for more.
Args:
stack: The stack object, which must support appending values.
substack: The stack to append.
op_id: A unique variable that is also passed into the corresponding pop.
Allows optimization passes to track pairs of pushes and pops.
Raises:
ValueError: If a non-stack value for `substack` is passed. | [
"Proxy",
"of",
"push",
"where",
"we",
"know",
"we",
"re",
"pushing",
"a",
"stack",
"onto",
"a",
"stack",
"."
] | python | train |
PyCQA/astroid | astroid/as_string.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L363-L367 | def visit_keyword(self, node):
"""return an astroid.Keyword node as string"""
if node.arg is None:
return "**%s" % node.value.accept(self)
return "%s=%s" % (node.arg, node.value.accept(self)) | [
"def",
"visit_keyword",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"arg",
"is",
"None",
":",
"return",
"\"**%s\"",
"%",
"node",
".",
"value",
".",
"accept",
"(",
"self",
")",
"return",
"\"%s=%s\"",
"%",
"(",
"node",
".",
"arg",
",",
"no... | return an astroid.Keyword node as string | [
"return",
"an",
"astroid",
".",
"Keyword",
"node",
"as",
"string"
] | python | train |
xflr6/gsheets | gsheets/tools.py | https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/tools.py#L133-L140 | def uniqued(iterable):
"""Return unique list of ``iterable`` items preserving order.
>>> uniqued('spameggs')
['s', 'p', 'a', 'm', 'e', 'g']
"""
seen = set()
return [item for item in iterable if item not in seen and not seen.add(item)] | [
"def",
"uniqued",
"(",
"iterable",
")",
":",
"seen",
"=",
"set",
"(",
")",
"return",
"[",
"item",
"for",
"item",
"in",
"iterable",
"if",
"item",
"not",
"in",
"seen",
"and",
"not",
"seen",
".",
"add",
"(",
"item",
")",
"]"
] | Return unique list of ``iterable`` items preserving order.
>>> uniqued('spameggs')
['s', 'p', 'a', 'm', 'e', 'g'] | [
"Return",
"unique",
"list",
"of",
"iterable",
"items",
"preserving",
"order",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/extensions/autoreload.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/autoreload.py#L132-L136 | def _get_compiled_ext():
"""Official way to get the extension of compiled files (.pyc or .pyo)"""
for ext, mode, typ in imp.get_suffixes():
if typ == imp.PY_COMPILED:
return ext | [
"def",
"_get_compiled_ext",
"(",
")",
":",
"for",
"ext",
",",
"mode",
",",
"typ",
"in",
"imp",
".",
"get_suffixes",
"(",
")",
":",
"if",
"typ",
"==",
"imp",
".",
"PY_COMPILED",
":",
"return",
"ext"
] | Official way to get the extension of compiled files (.pyc or .pyo) | [
"Official",
"way",
"to",
"get",
"the",
"extension",
"of",
"compiled",
"files",
"(",
".",
"pyc",
"or",
".",
"pyo",
")"
] | python | test |
jbasko/configmanager | configmanager/items.py | https://github.com/jbasko/configmanager/blob/1d7229ce367143c7210d8e5f0782de03945a1721/configmanager/items.py#L178-L197 | def _get_envvar_value(self):
"""
Internal helper to get item value from an environment variable
if item is controlled by one, and if the variable is set.
Returns not_set otherwise.
"""
envvar_name = None
if self.envvar is True:
envvar_name = self.envvar_name
if envvar_name is None:
envvar_name = '_'.join(self.get_path()).upper()
elif self.envvar:
envvar_name = self.envvar
if envvar_name and envvar_name in os.environ:
return self.type.deserialize(os.environ[envvar_name])
else:
return not_set | [
"def",
"_get_envvar_value",
"(",
"self",
")",
":",
"envvar_name",
"=",
"None",
"if",
"self",
".",
"envvar",
"is",
"True",
":",
"envvar_name",
"=",
"self",
".",
"envvar_name",
"if",
"envvar_name",
"is",
"None",
":",
"envvar_name",
"=",
"'_'",
".",
"join",
... | Internal helper to get item value from an environment variable
if item is controlled by one, and if the variable is set.
Returns not_set otherwise. | [
"Internal",
"helper",
"to",
"get",
"item",
"value",
"from",
"an",
"environment",
"variable",
"if",
"item",
"is",
"controlled",
"by",
"one",
"and",
"if",
"the",
"variable",
"is",
"set",
"."
] | python | train |
miku/gluish | gluish/intervals.py | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L73-L77 | def biweekly(date=datetime.date.today()):
"""
Every two weeks.
"""
return datetime.date(date.year, date.month, 1 if date.day < 15 else 15) | [
"def",
"biweekly",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"return",
"datetime",
".",
"date",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"1",
"if",
"date",
".",
"day",
"<",
"15",
"else",
"15",
... | Every two weeks. | [
"Every",
"two",
"weeks",
"."
] | python | train |
LionelAuroux/pyrser | pyrser/type_system/scope.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/scope.py#L406-L504 | def get_by_params(self, params: [Scope]) -> (Scope, [[Scope]]):
""" Retrieve a Set of all signature that match the parameter list.
Return a pair:
pair[0] the overloads for the functions
pair[1] the overloads for the parameters
(a list of candidate list of parameters)
"""
lst = []
scopep = []
# for each of our signatures
for s in self.values():
# for each params of this signature
if hasattr(s, 'tparams'):
# number of matched params
mcnt = 0
# temporary collect
nbparam_sig = (0 if s.tparams is None else len(s.tparams))
nbparam_candidates = len(params)
# don't treat signature too short
if nbparam_sig > nbparam_candidates:
continue
# don't treat call signature too long if not variadic
if nbparam_candidates > nbparam_sig and not s.variadic:
continue
tmp = [None] * nbparam_candidates
variadic_types = []
for i in range(nbparam_candidates):
tmp[i] = Scope(state=StateScope.LINKED)
tmp[i].set_parent(self)
# match param of the expr
if i < nbparam_sig:
if params[i].state == StateScope.EMBEDDED:
raise ValueError(
("params[%d] of get_by_params is a StateScope."
+ "EMBEDDED scope... "
+ "read the doc and try a StateScope.FREE"
+ " or StateScope.LINKED.") % i
)
m = params[i].get_by_return_type(s.tparams[i])
if len(m) > 0:
mcnt += 1
tmp[i].update(m)
else:
# co/contra-variance
# we just need to search a t1->t2
# and add it into the tree (with/without warnings)
t1 = params[i]
t2 = s.tparams[i]
# if exist a fun (t1) -> t2
(is_convertible,
signature,
translator
) = t1.findTranslationTo(t2)
if is_convertible:
# add a translator in the EvalCtx
signature.use_translator(translator)
mcnt += 1
nscope = Scope(
sig=[signature],
state=StateScope.LINKED,
is_namespace=False
)
nscope.set_parent(self)
tmp[i].update(nscope)
elif s.tparams[i].is_polymorphic:
# handle polymorphic parameter
mcnt += 1
if not isinstance(params[i], Scope):
raise Exception(
"params[%d] must be a Scope" % i
)
tmp[i].update(params[i])
else:
# handle polymorphic return type
m = params[i].get_all_polymorphic_return()
if len(m) > 0:
mcnt += 1
tmp[i].update(m)
# for variadic extra parameters
else:
mcnt += 1
if not isinstance(params[i], Scope):
raise Exception("params[%d] must be a Scope" % i)
variadic_types.append(params[i].first().tret)
tmp[i].update(params[i])
# we have match all candidates
if mcnt == len(params):
# select this signature but
# box it (with EvalCtx) for type resolution
lst.append(EvalCtx.from_sig(s))
lastentry = lst[-1]
if lastentry.variadic:
lastentry.use_variadic_types(variadic_types)
scopep.append(tmp)
rscope = Scope(sig=lst, state=StateScope.LINKED, is_namespace=False)
# inherit type/translation from parent
rscope.set_parent(self)
return (rscope, scopep) | [
"def",
"get_by_params",
"(",
"self",
",",
"params",
":",
"[",
"Scope",
"]",
")",
"->",
"(",
"Scope",
",",
"[",
"[",
"Scope",
"]",
"]",
")",
":",
"lst",
"=",
"[",
"]",
"scopep",
"=",
"[",
"]",
"# for each of our signatures",
"for",
"s",
"in",
"self"... | Retrieve a Set of all signature that match the parameter list.
Return a pair:
pair[0] the overloads for the functions
pair[1] the overloads for the parameters
(a list of candidate list of parameters) | [
"Retrieve",
"a",
"Set",
"of",
"all",
"signature",
"that",
"match",
"the",
"parameter",
"list",
".",
"Return",
"a",
"pair",
":"
] | python | test |
benhoff/vexbot | vexbot/util/messaging.py | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/util/messaging.py#L3-L17 | def get_addresses(message: list) -> list:
"""
parses a raw list from zmq to get back the components that are the address
messages are broken by the addresses in the beginning and then the
message, like this: ```addresses | '' | message ```
"""
# Need the address so that we know who to send the message back to
addresses = []
for address in message:
# if we hit a blank string, then we've got all the addresses
if address == b'':
break
addresses.append(address)
return addresses | [
"def",
"get_addresses",
"(",
"message",
":",
"list",
")",
"->",
"list",
":",
"# Need the address so that we know who to send the message back to",
"addresses",
"=",
"[",
"]",
"for",
"address",
"in",
"message",
":",
"# if we hit a blank string, then we've got all the addresses... | parses a raw list from zmq to get back the components that are the address
messages are broken by the addresses in the beginning and then the
message, like this: ```addresses | '' | message ``` | [
"parses",
"a",
"raw",
"list",
"from",
"zmq",
"to",
"get",
"back",
"the",
"components",
"that",
"are",
"the",
"address",
"messages",
"are",
"broken",
"by",
"the",
"addresses",
"in",
"the",
"beginning",
"and",
"then",
"the",
"message",
"like",
"this",
":",
... | python | train |
IdentityPython/fedoidcmsg | src/fedoidcmsg/operator.py | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L237-L329 | def _unpack(self, ms_dict, keyjar, cls, jwt_ms=None, liss=None):
"""
:param ms_dict: Metadata statement as a dictionary
:param keyjar: A keyjar with the necessary FO keys
:param cls: What class to map the metadata into
:param jwt_ms: Metadata statement as a JWS
:param liss: List of FO issuer IDs
:return: ParseInfo instance
"""
if liss is None:
liss = []
_pr = ParseInfo()
_pr.input = ms_dict
ms_flag = False
if 'metadata_statements' in ms_dict:
ms_flag = True
for iss, _ms in ms_dict['metadata_statements'].items():
if liss and iss not in liss:
continue
_pr = self._ums(_pr, _ms, keyjar)
if 'metadata_statement_uris' in ms_dict:
ms_flag = True
if self.httpcli:
for iss, url in ms_dict['metadata_statement_uris'].items():
if liss and iss not in liss:
continue
rsp = self.httpcli(method='GET', url=url,
verify=self.verify_ssl)
if rsp.status_code == 200:
_pr = self._ums(_pr, rsp.text, keyjar)
else:
raise ParseError(
'Could not fetch jws from {}'.format(url))
for _ms in _pr.parsed_statement:
if _ms: # can be None
loaded = False
try:
keyjar.import_jwks_as_json(_ms['signing_keys'],
ms_dict['iss'])
except KeyError:
pass
except TypeError:
try:
keyjar.import_jwks(_ms['signing_keys'], ms_dict['iss'])
except Exception as err:
logger.error(err)
raise
else:
loaded = True
else:
loaded = True
if loaded:
logger.debug(
'Loaded signing keys belonging to {} into the '
'keyjar'.format(ms_dict['iss']))
if ms_flag is True and not _pr.parsed_statement:
return _pr
if jwt_ms:
logger.debug("verifying signed JWT: {}".format(jwt_ms))
try:
_pr.result = cls().from_jwt(jwt_ms, keyjar=keyjar)
except MissingSigningKey:
if 'signing_keys' in ms_dict:
try:
_pr.result = self.self_signed(ms_dict, jwt_ms, cls)
except MissingSigningKey as err:
logger.error('Encountered: {}'.format(err))
_pr.error[jwt_ms] = err
except (JWSException, BadSignature, KeyError) as err:
logger.error('Encountered: {}'.format(err))
_pr.error[jwt_ms] = err
else:
_pr.result = ms_dict
if _pr.result and _pr.parsed_statement:
_prr = _pr.result
_res = {}
for x in _pr.parsed_statement:
if x:
_res[get_fo(x)] = x
_msg = Message(**_res)
logger.debug('Resulting metadata statement: {}'.format(_msg))
_pr.result['metadata_statements'] = _msg
return _pr | [
"def",
"_unpack",
"(",
"self",
",",
"ms_dict",
",",
"keyjar",
",",
"cls",
",",
"jwt_ms",
"=",
"None",
",",
"liss",
"=",
"None",
")",
":",
"if",
"liss",
"is",
"None",
":",
"liss",
"=",
"[",
"]",
"_pr",
"=",
"ParseInfo",
"(",
")",
"_pr",
".",
"in... | :param ms_dict: Metadata statement as a dictionary
:param keyjar: A keyjar with the necessary FO keys
:param cls: What class to map the metadata into
:param jwt_ms: Metadata statement as a JWS
:param liss: List of FO issuer IDs
:return: ParseInfo instance | [
":",
"param",
"ms_dict",
":",
"Metadata",
"statement",
"as",
"a",
"dictionary",
":",
"param",
"keyjar",
":",
"A",
"keyjar",
"with",
"the",
"necessary",
"FO",
"keys",
":",
"param",
"cls",
":",
"What",
"class",
"to",
"map",
"the",
"metadata",
"into",
":",
... | python | test |
jepegit/cellpy | cellpy/readers/dbreader.py | https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/dbreader.py#L122-L151 | def _open_sheet(self, dtypes_dict=None):
"""Opens sheets and returns it"""
table_name = self.db_sheet_table
header_row = self.db_header_row
nrows = self.nrows
if dtypes_dict is None:
dtypes_dict = self.dtypes_dict
rows_to_skip = self.skiprows
logging.debug(f"Trying to open the file {self.db_file}")
logging.debug(f"Number of rows: {nrows}")
logging.debug(f"Skipping the following rows: {rows_to_skip}")
logging.debug(f"Declaring the following dtyps: {dtypes_dict}")
work_book = pd.ExcelFile(self.db_file)
try:
sheet = work_book.parse(
table_name, header=header_row, skiprows=rows_to_skip,
dtype=dtypes_dict, nrows=nrows,
)
except ValueError as e:
logging.debug("Could not parse all the columns (ValueError) "
"using given dtypes. Trying without dtypes.")
logging.debug(str(e))
sheet = work_book.parse(
table_name, header=header_row, skiprows=rows_to_skip,
nrows=nrows,
)
return sheet | [
"def",
"_open_sheet",
"(",
"self",
",",
"dtypes_dict",
"=",
"None",
")",
":",
"table_name",
"=",
"self",
".",
"db_sheet_table",
"header_row",
"=",
"self",
".",
"db_header_row",
"nrows",
"=",
"self",
".",
"nrows",
"if",
"dtypes_dict",
"is",
"None",
":",
"dt... | Opens sheets and returns it | [
"Opens",
"sheets",
"and",
"returns",
"it"
] | python | train |
marcomusy/vtkplotter | vtkplotter/actors.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1002-L1011 | def centerOfMass(self):
"""Get the center of mass of actor.
.. hint:: |fatlimb| |fatlimb.py|_
"""
cmf = vtk.vtkCenterOfMass()
cmf.SetInputData(self.polydata(True))
cmf.Update()
c = cmf.GetCenter()
return np.array(c) | [
"def",
"centerOfMass",
"(",
"self",
")",
":",
"cmf",
"=",
"vtk",
".",
"vtkCenterOfMass",
"(",
")",
"cmf",
".",
"SetInputData",
"(",
"self",
".",
"polydata",
"(",
"True",
")",
")",
"cmf",
".",
"Update",
"(",
")",
"c",
"=",
"cmf",
".",
"GetCenter",
"... | Get the center of mass of actor.
.. hint:: |fatlimb| |fatlimb.py|_ | [
"Get",
"the",
"center",
"of",
"mass",
"of",
"actor",
"."
] | python | train |
ajslater/picopt | picopt/files.py | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/files.py#L19-L48 | def _cleanup_after_optimize_aux(filename, new_filename, old_format,
new_format):
"""
Replace old file with better one or discard new wasteful file.
"""
bytes_in = 0
bytes_out = 0
final_filename = filename
try:
bytes_in = os.stat(filename).st_size
bytes_out = os.stat(new_filename).st_size
if (bytes_out > 0) and ((bytes_out < bytes_in) or Settings.bigger):
if old_format != new_format:
final_filename = replace_ext(filename,
new_format.lower())
rem_filename = filename + REMOVE_EXT
if not Settings.test:
os.rename(filename, rem_filename)
os.rename(new_filename, final_filename)
os.remove(rem_filename)
else:
os.remove(new_filename)
else:
os.remove(new_filename)
bytes_out = bytes_in
except OSError as ex:
print(ex)
return final_filename, bytes_in, bytes_out | [
"def",
"_cleanup_after_optimize_aux",
"(",
"filename",
",",
"new_filename",
",",
"old_format",
",",
"new_format",
")",
":",
"bytes_in",
"=",
"0",
"bytes_out",
"=",
"0",
"final_filename",
"=",
"filename",
"try",
":",
"bytes_in",
"=",
"os",
".",
"stat",
"(",
"... | Replace old file with better one or discard new wasteful file. | [
"Replace",
"old",
"file",
"with",
"better",
"one",
"or",
"discard",
"new",
"wasteful",
"file",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/orderedmultidict/orderedmultidict.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L353-L392 | def setlist(self, key, values):
"""
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't have corresponding items with <key>
to replace are appended to the end of the list of all items.
If values is an empty list, [], <key> is deleted, equivalent in action
to del self[<key>].
Example:
omd = omdict([(1,1), (2,2)])
omd.setlist(1, [11, 111])
omd.allitems() == [(1,11), (2,2), (1,111)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [None])
omd.allitems() == [(1,None), (2,2)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [])
omd.allitems() == [(2,2)]
Returns: <self>.
"""
if not values and key in self:
self.pop(key)
else:
it = zip_longest(
list(self._map.get(key, [])), values, fillvalue=_absent)
for node, value in it:
if node is not _absent and value is not _absent:
node.value = value
elif node is _absent:
self.add(key, value)
elif value is _absent:
self._map[key].remove(node)
self._items.removenode(node)
return self | [
"def",
"setlist",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"if",
"not",
"values",
"and",
"key",
"in",
"self",
":",
"self",
".",
"pop",
"(",
"key",
")",
"else",
":",
"it",
"=",
"zip_longest",
"(",
"list",
"(",
"self",
".",
"_map",
".",
... | Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't have corresponding items with <key>
to replace are appended to the end of the list of all items.
If values is an empty list, [], <key> is deleted, equivalent in action
to del self[<key>].
Example:
omd = omdict([(1,1), (2,2)])
omd.setlist(1, [11, 111])
omd.allitems() == [(1,11), (2,2), (1,111)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [None])
omd.allitems() == [(1,None), (2,2)]
omd = omdict([(1,1), (1,11), (2,2), (1,111)])
omd.setlist(1, [])
omd.allitems() == [(2,2)]
Returns: <self>. | [
"Sets",
"<key",
">",
"s",
"list",
"of",
"values",
"to",
"<values",
">",
".",
"Existing",
"items",
"with",
"key",
"<key",
">",
"are",
"first",
"replaced",
"with",
"new",
"values",
"from",
"<values",
">",
".",
"Any",
"remaining",
"old",
"items",
"that",
... | python | train |
ricequant/rqalpha | rqalpha/interface.py | https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/interface.py#L360-L398 | def history_bars(self, instrument, bar_count, frequency, fields, dt, skip_suspended=True,
include_now=False, adjust_type='pre', adjust_orig=None):
"""
获取历史数据
:param instrument: 合约对象
:type instrument: :class:`~Instrument`
:param int bar_count: 获取的历史数据数量
:param str frequency: 周期频率,`1d` 表示日周期, `1m` 表示分钟周期
:param str fields: 返回数据字段
========================= ===================================================
fields 字段名
========================= ===================================================
datetime 时间戳
open 开盘价
high 最高价
low 最低价
close 收盘价
volume 成交量
total_turnover 成交额
datetime int类型时间戳
open_interest 持仓量(期货专用)
basis_spread 期现差(股指期货专用)
settlement 结算价(期货日线专用)
prev_settlement 结算价(期货日线专用)
========================= ===================================================
:param datetime.datetime dt: 时间
:param bool skip_suspended: 是否跳过停牌日
:param bool include_now: 是否包含当天最新数据
:param str adjust_type: 复权类型,'pre', 'none', 'post'
:param datetime.datetime adjust_orig: 复权起点;
:return: `numpy.ndarray`
"""
raise NotImplementedError | [
"def",
"history_bars",
"(",
"self",
",",
"instrument",
",",
"bar_count",
",",
"frequency",
",",
"fields",
",",
"dt",
",",
"skip_suspended",
"=",
"True",
",",
"include_now",
"=",
"False",
",",
"adjust_type",
"=",
"'pre'",
",",
"adjust_orig",
"=",
"None",
")... | 获取历史数据
:param instrument: 合约对象
:type instrument: :class:`~Instrument`
:param int bar_count: 获取的历史数据数量
:param str frequency: 周期频率,`1d` 表示日周期, `1m` 表示分钟周期
:param str fields: 返回数据字段
========================= ===================================================
fields 字段名
========================= ===================================================
datetime 时间戳
open 开盘价
high 最高价
low 最低价
close 收盘价
volume 成交量
total_turnover 成交额
datetime int类型时间戳
open_interest 持仓量(期货专用)
basis_spread 期现差(股指期货专用)
settlement 结算价(期货日线专用)
prev_settlement 结算价(期货日线专用)
========================= ===================================================
:param datetime.datetime dt: 时间
:param bool skip_suspended: 是否跳过停牌日
:param bool include_now: 是否包含当天最新数据
:param str adjust_type: 复权类型,'pre', 'none', 'post'
:param datetime.datetime adjust_orig: 复权起点;
:return: `numpy.ndarray` | [
"获取历史数据"
] | python | train |
EventTeam/beliefs | src/beliefs/beliefstate.py | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L460-L473 | def number_of_singleton_referents(self):
"""
Returns the number of singleton elements of the referential domain that are
compatible with the current belief state.
This is the size of the union of all referent sets.
"""
if self.__dict__['referential_domain']:
ct = 0
for i in self.iter_singleton_referents():
ct += 1
return ct
else:
raise Exception("self.referential_domain must be defined") | [
"def",
"number_of_singleton_referents",
"(",
"self",
")",
":",
"if",
"self",
".",
"__dict__",
"[",
"'referential_domain'",
"]",
":",
"ct",
"=",
"0",
"for",
"i",
"in",
"self",
".",
"iter_singleton_referents",
"(",
")",
":",
"ct",
"+=",
"1",
"return",
"ct",
... | Returns the number of singleton elements of the referential domain that are
compatible with the current belief state.
This is the size of the union of all referent sets. | [
"Returns",
"the",
"number",
"of",
"singleton",
"elements",
"of",
"the",
"referential",
"domain",
"that",
"are",
"compatible",
"with",
"the",
"current",
"belief",
"state",
"."
] | python | train |
LogicalDash/LiSE | allegedb/allegedb/cache.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L931-L938 | def iter_predecessors(self, graph, dest, branch, turn, tick, *, forward=None):
"""Iterate over predecessors to a given destination node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.predecessors[graph, dest], branch, turn, tick)[0]
return
if forward is None:
forward = self.db._forward
yield from self._get_origcache(graph, dest, branch, turn, tick, forward=forward) | [
"def",
"iter_predecessors",
"(",
"self",
",",
"graph",
",",
"dest",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
"=",
"None",
")",
":",
"if",
"self",
".",
"db",
".",
"_no_kc",
":",
"yield",
"from",
"self",
".",
"_adds_dels_sucpr... | Iterate over predecessors to a given destination node at a given time. | [
"Iterate",
"over",
"predecessors",
"to",
"a",
"given",
"destination",
"node",
"at",
"a",
"given",
"time",
"."
] | python | train |
nugget/python-insteonplm | insteonplm/address.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/address.py#L116-L121 | def hex(self):
"""Emit the address in bare hex format (aabbcc)."""
addrstr = '000000'
if self.addr is not None:
addrstr = binascii.hexlify(self.addr).decode()
return addrstr | [
"def",
"hex",
"(",
"self",
")",
":",
"addrstr",
"=",
"'000000'",
"if",
"self",
".",
"addr",
"is",
"not",
"None",
":",
"addrstr",
"=",
"binascii",
".",
"hexlify",
"(",
"self",
".",
"addr",
")",
".",
"decode",
"(",
")",
"return",
"addrstr"
] | Emit the address in bare hex format (aabbcc). | [
"Emit",
"the",
"address",
"in",
"bare",
"hex",
"format",
"(",
"aabbcc",
")",
"."
] | python | train |
bspaans/python-mingus | mingus/midi/sequencer.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L98-L102 | def detach(self, listener):
"""Detach a listening object so that it won't receive any events
anymore."""
if listener in self.listeners:
self.listeners.remove(listener) | [
"def",
"detach",
"(",
"self",
",",
"listener",
")",
":",
"if",
"listener",
"in",
"self",
".",
"listeners",
":",
"self",
".",
"listeners",
".",
"remove",
"(",
"listener",
")"
] | Detach a listening object so that it won't receive any events
anymore. | [
"Detach",
"a",
"listening",
"object",
"so",
"that",
"it",
"won",
"t",
"receive",
"any",
"events",
"anymore",
"."
] | python | train |
angr/claripy | claripy/ast/fp.py | https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/ast/fp.py#L16-L27 | def to_fp(self, sort, rm=None):
"""
Convert this float to a different sort
:param sort: The sort to convert to
:param rm: Optional: The rounding mode to use
:return: An FP AST
"""
if rm is None:
rm = fp.RM.default()
return fpToFP(rm, self, sort) | [
"def",
"to_fp",
"(",
"self",
",",
"sort",
",",
"rm",
"=",
"None",
")",
":",
"if",
"rm",
"is",
"None",
":",
"rm",
"=",
"fp",
".",
"RM",
".",
"default",
"(",
")",
"return",
"fpToFP",
"(",
"rm",
",",
"self",
",",
"sort",
")"
] | Convert this float to a different sort
:param sort: The sort to convert to
:param rm: Optional: The rounding mode to use
:return: An FP AST | [
"Convert",
"this",
"float",
"to",
"a",
"different",
"sort"
] | python | train |
72squared/redpipe | redpipe/keyspaces.py | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1503-L1531 | def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param end:
:param desc:
:param withscores:
:param score_cast_func:
:return:
"""
with self.pipe as pipe:
f = Future()
res = pipe.zrange(
self.redis_key(name), start, end, desc=desc,
withscores=withscores, score_cast_func=score_cast_func)
def cb():
if withscores:
f.set([(self.valueparse.decode(v), s) for v, s in
res.result])
else:
f.set([self.valueparse.decode(v) for v in res.result])
pipe.on_execute(cb)
return f | [
"def",
"zrange",
"(",
"self",
",",
"name",
",",
"start",
",",
"end",
",",
"desc",
"=",
"False",
",",
"withscores",
"=",
"False",
",",
"score_cast_func",
"=",
"float",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"("... | Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param end:
:param desc:
:param withscores:
:param score_cast_func:
:return: | [
"Returns",
"all",
"the",
"elements",
"including",
"between",
"start",
"(",
"non",
"included",
")",
"and",
"stop",
"(",
"included",
")",
"."
] | python | train |
shmir/PyIxExplorer | ixexplorer/ixe_port.py | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_port.py#L169-L181 | def reserve(self, force=False):
""" Reserve port.
:param force: True - take forcefully, False - fail if port is reserved by other user
"""
if not force:
try:
self.api.call_rc('ixPortTakeOwnership {}'.format(self.uri))
except Exception as _:
raise TgnError('Failed to take ownership for port {} current owner is {}'.format(self, self.owner))
else:
self.api.call_rc('ixPortTakeOwnership {} force'.format(self.uri)) | [
"def",
"reserve",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
":",
"try",
":",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixPortTakeOwnership {}'",
".",
"format",
"(",
"self",
".",
"uri",
")",
")",
"except",
"Exception",
... | Reserve port.
:param force: True - take forcefully, False - fail if port is reserved by other user | [
"Reserve",
"port",
"."
] | python | train |
ejeschke/ginga | ginga/Bindings.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L2658-L2704 | def mode_key_down(self, viewer, keyname):
"""This method is called when a key is pressed and was not handled
by some other handler with precedence, such as a subcanvas.
"""
# Is this a mode key?
if keyname not in self.mode_map:
if (keyname not in self.mode_tbl) or (self._kbdmode != 'meta'):
# No
return False
bnch = self.mode_tbl[keyname]
else:
bnch = self.mode_map[keyname]
mode_name = bnch.name
self.logger.debug("cur mode='%s' mode pressed='%s'" % (
self._kbdmode, mode_name))
if mode_name == self._kbdmode:
# <== same key was pressed that started the mode we're in
# standard handling is to close the mode when we press the
# key again that started that mode
self.reset_mode(viewer)
return True
if self._delayed_reset:
# <== this shouldn't happen, but put here to reset handling
# of delayed_reset just in case (see cursor up handling)
self._delayed_reset = False
return True
if ((self._kbdmode in (None, 'meta')) or
(self._kbdmode_type != 'locked') or (mode_name == 'meta')):
if self._kbdmode is not None:
self.reset_mode(viewer)
# activate this mode
if self._kbdmode in (None, 'meta'):
mode_type = bnch.type
if mode_type is None:
mode_type = self._kbdmode_type_default
self.set_mode(mode_name, mode_type)
if bnch.msg is not None:
viewer.onscreen_message(bnch.msg)
return True
return False | [
"def",
"mode_key_down",
"(",
"self",
",",
"viewer",
",",
"keyname",
")",
":",
"# Is this a mode key?",
"if",
"keyname",
"not",
"in",
"self",
".",
"mode_map",
":",
"if",
"(",
"keyname",
"not",
"in",
"self",
".",
"mode_tbl",
")",
"or",
"(",
"self",
".",
... | This method is called when a key is pressed and was not handled
by some other handler with precedence, such as a subcanvas. | [
"This",
"method",
"is",
"called",
"when",
"a",
"key",
"is",
"pressed",
"and",
"was",
"not",
"handled",
"by",
"some",
"other",
"handler",
"with",
"precedence",
"such",
"as",
"a",
"subcanvas",
"."
] | python | train |
mathiasertl/xmpp-backends | xmpp_backends/base.py | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L174-L192 | def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module | [
"def",
"module",
"(",
"self",
")",
":",
"if",
"self",
".",
"_module",
"is",
"None",
":",
"if",
"self",
".",
"library",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Backend '%s' doesn't specify a library attribute\"",
"%",
"self",
".",
"__class__",
")",
... | The module specified by the ``library`` attribute. | [
"The",
"module",
"specified",
"by",
"the",
"library",
"attribute",
"."
] | python | train |
jaegertracing/jaeger-client-python | jaeger_client/span.py | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/span.py#L76-L90 | def set_tag(self, key, value):
"""
:param key:
:param value:
"""
with self.update_lock:
if key == ext_tags.SAMPLING_PRIORITY and not self._set_sampling_priority(value):
return self
if self.is_sampled():
tag = thrift.make_tag(
key=key,
value=value,
max_length=self.tracer.max_tag_value_length, )
self.tags.append(tag)
return self | [
"def",
"set_tag",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"with",
"self",
".",
"update_lock",
":",
"if",
"key",
"==",
"ext_tags",
".",
"SAMPLING_PRIORITY",
"and",
"not",
"self",
".",
"_set_sampling_priority",
"(",
"value",
")",
":",
"return",
"s... | :param key:
:param value: | [
":",
"param",
"key",
":",
":",
"param",
"value",
":"
] | python | train |
annoviko/pyclustering | pyclustering/cluster/xmeans.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/xmeans.py#L412-L460 | def __bayesian_information_criterion(self, clusters, centers):
"""!
@brief Calculates splitting criterion for input clusters using bayesian information criterion.
@param[in] clusters (list): Clusters for which splitting criterion should be calculated.
@param[in] centers (list): Centers of the clusters.
@return (double) Splitting criterion in line with bayesian information criterion.
High value of splitting criterion means that current structure is much better.
@see __minimum_noiseless_description_length(clusters, centers)
"""
scores = [float('inf')] * len(clusters) # splitting criterion
dimension = len(self.__pointer_data[0])
# estimation of the noise variance in the data set
sigma_sqrt = 0.0
K = len(clusters)
N = 0.0
for index_cluster in range(0, len(clusters), 1):
for index_object in clusters[index_cluster]:
sigma_sqrt += euclidean_distance_square(self.__pointer_data[index_object], centers[index_cluster]);
N += len(clusters[index_cluster])
if N - K > 0:
sigma_sqrt /= (N - K)
p = (K - 1) + dimension * K + 1
# in case of the same points, sigma_sqrt can be zero (issue: #407)
sigma_multiplier = 0.0
if sigma_sqrt <= 0.0:
sigma_multiplier = float('-inf')
else:
sigma_multiplier = dimension * 0.5 * log(sigma_sqrt)
# splitting criterion
for index_cluster in range(0, len(clusters), 1):
n = len(clusters[index_cluster])
L = n * log(n) - n * log(N) - n * 0.5 * log(2.0 * numpy.pi) - n * sigma_multiplier - (n - K) * 0.5
# BIC calculation
scores[index_cluster] = L - p * 0.5 * log(N)
return sum(scores) | [
"def",
"__bayesian_information_criterion",
"(",
"self",
",",
"clusters",
",",
"centers",
")",
":",
"scores",
"=",
"[",
"float",
"(",
"'inf'",
")",
"]",
"*",
"len",
"(",
"clusters",
")",
"# splitting criterion\r",
"dimension",
"=",
"len",
"(",
"self",
".",
... | !
@brief Calculates splitting criterion for input clusters using bayesian information criterion.
@param[in] clusters (list): Clusters for which splitting criterion should be calculated.
@param[in] centers (list): Centers of the clusters.
@return (double) Splitting criterion in line with bayesian information criterion.
High value of splitting criterion means that current structure is much better.
@see __minimum_noiseless_description_length(clusters, centers) | [
"!"
] | python | valid |
casebeer/audiogen | audiogen/sampler.py | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L189-L197 | def cache_finite_samples(f):
'''Decorator to cache audio samples produced by the wrapped generator.'''
cache = {}
def wrap(*args):
key = FRAME_RATE, args
if key not in cache:
cache[key] = [sample for sample in f(*args)]
return (sample for sample in cache[key])
return wrap | [
"def",
"cache_finite_samples",
"(",
"f",
")",
":",
"cache",
"=",
"{",
"}",
"def",
"wrap",
"(",
"*",
"args",
")",
":",
"key",
"=",
"FRAME_RATE",
",",
"args",
"if",
"key",
"not",
"in",
"cache",
":",
"cache",
"[",
"key",
"]",
"=",
"[",
"sample",
"fo... | Decorator to cache audio samples produced by the wrapped generator. | [
"Decorator",
"to",
"cache",
"audio",
"samples",
"produced",
"by",
"the",
"wrapped",
"generator",
"."
] | python | train |
booktype/python-ooxml | ooxml/serialize.py | https://github.com/booktype/python-ooxml/blob/b56990a5bee2e1bc46839cec5161ff3726dc4d87/ooxml/serialize.py#L776-L794 | def serialize_endnote(ctx, document, el, root):
"Serializes endnotes."
footnote_num = el.rid
if el.rid not in ctx.endnote_list:
ctx.endnote_id += 1
ctx.endnote_list[el.rid] = ctx.endnote_id
footnote_num = ctx.endnote_list[el.rid]
note = etree.SubElement(root, 'sup')
link = etree.SubElement(note, 'a')
link.set('href', '#')
link.text = u'{}'.format(footnote_num)
fire_hooks(ctx, document, el, note, ctx.get_hook('endnote'))
return root | [
"def",
"serialize_endnote",
"(",
"ctx",
",",
"document",
",",
"el",
",",
"root",
")",
":",
"footnote_num",
"=",
"el",
".",
"rid",
"if",
"el",
".",
"rid",
"not",
"in",
"ctx",
".",
"endnote_list",
":",
"ctx",
".",
"endnote_id",
"+=",
"1",
"ctx",
".",
... | Serializes endnotes. | [
"Serializes",
"endnotes",
"."
] | python | train |
kivy/python-for-android | pythonforandroid/recipe.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/recipe.py#L1167-L1173 | def md5sum(filen):
'''Calculate the md5sum of a file.
'''
with open(filen, 'rb') as fileh:
md5 = hashlib.md5(fileh.read())
return md5.hexdigest() | [
"def",
"md5sum",
"(",
"filen",
")",
":",
"with",
"open",
"(",
"filen",
",",
"'rb'",
")",
"as",
"fileh",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
"fileh",
".",
"read",
"(",
")",
")",
"return",
"md5",
".",
"hexdigest",
"(",
")"
] | Calculate the md5sum of a file. | [
"Calculate",
"the",
"md5sum",
"of",
"a",
"file",
"."
] | python | train |
idmillington/layout | layout/managers/root.py | https://github.com/idmillington/layout/blob/c452d1d7a74c9a74f7639c1b49e2a41c4e354bb5/layout/managers/root.py#L55-L65 | def _get_smallest_dimensions(self, data):
"""A utility method to return the minimum size needed to fit
all the elements in."""
min_width = 0
min_height = 0
for element in self.elements:
if not element: continue
size = element.get_minimum_size(data)
min_width = max(min_width, size.x)
min_height = max(min_height, size.y)
return datatypes.Point(min_width, min_height) | [
"def",
"_get_smallest_dimensions",
"(",
"self",
",",
"data",
")",
":",
"min_width",
"=",
"0",
"min_height",
"=",
"0",
"for",
"element",
"in",
"self",
".",
"elements",
":",
"if",
"not",
"element",
":",
"continue",
"size",
"=",
"element",
".",
"get_minimum_s... | A utility method to return the minimum size needed to fit
all the elements in. | [
"A",
"utility",
"method",
"to",
"return",
"the",
"minimum",
"size",
"needed",
"to",
"fit",
"all",
"the",
"elements",
"in",
"."
] | python | train |
ethereum/py-evm | eth/db/header.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L286-L320 | def _set_as_canonical_chain_head(cls, db: BaseDB, block_hash: Hash32
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain
"""
try:
header = cls._get_block_header_by_hash(db, block_hash)
except HeaderNotFound:
raise ValueError(
"Cannot use unknown block hash as canonical head: {}".format(block_hash)
)
new_canonical_headers = tuple(reversed(cls._find_new_ancestors(db, header)))
old_canonical_headers = []
for h in new_canonical_headers:
try:
old_canonical_hash = cls._get_canonical_block_hash(db, h.block_number)
except HeaderNotFound:
# no old_canonical block, and no more possible
break
else:
old_canonical_header = cls._get_block_header_by_hash(db, old_canonical_hash)
old_canonical_headers.append(old_canonical_header)
for h in new_canonical_headers:
cls._add_block_number_to_hash_lookup(db, h)
db.set(SchemaV1.make_canonical_head_hash_lookup_key(), header.hash)
return new_canonical_headers, tuple(old_canonical_headers) | [
"def",
"_set_as_canonical_chain_head",
"(",
"cls",
",",
"db",
":",
"BaseDB",
",",
"block_hash",
":",
"Hash32",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"try",
":... | Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain | [
"Sets",
"the",
"canonical",
"chain",
"HEAD",
"to",
"the",
"block",
"header",
"as",
"specified",
"by",
"the",
"given",
"block",
"hash",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/linode.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/linode.py#L1661-L1671 | def _get_status_descr_by_id(status_id):
'''
Return linode status by ID
status_id
linode VM status ID
'''
for status_name, status_data in six.iteritems(LINODE_STATUS):
if status_data['code'] == int(status_id):
return status_data['descr']
return LINODE_STATUS.get(status_id, None) | [
"def",
"_get_status_descr_by_id",
"(",
"status_id",
")",
":",
"for",
"status_name",
",",
"status_data",
"in",
"six",
".",
"iteritems",
"(",
"LINODE_STATUS",
")",
":",
"if",
"status_data",
"[",
"'code'",
"]",
"==",
"int",
"(",
"status_id",
")",
":",
"return",... | Return linode status by ID
status_id
linode VM status ID | [
"Return",
"linode",
"status",
"by",
"ID"
] | python | train |
openvax/varcode | varcode/effects/effect_ordering.py | https://github.com/openvax/varcode/blob/981633db45ca2b31f76c06894a7360ea5d70a9b8/varcode/effects/effect_ordering.py#L316-L331 | def select_between_exonic_splice_site_and_alternate_effect(effect):
"""
If the given effect is an ExonicSpliceSite then it might contain
an alternate effect of higher priority. In that case, return the
alternate effect. Otherwise, this acts as an identity function.
"""
if effect.__class__ is not ExonicSpliceSite:
return effect
if effect.alternate_effect is None:
return effect
splice_priority = effect_priority(effect)
alternate_priority = effect_priority(effect.alternate_effect)
if splice_priority > alternate_priority:
return effect
else:
return effect.alternate_effect | [
"def",
"select_between_exonic_splice_site_and_alternate_effect",
"(",
"effect",
")",
":",
"if",
"effect",
".",
"__class__",
"is",
"not",
"ExonicSpliceSite",
":",
"return",
"effect",
"if",
"effect",
".",
"alternate_effect",
"is",
"None",
":",
"return",
"effect",
"spl... | If the given effect is an ExonicSpliceSite then it might contain
an alternate effect of higher priority. In that case, return the
alternate effect. Otherwise, this acts as an identity function. | [
"If",
"the",
"given",
"effect",
"is",
"an",
"ExonicSpliceSite",
"then",
"it",
"might",
"contain",
"an",
"alternate",
"effect",
"of",
"higher",
"priority",
".",
"In",
"that",
"case",
"return",
"the",
"alternate",
"effect",
".",
"Otherwise",
"this",
"acts",
"a... | python | train |
AmesCornish/buttersink | buttersink/S3Store.py | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/S3Store.py#L195-L203 | def receiveVolumeInfo(self, paths):
""" Return Context Manager for a file-like (stream) object to store volume info. """
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if self._skipDryRun(logger)("receive info in '%s'", path):
return None
return _Uploader(self.bucket, path, bufferSize=theInfoBufferSize) | [
"def",
"receiveVolumeInfo",
"(",
"self",
",",
"paths",
")",
":",
"path",
"=",
"self",
".",
"selectReceivePath",
"(",
"paths",
")",
"path",
"=",
"path",
"+",
"Store",
".",
"theInfoExtension",
"if",
"self",
".",
"_skipDryRun",
"(",
"logger",
")",
"(",
"\"r... | Return Context Manager for a file-like (stream) object to store volume info. | [
"Return",
"Context",
"Manager",
"for",
"a",
"file",
"-",
"like",
"(",
"stream",
")",
"object",
"to",
"store",
"volume",
"info",
"."
] | python | train |
tuomas2/automate | src/automate/statusobject.py | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/statusobject.py#L354-L366 | def _do_change_status(self, status, force=False):
"""
This function is called by
- set_status
- _update_program_stack if active program is being changed
- thia may be launched by sensor status change.
status lock is necessary because these happen from different
threads.
This does not directly change status, but adds change request
to queue.
"""
self.system.worker_thread.put(DummyStatusWorkerTask(self._request_status_change_in_queue, status, force=force)) | [
"def",
"_do_change_status",
"(",
"self",
",",
"status",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"system",
".",
"worker_thread",
".",
"put",
"(",
"DummyStatusWorkerTask",
"(",
"self",
".",
"_request_status_change_in_queue",
",",
"status",
",",
"force... | This function is called by
- set_status
- _update_program_stack if active program is being changed
- thia may be launched by sensor status change.
status lock is necessary because these happen from different
threads.
This does not directly change status, but adds change request
to queue. | [
"This",
"function",
"is",
"called",
"by",
"-",
"set_status",
"-",
"_update_program_stack",
"if",
"active",
"program",
"is",
"being",
"changed",
"-",
"thia",
"may",
"be",
"launched",
"by",
"sensor",
"status",
"change",
".",
"status",
"lock",
"is",
"necessary",
... | python | train |
project-ncl/pnc-cli | pnc_cli/projects.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/projects.py#L44-L50 | def update_project(id, **kwargs):
"""
Update an existing Project with new information
"""
content = update_project_raw(id, **kwargs)
if content:
return utils.format_json(content) | [
"def",
"update_project",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"update_project_raw",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"content",
":",
"return",
"utils",
".",
"format_json",
"(",
"content",
")"
] | Update an existing Project with new information | [
"Update",
"an",
"existing",
"Project",
"with",
"new",
"information"
] | python | train |
Karaage-Cluster/karaage | karaage/plugins/kgapplications/views/states.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/plugins/kgapplications/views/states.py#L391-L459 | def get_next_action(self, request, application, label, roles):
""" Process the get_next_action request at the current step. """
actions = self.get_actions(request, application, roles)
# if the user is not the applicant, the steps don't apply.
if 'is_applicant' not in roles:
return super(StateWithSteps, self).get_next_action(
request, application, label, roles)
# was label supplied?
if label is None:
# no label given, find first step and redirect to it.
this_id = self._order[0]
url = base.get_url(request, application, roles, this_id)
return HttpResponseRedirect(url)
else:
# label was given, get the step position and id for it
this_id = label
if this_id not in self._steps:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
position = self._order.index(this_id)
# get the step given the label
this_step = self._steps[this_id]
# define list of allowed actions for step
step_actions = {}
if 'cancel' in actions:
step_actions['cancel'] = "state:cancel"
if 'submit' in actions and position == len(self._order) - 1:
step_actions['submit'] = "state:submit"
if position > 0:
step_actions['prev'] = self._order[position - 1]
if position < len(self._order) - 1:
step_actions['next'] = self._order[position + 1]
# process the request
if request.method == "GET":
# if GET request, state changes are not allowed
response = this_step.view(
request, application, this_id, roles, step_actions.keys())
assert isinstance(response, HttpResponse)
return response
elif request.method == "POST":
# if POST request, state changes are allowed
response = this_step.view(
request, application, this_id, roles, step_actions.keys())
assert response is not None
# If it was a HttpResponse, just return it
if isinstance(response, HttpResponse):
return response
else:
# try to lookup the response
if response not in step_actions:
raise RuntimeError(
"Invalid response '%s' from step '%s'"
% (response, this_step))
action = step_actions[response]
# process the required action
if action.startswith("state:"):
return action[6:]
else:
url = base.get_url(request, application, roles, action)
return HttpResponseRedirect(url)
# Something went wrong.
return HttpResponseBadRequest("<h1>Bad Request</h1>") | [
"def",
"get_next_action",
"(",
"self",
",",
"request",
",",
"application",
",",
"label",
",",
"roles",
")",
":",
"actions",
"=",
"self",
".",
"get_actions",
"(",
"request",
",",
"application",
",",
"roles",
")",
"# if the user is not the applicant, the steps don't... | Process the get_next_action request at the current step. | [
"Process",
"the",
"get_next_action",
"request",
"at",
"the",
"current",
"step",
"."
] | python | train |
The-Politico/politico-civic-almanac | almanac/utils/auth.py | https://github.com/The-Politico/politico-civic-almanac/blob/f97521fabd445c8a0fa97a435f6d39f517ef3892/almanac/utils/auth.py#L8-L21 | def secure(view):
"""
Authentication decorator for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator.
"""
auth_decorator = import_class(settings.AUTH_DECORATOR)
return (
view if project_settings.DEBUG
else method_decorator(auth_decorator, name='dispatch')(view)
) | [
"def",
"secure",
"(",
"view",
")",
":",
"auth_decorator",
"=",
"import_class",
"(",
"settings",
".",
"AUTH_DECORATOR",
")",
"return",
"(",
"view",
"if",
"project_settings",
".",
"DEBUG",
"else",
"method_decorator",
"(",
"auth_decorator",
",",
"name",
"=",
"'di... | Authentication decorator for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator. | [
"Authentication",
"decorator",
"for",
"views",
"."
] | python | train |
Crypto-toolbox/bitex | bitex/api/WSS/bitfinex.py | https://github.com/Crypto-toolbox/bitex/blob/56d46ea3db6de5219a72dad9b052fbabc921232f/bitex/api/WSS/bitfinex.py#L307-L364 | def process(self):
"""
Processes the Client queue, and passes the data to the respective
methods.
:return:
"""
while self.running:
if self._processor_lock.acquire(blocking=False):
if self.ping_timer:
try:
self._check_ping()
except TimeoutError:
log.exception("BitfinexWSS.ping(): TimedOut! (%ss)" %
self.ping_timer)
except (WebSocketConnectionClosedException,
ConnectionResetError):
log.exception("BitfinexWSS.ping(): Connection Error!")
self.conn = None
if not self.conn:
# The connection was killed - initiate restart
self._controller_q.put('restart')
skip_processing = False
try:
ts, data = self.receiver_q.get(timeout=0.1)
except queue.Empty:
skip_processing = True
ts = time.time()
data = None
if not skip_processing:
log.debug("Processing Data: %s", data)
if isinstance(data, list):
self.handle_data(ts, data)
else: # Not a list, hence it could be a response
try:
self.handle_response(ts, data)
except UnknownEventError:
# We don't know what event this is- Raise an
# error & log data!
log.exception("main() - UnknownEventError: %s",
data)
log.info("main() - Shutting Down due to "
"Unknown Error!")
self._controller_q.put('stop')
except ConnectionResetError:
log.info("processor Thread: Connection Was reset, "
"initiating restart")
self._controller_q.put('restart')
self._check_heartbeats(ts)
self._processor_lock.release()
else:
time.sleep(0.5) | [
"def",
"process",
"(",
"self",
")",
":",
"while",
"self",
".",
"running",
":",
"if",
"self",
".",
"_processor_lock",
".",
"acquire",
"(",
"blocking",
"=",
"False",
")",
":",
"if",
"self",
".",
"ping_timer",
":",
"try",
":",
"self",
".",
"_check_ping",
... | Processes the Client queue, and passes the data to the respective
methods.
:return: | [
"Processes",
"the",
"Client",
"queue",
"and",
"passes",
"the",
"data",
"to",
"the",
"respective",
"methods",
".",
":",
"return",
":"
] | python | train |
radjkarl/imgProcessor | imgProcessor/transformations.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/transformations.py#L78-L87 | def toFloatArray(img):
'''
transform an unsigned integer array into a
float array of the right size
'''
_D = {1: np.float32, # uint8
2: np.float32, # uint16
4: np.float64, # uint32
8: np.float64} # uint64
return img.astype(_D[img.itemsize]) | [
"def",
"toFloatArray",
"(",
"img",
")",
":",
"_D",
"=",
"{",
"1",
":",
"np",
".",
"float32",
",",
"# uint8\r",
"2",
":",
"np",
".",
"float32",
",",
"# uint16\r",
"4",
":",
"np",
".",
"float64",
",",
"# uint32\r",
"8",
":",
"np",
".",
"float64",
"... | transform an unsigned integer array into a
float array of the right size | [
"transform",
"an",
"unsigned",
"integer",
"array",
"into",
"a",
"float",
"array",
"of",
"the",
"right",
"size"
] | python | train |
pkkid/python-plexapi | plexapi/sync.py | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/sync.py#L93-L101 | def markDownloaded(self, media):
""" Mark the file as downloaded (by the nature of Plex it will be marked as downloaded within
any SyncItem where it presented).
Parameters:
media (base.Playable): the media to be marked as downloaded.
"""
url = '/sync/%s/item/%s/downloaded' % (self.clientIdentifier, media.ratingKey)
media._server.query(url, method=requests.put) | [
"def",
"markDownloaded",
"(",
"self",
",",
"media",
")",
":",
"url",
"=",
"'/sync/%s/item/%s/downloaded'",
"%",
"(",
"self",
".",
"clientIdentifier",
",",
"media",
".",
"ratingKey",
")",
"media",
".",
"_server",
".",
"query",
"(",
"url",
",",
"method",
"="... | Mark the file as downloaded (by the nature of Plex it will be marked as downloaded within
any SyncItem where it presented).
Parameters:
media (base.Playable): the media to be marked as downloaded. | [
"Mark",
"the",
"file",
"as",
"downloaded",
"(",
"by",
"the",
"nature",
"of",
"Plex",
"it",
"will",
"be",
"marked",
"as",
"downloaded",
"within",
"any",
"SyncItem",
"where",
"it",
"presented",
")",
"."
] | python | train |
wonambi-python/wonambi | wonambi/trans/select.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L690-L715 | def _create_subepochs(x, nperseg, step):
"""Transform the data into a matrix for easy manipulation
Parameters
----------
x : 1d ndarray
actual data values
nperseg : int
number of samples in each row to create
step : int
distance in samples between rows
Returns
-------
2d ndarray
a view (i.e. doesn't copy data) of the original x, with shape
determined by nperseg and step. You should use the last dimension
"""
axis = x.ndim - 1 # last dim
nsmp = x.shape[axis]
stride = x.strides[axis]
noverlap = nperseg - step
v_shape = *x.shape[:axis], (nsmp - noverlap) // step, nperseg
v_strides = *x.strides[:axis], stride * step, stride
v = as_strided(x, shape=v_shape, strides=v_strides,
writeable=False) # much safer
return v | [
"def",
"_create_subepochs",
"(",
"x",
",",
"nperseg",
",",
"step",
")",
":",
"axis",
"=",
"x",
".",
"ndim",
"-",
"1",
"# last dim",
"nsmp",
"=",
"x",
".",
"shape",
"[",
"axis",
"]",
"stride",
"=",
"x",
".",
"strides",
"[",
"axis",
"]",
"noverlap",
... | Transform the data into a matrix for easy manipulation
Parameters
----------
x : 1d ndarray
actual data values
nperseg : int
number of samples in each row to create
step : int
distance in samples between rows
Returns
-------
2d ndarray
a view (i.e. doesn't copy data) of the original x, with shape
determined by nperseg and step. You should use the last dimension | [
"Transform",
"the",
"data",
"into",
"a",
"matrix",
"for",
"easy",
"manipulation"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L267-L270 | def init_session(self):
"""create our session object"""
default_secure(self.config)
self.session = Session(config=self.config, username=u'kernel') | [
"def",
"init_session",
"(",
"self",
")",
":",
"default_secure",
"(",
"self",
".",
"config",
")",
"self",
".",
"session",
"=",
"Session",
"(",
"config",
"=",
"self",
".",
"config",
",",
"username",
"=",
"u'kernel'",
")"
] | create our session object | [
"create",
"our",
"session",
"object"
] | python | test |
Unidata/MetPy | examples/gridding/Point_Interpolation.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/examples/gridding/Point_Interpolation.py#L24-L34 | def basic_map(proj):
"""Make our basic default map for plotting"""
fig = plt.figure(figsize=(15, 10))
add_metpy_logo(fig, 0, 80, size='large')
view = fig.add_axes([0, 0, 1, 1], projection=proj)
view.set_extent([-120, -70, 20, 50])
view.add_feature(cfeature.STATES.with_scale('50m'))
view.add_feature(cfeature.OCEAN)
view.add_feature(cfeature.COASTLINE)
view.add_feature(cfeature.BORDERS, linestyle=':')
return fig, view | [
"def",
"basic_map",
"(",
"proj",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"15",
",",
"10",
")",
")",
"add_metpy_logo",
"(",
"fig",
",",
"0",
",",
"80",
",",
"size",
"=",
"'large'",
")",
"view",
"=",
"fig",
".",
"add... | Make our basic default map for plotting | [
"Make",
"our",
"basic",
"default",
"map",
"for",
"plotting"
] | python | train |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L10888-L10971 | def chart_maker(Int, Top, start=100, outfile='chart.txt'):
"""
Makes a chart for performing IZZI experiments. Print out the file and
tape it to the oven. This chart will help keep track of the different
steps.
Z : performed in zero field - enter the temperature XXX.0 in the sio
formatted measurement file created by the LabView program
I : performed in the lab field written at the top of the form
P : a pTRM step - performed at the temperature and in the lab field.
Parameters
__________
Int : list of intervals [e.g., 50,10,5]
Top : list of upper bounds for each interval [e.g., 500, 550, 600]
start : first temperature step, default is 100
outfile : name of output file, default is 'chart.txt'
Output
_________
creates a file with:
file: write down the name of the measurement file
field: write down the lab field for the infield steps (in uT)
the type of step (Z: zerofield, I: infield, P: pTRM step
temperature of the step and code for SIO-like treatment steps
XXX.0 [zero field]
XXX.1 [in field]
XXX.2 [pTRM check] - done in a lab field
date : date the step was performed
run # : an optional run number
zones I-III : field in the zones in the oven
start : time the run was started
sp : time the setpoint was reached
cool : time cooling started
"""
low, k, iz = start, 0, 0
Tzero = []
f = open('chart.txt', 'w')
vline = '\t%s\n' % (
' | | | | | | | |')
hline = '______________________________________________________________________________\n'
f.write('file:_________________ field:___________uT\n\n\n')
f.write('%s\n' % (
' date | run# | zone I | zone II | zone III | start | sp | cool|'))
f.write(hline)
f.write('\t%s' % (' 0.0'))
f.write(vline)
f.write(hline)
for k in range(len(Top)):
for t in range(low, Top[k]+Int[k], Int[k]):
if iz == 0:
Tzero.append(t) # zero field first step
f.write('%s \t %s' % ('Z', str(t)+'.'+str(iz)))
f.write(vline)
f.write(hline)
if len(Tzero) > 1:
f.write('%s \t %s' % ('P', str(Tzero[-2])+'.'+str(2)))
f.write(vline)
f.write(hline)
iz = 1
# infield after zero field first
f.write('%s \t %s' % ('I', str(t)+'.'+str(iz)))
f.write(vline)
f.write(hline)
# f.write('%s \t %s'%('T',str(t)+'.'+str(3))) # print second zero field (tail check)
# f.write(vline)
# f.write(hline)
elif iz == 1:
# infield first step
f.write('%s \t %s' % ('I', str(t)+'.'+str(iz)))
f.write(vline)
f.write(hline)
iz = 0
# zero field step (after infield)
f.write('%s \t %s' % ('Z', str(t)+'.'+str(iz)))
f.write(vline)
f.write(hline)
try:
low = Top[k]+Int[k+1] # increment to next temp step
except:
f.close()
print("output stored in: chart.txt") | [
"def",
"chart_maker",
"(",
"Int",
",",
"Top",
",",
"start",
"=",
"100",
",",
"outfile",
"=",
"'chart.txt'",
")",
":",
"low",
",",
"k",
",",
"iz",
"=",
"start",
",",
"0",
",",
"0",
"Tzero",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"'chart.txt'",
",... | Makes a chart for performing IZZI experiments. Print out the file and
tape it to the oven. This chart will help keep track of the different
steps.
Z : performed in zero field - enter the temperature XXX.0 in the sio
formatted measurement file created by the LabView program
I : performed in the lab field written at the top of the form
P : a pTRM step - performed at the temperature and in the lab field.
Parameters
__________
Int : list of intervals [e.g., 50,10,5]
Top : list of upper bounds for each interval [e.g., 500, 550, 600]
start : first temperature step, default is 100
outfile : name of output file, default is 'chart.txt'
Output
_________
creates a file with:
file: write down the name of the measurement file
field: write down the lab field for the infield steps (in uT)
the type of step (Z: zerofield, I: infield, P: pTRM step
temperature of the step and code for SIO-like treatment steps
XXX.0 [zero field]
XXX.1 [in field]
XXX.2 [pTRM check] - done in a lab field
date : date the step was performed
run # : an optional run number
zones I-III : field in the zones in the oven
start : time the run was started
sp : time the setpoint was reached
cool : time cooling started | [
"Makes",
"a",
"chart",
"for",
"performing",
"IZZI",
"experiments",
".",
"Print",
"out",
"the",
"file",
"and",
"tape",
"it",
"to",
"the",
"oven",
".",
"This",
"chart",
"will",
"help",
"keep",
"track",
"of",
"the",
"different",
"steps",
".",
"Z",
":",
"p... | python | train |
fboender/ansible-cmdb | lib/mako/lexer.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/lexer.py#L66-L94 | def match_reg(self, reg):
"""match the given regular expression object to the current text
position.
if a match occurs, update the current text and line position.
"""
mp = self.match_position
match = reg.match(self.text, self.match_position)
if match:
(start, end) = match.span()
if end == start:
self.match_position = end + 1
else:
self.match_position = end
self.matched_lineno = self.lineno
lines = re.findall(r"\n", self.text[mp:self.match_position])
cp = mp - 1
while (cp >= 0 and cp < self.textlength and self.text[cp] != '\n'):
cp -= 1
self.matched_charpos = mp - cp
self.lineno += len(lines)
#print "MATCHED:", match.group(0), "LINE START:",
# self.matched_lineno, "LINE END:", self.lineno
#print "MATCH:", regexp, "\n", self.text[mp : mp + 15], \
# (match and "TRUE" or "FALSE")
return match | [
"def",
"match_reg",
"(",
"self",
",",
"reg",
")",
":",
"mp",
"=",
"self",
".",
"match_position",
"match",
"=",
"reg",
".",
"match",
"(",
"self",
".",
"text",
",",
"self",
".",
"match_position",
")",
"if",
"match",
":",
"(",
"start",
",",
"end",
")"... | match the given regular expression object to the current text
position.
if a match occurs, update the current text and line position. | [
"match",
"the",
"given",
"regular",
"expression",
"object",
"to",
"the",
"current",
"text",
"position",
"."
] | python | train |
python-beaver/python-beaver | beaver/transports/stomp_transport.py | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/stomp_transport.py#L64-L74 | def reconnect(self):
"""Allows reconnection from when a handled
TransportException is thrown"""
try:
self.conn.close()
except Exception,e:
self.logger.warn(e)
self.createConnection()
return True | [
"def",
"reconnect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"conn",
".",
"close",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"e",
")",
"self",
".",
"createConnection",
"(",
")",
"return",
"True"... | Allows reconnection from when a handled
TransportException is thrown | [
"Allows",
"reconnection",
"from",
"when",
"a",
"handled",
"TransportException",
"is",
"thrown"
] | python | train |
novopl/peltak | src/peltak/extra/docker/logic.py | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L58-L84 | def docker_list(registry_pass):
# type: (str) -> None
""" List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password.
"""
registry = conf.get('docker.registry', None)
if registry is None:
log.err("You must define docker.registry conf variable to list images")
sys.exit(-1)
registry_user = conf.get('docker.registry_user', None)
if registry_user is None:
registry_user = click.prompt("Username")
rc = client.RegistryClient(registry, registry_user, registry_pass)
images = {x: rc.list_tags(x) for x in rc.list_images()}
shell.cprint("<32>Images in <34>{} <32>registry:", registry)
for image, tags in images.items():
shell.cprint(' <92>{}', image)
for tag in tags:
shell.cprint(' <90>{}:<35>{}', image, tag) | [
"def",
"docker_list",
"(",
"registry_pass",
")",
":",
"# type: (str) -> None",
"registry",
"=",
"conf",
".",
"get",
"(",
"'docker.registry'",
",",
"None",
")",
"if",
"registry",
"is",
"None",
":",
"log",
".",
"err",
"(",
"\"You must define docker.registry conf var... | List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password. | [
"List",
"docker",
"images",
"stored",
"in",
"the",
"remote",
"registry",
"."
] | python | train |
spyder-ide/spyder | spyder/dependencies.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/dependencies.py#L66-L75 | def add(modname, features, required_version, installed_version=None,
optional=False):
"""Add Spyder dependency"""
global DEPENDENCIES
for dependency in DEPENDENCIES:
if dependency.modname == modname:
raise ValueError("Dependency has already been registered: %s"\
% modname)
DEPENDENCIES += [Dependency(modname, features, required_version,
installed_version, optional)] | [
"def",
"add",
"(",
"modname",
",",
"features",
",",
"required_version",
",",
"installed_version",
"=",
"None",
",",
"optional",
"=",
"False",
")",
":",
"global",
"DEPENDENCIES",
"for",
"dependency",
"in",
"DEPENDENCIES",
":",
"if",
"dependency",
".",
"modname"... | Add Spyder dependency | [
"Add",
"Spyder",
"dependency"
] | python | train |
has2k1/plydata | plydata/dataframe/common.py | https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L440-L445 | def _all(cls, verb):
"""
A verb
"""
groups = set(_get_groups(verb))
return [col for col in verb.data if col not in groups] | [
"def",
"_all",
"(",
"cls",
",",
"verb",
")",
":",
"groups",
"=",
"set",
"(",
"_get_groups",
"(",
"verb",
")",
")",
"return",
"[",
"col",
"for",
"col",
"in",
"verb",
".",
"data",
"if",
"col",
"not",
"in",
"groups",
"]"
] | A verb | [
"A",
"verb"
] | python | train |
4degrees/clique | source/clique/collection.py | https://github.com/4degrees/clique/blob/af1d4fef1d60c30a870257199a4d98597d15417d/source/clique/collection.py#L77-L82 | def _update_expression(self):
'''Update internal expression.'''
self._expression = re.compile(
'^{0}(?P<index>(?P<padding>0*)\d+?){1}$'
.format(re.escape(self.head), re.escape(self.tail))
) | [
"def",
"_update_expression",
"(",
"self",
")",
":",
"self",
".",
"_expression",
"=",
"re",
".",
"compile",
"(",
"'^{0}(?P<index>(?P<padding>0*)\\d+?){1}$'",
".",
"format",
"(",
"re",
".",
"escape",
"(",
"self",
".",
"head",
")",
",",
"re",
".",
"escape",
"... | Update internal expression. | [
"Update",
"internal",
"expression",
"."
] | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/brocade_vcs_rpc/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/brocade_vcs_rpc/__init__.py#L158-L182 | def _set_get_last_config_update_time(self, v, load=False):
"""
Setter method for get_last_config_update_time, mapped from YANG variable /brocade_vcs_rpc/get_last_config_update_time (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_last_config_update_time is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_get_last_config_update_time() directly.
YANG Description: This rpc function provides time-stamp of the last
configutation change done on the managed device.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=get_last_config_update_time.get_last_config_update_time, is_leaf=True, yang_name="get-last-config-update-time", rest_name="get-last-config-update-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'hidden': u'rpccmd', u'actionpoint': u'last-config-update-time-action-point'}}, namespace='urn:brocade.com:mgmt:brocade-vcs', defining_module='brocade-vcs', yang_type='rpc', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """get_last_config_update_time must be of a type compatible with rpc""",
'defined-type': "rpc",
'generated-type': """YANGDynClass(base=get_last_config_update_time.get_last_config_update_time, is_leaf=True, yang_name="get-last-config-update-time", rest_name="get-last-config-update-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'hidden': u'rpccmd', u'actionpoint': u'last-config-update-time-action-point'}}, namespace='urn:brocade.com:mgmt:brocade-vcs', defining_module='brocade-vcs', yang_type='rpc', is_config=True)""",
})
self.__get_last_config_update_time = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_get_last_config_update_time",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"... | Setter method for get_last_config_update_time, mapped from YANG variable /brocade_vcs_rpc/get_last_config_update_time (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_last_config_update_time is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_get_last_config_update_time() directly.
YANG Description: This rpc function provides time-stamp of the last
configutation change done on the managed device. | [
"Setter",
"method",
"for",
"get_last_config_update_time",
"mapped",
"from",
"YANG",
"variable",
"/",
"brocade_vcs_rpc",
"/",
"get_last_config_update_time",
"(",
"rpc",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"i... | python | train |
rsgalloway/grit | grit/repo/proxy.py | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/proxy.py#L90-L112 | def __request(self, url, params):
"""
Make an HTTP POST request to the server and return JSON data.
:param url: HTTP URL to object.
:returns: Response as dict.
"""
log.debug('request: %s %s' %(url, str(params)))
try:
response = urlopen(url, urlencode(params)).read()
if params.get('action') != 'data':
log.debug('response: %s' % response)
if params.get('action', None) == 'data':
return response
else:
return json.loads(response)
except TypeError, e:
log.exception('request error')
raise ServerError(e)
except IOError, e:
log.error('request error: %s' % str(e))
raise ServerError(e) | [
"def",
"__request",
"(",
"self",
",",
"url",
",",
"params",
")",
":",
"log",
".",
"debug",
"(",
"'request: %s %s'",
"%",
"(",
"url",
",",
"str",
"(",
"params",
")",
")",
")",
"try",
":",
"response",
"=",
"urlopen",
"(",
"url",
",",
"urlencode",
"("... | Make an HTTP POST request to the server and return JSON data.
:param url: HTTP URL to object.
:returns: Response as dict. | [
"Make",
"an",
"HTTP",
"POST",
"request",
"to",
"the",
"server",
"and",
"return",
"JSON",
"data",
"."
] | python | train |
edx/edx-oauth2-provider | edx_oauth2_provider/oidc/core.py | https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L39-L56 | def encode(self, secret, algorithm='HS256'):
"""
Encode the set of claims to the JWT (JSON Web Token) format
according to the OpenID Connect specification:
http://openid.net/specs/openid-connect-basic-1_0.html#IDToken
Arguments:
claims (dict): A dictionary with the OpenID Connect claims.
secret (str): Secret used to encode the id_token.
algorithm (str): Algorithm used for encoding.
Defaults to HS256.
Returns encoded JWT token string.
"""
return jwt.encode(self.claims, secret, algorithm) | [
"def",
"encode",
"(",
"self",
",",
"secret",
",",
"algorithm",
"=",
"'HS256'",
")",
":",
"return",
"jwt",
".",
"encode",
"(",
"self",
".",
"claims",
",",
"secret",
",",
"algorithm",
")"
] | Encode the set of claims to the JWT (JSON Web Token) format
according to the OpenID Connect specification:
http://openid.net/specs/openid-connect-basic-1_0.html#IDToken
Arguments:
claims (dict): A dictionary with the OpenID Connect claims.
secret (str): Secret used to encode the id_token.
algorithm (str): Algorithm used for encoding.
Defaults to HS256.
Returns encoded JWT token string. | [
"Encode",
"the",
"set",
"of",
"claims",
"to",
"the",
"JWT",
"(",
"JSON",
"Web",
"Token",
")",
"format",
"according",
"to",
"the",
"OpenID",
"Connect",
"specification",
":"
] | python | train |
aparo/pyes | pyes/orm/queryset.py | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L643-L647 | def none(self):
"""
Returns an empty QuerySet.
"""
return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection) | [
"def",
"none",
"(",
"self",
")",
":",
"return",
"EmptyQuerySet",
"(",
"model",
"=",
"self",
".",
"model",
",",
"using",
"=",
"self",
".",
"_using",
",",
"connection",
"=",
"self",
".",
"_connection",
")"
] | Returns an empty QuerySet. | [
"Returns",
"an",
"empty",
"QuerySet",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.