repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
hollenstein/maspy | maspy/inference.py | ProteinGroup._addProteins | def _addProteins(self, proteinIds, containerNames):
"""Add one or multiple proteinIds to the respective container.
:param proteinIds: a proteinId or a list of proteinIds, a proteinId
must be a string.
:param containerNames: list, entries must be one or multiple of
'leading', 'subset', 'subsumableProteins' or 'proteins'
:param addToProteins: bool, if True the proteinIds are added to the
"""
proteinIds = AUX.toList(proteinIds)
for containerName in containerNames:
proteinContainer = getattr(self, containerName)
proteinContainer.update(proteinIds) | python | def _addProteins(self, proteinIds, containerNames):
"""Add one or multiple proteinIds to the respective container.
:param proteinIds: a proteinId or a list of proteinIds, a proteinId
must be a string.
:param containerNames: list, entries must be one or multiple of
'leading', 'subset', 'subsumableProteins' or 'proteins'
:param addToProteins: bool, if True the proteinIds are added to the
"""
proteinIds = AUX.toList(proteinIds)
for containerName in containerNames:
proteinContainer = getattr(self, containerName)
proteinContainer.update(proteinIds) | [
"def",
"_addProteins",
"(",
"self",
",",
"proteinIds",
",",
"containerNames",
")",
":",
"proteinIds",
"=",
"AUX",
".",
"toList",
"(",
"proteinIds",
")",
"for",
"containerName",
"in",
"containerNames",
":",
"proteinContainer",
"=",
"getattr",
"(",
"self",
",",
... | Add one or multiple proteinIds to the respective container.
:param proteinIds: a proteinId or a list of proteinIds, a proteinId
must be a string.
:param containerNames: list, entries must be one or multiple of
'leading', 'subset', 'subsumableProteins' or 'proteins'
:param addToProteins: bool, if True the proteinIds are added to the | [
"Add",
"one",
"or",
"multiple",
"proteinIds",
"to",
"the",
"respective",
"container",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/inference.py#L408-L420 | train | 55,600 |
diamondman/proteusisc | proteusisc/contracts.py | Requirement.satisfies | def satisfies(self, other):
"""Check if the capabilities of a primitive are enough to satisfy a requirement.
Should be called on a Requirement that is acting as a
capability of a primitive. This method returning true means
that the capability advertised here is enough to handle
representing the data described by the Requirement passed in
as 'other'.
Here is a chart showing what satisfies what.
other
A C 0 1
|Y N N N N
s A|Y Y Y Y Y
e C|Y - Y Y Y
l 0|Y * * Y N
f 1|Y * * N Y
' ' = No Care
A = arbitrary
C = Constant
0 = ZERO
1 = ONE
Y = YES
N = NO
- = Could satisfy with multiple instances
* = Not yet determined behavior. Used for bitbanging controllers.
"""
if other.isnocare:
return True
if self.isnocare:
return False
if self.arbitrary:
return True
if self.constant and not other.arbitrary:
return True
if self.value is other.value and not other.arbitrary\
and not other.constant:
return True
return False | python | def satisfies(self, other):
"""Check if the capabilities of a primitive are enough to satisfy a requirement.
Should be called on a Requirement that is acting as a
capability of a primitive. This method returning true means
that the capability advertised here is enough to handle
representing the data described by the Requirement passed in
as 'other'.
Here is a chart showing what satisfies what.
other
A C 0 1
|Y N N N N
s A|Y Y Y Y Y
e C|Y - Y Y Y
l 0|Y * * Y N
f 1|Y * * N Y
' ' = No Care
A = arbitrary
C = Constant
0 = ZERO
1 = ONE
Y = YES
N = NO
- = Could satisfy with multiple instances
* = Not yet determined behavior. Used for bitbanging controllers.
"""
if other.isnocare:
return True
if self.isnocare:
return False
if self.arbitrary:
return True
if self.constant and not other.arbitrary:
return True
if self.value is other.value and not other.arbitrary\
and not other.constant:
return True
return False | [
"def",
"satisfies",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"isnocare",
":",
"return",
"True",
"if",
"self",
".",
"isnocare",
":",
"return",
"False",
"if",
"self",
".",
"arbitrary",
":",
"return",
"True",
"if",
"self",
".",
"constant",... | Check if the capabilities of a primitive are enough to satisfy a requirement.
Should be called on a Requirement that is acting as a
capability of a primitive. This method returning true means
that the capability advertised here is enough to handle
representing the data described by the Requirement passed in
as 'other'.
Here is a chart showing what satisfies what.
other
A C 0 1
|Y N N N N
s A|Y Y Y Y Y
e C|Y - Y Y Y
l 0|Y * * Y N
f 1|Y * * N Y
' ' = No Care
A = arbitrary
C = Constant
0 = ZERO
1 = ONE
Y = YES
N = NO
- = Could satisfy with multiple instances
* = Not yet determined behavior. Used for bitbanging controllers. | [
"Check",
"if",
"the",
"capabilities",
"of",
"a",
"primitive",
"are",
"enough",
"to",
"satisfy",
"a",
"requirement",
"."
] | 7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c | https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/contracts.py#L122-L164 | train | 55,601 |
nicferrier/md | src/mdlib/client.py | MdClient._list | def _list(self, foldername="INBOX", reverse=False, since=None):
"""Do structured list output.
Sorts the list by date, possibly reversed, filtered from 'since'.
The returned list is: foldername, message key, message object
"""
folder = self.folder \
if foldername == "INBOX" \
else self._getfolder(foldername)
def sortcmp(d):
try:
return d[1].date
except:
return -1
lst = folder.items() if not since else folder.items_since(since)
sorted_lst = sorted(lst, key=sortcmp, reverse=1 if reverse else 0)
itemlist = [(folder, key, msg) for key,msg in sorted_lst]
return itemlist | python | def _list(self, foldername="INBOX", reverse=False, since=None):
"""Do structured list output.
Sorts the list by date, possibly reversed, filtered from 'since'.
The returned list is: foldername, message key, message object
"""
folder = self.folder \
if foldername == "INBOX" \
else self._getfolder(foldername)
def sortcmp(d):
try:
return d[1].date
except:
return -1
lst = folder.items() if not since else folder.items_since(since)
sorted_lst = sorted(lst, key=sortcmp, reverse=1 if reverse else 0)
itemlist = [(folder, key, msg) for key,msg in sorted_lst]
return itemlist | [
"def",
"_list",
"(",
"self",
",",
"foldername",
"=",
"\"INBOX\"",
",",
"reverse",
"=",
"False",
",",
"since",
"=",
"None",
")",
":",
"folder",
"=",
"self",
".",
"folder",
"if",
"foldername",
"==",
"\"INBOX\"",
"else",
"self",
".",
"_getfolder",
"(",
"f... | Do structured list output.
Sorts the list by date, possibly reversed, filtered from 'since'.
The returned list is: foldername, message key, message object | [
"Do",
"structured",
"list",
"output",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L80-L100 | train | 55,602 |
nicferrier/md | src/mdlib/client.py | MdClient.ls | def ls(self, foldername="INBOX", reverse=False, since=None, grep=None, field=None, stream=sys.stdout):
"""Do standard text list of the folder to the stream.
'foldername' is the folder to list.. INBOX by default.
'since' allows the listing to be date filtered since that
date. It should be a float, a time since epoch.
'grep' allows text matching on the whole record
'field' allows only 1 field to be output
"""
if foldername == "":
foldername = "INBOX"
msg_list = self._list(foldername, reverse, since)
for folder, mk, m in msg_list:
try:
# I am very unsure about this defaulting of foldername
output_items = (
"%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
m.date,
m.get_from()[0:50] if m.get_from() else "",
m.get_flags(),
re.sub("\n", "", m.get_subject() or "")
)
output_string = "% -20s % 20s % 50s [%s] %s" % output_items
if not grep or (grep and grep in output_string):
if field:
print(output_items[int(field)], file=stream)
else:
print(output_string, file=stream)
except IOError as e:
if e.errno == errno.EPIPE:
# Broken pipe we can ignore
return
self.logger.exception("whoops!")
except Exception as e:
self.logger.exception("whoops!") | python | def ls(self, foldername="INBOX", reverse=False, since=None, grep=None, field=None, stream=sys.stdout):
"""Do standard text list of the folder to the stream.
'foldername' is the folder to list.. INBOX by default.
'since' allows the listing to be date filtered since that
date. It should be a float, a time since epoch.
'grep' allows text matching on the whole record
'field' allows only 1 field to be output
"""
if foldername == "":
foldername = "INBOX"
msg_list = self._list(foldername, reverse, since)
for folder, mk, m in msg_list:
try:
# I am very unsure about this defaulting of foldername
output_items = (
"%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
m.date,
m.get_from()[0:50] if m.get_from() else "",
m.get_flags(),
re.sub("\n", "", m.get_subject() or "")
)
output_string = "% -20s % 20s % 50s [%s] %s" % output_items
if not grep or (grep and grep in output_string):
if field:
print(output_items[int(field)], file=stream)
else:
print(output_string, file=stream)
except IOError as e:
if e.errno == errno.EPIPE:
# Broken pipe we can ignore
return
self.logger.exception("whoops!")
except Exception as e:
self.logger.exception("whoops!") | [
"def",
"ls",
"(",
"self",
",",
"foldername",
"=",
"\"INBOX\"",
",",
"reverse",
"=",
"False",
",",
"since",
"=",
"None",
",",
"grep",
"=",
"None",
",",
"field",
"=",
"None",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"foldername",
"==... | Do standard text list of the folder to the stream.
'foldername' is the folder to list.. INBOX by default.
'since' allows the listing to be date filtered since that
date. It should be a float, a time since epoch.
'grep' allows text matching on the whole record
'field' allows only 1 field to be output | [
"Do",
"standard",
"text",
"list",
"of",
"the",
"folder",
"to",
"the",
"stream",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L102-L141 | train | 55,603 |
nicferrier/md | src/mdlib/client.py | MdClient.lisp | def lisp(self, foldername="INBOX", reverse=False, since=None, stream=sys.stdout):
"""Do JSON list of the folder to the stream.
'since' allows the listing to be date filtered since that
date. It should be a float, a time since epoch.
"""
def fromval(hdr):
if hdr:
return parseaddr(hdr)
for folder, mk, m in self._list(foldername, reverse, since):
try:
print(json.dumps({
'folder': folder.folder or foldername or "INBOX",
'key': "%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
'date': str(m.date),
"flags": m.get_flags(),
'from': fromval(m.get_from()),
'subject': re.sub("\n|\'|\"", _escape, m.get_subject() or "")
}), file=stream)
except IOError as e:
if e.errno == errno.EPIPE:
# Broken pipe we can ignore
return
self.logger.exception("whoops!")
except Exception as e:
self.logger.exception("whoops!") | python | def lisp(self, foldername="INBOX", reverse=False, since=None, stream=sys.stdout):
"""Do JSON list of the folder to the stream.
'since' allows the listing to be date filtered since that
date. It should be a float, a time since epoch.
"""
def fromval(hdr):
if hdr:
return parseaddr(hdr)
for folder, mk, m in self._list(foldername, reverse, since):
try:
print(json.dumps({
'folder': folder.folder or foldername or "INBOX",
'key': "%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
'date': str(m.date),
"flags": m.get_flags(),
'from': fromval(m.get_from()),
'subject': re.sub("\n|\'|\"", _escape, m.get_subject() or "")
}), file=stream)
except IOError as e:
if e.errno == errno.EPIPE:
# Broken pipe we can ignore
return
self.logger.exception("whoops!")
except Exception as e:
self.logger.exception("whoops!") | [
"def",
"lisp",
"(",
"self",
",",
"foldername",
"=",
"\"INBOX\"",
",",
"reverse",
"=",
"False",
",",
"since",
"=",
"None",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"def",
"fromval",
"(",
"hdr",
")",
":",
"if",
"hdr",
":",
"return",
"parse... | Do JSON list of the folder to the stream.
'since' allows the listing to be date filtered since that
date. It should be a float, a time since epoch. | [
"Do",
"JSON",
"list",
"of",
"the",
"folder",
"to",
"the",
"stream",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L143-L169 | train | 55,604 |
nicferrier/md | src/mdlib/client.py | MdClient.lsfolders | def lsfolders(self, stream=sys.stdout):
"""List the subfolders"""
for f in self.folder.folders():
print(f.folder.strip("."), file=stream) | python | def lsfolders(self, stream=sys.stdout):
"""List the subfolders"""
for f in self.folder.folders():
print(f.folder.strip("."), file=stream) | [
"def",
"lsfolders",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"f",
"in",
"self",
".",
"folder",
".",
"folders",
"(",
")",
":",
"print",
"(",
"f",
".",
"folder",
".",
"strip",
"(",
"\".\"",
")",
",",
"file",
"=",
"s... | List the subfolders | [
"List",
"the",
"subfolders"
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L171-L174 | train | 55,605 |
nicferrier/md | src/mdlib/client.py | MdClient._get | def _get(self, msgid):
"""Yields the message header against each part from the message."""
foldername, msgkey = msgid.split(SEPERATOR)
folder = self.folder if foldername == "INBOX" else self._getfolder(foldername)
# Now look up the message
msg = folder[msgkey]
msg.is_seen = True
hdr = list(msg.items())
for p in msg.walk():
yield hdr,p
return | python | def _get(self, msgid):
"""Yields the message header against each part from the message."""
foldername, msgkey = msgid.split(SEPERATOR)
folder = self.folder if foldername == "INBOX" else self._getfolder(foldername)
# Now look up the message
msg = folder[msgkey]
msg.is_seen = True
hdr = list(msg.items())
for p in msg.walk():
yield hdr,p
return | [
"def",
"_get",
"(",
"self",
",",
"msgid",
")",
":",
"foldername",
",",
"msgkey",
"=",
"msgid",
".",
"split",
"(",
"SEPERATOR",
")",
"folder",
"=",
"self",
".",
"folder",
"if",
"foldername",
"==",
"\"INBOX\"",
"else",
"self",
".",
"_getfolder",
"(",
"fo... | Yields the message header against each part from the message. | [
"Yields",
"the",
"message",
"header",
"against",
"each",
"part",
"from",
"the",
"message",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L187-L197 | train | 55,606 |
nicferrier/md | src/mdlib/client.py | MdClient.gettext | def gettext(self, msgid, stream=sys.stdout, splitter="--text follows this line--\n"):
"""Get the first text part we can find and print it as a message.
This is a simple cowpath, most of the time you want the first plain part.
'msgid' is the message to be used
'stream' is printed to with the header, splitter, first-textpart
'splitter' is text used to split the header from the body, Emacs uses this
"""
for hdr,part in self._get(msgid):
if part.get_content_type() == "text/plain":
for name,val in hdr:
# Use the subtype, since we're printing just that - tidy it up first
if name.lower() == "content-type":
val = part["content-type"]
val = " ".join([l.strip() for l in val.split("\n")])
print("%s: %s" % (name,val), file=stream)
print(splitter, file=stream)
payload = part.get_payload(decode=True)
# There seems to be a problem with the parser not doing charsets for parts
chartype = part.get_charset() \
or _get_charset(part.get("Content-Type", "")) \
or "us-ascii"
print(payload.decode(chartype), file=stream)
break | python | def gettext(self, msgid, stream=sys.stdout, splitter="--text follows this line--\n"):
"""Get the first text part we can find and print it as a message.
This is a simple cowpath, most of the time you want the first plain part.
'msgid' is the message to be used
'stream' is printed to with the header, splitter, first-textpart
'splitter' is text used to split the header from the body, Emacs uses this
"""
for hdr,part in self._get(msgid):
if part.get_content_type() == "text/plain":
for name,val in hdr:
# Use the subtype, since we're printing just that - tidy it up first
if name.lower() == "content-type":
val = part["content-type"]
val = " ".join([l.strip() for l in val.split("\n")])
print("%s: %s" % (name,val), file=stream)
print(splitter, file=stream)
payload = part.get_payload(decode=True)
# There seems to be a problem with the parser not doing charsets for parts
chartype = part.get_charset() \
or _get_charset(part.get("Content-Type", "")) \
or "us-ascii"
print(payload.decode(chartype), file=stream)
break | [
"def",
"gettext",
"(",
"self",
",",
"msgid",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"splitter",
"=",
"\"--text follows this line--\\n\"",
")",
":",
"for",
"hdr",
",",
"part",
"in",
"self",
".",
"_get",
"(",
"msgid",
")",
":",
"if",
"part",
".",... | Get the first text part we can find and print it as a message.
This is a simple cowpath, most of the time you want the first plain part.
'msgid' is the message to be used
'stream' is printed to with the header, splitter, first-textpart
'splitter' is text used to split the header from the body, Emacs uses this | [
"Get",
"the",
"first",
"text",
"part",
"we",
"can",
"find",
"and",
"print",
"it",
"as",
"a",
"message",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L199-L223 | train | 55,607 |
nicferrier/md | src/mdlib/client.py | MdClient.getrawpart | def getrawpart(self, msgid, stream=sys.stdout):
"""Get the first part from the message and print it raw.
"""
for hdr, part in self._get(msgid):
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream)
break | python | def getrawpart(self, msgid, stream=sys.stdout):
"""Get the first part from the message and print it raw.
"""
for hdr, part in self._get(msgid):
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream)
break | [
"def",
"getrawpart",
"(",
"self",
",",
"msgid",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"hdr",
",",
"part",
"in",
"self",
".",
"_get",
"(",
"msgid",
")",
":",
"pl",
"=",
"part",
".",
"get_payload",
"(",
"decode",
"=",
"True",
"... | Get the first part from the message and print it raw. | [
"Get",
"the",
"first",
"part",
"from",
"the",
"message",
"and",
"print",
"it",
"raw",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L225-L232 | train | 55,608 |
nicferrier/md | src/mdlib/client.py | MdClient.getrawpartid | def getrawpartid(self, msgid, partid, stream=sys.stdout):
"""Get a specific part from the message and print it raw.
"""
parts = [part for hdr,part in self._get(msgid)]
part = parts[int(partid)]
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream) | python | def getrawpartid(self, msgid, partid, stream=sys.stdout):
"""Get a specific part from the message and print it raw.
"""
parts = [part for hdr,part in self._get(msgid)]
part = parts[int(partid)]
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream) | [
"def",
"getrawpartid",
"(",
"self",
",",
"msgid",
",",
"partid",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"parts",
"=",
"[",
"part",
"for",
"hdr",
",",
"part",
"in",
"self",
".",
"_get",
"(",
"msgid",
")",
"]",
"part",
"=",
"parts",
"[... | Get a specific part from the message and print it raw. | [
"Get",
"a",
"specific",
"part",
"from",
"the",
"message",
"and",
"print",
"it",
"raw",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L234-L241 | train | 55,609 |
nicferrier/md | src/mdlib/client.py | MdClient.getraw | def getraw(self, msgid, stream=sys.stdout):
"""Get the whole message and print it.
"""
foldername, msgkey = msgid.split(SEPERATOR)
folder = self.folder if foldername == "INBOX" else self._getfolder(foldername)
msg = folder[msgkey]
print(msg.content) | python | def getraw(self, msgid, stream=sys.stdout):
"""Get the whole message and print it.
"""
foldername, msgkey = msgid.split(SEPERATOR)
folder = self.folder if foldername == "INBOX" else self._getfolder(foldername)
msg = folder[msgkey]
print(msg.content) | [
"def",
"getraw",
"(",
"self",
",",
"msgid",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"foldername",
",",
"msgkey",
"=",
"msgid",
".",
"split",
"(",
"SEPERATOR",
")",
"folder",
"=",
"self",
".",
"folder",
"if",
"foldername",
"==",
"\"INBOX\"",... | Get the whole message and print it. | [
"Get",
"the",
"whole",
"message",
"and",
"print",
"it",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L244-L250 | train | 55,610 |
nicferrier/md | src/mdlib/client.py | MdClient.getstruct | def getstruct(self, msgid, as_json=False, stream=sys.stdout):
"""Get and print the whole message.
as_json indicates whether to print the part list as JSON or not.
"""
parts = [part.get_content_type() for hdr, part in self._get(msgid)]
if as_json:
print(json.dumps(parts), file=stream)
else:
for c in parts:
print(c, file=stream) | python | def getstruct(self, msgid, as_json=False, stream=sys.stdout):
"""Get and print the whole message.
as_json indicates whether to print the part list as JSON or not.
"""
parts = [part.get_content_type() for hdr, part in self._get(msgid)]
if as_json:
print(json.dumps(parts), file=stream)
else:
for c in parts:
print(c, file=stream) | [
"def",
"getstruct",
"(",
"self",
",",
"msgid",
",",
"as_json",
"=",
"False",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"parts",
"=",
"[",
"part",
".",
"get_content_type",
"(",
")",
"for",
"hdr",
",",
"part",
"in",
"self",
".",
"_get",
"("... | Get and print the whole message.
as_json indicates whether to print the part list as JSON or not. | [
"Get",
"and",
"print",
"the",
"whole",
"message",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/client.py#L252-L262 | train | 55,611 |
GeorgeArgyros/symautomata | symautomata/cfgpda.py | CfgPDA._extract_alphabet | def _extract_alphabet(self, grammar):
"""
Extract an alphabet from the given grammar.
"""
alphabet = set([])
for terminal in grammar.Terminals:
alphabet |= set([x for x in terminal])
self.alphabet = list(alphabet) | python | def _extract_alphabet(self, grammar):
"""
Extract an alphabet from the given grammar.
"""
alphabet = set([])
for terminal in grammar.Terminals:
alphabet |= set([x for x in terminal])
self.alphabet = list(alphabet) | [
"def",
"_extract_alphabet",
"(",
"self",
",",
"grammar",
")",
":",
"alphabet",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"terminal",
"in",
"grammar",
".",
"Terminals",
":",
"alphabet",
"|=",
"set",
"(",
"[",
"x",
"for",
"x",
"in",
"terminal",
"]",
")",
... | Extract an alphabet from the given grammar. | [
"Extract",
"an",
"alphabet",
"from",
"the",
"given",
"grammar",
"."
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/cfgpda.py#L18-L25 | train | 55,612 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.action | def action(self, column=None, value=None, **kwargs):
"""
The underlying GICS table provides codes and descriptions
identifying the current status or disposition of a grant project.
>>> GICS().action('action_code', 'A')
"""
return self._resolve_call('GIC_ACTION', column, value, **kwargs) | python | def action(self, column=None, value=None, **kwargs):
"""
The underlying GICS table provides codes and descriptions
identifying the current status or disposition of a grant project.
>>> GICS().action('action_code', 'A')
"""
return self._resolve_call('GIC_ACTION', column, value, **kwargs) | [
"def",
"action",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_ACTION'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | The underlying GICS table provides codes and descriptions
identifying the current status or disposition of a grant project.
>>> GICS().action('action_code', 'A') | [
"The",
"underlying",
"GICS",
"table",
"provides",
"codes",
"and",
"descriptions",
"identifying",
"the",
"current",
"status",
"or",
"disposition",
"of",
"a",
"grant",
"project",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L23-L30 | train | 55,613 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.applicant | def applicant(self, column=None, value=None, **kwargs):
"""
Find the applicant information for a grant.
>>> GICS().applicant('zip_code', 94105)
"""
return self._resolve_call('GIC_APPLICANT', column, value, **kwargs) | python | def applicant(self, column=None, value=None, **kwargs):
"""
Find the applicant information for a grant.
>>> GICS().applicant('zip_code', 94105)
"""
return self._resolve_call('GIC_APPLICANT', column, value, **kwargs) | [
"def",
"applicant",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_APPLICANT'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Find the applicant information for a grant.
>>> GICS().applicant('zip_code', 94105) | [
"Find",
"the",
"applicant",
"information",
"for",
"a",
"grant",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L32-L38 | train | 55,614 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.authority | def authority(self, column=None, value=None, **kwargs):
"""Provides codes and associated authorizing statutes."""
return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs) | python | def authority(self, column=None, value=None, **kwargs):
"""Provides codes and associated authorizing statutes."""
return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs) | [
"def",
"authority",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_AUTHORITY'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Provides codes and associated authorizing statutes. | [
"Provides",
"codes",
"and",
"associated",
"authorizing",
"statutes",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L47-L49 | train | 55,615 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.construction | def construction(self, column=None, value=None, **kwargs):
"""
Identifies monetary, descriptive, and milestone information for
Wastewater Treatment construction grants.
>>> GICS().construction('complete_percent', 91)
"""
return self._resolve_call('GIC_CONSTRUCTION', column, value, **kwargs) | python | def construction(self, column=None, value=None, **kwargs):
"""
Identifies monetary, descriptive, and milestone information for
Wastewater Treatment construction grants.
>>> GICS().construction('complete_percent', 91)
"""
return self._resolve_call('GIC_CONSTRUCTION', column, value, **kwargs) | [
"def",
"construction",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_CONSTRUCTION'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Identifies monetary, descriptive, and milestone information for
Wastewater Treatment construction grants.
>>> GICS().construction('complete_percent', 91) | [
"Identifies",
"monetary",
"descriptive",
"and",
"milestone",
"information",
"for",
"Wastewater",
"Treatment",
"construction",
"grants",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L51-L58 | train | 55,616 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.eligible_cost | def eligible_cost(self, column=None, value=None, **kwargs):
"""
The assistance dollar amounts by eligible cost category.
>>> GICS().eligible_cost('amount', 100000)
"""
return self._resolve_call('GIC_ELIGIBLE_COST', column, value, **kwargs) | python | def eligible_cost(self, column=None, value=None, **kwargs):
"""
The assistance dollar amounts by eligible cost category.
>>> GICS().eligible_cost('amount', 100000)
"""
return self._resolve_call('GIC_ELIGIBLE_COST', column, value, **kwargs) | [
"def",
"eligible_cost",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_ELIGIBLE_COST'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"... | The assistance dollar amounts by eligible cost category.
>>> GICS().eligible_cost('amount', 100000) | [
"The",
"assistance",
"dollar",
"amounts",
"by",
"eligible",
"cost",
"category",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L60-L66 | train | 55,617 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.grant | def grant(self, column=None, value=None, **kwargs):
"""
Provides various award, project, and grant personnel information.
>>> GICS().grant('project_city_name', 'San Francisco')
"""
return self._resolve_call('GIC_GRANT', column, value, **kwargs) | python | def grant(self, column=None, value=None, **kwargs):
"""
Provides various award, project, and grant personnel information.
>>> GICS().grant('project_city_name', 'San Francisco')
"""
return self._resolve_call('GIC_GRANT', column, value, **kwargs) | [
"def",
"grant",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_GRANT'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Provides various award, project, and grant personnel information.
>>> GICS().grant('project_city_name', 'San Francisco') | [
"Provides",
"various",
"award",
"project",
"and",
"grant",
"personnel",
"information",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L68-L74 | train | 55,618 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.grant_assistance | def grant_assistance(self, column=None, value=None, **kwargs):
"""Many-to-many table connecting grants and assistance."""
return self._resolve_call('GIC_GRANT_ASST_PGM', column, value, **kwargs) | python | def grant_assistance(self, column=None, value=None, **kwargs):
"""Many-to-many table connecting grants and assistance."""
return self._resolve_call('GIC_GRANT_ASST_PGM', column, value, **kwargs) | [
"def",
"grant_assistance",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_GRANT_ASST_PGM'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
... | Many-to-many table connecting grants and assistance. | [
"Many",
"-",
"to",
"-",
"many",
"table",
"connecting",
"grants",
"and",
"assistance",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L76-L78 | train | 55,619 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.grant_authority | def grant_authority(self, column=None, value=None, **kwargs):
"""Many-to-many table connecting grants and authority."""
return self._resolve_call('GIC_GRANT_AUTH', column, value, **kwargs) | python | def grant_authority(self, column=None, value=None, **kwargs):
"""Many-to-many table connecting grants and authority."""
return self._resolve_call('GIC_GRANT_AUTH', column, value, **kwargs) | [
"def",
"grant_authority",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_GRANT_AUTH'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
... | Many-to-many table connecting grants and authority. | [
"Many",
"-",
"to",
"-",
"many",
"table",
"connecting",
"grants",
"and",
"authority",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L80-L82 | train | 55,620 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.lab_office | def lab_office(self, column=None, value=None, **kwargs):
"""Abbreviations, names, and locations of labratories and offices."""
return self._resolve_call('GIC_LAB_OFFICE', column, value, **kwargs) | python | def lab_office(self, column=None, value=None, **kwargs):
"""Abbreviations, names, and locations of labratories and offices."""
return self._resolve_call('GIC_LAB_OFFICE', column, value, **kwargs) | [
"def",
"lab_office",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_LAB_OFFICE'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Abbreviations, names, and locations of labratories and offices. | [
"Abbreviations",
"names",
"and",
"locations",
"of",
"labratories",
"and",
"offices",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L84-L86 | train | 55,621 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.milestone | def milestone(self, column=None, value=None, **kwargs):
"""
Status codes and related dates of certain grants,
>>> GICS().milestone('milestone_date', '16-MAR-01')
"""
return self._resolve_call('GIC_MILESTONE', column, value, **kwargs) | python | def milestone(self, column=None, value=None, **kwargs):
"""
Status codes and related dates of certain grants,
>>> GICS().milestone('milestone_date', '16-MAR-01')
"""
return self._resolve_call('GIC_MILESTONE', column, value, **kwargs) | [
"def",
"milestone",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_MILESTONE'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Status codes and related dates of certain grants,
>>> GICS().milestone('milestone_date', '16-MAR-01') | [
"Status",
"codes",
"and",
"related",
"dates",
"of",
"certain",
"grants"
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L88-L94 | train | 55,622 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.record_type | def record_type(self, column=None, value=None, **kwargs):
"""
Codes and descriptions indicating whether an award is for a new
project or for the continuation of a currently funded one.
>>> GICS().record_type('record_type_code', 'A')
"""
return self._resolve_call('GIC_RECORD_TYPE', column, value, **kwargs) | python | def record_type(self, column=None, value=None, **kwargs):
"""
Codes and descriptions indicating whether an award is for a new
project or for the continuation of a currently funded one.
>>> GICS().record_type('record_type_code', 'A')
"""
return self._resolve_call('GIC_RECORD_TYPE', column, value, **kwargs) | [
"def",
"record_type",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_RECORD_TYPE'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Codes and descriptions indicating whether an award is for a new
project or for the continuation of a currently funded one.
>>> GICS().record_type('record_type_code', 'A') | [
"Codes",
"and",
"descriptions",
"indicating",
"whether",
"an",
"award",
"is",
"for",
"a",
"new",
"project",
"or",
"for",
"the",
"continuation",
"of",
"a",
"currently",
"funded",
"one",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L96-L103 | train | 55,623 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.srf_cap | def srf_cap(self, column=None, value=None, **kwargs):
"""
Fiscal dollar amounts for State Revolving Fund Capitalization
Grants.
>>> GICS().srf_cap('grant_number', '340001900')
"""
return self._resolve_call('GIC_SRF_CAP', column, value, **kwargs) | python | def srf_cap(self, column=None, value=None, **kwargs):
"""
Fiscal dollar amounts for State Revolving Fund Capitalization
Grants.
>>> GICS().srf_cap('grant_number', '340001900')
"""
return self._resolve_call('GIC_SRF_CAP', column, value, **kwargs) | [
"def",
"srf_cap",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_SRF_CAP'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Fiscal dollar amounts for State Revolving Fund Capitalization
Grants.
>>> GICS().srf_cap('grant_number', '340001900') | [
"Fiscal",
"dollar",
"amounts",
"for",
"State",
"Revolving",
"Fund",
"Capitalization",
"Grants",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L105-L112 | train | 55,624 |
codeforamerica/epa_python | epa/gics/gics.py | GICS.status | def status(self, column=None, value=None, **kwargs):
"""
Provides codes and descriptions of project milestones.
>>> GICS().status('status_code', 'AF')
"""
return self._resolve_call('GIC_STATUS', column, value, **kwargs) | python | def status(self, column=None, value=None, **kwargs):
"""
Provides codes and descriptions of project milestones.
>>> GICS().status('status_code', 'AF')
"""
return self._resolve_call('GIC_STATUS', column, value, **kwargs) | [
"def",
"status",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_STATUS'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Provides codes and descriptions of project milestones.
>>> GICS().status('status_code', 'AF') | [
"Provides",
"codes",
"and",
"descriptions",
"of",
"project",
"milestones",
"."
] | 62a53da62936bea8daa487a01a52b973e9062b2c | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/gics/gics.py#L114-L120 | train | 55,625 |
hollenstein/maspy | maspy/xml.py | recRemoveTreeFormating | def recRemoveTreeFormating(element):
"""Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all child elements.
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recRemoveTreeFormating(child)
if element.text is not None:
if len(element.text.strip()) == 0:
element.text = None
else:
element.text = element.text.strip()
if element.tail is not None:
if len(element.tail.strip()) == 0:
element.tail = None
else:
element.tail = element.tail.strip() | python | def recRemoveTreeFormating(element):
"""Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all child elements.
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recRemoveTreeFormating(child)
if element.text is not None:
if len(element.text.strip()) == 0:
element.text = None
else:
element.text = element.text.strip()
if element.tail is not None:
if len(element.tail.strip()) == 0:
element.tail = None
else:
element.tail = element.tail.strip() | [
"def",
"recRemoveTreeFormating",
"(",
"element",
")",
":",
"children",
"=",
"element",
".",
"getchildren",
"(",
")",
"if",
"len",
"(",
"children",
")",
">",
"0",
":",
"for",
"child",
"in",
"children",
":",
"recRemoveTreeFormating",
"(",
"child",
")",
"if",... | Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all child elements. | [
"Removes",
"whitespace",
"characters",
"which",
"are",
"leftovers",
"from",
"previous",
"xml",
"formatting",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/xml.py#L104-L126 | train | 55,626 |
hollenstein/maspy | maspy/xml.py | recCopyElement | def recCopyElement(oldelement):
"""Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements
"""
newelement = ETREE.Element(oldelement.tag, oldelement.attrib)
if len(oldelement.getchildren()) > 0:
for childelement in oldelement.getchildren():
newelement.append(recCopyElement(childelement))
return newelement | python | def recCopyElement(oldelement):
"""Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements
"""
newelement = ETREE.Element(oldelement.tag, oldelement.attrib)
if len(oldelement.getchildren()) > 0:
for childelement in oldelement.getchildren():
newelement.append(recCopyElement(childelement))
return newelement | [
"def",
"recCopyElement",
"(",
"oldelement",
")",
":",
"newelement",
"=",
"ETREE",
".",
"Element",
"(",
"oldelement",
".",
"tag",
",",
"oldelement",
".",
"attrib",
")",
"if",
"len",
"(",
"oldelement",
".",
"getchildren",
"(",
")",
")",
">",
"0",
":",
"f... | Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements | [
"Generates",
"a",
"copy",
"of",
"an",
"xml",
"element",
"and",
"recursively",
"of",
"all",
"child",
"elements",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/xml.py#L129-L144 | train | 55,627 |
hollenstein/maspy | maspy/xml.py | getParam | def getParam(xmlelement):
"""Converts an mzML xml element to a param tuple.
:param xmlelement: #TODO docstring
:returns: a param tuple or False if the xmlelement is not a parameter
('userParam', 'cvParam' or 'referenceableParamGroupRef')
"""
elementTag = clearTag(xmlelement.tag)
if elementTag in ['userParam', 'cvParam', 'referenceableParamGroupRef']:
if elementTag == 'cvParam':
param = cvParamFromDict(xmlelement.attrib)
elif elementTag == 'userParam':
param = userParamFromDict(xmlelement.attrib)
else:
param = refParamGroupFromDict(xmlelement.attrib)
else:
param = False
return param | python | def getParam(xmlelement):
"""Converts an mzML xml element to a param tuple.
:param xmlelement: #TODO docstring
:returns: a param tuple or False if the xmlelement is not a parameter
('userParam', 'cvParam' or 'referenceableParamGroupRef')
"""
elementTag = clearTag(xmlelement.tag)
if elementTag in ['userParam', 'cvParam', 'referenceableParamGroupRef']:
if elementTag == 'cvParam':
param = cvParamFromDict(xmlelement.attrib)
elif elementTag == 'userParam':
param = userParamFromDict(xmlelement.attrib)
else:
param = refParamGroupFromDict(xmlelement.attrib)
else:
param = False
return param | [
"def",
"getParam",
"(",
"xmlelement",
")",
":",
"elementTag",
"=",
"clearTag",
"(",
"xmlelement",
".",
"tag",
")",
"if",
"elementTag",
"in",
"[",
"'userParam'",
",",
"'cvParam'",
",",
"'referenceableParamGroupRef'",
"]",
":",
"if",
"elementTag",
"==",
"'cvPara... | Converts an mzML xml element to a param tuple.
:param xmlelement: #TODO docstring
:returns: a param tuple or False if the xmlelement is not a parameter
('userParam', 'cvParam' or 'referenceableParamGroupRef') | [
"Converts",
"an",
"mzML",
"xml",
"element",
"to",
"a",
"param",
"tuple",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/xml.py#L204-L222 | train | 55,628 |
hollenstein/maspy | maspy/xml.py | xmlAddParams | def xmlAddParams(parentelement, params):
"""Generates new mzML parameter xml elements and adds them to the
'parentelement' as xml children elements.
:param parentelement: :class:`xml.etree.Element`, an mzML element
:param params: a list of mzML parameter tuples ('cvParam', 'userParam' or
'referencableParamGroup')
"""
if not params:
return None
for param in params:
if len(param) == 3:
cvAttrib = {'cvRef': param[0].split(':')[0], 'accession': param[0],
'name':oboTranslator.getNameWithId(param[0])
}
if param[1]:
cvAttrib.update({'value': param[1]})
else:
cvAttrib.update({'value': ''})
if param[2]:
unitName = oboTranslator.getNameWithId(param[2])
cvAttrib.update({'unitAccession': param[2],
'unitCvRef': param[2].split(':')[0],
'unitName': unitName
})
paramElement = ETREE.Element('cvParam', **cvAttrib)
elif len(param) == 4:
userAttrib = {'name': param[0]}
if param[1]:
userAttrib.update({'value': param[1]})
else:
userAttrib.update({'value': ''})
if param[2]:
userAttrib.update({'unitAccession': param[2],
'unitCvRef': param[2].split(':')[0]
})
if param[3]:
userAttrib.update({'type': param[3]})
paramElement = ETREE.Element('userParam', **userAttrib)
elif param[0] == 'ref':
refAttrib = {'ref': param[1]}
paramElement = ETREE.Element('referenceableParamGroupRef',
**refAttrib
)
parentelement.append(paramElement) | python | def xmlAddParams(parentelement, params):
"""Generates new mzML parameter xml elements and adds them to the
'parentelement' as xml children elements.
:param parentelement: :class:`xml.etree.Element`, an mzML element
:param params: a list of mzML parameter tuples ('cvParam', 'userParam' or
'referencableParamGroup')
"""
if not params:
return None
for param in params:
if len(param) == 3:
cvAttrib = {'cvRef': param[0].split(':')[0], 'accession': param[0],
'name':oboTranslator.getNameWithId(param[0])
}
if param[1]:
cvAttrib.update({'value': param[1]})
else:
cvAttrib.update({'value': ''})
if param[2]:
unitName = oboTranslator.getNameWithId(param[2])
cvAttrib.update({'unitAccession': param[2],
'unitCvRef': param[2].split(':')[0],
'unitName': unitName
})
paramElement = ETREE.Element('cvParam', **cvAttrib)
elif len(param) == 4:
userAttrib = {'name': param[0]}
if param[1]:
userAttrib.update({'value': param[1]})
else:
userAttrib.update({'value': ''})
if param[2]:
userAttrib.update({'unitAccession': param[2],
'unitCvRef': param[2].split(':')[0]
})
if param[3]:
userAttrib.update({'type': param[3]})
paramElement = ETREE.Element('userParam', **userAttrib)
elif param[0] == 'ref':
refAttrib = {'ref': param[1]}
paramElement = ETREE.Element('referenceableParamGroupRef',
**refAttrib
)
parentelement.append(paramElement) | [
"def",
"xmlAddParams",
"(",
"parentelement",
",",
"params",
")",
":",
"if",
"not",
"params",
":",
"return",
"None",
"for",
"param",
"in",
"params",
":",
"if",
"len",
"(",
"param",
")",
"==",
"3",
":",
"cvAttrib",
"=",
"{",
"'cvRef'",
":",
"param",
"[... | Generates new mzML parameter xml elements and adds them to the
'parentelement' as xml children elements.
:param parentelement: :class:`xml.etree.Element`, an mzML element
:param params: a list of mzML parameter tuples ('cvParam', 'userParam' or
'referencableParamGroup') | [
"Generates",
"new",
"mzML",
"parameter",
"xml",
"elements",
"and",
"adds",
"them",
"to",
"the",
"parentelement",
"as",
"xml",
"children",
"elements",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/xml.py#L243-L287 | train | 55,629 |
hollenstein/maspy | maspy/xml.py | interpretBitEncoding | def interpretBitEncoding(bitEncoding):
"""Returns a floattype string and a numpy array type.
:param bitEncoding: Must be either '64' or '32'
:returns: (floattype, numpyType)
"""
if bitEncoding == '64':
floattype = 'd' # 64-bit
numpyType = numpy.float64
elif bitEncoding == '32':
floattype = 'f' # 32-bit
numpyType = numpy.float32
else:
errorText = ''.join(['bitEncoding \'', bitEncoding, '\' not defined. ',
'Must be \'64\' or \'32\''
])
raise TypeError(errorText)
return (floattype, numpyType) | python | def interpretBitEncoding(bitEncoding):
"""Returns a floattype string and a numpy array type.
:param bitEncoding: Must be either '64' or '32'
:returns: (floattype, numpyType)
"""
if bitEncoding == '64':
floattype = 'd' # 64-bit
numpyType = numpy.float64
elif bitEncoding == '32':
floattype = 'f' # 32-bit
numpyType = numpy.float32
else:
errorText = ''.join(['bitEncoding \'', bitEncoding, '\' not defined. ',
'Must be \'64\' or \'32\''
])
raise TypeError(errorText)
return (floattype, numpyType) | [
"def",
"interpretBitEncoding",
"(",
"bitEncoding",
")",
":",
"if",
"bitEncoding",
"==",
"'64'",
":",
"floattype",
"=",
"'d'",
"# 64-bit",
"numpyType",
"=",
"numpy",
".",
"float64",
"elif",
"bitEncoding",
"==",
"'32'",
":",
"floattype",
"=",
"'f'",
"# 32-bit",
... | Returns a floattype string and a numpy array type.
:param bitEncoding: Must be either '64' or '32'
:returns: (floattype, numpyType) | [
"Returns",
"a",
"floattype",
"string",
"and",
"a",
"numpy",
"array",
"type",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/xml.py#L293-L311 | train | 55,630 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/thermo/thermo.py | calc_partition_function | def calc_partition_function(mass, omega_array, temperature_array):
"""
Calculates the partition function of your system at each point in time.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the same length as the Hamiltonian
temperature_array : array
array which represents the temperature at every point in your time trace
and should therefore have the same length as the Hamiltonian
Returns:
-------
Partition function : array
The Partition Function at every point in time over a given trap-frequency and temperature change.
"""
Kappa_t= mass*omega_array**2
return _np.sqrt(4*_np.pi**2*_scipy.constants.Boltzmann**2*temperature_array**2/(mass*Kappa_t)) | python | def calc_partition_function(mass, omega_array, temperature_array):
"""
Calculates the partition function of your system at each point in time.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the same length as the Hamiltonian
temperature_array : array
array which represents the temperature at every point in your time trace
and should therefore have the same length as the Hamiltonian
Returns:
-------
Partition function : array
The Partition Function at every point in time over a given trap-frequency and temperature change.
"""
Kappa_t= mass*omega_array**2
return _np.sqrt(4*_np.pi**2*_scipy.constants.Boltzmann**2*temperature_array**2/(mass*Kappa_t)) | [
"def",
"calc_partition_function",
"(",
"mass",
",",
"omega_array",
",",
"temperature_array",
")",
":",
"Kappa_t",
"=",
"mass",
"*",
"omega_array",
"**",
"2",
"return",
"_np",
".",
"sqrt",
"(",
"4",
"*",
"_np",
".",
"pi",
"**",
"2",
"*",
"_scipy",
".",
... | Calculates the partition function of your system at each point in time.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the same length as the Hamiltonian
temperature_array : array
array which represents the temperature at every point in your time trace
and should therefore have the same length as the Hamiltonian
Returns:
-------
Partition function : array
The Partition Function at every point in time over a given trap-frequency and temperature change. | [
"Calculates",
"the",
"partition",
"function",
"of",
"your",
"system",
"at",
"each",
"point",
"in",
"time",
"."
] | 9d390acc834d70024d47b574aea14189a5a5714e | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/thermo/thermo.py#L185-L206 | train | 55,631 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/thermo/thermo.py | ThermoObject.calc_mean_and_variance_of_variances | def calc_mean_and_variance_of_variances(self, NumberOfOscillations):
"""
Calculates the mean and variance of a set of varainces.
This set is obtained by splitting the timetrace into chunks
of points with a length of NumberOfOscillations oscillations.
Parameters
----------
NumberOfOscillations : int
The number of oscillations each chunk of the timetrace
used to calculate the variance should contain.
Returns
-------
Mean : float
Variance : float
"""
SplittedArraySize = int(self.SampleFreq/self.FTrap.n) * NumberOfOscillations
VoltageArraySize = len(self.voltage)
SnippetsVariances = _np.var(self.voltage[:VoltageArraySize-_np.mod(VoltageArraySize,SplittedArraySize)].reshape(-1,SplittedArraySize),axis=1)
return _np.mean(SnippetsVariances), _np.var(SnippetsVariances) | python | def calc_mean_and_variance_of_variances(self, NumberOfOscillations):
"""
Calculates the mean and variance of a set of varainces.
This set is obtained by splitting the timetrace into chunks
of points with a length of NumberOfOscillations oscillations.
Parameters
----------
NumberOfOscillations : int
The number of oscillations each chunk of the timetrace
used to calculate the variance should contain.
Returns
-------
Mean : float
Variance : float
"""
SplittedArraySize = int(self.SampleFreq/self.FTrap.n) * NumberOfOscillations
VoltageArraySize = len(self.voltage)
SnippetsVariances = _np.var(self.voltage[:VoltageArraySize-_np.mod(VoltageArraySize,SplittedArraySize)].reshape(-1,SplittedArraySize),axis=1)
return _np.mean(SnippetsVariances), _np.var(SnippetsVariances) | [
"def",
"calc_mean_and_variance_of_variances",
"(",
"self",
",",
"NumberOfOscillations",
")",
":",
"SplittedArraySize",
"=",
"int",
"(",
"self",
".",
"SampleFreq",
"/",
"self",
".",
"FTrap",
".",
"n",
")",
"*",
"NumberOfOscillations",
"VoltageArraySize",
"=",
"len"... | Calculates the mean and variance of a set of varainces.
This set is obtained by splitting the timetrace into chunks
of points with a length of NumberOfOscillations oscillations.
Parameters
----------
NumberOfOscillations : int
The number of oscillations each chunk of the timetrace
used to calculate the variance should contain.
Returns
-------
Mean : float
Variance : float | [
"Calculates",
"the",
"mean",
"and",
"variance",
"of",
"a",
"set",
"of",
"varainces",
".",
"This",
"set",
"is",
"obtained",
"by",
"splitting",
"the",
"timetrace",
"into",
"chunks",
"of",
"points",
"with",
"a",
"length",
"of",
"NumberOfOscillations",
"oscillatio... | 9d390acc834d70024d47b574aea14189a5a5714e | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/thermo/thermo.py#L161-L182 | train | 55,632 |
pauleveritt/kaybee | kaybee/plugins/resources/handlers.py | register_template_directory | def register_template_directory(kb_app: kb,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docnames=List[str],
):
""" Add this resource's templates dir to template paths """
template_bridge = sphinx_app.builder.templates
actions = ResourceAction.get_callbacks(kb_app)
for action in actions:
f = os.path.dirname(inspect.getfile(action))
template_bridge.loaders.append(SphinxFileSystemLoader(f)) | python | def register_template_directory(kb_app: kb,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docnames=List[str],
):
""" Add this resource's templates dir to template paths """
template_bridge = sphinx_app.builder.templates
actions = ResourceAction.get_callbacks(kb_app)
for action in actions:
f = os.path.dirname(inspect.getfile(action))
template_bridge.loaders.append(SphinxFileSystemLoader(f)) | [
"def",
"register_template_directory",
"(",
"kb_app",
":",
"kb",
",",
"sphinx_app",
":",
"Sphinx",
",",
"sphinx_env",
":",
"BuildEnvironment",
",",
"docnames",
"=",
"List",
"[",
"str",
"]",
",",
")",
":",
"template_bridge",
"=",
"sphinx_app",
".",
"builder",
... | Add this resource's templates dir to template paths | [
"Add",
"this",
"resource",
"s",
"templates",
"dir",
"to",
"template",
"paths"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/handlers.py#L35-L48 | train | 55,633 |
pauleveritt/kaybee | kaybee/plugins/resources/handlers.py | add_directives | def add_directives(kb_app: kb,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docnames=List[str],
):
""" For each resource type, register a new Sphinx directive """
for k, v in list(kb_app.config.resources.items()):
sphinx_app.add_directive(k, ResourceDirective) | python | def add_directives(kb_app: kb,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docnames=List[str],
):
""" For each resource type, register a new Sphinx directive """
for k, v in list(kb_app.config.resources.items()):
sphinx_app.add_directive(k, ResourceDirective) | [
"def",
"add_directives",
"(",
"kb_app",
":",
"kb",
",",
"sphinx_app",
":",
"Sphinx",
",",
"sphinx_env",
":",
"BuildEnvironment",
",",
"docnames",
"=",
"List",
"[",
"str",
"]",
",",
")",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"kb_app",
".",
"co... | For each resource type, register a new Sphinx directive | [
"For",
"each",
"resource",
"type",
"register",
"a",
"new",
"Sphinx",
"directive"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/handlers.py#L52-L60 | train | 55,634 |
pauleveritt/kaybee | kaybee/plugins/resources/handlers.py | stamp_title | def stamp_title(kb_app: kb,
sphinx_app: Sphinx,
doctree: doctree):
""" Walk the tree and extra RST title into resource.title """
# First, find out which resource this is. Won't be easy.
resources = sphinx_app.env.resources
confdir = sphinx_app.confdir
source = PurePath(doctree.attributes['source'])
# Get the relative path inside the docs dir, without .rst, then
# get the resource
docname = str(source.relative_to(confdir)).split('.rst')[0]
resource = resources.get(docname)
if resource:
# Stamp the title on the resource
title = get_rst_title(doctree)
resource.title = title | python | def stamp_title(kb_app: kb,
sphinx_app: Sphinx,
doctree: doctree):
""" Walk the tree and extra RST title into resource.title """
# First, find out which resource this is. Won't be easy.
resources = sphinx_app.env.resources
confdir = sphinx_app.confdir
source = PurePath(doctree.attributes['source'])
# Get the relative path inside the docs dir, without .rst, then
# get the resource
docname = str(source.relative_to(confdir)).split('.rst')[0]
resource = resources.get(docname)
if resource:
# Stamp the title on the resource
title = get_rst_title(doctree)
resource.title = title | [
"def",
"stamp_title",
"(",
"kb_app",
":",
"kb",
",",
"sphinx_app",
":",
"Sphinx",
",",
"doctree",
":",
"doctree",
")",
":",
"# First, find out which resource this is. Won't be easy.",
"resources",
"=",
"sphinx_app",
".",
"env",
".",
"resources",
"confdir",
"=",
"s... | Walk the tree and extra RST title into resource.title | [
"Walk",
"the",
"tree",
"and",
"extra",
"RST",
"title",
"into",
"resource",
".",
"title"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/handlers.py#L84-L102 | train | 55,635 |
hbldh/flask-pybankid | flask_pybankid.py | PyBankID.handle_exception | def handle_exception(error):
"""Simple method for handling exceptions raised by `PyBankID`.
:param flask_pybankid.FlaskPyBankIDError error: The exception to handle.
:return: The exception represented as a dictionary.
:rtype: dict
"""
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response | python | def handle_exception(error):
"""Simple method for handling exceptions raised by `PyBankID`.
:param flask_pybankid.FlaskPyBankIDError error: The exception to handle.
:return: The exception represented as a dictionary.
:rtype: dict
"""
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response | [
"def",
"handle_exception",
"(",
"error",
")",
":",
"response",
"=",
"jsonify",
"(",
"error",
".",
"to_dict",
"(",
")",
")",
"response",
".",
"status_code",
"=",
"error",
".",
"status_code",
"return",
"response"
] | Simple method for handling exceptions raised by `PyBankID`.
:param flask_pybankid.FlaskPyBankIDError error: The exception to handle.
:return: The exception represented as a dictionary.
:rtype: dict | [
"Simple",
"method",
"for",
"handling",
"exceptions",
"raised",
"by",
"PyBankID",
"."
] | b9af666f587b027391b25d811788d934a12b57e6 | https://github.com/hbldh/flask-pybankid/blob/b9af666f587b027391b25d811788d934a12b57e6/flask_pybankid.py#L166-L176 | train | 55,636 |
hbldh/flask-pybankid | flask_pybankid.py | FlaskPyBankIDError.create_from_pybankid_exception | def create_from_pybankid_exception(cls, exception):
"""Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError`
"""
return cls(
"{0}: {1}".format(exception.__class__.__name__, str(exception)),
_exception_class_to_status_code.get(exception.__class__),
) | python | def create_from_pybankid_exception(cls, exception):
"""Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError`
"""
return cls(
"{0}: {1}".format(exception.__class__.__name__, str(exception)),
_exception_class_to_status_code.get(exception.__class__),
) | [
"def",
"create_from_pybankid_exception",
"(",
"cls",
",",
"exception",
")",
":",
"return",
"cls",
"(",
"\"{0}: {1}\"",
".",
"format",
"(",
"exception",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"exception",
")",
")",
",",
"_exception_class_to_status_co... | Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError` | [
"Class",
"method",
"for",
"initiating",
"from",
"a",
"PyBankID",
"exception",
"."
] | b9af666f587b027391b25d811788d934a12b57e6 | https://github.com/hbldh/flask-pybankid/blob/b9af666f587b027391b25d811788d934a12b57e6/flask_pybankid.py#L192-L203 | train | 55,637 |
hbldh/flask-pybankid | flask_pybankid.py | FlaskPyBankIDError.to_dict | def to_dict(self):
"""Create a dict representation of this exception.
:return: The dictionary representation.
:rtype: dict
"""
rv = dict(self.payload or ())
rv["message"] = self.message
return rv | python | def to_dict(self):
"""Create a dict representation of this exception.
:return: The dictionary representation.
:rtype: dict
"""
rv = dict(self.payload or ())
rv["message"] = self.message
return rv | [
"def",
"to_dict",
"(",
"self",
")",
":",
"rv",
"=",
"dict",
"(",
"self",
".",
"payload",
"or",
"(",
")",
")",
"rv",
"[",
"\"message\"",
"]",
"=",
"self",
".",
"message",
"return",
"rv"
] | Create a dict representation of this exception.
:return: The dictionary representation.
:rtype: dict | [
"Create",
"a",
"dict",
"representation",
"of",
"this",
"exception",
"."
] | b9af666f587b027391b25d811788d934a12b57e6 | https://github.com/hbldh/flask-pybankid/blob/b9af666f587b027391b25d811788d934a12b57e6/flask_pybankid.py#L205-L214 | train | 55,638 |
asobrien/randomOrg | randomorg/_rand_core.py | integers | def integers(num, minimum, maximum, base=10):
# TODO: Ensure numbers within bounds
"""Random integers within specified interval.
The integer generator generates truly random integers in the specified
interval.
Parameters
----------
num : int, bounds=[1, 1E4]
Total number of integers in returned array.
minimum : int, bounds=[-1E9, 1E9]
Minimum value (inclusive) of returned integers.
maximum : int, bounds=[-1E9, 1E9]
Maximum value (inclusive) of returned integers.
base: int, values=[2, 8, 10, 16], default=10
Base used to print numbers in array, the default is decimal
representation (base=10).
Returns
-------
integers : array
A 1D numpy array containing integers between the specified
bounds.
Examples
--------
Generate an array of 10 integers with values between -100 and 100,
inclusive:
>>> integers(10, -100, 100)
A coin toss, where heads=1 and tails=0, with multiple flips (flips should
be an odd number):
>>> sum(integers(5, 0, 1))
"""
function = 'integers'
num, minimum, maximum = list(map(int, [num, minimum, maximum]))
# INPUT ERROR CHECKING
# Check input values are within range
if (1 <= num <= 10 ** 4) is False:
print('ERROR: %s is out of range' % num)
return
if (-10 ** 9 <= minimum <= 10 ** 9) is False:
print('ERROR: %s is out of range' % minimum)
return
if (-10 ** 9 <= maximum <= 10 ** 9) is False:
print('ERROR: %s is out of range' % maximum)
return
if maximum < minimum:
print('ERROR: %s is less than %s' % (maximum, minimum))
return
base = int(base)
if base not in [2, 8, 10, 16]:
raise Exception('Base not in range!')
opts = {'num': num,
'min': minimum,
'max': maximum,
'col': 1,
'base': base,
'format': 'plain',
'rnd': 'new'}
integers = get_http(RANDOM_URL, function, opts)
integers_arr = str_to_arr(integers)
return integers_arr | python | def integers(num, minimum, maximum, base=10):
# TODO: Ensure numbers within bounds
"""Random integers within specified interval.
The integer generator generates truly random integers in the specified
interval.
Parameters
----------
num : int, bounds=[1, 1E4]
Total number of integers in returned array.
minimum : int, bounds=[-1E9, 1E9]
Minimum value (inclusive) of returned integers.
maximum : int, bounds=[-1E9, 1E9]
Maximum value (inclusive) of returned integers.
base: int, values=[2, 8, 10, 16], default=10
Base used to print numbers in array, the default is decimal
representation (base=10).
Returns
-------
integers : array
A 1D numpy array containing integers between the specified
bounds.
Examples
--------
Generate an array of 10 integers with values between -100 and 100,
inclusive:
>>> integers(10, -100, 100)
A coin toss, where heads=1 and tails=0, with multiple flips (flips should
be an odd number):
>>> sum(integers(5, 0, 1))
"""
function = 'integers'
num, minimum, maximum = list(map(int, [num, minimum, maximum]))
# INPUT ERROR CHECKING
# Check input values are within range
if (1 <= num <= 10 ** 4) is False:
print('ERROR: %s is out of range' % num)
return
if (-10 ** 9 <= minimum <= 10 ** 9) is False:
print('ERROR: %s is out of range' % minimum)
return
if (-10 ** 9 <= maximum <= 10 ** 9) is False:
print('ERROR: %s is out of range' % maximum)
return
if maximum < minimum:
print('ERROR: %s is less than %s' % (maximum, minimum))
return
base = int(base)
if base not in [2, 8, 10, 16]:
raise Exception('Base not in range!')
opts = {'num': num,
'min': minimum,
'max': maximum,
'col': 1,
'base': base,
'format': 'plain',
'rnd': 'new'}
integers = get_http(RANDOM_URL, function, opts)
integers_arr = str_to_arr(integers)
return integers_arr | [
"def",
"integers",
"(",
"num",
",",
"minimum",
",",
"maximum",
",",
"base",
"=",
"10",
")",
":",
"# TODO: Ensure numbers within bounds",
"function",
"=",
"'integers'",
"num",
",",
"minimum",
",",
"maximum",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"[",
... | Random integers within specified interval.
The integer generator generates truly random integers in the specified
interval.
Parameters
----------
num : int, bounds=[1, 1E4]
Total number of integers in returned array.
minimum : int, bounds=[-1E9, 1E9]
Minimum value (inclusive) of returned integers.
maximum : int, bounds=[-1E9, 1E9]
Maximum value (inclusive) of returned integers.
base: int, values=[2, 8, 10, 16], default=10
Base used to print numbers in array, the default is decimal
representation (base=10).
Returns
-------
integers : array
A 1D numpy array containing integers between the specified
bounds.
Examples
--------
Generate an array of 10 integers with values between -100 and 100,
inclusive:
>>> integers(10, -100, 100)
A coin toss, where heads=1 and tails=0, with multiple flips (flips should
be an odd number):
>>> sum(integers(5, 0, 1)) | [
"Random",
"integers",
"within",
"specified",
"interval",
"."
] | 76c3f167c5689992d32cd1f827816254158160f7 | https://github.com/asobrien/randomOrg/blob/76c3f167c5689992d32cd1f827816254158160f7/randomorg/_rand_core.py#L25-L95 | train | 55,639 |
asobrien/randomOrg | randomorg/_rand_core.py | sequence | def sequence(minimum, maximum):
"""Randomize a sequence of integers."""
function = 'sequences'
opts = {'min': minimum,
'max': maximum,
'col': 1,
'format': 'plain',
'rnd': 'new'}
deal = get_http(RANDOM_URL, function, opts)
deal_arr = str_to_arr(deal)
return deal_arr | python | def sequence(minimum, maximum):
"""Randomize a sequence of integers."""
function = 'sequences'
opts = {'min': minimum,
'max': maximum,
'col': 1,
'format': 'plain',
'rnd': 'new'}
deal = get_http(RANDOM_URL, function, opts)
deal_arr = str_to_arr(deal)
return deal_arr | [
"def",
"sequence",
"(",
"minimum",
",",
"maximum",
")",
":",
"function",
"=",
"'sequences'",
"opts",
"=",
"{",
"'min'",
":",
"minimum",
",",
"'max'",
":",
"maximum",
",",
"'col'",
":",
"1",
",",
"'format'",
":",
"'plain'",
",",
"'rnd'",
":",
"'new'",
... | Randomize a sequence of integers. | [
"Randomize",
"a",
"sequence",
"of",
"integers",
"."
] | 76c3f167c5689992d32cd1f827816254158160f7 | https://github.com/asobrien/randomOrg/blob/76c3f167c5689992d32cd1f827816254158160f7/randomorg/_rand_core.py#L98-L108 | train | 55,640 |
asobrien/randomOrg | randomorg/_rand_core.py | string | def string(num, length, digits=False, upper=True, lower=True, unique=False):
"""Random strings."""
function = 'strings'
# Convert arguments to random.org style
# for a discussion on the method see: http://bit.ly/TKGkOF
digits = convert(digits)
upper = convert(upper)
lower = convert(lower)
unique = convert(unique)
opts = {'num': num,
'len': length,
'digits': digits,
'upperalpha': upper,
'loweralpha': lower,
'format': 'plain',
'rnd': 'new'}
seq = get_http(RANDOM_URL, function, opts)
seq = seq.strip().split('\n') # convert to list
# seq_arr = str_to_arr(seq)
return seq | python | def string(num, length, digits=False, upper=True, lower=True, unique=False):
"""Random strings."""
function = 'strings'
# Convert arguments to random.org style
# for a discussion on the method see: http://bit.ly/TKGkOF
digits = convert(digits)
upper = convert(upper)
lower = convert(lower)
unique = convert(unique)
opts = {'num': num,
'len': length,
'digits': digits,
'upperalpha': upper,
'loweralpha': lower,
'format': 'plain',
'rnd': 'new'}
seq = get_http(RANDOM_URL, function, opts)
seq = seq.strip().split('\n') # convert to list
# seq_arr = str_to_arr(seq)
return seq | [
"def",
"string",
"(",
"num",
",",
"length",
",",
"digits",
"=",
"False",
",",
"upper",
"=",
"True",
",",
"lower",
"=",
"True",
",",
"unique",
"=",
"False",
")",
":",
"function",
"=",
"'strings'",
"# Convert arguments to random.org style",
"# for a discussion o... | Random strings. | [
"Random",
"strings",
"."
] | 76c3f167c5689992d32cd1f827816254158160f7 | https://github.com/asobrien/randomOrg/blob/76c3f167c5689992d32cd1f827816254158160f7/randomorg/_rand_core.py#L111-L131 | train | 55,641 |
asobrien/randomOrg | randomorg/_rand_core.py | quota | def quota(ip=None):
"""Check your quota."""
# TODO: Add arbitrary user defined IP check
url = 'http://www.random.org/quota/?format=plain'
data = urlopen(url)
credit = int(data.read().strip())
if data.code == 200:
return credit
else:
return "ERROR: Server responded with code %s" % data.code | python | def quota(ip=None):
"""Check your quota."""
# TODO: Add arbitrary user defined IP check
url = 'http://www.random.org/quota/?format=plain'
data = urlopen(url)
credit = int(data.read().strip())
if data.code == 200:
return credit
else:
return "ERROR: Server responded with code %s" % data.code | [
"def",
"quota",
"(",
"ip",
"=",
"None",
")",
":",
"# TODO: Add arbitrary user defined IP check",
"url",
"=",
"'http://www.random.org/quota/?format=plain'",
"data",
"=",
"urlopen",
"(",
"url",
")",
"credit",
"=",
"int",
"(",
"data",
".",
"read",
"(",
")",
".",
... | Check your quota. | [
"Check",
"your",
"quota",
"."
] | 76c3f167c5689992d32cd1f827816254158160f7 | https://github.com/asobrien/randomOrg/blob/76c3f167c5689992d32cd1f827816254158160f7/randomorg/_rand_core.py#L134-L143 | train | 55,642 |
asobrien/randomOrg | randomorg/_rand_core.py | get_http | def get_http(base_url, function, opts):
"""HTTP request generator."""
url = (os.path.join(base_url, function) + '/?' + urlencode(opts))
data = urlopen(url)
if data.code != 200:
raise ValueError("Random.rg returned server code: " + str(data.code))
return data.read() | python | def get_http(base_url, function, opts):
"""HTTP request generator."""
url = (os.path.join(base_url, function) + '/?' + urlencode(opts))
data = urlopen(url)
if data.code != 200:
raise ValueError("Random.rg returned server code: " + str(data.code))
return data.read() | [
"def",
"get_http",
"(",
"base_url",
",",
"function",
",",
"opts",
")",
":",
"url",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_url",
",",
"function",
")",
"+",
"'/?'",
"+",
"urlencode",
"(",
"opts",
")",
")",
"data",
"=",
"urlopen",
"(",
... | HTTP request generator. | [
"HTTP",
"request",
"generator",
"."
] | 76c3f167c5689992d32cd1f827816254158160f7 | https://github.com/asobrien/randomOrg/blob/76c3f167c5689992d32cd1f827816254158160f7/randomorg/_rand_core.py#L148-L155 | train | 55,643 |
Equitable/trump | setup.py | read | def read(*p):
"""Build a file path from paths and return the contents."""
with open(os.path.join(*p), 'r') as fi:
return fi.read() | python | def read(*p):
"""Build a file path from paths and return the contents."""
with open(os.path.join(*p), 'r') as fi:
return fi.read() | [
"def",
"read",
"(",
"*",
"p",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"*",
"p",
")",
",",
"'r'",
")",
"as",
"fi",
":",
"return",
"fi",
".",
"read",
"(",
")"
] | Build a file path from paths and return the contents. | [
"Build",
"a",
"file",
"path",
"from",
"paths",
"and",
"return",
"the",
"contents",
"."
] | a2802692bc642fa32096374159eea7ceca2947b4 | https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/setup.py#L42-L45 | train | 55,644 |
sporsh/carnifex | carnifex/inductor.py | ProcessInductor.execute | def execute(self, processProtocol, command, env={},
path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Form a command and start a process in the desired environment.
"""
raise NotImplementedError() | python | def execute(self, processProtocol, command, env={},
path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Form a command and start a process in the desired environment.
"""
raise NotImplementedError() | [
"def",
"execute",
"(",
"self",
",",
"processProtocol",
",",
"command",
",",
"env",
"=",
"{",
"}",
",",
"path",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"usePTY",
"=",
"0",
",",
"childFDs",
"=",
"None",
")",
":",
"raise"... | Form a command and start a process in the desired environment. | [
"Form",
"a",
"command",
"and",
"start",
"a",
"process",
"in",
"the",
"desired",
"environment",
"."
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/inductor.py#L15-L19 | train | 55,645 |
sporsh/carnifex | carnifex/inductor.py | ProcessInductor.run | def run(self, command, env={}, path=None,
uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a command and return the results of the completed run.
"""
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
d = defer.maybeDeferred(self.execute, processProtocol, command, env,
path, uid, gid, usePTY, childFDs)
d.addErrback(deferred.errback)
return deferred | python | def run(self, command, env={}, path=None,
uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a command and return the results of the completed run.
"""
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
d = defer.maybeDeferred(self.execute, processProtocol, command, env,
path, uid, gid, usePTY, childFDs)
d.addErrback(deferred.errback)
return deferred | [
"def",
"run",
"(",
"self",
",",
"command",
",",
"env",
"=",
"{",
"}",
",",
"path",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"usePTY",
"=",
"0",
",",
"childFDs",
"=",
"None",
")",
":",
"deferred",
"=",
"defer",
".",
... | Execute a command and return the results of the completed run. | [
"Execute",
"a",
"command",
"and",
"return",
"the",
"results",
"of",
"the",
"completed",
"run",
"."
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/inductor.py#L21-L30 | train | 55,646 |
sporsh/carnifex | carnifex/inductor.py | ProcessInductor.getOutput | def getOutput(self, command, env={}, path=None,
uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a command and get the output of the finished process.
"""
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
self.execute(processProtocol, command, env,
path, uid, gid, usePTY, childFDs)
@deferred.addCallback
def getStdOut(tuple_):
stdout, _stderr, _returnCode = tuple_
return stdout
return deferred | python | def getOutput(self, command, env={}, path=None,
uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a command and get the output of the finished process.
"""
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
self.execute(processProtocol, command, env,
path, uid, gid, usePTY, childFDs)
@deferred.addCallback
def getStdOut(tuple_):
stdout, _stderr, _returnCode = tuple_
return stdout
return deferred | [
"def",
"getOutput",
"(",
"self",
",",
"command",
",",
"env",
"=",
"{",
"}",
",",
"path",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"usePTY",
"=",
"0",
",",
"childFDs",
"=",
"None",
")",
":",
"deferred",
"=",
"defer",
"... | Execute a command and get the output of the finished process. | [
"Execute",
"a",
"command",
"and",
"get",
"the",
"output",
"of",
"the",
"finished",
"process",
"."
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/inductor.py#L32-L44 | train | 55,647 |
sporsh/carnifex | carnifex/inductor.py | ProcessInductor.getExitCode | def getExitCode(self, command, env={}, path=None, uid=None, gid=None,
usePTY=0, childFDs=None):
"""Execute a command and get the return code of the finished process.
"""
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
self.execute(processProtocol, command, env, path, uid, gid,
usePTY, childFDs)
@deferred.addCallback
def getStdOut(tuple_):
_stdout, _stderr, exitCode = tuple_
return exitCode
return deferred | python | def getExitCode(self, command, env={}, path=None, uid=None, gid=None,
usePTY=0, childFDs=None):
"""Execute a command and get the return code of the finished process.
"""
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
self.execute(processProtocol, command, env, path, uid, gid,
usePTY, childFDs)
@deferred.addCallback
def getStdOut(tuple_):
_stdout, _stderr, exitCode = tuple_
return exitCode
return deferred | [
"def",
"getExitCode",
"(",
"self",
",",
"command",
",",
"env",
"=",
"{",
"}",
",",
"path",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"usePTY",
"=",
"0",
",",
"childFDs",
"=",
"None",
")",
":",
"deferred",
"=",
"defer",
... | Execute a command and get the return code of the finished process. | [
"Execute",
"a",
"command",
"and",
"get",
"the",
"return",
"code",
"of",
"the",
"finished",
"process",
"."
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/inductor.py#L46-L58 | train | 55,648 |
thomasantony/simplepipe | simplepipe.py | validate_task | def validate_task(original_task):
"""
Validates task and adds default values for missing options using the
following steps.
1. If there is no input list specified or if it is None, the input spec is
assumed to be ['*'].
2. If there are not outputs specified, or if the output spec is None or an
empty list, the output spec is assumed to be ['*'].
3. If the input or output spec is not iterable, they are converted into
single element tuples. If they are any iterable, they are converted into
tuples.
4. The task['fn'] option must be callable.
5. If number of outputs is more than one, task['fn'] must be a generator
function.
6. Generator functions are not supported for output spec of '*'.
Returns new task with updated options
"""
task = original_task._asdict()
# Default values for inputs and outputs
if 'inputs' not in task or task['inputs'] is None:
task['inputs'] = ['*']
# Outputs list cannot be empty
if ('outputs' not in task or
task['outputs'] is None or
len(task['outputs']) == 0):
task['outputs'] = ['*']
# Convert to tuples (even for single values)
if not hasattr(task['inputs'], '__iter__') or isinstance(task['inputs'], str):
task['inputs'] = (task['inputs'],)
else:
task['inputs'] = tuple(task['inputs'])
if not hasattr(task['outputs'], '__iter__') or isinstance(task['outputs'], str):
task['outputs'] = (task['outputs'],)
else:
task['outputs'] = tuple(task['outputs'])
if not callable(task['fn']):
raise TypeError('Task function must be a callable object')
if (len(task['outputs']) > 1 and
not inspect.isgeneratorfunction(task['fn'])):
raise TypeError('Multiple outputs are only supported with \
generator functions')
if inspect.isgeneratorfunction(task['fn']):
if task['outputs'][0] == '*':
raise TypeError('Generator functions cannot be used for tasks with \
output specification "*"')
return Task(**task) | python | def validate_task(original_task):
"""
Validates task and adds default values for missing options using the
following steps.
1. If there is no input list specified or if it is None, the input spec is
assumed to be ['*'].
2. If there are not outputs specified, or if the output spec is None or an
empty list, the output spec is assumed to be ['*'].
3. If the input or output spec is not iterable, they are converted into
single element tuples. If they are any iterable, they are converted into
tuples.
4. The task['fn'] option must be callable.
5. If number of outputs is more than one, task['fn'] must be a generator
function.
6. Generator functions are not supported for output spec of '*'.
Returns new task with updated options
"""
task = original_task._asdict()
# Default values for inputs and outputs
if 'inputs' not in task or task['inputs'] is None:
task['inputs'] = ['*']
# Outputs list cannot be empty
if ('outputs' not in task or
task['outputs'] is None or
len(task['outputs']) == 0):
task['outputs'] = ['*']
# Convert to tuples (even for single values)
if not hasattr(task['inputs'], '__iter__') or isinstance(task['inputs'], str):
task['inputs'] = (task['inputs'],)
else:
task['inputs'] = tuple(task['inputs'])
if not hasattr(task['outputs'], '__iter__') or isinstance(task['outputs'], str):
task['outputs'] = (task['outputs'],)
else:
task['outputs'] = tuple(task['outputs'])
if not callable(task['fn']):
raise TypeError('Task function must be a callable object')
if (len(task['outputs']) > 1 and
not inspect.isgeneratorfunction(task['fn'])):
raise TypeError('Multiple outputs are only supported with \
generator functions')
if inspect.isgeneratorfunction(task['fn']):
if task['outputs'][0] == '*':
raise TypeError('Generator functions cannot be used for tasks with \
output specification "*"')
return Task(**task) | [
"def",
"validate_task",
"(",
"original_task",
")",
":",
"task",
"=",
"original_task",
".",
"_asdict",
"(",
")",
"# Default values for inputs and outputs",
"if",
"'inputs'",
"not",
"in",
"task",
"or",
"task",
"[",
"'inputs'",
"]",
"is",
"None",
":",
"task",
"["... | Validates task and adds default values for missing options using the
following steps.
1. If there is no input list specified or if it is None, the input spec is
assumed to be ['*'].
2. If there are not outputs specified, or if the output spec is None or an
empty list, the output spec is assumed to be ['*'].
3. If the input or output spec is not iterable, they are converted into
single element tuples. If they are any iterable, they are converted into
tuples.
4. The task['fn'] option must be callable.
5. If number of outputs is more than one, task['fn'] must be a generator
function.
6. Generator functions are not supported for output spec of '*'.
Returns new task with updated options | [
"Validates",
"task",
"and",
"adds",
"default",
"values",
"for",
"missing",
"options",
"using",
"the",
"following",
"steps",
"."
] | c79d5f6ab27067e16d3d5d23364be5dd12448c04 | https://github.com/thomasantony/simplepipe/blob/c79d5f6ab27067e16d3d5d23364be5dd12448c04/simplepipe.py#L13-L72 | train | 55,649 |
thomasantony/simplepipe | simplepipe.py | run_task | def run_task(task, workspace):
"""
Runs the task and updates the workspace with results.
Parameters
----------
task - dict
Task Description
Examples:
{'task': task_func, 'inputs': ['a', 'b'], 'outputs': 'c'}
{'task': task_func, 'inputs': '*', 'outputs': '*'}
{'task': task_func, 'inputs': ['*','a'], 'outputs': 'b'}
Returns a new workspace with results
"""
data = copy.copy(workspace)
task = validate_task(task)
# Prepare input to task
inputs = [input_parser(key, data) for key in task.inputs]
if inspect.isgeneratorfunction(task.fn):
# Multiple output task
# Assuming number of outputs are equal to number of return values
data.update(zip(task.outputs, task.fn(*inputs)))
else:
# Single output task
results = task.fn(*inputs)
if task.outputs[0] != '*':
results = {task.outputs[0]: results}
elif not isinstance(results, dict):
raise TypeError('Result should be a dict for output type *')
data.update(results)
return data | python | def run_task(task, workspace):
"""
Runs the task and updates the workspace with results.
Parameters
----------
task - dict
Task Description
Examples:
{'task': task_func, 'inputs': ['a', 'b'], 'outputs': 'c'}
{'task': task_func, 'inputs': '*', 'outputs': '*'}
{'task': task_func, 'inputs': ['*','a'], 'outputs': 'b'}
Returns a new workspace with results
"""
data = copy.copy(workspace)
task = validate_task(task)
# Prepare input to task
inputs = [input_parser(key, data) for key in task.inputs]
if inspect.isgeneratorfunction(task.fn):
# Multiple output task
# Assuming number of outputs are equal to number of return values
data.update(zip(task.outputs, task.fn(*inputs)))
else:
# Single output task
results = task.fn(*inputs)
if task.outputs[0] != '*':
results = {task.outputs[0]: results}
elif not isinstance(results, dict):
raise TypeError('Result should be a dict for output type *')
data.update(results)
return data | [
"def",
"run_task",
"(",
"task",
",",
"workspace",
")",
":",
"data",
"=",
"copy",
".",
"copy",
"(",
"workspace",
")",
"task",
"=",
"validate_task",
"(",
"task",
")",
"# Prepare input to task",
"inputs",
"=",
"[",
"input_parser",
"(",
"key",
",",
"data",
"... | Runs the task and updates the workspace with results.
Parameters
----------
task - dict
Task Description
Examples:
{'task': task_func, 'inputs': ['a', 'b'], 'outputs': 'c'}
{'task': task_func, 'inputs': '*', 'outputs': '*'}
{'task': task_func, 'inputs': ['*','a'], 'outputs': 'b'}
Returns a new workspace with results | [
"Runs",
"the",
"task",
"and",
"updates",
"the",
"workspace",
"with",
"results",
"."
] | c79d5f6ab27067e16d3d5d23364be5dd12448c04 | https://github.com/thomasantony/simplepipe/blob/c79d5f6ab27067e16d3d5d23364be5dd12448c04/simplepipe.py#L83-L119 | train | 55,650 |
thomasantony/simplepipe | simplepipe.py | run_hook | def run_hook(name, workspace, hooks):
"""Runs all hooks added under the give name.
Parameters
----------
name - str
Name of the hook to invoke
workspace - dict
Workspace that the hook functions operate on
hooks - dict of lists
Mapping with hook names and callback functions
"""
data = copy.copy(workspace)
for hook_listener in hooks.get(name, []):
# Hook functions may mutate the data and returns nothing
hook_listener(data)
return data | python | def run_hook(name, workspace, hooks):
"""Runs all hooks added under the give name.
Parameters
----------
name - str
Name of the hook to invoke
workspace - dict
Workspace that the hook functions operate on
hooks - dict of lists
Mapping with hook names and callback functions
"""
data = copy.copy(workspace)
for hook_listener in hooks.get(name, []):
# Hook functions may mutate the data and returns nothing
hook_listener(data)
return data | [
"def",
"run_hook",
"(",
"name",
",",
"workspace",
",",
"hooks",
")",
":",
"data",
"=",
"copy",
".",
"copy",
"(",
"workspace",
")",
"for",
"hook_listener",
"in",
"hooks",
".",
"get",
"(",
"name",
",",
"[",
"]",
")",
":",
"# Hook functions may mutate the d... | Runs all hooks added under the give name.
Parameters
----------
name - str
Name of the hook to invoke
workspace - dict
Workspace that the hook functions operate on
hooks - dict of lists
Mapping with hook names and callback functions | [
"Runs",
"all",
"hooks",
"added",
"under",
"the",
"give",
"name",
"."
] | c79d5f6ab27067e16d3d5d23364be5dd12448c04 | https://github.com/thomasantony/simplepipe/blob/c79d5f6ab27067e16d3d5d23364be5dd12448c04/simplepipe.py#L122-L141 | train | 55,651 |
thomasantony/simplepipe | simplepipe.py | Workflow.add_task | def add_task(self, fn, inputs=None, outputs=None):
"""
Adds a task to the workflow.
Returns self to facilitate chaining method calls
"""
# self.tasks.append({'task': task, 'inputs': inputs, 'outputs': outputs})
self.tasks.append(Task(fn, inputs, outputs))
return self | python | def add_task(self, fn, inputs=None, outputs=None):
"""
Adds a task to the workflow.
Returns self to facilitate chaining method calls
"""
# self.tasks.append({'task': task, 'inputs': inputs, 'outputs': outputs})
self.tasks.append(Task(fn, inputs, outputs))
return self | [
"def",
"add_task",
"(",
"self",
",",
"fn",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
")",
":",
"# self.tasks.append({'task': task, 'inputs': inputs, 'outputs': outputs})",
"self",
".",
"tasks",
".",
"append",
"(",
"Task",
"(",
"fn",
",",
"inputs",... | Adds a task to the workflow.
Returns self to facilitate chaining method calls | [
"Adds",
"a",
"task",
"to",
"the",
"workflow",
"."
] | c79d5f6ab27067e16d3d5d23364be5dd12448c04 | https://github.com/thomasantony/simplepipe/blob/c79d5f6ab27067e16d3d5d23364be5dd12448c04/simplepipe.py#L158-L166 | train | 55,652 |
thomasantony/simplepipe | simplepipe.py | Workflow.add_hook | def add_hook(self, name, function):
"""
Adds a function to be called for hook of a given name.
The function gets entire workspace as input and
does not return anything.
Example:
def hook_fcn(workspace):
pass
"""
if not callable(function):
return ValueError('Hook function should be callable')
if name not in self.hooks:
self.hooks[name] = []
self.hooks[name].append(function)
return self | python | def add_hook(self, name, function):
"""
Adds a function to be called for hook of a given name.
The function gets entire workspace as input and
does not return anything.
Example:
def hook_fcn(workspace):
pass
"""
if not callable(function):
return ValueError('Hook function should be callable')
if name not in self.hooks:
self.hooks[name] = []
self.hooks[name].append(function)
return self | [
"def",
"add_hook",
"(",
"self",
",",
"name",
",",
"function",
")",
":",
"if",
"not",
"callable",
"(",
"function",
")",
":",
"return",
"ValueError",
"(",
"'Hook function should be callable'",
")",
"if",
"name",
"not",
"in",
"self",
".",
"hooks",
":",
"self"... | Adds a function to be called for hook of a given name.
The function gets entire workspace as input and
does not return anything.
Example:
def hook_fcn(workspace):
pass | [
"Adds",
"a",
"function",
"to",
"be",
"called",
"for",
"hook",
"of",
"a",
"given",
"name",
"."
] | c79d5f6ab27067e16d3d5d23364be5dd12448c04 | https://github.com/thomasantony/simplepipe/blob/c79d5f6ab27067e16d3d5d23364be5dd12448c04/simplepipe.py#L179-L195 | train | 55,653 |
foremast/gogo-utils | src/gogoutils/generator.py | Generator.dns | def dns(self):
"""DNS details."""
dns = {
'elb': self.dns_elb(),
'elb_region': self.dns_elb_region(),
'global': self.dns_global(),
'region': self.dns_region(),
'instance': self.dns_instance(),
}
return dns | python | def dns(self):
"""DNS details."""
dns = {
'elb': self.dns_elb(),
'elb_region': self.dns_elb_region(),
'global': self.dns_global(),
'region': self.dns_region(),
'instance': self.dns_instance(),
}
return dns | [
"def",
"dns",
"(",
"self",
")",
":",
"dns",
"=",
"{",
"'elb'",
":",
"self",
".",
"dns_elb",
"(",
")",
",",
"'elb_region'",
":",
"self",
".",
"dns_elb_region",
"(",
")",
",",
"'global'",
":",
"self",
".",
"dns_global",
"(",
")",
",",
"'region'",
":"... | DNS details. | [
"DNS",
"details",
"."
] | 3909c2d26e49baa8ad68e6be40977d4370d7c1ca | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L111-L121 | train | 55,654 |
foremast/gogo-utils | src/gogoutils/generator.py | Generator.s3_app_bucket | def s3_app_bucket(self, include_region=False):
"""Generate s3 application bucket name.
Args:
include_region (bool): Include region in the name generation.
"""
if include_region:
s3_app_bucket = self.format['s3_app_region_bucket'].format(**self.data)
else:
s3_app_bucket = self.format['s3_app_bucket'].format(**self.data)
return s3_app_bucket | python | def s3_app_bucket(self, include_region=False):
"""Generate s3 application bucket name.
Args:
include_region (bool): Include region in the name generation.
"""
if include_region:
s3_app_bucket = self.format['s3_app_region_bucket'].format(**self.data)
else:
s3_app_bucket = self.format['s3_app_bucket'].format(**self.data)
return s3_app_bucket | [
"def",
"s3_app_bucket",
"(",
"self",
",",
"include_region",
"=",
"False",
")",
":",
"if",
"include_region",
":",
"s3_app_bucket",
"=",
"self",
".",
"format",
"[",
"'s3_app_region_bucket'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"data",
")",
"else"... | Generate s3 application bucket name.
Args:
include_region (bool): Include region in the name generation. | [
"Generate",
"s3",
"application",
"bucket",
"name",
"."
] | 3909c2d26e49baa8ad68e6be40977d4370d7c1ca | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L123-L133 | train | 55,655 |
foremast/gogo-utils | src/gogoutils/generator.py | Generator.shared_s3_app_bucket | def shared_s3_app_bucket(self, include_region=False):
"""Generate shared s3 application bucket name.
Args:
include_region (bool): Include region in the name generation.
"""
if include_region:
shared_s3_app_bucket = self.format['shared_s3_app_region_bucket'].format(**self.data)
else:
shared_s3_app_bucket = self.format['shared_s3_app_bucket'].format(**self.data)
return shared_s3_app_bucket | python | def shared_s3_app_bucket(self, include_region=False):
"""Generate shared s3 application bucket name.
Args:
include_region (bool): Include region in the name generation.
"""
if include_region:
shared_s3_app_bucket = self.format['shared_s3_app_region_bucket'].format(**self.data)
else:
shared_s3_app_bucket = self.format['shared_s3_app_bucket'].format(**self.data)
return shared_s3_app_bucket | [
"def",
"shared_s3_app_bucket",
"(",
"self",
",",
"include_region",
"=",
"False",
")",
":",
"if",
"include_region",
":",
"shared_s3_app_bucket",
"=",
"self",
".",
"format",
"[",
"'shared_s3_app_region_bucket'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"d... | Generate shared s3 application bucket name.
Args:
include_region (bool): Include region in the name generation. | [
"Generate",
"shared",
"s3",
"application",
"bucket",
"name",
"."
] | 3909c2d26e49baa8ad68e6be40977d4370d7c1ca | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L135-L145 | train | 55,656 |
foremast/gogo-utils | src/gogoutils/generator.py | Generator.iam | def iam(self):
"""Generate iam details."""
iam = {
'group': self.format['iam_group'].format(**self.data),
'lambda_role': self.format['iam_lambda_role'].format(**self.data),
'policy': self.format['iam_policy'].format(**self.data),
'profile': self.format['iam_profile'].format(**self.data),
'role': self.format['iam_role'].format(**self.data),
'user': self.format['iam_user'].format(**self.data),
'base': self.format['iam_base'].format(**self.data),
}
return iam | python | def iam(self):
"""Generate iam details."""
iam = {
'group': self.format['iam_group'].format(**self.data),
'lambda_role': self.format['iam_lambda_role'].format(**self.data),
'policy': self.format['iam_policy'].format(**self.data),
'profile': self.format['iam_profile'].format(**self.data),
'role': self.format['iam_role'].format(**self.data),
'user': self.format['iam_user'].format(**self.data),
'base': self.format['iam_base'].format(**self.data),
}
return iam | [
"def",
"iam",
"(",
"self",
")",
":",
"iam",
"=",
"{",
"'group'",
":",
"self",
".",
"format",
"[",
"'iam_group'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"data",
")",
",",
"'lambda_role'",
":",
"self",
".",
"format",
"[",
"'iam_lambda_role'",
... | Generate iam details. | [
"Generate",
"iam",
"details",
"."
] | 3909c2d26e49baa8ad68e6be40977d4370d7c1ca | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L147-L159 | train | 55,657 |
foremast/gogo-utils | src/gogoutils/generator.py | Generator.archaius | def archaius(self):
"""Generate archaius bucket path."""
bucket = self.format['s3_bucket'].format(**self.data)
path = self.format['s3_bucket_path'].format(**self.data)
archaius_name = self.format['s3_archaius_name'].format(**self.data)
archaius = {'s3': archaius_name, 'bucket': bucket, 'path': path}
return archaius | python | def archaius(self):
"""Generate archaius bucket path."""
bucket = self.format['s3_bucket'].format(**self.data)
path = self.format['s3_bucket_path'].format(**self.data)
archaius_name = self.format['s3_archaius_name'].format(**self.data)
archaius = {'s3': archaius_name, 'bucket': bucket, 'path': path}
return archaius | [
"def",
"archaius",
"(",
"self",
")",
":",
"bucket",
"=",
"self",
".",
"format",
"[",
"'s3_bucket'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"data",
")",
"path",
"=",
"self",
".",
"format",
"[",
"'s3_bucket_path'",
"]",
".",
"format",
"(",
"... | Generate archaius bucket path. | [
"Generate",
"archaius",
"bucket",
"path",
"."
] | 3909c2d26e49baa8ad68e6be40977d4370d7c1ca | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L161-L168 | train | 55,658 |
foremast/gogo-utils | src/gogoutils/generator.py | Generator.jenkins | def jenkins(self):
"""Generate jenkins job details."""
job_name = self.format['jenkins_job_name'].format(**self.data)
job = {'name': job_name}
return job | python | def jenkins(self):
"""Generate jenkins job details."""
job_name = self.format['jenkins_job_name'].format(**self.data)
job = {'name': job_name}
return job | [
"def",
"jenkins",
"(",
"self",
")",
":",
"job_name",
"=",
"self",
".",
"format",
"[",
"'jenkins_job_name'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"data",
")",
"job",
"=",
"{",
"'name'",
":",
"job_name",
"}",
"return",
"job"
] | Generate jenkins job details. | [
"Generate",
"jenkins",
"job",
"details",
"."
] | 3909c2d26e49baa8ad68e6be40977d4370d7c1ca | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L170-L175 | train | 55,659 |
foremast/gogo-utils | src/gogoutils/generator.py | Generator.gitlab | def gitlab(self):
"""Generate gitlab details."""
main_name = self.format['git_repo'].format(**self.data)
qe_name = self.format['git_repo_qe'].format(**self.data)
config_name = self.format['git_repo_configs'].format(**self.data)
git = {
'config': config_name,
'main': main_name,
'qe': qe_name,
}
return git | python | def gitlab(self):
"""Generate gitlab details."""
main_name = self.format['git_repo'].format(**self.data)
qe_name = self.format['git_repo_qe'].format(**self.data)
config_name = self.format['git_repo_configs'].format(**self.data)
git = {
'config': config_name,
'main': main_name,
'qe': qe_name,
}
return git | [
"def",
"gitlab",
"(",
"self",
")",
":",
"main_name",
"=",
"self",
".",
"format",
"[",
"'git_repo'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"data",
")",
"qe_name",
"=",
"self",
".",
"format",
"[",
"'git_repo_qe'",
"]",
".",
"format",
"(",
"... | Generate gitlab details. | [
"Generate",
"gitlab",
"details",
"."
] | 3909c2d26e49baa8ad68e6be40977d4370d7c1ca | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L177-L189 | train | 55,660 |
mozilla-releng/mozilla-version | mozilla_version/parser.py | get_value_matched_by_regex | def get_value_matched_by_regex(field_name, regex_matches, string):
"""Ensure value stored in regex group exists."""
try:
value = regex_matches.group(field_name)
if value is not None:
return value
except IndexError:
pass
raise MissingFieldError(string, field_name) | python | def get_value_matched_by_regex(field_name, regex_matches, string):
"""Ensure value stored in regex group exists."""
try:
value = regex_matches.group(field_name)
if value is not None:
return value
except IndexError:
pass
raise MissingFieldError(string, field_name) | [
"def",
"get_value_matched_by_regex",
"(",
"field_name",
",",
"regex_matches",
",",
"string",
")",
":",
"try",
":",
"value",
"=",
"regex_matches",
".",
"group",
"(",
"field_name",
")",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"value",
"except",
"Ind... | Ensure value stored in regex group exists. | [
"Ensure",
"value",
"stored",
"in",
"regex",
"group",
"exists",
"."
] | e5400f31f7001bd48fb6e17626905147dd4c17d7 | https://github.com/mozilla-releng/mozilla-version/blob/e5400f31f7001bd48fb6e17626905147dd4c17d7/mozilla_version/parser.py#L6-L15 | train | 55,661 |
mozilla-releng/mozilla-version | mozilla_version/parser.py | positive_int | def positive_int(val):
"""Parse `val` into a positive integer."""
if isinstance(val, float):
raise ValueError('"{}" must not be a float'.format(val))
val = int(val)
if val >= 0:
return val
raise ValueError('"{}" must be positive'.format(val)) | python | def positive_int(val):
"""Parse `val` into a positive integer."""
if isinstance(val, float):
raise ValueError('"{}" must not be a float'.format(val))
val = int(val)
if val >= 0:
return val
raise ValueError('"{}" must be positive'.format(val)) | [
"def",
"positive_int",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"float",
")",
":",
"raise",
"ValueError",
"(",
"'\"{}\" must not be a float'",
".",
"format",
"(",
"val",
")",
")",
"val",
"=",
"int",
"(",
"val",
")",
"if",
"val",
">=",... | Parse `val` into a positive integer. | [
"Parse",
"val",
"into",
"a",
"positive",
"integer",
"."
] | e5400f31f7001bd48fb6e17626905147dd4c17d7 | https://github.com/mozilla-releng/mozilla-version/blob/e5400f31f7001bd48fb6e17626905147dd4c17d7/mozilla_version/parser.py#L26-L33 | train | 55,662 |
mozilla-releng/mozilla-version | mozilla_version/parser.py | strictly_positive_int_or_none | def strictly_positive_int_or_none(val):
"""Parse `val` into either `None` or a strictly positive integer."""
val = positive_int_or_none(val)
if val is None or val > 0:
return val
raise ValueError('"{}" must be strictly positive'.format(val)) | python | def strictly_positive_int_or_none(val):
"""Parse `val` into either `None` or a strictly positive integer."""
val = positive_int_or_none(val)
if val is None or val > 0:
return val
raise ValueError('"{}" must be strictly positive'.format(val)) | [
"def",
"strictly_positive_int_or_none",
"(",
"val",
")",
":",
"val",
"=",
"positive_int_or_none",
"(",
"val",
")",
"if",
"val",
"is",
"None",
"or",
"val",
">",
"0",
":",
"return",
"val",
"raise",
"ValueError",
"(",
"'\"{}\" must be strictly positive'",
".",
"f... | Parse `val` into either `None` or a strictly positive integer. | [
"Parse",
"val",
"into",
"either",
"None",
"or",
"a",
"strictly",
"positive",
"integer",
"."
] | e5400f31f7001bd48fb6e17626905147dd4c17d7 | https://github.com/mozilla-releng/mozilla-version/blob/e5400f31f7001bd48fb6e17626905147dd4c17d7/mozilla_version/parser.py#L43-L48 | train | 55,663 |
hollenstein/maspy | maspy/ontology.py | _attributeLinesToDict | def _attributeLinesToDict(attributeLines):
"""Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
NOTE: Some attributes can occur multiple times in one single term, for
example 'is_a' or 'relationship'. However, currently only the last
occurence is stored.
"""
attributes = dict()
for line in attributeLines:
attributeId, attributeValue = line.split(':', 1)
attributes[attributeId.strip()] = attributeValue.strip()
return attributes | python | def _attributeLinesToDict(attributeLines):
"""Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
NOTE: Some attributes can occur multiple times in one single term, for
example 'is_a' or 'relationship'. However, currently only the last
occurence is stored.
"""
attributes = dict()
for line in attributeLines:
attributeId, attributeValue = line.split(':', 1)
attributes[attributeId.strip()] = attributeValue.strip()
return attributes | [
"def",
"_attributeLinesToDict",
"(",
"attributeLines",
")",
":",
"attributes",
"=",
"dict",
"(",
")",
"for",
"line",
"in",
"attributeLines",
":",
"attributeId",
",",
"attributeValue",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"attributes",
"[",
... | Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
NOTE: Some attributes can occur multiple times in one single term, for
example 'is_a' or 'relationship'. However, currently only the last
occurence is stored. | [
"Converts",
"a",
"list",
"of",
"obo",
"Term",
"lines",
"to",
"a",
"dictionary",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/ontology.py#L82-L98 | train | 55,664 |
hollenstein/maspy | maspy/ontology.py | _termIsObsolete | def _termIsObsolete(oboTerm):
"""Determine wheter an obo 'Term' entry is marked as obsolete.
:param oboTerm: a dictionary as return by
:func:`maspy.ontology._attributeLinesToDict()`
:return: bool
"""
isObsolete = False
if u'is_obsolete' in oboTerm:
if oboTerm[u'is_obsolete'].lower() == u'true':
isObsolete = True
return isObsolete | python | def _termIsObsolete(oboTerm):
"""Determine wheter an obo 'Term' entry is marked as obsolete.
:param oboTerm: a dictionary as return by
:func:`maspy.ontology._attributeLinesToDict()`
:return: bool
"""
isObsolete = False
if u'is_obsolete' in oboTerm:
if oboTerm[u'is_obsolete'].lower() == u'true':
isObsolete = True
return isObsolete | [
"def",
"_termIsObsolete",
"(",
"oboTerm",
")",
":",
"isObsolete",
"=",
"False",
"if",
"u'is_obsolete'",
"in",
"oboTerm",
":",
"if",
"oboTerm",
"[",
"u'is_obsolete'",
"]",
".",
"lower",
"(",
")",
"==",
"u'true'",
":",
"isObsolete",
"=",
"True",
"return",
"i... | Determine wheter an obo 'Term' entry is marked as obsolete.
:param oboTerm: a dictionary as return by
:func:`maspy.ontology._attributeLinesToDict()`
:return: bool | [
"Determine",
"wheter",
"an",
"obo",
"Term",
"entry",
"is",
"marked",
"as",
"obsolete",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/ontology.py#L101-L113 | train | 55,665 |
invinst/ResponseBot | responsebot/utils/handler_utils.py | discover_handler_classes | def discover_handler_classes(handlers_package):
"""
Looks for handler classes within handler path module.
Currently it's not looking deep into nested module.
:param handlers_package: module path to handlers
:type handlers_package: string
:return: list of handler classes
"""
if handlers_package is None:
return
# Add working directory into PYTHONPATH to import developer packages
sys.path.insert(0, os.getcwd())
package = import_module(handlers_package)
# Continue searching for module if package is not a module
if hasattr(package, '__path__'):
for _, modname, _ in pkgutil.iter_modules(package.__path__):
import_module('{package}.{module}'.format(package=package.__name__, module=modname))
return registered_handlers | python | def discover_handler_classes(handlers_package):
"""
Looks for handler classes within handler path module.
Currently it's not looking deep into nested module.
:param handlers_package: module path to handlers
:type handlers_package: string
:return: list of handler classes
"""
if handlers_package is None:
return
# Add working directory into PYTHONPATH to import developer packages
sys.path.insert(0, os.getcwd())
package = import_module(handlers_package)
# Continue searching for module if package is not a module
if hasattr(package, '__path__'):
for _, modname, _ in pkgutil.iter_modules(package.__path__):
import_module('{package}.{module}'.format(package=package.__name__, module=modname))
return registered_handlers | [
"def",
"discover_handler_classes",
"(",
"handlers_package",
")",
":",
"if",
"handlers_package",
"is",
"None",
":",
"return",
"# Add working directory into PYTHONPATH to import developer packages",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"getcwd",
... | Looks for handler classes within handler path module.
Currently it's not looking deep into nested module.
:param handlers_package: module path to handlers
:type handlers_package: string
:return: list of handler classes | [
"Looks",
"for",
"handler",
"classes",
"within",
"handler",
"path",
"module",
"."
] | a6b1a431a343007f7ae55a193e432a61af22253f | https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/utils/handler_utils.py#L14-L37 | train | 55,666 |
derpferd/little-python | littlepython/tokenizer.py | Tokens.get_multi_word_keywords | def get_multi_word_keywords(features):
"""This returns an OrderedDict containing the multi word keywords in order of length.
This is so the tokenizer will match the longer matches before the shorter matches
"""
keys = {
'is not': Token(TokenTypes.NOT_EQUAL, 'is not'),
}
return OrderedDict(sorted(list(keys.items()), key=lambda t: len(t[0]), reverse=True)) | python | def get_multi_word_keywords(features):
"""This returns an OrderedDict containing the multi word keywords in order of length.
This is so the tokenizer will match the longer matches before the shorter matches
"""
keys = {
'is not': Token(TokenTypes.NOT_EQUAL, 'is not'),
}
return OrderedDict(sorted(list(keys.items()), key=lambda t: len(t[0]), reverse=True)) | [
"def",
"get_multi_word_keywords",
"(",
"features",
")",
":",
"keys",
"=",
"{",
"'is not'",
":",
"Token",
"(",
"TokenTypes",
".",
"NOT_EQUAL",
",",
"'is not'",
")",
",",
"}",
"return",
"OrderedDict",
"(",
"sorted",
"(",
"list",
"(",
"keys",
".",
"items",
... | This returns an OrderedDict containing the multi word keywords in order of length.
This is so the tokenizer will match the longer matches before the shorter matches | [
"This",
"returns",
"an",
"OrderedDict",
"containing",
"the",
"multi",
"word",
"keywords",
"in",
"order",
"of",
"length",
".",
"This",
"is",
"so",
"the",
"tokenizer",
"will",
"match",
"the",
"longer",
"matches",
"before",
"the",
"shorter",
"matches"
] | 3f89c74cffb6532c12c5b40843bd8ff8605638ba | https://github.com/derpferd/little-python/blob/3f89c74cffb6532c12c5b40843bd8ff8605638ba/littlepython/tokenizer.py#L204-L211 | train | 55,667 |
e7dal/bubble3 | bubble3/util/inside_try.py | inside_try | def inside_try(func, options={}):
""" decorator to silence exceptions, for logging
we want a "safe" fail of the functions """
if six.PY2:
name = func.func_name
else:
name = func.__name__
@wraps(func)
def silenceit(*args, **kwargs):
""" the function func to be silenced is wrapped inside a
try catch and returned, exceptions are logged
exceptions are returned in an error dict
takes all kinds of arguments and passes to the original func
"""
excpt = None
try:
return func(*args, **kwargs)
# pylint: disable=W0703
# inside_try.silenceit: Catching too general exception Exception
# that's the idea!
except Exception as excpt:
# first tell the object in charge
if 'ctx' in kwargs:
ctx = kwargs['ctx']
else:
# otherwise tell object defined in options
# if we can be sure there is a context
ctx = get_try_option(None, 'ctx')
if not ctx:
# tell a new object
ctx = Bubble('Inside Try')
# ctx.set_verbose(100); #todo: move to magic
head = name + ': silenced function inside_try:Error:'
if get_try_option(ctx, 'count_it'):
ctx.gbc.cry(head + 'counting')
if get_try_option(ctx, 'print_it'):
ctx.gbc.cry(head + 'printing:' + str(excpt))
if get_try_option(ctx, 'print_args'):
ctx.gbc.cry(head + 'printing ak:' + str(excpt))
ctx.gbc.cry('args', stuff=args)
ctx.gbc.cry('kwargs', stuff=kwargs)
if get_try_option(ctx, 'inspect_it'):
ctx.gbc.cry(head + 'inspecting:', stuff=excpt)
for s in inspect.stack():
ctx.gbc.cry(head + ':stack:', stuff=s)
if get_try_option(ctx, 'log_it'):
ctx.gbc.cry(head + 'logging')
for s in inspect.stack():
ctx.gbc.cry(head + ':stack:', stuff=s)
if get_try_option(ctx, 'reraise_it'):
ctx.gbc.cry(head + 'reraising')
raise excpt
# always return error
return {'error': str(excpt),
'silenced': name,
'args': args,
'kwargs': kwargs}
return silenceit | python | def inside_try(func, options={}):
""" decorator to silence exceptions, for logging
we want a "safe" fail of the functions """
if six.PY2:
name = func.func_name
else:
name = func.__name__
@wraps(func)
def silenceit(*args, **kwargs):
""" the function func to be silenced is wrapped inside a
try catch and returned, exceptions are logged
exceptions are returned in an error dict
takes all kinds of arguments and passes to the original func
"""
excpt = None
try:
return func(*args, **kwargs)
# pylint: disable=W0703
# inside_try.silenceit: Catching too general exception Exception
# that's the idea!
except Exception as excpt:
# first tell the object in charge
if 'ctx' in kwargs:
ctx = kwargs['ctx']
else:
# otherwise tell object defined in options
# if we can be sure there is a context
ctx = get_try_option(None, 'ctx')
if not ctx:
# tell a new object
ctx = Bubble('Inside Try')
# ctx.set_verbose(100); #todo: move to magic
head = name + ': silenced function inside_try:Error:'
if get_try_option(ctx, 'count_it'):
ctx.gbc.cry(head + 'counting')
if get_try_option(ctx, 'print_it'):
ctx.gbc.cry(head + 'printing:' + str(excpt))
if get_try_option(ctx, 'print_args'):
ctx.gbc.cry(head + 'printing ak:' + str(excpt))
ctx.gbc.cry('args', stuff=args)
ctx.gbc.cry('kwargs', stuff=kwargs)
if get_try_option(ctx, 'inspect_it'):
ctx.gbc.cry(head + 'inspecting:', stuff=excpt)
for s in inspect.stack():
ctx.gbc.cry(head + ':stack:', stuff=s)
if get_try_option(ctx, 'log_it'):
ctx.gbc.cry(head + 'logging')
for s in inspect.stack():
ctx.gbc.cry(head + ':stack:', stuff=s)
if get_try_option(ctx, 'reraise_it'):
ctx.gbc.cry(head + 'reraising')
raise excpt
# always return error
return {'error': str(excpt),
'silenced': name,
'args': args,
'kwargs': kwargs}
return silenceit | [
"def",
"inside_try",
"(",
"func",
",",
"options",
"=",
"{",
"}",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"func",
".",
"func_name",
"else",
":",
"name",
"=",
"func",
".",
"__name__",
"@",
"wraps",
"(",
"func",
")",
"def",
"silenceit",
... | decorator to silence exceptions, for logging
we want a "safe" fail of the functions | [
"decorator",
"to",
"silence",
"exceptions",
"for",
"logging",
"we",
"want",
"a",
"safe",
"fail",
"of",
"the",
"functions"
] | 59c735281a95b44f6263a25f4d6ce24fca520082 | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/bubble3/util/inside_try.py#L65-L125 | train | 55,668 |
dturanski/springcloudstream | springcloudstream/grpc/stream.py | BaseStreamComponent.start | def start(self):
"""
Start the server and run forever.
"""
Server().start(self.options,self.handler_function, self.__class__.component_type) | python | def start(self):
"""
Start the server and run forever.
"""
Server().start(self.options,self.handler_function, self.__class__.component_type) | [
"def",
"start",
"(",
"self",
")",
":",
"Server",
"(",
")",
".",
"start",
"(",
"self",
".",
"options",
",",
"self",
".",
"handler_function",
",",
"self",
".",
"__class__",
".",
"component_type",
")"
] | Start the server and run forever. | [
"Start",
"the",
"server",
"and",
"run",
"forever",
"."
] | 208b542f9eba82e97882d52703af8e965a62a980 | https://github.com/dturanski/springcloudstream/blob/208b542f9eba82e97882d52703af8e965a62a980/springcloudstream/grpc/stream.py#L108-L112 | train | 55,669 |
sharibarboza/py_zap | py_zap/sorter.py | Sorter.sort_entries | def sort_entries(self):
"""Get whether reverse is True or False. Return the sorted data."""
return sorted(self.data, key=self.sort_func, reverse=self.get_reverse()) | python | def sort_entries(self):
"""Get whether reverse is True or False. Return the sorted data."""
return sorted(self.data, key=self.sort_func, reverse=self.get_reverse()) | [
"def",
"sort_entries",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"data",
",",
"key",
"=",
"self",
".",
"sort_func",
",",
"reverse",
"=",
"self",
".",
"get_reverse",
"(",
")",
")"
] | Get whether reverse is True or False. Return the sorted data. | [
"Get",
"whether",
"reverse",
"is",
"True",
"or",
"False",
".",
"Return",
"the",
"sorted",
"data",
"."
] | ce90853efcad66d3e28b8f1ac910f275349d016c | https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/sorter.py#L61-L63 | train | 55,670 |
stephrdev/django-tapeforms | tapeforms/fieldsets.py | TapeformFieldset.visible_fields | def visible_fields(self):
"""
Returns the reduced set of visible fields to output from the form.
This method respects the provided ``fields`` configuration _and_ exlcudes
all fields from the ``exclude`` configuration.
If no ``fields`` where provided when configuring this fieldset, all visible
fields minus the excluded fields will be returned.
:return: List of bound field instances or empty tuple.
"""
form_visible_fields = self.form.visible_fields()
if self.render_fields:
fields = self.render_fields
else:
fields = [field.name for field in form_visible_fields]
filtered_fields = [field for field in fields if field not in self.exclude_fields]
return [field for field in form_visible_fields if field.name in filtered_fields] | python | def visible_fields(self):
"""
Returns the reduced set of visible fields to output from the form.
This method respects the provided ``fields`` configuration _and_ exlcudes
all fields from the ``exclude`` configuration.
If no ``fields`` where provided when configuring this fieldset, all visible
fields minus the excluded fields will be returned.
:return: List of bound field instances or empty tuple.
"""
form_visible_fields = self.form.visible_fields()
if self.render_fields:
fields = self.render_fields
else:
fields = [field.name for field in form_visible_fields]
filtered_fields = [field for field in fields if field not in self.exclude_fields]
return [field for field in form_visible_fields if field.name in filtered_fields] | [
"def",
"visible_fields",
"(",
"self",
")",
":",
"form_visible_fields",
"=",
"self",
".",
"form",
".",
"visible_fields",
"(",
")",
"if",
"self",
".",
"render_fields",
":",
"fields",
"=",
"self",
".",
"render_fields",
"else",
":",
"fields",
"=",
"[",
"field"... | Returns the reduced set of visible fields to output from the form.
This method respects the provided ``fields`` configuration _and_ exlcudes
all fields from the ``exclude`` configuration.
If no ``fields`` where provided when configuring this fieldset, all visible
fields minus the excluded fields will be returned.
:return: List of bound field instances or empty tuple. | [
"Returns",
"the",
"reduced",
"set",
"of",
"visible",
"fields",
"to",
"output",
"from",
"the",
"form",
"."
] | 255602de43777141f18afaf30669d7bdd4f7c323 | https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/fieldsets.py#L76-L97 | train | 55,671 |
stephrdev/django-tapeforms | tapeforms/fieldsets.py | TapeformFieldsetsMixin.get_fieldsets | def get_fieldsets(self, fieldsets=None):
"""
This method returns a generator which yields fieldset instances.
The method uses the optional fieldsets argument to generate fieldsets for.
If no fieldsets argument is passed, the class property ``fieldsets`` is used.
When generating the fieldsets, the method ensures that at least one fielset
will be the primary fieldset which is responsible for rendering the non field
errors and hidden fields.
:param fieldsets: Alternative set of fieldset kwargs. If passed this set is
prevered of the ``fieldsets`` property of the form.
:return: generator which yields fieldset instances.
"""
fieldsets = fieldsets or self.fieldsets
if not fieldsets:
raise StopIteration
# Search for primary marker in at least one of the fieldset kwargs.
has_primary = any(fieldset.get('primary') for fieldset in fieldsets)
for fieldset_kwargs in fieldsets:
fieldset_kwargs = copy.deepcopy(fieldset_kwargs)
fieldset_kwargs['form'] = self
if not has_primary:
fieldset_kwargs['primary'] = True
has_primary = True
yield self.get_fieldset(**fieldset_kwargs) | python | def get_fieldsets(self, fieldsets=None):
"""
This method returns a generator which yields fieldset instances.
The method uses the optional fieldsets argument to generate fieldsets for.
If no fieldsets argument is passed, the class property ``fieldsets`` is used.
When generating the fieldsets, the method ensures that at least one fielset
will be the primary fieldset which is responsible for rendering the non field
errors and hidden fields.
:param fieldsets: Alternative set of fieldset kwargs. If passed this set is
prevered of the ``fieldsets`` property of the form.
:return: generator which yields fieldset instances.
"""
fieldsets = fieldsets or self.fieldsets
if not fieldsets:
raise StopIteration
# Search for primary marker in at least one of the fieldset kwargs.
has_primary = any(fieldset.get('primary') for fieldset in fieldsets)
for fieldset_kwargs in fieldsets:
fieldset_kwargs = copy.deepcopy(fieldset_kwargs)
fieldset_kwargs['form'] = self
if not has_primary:
fieldset_kwargs['primary'] = True
has_primary = True
yield self.get_fieldset(**fieldset_kwargs) | [
"def",
"get_fieldsets",
"(",
"self",
",",
"fieldsets",
"=",
"None",
")",
":",
"fieldsets",
"=",
"fieldsets",
"or",
"self",
".",
"fieldsets",
"if",
"not",
"fieldsets",
":",
"raise",
"StopIteration",
"# Search for primary marker in at least one of the fieldset kwargs.",
... | This method returns a generator which yields fieldset instances.
The method uses the optional fieldsets argument to generate fieldsets for.
If no fieldsets argument is passed, the class property ``fieldsets`` is used.
When generating the fieldsets, the method ensures that at least one fielset
will be the primary fieldset which is responsible for rendering the non field
errors and hidden fields.
:param fieldsets: Alternative set of fieldset kwargs. If passed this set is
prevered of the ``fieldsets`` property of the form.
:return: generator which yields fieldset instances. | [
"This",
"method",
"returns",
"a",
"generator",
"which",
"yields",
"fieldset",
"instances",
"."
] | 255602de43777141f18afaf30669d7bdd4f7c323 | https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/fieldsets.py#L132-L163 | train | 55,672 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/Saleae/Saleae.py | get_chunks | def get_chunks(Array, Chunksize):
"""Generator that yields chunks of size ChunkSize"""
for i in range(0, len(Array), Chunksize):
yield Array[i:i + Chunksize] | python | def get_chunks(Array, Chunksize):
"""Generator that yields chunks of size ChunkSize"""
for i in range(0, len(Array), Chunksize):
yield Array[i:i + Chunksize] | [
"def",
"get_chunks",
"(",
"Array",
",",
"Chunksize",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"Array",
")",
",",
"Chunksize",
")",
":",
"yield",
"Array",
"[",
"i",
":",
"i",
"+",
"Chunksize",
"]"
] | Generator that yields chunks of size ChunkSize | [
"Generator",
"that",
"yields",
"chunks",
"of",
"size",
"ChunkSize"
] | 9d390acc834d70024d47b574aea14189a5a5714e | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/Saleae/Saleae.py#L4-L7 | train | 55,673 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/Saleae/Saleae.py | read_data_from_bin_file | def read_data_from_bin_file(fileName):
"""
Loads the binary data stored in the a binary file and extracts the
data for each channel that was saved, along with the sample rate and length
of the data array.
Parameters
----------
fileContent : bytes
bytes object containing the data from a .bin file exported from
the saleae data logger.
Returns
-------
ChannelData : list
List containing a list which contains the data from each channel
LenOf1Channel : int
The length of the data in each channel
NumOfChannels : int
The number of channels saved
SampleTime : float
The time between samples (in seconds)
SampleRate : float
The sample rate (in Hz)
"""
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
(ChannelData, LenOf1Channel,
NumOfChannels, SampleTime) = read_data_from_bytes(fileContent)
return ChannelData, LenOf1Channel, NumOfChannels, SampleTime | python | def read_data_from_bin_file(fileName):
"""
Loads the binary data stored in the a binary file and extracts the
data for each channel that was saved, along with the sample rate and length
of the data array.
Parameters
----------
fileContent : bytes
bytes object containing the data from a .bin file exported from
the saleae data logger.
Returns
-------
ChannelData : list
List containing a list which contains the data from each channel
LenOf1Channel : int
The length of the data in each channel
NumOfChannels : int
The number of channels saved
SampleTime : float
The time between samples (in seconds)
SampleRate : float
The sample rate (in Hz)
"""
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
(ChannelData, LenOf1Channel,
NumOfChannels, SampleTime) = read_data_from_bytes(fileContent)
return ChannelData, LenOf1Channel, NumOfChannels, SampleTime | [
"def",
"read_data_from_bin_file",
"(",
"fileName",
")",
":",
"with",
"open",
"(",
"fileName",
",",
"mode",
"=",
"'rb'",
")",
"as",
"file",
":",
"# b is important -> binary",
"fileContent",
"=",
"file",
".",
"read",
"(",
")",
"(",
"ChannelData",
",",
"LenOf1C... | Loads the binary data stored in the a binary file and extracts the
data for each channel that was saved, along with the sample rate and length
of the data array.
Parameters
----------
fileContent : bytes
bytes object containing the data from a .bin file exported from
the saleae data logger.
Returns
-------
ChannelData : list
List containing a list which contains the data from each channel
LenOf1Channel : int
The length of the data in each channel
NumOfChannels : int
The number of channels saved
SampleTime : float
The time between samples (in seconds)
SampleRate : float
The sample rate (in Hz) | [
"Loads",
"the",
"binary",
"data",
"stored",
"in",
"the",
"a",
"binary",
"file",
"and",
"extracts",
"the",
"data",
"for",
"each",
"channel",
"that",
"was",
"saved",
"along",
"with",
"the",
"sample",
"rate",
"and",
"length",
"of",
"the",
"data",
"array",
"... | 9d390acc834d70024d47b574aea14189a5a5714e | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/Saleae/Saleae.py#L9-L40 | train | 55,674 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/Saleae/Saleae.py | read_data_from_bytes | def read_data_from_bytes(fileContent):
"""
Takes the binary data stored in the binary string provided and extracts the
data for each channel that was saved, along with the sample rate and length
of the data array.
Parameters
----------
fileContent : bytes
bytes object containing the data from a .bin file exported from
the saleae data logger.
Returns
-------
ChannelData : list
List containing a list which contains the data from each channel
LenOf1Channel : int
The length of the data in each channel
NumOfChannels : int
The number of channels saved
SampleTime : float
The time between samples (in seconds)
SampleRate : float
The sample rate (in Hz)
"""
TotalDataLen = struct.unpack('Q', fileContent[:8])[0] # Unsigned long long
NumOfChannels = struct.unpack('I', fileContent[8:12])[0] # unsigned Long
SampleTime = struct.unpack('d', fileContent[12:20])[0]
AllChannelData = struct.unpack("f" * ((len(fileContent) -20) // 4), fileContent[20:])
# ignore the heading bytes (= 20)
# The remaining part forms the body, to know the number of bytes in the body do an integer division by 4 (since 4 bytes = 32 bits = sizeof(float)
LenOf1Channel = int(TotalDataLen/NumOfChannels)
ChannelData = list(get_chunks(AllChannelData, LenOf1Channel))
return ChannelData, LenOf1Channel, NumOfChannels, SampleTime | python | def read_data_from_bytes(fileContent):
"""
Takes the binary data stored in the binary string provided and extracts the
data for each channel that was saved, along with the sample rate and length
of the data array.
Parameters
----------
fileContent : bytes
bytes object containing the data from a .bin file exported from
the saleae data logger.
Returns
-------
ChannelData : list
List containing a list which contains the data from each channel
LenOf1Channel : int
The length of the data in each channel
NumOfChannels : int
The number of channels saved
SampleTime : float
The time between samples (in seconds)
SampleRate : float
The sample rate (in Hz)
"""
TotalDataLen = struct.unpack('Q', fileContent[:8])[0] # Unsigned long long
NumOfChannels = struct.unpack('I', fileContent[8:12])[0] # unsigned Long
SampleTime = struct.unpack('d', fileContent[12:20])[0]
AllChannelData = struct.unpack("f" * ((len(fileContent) -20) // 4), fileContent[20:])
# ignore the heading bytes (= 20)
# The remaining part forms the body, to know the number of bytes in the body do an integer division by 4 (since 4 bytes = 32 bits = sizeof(float)
LenOf1Channel = int(TotalDataLen/NumOfChannels)
ChannelData = list(get_chunks(AllChannelData, LenOf1Channel))
return ChannelData, LenOf1Channel, NumOfChannels, SampleTime | [
"def",
"read_data_from_bytes",
"(",
"fileContent",
")",
":",
"TotalDataLen",
"=",
"struct",
".",
"unpack",
"(",
"'Q'",
",",
"fileContent",
"[",
":",
"8",
"]",
")",
"[",
"0",
"]",
"# Unsigned long long ",
"NumOfChannels",
"=",
"struct",
".",
"unpack",
"(",
... | Takes the binary data stored in the binary string provided and extracts the
data for each channel that was saved, along with the sample rate and length
of the data array.
Parameters
----------
fileContent : bytes
bytes object containing the data from a .bin file exported from
the saleae data logger.
Returns
-------
ChannelData : list
List containing a list which contains the data from each channel
LenOf1Channel : int
The length of the data in each channel
NumOfChannels : int
The number of channels saved
SampleTime : float
The time between samples (in seconds)
SampleRate : float
The sample rate (in Hz) | [
"Takes",
"the",
"binary",
"data",
"stored",
"in",
"the",
"binary",
"string",
"provided",
"and",
"extracts",
"the",
"data",
"for",
"each",
"channel",
"that",
"was",
"saved",
"along",
"with",
"the",
"sample",
"rate",
"and",
"length",
"of",
"the",
"data",
"ar... | 9d390acc834d70024d47b574aea14189a5a5714e | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/Saleae/Saleae.py#L42-L79 | train | 55,675 |
Hypex/hyppy | hyppy/func.py | get_coord_box | def get_coord_box(centre_x, centre_y, distance):
"""Get the square boundary coordinates for a given centre and distance"""
"""Todo: return coordinates inside a circle, rather than a square"""
return {
'top_left': (centre_x - distance, centre_y + distance),
'top_right': (centre_x + distance, centre_y + distance),
'bottom_left': (centre_x - distance, centre_y - distance),
'bottom_right': (centre_x + distance, centre_y - distance),
} | python | def get_coord_box(centre_x, centre_y, distance):
"""Get the square boundary coordinates for a given centre and distance"""
"""Todo: return coordinates inside a circle, rather than a square"""
return {
'top_left': (centre_x - distance, centre_y + distance),
'top_right': (centre_x + distance, centre_y + distance),
'bottom_left': (centre_x - distance, centre_y - distance),
'bottom_right': (centre_x + distance, centre_y - distance),
} | [
"def",
"get_coord_box",
"(",
"centre_x",
",",
"centre_y",
",",
"distance",
")",
":",
"\"\"\"Todo: return coordinates inside a circle, rather than a square\"\"\"",
"return",
"{",
"'top_left'",
":",
"(",
"centre_x",
"-",
"distance",
",",
"centre_y",
"+",
"distance",
")",
... | Get the square boundary coordinates for a given centre and distance | [
"Get",
"the",
"square",
"boundary",
"coordinates",
"for",
"a",
"given",
"centre",
"and",
"distance"
] | a425619c2a102b0e598fd6cac8aa0f6b766f542d | https://github.com/Hypex/hyppy/blob/a425619c2a102b0e598fd6cac8aa0f6b766f542d/hyppy/func.py#L1-L9 | train | 55,676 |
Hypex/hyppy | hyppy/func.py | fleet_ttb | def fleet_ttb(unit_type, quantity, factories, is_techno=False, is_dict=False, stasis_enabled=False):
"""
Calculate the time taken to construct a given fleet
"""
unit_weights = {
UNIT_SCOUT: 1,
UNIT_DESTROYER: 13,
UNIT_BOMBER: 10,
UNIT_CRUISER: 85,
UNIT_STARBASE: 1,
}
govt_weight = 80 if is_dict else 100
prod_weight = 85 if is_techno else 100
weighted_qty = unit_weights[unit_type] * quantity
ttb = (weighted_qty * govt_weight * prod_weight) * (2 * factories)
# TTB is 66% longer with stasis enabled
return ttb + (ttb * 0.66) if stasis_enabled else ttb | python | def fleet_ttb(unit_type, quantity, factories, is_techno=False, is_dict=False, stasis_enabled=False):
"""
Calculate the time taken to construct a given fleet
"""
unit_weights = {
UNIT_SCOUT: 1,
UNIT_DESTROYER: 13,
UNIT_BOMBER: 10,
UNIT_CRUISER: 85,
UNIT_STARBASE: 1,
}
govt_weight = 80 if is_dict else 100
prod_weight = 85 if is_techno else 100
weighted_qty = unit_weights[unit_type] * quantity
ttb = (weighted_qty * govt_weight * prod_weight) * (2 * factories)
# TTB is 66% longer with stasis enabled
return ttb + (ttb * 0.66) if stasis_enabled else ttb | [
"def",
"fleet_ttb",
"(",
"unit_type",
",",
"quantity",
",",
"factories",
",",
"is_techno",
"=",
"False",
",",
"is_dict",
"=",
"False",
",",
"stasis_enabled",
"=",
"False",
")",
":",
"unit_weights",
"=",
"{",
"UNIT_SCOUT",
":",
"1",
",",
"UNIT_DESTROYER",
"... | Calculate the time taken to construct a given fleet | [
"Calculate",
"the",
"time",
"taken",
"to",
"construct",
"a",
"given",
"fleet"
] | a425619c2a102b0e598fd6cac8aa0f6b766f542d | https://github.com/Hypex/hyppy/blob/a425619c2a102b0e598fd6cac8aa0f6b766f542d/hyppy/func.py#L19-L40 | train | 55,677 |
standage/tag | tag/reader.py | parse_fasta | def parse_fasta(data): # pragma: no cover
"""
Load sequences in Fasta format.
This generator function yields a Sequence object for each sequence record
in a GFF3 file. Implementation stolen shamelessly from
http://stackoverflow.com/a/7655072/459780.
"""
name, seq = None, []
for line in data:
line = line.rstrip()
if line.startswith('>'):
if name:
yield Sequence(name, ''.join(seq))
name, seq = line, []
else:
seq.append(line)
if name:
yield Sequence(name, ''.join(seq)) | python | def parse_fasta(data): # pragma: no cover
"""
Load sequences in Fasta format.
This generator function yields a Sequence object for each sequence record
in a GFF3 file. Implementation stolen shamelessly from
http://stackoverflow.com/a/7655072/459780.
"""
name, seq = None, []
for line in data:
line = line.rstrip()
if line.startswith('>'):
if name:
yield Sequence(name, ''.join(seq))
name, seq = line, []
else:
seq.append(line)
if name:
yield Sequence(name, ''.join(seq)) | [
"def",
"parse_fasta",
"(",
"data",
")",
":",
"# pragma: no cover",
"name",
",",
"seq",
"=",
"None",
",",
"[",
"]",
"for",
"line",
"in",
"data",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'>'",
")",
":"... | Load sequences in Fasta format.
This generator function yields a Sequence object for each sequence record
in a GFF3 file. Implementation stolen shamelessly from
http://stackoverflow.com/a/7655072/459780. | [
"Load",
"sequences",
"in",
"Fasta",
"format",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/reader.py#L19-L37 | train | 55,678 |
standage/tag | tag/reader.py | GFF3Reader._reset | def _reset(self):
"""Clear internal data structure."""
self.records = list()
self.featsbyid = dict()
self.featsbyparent = dict()
self.countsbytype = dict() | python | def _reset(self):
"""Clear internal data structure."""
self.records = list()
self.featsbyid = dict()
self.featsbyparent = dict()
self.countsbytype = dict() | [
"def",
"_reset",
"(",
"self",
")",
":",
"self",
".",
"records",
"=",
"list",
"(",
")",
"self",
".",
"featsbyid",
"=",
"dict",
"(",
")",
"self",
".",
"featsbyparent",
"=",
"dict",
"(",
")",
"self",
".",
"countsbytype",
"=",
"dict",
"(",
")"
] | Clear internal data structure. | [
"Clear",
"internal",
"data",
"structure",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/reader.py#L222-L227 | train | 55,679 |
jplusplus/statscraper | statscraper/BaseScraperList.py | BaseScraperList.get_by_label | def get_by_label(self, label):
""" Return the first item with a specific label,
or None.
"""
return next((x for x in self if x.label == label), None) | python | def get_by_label(self, label):
""" Return the first item with a specific label,
or None.
"""
return next((x for x in self if x.label == label), None) | [
"def",
"get_by_label",
"(",
"self",
",",
"label",
")",
":",
"return",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"self",
"if",
"x",
".",
"label",
"==",
"label",
")",
",",
"None",
")"
] | Return the first item with a specific label,
or None. | [
"Return",
"the",
"first",
"item",
"with",
"a",
"specific",
"label",
"or",
"None",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/BaseScraperList.py#L17-L21 | train | 55,680 |
sporsh/carnifex | carnifex/ssh/userauth.py | AutomaticUserAuthClient.getGenericAnswers | def getGenericAnswers(self, name, instruction, prompts):
"""Called when the server requests keyboard interactive authentication
"""
responses = []
for prompt, _echo in prompts:
password = self.getPassword(prompt)
responses.append(password)
return defer.succeed(responses) | python | def getGenericAnswers(self, name, instruction, prompts):
"""Called when the server requests keyboard interactive authentication
"""
responses = []
for prompt, _echo in prompts:
password = self.getPassword(prompt)
responses.append(password)
return defer.succeed(responses) | [
"def",
"getGenericAnswers",
"(",
"self",
",",
"name",
",",
"instruction",
",",
"prompts",
")",
":",
"responses",
"=",
"[",
"]",
"for",
"prompt",
",",
"_echo",
"in",
"prompts",
":",
"password",
"=",
"self",
".",
"getPassword",
"(",
"prompt",
")",
"respons... | Called when the server requests keyboard interactive authentication | [
"Called",
"when",
"the",
"server",
"requests",
"keyboard",
"interactive",
"authentication"
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/ssh/userauth.py#L20-L28 | train | 55,681 |
LeastAuthority/txkube | src/txkube/_authentication.py | pairwise | def pairwise(iterable):
"""
Generate consecutive pairs of elements from the given iterable.
"""
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return
for element in iterator:
yield first, element
first = element | python | def pairwise(iterable):
"""
Generate consecutive pairs of elements from the given iterable.
"""
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return
for element in iterator:
yield first, element
first = element | [
"def",
"pairwise",
"(",
"iterable",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"try",
":",
"first",
"=",
"next",
"(",
"iterator",
")",
"except",
"StopIteration",
":",
"return",
"for",
"element",
"in",
"iterator",
":",
"yield",
"first",
",",... | Generate consecutive pairs of elements from the given iterable. | [
"Generate",
"consecutive",
"pairs",
"of",
"elements",
"from",
"the",
"given",
"iterable",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_authentication.py#L66-L77 | train | 55,682 |
LeastAuthority/txkube | src/txkube/_authentication.py | https_policy_from_config | def https_policy_from_config(config):
"""
Create an ``IPolicyForHTTPS`` which can authenticate a Kubernetes API
server.
:param KubeConfig config: A Kubernetes configuration containing an active
context identifying a cluster. The resulting ``IPolicyForHTTPS`` will
authenticate the API server for that cluster.
:return IPolicyForHTTPS: A TLS context which requires server certificates
signed by the certificate authority certificate associated with the
active context's cluster.
"""
server = config.cluster["server"]
base_url = URL.fromText(native_string_to_unicode(server))
ca_certs = pem.parse(config.cluster["certificate-authority"].bytes())
if not ca_certs:
raise ValueError("No certificate authority certificate found.")
ca_cert = ca_certs[0]
try:
# Validate the certificate so we have early failures for garbage data.
ssl.Certificate.load(ca_cert.as_bytes(), FILETYPE_PEM)
except OpenSSLError as e:
raise ValueError(
"Invalid certificate authority certificate found.",
str(e),
)
netloc = NetLocation(host=base_url.host, port=base_url.port)
policy = ClientCertificatePolicyForHTTPS(
credentials={},
trust_roots={
netloc: ca_cert,
},
)
return policy | python | def https_policy_from_config(config):
"""
Create an ``IPolicyForHTTPS`` which can authenticate a Kubernetes API
server.
:param KubeConfig config: A Kubernetes configuration containing an active
context identifying a cluster. The resulting ``IPolicyForHTTPS`` will
authenticate the API server for that cluster.
:return IPolicyForHTTPS: A TLS context which requires server certificates
signed by the certificate authority certificate associated with the
active context's cluster.
"""
server = config.cluster["server"]
base_url = URL.fromText(native_string_to_unicode(server))
ca_certs = pem.parse(config.cluster["certificate-authority"].bytes())
if not ca_certs:
raise ValueError("No certificate authority certificate found.")
ca_cert = ca_certs[0]
try:
# Validate the certificate so we have early failures for garbage data.
ssl.Certificate.load(ca_cert.as_bytes(), FILETYPE_PEM)
except OpenSSLError as e:
raise ValueError(
"Invalid certificate authority certificate found.",
str(e),
)
netloc = NetLocation(host=base_url.host, port=base_url.port)
policy = ClientCertificatePolicyForHTTPS(
credentials={},
trust_roots={
netloc: ca_cert,
},
)
return policy | [
"def",
"https_policy_from_config",
"(",
"config",
")",
":",
"server",
"=",
"config",
".",
"cluster",
"[",
"\"server\"",
"]",
"base_url",
"=",
"URL",
".",
"fromText",
"(",
"native_string_to_unicode",
"(",
"server",
")",
")",
"ca_certs",
"=",
"pem",
".",
"pars... | Create an ``IPolicyForHTTPS`` which can authenticate a Kubernetes API
server.
:param KubeConfig config: A Kubernetes configuration containing an active
context identifying a cluster. The resulting ``IPolicyForHTTPS`` will
authenticate the API server for that cluster.
:return IPolicyForHTTPS: A TLS context which requires server certificates
signed by the certificate authority certificate associated with the
active context's cluster. | [
"Create",
"an",
"IPolicyForHTTPS",
"which",
"can",
"authenticate",
"a",
"Kubernetes",
"API",
"server",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_authentication.py#L235-L272 | train | 55,683 |
LeastAuthority/txkube | src/txkube/_authentication.py | authenticate_with_certificate_chain | def authenticate_with_certificate_chain(reactor, base_url, client_chain, client_key, ca_cert):
"""
Create an ``IAgent`` which can issue authenticated requests to a
particular Kubernetes server using a client certificate.
:param reactor: The reactor with which to configure the resulting agent.
:param twisted.python.url.URL base_url: The base location of the
Kubernetes API.
:param list[pem.Certificate] client_chain: The client certificate (and
chain, if applicable) to use.
:param pem.Key client_key: The private key to use with the client
certificate.
:param pem.Certificate ca_cert: The certificate authority to respect when
verifying the Kubernetes server certificate.
:return IAgent: An agent which will authenticate itself to a particular
Kubernetes server and which will verify that server or refuse to
interact with it.
"""
if base_url.scheme != u"https":
raise ValueError(
"authenticate_with_certificate() makes sense for HTTPS, not {!r}".format(
base_url.scheme
),
)
netloc = NetLocation(host=base_url.host, port=base_url.port)
policy = ClientCertificatePolicyForHTTPS(
credentials={
netloc: TLSCredentials(
chain=Chain(certificates=Certificates(client_chain)),
key=client_key,
),
},
trust_roots={
netloc: ca_cert,
},
)
return Agent(reactor, contextFactory=policy) | python | def authenticate_with_certificate_chain(reactor, base_url, client_chain, client_key, ca_cert):
"""
Create an ``IAgent`` which can issue authenticated requests to a
particular Kubernetes server using a client certificate.
:param reactor: The reactor with which to configure the resulting agent.
:param twisted.python.url.URL base_url: The base location of the
Kubernetes API.
:param list[pem.Certificate] client_chain: The client certificate (and
chain, if applicable) to use.
:param pem.Key client_key: The private key to use with the client
certificate.
:param pem.Certificate ca_cert: The certificate authority to respect when
verifying the Kubernetes server certificate.
:return IAgent: An agent which will authenticate itself to a particular
Kubernetes server and which will verify that server or refuse to
interact with it.
"""
if base_url.scheme != u"https":
raise ValueError(
"authenticate_with_certificate() makes sense for HTTPS, not {!r}".format(
base_url.scheme
),
)
netloc = NetLocation(host=base_url.host, port=base_url.port)
policy = ClientCertificatePolicyForHTTPS(
credentials={
netloc: TLSCredentials(
chain=Chain(certificates=Certificates(client_chain)),
key=client_key,
),
},
trust_roots={
netloc: ca_cert,
},
)
return Agent(reactor, contextFactory=policy) | [
"def",
"authenticate_with_certificate_chain",
"(",
"reactor",
",",
"base_url",
",",
"client_chain",
",",
"client_key",
",",
"ca_cert",
")",
":",
"if",
"base_url",
".",
"scheme",
"!=",
"u\"https\"",
":",
"raise",
"ValueError",
"(",
"\"authenticate_with_certificate() ma... | Create an ``IAgent`` which can issue authenticated requests to a
particular Kubernetes server using a client certificate.
:param reactor: The reactor with which to configure the resulting agent.
:param twisted.python.url.URL base_url: The base location of the
Kubernetes API.
:param list[pem.Certificate] client_chain: The client certificate (and
chain, if applicable) to use.
:param pem.Key client_key: The private key to use with the client
certificate.
:param pem.Certificate ca_cert: The certificate authority to respect when
verifying the Kubernetes server certificate.
:return IAgent: An agent which will authenticate itself to a particular
Kubernetes server and which will verify that server or refuse to
interact with it. | [
"Create",
"an",
"IAgent",
"which",
"can",
"issue",
"authenticated",
"requests",
"to",
"a",
"particular",
"Kubernetes",
"server",
"using",
"a",
"client",
"certificate",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_authentication.py#L276-L318 | train | 55,684 |
LeastAuthority/txkube | src/txkube/_authentication.py | authenticate_with_certificate | def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):
"""
See ``authenticate_with_certificate_chain``.
:param pem.Certificate client_cert: The client certificate to use.
"""
return authenticate_with_certificate_chain(
reactor, base_url, [client_cert], client_key, ca_cert,
) | python | def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):
"""
See ``authenticate_with_certificate_chain``.
:param pem.Certificate client_cert: The client certificate to use.
"""
return authenticate_with_certificate_chain(
reactor, base_url, [client_cert], client_key, ca_cert,
) | [
"def",
"authenticate_with_certificate",
"(",
"reactor",
",",
"base_url",
",",
"client_cert",
",",
"client_key",
",",
"ca_cert",
")",
":",
"return",
"authenticate_with_certificate_chain",
"(",
"reactor",
",",
"base_url",
",",
"[",
"client_cert",
"]",
",",
"client_key... | See ``authenticate_with_certificate_chain``.
:param pem.Certificate client_cert: The client certificate to use. | [
"See",
"authenticate_with_certificate_chain",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_authentication.py#L322-L330 | train | 55,685 |
LeastAuthority/txkube | src/txkube/_authentication.py | authenticate_with_serviceaccount | def authenticate_with_serviceaccount(reactor, **kw):
"""
Create an ``IAgent`` which can issue authenticated requests to a
particular Kubernetes server using a service account token.
:param reactor: The reactor with which to configure the resulting agent.
:param bytes path: The location of the service account directory. The
default should work fine for normal use within a container.
:return IAgent: An agent which will authenticate itself to a particular
Kubernetes server and which will verify that server or refuse to
interact with it.
"""
config = KubeConfig.from_service_account(**kw)
policy = https_policy_from_config(config)
token = config.user["token"]
agent = HeaderInjectingAgent(
_to_inject=Headers({u"authorization": [u"Bearer {}".format(token)]}),
_agent=Agent(reactor, contextFactory=policy),
)
return agent | python | def authenticate_with_serviceaccount(reactor, **kw):
"""
Create an ``IAgent`` which can issue authenticated requests to a
particular Kubernetes server using a service account token.
:param reactor: The reactor with which to configure the resulting agent.
:param bytes path: The location of the service account directory. The
default should work fine for normal use within a container.
:return IAgent: An agent which will authenticate itself to a particular
Kubernetes server and which will verify that server or refuse to
interact with it.
"""
config = KubeConfig.from_service_account(**kw)
policy = https_policy_from_config(config)
token = config.user["token"]
agent = HeaderInjectingAgent(
_to_inject=Headers({u"authorization": [u"Bearer {}".format(token)]}),
_agent=Agent(reactor, contextFactory=policy),
)
return agent | [
"def",
"authenticate_with_serviceaccount",
"(",
"reactor",
",",
"*",
"*",
"kw",
")",
":",
"config",
"=",
"KubeConfig",
".",
"from_service_account",
"(",
"*",
"*",
"kw",
")",
"policy",
"=",
"https_policy_from_config",
"(",
"config",
")",
"token",
"=",
"config",... | Create an ``IAgent`` which can issue authenticated requests to a
particular Kubernetes server using a service account token.
:param reactor: The reactor with which to configure the resulting agent.
:param bytes path: The location of the service account directory. The
default should work fine for normal use within a container.
:return IAgent: An agent which will authenticate itself to a particular
Kubernetes server and which will verify that server or refuse to
interact with it. | [
"Create",
"an",
"IAgent",
"which",
"can",
"issue",
"authenticated",
"requests",
"to",
"a",
"particular",
"Kubernetes",
"server",
"using",
"a",
"service",
"account",
"token",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_authentication.py#L361-L382 | train | 55,686 |
binbrain/OpenSesame | OpenSesame/keyring.py | OpenKeyring.first_time_setup | def first_time_setup(self):
"""First time running Open Sesame?
Create keyring and an auto-unlock key in default keyring. Make sure
these things don't already exist.
"""
if not self._auto_unlock_key_position():
pw = password.create_passwords()[0]
attrs = {'application': self.keyring}
gkr.item_create_sync(self.default_keyring
,gkr.ITEM_GENERIC_SECRET
,self.keyring
,attrs
,pw
,True)
found_pos = self._auto_unlock_key_position()
item_info = gkr.item_get_info_sync(self.default_keyring, found_pos)
gkr.create_sync(self.keyring, item_info.get_secret()) | python | def first_time_setup(self):
"""First time running Open Sesame?
Create keyring and an auto-unlock key in default keyring. Make sure
these things don't already exist.
"""
if not self._auto_unlock_key_position():
pw = password.create_passwords()[0]
attrs = {'application': self.keyring}
gkr.item_create_sync(self.default_keyring
,gkr.ITEM_GENERIC_SECRET
,self.keyring
,attrs
,pw
,True)
found_pos = self._auto_unlock_key_position()
item_info = gkr.item_get_info_sync(self.default_keyring, found_pos)
gkr.create_sync(self.keyring, item_info.get_secret()) | [
"def",
"first_time_setup",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_auto_unlock_key_position",
"(",
")",
":",
"pw",
"=",
"password",
".",
"create_passwords",
"(",
")",
"[",
"0",
"]",
"attrs",
"=",
"{",
"'application'",
":",
"self",
".",
"keyrin... | First time running Open Sesame?
Create keyring and an auto-unlock key in default keyring. Make sure
these things don't already exist. | [
"First",
"time",
"running",
"Open",
"Sesame?",
"Create",
"keyring",
"and",
"an",
"auto",
"-",
"unlock",
"key",
"in",
"default",
"keyring",
".",
"Make",
"sure",
"these",
"things",
"don",
"t",
"already",
"exist",
"."
] | e32c306385012646400ecb49fc65c64b14ce3a93 | https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/keyring.py#L31-L48 | train | 55,687 |
binbrain/OpenSesame | OpenSesame/keyring.py | OpenKeyring._auto_unlock_key_position | def _auto_unlock_key_position(self):
"""Find the open sesame password in the default keyring
"""
found_pos = None
default_keyring_ids = gkr.list_item_ids_sync(self.default_keyring)
for pos in default_keyring_ids:
item_attrs = gkr.item_get_attributes_sync(self.default_keyring, pos)
app = 'application'
if item_attrs.has_key(app) and item_attrs[app] == "opensesame":
found_pos = pos
break
return found_pos | python | def _auto_unlock_key_position(self):
"""Find the open sesame password in the default keyring
"""
found_pos = None
default_keyring_ids = gkr.list_item_ids_sync(self.default_keyring)
for pos in default_keyring_ids:
item_attrs = gkr.item_get_attributes_sync(self.default_keyring, pos)
app = 'application'
if item_attrs.has_key(app) and item_attrs[app] == "opensesame":
found_pos = pos
break
return found_pos | [
"def",
"_auto_unlock_key_position",
"(",
"self",
")",
":",
"found_pos",
"=",
"None",
"default_keyring_ids",
"=",
"gkr",
".",
"list_item_ids_sync",
"(",
"self",
".",
"default_keyring",
")",
"for",
"pos",
"in",
"default_keyring_ids",
":",
"item_attrs",
"=",
"gkr",
... | Find the open sesame password in the default keyring | [
"Find",
"the",
"open",
"sesame",
"password",
"in",
"the",
"default",
"keyring"
] | e32c306385012646400ecb49fc65c64b14ce3a93 | https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/keyring.py#L50-L61 | train | 55,688 |
binbrain/OpenSesame | OpenSesame/keyring.py | OpenKeyring.get_position_searchable | def get_position_searchable(self):
"""Return dict of the position and corrasponding searchable str
"""
ids = gkr.list_item_ids_sync(self.keyring)
position_searchable = {}
for i in ids:
item_attrs = gkr.item_get_attributes_sync(self.keyring, i)
position_searchable[i] = item_attrs['searchable']
return position_searchable | python | def get_position_searchable(self):
"""Return dict of the position and corrasponding searchable str
"""
ids = gkr.list_item_ids_sync(self.keyring)
position_searchable = {}
for i in ids:
item_attrs = gkr.item_get_attributes_sync(self.keyring, i)
position_searchable[i] = item_attrs['searchable']
return position_searchable | [
"def",
"get_position_searchable",
"(",
"self",
")",
":",
"ids",
"=",
"gkr",
".",
"list_item_ids_sync",
"(",
"self",
".",
"keyring",
")",
"position_searchable",
"=",
"{",
"}",
"for",
"i",
"in",
"ids",
":",
"item_attrs",
"=",
"gkr",
".",
"item_get_attributes_s... | Return dict of the position and corrasponding searchable str | [
"Return",
"dict",
"of",
"the",
"position",
"and",
"corrasponding",
"searchable",
"str"
] | e32c306385012646400ecb49fc65c64b14ce3a93 | https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/keyring.py#L69-L77 | train | 55,689 |
binbrain/OpenSesame | OpenSesame/keyring.py | OpenKeyring._match_exists | def _match_exists(self, searchable):
"""Make sure the searchable description doesn't already exist
"""
position_searchable = self.get_position_searchable()
for pos,val in position_searchable.iteritems():
if val == searchable:
return pos
return False | python | def _match_exists(self, searchable):
"""Make sure the searchable description doesn't already exist
"""
position_searchable = self.get_position_searchable()
for pos,val in position_searchable.iteritems():
if val == searchable:
return pos
return False | [
"def",
"_match_exists",
"(",
"self",
",",
"searchable",
")",
":",
"position_searchable",
"=",
"self",
".",
"get_position_searchable",
"(",
")",
"for",
"pos",
",",
"val",
"in",
"position_searchable",
".",
"iteritems",
"(",
")",
":",
"if",
"val",
"==",
"search... | Make sure the searchable description doesn't already exist | [
"Make",
"sure",
"the",
"searchable",
"description",
"doesn",
"t",
"already",
"exist"
] | e32c306385012646400ecb49fc65c64b14ce3a93 | https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/keyring.py#L79-L86 | train | 55,690 |
binbrain/OpenSesame | OpenSesame/keyring.py | OpenKeyring.save_password | def save_password(self, password, **attrs):
"""Save the new password, save the old password with the date prepended
"""
pos_of_match = self._match_exists(attrs['searchable'])
if pos_of_match:
old_password = self.get_password(pos_of_match).get_secret()
gkr.item_delete_sync(self.keyring, pos_of_match)
desc = str(int(time.time())) + "_" + attrs['searchable']
gkr.item_create_sync(self.keyring
,gkr.ITEM_GENERIC_SECRET
,desc
,{}
,old_password
,True)
desc = attrs['searchable']
pos = gkr.item_create_sync(self.keyring
,gkr.ITEM_GENERIC_SECRET
,desc
,attrs
,password
,True)
return pos | python | def save_password(self, password, **attrs):
"""Save the new password, save the old password with the date prepended
"""
pos_of_match = self._match_exists(attrs['searchable'])
if pos_of_match:
old_password = self.get_password(pos_of_match).get_secret()
gkr.item_delete_sync(self.keyring, pos_of_match)
desc = str(int(time.time())) + "_" + attrs['searchable']
gkr.item_create_sync(self.keyring
,gkr.ITEM_GENERIC_SECRET
,desc
,{}
,old_password
,True)
desc = attrs['searchable']
pos = gkr.item_create_sync(self.keyring
,gkr.ITEM_GENERIC_SECRET
,desc
,attrs
,password
,True)
return pos | [
"def",
"save_password",
"(",
"self",
",",
"password",
",",
"*",
"*",
"attrs",
")",
":",
"pos_of_match",
"=",
"self",
".",
"_match_exists",
"(",
"attrs",
"[",
"'searchable'",
"]",
")",
"if",
"pos_of_match",
":",
"old_password",
"=",
"self",
".",
"get_passwo... | Save the new password, save the old password with the date prepended | [
"Save",
"the",
"new",
"password",
"save",
"the",
"old",
"password",
"with",
"the",
"date",
"prepended"
] | e32c306385012646400ecb49fc65c64b14ce3a93 | https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/keyring.py#L88-L109 | train | 55,691 |
diamondman/proteusisc | proteusisc/jtagDeviceDescription.py | get_descriptor_for_idcode | def get_descriptor_for_idcode(idcode):
"""Use this method to find bsdl descriptions for devices.
The caching on this method drastically lower the execution
time when there are a lot of bsdl files and more than one
device. May move it into a metaclass to make it more
transparent."""
idcode = idcode&0x0fffffff
id_str = "XXXX"+bin(idcode)[2:].zfill(28)
descr_file_path = _check_cache_for_idcode(id_str)
if descr_file_path:
with open(descr_file_path, 'r') as f:
dat = json.load(f)
if dat.get("_file_version",-1) == JTAGDeviceDescription.version:
return JTAGDeviceDescription(dat.get('idcode'),
dat.get('name'),
dat.get('ir_length'),
dat.get('instruction_opcodes'),
dat.get('registers'),
dat.get('instruction_register_map'))
print(" Device detected ("+id_str+"). Fetching missing descriptor...")
sid = get_sid(id_str)
details = get_details(sid)
attribs = decode_bsdl(sid)
#VERIFYING PARSED DATA FROM 2 SOURCES. MESSY BUT USEFUL.
instruction_length = 0
if attribs.get('INSTRUCTION_LENGTH') ==\
details.get('INSTRUCTION_LENGTH'):
instruction_length = attribs.get('INSTRUCTION_LENGTH')
elif attribs.get('INSTRUCTION_LENGTH') and\
details.get('INSTRUCTION_LENGTH'):
raise Exception("INSTRUCTION_LENGTH can not be determined")
elif attribs.get('INSTRUCTION_LENGTH'):
instruction_length = attribs.get('INSTRUCTION_LENGTH')
else:
instruction_length = details.get('INSTRUCTION_LENGTH')
for instruction_name in details.get('instructions'):
if instruction_name not in\
attribs.get('INSTRUCTION_OPCODE',[]):
raise Exception("INSTRUCTION_OPCODE sources do not match")
#print(attribs['IDCODE_REGISTER'])
descr = JTAGDeviceDescription(attribs['IDCODE_REGISTER'].upper(),
details['name'], instruction_length,
attribs['INSTRUCTION_OPCODE'],
attribs['REGISTERS'],
attribs['INSTRUCTION_TO_REGISTER'])
#CACHE DESCR AS FILE!
if not os.path.isdir(base_descr_dir):
os.makedirs(base_descr_dir)
descr_file_path = os.path.join(base_descr_dir,
attribs['IDCODE_REGISTER']\
.upper()+'.json')
with open(descr_file_path, 'w') as f:
json.dump(descr._dump(), f)
return descr | python | def get_descriptor_for_idcode(idcode):
"""Use this method to find bsdl descriptions for devices.
The caching on this method drastically lower the execution
time when there are a lot of bsdl files and more than one
device. May move it into a metaclass to make it more
transparent."""
idcode = idcode&0x0fffffff
id_str = "XXXX"+bin(idcode)[2:].zfill(28)
descr_file_path = _check_cache_for_idcode(id_str)
if descr_file_path:
with open(descr_file_path, 'r') as f:
dat = json.load(f)
if dat.get("_file_version",-1) == JTAGDeviceDescription.version:
return JTAGDeviceDescription(dat.get('idcode'),
dat.get('name'),
dat.get('ir_length'),
dat.get('instruction_opcodes'),
dat.get('registers'),
dat.get('instruction_register_map'))
print(" Device detected ("+id_str+"). Fetching missing descriptor...")
sid = get_sid(id_str)
details = get_details(sid)
attribs = decode_bsdl(sid)
#VERIFYING PARSED DATA FROM 2 SOURCES. MESSY BUT USEFUL.
instruction_length = 0
if attribs.get('INSTRUCTION_LENGTH') ==\
details.get('INSTRUCTION_LENGTH'):
instruction_length = attribs.get('INSTRUCTION_LENGTH')
elif attribs.get('INSTRUCTION_LENGTH') and\
details.get('INSTRUCTION_LENGTH'):
raise Exception("INSTRUCTION_LENGTH can not be determined")
elif attribs.get('INSTRUCTION_LENGTH'):
instruction_length = attribs.get('INSTRUCTION_LENGTH')
else:
instruction_length = details.get('INSTRUCTION_LENGTH')
for instruction_name in details.get('instructions'):
if instruction_name not in\
attribs.get('INSTRUCTION_OPCODE',[]):
raise Exception("INSTRUCTION_OPCODE sources do not match")
#print(attribs['IDCODE_REGISTER'])
descr = JTAGDeviceDescription(attribs['IDCODE_REGISTER'].upper(),
details['name'], instruction_length,
attribs['INSTRUCTION_OPCODE'],
attribs['REGISTERS'],
attribs['INSTRUCTION_TO_REGISTER'])
#CACHE DESCR AS FILE!
if not os.path.isdir(base_descr_dir):
os.makedirs(base_descr_dir)
descr_file_path = os.path.join(base_descr_dir,
attribs['IDCODE_REGISTER']\
.upper()+'.json')
with open(descr_file_path, 'w') as f:
json.dump(descr._dump(), f)
return descr | [
"def",
"get_descriptor_for_idcode",
"(",
"idcode",
")",
":",
"idcode",
"=",
"idcode",
"&",
"0x0fffffff",
"id_str",
"=",
"\"XXXX\"",
"+",
"bin",
"(",
"idcode",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"28",
")",
"descr_file_path",
"=",
"_check_cache_for_... | Use this method to find bsdl descriptions for devices.
The caching on this method drastically lower the execution
time when there are a lot of bsdl files and more than one
device. May move it into a metaclass to make it more
transparent. | [
"Use",
"this",
"method",
"to",
"find",
"bsdl",
"descriptions",
"for",
"devices",
".",
"The",
"caching",
"on",
"this",
"method",
"drastically",
"lower",
"the",
"execution",
"time",
"when",
"there",
"are",
"a",
"lot",
"of",
"bsdl",
"files",
"and",
"more",
"t... | 7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c | https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/jtagDeviceDescription.py#L30-L90 | train | 55,692 |
jplusplus/statscraper | statscraper/scrapers/uka_scraper.py | UKA._fetch_dimensions | def _fetch_dimensions(self, dataset):
""" Iterate through semesters, counties and municipalities.
"""
yield Dimension(u"school")
yield Dimension(u"year",
datatype="year")
yield Dimension(u"semester",
datatype="academic_term",
dialect="swedish") # HT/VT
yield Dimension(u"municipality",
datatype="year",
domain="sweden/municipalities") | python | def _fetch_dimensions(self, dataset):
""" Iterate through semesters, counties and municipalities.
"""
yield Dimension(u"school")
yield Dimension(u"year",
datatype="year")
yield Dimension(u"semester",
datatype="academic_term",
dialect="swedish") # HT/VT
yield Dimension(u"municipality",
datatype="year",
domain="sweden/municipalities") | [
"def",
"_fetch_dimensions",
"(",
"self",
",",
"dataset",
")",
":",
"yield",
"Dimension",
"(",
"u\"school\"",
")",
"yield",
"Dimension",
"(",
"u\"year\"",
",",
"datatype",
"=",
"\"year\"",
")",
"yield",
"Dimension",
"(",
"u\"semester\"",
",",
"datatype",
"=",
... | Iterate through semesters, counties and municipalities. | [
"Iterate",
"through",
"semesters",
"counties",
"and",
"municipalities",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/uka_scraper.py#L24-L35 | train | 55,693 |
LeastAuthority/txkube | src/txkube/_network.py | _merge_configs | def _merge_configs(configs):
"""
Merge one or more ``KubeConfig`` objects.
:param list[KubeConfig] configs: The configurations to merge.
:return KubeConfig: A single configuration object with the merged
configuration.
"""
result = {
u"contexts": [],
u"users": [],
u"clusters": [],
u"current-context": None,
}
for config in configs:
for k in {u"contexts", u"users", u"clusters"}:
try:
values = config.doc[k]
except KeyError:
pass
else:
result[k].extend(values)
if result[u"current-context"] is None:
try:
result[u"current-context"] = config.doc[u"current-context"]
except KeyError:
pass
return KubeConfig(result) | python | def _merge_configs(configs):
"""
Merge one or more ``KubeConfig`` objects.
:param list[KubeConfig] configs: The configurations to merge.
:return KubeConfig: A single configuration object with the merged
configuration.
"""
result = {
u"contexts": [],
u"users": [],
u"clusters": [],
u"current-context": None,
}
for config in configs:
for k in {u"contexts", u"users", u"clusters"}:
try:
values = config.doc[k]
except KeyError:
pass
else:
result[k].extend(values)
if result[u"current-context"] is None:
try:
result[u"current-context"] = config.doc[u"current-context"]
except KeyError:
pass
return KubeConfig(result) | [
"def",
"_merge_configs",
"(",
"configs",
")",
":",
"result",
"=",
"{",
"u\"contexts\"",
":",
"[",
"]",
",",
"u\"users\"",
":",
"[",
"]",
",",
"u\"clusters\"",
":",
"[",
"]",
",",
"u\"current-context\"",
":",
"None",
",",
"}",
"for",
"config",
"in",
"co... | Merge one or more ``KubeConfig`` objects.
:param list[KubeConfig] configs: The configurations to merge.
:return KubeConfig: A single configuration object with the merged
configuration. | [
"Merge",
"one",
"or",
"more",
"KubeConfig",
"objects",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_network.py#L61-L91 | train | 55,694 |
LeastAuthority/txkube | src/txkube/_network.py | _merge_configs_from_env | def _merge_configs_from_env(kubeconfigs):
"""
Merge configuration files from a ``KUBECONFIG`` environment variable.
:param bytes kubeconfigs: A value like the one given to ``KUBECONFIG`` to
specify multiple configuration files.
:return KubeConfig: A configuration object which has merged all of the
configuration from the specified configuration files. Merging is
performed according to
https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files
"""
paths = list(
FilePath(p)
for p
in kubeconfigs.split(pathsep)
if p
)
config = _merge_configs(list(
KubeConfig.from_file(p.path)
for p
in paths
))
return config | python | def _merge_configs_from_env(kubeconfigs):
"""
Merge configuration files from a ``KUBECONFIG`` environment variable.
:param bytes kubeconfigs: A value like the one given to ``KUBECONFIG`` to
specify multiple configuration files.
:return KubeConfig: A configuration object which has merged all of the
configuration from the specified configuration files. Merging is
performed according to
https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files
"""
paths = list(
FilePath(p)
for p
in kubeconfigs.split(pathsep)
if p
)
config = _merge_configs(list(
KubeConfig.from_file(p.path)
for p
in paths
))
return config | [
"def",
"_merge_configs_from_env",
"(",
"kubeconfigs",
")",
":",
"paths",
"=",
"list",
"(",
"FilePath",
"(",
"p",
")",
"for",
"p",
"in",
"kubeconfigs",
".",
"split",
"(",
"pathsep",
")",
"if",
"p",
")",
"config",
"=",
"_merge_configs",
"(",
"list",
"(",
... | Merge configuration files from a ``KUBECONFIG`` environment variable.
:param bytes kubeconfigs: A value like the one given to ``KUBECONFIG`` to
specify multiple configuration files.
:return KubeConfig: A configuration object which has merged all of the
configuration from the specified configuration files. Merging is
performed according to
https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files | [
"Merge",
"configuration",
"files",
"from",
"a",
"KUBECONFIG",
"environment",
"variable",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_network.py#L94-L117 | train | 55,695 |
LeastAuthority/txkube | src/txkube/_network.py | network_kubernetes_from_context | def network_kubernetes_from_context(
reactor, context=None, path=None, environ=None,
default_config_path=FilePath(expanduser(u"~/.kube/config")),
):
"""
Create a new ``IKubernetes`` provider based on a kube config file.
:param reactor: A Twisted reactor which will be used for I/O and
scheduling.
:param unicode context: The name of the kube config context from which to
load configuration details. Or, ``None`` to respect the current
context setting from the configuration.
:param FilePath path: The location of the kube config file to use.
:param dict environ: A environment direction in which to look up
``KUBECONFIG``. If ``None``, the real process environment will be
inspected. This is used only if ``path`` is ``None``.
:return IKubernetes: The Kubernetes service described by the named
context.
"""
if path is None:
if environ is None:
from os import environ
try:
kubeconfigs = environ[u"KUBECONFIG"]
except KeyError:
config = KubeConfig.from_file(default_config_path.path)
else:
config = _merge_configs_from_env(kubeconfigs)
else:
config = KubeConfig.from_file(path.path)
if context is None:
context = config.doc[u"current-context"]
context = config.contexts[context]
cluster = config.clusters[context[u"cluster"]]
user = config.users[context[u"user"]]
if isinstance(cluster[u"server"], bytes):
base_url = URL.fromText(cluster[u"server"].decode("ascii"))
else:
base_url = URL.fromText(cluster[u"server"])
[ca_cert] = parse(cluster[u"certificate-authority"].bytes())
client_chain = parse(user[u"client-certificate"].bytes())
[client_key] = parse(user[u"client-key"].bytes())
agent = authenticate_with_certificate_chain(
reactor, base_url, client_chain, client_key, ca_cert,
)
return network_kubernetes(
base_url=base_url,
agent=agent,
) | python | def network_kubernetes_from_context(
reactor, context=None, path=None, environ=None,
default_config_path=FilePath(expanduser(u"~/.kube/config")),
):
"""
Create a new ``IKubernetes`` provider based on a kube config file.
:param reactor: A Twisted reactor which will be used for I/O and
scheduling.
:param unicode context: The name of the kube config context from which to
load configuration details. Or, ``None`` to respect the current
context setting from the configuration.
:param FilePath path: The location of the kube config file to use.
:param dict environ: A environment direction in which to look up
``KUBECONFIG``. If ``None``, the real process environment will be
inspected. This is used only if ``path`` is ``None``.
:return IKubernetes: The Kubernetes service described by the named
context.
"""
if path is None:
if environ is None:
from os import environ
try:
kubeconfigs = environ[u"KUBECONFIG"]
except KeyError:
config = KubeConfig.from_file(default_config_path.path)
else:
config = _merge_configs_from_env(kubeconfigs)
else:
config = KubeConfig.from_file(path.path)
if context is None:
context = config.doc[u"current-context"]
context = config.contexts[context]
cluster = config.clusters[context[u"cluster"]]
user = config.users[context[u"user"]]
if isinstance(cluster[u"server"], bytes):
base_url = URL.fromText(cluster[u"server"].decode("ascii"))
else:
base_url = URL.fromText(cluster[u"server"])
[ca_cert] = parse(cluster[u"certificate-authority"].bytes())
client_chain = parse(user[u"client-certificate"].bytes())
[client_key] = parse(user[u"client-key"].bytes())
agent = authenticate_with_certificate_chain(
reactor, base_url, client_chain, client_key, ca_cert,
)
return network_kubernetes(
base_url=base_url,
agent=agent,
) | [
"def",
"network_kubernetes_from_context",
"(",
"reactor",
",",
"context",
"=",
"None",
",",
"path",
"=",
"None",
",",
"environ",
"=",
"None",
",",
"default_config_path",
"=",
"FilePath",
"(",
"expanduser",
"(",
"u\"~/.kube/config\"",
")",
")",
",",
")",
":",
... | Create a new ``IKubernetes`` provider based on a kube config file.
:param reactor: A Twisted reactor which will be used for I/O and
scheduling.
:param unicode context: The name of the kube config context from which to
load configuration details. Or, ``None`` to respect the current
context setting from the configuration.
:param FilePath path: The location of the kube config file to use.
:param dict environ: A environment direction in which to look up
``KUBECONFIG``. If ``None``, the real process environment will be
inspected. This is used only if ``path`` is ``None``.
:return IKubernetes: The Kubernetes service described by the named
context. | [
"Create",
"a",
"new",
"IKubernetes",
"provider",
"based",
"on",
"a",
"kube",
"config",
"file",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_network.py#L120-L178 | train | 55,696 |
LeastAuthority/txkube | src/txkube/_network.py | collection_location | def collection_location(obj):
"""
Get the URL for the collection of objects like ``obj``.
:param obj: Either a type representing a Kubernetes object kind or an
instance of such a type.
:return tuple[unicode]: Some path segments to stick on to a base URL to
construct the location of the collection of objects like the one
given.
"""
# TODO kind is not part of IObjectLoader and we should really be loading
# apiVersion off of this object too.
kind = obj.kind
apiVersion = obj.apiVersion
prefix = version_to_segments[apiVersion]
collection = kind.lower() + u"s"
if IObject.providedBy(obj):
# Actual objects *could* have a namespace...
namespace = obj.metadata.namespace
else:
# Types representing a kind couldn't possible.
namespace = None
if namespace is None:
# If there's no namespace, look in the un-namespaced area.
return prefix + (collection,)
# If there is, great, look there.
return prefix + (u"namespaces", namespace, collection) | python | def collection_location(obj):
"""
Get the URL for the collection of objects like ``obj``.
:param obj: Either a type representing a Kubernetes object kind or an
instance of such a type.
:return tuple[unicode]: Some path segments to stick on to a base URL to
construct the location of the collection of objects like the one
given.
"""
# TODO kind is not part of IObjectLoader and we should really be loading
# apiVersion off of this object too.
kind = obj.kind
apiVersion = obj.apiVersion
prefix = version_to_segments[apiVersion]
collection = kind.lower() + u"s"
if IObject.providedBy(obj):
# Actual objects *could* have a namespace...
namespace = obj.metadata.namespace
else:
# Types representing a kind couldn't possible.
namespace = None
if namespace is None:
# If there's no namespace, look in the un-namespaced area.
return prefix + (collection,)
# If there is, great, look there.
return prefix + (u"namespaces", namespace, collection) | [
"def",
"collection_location",
"(",
"obj",
")",
":",
"# TODO kind is not part of IObjectLoader and we should really be loading",
"# apiVersion off of this object too.",
"kind",
"=",
"obj",
".",
"kind",
"apiVersion",
"=",
"obj",
".",
"apiVersion",
"prefix",
"=",
"version_to_seg... | Get the URL for the collection of objects like ``obj``.
:param obj: Either a type representing a Kubernetes object kind or an
instance of such a type.
:return tuple[unicode]: Some path segments to stick on to a base URL to
construct the location of the collection of objects like the one
given. | [
"Get",
"the",
"URL",
"for",
"the",
"collection",
"of",
"objects",
"like",
"obj",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_network.py#L424-L456 | train | 55,697 |
botstory/botstory | botstory/ast/story_context/reducers.py | execute | async def execute(ctx):
"""
execute story part at the current context
and make one step further
:param ctx:
:return:
"""
tail_depth = len(ctx.stack()) - 1
story_part = ctx.get_current_story_part()
logger.debug('# going to call: {}'.format(story_part.__name__))
waiting_for = story_part(ctx.message)
if inspect.iscoroutinefunction(story_part):
waiting_for = await waiting_for
logger.debug('# got result {}'.format(waiting_for))
# story part could run callable story and return its context
if isinstance(waiting_for, story_context.StoryContext):
# for such cases is very important to know `tail_depth`
# because story context from callable story already has
# few stack items above our tail
ctx = waiting_for.clone()
ctx.waiting_for = callable.WaitForReturn()
else:
ctx = ctx.clone()
ctx.waiting_for = waiting_for
tail_data = ctx.message['session']['stack'][tail_depth]['data']
tail_step = ctx.message['session']['stack'][tail_depth]['step']
if ctx.is_waiting_for_input():
if isinstance(ctx.waiting_for, callable.EndOfStory):
if isinstance(ctx.waiting_for.data, dict):
new_data = {**ctx.get_user_data(), **ctx.waiting_for.data}
else:
new_data = ctx.waiting_for.data
ctx.message = {
**ctx.message,
'session': {
**ctx.message['session'],
'data': new_data,
},
}
tail_step += 1
elif isinstance(ctx.waiting_for, loop.ScopeMatcher):
# jumping in a loop
tail_data = matchers.serialize(ctx.waiting_for)
elif isinstance(ctx.waiting_for, loop.BreakLoop):
tail_step += 1
else:
tail_data = matchers.serialize(
matchers.get_validator(ctx.waiting_for)
)
tail_step += 1
ctx.message = modify_stack_in_message(ctx.message,
lambda stack: stack[:tail_depth] +
[{
'data': tail_data,
'step': tail_step,
'topic': stack[tail_depth]['topic'],
}] +
stack[tail_depth + 1:])
logger.debug('# mutated ctx after execute')
logger.debug(ctx)
return ctx | python | async def execute(ctx):
"""
execute story part at the current context
and make one step further
:param ctx:
:return:
"""
tail_depth = len(ctx.stack()) - 1
story_part = ctx.get_current_story_part()
logger.debug('# going to call: {}'.format(story_part.__name__))
waiting_for = story_part(ctx.message)
if inspect.iscoroutinefunction(story_part):
waiting_for = await waiting_for
logger.debug('# got result {}'.format(waiting_for))
# story part could run callable story and return its context
if isinstance(waiting_for, story_context.StoryContext):
# for such cases is very important to know `tail_depth`
# because story context from callable story already has
# few stack items above our tail
ctx = waiting_for.clone()
ctx.waiting_for = callable.WaitForReturn()
else:
ctx = ctx.clone()
ctx.waiting_for = waiting_for
tail_data = ctx.message['session']['stack'][tail_depth]['data']
tail_step = ctx.message['session']['stack'][tail_depth]['step']
if ctx.is_waiting_for_input():
if isinstance(ctx.waiting_for, callable.EndOfStory):
if isinstance(ctx.waiting_for.data, dict):
new_data = {**ctx.get_user_data(), **ctx.waiting_for.data}
else:
new_data = ctx.waiting_for.data
ctx.message = {
**ctx.message,
'session': {
**ctx.message['session'],
'data': new_data,
},
}
tail_step += 1
elif isinstance(ctx.waiting_for, loop.ScopeMatcher):
# jumping in a loop
tail_data = matchers.serialize(ctx.waiting_for)
elif isinstance(ctx.waiting_for, loop.BreakLoop):
tail_step += 1
else:
tail_data = matchers.serialize(
matchers.get_validator(ctx.waiting_for)
)
tail_step += 1
ctx.message = modify_stack_in_message(ctx.message,
lambda stack: stack[:tail_depth] +
[{
'data': tail_data,
'step': tail_step,
'topic': stack[tail_depth]['topic'],
}] +
stack[tail_depth + 1:])
logger.debug('# mutated ctx after execute')
logger.debug(ctx)
return ctx | [
"async",
"def",
"execute",
"(",
"ctx",
")",
":",
"tail_depth",
"=",
"len",
"(",
"ctx",
".",
"stack",
"(",
")",
")",
"-",
"1",
"story_part",
"=",
"ctx",
".",
"get_current_story_part",
"(",
")",
"logger",
".",
"debug",
"(",
"'# going to call: {}'",
".",
... | execute story part at the current context
and make one step further
:param ctx:
:return: | [
"execute",
"story",
"part",
"at",
"the",
"current",
"context",
"and",
"make",
"one",
"step",
"further"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/ast/story_context/reducers.py#L20-L85 | train | 55,698 |
botstory/botstory | botstory/ast/story_context/reducers.py | iterate_storyline | def iterate_storyline(ctx):
"""
iterate the last storyline from the last visited story part
:param ctx:
:return:
"""
logger.debug('# start iterate')
compiled_story = ctx.compiled_story()
if not compiled_story:
return
for step in range(ctx.current_step(),
len(compiled_story.story_line)):
ctx = ctx.clone()
tail = ctx.stack_tail()
ctx.message = modify_stack_in_message(ctx.message,
lambda stack: stack[:-1] + [{
'data': tail['data'],
'step': step,
'topic': tail['topic'],
}])
logger.debug('# [{}] iterate'.format(step))
logger.debug(ctx)
ctx = yield ctx | python | def iterate_storyline(ctx):
"""
iterate the last storyline from the last visited story part
:param ctx:
:return:
"""
logger.debug('# start iterate')
compiled_story = ctx.compiled_story()
if not compiled_story:
return
for step in range(ctx.current_step(),
len(compiled_story.story_line)):
ctx = ctx.clone()
tail = ctx.stack_tail()
ctx.message = modify_stack_in_message(ctx.message,
lambda stack: stack[:-1] + [{
'data': tail['data'],
'step': step,
'topic': tail['topic'],
}])
logger.debug('# [{}] iterate'.format(step))
logger.debug(ctx)
ctx = yield ctx | [
"def",
"iterate_storyline",
"(",
"ctx",
")",
":",
"logger",
".",
"debug",
"(",
"'# start iterate'",
")",
"compiled_story",
"=",
"ctx",
".",
"compiled_story",
"(",
")",
"if",
"not",
"compiled_story",
":",
"return",
"for",
"step",
"in",
"range",
"(",
"ctx",
... | iterate the last storyline from the last visited story part
:param ctx:
:return: | [
"iterate",
"the",
"last",
"storyline",
"from",
"the",
"last",
"visited",
"story",
"part"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/ast/story_context/reducers.py#L88-L114 | train | 55,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.