repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | UcsUtils.DownloadFile | def DownloadFile(hUcs, source, destination):
"""
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to
download the files from the Ucs.
"""
import urllib2
from sys import stdout
from time import sleep
httpAddress = "%s/%s" % (hUcs.Uri(),... | python | def DownloadFile(hUcs, source, destination):
"""
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to
download the files from the Ucs.
"""
import urllib2
from sys import stdout
from time import sleep
httpAddress = "%s/%s" % (hUcs.Uri(),... | [
"def",
"DownloadFile",
"(",
"hUcs",
",",
"source",
",",
"destination",
")",
":",
"import",
"urllib2",
"from",
"sys",
"import",
"stdout",
"from",
"time",
"import",
"sleep",
"httpAddress",
"=",
"\"%s/%s\"",
"%",
"(",
"hUcs",
".",
"Uri",
"(",
")",
",",
"sou... | Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to
download the files from the Ucs. | [
"Method",
"provides",
"the",
"functionality",
"to",
"download",
"file",
"from",
"the",
"UCS",
".",
"This",
"method",
"is",
"used",
"in",
"BackupUcs",
"and",
"GetTechSupport",
"to",
"download",
"the",
"files",
"from",
"the",
"Ucs",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L721-L757 | train | This method downloads a file from the UCS and writes it to the destination. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | UcsUtils.GetSyncMoConfigFilePath | def GetSyncMoConfigFilePath():
""" Method returs the path of SyncMoConfig.xml file. """
return os.path.join(os.path.join(os.path.dirname(__file__), "resources"), "SyncMoConfig.xml") | python | def GetSyncMoConfigFilePath():
""" Method returs the path of SyncMoConfig.xml file. """
return os.path.join(os.path.join(os.path.dirname(__file__), "resources"), "SyncMoConfig.xml") | [
"def",
"GetSyncMoConfigFilePath",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"resources\"",
")",
",",
"\"SyncMoConfig.xml\"",
")"
] | Method returs the path of SyncMoConfig.xml file. | [
"Method",
"returs",
"the",
"path",
"of",
"SyncMoConfig",
".",
"xml",
"file",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L760-L762 | train | Method returns the path of SyncMoConfig. xml file. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | UcsUtils.GetSyncMoConfig | def GetSyncMoConfig(ConfigDoc):
""" Internal support method for SyncManagedObject. """
moConfigMap = {}
configList = ConfigDoc.getElementsByTagName("mo")
for moConfigNode in configList:
classId = None
noun = None
version = None
actionVersion = None
action = None
ignoreReason = None
status ... | python | def GetSyncMoConfig(ConfigDoc):
""" Internal support method for SyncManagedObject. """
moConfigMap = {}
configList = ConfigDoc.getElementsByTagName("mo")
for moConfigNode in configList:
classId = None
noun = None
version = None
actionVersion = None
action = None
ignoreReason = None
status ... | [
"def",
"GetSyncMoConfig",
"(",
"ConfigDoc",
")",
":",
"moConfigMap",
"=",
"{",
"}",
"configList",
"=",
"ConfigDoc",
".",
"getElementsByTagName",
"(",
"\"mo\"",
")",
"for",
"moConfigNode",
"in",
"configList",
":",
"classId",
"=",
"None",
"noun",
"=",
"None",
... | Internal support method for SyncManagedObject. | [
"Internal",
"support",
"method",
"for",
"SyncManagedObject",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L765-L819 | train | Internal support method for SyncManagedObject. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | UcsUtils.Expandkey | def Expandkey(key, clen):
""" Internal method supporting encryption and decryption functionality. """
import sha
from string import join
from array import array
blocks = (clen + 19) / 20
xkey = []
seed = key
for i in xrange(blocks):
seed = sha.new(key + seed).digest()
xkey.append(seed)
j = join... | python | def Expandkey(key, clen):
""" Internal method supporting encryption and decryption functionality. """
import sha
from string import join
from array import array
blocks = (clen + 19) / 20
xkey = []
seed = key
for i in xrange(blocks):
seed = sha.new(key + seed).digest()
xkey.append(seed)
j = join... | [
"def",
"Expandkey",
"(",
"key",
",",
"clen",
")",
":",
"import",
"sha",
"from",
"string",
"import",
"join",
"from",
"array",
"import",
"array",
"blocks",
"=",
"(",
"clen",
"+",
"19",
")",
"/",
"20",
"xkey",
"=",
"[",
"]",
"seed",
"=",
"key",
"for",... | Internal method supporting encryption and decryption functionality. | [
"Internal",
"method",
"supporting",
"encryption",
"and",
"decryption",
"functionality",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L829-L842 | train | Internal method supporting encryption and decryption functionality. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | UcsUtils.EncryptPassword | def EncryptPassword(password, key):
""" Encrypts the password using the given key. """
from time import time
from array import array
import hmac
import sha
import os
import base64
H = UcsUtils.GetShaHash
uhash = H(','.join(str(x) for x in [`time()`, `os.getpid()`, `len(password)`, password, key]))[:... | python | def EncryptPassword(password, key):
""" Encrypts the password using the given key. """
from time import time
from array import array
import hmac
import sha
import os
import base64
H = UcsUtils.GetShaHash
uhash = H(','.join(str(x) for x in [`time()`, `os.getpid()`, `len(password)`, password, key]))[:... | [
"def",
"EncryptPassword",
"(",
"password",
",",
"key",
")",
":",
"from",
"time",
"import",
"time",
"from",
"array",
"import",
"array",
"import",
"hmac",
"import",
"sha",
"import",
"os",
"import",
"base64",
"H",
"=",
"UcsUtils",
".",
"GetShaHash",
"uhash",
... | Encrypts the password using the given key. | [
"Encrypts",
"the",
"password",
"using",
"the",
"given",
"key",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L845-L872 | train | Encrypts the given password using the given key. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | UcsUtils.DecryptPassword | def DecryptPassword(cipher, key):
""" Decrypts the password using the given key with which the password was encrypted first. """
import base64
import hmac
import sha
from array import array
H = UcsUtils.GetShaHash
cipher = cipher + "\n"
cipher = base64.decodestring(cipher)
n = len(cipher) - 16 - 8
... | python | def DecryptPassword(cipher, key):
""" Decrypts the password using the given key with which the password was encrypted first. """
import base64
import hmac
import sha
from array import array
H = UcsUtils.GetShaHash
cipher = cipher + "\n"
cipher = base64.decodestring(cipher)
n = len(cipher) - 16 - 8
... | [
"def",
"DecryptPassword",
"(",
"cipher",
",",
"key",
")",
":",
"import",
"base64",
"import",
"hmac",
"import",
"sha",
"from",
"array",
"import",
"array",
"H",
"=",
"UcsUtils",
".",
"GetShaHash",
"cipher",
"=",
"cipher",
"+",
"\"\\n\"",
"cipher",
"=",
"base... | Decrypts the password using the given key with which the password was encrypted first. | [
"Decrypts",
"the",
"password",
"using",
"the",
"given",
"key",
"with",
"which",
"the",
"password",
"was",
"encrypted",
"first",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L875-L902 | train | Decrypts the password using the given key with which the password was encrypted first. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | _GenericMO.LoadFromXml | def LoadFromXml(self, node):
""" Method updates the object from the xml. """
import os
self.classId = node.localName
metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId)
if metaClassId:
self.classId = metaClassId
if node.hasAttribute(NamingPropertyId.DN):
self.dn = node.getAttribute(N... | python | def LoadFromXml(self, node):
""" Method updates the object from the xml. """
import os
self.classId = node.localName
metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId)
if metaClassId:
self.classId = metaClassId
if node.hasAttribute(NamingPropertyId.DN):
self.dn = node.getAttribute(N... | [
"def",
"LoadFromXml",
"(",
"self",
",",
"node",
")",
":",
"import",
"os",
"self",
".",
"classId",
"=",
"node",
".",
"localName",
"metaClassId",
"=",
"UcsUtils",
".",
"FindClassIdInMoMetaIgnoreCase",
"(",
"self",
".",
"classId",
")",
"if",
"metaClassId",
":",... | Method updates the object from the xml. | [
"Method",
"updates",
"the",
"object",
"from",
"the",
"xml",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1061-L1092 | train | Loads the object from the xml. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | _GenericMO.WriteXml | def WriteXml(self, w, option, elementName=None):
""" Method writes the xml representation of the generic managed object. """
if elementName == None:
x = w.createElement(self.classId)
else:
x = w.createElement(elementName)
for prop in self.__dict__['properties']:
x.setAttribute(UcsUtils.WordL(prop), se... | python | def WriteXml(self, w, option, elementName=None):
""" Method writes the xml representation of the generic managed object. """
if elementName == None:
x = w.createElement(self.classId)
else:
x = w.createElement(elementName)
for prop in self.__dict__['properties']:
x.setAttribute(UcsUtils.WordL(prop), se... | [
"def",
"WriteXml",
"(",
"self",
",",
"w",
",",
"option",
",",
"elementName",
"=",
"None",
")",
":",
"if",
"elementName",
"==",
"None",
":",
"x",
"=",
"w",
".",
"createElement",
"(",
"self",
".",
"classId",
")",
"else",
":",
"x",
"=",
"w",
".",
"c... | Method writes the xml representation of the generic managed object. | [
"Method",
"writes",
"the",
"xml",
"representation",
"of",
"the",
"generic",
"managed",
"object",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1094-L1107 | train | Method writes the xml representation of the generic object. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | _GenericMO.ToManagedObject | def ToManagedObject(self):
"""
Method creates and returns an object of ManagedObject class using the classId and information from the
Generic managed object.
"""
from Ucs import ClassFactory
cln = UcsUtils.WordU(self.classId)
mo = ClassFactory(cln)
if mo and (isinstance(mo, ManagedObject) == True):
... | python | def ToManagedObject(self):
"""
Method creates and returns an object of ManagedObject class using the classId and information from the
Generic managed object.
"""
from Ucs import ClassFactory
cln = UcsUtils.WordU(self.classId)
mo = ClassFactory(cln)
if mo and (isinstance(mo, ManagedObject) == True):
... | [
"def",
"ToManagedObject",
"(",
"self",
")",
":",
"from",
"Ucs",
"import",
"ClassFactory",
"cln",
"=",
"UcsUtils",
".",
"WordU",
"(",
"self",
".",
"classId",
")",
"mo",
"=",
"ClassFactory",
"(",
"cln",
")",
"if",
"mo",
"and",
"(",
"isinstance",
"(",
"mo... | Method creates and returns an object of ManagedObject class using the classId and information from the
Generic managed object. | [
"Method",
"creates",
"and",
"returns",
"an",
"object",
"of",
"ManagedObject",
"class",
"using",
"the",
"classId",
"and",
"information",
"from",
"the",
"Generic",
"managed",
"object",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1109-L1133 | train | Method creates and returns an object of ManagedObject class using the classId and properties from the
Generic managed object. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | _GenericMO.FromManagedObject | def FromManagedObject(self):
"""
Method creates and returns an object of _GenericMO class using the classId and other information from the
managed object.
"""
import os
if (isinstance(self.mo, ManagedObject) == True):
self.classId = self.mo.classId
if self.mo.getattr('Dn'):
self.dn = self.mo.get... | python | def FromManagedObject(self):
"""
Method creates and returns an object of _GenericMO class using the classId and other information from the
managed object.
"""
import os
if (isinstance(self.mo, ManagedObject) == True):
self.classId = self.mo.classId
if self.mo.getattr('Dn'):
self.dn = self.mo.get... | [
"def",
"FromManagedObject",
"(",
"self",
")",
":",
"import",
"os",
"if",
"(",
"isinstance",
"(",
"self",
".",
"mo",
",",
"ManagedObject",
")",
"==",
"True",
")",
":",
"self",
".",
"classId",
"=",
"self",
".",
"mo",
".",
"classId",
"if",
"self",
".",
... | Method creates and returns an object of _GenericMO class using the classId and other information from the
managed object. | [
"Method",
"creates",
"and",
"returns",
"an",
"object",
"of",
"_GenericMO",
"class",
"using",
"the",
"classId",
"and",
"other",
"information",
"from",
"the",
"managed",
"object",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1135-L1162 | train | Method creates and returns an object of _GenericMO class using the classId and other information from the ManagedObject object. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | _GenericMO.GetChildClassId | def GetChildClassId(self, classId):
"""
Method extracts and returns the child object list same as the given classId
"""
childList = []
for ch in self.child:
if ch.classId.lower() == classId.lower():
childList.append(ch)
return childList | python | def GetChildClassId(self, classId):
"""
Method extracts and returns the child object list same as the given classId
"""
childList = []
for ch in self.child:
if ch.classId.lower() == classId.lower():
childList.append(ch)
return childList | [
"def",
"GetChildClassId",
"(",
"self",
",",
"classId",
")",
":",
"childList",
"=",
"[",
"]",
"for",
"ch",
"in",
"self",
".",
"child",
":",
"if",
"ch",
".",
"classId",
".",
"lower",
"(",
")",
"==",
"classId",
".",
"lower",
"(",
")",
":",
"childList"... | Method extracts and returns the child object list same as the given classId | [
"Method",
"extracts",
"and",
"returns",
"the",
"child",
"object",
"list",
"same",
"as",
"the",
"given",
"classId"
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1180-L1188 | train | GetChildClassId extracts and returns the child object list same as the given classId |
tehmaze/natural | natural/date.py | _total_seconds | def _total_seconds(t):
'''
Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243
'''
return sum([
int(t.days * 86400 + t.seconds),
... | python | def _total_seconds(t):
'''
Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243
'''
return sum([
int(t.days * 86400 + t.seconds),
... | [
"def",
"_total_seconds",
"(",
"t",
")",
":",
"return",
"sum",
"(",
"[",
"int",
"(",
"t",
".",
"days",
"*",
"86400",
"+",
"t",
".",
"seconds",
")",
",",
"int",
"(",
"round",
"(",
"t",
".",
"microseconds",
"/",
"1000000.0",
")",
")",
"]",
")"
] | Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243 | [
"Takes",
"a",
"datetime",
".",
"timedelta",
"object",
"and",
"returns",
"the",
"delta",
"in",
"seconds",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L41-L53 | train | Takes a datetime. timedelta object and returns the delta in seconds. |
tehmaze/natural | natural/date.py | _to_datetime | def _to_datetime(t):
'''
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.datetime` object.
>>> _to_datetime('2013-12-11')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('Wed, 11 Dec 2013')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('We... | python | def _to_datetime(t):
'''
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.datetime` object.
>>> _to_datetime('2013-12-11')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('Wed, 11 Dec 2013')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('We... | [
"def",
"_to_datetime",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"six",
".",
"integer_types",
"+",
"(",
"float",
",",
")",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"t",
")",
".",
"replace",
"(",
"micros... | Internal function that tries whatever to convert ``t`` into a
:class:`datetime.datetime` object.
>>> _to_datetime('2013-12-11')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('Wed, 11 Dec 2013')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('Wed, 11 Dec 13')
datetime.datet... | [
"Internal",
"function",
"that",
"tries",
"whatever",
"to",
"convert",
"t",
"into",
"a",
":",
"class",
":",
"datetime",
".",
"datetime",
"object",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L56-L94 | train | Internal function that tries to convert t into a
Taxonomy datetime object. |
tehmaze/natural | natural/date.py | _to_date | def _to_date(t):
'''
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.date` object.
>>> _to_date('2013-12-11')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 2013')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 13')
datetime.date(2013, 12... | python | def _to_date(t):
'''
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.date` object.
>>> _to_date('2013-12-11')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 2013')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 13')
datetime.date(2013, 12... | [
"def",
"_to_date",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"six",
".",
"integer_types",
"+",
"(",
"float",
",",
")",
")",
":",
"return",
"datetime",
".",
"date",
".",
"fromtimestamp",
"(",
"t",
")",
"elif",
"isinstance",
"(",
"t",
",... | Internal function that tries whatever to convert ``t`` into a
:class:`datetime.date` object.
>>> _to_date('2013-12-11')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 2013')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 13')
datetime.date(2013, 12, 11) | [
"Internal",
"function",
"that",
"tries",
"whatever",
"to",
"convert",
"t",
"into",
"a",
":",
"class",
":",
"datetime",
".",
"date",
"object",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L97-L129 | train | Internal function that tries to convert t into a
datetime. date object. |
tehmaze/natural | natural/date.py | delta | def delta(t1, t2, words=True, justnow=datetime.timedelta(seconds=10)):
'''
Calculates the estimated delta between two time objects in human-readable
format. Used internally by the :func:`day` and :func:`duration` functions.
:param t1: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
... | python | def delta(t1, t2, words=True, justnow=datetime.timedelta(seconds=10)):
'''
Calculates the estimated delta between two time objects in human-readable
format. Used internally by the :func:`day` and :func:`duration` functions.
:param t1: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
... | [
"def",
"delta",
"(",
"t1",
",",
"t2",
",",
"words",
"=",
"True",
",",
"justnow",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
")",
":",
"t1",
"=",
"_to_datetime",
"(",
"t1",
")",
"t2",
"=",
"_to_datetime",
"(",
"t2",
")",
"d... | Calculates the estimated delta between two time objects in human-readable
format. Used internally by the :func:`day` and :func:`duration` functions.
:param t1: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
:param t2: timestamp, :class:`datetime.date` or :class:`datet... | [
"Calculates",
"the",
"estimated",
"delta",
"between",
"two",
"time",
"objects",
"in",
"human",
"-",
"readable",
"format",
".",
"Used",
"internally",
"by",
"the",
":",
"func",
":",
"day",
"and",
":",
"func",
":",
"duration",
"functions",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L132-L263 | train | Calculates the estimated delta between two time objects in human - readable format. |
tehmaze/natural | natural/date.py | day | def day(t, now=None, format='%B %d'):
'''
Date delta compared to ``t``. You can override ``now`` to specify what date
to compare to.
You can override the date format by supplying a ``format`` parameter.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
... | python | def day(t, now=None, format='%B %d'):
'''
Date delta compared to ``t``. You can override ``now`` to specify what date
to compare to.
You can override the date format by supplying a ``format`` parameter.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
... | [
"def",
"day",
"(",
"t",
",",
"now",
"=",
"None",
",",
"format",
"=",
"'%B %d'",
")",
":",
"t1",
"=",
"_to_date",
"(",
"t",
")",
"t2",
"=",
"_to_date",
"(",
"now",
"or",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"diff",
"=",
"t1",
... | Date delta compared to ``t``. You can override ``now`` to specify what date
to compare to.
You can override the date format by supplying a ``format`` parameter.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
:param now: default ``None``, optionally a :cl... | [
"Date",
"delta",
"compared",
"to",
"t",
".",
"You",
"can",
"override",
"now",
"to",
"specify",
"what",
"date",
"to",
"compare",
"to",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L266-L310 | train | Return a string that represents the day of the current date. |
tehmaze/natural | natural/date.py | duration | def duration(t, now=None, precision=1, pad=', ', words=None,
justnow=datetime.timedelta(seconds=10)):
'''
Time delta compared to ``t``. You can override ``now`` to specify what time
to compare to.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
objec... | python | def duration(t, now=None, precision=1, pad=', ', words=None,
justnow=datetime.timedelta(seconds=10)):
'''
Time delta compared to ``t``. You can override ``now`` to specify what time
to compare to.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
objec... | [
"def",
"duration",
"(",
"t",
",",
"now",
"=",
"None",
",",
"precision",
"=",
"1",
",",
"pad",
"=",
"', '",
",",
"words",
"=",
"None",
",",
"justnow",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
")",
":",
"if",
"words",
"is"... | Time delta compared to ``t``. You can override ``now`` to specify what time
to compare to.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
:param now: default ``None``, optionally a :class:`datetime.datetime`
object
:param precision: defaul... | [
"Time",
"delta",
"compared",
"to",
"t",
".",
"You",
"can",
"override",
"now",
"to",
"specify",
"what",
"time",
"to",
"compare",
"to",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L313-L391 | train | Prints a string representation of the time delta compared to t. |
tehmaze/natural | natural/date.py | compress | def compress(t, sign=False, pad=''):
'''
Convert the input to compressed format, works with a
:class:`datetime.timedelta` object or a number that represents the number
of seconds you want to compress. If you supply a timestamp or a
:class:`datetime.datetime` object, it will give the delta relative ... | python | def compress(t, sign=False, pad=''):
'''
Convert the input to compressed format, works with a
:class:`datetime.timedelta` object or a number that represents the number
of seconds you want to compress. If you supply a timestamp or a
:class:`datetime.datetime` object, it will give the delta relative ... | [
"def",
"compress",
"(",
"t",
",",
"sign",
"=",
"False",
",",
"pad",
"=",
"''",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"datetime",
".",
"timedelta",
")",
":",
"seconds",
"=",
"t",
".",
"seconds",
"+",
"(",
"t",
".",
"days",
"*",
"86400",
"... | Convert the input to compressed format, works with a
:class:`datetime.timedelta` object or a number that represents the number
of seconds you want to compress. If you supply a timestamp or a
:class:`datetime.datetime` object, it will give the delta relative to the
current time.
You can enable show... | [
"Convert",
"the",
"input",
"to",
"compressed",
"format",
"works",
"with",
"a",
":",
"class",
":",
"datetime",
".",
"timedelta",
"object",
"or",
"a",
"number",
"that",
"represents",
"the",
"number",
"of",
"seconds",
"you",
"want",
"to",
"compress",
".",
"If... | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L394-L454 | train | Convert the input to a compressed format. |
yeraydiazdiaz/lunr.py | lunr/index.py | Index.search | def search(self, query_string):
"""Performs a search against the index using lunr query syntax.
Results will be returned sorted by their score, the most relevant
results will be returned first.
For more programmatic querying use `lunr.Index.query`.
Args:
query_stri... | python | def search(self, query_string):
"""Performs a search against the index using lunr query syntax.
Results will be returned sorted by their score, the most relevant
results will be returned first.
For more programmatic querying use `lunr.Index.query`.
Args:
query_stri... | [
"def",
"search",
"(",
"self",
",",
"query_string",
")",
":",
"query",
"=",
"self",
".",
"create_query",
"(",
")",
"# TODO: should QueryParser be a method of query? should it return one?",
"parser",
"=",
"QueryParser",
"(",
"query_string",
",",
"query",
")",
"parser",
... | Performs a search against the index using lunr query syntax.
Results will be returned sorted by their score, the most relevant
results will be returned first.
For more programmatic querying use `lunr.Index.query`.
Args:
query_string (str): A string to parse into a Query.
... | [
"Performs",
"a",
"search",
"against",
"the",
"index",
"using",
"lunr",
"query",
"syntax",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/index.py#L47-L65 | train | Performs a search against the index using a query syntax. |
yeraydiazdiaz/lunr.py | lunr/index.py | Index.create_query | def create_query(self, fields=None):
"""Convenience method to create a Query with the Index's fields.
Args:
fields (iterable, optional): The fields to include in the Query,
defaults to the Index's `all_fields`.
Returns:
Query: With the specified fields o... | python | def create_query(self, fields=None):
"""Convenience method to create a Query with the Index's fields.
Args:
fields (iterable, optional): The fields to include in the Query,
defaults to the Index's `all_fields`.
Returns:
Query: With the specified fields o... | [
"def",
"create_query",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"if",
"fields",
"is",
"None",
":",
"return",
"Query",
"(",
"self",
".",
"fields",
")",
"non_contained_fields",
"=",
"set",
"(",
"fields",
")",
"-",
"set",
"(",
"self",
".",
"fi... | Convenience method to create a Query with the Index's fields.
Args:
fields (iterable, optional): The fields to include in the Query,
defaults to the Index's `all_fields`.
Returns:
Query: With the specified fields or all the fields in the Index. | [
"Convenience",
"method",
"to",
"create",
"a",
"Query",
"with",
"the",
"Index",
"s",
"fields",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/index.py#L67-L86 | train | Convenience method to create a Query with the Index s fields. |
yeraydiazdiaz/lunr.py | lunr/index.py | Index.query | def query(self, query=None, callback=None):
"""Performs a query against the index using the passed lunr.Query
object.
If performing programmatic queries against the index, this method is
preferred over `lunr.Index.search` so as to avoid the additional query
parsing overhead.
... | python | def query(self, query=None, callback=None):
"""Performs a query against the index using the passed lunr.Query
object.
If performing programmatic queries against the index, this method is
preferred over `lunr.Index.search` so as to avoid the additional query
parsing overhead.
... | [
"def",
"query",
"(",
"self",
",",
"query",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"query",
"is",
"None",
":",
"query",
"=",
"self",
".",
"create_query",
"(",
")",
"if",
"callback",
"is",
"not",
"None",
":",
"callback",
"(",
"que... | Performs a query against the index using the passed lunr.Query
object.
If performing programmatic queries against the index, this method is
preferred over `lunr.Index.search` so as to avoid the additional query
parsing overhead.
Args:
query (lunr.Query): A configure... | [
"Performs",
"a",
"query",
"against",
"the",
"index",
"using",
"the",
"passed",
"lunr",
".",
"Query",
"object",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/index.py#L88-L318 | train | Performs a query against the index using the passed query and returns a list of results. |
yeraydiazdiaz/lunr.py | lunr/index.py | Index.load | def load(cls, serialized_index):
"""Load a serialized index"""
from lunr import __TARGET_JS_VERSION__
if isinstance(serialized_index, basestring):
serialized_index = json.loads(serialized_index)
if serialized_index["version"] != __TARGET_JS_VERSION__:
logger.war... | python | def load(cls, serialized_index):
"""Load a serialized index"""
from lunr import __TARGET_JS_VERSION__
if isinstance(serialized_index, basestring):
serialized_index = json.loads(serialized_index)
if serialized_index["version"] != __TARGET_JS_VERSION__:
logger.war... | [
"def",
"load",
"(",
"cls",
",",
"serialized_index",
")",
":",
"from",
"lunr",
"import",
"__TARGET_JS_VERSION__",
"if",
"isinstance",
"(",
"serialized_index",
",",
"basestring",
")",
":",
"serialized_index",
"=",
"json",
".",
"loads",
"(",
"serialized_index",
")"... | Load a serialized index | [
"Load",
"a",
"serialized",
"index"
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/index.py#L340-L372 | train | Load a serialized index |
jaraco/jaraco.mongodb | jaraco/mongodb/compat.py | save | def save(coll, to_save):
"""
Pymongo has deprecated the save logic, even though
MongoDB still advertizes that logic in the core API:
https://docs.mongodb.com/manual/reference/method/db.collection.save/
This function provides a compatible interface.
"""
filter = Projection(['_id'], to_save)
upsert_replace = fun... | python | def save(coll, to_save):
"""
Pymongo has deprecated the save logic, even though
MongoDB still advertizes that logic in the core API:
https://docs.mongodb.com/manual/reference/method/db.collection.save/
This function provides a compatible interface.
"""
filter = Projection(['_id'], to_save)
upsert_replace = fun... | [
"def",
"save",
"(",
"coll",
",",
"to_save",
")",
":",
"filter",
"=",
"Projection",
"(",
"[",
"'_id'",
"]",
",",
"to_save",
")",
"upsert_replace",
"=",
"functools",
".",
"partial",
"(",
"coll",
".",
"replace_one",
",",
"filter",
",",
"upsert",
"=",
"Tru... | Pymongo has deprecated the save logic, even though
MongoDB still advertizes that logic in the core API:
https://docs.mongodb.com/manual/reference/method/db.collection.save/
This function provides a compatible interface. | [
"Pymongo",
"has",
"deprecated",
"the",
"save",
"logic",
"even",
"though",
"MongoDB",
"still",
"advertizes",
"that",
"logic",
"in",
"the",
"core",
"API",
":",
"https",
":",
"//",
"docs",
".",
"mongodb",
".",
"com",
"/",
"manual",
"/",
"reference",
"/",
"m... | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/compat.py#L7-L18 | train | Save a record in the given collection. |
CyberInt/celstash | celstash.py | configure | def configure(logstash_host=None, logstash_port=None, logdir=None):
'''Configuration settings.'''
if not (logstash_host or logstash_port or logdir):
raise ValueError('you must specify at least one parameter')
config.logstash.host = logstash_host or config.logstash.host
config.logstash.port = l... | python | def configure(logstash_host=None, logstash_port=None, logdir=None):
'''Configuration settings.'''
if not (logstash_host or logstash_port or logdir):
raise ValueError('you must specify at least one parameter')
config.logstash.host = logstash_host or config.logstash.host
config.logstash.port = l... | [
"def",
"configure",
"(",
"logstash_host",
"=",
"None",
",",
"logstash_port",
"=",
"None",
",",
"logdir",
"=",
"None",
")",
":",
"if",
"not",
"(",
"logstash_host",
"or",
"logstash_port",
"or",
"logdir",
")",
":",
"raise",
"ValueError",
"(",
"'you must specify... | Configuration settings. | [
"Configuration",
"settings",
"."
] | d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e | https://github.com/CyberInt/celstash/blob/d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e/celstash.py#L51-L61 | train | Configure the logstash server. |
CyberInt/celstash | celstash.py | new_logger | def new_logger(name):
'''Return new logger which will log both to logstash and to file in JSON
format.
Log files are stored in <logdir>/name.json
'''
log = get_task_logger(name)
handler = logstash.LogstashHandler(
config.logstash.host, config.logstash.port)
log.addHandler(handler)... | python | def new_logger(name):
'''Return new logger which will log both to logstash and to file in JSON
format.
Log files are stored in <logdir>/name.json
'''
log = get_task_logger(name)
handler = logstash.LogstashHandler(
config.logstash.host, config.logstash.port)
log.addHandler(handler)... | [
"def",
"new_logger",
"(",
"name",
")",
":",
"log",
"=",
"get_task_logger",
"(",
"name",
")",
"handler",
"=",
"logstash",
".",
"LogstashHandler",
"(",
"config",
".",
"logstash",
".",
"host",
",",
"config",
".",
"logstash",
".",
"port",
")",
"log",
".",
... | Return new logger which will log both to logstash and to file in JSON
format.
Log files are stored in <logdir>/name.json | [
"Return",
"new",
"logger",
"which",
"will",
"log",
"both",
"to",
"logstash",
"and",
"to",
"file",
"in",
"JSON",
"format",
"."
] | d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e | https://github.com/CyberInt/celstash/blob/d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e/celstash.py#L69-L91 | train | Return new logger which will log both to logstash and to file in JSON
format. |
JensRantil/rewind | rewind/server/main.py | _zmq_socket_context | def _zmq_socket_context(context, socket_type, bind_endpoints):
"""A ZeroMQ socket context that both constructs a socket and closes it."""
socket = context.socket(socket_type)
try:
for endpoint in bind_endpoints:
try:
socket.bind(endpoint)
except Exception:
... | python | def _zmq_socket_context(context, socket_type, bind_endpoints):
"""A ZeroMQ socket context that both constructs a socket and closes it."""
socket = context.socket(socket_type)
try:
for endpoint in bind_endpoints:
try:
socket.bind(endpoint)
except Exception:
... | [
"def",
"_zmq_socket_context",
"(",
"context",
",",
"socket_type",
",",
"bind_endpoints",
")",
":",
"socket",
"=",
"context",
".",
"socket",
"(",
"socket_type",
")",
"try",
":",
"for",
"endpoint",
"in",
"bind_endpoints",
":",
"try",
":",
"socket",
".",
"bind"... | A ZeroMQ socket context that both constructs a socket and closes it. | [
"A",
"ZeroMQ",
"socket",
"context",
"that",
"both",
"constructs",
"a",
"socket",
"and",
"closes",
"it",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L229-L241 | train | A ZeroMQ socket context that both constructs a socket and closes it. |
JensRantil/rewind | rewind/server/main.py | _get_with_fallback | def _get_with_fallback(config, section, option, fallback):
"""Get a configuration value, using fallback for missing values.
Parameters:
config -- the configparser to try to extract the option value from.
section -- the section to extract value from.
option -- the name of the option to extract ... | python | def _get_with_fallback(config, section, option, fallback):
"""Get a configuration value, using fallback for missing values.
Parameters:
config -- the configparser to try to extract the option value from.
section -- the section to extract value from.
option -- the name of the option to extract ... | [
"def",
"_get_with_fallback",
"(",
"config",
",",
"section",
",",
"option",
",",
"fallback",
")",
":",
"exists",
"=",
"(",
"config",
".",
"has_section",
"(",
"section",
")",
"and",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
")",
"if"... | Get a configuration value, using fallback for missing values.
Parameters:
config -- the configparser to try to extract the option value from.
section -- the section to extract value from.
option -- the name of the option to extract value from.
fallback -- fallback value to return if no value w... | [
"Get",
"a",
"configuration",
"value",
"using",
"fallback",
"for",
"missing",
"values",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L244-L262 | train | Get a configuration value using fallback for missing values. |
JensRantil/rewind | rewind/server/main.py | run | def run(options, exit_codeword=None):
"""Actually execute the program.
Calling this method can be done from tests to simulate executing the
application from command line.
Parameters:
options -- `optionparser` from config file.
exit_codeword -- an optional exit_message that will shut down... | python | def run(options, exit_codeword=None):
"""Actually execute the program.
Calling this method can be done from tests to simulate executing the
application from command line.
Parameters:
options -- `optionparser` from config file.
exit_codeword -- an optional exit_message that will shut down... | [
"def",
"run",
"(",
"options",
",",
"exit_codeword",
"=",
"None",
")",
":",
"QUERY_ENDP_OPT",
"=",
"'query-bind-endpoint'",
"STREAM_ENDP_OPT",
"=",
"'streaming-bind-endpoint'",
"ZMQ_NTHREADS",
"=",
"\"zmq-nthreads\"",
"if",
"not",
"options",
".",
"has_section",
"(",
... | Actually execute the program.
Calling this method can be done from tests to simulate executing the
application from command line.
Parameters:
options -- `optionparser` from config file.
exit_codeword -- an optional exit_message that will shut down Rewind. Used
for testin... | [
"Actually",
"execute",
"the",
"program",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L265-L330 | train | This method is called by the command line program to simulate executing the Rewind application. |
JensRantil/rewind | rewind/server/main.py | main | def main(argv=None):
"""Entry point for Rewind.
Parses input and calls run() for the real work.
Parameters:
argv -- sys.argv arguments. Can be set for testing purposes.
returns -- the proposed exit code for the program.
"""
parser = argparse.ArgumentParser(
description='Event ... | python | def main(argv=None):
"""Entry point for Rewind.
Parses input and calls run() for the real work.
Parameters:
argv -- sys.argv arguments. Can be set for testing purposes.
returns -- the proposed exit code for the program.
"""
parser = argparse.ArgumentParser(
description='Event ... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Event storage and event proxy.'",
",",
"usage",
"=",
"'%(prog)s <configfile>'",
")",
"parser",
".",
"add_argument",
"(",
"'--exit-codewo... | Entry point for Rewind.
Parses input and calls run() for the real work.
Parameters:
argv -- sys.argv arguments. Can be set for testing purposes.
returns -- the proposed exit code for the program. | [
"Entry",
"point",
"for",
"Rewind",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L333-L361 | train | Entry point for Rewind. |
JensRantil/rewind | rewind/server/main.py | _IdGenerator.generate | def generate(self):
"""Generate a new string and return it."""
key = self._propose_new_key()
while self.key_exists(key):
_logger.warning('Previous candidate was used.'
' Regenerating another...')
key = self._propose_new_key()
return key | python | def generate(self):
"""Generate a new string and return it."""
key = self._propose_new_key()
while self.key_exists(key):
_logger.warning('Previous candidate was used.'
' Regenerating another...')
key = self._propose_new_key()
return key | [
"def",
"generate",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_propose_new_key",
"(",
")",
"while",
"self",
".",
"key_exists",
"(",
"key",
")",
":",
"_logger",
".",
"warning",
"(",
"'Previous candidate was used.'",
"' Regenerating another...'",
")",
"key... | Generate a new string and return it. | [
"Generate",
"a",
"new",
"string",
"and",
"return",
"it",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L55-L62 | train | Generate a new string and return it. |
JensRantil/rewind | rewind/server/main.py | _RewindRunner._handle_one_message | def _handle_one_message(self):
"""Handle one single incoming message on any socket.
This is the inner loop of the main application loop.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
It is crucial that this class function alway... | python | def _handle_one_message(self):
"""Handle one single incoming message on any socket.
This is the inner loop of the main application loop.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
It is crucial that this class function alway... | [
"def",
"_handle_one_message",
"(",
"self",
")",
":",
"result",
"=",
"True",
"requesttype",
"=",
"self",
".",
"query_socket",
".",
"recv",
"(",
")",
"if",
"requesttype",
"==",
"b\"PUBLISH\"",
":",
"self",
".",
"_handle_incoming_event",
"(",
")",
"elif",
"requ... | Handle one single incoming message on any socket.
This is the inner loop of the main application loop.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
It is crucial that this class function always respond with a
query_socket.sent... | [
"Handle",
"one",
"single",
"incoming",
"message",
"on",
"any",
"socket",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L98-L129 | train | Handle one incoming message on any socket. |
JensRantil/rewind | rewind/server/main.py | _RewindRunner._handle_unknown_command | def _handle_unknown_command(self):
"""Handle an unknown RES command.
The function makes sure to recv all message parts and respond with an
error.
"""
while self.query_socket.getsockopt(zmq.RCVMORE):
# Making sure we 'empty' enveloped message. Otherwise, we can't
... | python | def _handle_unknown_command(self):
"""Handle an unknown RES command.
The function makes sure to recv all message parts and respond with an
error.
"""
while self.query_socket.getsockopt(zmq.RCVMORE):
# Making sure we 'empty' enveloped message. Otherwise, we can't
... | [
"def",
"_handle_unknown_command",
"(",
"self",
")",
":",
"while",
"self",
".",
"query_socket",
".",
"getsockopt",
"(",
"zmq",
".",
"RCVMORE",
")",
":",
"# Making sure we 'empty' enveloped message. Otherwise, we can't",
"# respond.",
"self",
".",
"query_socket",
".",
"... | Handle an unknown RES command.
The function makes sure to recv all message parts and respond with an
error. | [
"Handle",
"an",
"unknown",
"RES",
"command",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L131-L142 | train | Handle an unknown RES command. |
JensRantil/rewind | rewind/server/main.py | _RewindRunner._handle_event_query | def _handle_event_query(self):
"""Handle an incoming event query."""
assert self.query_socket.getsockopt(zmq.RCVMORE)
fro = self.query_socket.recv().decode()
assert self.query_socket.getsockopt(zmq.RCVMORE)
to = self.query_socket.recv().decode()
assert not self.query_sock... | python | def _handle_event_query(self):
"""Handle an incoming event query."""
assert self.query_socket.getsockopt(zmq.RCVMORE)
fro = self.query_socket.recv().decode()
assert self.query_socket.getsockopt(zmq.RCVMORE)
to = self.query_socket.recv().decode()
assert not self.query_sock... | [
"def",
"_handle_event_query",
"(",
"self",
")",
":",
"assert",
"self",
".",
"query_socket",
".",
"getsockopt",
"(",
"zmq",
".",
"RCVMORE",
")",
"fro",
"=",
"self",
".",
"query_socket",
".",
"recv",
"(",
")",
".",
"decode",
"(",
")",
"assert",
"self",
"... | Handle an incoming event query. | [
"Handle",
"an",
"incoming",
"event",
"query",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L144-L183 | train | Handle an incoming event query. |
JensRantil/rewind | rewind/server/main.py | _RewindRunner._handle_incoming_event | def _handle_incoming_event(self):
"""Handle an incoming event.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
TODO: Move the content of this function into `_handle_one_message`.
This class function does not simply handle incoming... | python | def _handle_incoming_event(self):
"""Handle an incoming event.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
TODO: Move the content of this function into `_handle_one_message`.
This class function does not simply handle incoming... | [
"def",
"_handle_incoming_event",
"(",
"self",
")",
":",
"eventstr",
"=",
"self",
".",
"query_socket",
".",
"recv",
"(",
")",
"newid",
"=",
"self",
".",
"id_generator",
".",
"generate",
"(",
")",
"# Make sure newid is not part of our request vocabulary",
"assert",
... | Handle an incoming event.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
TODO: Move the content of this function into `_handle_one_message`.
This class function does not simply handle incoming events. | [
"Handle",
"an",
"incoming",
"event",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L185-L215 | train | Handle an incoming event. |
yeraydiazdiaz/lunr.py | lunr/idf.py | idf | def idf(posting, document_count):
"""A function to calculate the inverse document frequency for a posting.
This is shared between the builder and the index.
"""
documents_with_term = 0
for field_name in posting:
if field_name == "_index":
continue
documents_with_term += l... | python | def idf(posting, document_count):
"""A function to calculate the inverse document frequency for a posting.
This is shared between the builder and the index.
"""
documents_with_term = 0
for field_name in posting:
if field_name == "_index":
continue
documents_with_term += l... | [
"def",
"idf",
"(",
"posting",
",",
"document_count",
")",
":",
"documents_with_term",
"=",
"0",
"for",
"field_name",
"in",
"posting",
":",
"if",
"field_name",
"==",
"\"_index\"",
":",
"continue",
"documents_with_term",
"+=",
"len",
"(",
"posting",
"[",
"field_... | A function to calculate the inverse document frequency for a posting.
This is shared between the builder and the index. | [
"A",
"function",
"to",
"calculate",
"the",
"inverse",
"document",
"frequency",
"for",
"a",
"posting",
".",
"This",
"is",
"shared",
"between",
"the",
"builder",
"and",
"the",
"index",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/idf.py#L6-L17 | train | A function to calculate the inverse document frequency for a posting. |
JensRantil/rewind | rewind/server/config.py | construct_eventstore | def construct_eventstore(config, section=None):
"""Construct the event store to write and write from/to.
The event store is constructed from an optionally given configuration file
and/or command line arguments. Command line arguments has higher
presendence over configuration file attributes.
If a ... | python | def construct_eventstore(config, section=None):
"""Construct the event store to write and write from/to.
The event store is constructed from an optionally given configuration file
and/or command line arguments. Command line arguments has higher
presendence over configuration file attributes.
If a ... | [
"def",
"construct_eventstore",
"(",
"config",
",",
"section",
"=",
"None",
")",
":",
"ESTORE_CLASS_ATTRIBUTE",
"=",
"'class'",
"if",
"config",
"is",
"None",
":",
"_logger",
".",
"warn",
"(",
"\"Using InMemoryEventStore. Events are not persisted.\"",
"\" See example conf... | Construct the event store to write and write from/to.
The event store is constructed from an optionally given configuration file
and/or command line arguments. Command line arguments has higher
presendence over configuration file attributes.
If a defined event store is missing, `InMemoryEventStore` wi... | [
"Construct",
"the",
"event",
"store",
"to",
"write",
"and",
"write",
"from",
"/",
"to",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/config.py#L45-L120 | train | Construct an event store to write and write from a given configuration dictionary. |
JensRantil/rewind | rewind/server/config.py | check_config_options | def check_config_options(_class, required_options, optional_options, options):
"""Helper method to check options.
Arguments:
_class -- the original class that takes received the options.
required_options -- the options that are required. If they are not
present, a Conf... | python | def check_config_options(_class, required_options, optional_options, options):
"""Helper method to check options.
Arguments:
_class -- the original class that takes received the options.
required_options -- the options that are required. If they are not
present, a Conf... | [
"def",
"check_config_options",
"(",
"_class",
",",
"required_options",
",",
"optional_options",
",",
"options",
")",
":",
"for",
"opt",
"in",
"required_options",
":",
"if",
"opt",
"not",
"in",
"options",
":",
"msg",
"=",
"\"Required option missing: {0}\"",
"raise"... | Helper method to check options.
Arguments:
_class -- the original class that takes received the options.
required_options -- the options that are required. If they are not
present, a ConfigurationError is raised. Given as a
tuple.
optional_optio... | [
"Helper",
"method",
"to",
"check",
"options",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/config.py#L123-L148 | train | Helper method to check the options for a new object. |
tehmaze/natural | natural/file.py | accessed | def accessed(filename):
'''
Retrieve how long ago a file has been accessed.
:param filename: name of the file
>>> print accessed(__file__) # doctest: +SKIP
just now
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_ATI... | python | def accessed(filename):
'''
Retrieve how long ago a file has been accessed.
:param filename: name of the file
>>> print accessed(__file__) # doctest: +SKIP
just now
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_ATI... | [
"def",
"accessed",
"(",
"filename",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"file",
")",
":",
"filename",
"=",
"filename",
".",
"name",
"return",
"duration",
"(",
"os",
".",
"stat",
"(",
"filename",
")",
"[",
"stat",
".",
"ST_ATIME",
"]",
... | Retrieve how long ago a file has been accessed.
:param filename: name of the file
>>> print accessed(__file__) # doctest: +SKIP
just now | [
"Retrieve",
"how",
"long",
"ago",
"a",
"file",
"has",
"been",
"accessed",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L7-L19 | train | Retrieve how long ago a file has been accessed. |
tehmaze/natural | natural/file.py | created | def created(filename):
'''
Retrieve how long ago a file has been created.
:param filename: name of the file
>>> print created('/') # doctest: +SKIP
8 weeks ago
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_CTI... | python | def created(filename):
'''
Retrieve how long ago a file has been created.
:param filename: name of the file
>>> print created('/') # doctest: +SKIP
8 weeks ago
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_CTI... | [
"def",
"created",
"(",
"filename",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"file",
")",
":",
"filename",
"=",
"filename",
".",
"name",
"return",
"duration",
"(",
"os",
".",
"stat",
"(",
"filename",
")",
"[",
"stat",
".",
"ST_CTIME",
"]",
... | Retrieve how long ago a file has been created.
:param filename: name of the file
>>> print created('/') # doctest: +SKIP
8 weeks ago | [
"Retrieve",
"how",
"long",
"ago",
"a",
"file",
"has",
"been",
"created",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L22-L34 | train | Retrieve how long ago a file has been created. |
tehmaze/natural | natural/file.py | modified | def modified(filename):
'''
Retrieve how long ago a file has been modified.
:param filename: name of the file
>>> print modified('/') # doctest: +SKIP
3 days ago
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_M... | python | def modified(filename):
'''
Retrieve how long ago a file has been modified.
:param filename: name of the file
>>> print modified('/') # doctest: +SKIP
3 days ago
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_M... | [
"def",
"modified",
"(",
"filename",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"file",
")",
":",
"filename",
"=",
"filename",
".",
"name",
"return",
"duration",
"(",
"os",
".",
"stat",
"(",
"filename",
")",
"[",
"stat",
".",
"ST_MTIME",
"]",
... | Retrieve how long ago a file has been modified.
:param filename: name of the file
>>> print modified('/') # doctest: +SKIP
3 days ago | [
"Retrieve",
"how",
"long",
"ago",
"a",
"file",
"has",
"been",
"modified",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L37-L49 | train | Retrieve how long ago a file has been modified. |
tehmaze/natural | natural/file.py | size | def size(filename, format='decimal'):
'''
Retrieve the size of a file.
:param filename: name of the file
>>> size('/etc/mime.types') # doctest: +SKIP
23.70 kB
'''
if isinstance(filename, file):
filename = filename.name
return filesize(os.stat(filename)[stat.ST_SIZE], ... | python | def size(filename, format='decimal'):
'''
Retrieve the size of a file.
:param filename: name of the file
>>> size('/etc/mime.types') # doctest: +SKIP
23.70 kB
'''
if isinstance(filename, file):
filename = filename.name
return filesize(os.stat(filename)[stat.ST_SIZE], ... | [
"def",
"size",
"(",
"filename",
",",
"format",
"=",
"'decimal'",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"file",
")",
":",
"filename",
"=",
"filename",
".",
"name",
"return",
"filesize",
"(",
"os",
".",
"stat",
"(",
"filename",
")",
"[",
... | Retrieve the size of a file.
:param filename: name of the file
>>> size('/etc/mime.types') # doctest: +SKIP
23.70 kB | [
"Retrieve",
"the",
"size",
"of",
"a",
"file",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L52-L65 | train | Retrieve the size of a file. |
rmst/chi | chi/rl/wrappers.py | AtariWrapper._observation | def _observation(self, observation):
""" Paper: First, to encode a single frame we take the maximum value for each pixel colour
value over the frame being encoded and the previous frame. This was necessary to
remove flickering that is present in games where some objects appear on... | python | def _observation(self, observation):
""" Paper: First, to encode a single frame we take the maximum value for each pixel colour
value over the frame being encoded and the previous frame. This was necessary to
remove flickering that is present in games where some objects appear on... | [
"def",
"_observation",
"(",
"self",
",",
"observation",
")",
":",
"obs",
"=",
"np",
".",
"maximum",
"(",
"observation",
",",
"self",
".",
"previous_frame",
")",
"self",
".",
"previous_frame",
"=",
"observation",
"\"\"\" Paper: Second, we then extract\n the Y ... | Paper: First, to encode a single frame we take the maximum value for each pixel colour
value over the frame being encoded and the previous frame. This was necessary to
remove flickering that is present in games where some objects appear only in even
frames while other obj... | [
"Paper",
":",
"First",
"to",
"encode",
"a",
"single",
"frame",
"we",
"take",
"the",
"maximum",
"value",
"for",
"each",
"pixel",
"colour",
"value",
"over",
"the",
"frame",
"being",
"encoded",
"and",
"the",
"previous",
"frame",
".",
"This",
"was",
"necessary... | b9205127f3736eb6ebbf6bb2960c4bbb747142b7 | https://github.com/rmst/chi/blob/b9205127f3736eb6ebbf6bb2960c4bbb747142b7/chi/rl/wrappers.py#L138-L156 | train | Given an observation we take the maximum value for each pixel colour
value over the frame and the previous frame and then extract the appropriate image. |
mapeveri/django-endless-pagination-vue | endless_pagination/templatetags/endless.py | show_more | def show_more(context, label=None, loading=settings.LOADING):
"""Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loadin... | python | def show_more(context, label=None, loading=settings.LOADING):
"""Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loadin... | [
"def",
"show_more",
"(",
"context",
",",
"label",
"=",
"None",
",",
"loading",
"=",
"settings",
".",
"LOADING",
")",
":",
"# This template tag could raise a PaginationError: you have to call",
"# *paginate* or *lazy_paginate* before including the showmore template.",
"data",
"=... | Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loading text too::
{% show_more "even more" "working" %}
Must... | [
"Show",
"the",
"link",
"to",
"get",
"the",
"next",
"page",
"in",
"a",
"Twitter",
"-",
"like",
"pagination",
"."
] | 3faa79a51b11d7ae0bd431abf8c38ecaf9180704 | https://github.com/mapeveri/django-endless-pagination-vue/blob/3faa79a51b11d7ae0bd431abf8c38ecaf9180704/endless_pagination/templatetags/endless.py#L327-L366 | train | Show the link to get the next page in a Twitter - like pagination. |
mapeveri/django-endless-pagination-vue | endless_pagination/templatetags/endless.py | show_more_table | def show_more_table(context, label=None, loading=settings.LOADING):
"""Show the link to get the next page in a Twitter-like pagination in a
template for table.
Usage::
{% show_more_table %}
Alternatively you can override the label passed to the default template::
{% show_more_table ... | python | def show_more_table(context, label=None, loading=settings.LOADING):
"""Show the link to get the next page in a Twitter-like pagination in a
template for table.
Usage::
{% show_more_table %}
Alternatively you can override the label passed to the default template::
{% show_more_table ... | [
"def",
"show_more_table",
"(",
"context",
",",
"label",
"=",
"None",
",",
"loading",
"=",
"settings",
".",
"LOADING",
")",
":",
"# This template tag could raise a PaginationError: you have to call",
"# *paginate* or *lazy_paginate* before including the showmore template.",
"retur... | Show the link to get the next page in a Twitter-like pagination in a
template for table.
Usage::
{% show_more_table %}
Alternatively you can override the label passed to the default template::
{% show_more_table "even more" %}
You can override the loading text too::
{% show... | [
"Show",
"the",
"link",
"to",
"get",
"the",
"next",
"page",
"in",
"a",
"Twitter",
"-",
"like",
"pagination",
"in",
"a",
"template",
"for",
"table",
"."
] | 3faa79a51b11d7ae0bd431abf8c38ecaf9180704 | https://github.com/mapeveri/django-endless-pagination-vue/blob/3faa79a51b11d7ae0bd431abf8c38ecaf9180704/endless_pagination/templatetags/endless.py#L370-L391 | train | Show the link to get the next page in a Twitter - like pagination in a
template for table. |
yeraydiazdiaz/lunr.py | lunr/languages/trimmer.py | generate_trimmer | def generate_trimmer(word_characters):
"""Returns a trimmer function from a string of word characters.
TODO: lunr-languages ships with lists of word characters for each language
I haven't found an equivalent in Python, we may need to copy it.
"""
start_re = r"^[^{}]+".format(word_characters)
en... | python | def generate_trimmer(word_characters):
"""Returns a trimmer function from a string of word characters.
TODO: lunr-languages ships with lists of word characters for each language
I haven't found an equivalent in Python, we may need to copy it.
"""
start_re = r"^[^{}]+".format(word_characters)
en... | [
"def",
"generate_trimmer",
"(",
"word_characters",
")",
":",
"start_re",
"=",
"r\"^[^{}]+\"",
".",
"format",
"(",
"word_characters",
")",
"end_re",
"=",
"r\"[^{}]+$\"",
".",
"format",
"(",
"word_characters",
")",
"def",
"trimmer",
"(",
"token",
",",
"i",
"=",
... | Returns a trimmer function from a string of word characters.
TODO: lunr-languages ships with lists of word characters for each language
I haven't found an equivalent in Python, we may need to copy it. | [
"Returns",
"a",
"trimmer",
"function",
"from",
"a",
"string",
"of",
"word",
"characters",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/languages/trimmer.py#L6-L23 | train | Returns a trimmer function from a string of word characters. |
kevin-brown/drf-json-api | rest_framework_json_api/utils.py | camelcase | def camelcase(string):
'''Return a string in lowerCamelCase
Examples:
"people" -> "people"
"profile images" -> "profileImages"
'''
out = slug(string).replace('-', ' ').title().replace(' ', '')
return out[0].lower() + out[1:] | python | def camelcase(string):
'''Return a string in lowerCamelCase
Examples:
"people" -> "people"
"profile images" -> "profileImages"
'''
out = slug(string).replace('-', ' ').title().replace(' ', '')
return out[0].lower() + out[1:] | [
"def",
"camelcase",
"(",
"string",
")",
":",
"out",
"=",
"slug",
"(",
"string",
")",
".",
"replace",
"(",
"'-'",
",",
"' '",
")",
".",
"title",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"out",
"[",
"0",
"]",
".",
"lower",
... | Return a string in lowerCamelCase
Examples:
"people" -> "people"
"profile images" -> "profileImages" | [
"Return",
"a",
"string",
"in",
"lowerCamelCase"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/utils.py#L69-L77 | train | Return a string in lowerCamelCase
Examples |
yeraydiazdiaz/lunr.py | lunr/vector.py | Vector.position_for_index | def position_for_index(self, index):
"""Calculates the position within the vector to insert a given index.
This is used internally by insert and upsert. If there are duplicate
indexes then the position is returned as if the value for that index
were to be updated, but it is the callers ... | python | def position_for_index(self, index):
"""Calculates the position within the vector to insert a given index.
This is used internally by insert and upsert. If there are duplicate
indexes then the position is returned as if the value for that index
were to be updated, but it is the callers ... | [
"def",
"position_for_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"self",
".",
"elements",
":",
"return",
"0",
"start",
"=",
"0",
"end",
"=",
"int",
"(",
"len",
"(",
"self",
".",
"elements",
")",
"/",
"2",
")",
"slice_length",
"=",
"en... | Calculates the position within the vector to insert a given index.
This is used internally by insert and upsert. If there are duplicate
indexes then the position is returned as if the value for that index
were to be updated, but it is the callers responsibility to check
whether there is... | [
"Calculates",
"the",
"position",
"within",
"the",
"vector",
"to",
"insert",
"a",
"given",
"index",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L37-L71 | train | Calculates the position within the vector to insert a given index. |
yeraydiazdiaz/lunr.py | lunr/vector.py | Vector.insert | def insert(self, insert_index, val):
"""Inserts an element at an index within the vector.
Does not allow duplicates, will throw an error if there is already an
entry for this index.
"""
def prevent_duplicates(index, val):
raise BaseLunrException("Duplicate index")
... | python | def insert(self, insert_index, val):
"""Inserts an element at an index within the vector.
Does not allow duplicates, will throw an error if there is already an
entry for this index.
"""
def prevent_duplicates(index, val):
raise BaseLunrException("Duplicate index")
... | [
"def",
"insert",
"(",
"self",
",",
"insert_index",
",",
"val",
")",
":",
"def",
"prevent_duplicates",
"(",
"index",
",",
"val",
")",
":",
"raise",
"BaseLunrException",
"(",
"\"Duplicate index\"",
")",
"self",
".",
"upsert",
"(",
"insert_index",
",",
"val",
... | Inserts an element at an index within the vector.
Does not allow duplicates, will throw an error if there is already an
entry for this index. | [
"Inserts",
"an",
"element",
"at",
"an",
"index",
"within",
"the",
"vector",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L73-L83 | train | Inserts an element at an index within the vector. |
yeraydiazdiaz/lunr.py | lunr/vector.py | Vector.upsert | def upsert(self, insert_index, val, fn=None):
"""Inserts or updates an existing index within the vector.
Args:
- insert_index (int): The index at which the element should be
inserted.
- val (int|float): The value to be inserted into the vector.
- fn (... | python | def upsert(self, insert_index, val, fn=None):
"""Inserts or updates an existing index within the vector.
Args:
- insert_index (int): The index at which the element should be
inserted.
- val (int|float): The value to be inserted into the vector.
- fn (... | [
"def",
"upsert",
"(",
"self",
",",
"insert_index",
",",
"val",
",",
"fn",
"=",
"None",
")",
":",
"fn",
"=",
"fn",
"or",
"(",
"lambda",
"current",
",",
"passed",
":",
"passed",
")",
"self",
".",
"_magnitude",
"=",
"0",
"position",
"=",
"self",
".",
... | Inserts or updates an existing index within the vector.
Args:
- insert_index (int): The index at which the element should be
inserted.
- val (int|float): The value to be inserted into the vector.
- fn (callable, optional): An optional callable taking two
... | [
"Inserts",
"or",
"updates",
"an",
"existing",
"index",
"within",
"the",
"vector",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L85-L103 | train | Inserts or updates an existing entry in the vector. |
yeraydiazdiaz/lunr.py | lunr/vector.py | Vector.to_list | def to_list(self):
"""Converts the vector to an array of the elements within the vector"""
output = []
for i in range(1, len(self.elements), 2):
output.append(self.elements[i])
return output | python | def to_list(self):
"""Converts the vector to an array of the elements within the vector"""
output = []
for i in range(1, len(self.elements), 2):
output.append(self.elements[i])
return output | [
"def",
"to_list",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"elements",
")",
",",
"2",
")",
":",
"output",
".",
"append",
"(",
"self",
".",
"elements",
"[",
"i",
"]",
")... | Converts the vector to an array of the elements within the vector | [
"Converts",
"the",
"vector",
"to",
"an",
"array",
"of",
"the",
"elements",
"within",
"the",
"vector"
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L105-L110 | train | Converts the vector to an array of the elements within the vector |
yeraydiazdiaz/lunr.py | lunr/vector.py | Vector.dot | def dot(self, other):
"""Calculates the dot product of this vector and another vector."""
dot_product = 0
a = self.elements
b = other.elements
a_len = len(a)
b_len = len(b)
i = j = 0
while i < a_len and j < b_len:
a_val = a[i]
b_va... | python | def dot(self, other):
"""Calculates the dot product of this vector and another vector."""
dot_product = 0
a = self.elements
b = other.elements
a_len = len(a)
b_len = len(b)
i = j = 0
while i < a_len and j < b_len:
a_val = a[i]
b_va... | [
"def",
"dot",
"(",
"self",
",",
"other",
")",
":",
"dot_product",
"=",
"0",
"a",
"=",
"self",
".",
"elements",
"b",
"=",
"other",
".",
"elements",
"a_len",
"=",
"len",
"(",
"a",
")",
"b_len",
"=",
"len",
"(",
"b",
")",
"i",
"=",
"j",
"=",
"0"... | Calculates the dot product of this vector and another vector. | [
"Calculates",
"the",
"dot",
"product",
"of",
"this",
"vector",
"and",
"another",
"vector",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L129-L150 | train | Calculates the dot product of this vector and another vector. |
yeraydiazdiaz/lunr.py | lunr/vector.py | Vector.similarity | def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude | python | def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude | [
"def",
"similarity",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"magnitude",
"==",
"0",
"or",
"other",
".",
"magnitude",
"==",
"0",
":",
"return",
"0",
"return",
"self",
".",
"dot",
"(",
"other",
")",
"/",
"self",
".",
"magnitude"
] | Calculates the cosine similarity between this vector and another
vector. | [
"Calculates",
"the",
"cosine",
"similarity",
"between",
"this",
"vector",
"and",
"another",
"vector",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L152-L158 | train | Calculates the cosine similarity between this vector and another vector. |
tehmaze/natural | natural/bank.py | bban_base10 | def bban_base10(number):
'''
Printable Basic Bank Account Number in base-10.
:param number: string
>>> bban_base10('01234567')
'45670123'
>>> bban_base10('ABCD')
'10111213'
'''
number = bban_compact(number)
number = number[4:] + number[:4]
return ''.join([str(IBAN_ALPHABET.... | python | def bban_base10(number):
'''
Printable Basic Bank Account Number in base-10.
:param number: string
>>> bban_base10('01234567')
'45670123'
>>> bban_base10('ABCD')
'10111213'
'''
number = bban_compact(number)
number = number[4:] + number[:4]
return ''.join([str(IBAN_ALPHABET.... | [
"def",
"bban_base10",
"(",
"number",
")",
":",
"number",
"=",
"bban_compact",
"(",
"number",
")",
"number",
"=",
"number",
"[",
"4",
":",
"]",
"+",
"number",
"[",
":",
"4",
"]",
"return",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"IBAN_ALPHABET",
".... | Printable Basic Bank Account Number in base-10.
:param number: string
>>> bban_base10('01234567')
'45670123'
>>> bban_base10('ABCD')
'10111213' | [
"Printable",
"Basic",
"Bank",
"Account",
"Number",
"in",
"base",
"-",
"10",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/bank.py#L21-L34 | train | Returns a string that is a base - 10 number. |
tehmaze/natural | natural/bank.py | bban | def bban(value, country=None, validate=False):
'''
Printable Basic Bank Account Number (BBAN) for the given country code. The
``country`` must be a valid ISO 3166-2 country code.
:param value: string or int
:param country: string
>>> bban('068-9999995-01', 'BE')
'068999999501'
>>> bban... | python | def bban(value, country=None, validate=False):
'''
Printable Basic Bank Account Number (BBAN) for the given country code. The
``country`` must be a valid ISO 3166-2 country code.
:param value: string or int
:param country: string
>>> bban('068-9999995-01', 'BE')
'068999999501'
>>> bban... | [
"def",
"bban",
"(",
"value",
",",
"country",
"=",
"None",
",",
"validate",
"=",
"False",
")",
":",
"value",
"=",
"bban_compact",
"(",
"value",
")",
"if",
"validate",
":",
"country",
"=",
"country",
".",
"upper",
"(",
")",
"try",
":",
"rules",
"=",
... | Printable Basic Bank Account Number (BBAN) for the given country code. The
``country`` must be a valid ISO 3166-2 country code.
:param value: string or int
:param country: string
>>> bban('068-9999995-01', 'BE')
'068999999501'
>>> bban('555', 'NL')
'555'
>>> bban('555', 'NL', validate=... | [
"Printable",
"Basic",
"Bank",
"Account",
"Number",
"(",
"BBAN",
")",
"for",
"the",
"given",
"country",
"code",
".",
"The",
"country",
"must",
"be",
"a",
"valid",
"ISO",
"3166",
"-",
"2",
"country",
"code",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/bank.py#L46-L84 | train | Returns a string that is a valid Basic Bank Account Number for the given country code. |
tehmaze/natural | natural/bank.py | iban | def iban(number, validate=False):
'''
Printable International Bank Account Number (IBAN) as specified in ISO
13616.
:param number: string
>>> iban('BE43068999999501')
'BE43 0689 9999 9501'
>>> iban('XY32012341234123', validate=True)
Traceback (most recent call last):
...
Va... | python | def iban(number, validate=False):
'''
Printable International Bank Account Number (IBAN) as specified in ISO
13616.
:param number: string
>>> iban('BE43068999999501')
'BE43 0689 9999 9501'
>>> iban('XY32012341234123', validate=True)
Traceback (most recent call last):
...
Va... | [
"def",
"iban",
"(",
"number",
",",
"validate",
"=",
"False",
")",
":",
"number",
"=",
"bban_compact",
"(",
"number",
")",
"if",
"validate",
":",
"country",
"=",
"number",
"[",
":",
"2",
"]",
"if",
"country",
"not",
"in",
"BBAN_RULES",
":",
"raise",
"... | Printable International Bank Account Number (IBAN) as specified in ISO
13616.
:param number: string
>>> iban('BE43068999999501')
'BE43 0689 9999 9501'
>>> iban('XY32012341234123', validate=True)
Traceback (most recent call last):
...
ValueError: Invalid IBAN, country unknown
>>... | [
"Printable",
"International",
"Bank",
"Account",
"Number",
"(",
"IBAN",
")",
"as",
"specified",
"in",
"ISO",
"13616",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/bank.py#L87-L122 | train | Return the IBAN of the given number. |
jaraco/jaraco.mongodb | jaraco/mongodb/uri.py | _add_scheme | def _add_scheme():
"""
urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so.
"""
lists = [
urllib.parse.uses_relative,
urllib.parse.uses_netloc,
urllib.parse.uses_query,
]
for l in lists:
l.append('mongodb') | python | def _add_scheme():
"""
urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so.
"""
lists = [
urllib.parse.uses_relative,
urllib.parse.uses_netloc,
urllib.parse.uses_query,
]
for l in lists:
l.append('mongodb') | [
"def",
"_add_scheme",
"(",
")",
":",
"lists",
"=",
"[",
"urllib",
".",
"parse",
".",
"uses_relative",
",",
"urllib",
".",
"parse",
".",
"uses_netloc",
",",
"urllib",
".",
"parse",
".",
"uses_query",
",",
"]",
"for",
"l",
"in",
"lists",
":",
"l",
".",... | urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so. | [
"urllib",
".",
"parse",
"doesn",
"t",
"support",
"the",
"mongodb",
"scheme",
"but",
"it",
"s",
"easy",
"to",
"make",
"it",
"so",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/uri.py#L7-L18 | train | Add mongodb scheme to the base url. |
yeraydiazdiaz/lunr.py | lunr/builder.py | Builder.field | def field(self, field_name, boost=1, extractor=None):
"""Adds a field to the list of document fields that will be indexed.
Every document being indexed should have this field. None values for
this field in indexed documents will not cause errors but will limit
the chance of that documen... | python | def field(self, field_name, boost=1, extractor=None):
"""Adds a field to the list of document fields that will be indexed.
Every document being indexed should have this field. None values for
this field in indexed documents will not cause errors but will limit
the chance of that documen... | [
"def",
"field",
"(",
"self",
",",
"field_name",
",",
"boost",
"=",
"1",
",",
"extractor",
"=",
"None",
")",
":",
"if",
"\"/\"",
"in",
"field_name",
":",
"raise",
"ValueError",
"(",
"\"Field {} contains illegal character `/`\"",
")",
"self",
".",
"_fields",
"... | Adds a field to the list of document fields that will be indexed.
Every document being indexed should have this field. None values for
this field in indexed documents will not cause errors but will limit
the chance of that document being retrieved by searches.
All fields should be adde... | [
"Adds",
"a",
"field",
"to",
"the",
"list",
"of",
"document",
"fields",
"that",
"will",
"be",
"indexed",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L69-L98 | train | Adds a field to the list of document fields that will be indexed. |
yeraydiazdiaz/lunr.py | lunr/builder.py | Builder.b | def b(self, number):
"""A parameter to tune the amount of field length normalisation that is
applied when calculating relevance scores.
A value of 0 will completely disable any normalisation and a value of 1
will fully normalise field lengths. The default is 0.75. Values of b
wi... | python | def b(self, number):
"""A parameter to tune the amount of field length normalisation that is
applied when calculating relevance scores.
A value of 0 will completely disable any normalisation and a value of 1
will fully normalise field lengths. The default is 0.75. Values of b
wi... | [
"def",
"b",
"(",
"self",
",",
"number",
")",
":",
"if",
"number",
"<",
"0",
":",
"self",
".",
"_b",
"=",
"0",
"elif",
"number",
">",
"1",
":",
"self",
".",
"_b",
"=",
"1",
"else",
":",
"self",
".",
"_b",
"=",
"number"
] | A parameter to tune the amount of field length normalisation that is
applied when calculating relevance scores.
A value of 0 will completely disable any normalisation and a value of 1
will fully normalise field lengths. The default is 0.75. Values of b
will be clamped to the range 0 - 1... | [
"A",
"parameter",
"to",
"tune",
"the",
"amount",
"of",
"field",
"length",
"normalisation",
"that",
"is",
"applied",
"when",
"calculating",
"relevance",
"scores",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L100-L113 | train | A parameter to tune the amount of field length normalisation that is applied when calculating relevance scores. |
yeraydiazdiaz/lunr.py | lunr/builder.py | Builder.add | def add(self, doc, attributes=None):
"""Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (... | python | def add(self, doc, attributes=None):
"""Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (... | [
"def",
"add",
"(",
"self",
",",
"doc",
",",
"attributes",
"=",
"None",
")",
":",
"doc_ref",
"=",
"str",
"(",
"doc",
"[",
"self",
".",
"_ref",
"]",
")",
"self",
".",
"_documents",
"[",
"doc_ref",
"]",
"=",
"attributes",
"or",
"{",
"}",
"self",
"."... | Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (by default
this is 'id') and it should h... | [
"Adds",
"a",
"document",
"to",
"the",
"index",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L125-L179 | train | Adds a document to the index. |
yeraydiazdiaz/lunr.py | lunr/builder.py | Builder.build | def build(self):
"""Builds the index, creating an instance of `lunr.Index`.
This completes the indexing process and should only be called once all
documents have been added to the index.
"""
self._calculate_average_field_lengths()
self._create_field_vectors()
sel... | python | def build(self):
"""Builds the index, creating an instance of `lunr.Index`.
This completes the indexing process and should only be called once all
documents have been added to the index.
"""
self._calculate_average_field_lengths()
self._create_field_vectors()
sel... | [
"def",
"build",
"(",
"self",
")",
":",
"self",
".",
"_calculate_average_field_lengths",
"(",
")",
"self",
".",
"_create_field_vectors",
"(",
")",
"self",
".",
"_create_token_set",
"(",
")",
"return",
"Index",
"(",
"inverted_index",
"=",
"self",
".",
"inverted_... | Builds the index, creating an instance of `lunr.Index`.
This completes the indexing process and should only be called once all
documents have been added to the index. | [
"Builds",
"the",
"index",
"creating",
"an",
"instance",
"of",
"lunr",
".",
"Index",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L181-L197 | train | Builds the index and returns an instance of lunr. Index. |
yeraydiazdiaz/lunr.py | lunr/builder.py | Builder._create_token_set | def _create_token_set(self):
"""Creates a token set of all tokens in the index using `lunr.TokenSet`
"""
self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys()))) | python | def _create_token_set(self):
"""Creates a token set of all tokens in the index using `lunr.TokenSet`
"""
self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys()))) | [
"def",
"_create_token_set",
"(",
"self",
")",
":",
"self",
".",
"token_set",
"=",
"TokenSet",
".",
"from_list",
"(",
"sorted",
"(",
"list",
"(",
"self",
".",
"inverted_index",
".",
"keys",
"(",
")",
")",
")",
")"
] | Creates a token set of all tokens in the index using `lunr.TokenSet` | [
"Creates",
"a",
"token",
"set",
"of",
"all",
"tokens",
"in",
"the",
"index",
"using",
"lunr",
".",
"TokenSet"
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L199-L202 | train | Creates a token set of all tokens in the index using lunr. TokenSet |
yeraydiazdiaz/lunr.py | lunr/builder.py | Builder._calculate_average_field_lengths | def _calculate_average_field_lengths(self):
"""Calculates the average document length for this index"""
accumulator = defaultdict(int)
documents_with_field = defaultdict(int)
for field_ref, length in self.field_lengths.items():
_field_ref = FieldRef.from_string(field_ref)
... | python | def _calculate_average_field_lengths(self):
"""Calculates the average document length for this index"""
accumulator = defaultdict(int)
documents_with_field = defaultdict(int)
for field_ref, length in self.field_lengths.items():
_field_ref = FieldRef.from_string(field_ref)
... | [
"def",
"_calculate_average_field_lengths",
"(",
"self",
")",
":",
"accumulator",
"=",
"defaultdict",
"(",
"int",
")",
"documents_with_field",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"field_ref",
",",
"length",
"in",
"self",
".",
"field_lengths",
".",
"items"... | Calculates the average document length for this index | [
"Calculates",
"the",
"average",
"document",
"length",
"for",
"this",
"index"
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L204-L219 | train | Calculates the average document length for this index |
yeraydiazdiaz/lunr.py | lunr/builder.py | Builder._create_field_vectors | def _create_field_vectors(self):
"""Builds a vector space model of every document using lunr.Vector."""
field_vectors = {}
term_idf_cache = {}
for field_ref, term_frequencies in self.field_term_frequencies.items():
_field_ref = FieldRef.from_string(field_ref)
fie... | python | def _create_field_vectors(self):
"""Builds a vector space model of every document using lunr.Vector."""
field_vectors = {}
term_idf_cache = {}
for field_ref, term_frequencies in self.field_term_frequencies.items():
_field_ref = FieldRef.from_string(field_ref)
fie... | [
"def",
"_create_field_vectors",
"(",
"self",
")",
":",
"field_vectors",
"=",
"{",
"}",
"term_idf_cache",
"=",
"{",
"}",
"for",
"field_ref",
",",
"term_frequencies",
"in",
"self",
".",
"field_term_frequencies",
".",
"items",
"(",
")",
":",
"_field_ref",
"=",
... | Builds a vector space model of every document using lunr.Vector. | [
"Builds",
"a",
"vector",
"space",
"model",
"of",
"every",
"document",
"using",
"lunr",
".",
"Vector",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L221-L265 | train | Creates a vector space model of every document. |
jaraco/jaraco.mongodb | jaraco/mongodb/sampling.py | estimate | def estimate(coll, filter={}, sample=1):
"""
Estimate the number of documents in the collection
matching the filter.
Sample may be a fixed number of documents to sample
or a percentage of the total collection size.
>>> coll = getfixture('bulky_collection')
>>> estimate(coll)
100
>>... | python | def estimate(coll, filter={}, sample=1):
"""
Estimate the number of documents in the collection
matching the filter.
Sample may be a fixed number of documents to sample
or a percentage of the total collection size.
>>> coll = getfixture('bulky_collection')
>>> estimate(coll)
100
>>... | [
"def",
"estimate",
"(",
"coll",
",",
"filter",
"=",
"{",
"}",
",",
"sample",
"=",
"1",
")",
":",
"total",
"=",
"coll",
".",
"estimated_document_count",
"(",
")",
"if",
"not",
"filter",
"and",
"sample",
"==",
"1",
":",
"return",
"total",
"if",
"sample... | Estimate the number of documents in the collection
matching the filter.
Sample may be a fixed number of documents to sample
or a percentage of the total collection size.
>>> coll = getfixture('bulky_collection')
>>> estimate(coll)
100
>>> query = {"val": {"$gte": 50}}
>>> val = estimat... | [
"Estimate",
"the",
"number",
"of",
"documents",
"in",
"the",
"collection",
"matching",
"the",
"filter",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/sampling.py#L6-L40 | train | Estimate the number of documents in the collection matching the filter. |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.render | def render(self, data, accepted_media_type=None, renderer_context=None):
"""Convert native data to JSON API
Tries each of the methods in `wrappers`, using the first successful
one, or raises `WrapperNotApplicable`.
"""
wrapper = None
success = False
for wrapper... | python | def render(self, data, accepted_media_type=None, renderer_context=None):
"""Convert native data to JSON API
Tries each of the methods in `wrappers`, using the first successful
one, or raises `WrapperNotApplicable`.
"""
wrapper = None
success = False
for wrapper... | [
"def",
"render",
"(",
"self",
",",
"data",
",",
"accepted_media_type",
"=",
"None",
",",
"renderer_context",
"=",
"None",
")",
":",
"wrapper",
"=",
"None",
"success",
"=",
"False",
"for",
"wrapper_name",
"in",
"self",
".",
"wrappers",
":",
"wrapper_method",
... | Convert native data to JSON API
Tries each of the methods in `wrappers`, using the first successful
one, or raises `WrapperNotApplicable`. | [
"Convert",
"native",
"data",
"to",
"JSON",
"API"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L47-L77 | train | Convert native data to JSON API format. |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.wrap_parser_error | def wrap_parser_error(self, data, renderer_context):
"""
Convert parser errors to the JSON API Error format
Parser errors have a status code of 400, like field errors, but have
the same native format as generic errors. Also, the detail message is
often specific to the input, so... | python | def wrap_parser_error(self, data, renderer_context):
"""
Convert parser errors to the JSON API Error format
Parser errors have a status code of 400, like field errors, but have
the same native format as generic errors. Also, the detail message is
often specific to the input, so... | [
"def",
"wrap_parser_error",
"(",
"self",
",",
"data",
",",
"renderer_context",
")",
":",
"response",
"=",
"renderer_context",
".",
"get",
"(",
"\"response\"",
",",
"None",
")",
"status_code",
"=",
"response",
"and",
"response",
".",
"status_code",
"if",
"statu... | Convert parser errors to the JSON API Error format
Parser errors have a status code of 400, like field errors, but have
the same native format as generic errors. Also, the detail message is
often specific to the input, so the error is listed as a 'detail'
rather than a 'title'. | [
"Convert",
"parser",
"errors",
"to",
"the",
"JSON",
"API",
"Error",
"format"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L91-L119 | train | Wrap parser errors to the JSON API Error |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.wrap_field_error | def wrap_field_error(self, data, renderer_context):
"""
Convert field error native data to the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for field errors is a dictionary where the keys are
field names (or 'non_field_er... | python | def wrap_field_error(self, data, renderer_context):
"""
Convert field error native data to the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for field errors is a dictionary where the keys are
field names (or 'non_field_er... | [
"def",
"wrap_field_error",
"(",
"self",
",",
"data",
",",
"renderer_context",
")",
":",
"response",
"=",
"renderer_context",
".",
"get",
"(",
"\"response\"",
",",
"None",
")",
"status_code",
"=",
"response",
"and",
"response",
".",
"status_code",
"if",
"status... | Convert field error native data to the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for field errors is a dictionary where the keys are
field names (or 'non_field_errors' for additional errors) and the
values are a list of error ... | [
"Convert",
"field",
"error",
"native",
"data",
"to",
"the",
"JSON",
"API",
"Error",
"format"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L121-L169 | train | Convert field error native data into the JSON API Error format. |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.wrap_generic_error | def wrap_generic_error(self, data, renderer_context):
"""
Convert generic error native data using the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for errors that are not bad requests, such as
authentication issues or mis... | python | def wrap_generic_error(self, data, renderer_context):
"""
Convert generic error native data using the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for errors that are not bad requests, such as
authentication issues or mis... | [
"def",
"wrap_generic_error",
"(",
"self",
",",
"data",
",",
"renderer_context",
")",
":",
"response",
"=",
"renderer_context",
".",
"get",
"(",
"\"response\"",
",",
"None",
")",
"status_code",
"=",
"response",
"and",
"response",
".",
"status_code",
"is_error",
... | Convert generic error native data using the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for errors that are not bad requests, such as
authentication issues or missing content, is a dictionary with a
'detail' key and a string val... | [
"Convert",
"generic",
"error",
"native",
"data",
"using",
"the",
"JSON",
"API",
"Error",
"format"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L171-L204 | train | Wrap generic error data into a JSON API error object. |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.wrap_error | def wrap_error(
self, data, renderer_context, keys_are_fields, issue_is_title):
"""Convert error native data to the JSON API Error format
JSON API has a different format for errors, but Django REST Framework
doesn't have a separate rendering path for errors. This results in
... | python | def wrap_error(
self, data, renderer_context, keys_are_fields, issue_is_title):
"""Convert error native data to the JSON API Error format
JSON API has a different format for errors, but Django REST Framework
doesn't have a separate rendering path for errors. This results in
... | [
"def",
"wrap_error",
"(",
"self",
",",
"data",
",",
"renderer_context",
",",
"keys_are_fields",
",",
"issue_is_title",
")",
":",
"response",
"=",
"renderer_context",
".",
"get",
"(",
"\"response\"",
",",
"None",
")",
"status_code",
"=",
"str",
"(",
"response",... | Convert error native data to the JSON API Error format
JSON API has a different format for errors, but Django REST Framework
doesn't have a separate rendering path for errors. This results in
some guesswork to determine if data is an error, what kind, and how
to handle it.
As ... | [
"Convert",
"error",
"native",
"data",
"to",
"the",
"JSON",
"API",
"Error",
"format"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L206-L247 | train | Convert error native data to the JSON API Error format |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.wrap_options | def wrap_options(self, data, renderer_context):
'''Wrap OPTIONS data as JSON API meta value'''
request = renderer_context.get("request", None)
method = request and getattr(request, 'method')
if method != 'OPTIONS':
raise WrapperNotApplicable("Request method must be OPTIONS")
... | python | def wrap_options(self, data, renderer_context):
'''Wrap OPTIONS data as JSON API meta value'''
request = renderer_context.get("request", None)
method = request and getattr(request, 'method')
if method != 'OPTIONS':
raise WrapperNotApplicable("Request method must be OPTIONS")
... | [
"def",
"wrap_options",
"(",
"self",
",",
"data",
",",
"renderer_context",
")",
":",
"request",
"=",
"renderer_context",
".",
"get",
"(",
"\"request\"",
",",
"None",
")",
"method",
"=",
"request",
"and",
"getattr",
"(",
"request",
",",
"'method'",
")",
"if"... | Wrap OPTIONS data as JSON API meta value | [
"Wrap",
"OPTIONS",
"data",
"as",
"JSON",
"API",
"meta",
"value"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L249-L258 | train | Wrap OPTIONS data as JSON API meta value |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.wrap_paginated | def wrap_paginated(self, data, renderer_context):
"""Convert paginated data to JSON API with meta"""
pagination_keys = ['count', 'next', 'previous', 'results']
for key in pagination_keys:
if not (data and key in data):
raise WrapperNotApplicable('Not paginated result... | python | def wrap_paginated(self, data, renderer_context):
"""Convert paginated data to JSON API with meta"""
pagination_keys = ['count', 'next', 'previous', 'results']
for key in pagination_keys:
if not (data and key in data):
raise WrapperNotApplicable('Not paginated result... | [
"def",
"wrap_paginated",
"(",
"self",
",",
"data",
",",
"renderer_context",
")",
":",
"pagination_keys",
"=",
"[",
"'count'",
",",
"'next'",
",",
"'previous'",
",",
"'results'",
"]",
"for",
"key",
"in",
"pagination_keys",
":",
"if",
"not",
"(",
"data",
"an... | Convert paginated data to JSON API with meta | [
"Convert",
"paginated",
"data",
"to",
"JSON",
"API",
"with",
"meta"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L260-L298 | train | Convert paginated data to JSON API with meta |
kevin-brown/drf-json-api | rest_framework_json_api/renderers.py | JsonApiMixin.wrap_default | def wrap_default(self, data, renderer_context):
"""Convert native data to a JSON API resource collection
This wrapper expects a standard DRF data object (a dict-like
object with a `fields` dict-like attribute), or a list of
such data objects.
"""
wrapper = self.dict_cla... | python | def wrap_default(self, data, renderer_context):
"""Convert native data to a JSON API resource collection
This wrapper expects a standard DRF data object (a dict-like
object with a `fields` dict-like attribute), or a list of
such data objects.
"""
wrapper = self.dict_cla... | [
"def",
"wrap_default",
"(",
"self",
",",
"data",
",",
"renderer_context",
")",
":",
"wrapper",
"=",
"self",
".",
"dict_class",
"(",
")",
"view",
"=",
"renderer_context",
".",
"get",
"(",
"\"view\"",
",",
"None",
")",
"request",
"=",
"renderer_context",
"."... | Convert native data to a JSON API resource collection
This wrapper expects a standard DRF data object (a dict-like
object with a `fields` dict-like attribute), or a list of
such data objects. | [
"Convert",
"native",
"data",
"to",
"a",
"JSON",
"API",
"resource",
"collection"
] | 664643bd02c0d92eadbd1f8c9d8507adf0538df6 | https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L300-L355 | train | Convert native data to a JSON API resource collection |
jaraco/jaraco.mongodb | jaraco/mongodb/sessions.py | Session._make_local | def _make_local(utc_datetime):
"""
For a naive utc_datetime, return the same time in the local timezone
(also naive).
"""
return utc_datetime.replace(
tzinfo=dateutil.tz.tzutc()
).astimezone(dateutil.tz.tzlocal()).replace(
tzinfo=None
) | python | def _make_local(utc_datetime):
"""
For a naive utc_datetime, return the same time in the local timezone
(also naive).
"""
return utc_datetime.replace(
tzinfo=dateutil.tz.tzutc()
).astimezone(dateutil.tz.tzlocal()).replace(
tzinfo=None
) | [
"def",
"_make_local",
"(",
"utc_datetime",
")",
":",
"return",
"utc_datetime",
".",
"replace",
"(",
"tzinfo",
"=",
"dateutil",
".",
"tz",
".",
"tzutc",
"(",
")",
")",
".",
"astimezone",
"(",
"dateutil",
".",
"tz",
".",
"tzlocal",
"(",
")",
")",
".",
... | For a naive utc_datetime, return the same time in the local timezone
(also naive). | [
"For",
"a",
"naive",
"utc_datetime",
"return",
"the",
"same",
"time",
"in",
"the",
"local",
"timezone",
"(",
"also",
"naive",
")",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/sessions.py#L138-L147 | train | Make a naive utc_datetime return the same time in the local timezone
( also naive. |
jaraco/jaraco.mongodb | jaraco/mongodb/sessions.py | Session.acquire_lock | def acquire_lock(self):
"""
Acquire the lock. Blocks indefinitely until lock is available
unless `lock_timeout` was supplied. If the lock_timeout elapses,
raises LockTimeout.
"""
# first ensure that a record exists for this session id
try:
self.collection.insert_one(dict(_id=self.id))
except pymongo.... | python | def acquire_lock(self):
"""
Acquire the lock. Blocks indefinitely until lock is available
unless `lock_timeout` was supplied. If the lock_timeout elapses,
raises LockTimeout.
"""
# first ensure that a record exists for this session id
try:
self.collection.insert_one(dict(_id=self.id))
except pymongo.... | [
"def",
"acquire_lock",
"(",
"self",
")",
":",
"# first ensure that a record exists for this session id",
"try",
":",
"self",
".",
"collection",
".",
"insert_one",
"(",
"dict",
"(",
"_id",
"=",
"self",
".",
"id",
")",
")",
"except",
"pymongo",
".",
"errors",
".... | Acquire the lock. Blocks indefinitely until lock is available
unless `lock_timeout` was supplied. If the lock_timeout elapses,
raises LockTimeout. | [
"Acquire",
"the",
"lock",
".",
"Blocks",
"indefinitely",
"until",
"lock",
"is",
"available",
"unless",
"lock_timeout",
"was",
"supplied",
".",
"If",
"the",
"lock_timeout",
"elapses",
"raises",
"LockTimeout",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/sessions.py#L172-L198 | train | Acquires the lock. Blocks indefinitely until the lock is available. |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.doublec | def doublec(self, j):
"""doublec(j) is TRUE <=> j,(j-1) contain a double consonant."""
if j < (self.k0 + 1):
return 0
if self.b[j] != self.b[j - 1]:
return 0
return self.cons(j) | python | def doublec(self, j):
"""doublec(j) is TRUE <=> j,(j-1) contain a double consonant."""
if j < (self.k0 + 1):
return 0
if self.b[j] != self.b[j - 1]:
return 0
return self.cons(j) | [
"def",
"doublec",
"(",
"self",
",",
"j",
")",
":",
"if",
"j",
"<",
"(",
"self",
".",
"k0",
"+",
"1",
")",
":",
"return",
"0",
"if",
"self",
".",
"b",
"[",
"j",
"]",
"!=",
"self",
".",
"b",
"[",
"j",
"-",
"1",
"]",
":",
"return",
"0",
"r... | doublec(j) is TRUE <=> j,(j-1) contain a double consonant. | [
"doublec",
"(",
"j",
")",
"is",
"TRUE",
"<",
"=",
">",
"j",
"(",
"j",
"-",
"1",
")",
"contain",
"a",
"double",
"consonant",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L123-L129 | train | is TRUE <= > j contain a double consonant. |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.cvc | def cvc(self, i):
"""cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
"""
... | python | def cvc(self, i):
"""cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
"""
... | [
"def",
"cvc",
"(",
"self",
",",
"i",
")",
":",
"if",
"(",
"i",
"<",
"(",
"self",
".",
"k0",
"+",
"2",
")",
"or",
"not",
"self",
".",
"cons",
"(",
"i",
")",
"or",
"self",
".",
"cons",
"(",
"i",
"-",
"1",
")",
"or",
"not",
"self",
".",
"c... | cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray. | [
"cvc",
"(",
"i",
")",
"is",
"TRUE",
"<",
"=",
">",
"i",
"-",
"2",
"i",
"-",
"1",
"i",
"has",
"the",
"form",
"consonant",
"-",
"vowel",
"-",
"consonant",
"and",
"also",
"if",
"the",
"second",
"c",
"is",
"not",
"w",
"x",
"or",
"y",
".",
"this",... | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L131-L149 | train | cvc returns 1 if i is TRUE > = i - 2 i is not TRUE <= > i - 1 i is not TRUE <= > i - 2 i is not TRUE <= > i - 1 i is not TRUE <= > i - 1 i is not TRUE <= > i - 2 i is not TRUE <= > i - 1 i is not TRUE <= > i - 1 i is not TRUE <= > i - 2 i is not TRUE <= > i - 1 i is not TRUE <= > i - 1 |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.ends | def ends(self, s):
"""ends(s) is TRUE <=> k0,...k ends with the string s."""
length = len(s)
if s[length - 1] != self.b[self.k]: # tiny speed-up
return 0
if length > (self.k - self.k0 + 1):
return 0
if self.b[self.k - length + 1 : self.k + 1] != s:
... | python | def ends(self, s):
"""ends(s) is TRUE <=> k0,...k ends with the string s."""
length = len(s)
if s[length - 1] != self.b[self.k]: # tiny speed-up
return 0
if length > (self.k - self.k0 + 1):
return 0
if self.b[self.k - length + 1 : self.k + 1] != s:
... | [
"def",
"ends",
"(",
"self",
",",
"s",
")",
":",
"length",
"=",
"len",
"(",
"s",
")",
"if",
"s",
"[",
"length",
"-",
"1",
"]",
"!=",
"self",
".",
"b",
"[",
"self",
".",
"k",
"]",
":",
"# tiny speed-up",
"return",
"0",
"if",
"length",
">",
"(",... | ends(s) is TRUE <=> k0,...k ends with the string s. | [
"ends",
"(",
"s",
")",
"is",
"TRUE",
"<",
"=",
">",
"k0",
"...",
"k",
"ends",
"with",
"the",
"string",
"s",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L151-L161 | train | ends is TRUE <= > k0... k ends with the string s. |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.step1ab | def step1ab(self):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> ... | python | def step1ab(self):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> ... | [
"def",
"step1ab",
"(",
"self",
")",
":",
"if",
"self",
".",
"b",
"[",
"self",
".",
"k",
"]",
"==",
"\"s\"",
":",
"if",
"self",
".",
"ends",
"(",
"\"sses\"",
")",
":",
"self",
".",
"k",
"=",
"self",
".",
"k",
"-",
"2",
"elif",
"self",
".",
"... | step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting ... | [
"step1ab",
"()",
"gets",
"rid",
"of",
"plurals",
"and",
"-",
"ed",
"or",
"-",
"ing",
".",
"e",
".",
"g",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L174-L219 | train | This method gets rid of plurals and - ed or - ing and - eed and - s and - eed and - s and - eed and - s and - s. e. g. the cvc is not the same as the cvc. |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.step1c | def step1c(self):
"""step1c() turns terminal y to i when there is another vowel in the stem."""
if self.ends("y") and self.vowelinstem():
self.b = self.b[: self.k] + "i" + self.b[self.k + 1 :] | python | def step1c(self):
"""step1c() turns terminal y to i when there is another vowel in the stem."""
if self.ends("y") and self.vowelinstem():
self.b = self.b[: self.k] + "i" + self.b[self.k + 1 :] | [
"def",
"step1c",
"(",
"self",
")",
":",
"if",
"self",
".",
"ends",
"(",
"\"y\"",
")",
"and",
"self",
".",
"vowelinstem",
"(",
")",
":",
"self",
".",
"b",
"=",
"self",
".",
"b",
"[",
":",
"self",
".",
"k",
"]",
"+",
"\"i\"",
"+",
"self",
".",
... | step1c() turns terminal y to i when there is another vowel in the stem. | [
"step1c",
"()",
"turns",
"terminal",
"y",
"to",
"i",
"when",
"there",
"is",
"another",
"vowel",
"in",
"the",
"stem",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L221-L224 | train | step 1 c turns terminal y to i when there is another vowel in the stem. |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.step2 | def step2(self):
"""step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0.
"""
if self.b[self.k - 1] == "a":
if self.ends("ational"):
self.r("ate")
... | python | def step2(self):
"""step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0.
"""
if self.b[self.k - 1] == "a":
if self.ends("ational"):
self.r("ate")
... | [
"def",
"step2",
"(",
"self",
")",
":",
"if",
"self",
".",
"b",
"[",
"self",
".",
"k",
"-",
"1",
"]",
"==",
"\"a\"",
":",
"if",
"self",
".",
"ends",
"(",
"\"ational\"",
")",
":",
"self",
".",
"r",
"(",
"\"ate\"",
")",
"elif",
"self",
".",
"end... | step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0. | [
"step2",
"()",
"maps",
"double",
"suffices",
"to",
"single",
"ones",
".",
"so",
"-",
"ization",
"(",
"=",
"-",
"ize",
"plus",
"-",
"ation",
")",
"maps",
"to",
"-",
"ize",
"etc",
".",
"note",
"that",
"the",
"string",
"before",
"the",
"suffix",
"must",... | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L226-L282 | train | This function maps double suffices to single ones. It maps single suffices to single ones. It maps double suffices to single ones. |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.step5 | def step5(self):
"""step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1.
"""
self.j = self.k
if self.b[self.k] == "e":
a = self.m()
if a > 1 or (a == 1 and not self.cvc(self.k - 1)):
self.k = self.k - 1
if self.b... | python | def step5(self):
"""step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1.
"""
self.j = self.k
if self.b[self.k] == "e":
a = self.m()
if a > 1 or (a == 1 and not self.cvc(self.k - 1)):
self.k = self.k - 1
if self.b... | [
"def",
"step5",
"(",
"self",
")",
":",
"self",
".",
"j",
"=",
"self",
".",
"k",
"if",
"self",
".",
"b",
"[",
"self",
".",
"k",
"]",
"==",
"\"e\"",
":",
"a",
"=",
"self",
".",
"m",
"(",
")",
"if",
"a",
">",
"1",
"or",
"(",
"a",
"==",
"1"... | step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1. | [
"step5",
"()",
"removes",
"a",
"final",
"-",
"e",
"if",
"m",
"()",
">",
"1",
"and",
"changes",
"-",
"ll",
"to",
"-",
"l",
"if",
"m",
"()",
">",
"1",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L388-L398 | train | Remove a final - e if m > 1 and changes - ll to - l if m > 1 and changes - ll to - l if m > 1 and changes - ll to - l if m > 1 and changes - ll to - l if m > 1 and changes - ll to - l if m > 1 and changes - ll to - l if m > 1 and changes - ll to - l if m > 1 and changes - ll to - l if m > 1 and m > 1. |
yeraydiazdiaz/lunr.py | lunr/stemmer.py | PorterStemmer.stem | def stem(self, p, metadata=None):
"""In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == '\0'). The
stemmer adjusts the characters p[i] ... p[j] and returns... | python | def stem(self, p, metadata=None):
"""In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == '\0'). The
stemmer adjusts the characters p[i] ... p[j] and returns... | [
"def",
"stem",
"(",
"self",
",",
"p",
",",
"metadata",
"=",
"None",
")",
":",
"# TODO: removed i and j from the original implementation",
"# to comply with the `token.update` API",
"i",
"=",
"0",
"j",
"=",
"len",
"(",
"p",
")",
"-",
"1",
"# copy the parameters into ... | In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == '\0'). The
stemmer adjusts the characters p[i] ... p[j] and returns the new
end-point of the string, k. ... | [
"In",
"stem",
"(",
"p",
"i",
"j",
")",
"p",
"is",
"a",
"char",
"pointer",
"and",
"the",
"string",
"to",
"be",
"stemmed",
"is",
"from",
"p",
"[",
"i",
"]",
"to",
"p",
"[",
"j",
"]",
"inclusive",
".",
"Typically",
"i",
"is",
"zero",
"and",
"j",
... | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stemmer.py#L400-L431 | train | In stem ( p i j ) returns the stemmed version of the string. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/utils/management.py | BootDeviceHelper.set_boot_device | def set_boot_device(self, device, persistent=False):
"""Set the boot device for the node.
Set the boot device to use on next reboot of the node.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if th... | python | def set_boot_device(self, device, persistent=False):
"""Set the boot device for the node.
Set the boot device to use on next reboot of the node.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if th... | [
"def",
"set_boot_device",
"(",
"self",
",",
"device",
",",
"persistent",
"=",
"False",
")",
":",
"operation",
"=",
"\"set_boot_device\"",
"try",
":",
"self",
".",
"sp_manager",
".",
"create_boot_policy",
"(",
")",
"self",
".",
"sp_manager",
".",
"set_boot_devi... | Set the boot device for the node.
Set the boot device to use on next reboot of the node.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if the boot device will
persist to all future boots, ... | [
"Set",
"the",
"boot",
"device",
"for",
"the",
"node",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/utils/management.py#L39-L57 | train | Set the boot device for the node. |
CiscoUcs/UcsPythonSDK | src/UcsSdk/utils/management.py | BootDeviceHelper.get_boot_device | def get_boot_device(self):
"""Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:raises: ... | python | def get_boot_device(self):
"""Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:raises: ... | [
"def",
"get_boot_device",
"(",
"self",
")",
":",
"operation",
"=",
"'get_boot_device'",
"try",
":",
"boot_device",
"=",
"self",
".",
"sp_manager",
".",
"get_boot_device",
"(",
")",
"return",
"boot_device",
"except",
"UcsException",
"as",
"ex",
":",
"print",
"(... | Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:raises: MissingParameterValue if a required pa... | [
"Get",
"the",
"current",
"boot",
"device",
"for",
"the",
"node",
"."
] | bf6b07d6abeacb922c92b198352eda4eb9e4629b | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/utils/management.py#L59-L81 | train | Get the current boot device for the node. |
yeraydiazdiaz/lunr.py | lunr/__main__.py | lunr | def lunr(ref, fields, documents, languages=None):
"""A convenience function to configure and construct a lunr.Index.
Args:
ref (str): The key in the documents to be used a the reference.
fields (list): A list of strings defining fields in the documents to
index. Optionally a list of... | python | def lunr(ref, fields, documents, languages=None):
"""A convenience function to configure and construct a lunr.Index.
Args:
ref (str): The key in the documents to be used a the reference.
fields (list): A list of strings defining fields in the documents to
index. Optionally a list of... | [
"def",
"lunr",
"(",
"ref",
",",
"fields",
",",
"documents",
",",
"languages",
"=",
"None",
")",
":",
"if",
"languages",
"is",
"not",
"None",
"and",
"lang",
".",
"LANGUAGE_SUPPORT",
":",
"if",
"isinstance",
"(",
"languages",
",",
"basestring",
")",
":",
... | A convenience function to configure and construct a lunr.Index.
Args:
ref (str): The key in the documents to be used a the reference.
fields (list): A list of strings defining fields in the documents to
index. Optionally a list of dictionaries with three keys:
`field_name` d... | [
"A",
"convenience",
"function",
"to",
"configure",
"and",
"construct",
"a",
"lunr",
".",
"Index",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/__main__.py#L13-L65 | train | A convenience function to configure and construct a lunr. Index. |
JensRantil/rewind | rewind/server/eventstores.py | _KeyValuePersister._actually_populate_keyvals | def _actually_populate_keyvals(filename):
"""Return a dictionary containing the key/values read from filename.
Raises IOError if the file does not exit etcetera.
"""
assert isinstance(filename, str)
keyvals = {}
with open(filename, 'r') as f:
for line in f:
... | python | def _actually_populate_keyvals(filename):
"""Return a dictionary containing the key/values read from filename.
Raises IOError if the file does not exit etcetera.
"""
assert isinstance(filename, str)
keyvals = {}
with open(filename, 'r') as f:
for line in f:
... | [
"def",
"_actually_populate_keyvals",
"(",
"filename",
")",
":",
"assert",
"isinstance",
"(",
"filename",
",",
"str",
")",
"keyvals",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",... | Return a dictionary containing the key/values read from filename.
Raises IOError if the file does not exit etcetera. | [
"Return",
"a",
"dictionary",
"containing",
"the",
"key",
"/",
"values",
"read",
"from",
"filename",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L76-L92 | train | Return a dictionary containing the key and value pairs read from filename. Raises IOError if the file does not exit etcetera. |
JensRantil/rewind | rewind/server/eventstores.py | _KeyValuePersister._read_keyvals | def _read_keyvals(filename):
"""Read the key/values if the file exists.
returns -- a dictionary with key/values, or empty dictionary if the
file does not exist.
"""
assert isinstance(filename, str)
if os.path.exists(filename):
return _KeyValuePers... | python | def _read_keyvals(filename):
"""Read the key/values if the file exists.
returns -- a dictionary with key/values, or empty dictionary if the
file does not exist.
"""
assert isinstance(filename, str)
if os.path.exists(filename):
return _KeyValuePers... | [
"def",
"_read_keyvals",
"(",
"filename",
")",
":",
"assert",
"isinstance",
"(",
"filename",
",",
"str",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"_KeyValuePersister",
".",
"_actually_populate_keyvals",
"(",
"filename",
... | Read the key/values if the file exists.
returns -- a dictionary with key/values, or empty dictionary if the
file does not exist. | [
"Read",
"the",
"key",
"/",
"values",
"if",
"the",
"file",
"exists",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L95-L106 | train | Read the key - value pairs from the file. |
JensRantil/rewind | rewind/server/eventstores.py | InMemoryEventStore.add_event | def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
if key in self.keys or key in self.events:
raise EventStore.EventKeyAlreadyExistError(
"The key already existed: {0}".format(key))
self.keys.append(key)
# Important no ... | python | def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
if key in self.keys or key in self.events:
raise EventStore.EventKeyAlreadyExistError(
"The key already existed: {0}".format(key))
self.keys.append(key)
# Important no ... | [
"def",
"add_event",
"(",
"self",
",",
"key",
",",
"event",
")",
":",
"if",
"key",
"in",
"self",
".",
"keys",
"or",
"key",
"in",
"self",
".",
"events",
":",
"raise",
"EventStore",
".",
"EventKeyAlreadyExistError",
"(",
"\"The key already existed: {0}\"",
".",... | Add an event and its corresponding key to the store. | [
"Add",
"an",
"event",
"and",
"its",
"corresponding",
"key",
"to",
"the",
"store",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L318-L325 | train | Add an event and its corresponding key to the store. |
JensRantil/rewind | rewind/server/eventstores.py | InMemoryEventStore.get_events | def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Parameters:
from_ -- if not None, return only events added after the event with
id `from_`. If None, return from the start of history.... | python | def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Parameters:
from_ -- if not None, return only events added after the event with
id `from_`. If None, return from the start of history.... | [
"def",
"get_events",
"(",
"self",
",",
"from_",
"=",
"None",
",",
"to",
"=",
"None",
")",
":",
"if",
"from_",
"and",
"(",
"from_",
"not",
"in",
"self",
".",
"keys",
"or",
"from_",
"not",
"in",
"self",
".",
"events",
")",
":",
"raise",
"EventStore",... | Query a slice of the events.
Events are always returned in the order the were added.
Parameters:
from_ -- if not None, return only events added after the event with
id `from_`. If None, return from the start of history.
to -- if not None, return only events ad... | [
"Query",
"a",
"slice",
"of",
"the",
"events",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L327-L360 | train | Query a slice of the events. |
JensRantil/rewind | rewind/server/eventstores.py | SQLiteEventStore.from_config | def from_config(_config, **options):
"""Instantiate an SQLite event store from config.
Parameters:
_config -- the configuration file options read from file(s). Not
used.
**options -- various options given to the specific event store. Shall
not... | python | def from_config(_config, **options):
"""Instantiate an SQLite event store from config.
Parameters:
_config -- the configuration file options read from file(s). Not
used.
**options -- various options given to the specific event store. Shall
not... | [
"def",
"from_config",
"(",
"_config",
",",
"*",
"*",
"options",
")",
":",
"expected_args",
"=",
"(",
"'path'",
",",
")",
"rconfig",
".",
"check_config_options",
"(",
"\"SQLiteEventStore\"",
",",
"expected_args",
",",
"tuple",
"(",
")",
",",
"options",
")",
... | Instantiate an SQLite event store from config.
Parameters:
_config -- the configuration file options read from file(s). Not
used.
**options -- various options given to the specific event store. Shall
not be used with this event store. Warning will be ... | [
"Instantiate",
"an",
"SQLite",
"event",
"store",
"from",
"config",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L407-L424 | train | Instantiate an SQLite event store from a configuration file. |
JensRantil/rewind | rewind/server/eventstores.py | SQLiteEventStore.add_event | def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
assert isinstance(key, str)
assert isinstance(event, bytes)
self.conn.execute('INSERT INTO events(uuid,event) VALUES (?,?)',
(key, event.decode('utf-8'))) | python | def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
assert isinstance(key, str)
assert isinstance(event, bytes)
self.conn.execute('INSERT INTO events(uuid,event) VALUES (?,?)',
(key, event.decode('utf-8'))) | [
"def",
"add_event",
"(",
"self",
",",
"key",
",",
"event",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"assert",
"isinstance",
"(",
"event",
",",
"bytes",
")",
"self",
".",
"conn",
".",
"execute",
"(",
"'INSERT INTO events(uuid,event) VA... | Add an event and its corresponding key to the store. | [
"Add",
"an",
"event",
"and",
"its",
"corresponding",
"key",
"to",
"the",
"store",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L426-L431 | train | Add an event and its corresponding key to the store. |
JensRantil/rewind | rewind/server/eventstores.py | SQLiteEventStore.get_events | def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Parameters:
from_ -- if not None, return only events added after the event with
id `from_`. If None, return from the start of history.... | python | def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Parameters:
from_ -- if not None, return only events added after the event with
id `from_`. If None, return from the start of history.... | [
"def",
"get_events",
"(",
"self",
",",
"from_",
"=",
"None",
",",
"to",
"=",
"None",
")",
":",
"assert",
"from_",
"is",
"None",
"or",
"isinstance",
"(",
"from_",
",",
"str",
")",
"assert",
"to",
"is",
"None",
"or",
"isinstance",
"(",
"to",
",",
"st... | Query a slice of the events.
Events are always returned in the order the were added.
Parameters:
from_ -- if not None, return only events added after the event with
id `from_`. If None, return from the start of history.
to -- if not None, return only events ad... | [
"Query",
"a",
"slice",
"of",
"the",
"events",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L433-L473 | train | Query a slice of the events. |
JensRantil/rewind | rewind/server/eventstores.py | SQLiteEventStore.key_exists | def key_exists(self, key):
"""Check whether a key exists in the event store.
Returns True if it does, False otherwise.
"""
assert isinstance(key, str)
cursor = self.conn.cursor()
with contextlib.closing(cursor):
cursor.execute('SELECT COUNT(*) FROM events WH... | python | def key_exists(self, key):
"""Check whether a key exists in the event store.
Returns True if it does, False otherwise.
"""
assert isinstance(key, str)
cursor = self.conn.cursor()
with contextlib.closing(cursor):
cursor.execute('SELECT COUNT(*) FROM events WH... | [
"def",
"key_exists",
"(",
"self",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"with",
"contextlib",
".",
"closing",
"(",
"cursor",
")",
":",
"cursor",
".",
... | Check whether a key exists in the event store.
Returns True if it does, False otherwise. | [
"Check",
"whether",
"a",
"key",
"exists",
"in",
"the",
"event",
"store",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L483-L500 | train | Check whether a key exists in the event store. Returns True if it does False otherwise. |
JensRantil/rewind | rewind/server/eventstores.py | SQLiteEventStore.count | def count(self):
"""Return the number of events in the db."""
cursor = self.conn.cursor()
with contextlib.closing(cursor):
cursor.execute('SELECT COUNT(*) FROM events')
res = cursor.fetchone()
return res[0] | python | def count(self):
"""Return the number of events in the db."""
cursor = self.conn.cursor()
with contextlib.closing(cursor):
cursor.execute('SELECT COUNT(*) FROM events')
res = cursor.fetchone()
return res[0] | [
"def",
"count",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"with",
"contextlib",
".",
"closing",
"(",
"cursor",
")",
":",
"cursor",
".",
"execute",
"(",
"'SELECT COUNT(*) FROM events'",
")",
"res",
"=",
"cursor",
... | Return the number of events in the db. | [
"Return",
"the",
"number",
"of",
"events",
"in",
"the",
"db",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L502-L508 | train | Return the number of events in the db. |
JensRantil/rewind | rewind/server/eventstores.py | SQLiteEventStore.close | def close(self):
"""Close the event store.
Important to close to not have any file descriptor leakages.
"""
if self.conn:
self.conn.close()
self.conn = None
fname = os.path.basename(self._path)
checksum_persister = _get_checksum_persister(self._... | python | def close(self):
"""Close the event store.
Important to close to not have any file descriptor leakages.
"""
if self.conn:
self.conn.close()
self.conn = None
fname = os.path.basename(self._path)
checksum_persister = _get_checksum_persister(self._... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"conn",
":",
"self",
".",
"conn",
".",
"close",
"(",
")",
"self",
".",
"conn",
"=",
"None",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"_path",
")",
"checksum_pers... | Close the event store.
Important to close to not have any file descriptor leakages. | [
"Close",
"the",
"event",
"store",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L510-L524 | train | Close the event store. |
JensRantil/rewind | rewind/server/eventstores.py | LogEventStore.from_config | def from_config(config, **options):
"""Instantiate an `LogEventStore` from config.
Parameters:
_config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store. Wa... | python | def from_config(config, **options):
"""Instantiate an `LogEventStore` from config.
Parameters:
_config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store. Wa... | [
"def",
"from_config",
"(",
"config",
",",
"*",
"*",
"options",
")",
":",
"expected_args",
"=",
"(",
"'path'",
",",
")",
"rconfig",
".",
"check_config_options",
"(",
"\"LogEventStore\"",
",",
"expected_args",
",",
"tuple",
"(",
")",
",",
"options",
")",
"re... | Instantiate an `LogEventStore` from config.
Parameters:
_config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store. Warning will be logged
for e... | [
"Instantiate",
"an",
"LogEventStore",
"from",
"config",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L549-L565 | train | Instantiate an LogEventStore from a configuration file. |
JensRantil/rewind | rewind/server/eventstores.py | LogEventStore.add_event | def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
assert isinstance(key, str)
assert isinstance(event, bytes)
if all([char.isalnum() or char == '-' for char in key]):
safe_key = key
else:
raise ValueError("Key must... | python | def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
assert isinstance(key, str)
assert isinstance(event, bytes)
if all([char.isalnum() or char == '-' for char in key]):
safe_key = key
else:
raise ValueError("Key must... | [
"def",
"add_event",
"(",
"self",
",",
"key",
",",
"event",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"assert",
"isinstance",
"(",
"event",
",",
"bytes",
")",
"if",
"all",
"(",
"[",
"char",
".",
"isalnum",
"(",
")",
"or",
"char"... | Add an event and its corresponding key to the store. | [
"Add",
"an",
"event",
"and",
"its",
"corresponding",
"key",
"to",
"the",
"store",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L575-L589 | train | Add an event and its corresponding key to the store. |
JensRantil/rewind | rewind/server/eventstores.py | LogEventStore.get_events | def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Does never throw EventOrderError because it is hard to detect
from an append-only file.
Parameters:
from_ -- if not None, return only ev... | python | def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Does never throw EventOrderError because it is hard to detect
from an append-only file.
Parameters:
from_ -- if not None, return only ev... | [
"def",
"get_events",
"(",
"self",
",",
"from_",
"=",
"None",
",",
"to",
"=",
"None",
")",
":",
"assert",
"from_",
"is",
"None",
"or",
"isinstance",
"(",
"from_",
",",
"str",
")",
"assert",
"to",
"is",
"None",
"or",
"isinstance",
"(",
"to",
",",
"st... | Query a slice of the events.
Events are always returned in the order the were added.
Does never throw EventOrderError because it is hard to detect
from an append-only file.
Parameters:
from_ -- if not None, return only events added after the event with
id ... | [
"Query",
"a",
"slice",
"of",
"the",
"events",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L621-L645 | train | Query a slice of the events. |
JensRantil/rewind | rewind/server/eventstores.py | LogEventStore.key_exists | def key_exists(self, key):
"""Check if key has previously been added to this store.
This function makes a linear search through the log file and is very
slow.
Returns True if the event has previously been added, False otherwise.
"""
assert isinstance(key, str)
... | python | def key_exists(self, key):
"""Check if key has previously been added to this store.
This function makes a linear search through the log file and is very
slow.
Returns True if the event has previously been added, False otherwise.
"""
assert isinstance(key, str)
... | [
"def",
"key_exists",
"(",
"self",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"self",
".",
"_close",
"(",
")",
"try",
":",
"return",
"self",
".",
"_unsafe_key_exists",
"(",
"key",
")",
"finally",
":",
"self",
".",
"_ope... | Check if key has previously been added to this store.
This function makes a linear search through the log file and is very
slow.
Returns True if the event has previously been added, False otherwise. | [
"Check",
"if",
"key",
"has",
"previously",
"been",
"added",
"to",
"this",
"store",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L656-L670 | train | Check if a key exists in this store. |
JensRantil/rewind | rewind/server/eventstores.py | LogEventStore.close | def close(self):
"""Persist a checksum and close the file."""
fname = os.path.basename(self._path)
checksum_persister = _get_checksum_persister(self._path)
with contextlib.closing(checksum_persister):
checksum_persister[fname] = self._hasher.hexdigest()
self._close() | python | def close(self):
"""Persist a checksum and close the file."""
fname = os.path.basename(self._path)
checksum_persister = _get_checksum_persister(self._path)
with contextlib.closing(checksum_persister):
checksum_persister[fname] = self._hasher.hexdigest()
self._close() | [
"def",
"close",
"(",
"self",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"_path",
")",
"checksum_persister",
"=",
"_get_checksum_persister",
"(",
"self",
".",
"_path",
")",
"with",
"contextlib",
".",
"closing",
"(",
"che... | Persist a checksum and close the file. | [
"Persist",
"a",
"checksum",
"and",
"close",
"the",
"file",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L672-L679 | train | Persist a checksum and close the file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.