body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
fa77854920d96da4ede812f0b2cf9de162bc905a1c97d9785d1feebc9e00c6bf
def getcontents(self): 'Get the bracket as an array or as a single bracket.' if ((self.size == 1) or (not self.pieces)): return self.getsinglebracket() rows = [] for index in range(self.size): cell = self.getcell(index) rows.append(TaggedBit().complete([cell], 'span class="arrayrow"')) return [TaggedBit().complete(rows, 'span class="array"')]
Get the bracket as an array or as a single bracket.
Lib/site-packages/docutils/utils/math/math2html.py
getcontents
edupyter/EDUPYTER
2
python
def getcontents(self): if ((self.size == 1) or (not self.pieces)): return self.getsinglebracket() rows = [] for index in range(self.size): cell = self.getcell(index) rows.append(TaggedBit().complete([cell], 'span class="arrayrow"')) return [TaggedBit().complete(rows, 'span class="array"')]
def getcontents(self): if ((self.size == 1) or (not self.pieces)): return self.getsinglebracket() rows = [] for index in range(self.size): cell = self.getcell(index) rows.append(TaggedBit().complete([cell], 'span class="arrayrow"')) return [TaggedBit().complete(rows, 'span class="array"')]<|docstring|>Get the bracket as an array or as a single bracket.<|endoftext|>
abb5b84fd8991fa9709b1814ea2b44220c3eaf2f16afa079ce1def01f62b09f0
def getsinglebracket(self): 'Return the bracket as a single sign.' if (self.original == '.'): return [TaggedBit().constant('', 'span class="emptydot"')] return [TaggedBit().constant(self.original, 'span class="stretchy"')]
Return the bracket as a single sign.
Lib/site-packages/docutils/utils/math/math2html.py
getsinglebracket
edupyter/EDUPYTER
2
python
def getsinglebracket(self): if (self.original == '.'): return [TaggedBit().constant(, 'span class="emptydot"')] return [TaggedBit().constant(self.original, 'span class="stretchy"')]
def getsinglebracket(self): if (self.original == '.'): return [TaggedBit().constant(, 'span class="emptydot"')] return [TaggedBit().constant(self.original, 'span class="stretchy"')]<|docstring|>Return the bracket as a single sign.<|endoftext|>
4a7a9fbebaf111a444f5cc954de8761238b38d35375e3729b414f2f4cb2c5988
def parsebit(self, pos): 'Parse the array' self.output = ContentsOutput() self.add(self.factory.parsetype(WholeFormula, pos))
Parse the array
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): self.output = ContentsOutput() self.add(self.factory.parsetype(WholeFormula, pos))
def parsebit(self, pos): self.output = ContentsOutput() self.add(self.factory.parsetype(WholeFormula, pos))<|docstring|>Parse the array<|endoftext|>
81c4e433add56ea2d4523d1a6c0553e5b4a7347b22467f52fc30c10174cfbbce
def parsebit(self, pos): 'Parse a whole row' index = 0 pos.pushending(self.cellseparator, optional=True) while (not pos.finished()): cell = self.createcell(index) cell.parsebit(pos) self.add(cell) index += 1 pos.checkskip(self.cellseparator) if (len(self.contents) == 0): self.output = EmptyOutput()
Parse a whole row
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): index = 0 pos.pushending(self.cellseparator, optional=True) while (not pos.finished()): cell = self.createcell(index) cell.parsebit(pos) self.add(cell) index += 1 pos.checkskip(self.cellseparator) if (len(self.contents) == 0): self.output = EmptyOutput()
def parsebit(self, pos): index = 0 pos.pushending(self.cellseparator, optional=True) while (not pos.finished()): cell = self.createcell(index) cell.parsebit(pos) self.add(cell) index += 1 pos.checkskip(self.cellseparator) if (len(self.contents) == 0): self.output = EmptyOutput()<|docstring|>Parse a whole row<|endoftext|>
b6c89ec6d506646c0725499438c4cc182d01eb28b1cd35b5bd6a9f5d205ca920
def createcell(self, index): 'Create the cell that corresponds to the given index.' alignment = self.alignments[(index % len(self.alignments))] return self.factory.create(FormulaCell).setalignment(alignment)
Create the cell that corresponds to the given index.
Lib/site-packages/docutils/utils/math/math2html.py
createcell
edupyter/EDUPYTER
2
python
def createcell(self, index): alignment = self.alignments[(index % len(self.alignments))] return self.factory.create(FormulaCell).setalignment(alignment)
def createcell(self, index): alignment = self.alignments[(index % len(self.alignments))] return self.factory.create(FormulaCell).setalignment(alignment)<|docstring|>Create the cell that corresponds to the given index.<|endoftext|>
527e4bcebb13251c0ff71da3873d7569734eb03bad39cd026492cf7b2916e588
def parserows(self, pos): 'Parse all rows, finish when no more row ends' self.rows = [] first = True for row in self.iteraterows(pos): if first: first = False else: self.addempty() row.parsebit(pos) self.addrow(row) self.size = len(self.rows)
Parse all rows, finish when no more row ends
Lib/site-packages/docutils/utils/math/math2html.py
parserows
edupyter/EDUPYTER
2
python
def parserows(self, pos): self.rows = [] first = True for row in self.iteraterows(pos): if first: first = False else: self.addempty() row.parsebit(pos) self.addrow(row) self.size = len(self.rows)
def parserows(self, pos): self.rows = [] first = True for row in self.iteraterows(pos): if first: first = False else: self.addempty() row.parsebit(pos) self.addrow(row) self.size = len(self.rows)<|docstring|>Parse all rows, finish when no more row ends<|endoftext|>
ea2d2408da652425b3214c6e16f4c0d94c86979a5cd541c6263ee3fc73bebd28
def iteraterows(self, pos): 'Iterate over all rows, end when no more row ends' rowseparator = FormulaConfig.array['rowseparator'] while True: pos.pushending(rowseparator, True) row = self.factory.create(FormulaRow) (yield row.setalignments(self.alignments)) if pos.checkfor(rowseparator): self.original += pos.popending(rowseparator) else: return
Iterate over all rows, end when no more row ends
Lib/site-packages/docutils/utils/math/math2html.py
iteraterows
edupyter/EDUPYTER
2
python
def iteraterows(self, pos): rowseparator = FormulaConfig.array['rowseparator'] while True: pos.pushending(rowseparator, True) row = self.factory.create(FormulaRow) (yield row.setalignments(self.alignments)) if pos.checkfor(rowseparator): self.original += pos.popending(rowseparator) else: return
def iteraterows(self, pos): rowseparator = FormulaConfig.array['rowseparator'] while True: pos.pushending(rowseparator, True) row = self.factory.create(FormulaRow) (yield row.setalignments(self.alignments)) if pos.checkfor(rowseparator): self.original += pos.popending(rowseparator) else: return<|docstring|>Iterate over all rows, end when no more row ends<|endoftext|>
61f8df7d274b8681ad98eb55c20ada9a0ec6a3b2272eb815b34bde7e631bfb7d
def addempty(self): 'Add an empty row.' row = self.factory.create(FormulaRow).setalignments(self.alignments) for (index, originalcell) in enumerate(self.rows[(- 1)].contents): cell = row.createcell(index) cell.add(FormulaConstant(u'\u2005')) row.add(cell) self.addrow(row)
Add an empty row.
Lib/site-packages/docutils/utils/math/math2html.py
addempty
edupyter/EDUPYTER
2
python
def addempty(self): row = self.factory.create(FormulaRow).setalignments(self.alignments) for (index, originalcell) in enumerate(self.rows[(- 1)].contents): cell = row.createcell(index) cell.add(FormulaConstant(u'\u2005')) row.add(cell) self.addrow(row)
def addempty(self): row = self.factory.create(FormulaRow).setalignments(self.alignments) for (index, originalcell) in enumerate(self.rows[(- 1)].contents): cell = row.createcell(index) cell.add(FormulaConstant(u'\u2005')) row.add(cell) self.addrow(row)<|docstring|>Add an empty row.<|endoftext|>
ea1ffd35cdcf1f25e233a7f5621bd84caece79653ecc2b3e13271c0211afb9c9
def addrow(self, row): 'Add a row to the contents and to the list of rows.' self.rows.append(row) self.add(row)
Add a row to the contents and to the list of rows.
Lib/site-packages/docutils/utils/math/math2html.py
addrow
edupyter/EDUPYTER
2
python
def addrow(self, row): self.rows.append(row) self.add(row)
def addrow(self, row): self.rows.append(row) self.add(row)<|docstring|>Add a row to the contents and to the list of rows.<|endoftext|>
aee215065099cca2ecd5f3ba3bcefb9f24092ab0a499406b924757ca49a3d028
def parsebit(self, pos): 'Parse the array' self.output = TaggedOutput().settag('span class="array"', False) self.parsealignments(pos) self.parserows(pos)
Parse the array
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="array"', False) self.parsealignments(pos) self.parserows(pos)
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="array"', False) self.parsealignments(pos) self.parserows(pos)<|docstring|>Parse the array<|endoftext|>
41015fda8fd919a0acf0e4b0c3eccbac4eb18f76643df8e7563a965f65024626
def parsealignments(self, pos): 'Parse the different alignments' self.valign = 'c' literal = self.parsesquareliteral(pos) if literal: self.valign = literal literal = self.parseliteral(pos) self.alignments = [] for l in literal: self.alignments.append(l)
Parse the different alignments
Lib/site-packages/docutils/utils/math/math2html.py
parsealignments
edupyter/EDUPYTER
2
python
def parsealignments(self, pos): self.valign = 'c' literal = self.parsesquareliteral(pos) if literal: self.valign = literal literal = self.parseliteral(pos) self.alignments = [] for l in literal: self.alignments.append(l)
def parsealignments(self, pos): self.valign = 'c' literal = self.parsesquareliteral(pos) if literal: self.valign = literal literal = self.parseliteral(pos) self.alignments = [] for l in literal: self.alignments.append(l)<|docstring|>Parse the different alignments<|endoftext|>
a5c6317765348167b78dfc110af4a8c8f68e87105357e3ecb69dce34a87557ea
def parsebit(self, pos): "Parse the matrix, set alignments to 'c'." self.output = TaggedOutput().settag('span class="array"', False) self.valign = 'c' self.alignments = ['c'] self.parserows(pos)
Parse the matrix, set alignments to 'c'.
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="array"', False) self.valign = 'c' self.alignments = ['c'] self.parserows(pos)
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="array"', False) self.valign = 'c' self.alignments = ['c'] self.parserows(pos)<|docstring|>Parse the matrix, set alignments to 'c'.<|endoftext|>
c2946757580467984b715534045f378d36dc896d27bec708198cefff2b25afbb
def parsebit(self, pos): 'Parse the cases' self.output = ContentsOutput() self.alignments = ['l', 'l'] self.parserows(pos) for row in self.contents: for cell in row.contents: cell.output.settag('span class="case align-l"', True) cell.contents.append(FormulaConstant(u'\u2003')) array = TaggedBit().complete(self.contents, 'span class="bracketcases"', True) brace = BigBracket(len(self.contents), '{', 'l') self.contents = (brace.getcontents() + [array])
Parse the cases
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): self.output = ContentsOutput() self.alignments = ['l', 'l'] self.parserows(pos) for row in self.contents: for cell in row.contents: cell.output.settag('span class="case align-l"', True) cell.contents.append(FormulaConstant(u'\u2003')) array = TaggedBit().complete(self.contents, 'span class="bracketcases"', True) brace = BigBracket(len(self.contents), '{', 'l') self.contents = (brace.getcontents() + [array])
def parsebit(self, pos): self.output = ContentsOutput() self.alignments = ['l', 'l'] self.parserows(pos) for row in self.contents: for cell in row.contents: cell.output.settag('span class="case align-l"', True) cell.contents.append(FormulaConstant(u'\u2003')) array = TaggedBit().complete(self.contents, 'span class="bracketcases"', True) brace = BigBracket(len(self.contents), '{', 'l') self.contents = (brace.getcontents() + [array])<|docstring|>Parse the cases<|endoftext|>
5cb4ba2803f365958ca6c2f58200e8fe1b2b7929b569a3c57a1661987e95b81f
def parsebit(self, pos): 'Parse the whole environment.' environment = self.piece.replace('*', '') self.output = TaggedOutput().settag(('span class="environment %s"' % environment), False) if (environment in FormulaConfig.environments): self.alignments = FormulaConfig.environments[environment] else: Trace.error(('Unknown equation environment ' + self.piece)) self.output = TaggedOutput().settag('span class="unknown"') self.add(FormulaConstant(('\\begin{%s} ' % environment))) self.alignments = ['l'] self.parserows(pos)
Parse the whole environment.
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): environment = self.piece.replace('*', ) self.output = TaggedOutput().settag(('span class="environment %s"' % environment), False) if (environment in FormulaConfig.environments): self.alignments = FormulaConfig.environments[environment] else: Trace.error(('Unknown equation environment ' + self.piece)) self.output = TaggedOutput().settag('span class="unknown"') self.add(FormulaConstant(('\\begin{%s} ' % environment))) self.alignments = ['l'] self.parserows(pos)
def parsebit(self, pos): environment = self.piece.replace('*', ) self.output = TaggedOutput().settag(('span class="environment %s"' % environment), False) if (environment in FormulaConfig.environments): self.alignments = FormulaConfig.environments[environment] else: Trace.error(('Unknown equation environment ' + self.piece)) self.output = TaggedOutput().settag('span class="unknown"') self.add(FormulaConstant(('\\begin{%s} ' % environment))) self.alignments = ['l'] self.parserows(pos)<|docstring|>Parse the whole environment.<|endoftext|>
669b92e4b571b1b8fb1f383fd48aef15bdbb78acc1b7d713259ea4f3de84c2e8
def parsebit(self, pos): 'Parse the begin command' command = self.parseliteral(pos) bit = self.findbit(command) ending = (((FormulaConfig.array['end'] + '{') + command) + '}') pos.pushending(ending) bit.parsebit(pos) self.add(bit) self.original += pos.popending(ending) self.size = bit.size
Parse the begin command
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): command = self.parseliteral(pos) bit = self.findbit(command) ending = (((FormulaConfig.array['end'] + '{') + command) + '}') pos.pushending(ending) bit.parsebit(pos) self.add(bit) self.original += pos.popending(ending) self.size = bit.size
def parsebit(self, pos): command = self.parseliteral(pos) bit = self.findbit(command) ending = (((FormulaConfig.array['end'] + '{') + command) + '}') pos.pushending(ending) bit.parsebit(pos) self.add(bit) self.original += pos.popending(ending) self.size = bit.size<|docstring|>Parse the begin command<|endoftext|>
6e14e6cdf2538c5ed0676a42717873cf3c495c8a062d525253eab0d1c2cd829e
def findbit(self, piece): 'Find the command bit corresponding to the \\begin{piece}' for type in BeginCommand.types: if (piece.replace('*', '') == type.piece): return self.factory.create(type) bit = self.factory.create(EquationEnvironment) bit.piece = piece return bit
Find the command bit corresponding to the \begin{piece}
Lib/site-packages/docutils/utils/math/math2html.py
findbit
edupyter/EDUPYTER
2
python
def findbit(self, piece): 'Find the command bit corresponding to the \\begin{piece}' for type in BeginCommand.types: if (piece.replace('*', ) == type.piece): return self.factory.create(type) bit = self.factory.create(EquationEnvironment) bit.piece = piece return bit
def findbit(self, piece): 'Find the command bit corresponding to the \\begin{piece}' for type in BeginCommand.types: if (piece.replace('*', ) == type.piece): return self.factory.create(type) bit = self.factory.create(EquationEnvironment) bit.piece = piece return bit<|docstring|>Find the command bit corresponding to the \begin{piece}<|endoftext|>
9b81abe7daee9397b2e4dd2c6c1a948b5ea29e7fe9121e5c3edf562bb59a803a
def parsebit(self, pos): 'Parse a combining function.' combining = self.translated parameter = self.parsesingleparameter(pos) if (not parameter): Trace.error(('Missing parameter for combining function ' + self.command)) return if (not isinstance(parameter, FormulaConstant)): try: extractor = ContainerExtractor(ContainerConfig.extracttext) parameter = extractor.extract(parameter)[0] except IndexError: Trace.error(('No base character found for "%s".' % self.command)) return if parameter.string.startswith(u'\u2009'): i = 2 else: i = 1 parameter.string = ((parameter.string[:i] + combining) + parameter.string[i:]) parameter.string = unicodedata.normalize('NFC', parameter.string)
Parse a combining function.
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): combining = self.translated parameter = self.parsesingleparameter(pos) if (not parameter): Trace.error(('Missing parameter for combining function ' + self.command)) return if (not isinstance(parameter, FormulaConstant)): try: extractor = ContainerExtractor(ContainerConfig.extracttext) parameter = extractor.extract(parameter)[0] except IndexError: Trace.error(('No base character found for "%s".' % self.command)) return if parameter.string.startswith(u'\u2009'): i = 2 else: i = 1 parameter.string = ((parameter.string[:i] + combining) + parameter.string[i:]) parameter.string = unicodedata.normalize('NFC', parameter.string)
def parsebit(self, pos): combining = self.translated parameter = self.parsesingleparameter(pos) if (not parameter): Trace.error(('Missing parameter for combining function ' + self.command)) return if (not isinstance(parameter, FormulaConstant)): try: extractor = ContainerExtractor(ContainerConfig.extracttext) parameter = extractor.extract(parameter)[0] except IndexError: Trace.error(('No base character found for "%s".' % self.command)) return if parameter.string.startswith(u'\u2009'): i = 2 else: i = 1 parameter.string = ((parameter.string[:i] + combining) + parameter.string[i:]) parameter.string = unicodedata.normalize('NFC', parameter.string)<|docstring|>Parse a combining function.<|endoftext|>
85516cc263411c587db1e8bf5c890b6513de993dde0f2c767ce0731cb46d8725
def parsesingleparameter(self, pos): 'Parse a parameter, or a single letter.' self.factory.clearskipped(pos) if pos.finished(): return None return self.parseparameter(pos)
Parse a parameter, or a single letter.
Lib/site-packages/docutils/utils/math/math2html.py
parsesingleparameter
edupyter/EDUPYTER
2
python
def parsesingleparameter(self, pos): self.factory.clearskipped(pos) if pos.finished(): return None return self.parseparameter(pos)
def parsesingleparameter(self, pos): self.factory.clearskipped(pos) if pos.finished(): return None return self.parseparameter(pos)<|docstring|>Parse a parameter, or a single letter.<|endoftext|>
35171c38c07d073cb89de01368e812d67ad67709d0aa88207208a475d475dc7e
def parsebit(self, pos): 'Parse an overset-function' symbol = self.translated self.symbol = TaggedBit().constant(symbol, 'sup') self.parameter = self.parseparameter(pos) self.output = TaggedOutput().settag('span class="embellished"') self.contents.insert(0, self.symbol) self.parameter.output = TaggedOutput().settag('span class="base"') self.simplifyifpossible()
Parse an overset-function
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): symbol = self.translated self.symbol = TaggedBit().constant(symbol, 'sup') self.parameter = self.parseparameter(pos) self.output = TaggedOutput().settag('span class="embellished"') self.contents.insert(0, self.symbol) self.parameter.output = TaggedOutput().settag('span class="base"') self.simplifyifpossible()
def parsebit(self, pos): symbol = self.translated self.symbol = TaggedBit().constant(symbol, 'sup') self.parameter = self.parseparameter(pos) self.output = TaggedOutput().settag('span class="embellished"') self.contents.insert(0, self.symbol) self.parameter.output = TaggedOutput().settag('span class="base"') self.simplifyifpossible()<|docstring|>Parse an overset-function<|endoftext|>
aef91a2604dd78774442ef020d13c1226b5c2c132620a3c9e2450948e211b19d
def parsebit(self, pos): 'Parse an underset-function' symbol = self.translated self.symbol = TaggedBit().constant(symbol, 'sub') self.parameter = self.parseparameter(pos) self.output = TaggedOutput().settag('span class="embellished"') self.contents.insert(0, self.symbol) self.parameter.output = TaggedOutput().settag('span class="base"') self.simplifyifpossible()
Parse an underset-function
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): symbol = self.translated self.symbol = TaggedBit().constant(symbol, 'sub') self.parameter = self.parseparameter(pos) self.output = TaggedOutput().settag('span class="embellished"') self.contents.insert(0, self.symbol) self.parameter.output = TaggedOutput().settag('span class="base"') self.simplifyifpossible()
def parsebit(self, pos): symbol = self.translated self.symbol = TaggedBit().constant(symbol, 'sub') self.parameter = self.parseparameter(pos) self.output = TaggedOutput().settag('span class="embellished"') self.contents.insert(0, self.symbol) self.parameter.output = TaggedOutput().settag('span class="base"') self.simplifyifpossible()<|docstring|>Parse an underset-function<|endoftext|>
fa55438c884f1d50a86c35bbe75e36f609e336fb93b0a11ccb1abaf3e35f5a04
def parsebit(self, pos): 'Parse a limit command.' self.output = TaggedOutput().settag('span class="limits"') symbol = self.translated self.contents.append(TaggedBit().constant(symbol, 'span class="limit"'))
Parse a limit command.
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="limits"') symbol = self.translated self.contents.append(TaggedBit().constant(symbol, 'span class="limit"'))
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="limits"') symbol = self.translated self.contents.append(TaggedBit().constant(symbol, 'span class="limit"'))<|docstring|>Parse a limit command.<|endoftext|>
52aa8fc8334d546fbffc2369e344e994468cb2e97ca732aa1447add9497bac3d
def parsebit(self, pos): 'Do nothing.' self.output = TaggedOutput().settag('span class="limits"') self.factory.clearskipped(pos)
Do nothing.
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="limits"') self.factory.clearskipped(pos)
def parsebit(self, pos): self.output = TaggedOutput().settag('span class="limits"') self.factory.clearskipped(pos)<|docstring|>Do nothing.<|endoftext|>
118de85d114b91ecc4ac81fe30809b429927cf7edae25d57482ffc576991fb47
def __unicode__(self): 'Return a printable representation.' return 'Limit previous command'
Return a printable representation.
Lib/site-packages/docutils/utils/math/math2html.py
__unicode__
edupyter/EDUPYTER
2
python
def __unicode__(self): return 'Limit previous command'
def __unicode__(self): return 'Limit previous command'<|docstring|>Return a printable representation.<|endoftext|>
8e6312409dac5d03358789c7977a7b5465f7236a617b254d39e7c93c299226b9
def process(self, contents, index): 'Process the limits for an element.' if Options.simplemath: return if self.checklimits(contents, index): self.modifylimits(contents, index) if (self.checkscript(contents, index) and self.checkscript(contents, (index + 1))): self.modifyscripts(contents, index)
Process the limits for an element.
Lib/site-packages/docutils/utils/math/math2html.py
process
edupyter/EDUPYTER
2
python
def process(self, contents, index): if Options.simplemath: return if self.checklimits(contents, index): self.modifylimits(contents, index) if (self.checkscript(contents, index) and self.checkscript(contents, (index + 1))): self.modifyscripts(contents, index)
def process(self, contents, index): if Options.simplemath: return if self.checklimits(contents, index): self.modifylimits(contents, index) if (self.checkscript(contents, index) and self.checkscript(contents, (index + 1))): self.modifyscripts(contents, index)<|docstring|>Process the limits for an element.<|endoftext|>
31e5e3092488627a1f808dad062e731e07410b8c942bc626709b8303e8763bd8
def checklimits(self, contents, index): 'Check if the current position has a limits command.' if (not DocumentParameters.displaymode): return False if self.checkcommand(contents, (index + 1), LimitPreviousCommand): self.limitsahead(contents, index) return False if (not isinstance(contents[index], LimitCommand)): return False return self.checkscript(contents, (index + 1))
Check if the current position has a limits command.
Lib/site-packages/docutils/utils/math/math2html.py
checklimits
edupyter/EDUPYTER
2
python
def checklimits(self, contents, index): if (not DocumentParameters.displaymode): return False if self.checkcommand(contents, (index + 1), LimitPreviousCommand): self.limitsahead(contents, index) return False if (not isinstance(contents[index], LimitCommand)): return False return self.checkscript(contents, (index + 1))
def checklimits(self, contents, index): if (not DocumentParameters.displaymode): return False if self.checkcommand(contents, (index + 1), LimitPreviousCommand): self.limitsahead(contents, index) return False if (not isinstance(contents[index], LimitCommand)): return False return self.checkscript(contents, (index + 1))<|docstring|>Check if the current position has a limits command.<|endoftext|>
4fbd8915ddf0bb6971683d008b2dd7d17902bc9c5dbef8758accfba809a179d3
def limitsahead(self, contents, index): 'Limit the current element based on the next.' contents[(index + 1)].add(contents[index].clone()) contents[index].output = EmptyOutput()
Limit the current element based on the next.
Lib/site-packages/docutils/utils/math/math2html.py
limitsahead
edupyter/EDUPYTER
2
python
def limitsahead(self, contents, index): contents[(index + 1)].add(contents[index].clone()) contents[index].output = EmptyOutput()
def limitsahead(self, contents, index): contents[(index + 1)].add(contents[index].clone()) contents[index].output = EmptyOutput()<|docstring|>Limit the current element based on the next.<|endoftext|>
39c821baa1ec1f2bf54d3e10eedf4d182a7f2cfa3905c1e504f8a6384fb25d87
def modifylimits(self, contents, index): 'Modify a limits commands so that the limits appear above and below.' limited = contents[index] subscript = self.getlimit(contents, (index + 1)) if self.checkscript(contents, (index + 1)): superscript = self.getlimit(contents, (index + 1)) else: superscript = TaggedBit().constant(u'\u2009', 'sup class="limit"') if (subscript.command == '^'): (superscript, subscript) = (subscript, superscript) limited.contents.append(subscript) limited.contents.insert(0, superscript)
Modify a limits commands so that the limits appear above and below.
Lib/site-packages/docutils/utils/math/math2html.py
modifylimits
edupyter/EDUPYTER
2
python
def modifylimits(self, contents, index): limited = contents[index] subscript = self.getlimit(contents, (index + 1)) if self.checkscript(contents, (index + 1)): superscript = self.getlimit(contents, (index + 1)) else: superscript = TaggedBit().constant(u'\u2009', 'sup class="limit"') if (subscript.command == '^'): (superscript, subscript) = (subscript, superscript) limited.contents.append(subscript) limited.contents.insert(0, superscript)
def modifylimits(self, contents, index): limited = contents[index] subscript = self.getlimit(contents, (index + 1)) if self.checkscript(contents, (index + 1)): superscript = self.getlimit(contents, (index + 1)) else: superscript = TaggedBit().constant(u'\u2009', 'sup class="limit"') if (subscript.command == '^'): (superscript, subscript) = (subscript, superscript) limited.contents.append(subscript) limited.contents.insert(0, superscript)<|docstring|>Modify a limits commands so that the limits appear above and below.<|endoftext|>
e0ac44876b3c961ca2d2ff16740a75df393fe2bd5f035793885a4af68e89b6fb
def getlimit(self, contents, index): 'Get the limit for a limits command.' limit = self.getscript(contents, index) limit.output.tag = limit.output.tag.replace('script', 'limit') return limit
Get the limit for a limits command.
Lib/site-packages/docutils/utils/math/math2html.py
getlimit
edupyter/EDUPYTER
2
python
def getlimit(self, contents, index): limit = self.getscript(contents, index) limit.output.tag = limit.output.tag.replace('script', 'limit') return limit
def getlimit(self, contents, index): limit = self.getscript(contents, index) limit.output.tag = limit.output.tag.replace('script', 'limit') return limit<|docstring|>Get the limit for a limits command.<|endoftext|>
d8fa6590781914c6241cd43daf384e8553a667a0dff31489dd31028079bb2d20
def modifyscripts(self, contents, index): 'Modify the super- and subscript to appear vertically aligned.' subscript = self.getscript(contents, index) superscript = self.getscript(contents, index) if (subscript.command == '^'): (superscript, subscript) = (subscript, superscript) scripts = TaggedBit().complete([superscript, subscript], 'span class="scripts"') contents.insert(index, scripts)
Modify the super- and subscript to appear vertically aligned.
Lib/site-packages/docutils/utils/math/math2html.py
modifyscripts
edupyter/EDUPYTER
2
python
def modifyscripts(self, contents, index): subscript = self.getscript(contents, index) superscript = self.getscript(contents, index) if (subscript.command == '^'): (superscript, subscript) = (subscript, superscript) scripts = TaggedBit().complete([superscript, subscript], 'span class="scripts"') contents.insert(index, scripts)
def modifyscripts(self, contents, index): subscript = self.getscript(contents, index) superscript = self.getscript(contents, index) if (subscript.command == '^'): (superscript, subscript) = (subscript, superscript) scripts = TaggedBit().complete([superscript, subscript], 'span class="scripts"') contents.insert(index, scripts)<|docstring|>Modify the super- and subscript to appear vertically aligned.<|endoftext|>
04003b18fd57acbdfcf4906094cf3bbff548b9a46812c8d211d1bfe96e6dd67d
def checkscript(self, contents, index): 'Check if the current element is a sub- or superscript.' return self.checkcommand(contents, index, SymbolFunction)
Check if the current element is a sub- or superscript.
Lib/site-packages/docutils/utils/math/math2html.py
checkscript
edupyter/EDUPYTER
2
python
def checkscript(self, contents, index): return self.checkcommand(contents, index, SymbolFunction)
def checkscript(self, contents, index): return self.checkcommand(contents, index, SymbolFunction)<|docstring|>Check if the current element is a sub- or superscript.<|endoftext|>
821df11a073a65f0c8dff1918b3b90c8ad2496330de0c6d98e87092b1949c752
def checkcommand(self, contents, index, type): 'Check for the given type as the current element.' if (len(contents) <= index): return False return isinstance(contents[index], type)
Check for the given type as the current element.
Lib/site-packages/docutils/utils/math/math2html.py
checkcommand
edupyter/EDUPYTER
2
python
def checkcommand(self, contents, index, type): if (len(contents) <= index): return False return isinstance(contents[index], type)
def checkcommand(self, contents, index, type): if (len(contents) <= index): return False return isinstance(contents[index], type)<|docstring|>Check for the given type as the current element.<|endoftext|>
719207267c7104bcc6dd691cc63558e68fc7205a024c8545d018ca140ecc442a
def getscript(self, contents, index): 'Get the sub- or superscript.' bit = contents[index] bit.output.tag += ' class="script"' del contents[index] return bit
Get the sub- or superscript.
Lib/site-packages/docutils/utils/math/math2html.py
getscript
edupyter/EDUPYTER
2
python
def getscript(self, contents, index): bit = contents[index] bit.output.tag += ' class="script"' del contents[index] return bit
def getscript(self, contents, index): bit = contents[index] bit.output.tag += ' class="script"' del contents[index] return bit<|docstring|>Get the sub- or superscript.<|endoftext|>
215785a00f4324ccca783c42d2793b6ebfcefb31db86168f20ef399b0880f72a
def parsebit(self, pos): 'Parse the bracket.' OneParamFunction.parsebit(self, pos)
Parse the bracket.
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): OneParamFunction.parsebit(self, pos)
def parsebit(self, pos): OneParamFunction.parsebit(self, pos)<|docstring|>Parse the bracket.<|endoftext|>
743497d0bea8343dcb4c9f6700f80e67a7c1f7b813d0f15610784bc8188d1e2e
def create(self, direction, character): 'Create the bracket for the given character.' self.original = character self.command = ('\\' + direction) self.contents = [FormulaConstant(character)] return self
Create the bracket for the given character.
Lib/site-packages/docutils/utils/math/math2html.py
create
edupyter/EDUPYTER
2
python
def create(self, direction, character): self.original = character self.command = ('\\' + direction) self.contents = [FormulaConstant(character)] return self
def create(self, direction, character): self.original = character self.command = ('\\' + direction) self.contents = [FormulaConstant(character)] return self<|docstring|>Create the bracket for the given character.<|endoftext|>
dc0ffbc83b34fc01835aacc29b99960dd89409e03173276f3b16db05e8e2db28
def process(self, contents, index): 'Convert the bracket using Unicode pieces, if possible.' if Options.simplemath: return if self.checkleft(contents, index): return self.processleft(contents, index)
Convert the bracket using Unicode pieces, if possible.
Lib/site-packages/docutils/utils/math/math2html.py
process
edupyter/EDUPYTER
2
python
def process(self, contents, index): if Options.simplemath: return if self.checkleft(contents, index): return self.processleft(contents, index)
def process(self, contents, index): if Options.simplemath: return if self.checkleft(contents, index): return self.processleft(contents, index)<|docstring|>Convert the bracket using Unicode pieces, if possible.<|endoftext|>
cd8544833593b8c9a99ba641de0c588fa6e85f1a988bc9259432de3a05febe02
def processleft(self, contents, index): 'Process a left bracket.' rightindex = self.findright(contents, (index + 1)) if (not rightindex): return size = self.findmax(contents, index, rightindex) self.resize(contents[index], size) self.resize(contents[rightindex], size)
Process a left bracket.
Lib/site-packages/docutils/utils/math/math2html.py
processleft
edupyter/EDUPYTER
2
python
def processleft(self, contents, index): rightindex = self.findright(contents, (index + 1)) if (not rightindex): return size = self.findmax(contents, index, rightindex) self.resize(contents[index], size) self.resize(contents[rightindex], size)
def processleft(self, contents, index): rightindex = self.findright(contents, (index + 1)) if (not rightindex): return size = self.findmax(contents, index, rightindex) self.resize(contents[index], size) self.resize(contents[rightindex], size)<|docstring|>Process a left bracket.<|endoftext|>
d7b38d74852a997396920c21520eb3796f92589e36037f485f2b7434a3932925
def checkleft(self, contents, index): 'Check if the command at the given index is left.' return self.checkdirection(contents[index], '\\left')
Check if the command at the given index is left.
Lib/site-packages/docutils/utils/math/math2html.py
checkleft
edupyter/EDUPYTER
2
python
def checkleft(self, contents, index): return self.checkdirection(contents[index], '\\left')
def checkleft(self, contents, index): return self.checkdirection(contents[index], '\\left')<|docstring|>Check if the command at the given index is left.<|endoftext|>
dbe468f75dc5159d7f06dbcdbdae83664c358278a869f1d9352c536f0161661f
def checkright(self, contents, index): 'Check if the command at the given index is right.' return self.checkdirection(contents[index], '\\right')
Check if the command at the given index is right.
Lib/site-packages/docutils/utils/math/math2html.py
checkright
edupyter/EDUPYTER
2
python
def checkright(self, contents, index): return self.checkdirection(contents[index], '\\right')
def checkright(self, contents, index): return self.checkdirection(contents[index], '\\right')<|docstring|>Check if the command at the given index is right.<|endoftext|>
41fc75c30398fc792801ad388c0482848947439d1e09a625622ee506dea235d8
def checkdirection(self, bit, command): 'Check if the given bit is the desired bracket command.' if (not isinstance(bit, BracketCommand)): return False return (bit.command == command)
Check if the given bit is the desired bracket command.
Lib/site-packages/docutils/utils/math/math2html.py
checkdirection
edupyter/EDUPYTER
2
python
def checkdirection(self, bit, command): if (not isinstance(bit, BracketCommand)): return False return (bit.command == command)
def checkdirection(self, bit, command): if (not isinstance(bit, BracketCommand)): return False return (bit.command == command)<|docstring|>Check if the given bit is the desired bracket command.<|endoftext|>
875bdd257e92bc670c698ea2f3bd1e77c137259f3d9c631f4172c87b47607687
def findright(self, contents, index): 'Find the right bracket starting at the given index, or 0.' depth = 1 while (index < len(contents)): if self.checkleft(contents, index): depth += 1 if self.checkright(contents, index): depth -= 1 if (depth == 0): return index index += 1 return None
Find the right bracket starting at the given index, or 0.
Lib/site-packages/docutils/utils/math/math2html.py
findright
edupyter/EDUPYTER
2
python
def findright(self, contents, index): depth = 1 while (index < len(contents)): if self.checkleft(contents, index): depth += 1 if self.checkright(contents, index): depth -= 1 if (depth == 0): return index index += 1 return None
def findright(self, contents, index): depth = 1 while (index < len(contents)): if self.checkleft(contents, index): depth += 1 if self.checkright(contents, index): depth -= 1 if (depth == 0): return index index += 1 return None<|docstring|>Find the right bracket starting at the given index, or 0.<|endoftext|>
824030e97ab6b66c6e1282e90a22d3b8d54429d035c5acb60808f04380d26ba7
def findmax(self, contents, leftindex, rightindex): 'Find the max size of the contents between the two given indices.' sliced = contents[leftindex:rightindex] return max([element.size for element in sliced])
Find the max size of the contents between the two given indices.
Lib/site-packages/docutils/utils/math/math2html.py
findmax
edupyter/EDUPYTER
2
python
def findmax(self, contents, leftindex, rightindex): sliced = contents[leftindex:rightindex] return max([element.size for element in sliced])
def findmax(self, contents, leftindex, rightindex): sliced = contents[leftindex:rightindex] return max([element.size for element in sliced])<|docstring|>Find the max size of the contents between the two given indices.<|endoftext|>
78f57441208a0033d9ba8855278c294459dce1ec772e8954139e409f67ad2da4
def resize(self, command, size): 'Resize a bracket command to the given size.' character = command.extracttext() alignment = command.command.replace('\\', '') bracket = BigBracket(size, character, alignment) command.output = ContentsOutput() command.contents = bracket.getcontents()
Resize a bracket command to the given size.
Lib/site-packages/docutils/utils/math/math2html.py
resize
edupyter/EDUPYTER
2
python
def resize(self, command, size): character = command.extracttext() alignment = command.command.replace('\\', ) bracket = BigBracket(size, character, alignment) command.output = ContentsOutput() command.contents = bracket.getcontents()
def resize(self, command, size): character = command.extracttext() alignment = command.command.replace('\\', ) bracket = BigBracket(size, character, alignment) command.output = ContentsOutput() command.contents = bracket.getcontents()<|docstring|>Resize a bracket command to the given size.<|endoftext|>
39545e449634b351377bd1614882a9078af86813ca6c88a43c8ed4c6670962e8
def parse(self, pos): 'Parse a parameter definition: [$0], {$x}, {$1!}...' for (opening, closing) in ParameterDefinition.parambrackets: if pos.checkskip(opening): if (opening == '['): self.optional = True if (not pos.checkskip('$')): Trace.error((('Wrong parameter name, did you mean $' + pos.current()) + '?')) return None self.name = pos.skipcurrent() if pos.checkskip('!'): self.literal = True if (not pos.checkskip(closing)): Trace.error(('Wrong parameter closing ' + pos.skipcurrent())) return None return self Trace.error(('Wrong character in parameter template: ' + pos.skipcurrent())) return None
Parse a parameter definition: [$0], {$x}, {$1!}...
Lib/site-packages/docutils/utils/math/math2html.py
parse
edupyter/EDUPYTER
2
python
def parse(self, pos): for (opening, closing) in ParameterDefinition.parambrackets: if pos.checkskip(opening): if (opening == '['): self.optional = True if (not pos.checkskip('$')): Trace.error((('Wrong parameter name, did you mean $' + pos.current()) + '?')) return None self.name = pos.skipcurrent() if pos.checkskip('!'): self.literal = True if (not pos.checkskip(closing)): Trace.error(('Wrong parameter closing ' + pos.skipcurrent())) return None return self Trace.error(('Wrong character in parameter template: ' + pos.skipcurrent())) return None
def parse(self, pos): for (opening, closing) in ParameterDefinition.parambrackets: if pos.checkskip(opening): if (opening == '['): self.optional = True if (not pos.checkskip('$')): Trace.error((('Wrong parameter name, did you mean $' + pos.current()) + '?')) return None self.name = pos.skipcurrent() if pos.checkskip('!'): self.literal = True if (not pos.checkskip(closing)): Trace.error(('Wrong parameter closing ' + pos.skipcurrent())) return None return self Trace.error(('Wrong character in parameter template: ' + pos.skipcurrent())) return None<|docstring|>Parse a parameter definition: [$0], {$x}, {$1!}...<|endoftext|>
3bb677721010cc68f2b2861268c9fbd2ae0664b33cc114544dcd3a3560855a93
def read(self, pos, function): 'Read the parameter itself using the definition.' if self.literal: if self.optional: self.literalvalue = function.parsesquareliteral(pos) else: self.literalvalue = function.parseliteral(pos) if self.literalvalue: self.value = FormulaConstant(self.literalvalue) elif self.optional: self.value = function.parsesquare(pos) else: self.value = function.parseparameter(pos)
Read the parameter itself using the definition.
Lib/site-packages/docutils/utils/math/math2html.py
read
edupyter/EDUPYTER
2
python
def read(self, pos, function): if self.literal: if self.optional: self.literalvalue = function.parsesquareliteral(pos) else: self.literalvalue = function.parseliteral(pos) if self.literalvalue: self.value = FormulaConstant(self.literalvalue) elif self.optional: self.value = function.parsesquare(pos) else: self.value = function.parseparameter(pos)
def read(self, pos, function): if self.literal: if self.optional: self.literalvalue = function.parsesquareliteral(pos) else: self.literalvalue = function.parseliteral(pos) if self.literalvalue: self.value = FormulaConstant(self.literalvalue) elif self.optional: self.value = function.parsesquare(pos) else: self.value = function.parseparameter(pos)<|docstring|>Read the parameter itself using the definition.<|endoftext|>
60e9bf6b3d6f111b477a7d8c15cfc3aeba55ea8ce779c2fdaa728153ac251c4a
def __unicode__(self): 'Return a printable representation.' result = ('param ' + self.name) if self.value: result += (': ' + unicode(self.value)) else: result += ' (empty)' return result
Return a printable representation.
Lib/site-packages/docutils/utils/math/math2html.py
__unicode__
edupyter/EDUPYTER
2
python
def __unicode__(self): result = ('param ' + self.name) if self.value: result += (': ' + unicode(self.value)) else: result += ' (empty)' return result
def __unicode__(self): result = ('param ' + self.name) if self.value: result += (': ' + unicode(self.value)) else: result += ' (empty)' return result<|docstring|>Return a printable representation.<|endoftext|>
44c0ee560af303400229d56f0f894c9b3b5a4087db0b4222591f83deb459b59a
def readparams(self, readtemplate, pos): 'Read the params according to the template.' self.params = dict() for paramdef in self.paramdefs(readtemplate): paramdef.read(pos, self) self.params[('$' + paramdef.name)] = paramdef
Read the params according to the template.
Lib/site-packages/docutils/utils/math/math2html.py
readparams
edupyter/EDUPYTER
2
python
def readparams(self, readtemplate, pos): self.params = dict() for paramdef in self.paramdefs(readtemplate): paramdef.read(pos, self) self.params[('$' + paramdef.name)] = paramdef
def readparams(self, readtemplate, pos): self.params = dict() for paramdef in self.paramdefs(readtemplate): paramdef.read(pos, self) self.params[('$' + paramdef.name)] = paramdef<|docstring|>Read the params according to the template.<|endoftext|>
1f56c0f9966d417130798a7f81f02413ccca495370579267d1fb09457541f589
def paramdefs(self, readtemplate): 'Read each param definition in the template' pos = TextPosition(readtemplate) while (not pos.finished()): paramdef = ParameterDefinition().parse(pos) if paramdef: (yield paramdef)
Read each param definition in the template
Lib/site-packages/docutils/utils/math/math2html.py
paramdefs
edupyter/EDUPYTER
2
python
def paramdefs(self, readtemplate): pos = TextPosition(readtemplate) while (not pos.finished()): paramdef = ParameterDefinition().parse(pos) if paramdef: (yield paramdef)
def paramdefs(self, readtemplate): pos = TextPosition(readtemplate) while (not pos.finished()): paramdef = ParameterDefinition().parse(pos) if paramdef: (yield paramdef)<|docstring|>Read each param definition in the template<|endoftext|>
851c67da830d1e563523d0383498ae52c96f616f90c394f141054374c8dcb92f
def getparam(self, name): 'Get a parameter as parsed.' if (not (name in self.params)): return None return self.params[name]
Get a parameter as parsed.
Lib/site-packages/docutils/utils/math/math2html.py
getparam
edupyter/EDUPYTER
2
python
def getparam(self, name): if (not (name in self.params)): return None return self.params[name]
def getparam(self, name): if (not (name in self.params)): return None return self.params[name]<|docstring|>Get a parameter as parsed.<|endoftext|>
c951fc3e8e87f34bfeda31ac1291660e91e81860fe9da444dcefb8a48f0c0d9f
def getvalue(self, name): 'Get the value of a parameter.' return self.getparam(name).value
Get the value of a parameter.
Lib/site-packages/docutils/utils/math/math2html.py
getvalue
edupyter/EDUPYTER
2
python
def getvalue(self, name): return self.getparam(name).value
def getvalue(self, name): return self.getparam(name).value<|docstring|>Get the value of a parameter.<|endoftext|>
77624ba755d9aaf659f90ef2bab6cdd04840e629d6b5c4796bf02d3d873a7eb2
def getliteralvalue(self, name): 'Get the literal value of a parameter.' param = self.getparam(name) if ((not param) or (not param.literalvalue)): return None return param.literalvalue
Get the literal value of a parameter.
Lib/site-packages/docutils/utils/math/math2html.py
getliteralvalue
edupyter/EDUPYTER
2
python
def getliteralvalue(self, name): param = self.getparam(name) if ((not param) or (not param.literalvalue)): return None return param.literalvalue
def getliteralvalue(self, name): param = self.getparam(name) if ((not param) or (not param.literalvalue)): return None return param.literalvalue<|docstring|>Get the literal value of a parameter.<|endoftext|>
ca88726105dfdfa0cd58d39cc36f41d9339d53cd92cea7914304c1a3226f4773
def parsebit(self, pos): 'Parse a function with [] and {} parameters' readtemplate = self.translated[0] writetemplate = self.translated[1] self.readparams(readtemplate, pos) self.contents = self.writeparams(writetemplate) self.computehybridsize()
Parse a function with [] and {} parameters
Lib/site-packages/docutils/utils/math/math2html.py
parsebit
edupyter/EDUPYTER
2
python
def parsebit(self, pos): readtemplate = self.translated[0] writetemplate = self.translated[1] self.readparams(readtemplate, pos) self.contents = self.writeparams(writetemplate) self.computehybridsize()
def parsebit(self, pos): readtemplate = self.translated[0] writetemplate = self.translated[1] self.readparams(readtemplate, pos) self.contents = self.writeparams(writetemplate) self.computehybridsize()<|docstring|>Parse a function with [] and {} parameters<|endoftext|>
660197f5d8cfd7148e0af9bf01ba2479f92e462af9904bf7dcc3bc8eb671d712
def writeparams(self, writetemplate): 'Write all params according to the template' return self.writepos(TextPosition(writetemplate))
Write all params according to the template
Lib/site-packages/docutils/utils/math/math2html.py
writeparams
edupyter/EDUPYTER
2
python
def writeparams(self, writetemplate): return self.writepos(TextPosition(writetemplate))
def writeparams(self, writetemplate): return self.writepos(TextPosition(writetemplate))<|docstring|>Write all params according to the template<|endoftext|>
47c80de0def8938fb80c7af82d17124d358ff125c24b6f235afd30b1ac8c3dfa
def writepos(self, pos): 'Write all params as read in the parse position.' result = [] while (not pos.finished()): if pos.checkskip('$'): param = self.writeparam(pos) if param: result.append(param) elif pos.checkskip('f'): function = self.writefunction(pos) if function: function.type = None result.append(function) elif pos.checkskip('('): result.append(self.writebracket('left', '(')) elif pos.checkskip(')'): result.append(self.writebracket('right', ')')) else: result.append(FormulaConstant(pos.skipcurrent())) return result
Write all params as read in the parse position.
Lib/site-packages/docutils/utils/math/math2html.py
writepos
edupyter/EDUPYTER
2
python
def writepos(self, pos): result = [] while (not pos.finished()): if pos.checkskip('$'): param = self.writeparam(pos) if param: result.append(param) elif pos.checkskip('f'): function = self.writefunction(pos) if function: function.type = None result.append(function) elif pos.checkskip('('): result.append(self.writebracket('left', '(')) elif pos.checkskip(')'): result.append(self.writebracket('right', ')')) else: result.append(FormulaConstant(pos.skipcurrent())) return result
def writepos(self, pos): result = [] while (not pos.finished()): if pos.checkskip('$'): param = self.writeparam(pos) if param: result.append(param) elif pos.checkskip('f'): function = self.writefunction(pos) if function: function.type = None result.append(function) elif pos.checkskip('('): result.append(self.writebracket('left', '(')) elif pos.checkskip(')'): result.append(self.writebracket('right', ')')) else: result.append(FormulaConstant(pos.skipcurrent())) return result<|docstring|>Write all params as read in the parse position.<|endoftext|>
a550bb37718d23295fffb0f15cdcdb0a1faf6c35990e49a8fb4db412b4fd4bc8
def writeparam(self, pos): 'Write a single param of the form $0, $x...' name = ('$' + pos.skipcurrent()) if (not (name in self.params)): Trace.error(('Unknown parameter ' + name)) return None if (not self.params[name]): return None if pos.checkskip('.'): self.params[name].value.type = pos.globalpha() return self.params[name].value
Write a single param of the form $0, $x...
Lib/site-packages/docutils/utils/math/math2html.py
writeparam
edupyter/EDUPYTER
2
python
def writeparam(self, pos): name = ('$' + pos.skipcurrent()) if (not (name in self.params)): Trace.error(('Unknown parameter ' + name)) return None if (not self.params[name]): return None if pos.checkskip('.'): self.params[name].value.type = pos.globalpha() return self.params[name].value
def writeparam(self, pos): name = ('$' + pos.skipcurrent()) if (not (name in self.params)): Trace.error(('Unknown parameter ' + name)) return None if (not self.params[name]): return None if pos.checkskip('.'): self.params[name].value.type = pos.globalpha() return self.params[name].value<|docstring|>Write a single param of the form $0, $x...<|endoftext|>
47813434d555fd527e7f0318539e1789146861ddc02ddf5aed46a758b57c4eb6
def writefunction(self, pos): 'Write a single function f0,...,fn.' tag = self.readtag(pos) if (not tag): return None if pos.checkskip('/'): return TaggedBit().selfcomplete(tag) if (not pos.checkskip('{')): Trace.error('Function should be defined in {}') return None pos.pushending('}') contents = self.writepos(pos) pos.popending() if (len(contents) == 0): return None return TaggedBit().complete(contents, tag)
Write a single function f0,...,fn.
Lib/site-packages/docutils/utils/math/math2html.py
writefunction
edupyter/EDUPYTER
2
python
def writefunction(self, pos): tag = self.readtag(pos) if (not tag): return None if pos.checkskip('/'): return TaggedBit().selfcomplete(tag) if (not pos.checkskip('{')): Trace.error('Function should be defined in {}') return None pos.pushending('}') contents = self.writepos(pos) pos.popending() if (len(contents) == 0): return None return TaggedBit().complete(contents, tag)
def writefunction(self, pos): tag = self.readtag(pos) if (not tag): return None if pos.checkskip('/'): return TaggedBit().selfcomplete(tag) if (not pos.checkskip('{')): Trace.error('Function should be defined in {}') return None pos.pushending('}') contents = self.writepos(pos) pos.popending() if (len(contents) == 0): return None return TaggedBit().complete(contents, tag)<|docstring|>Write a single function f0,...,fn.<|endoftext|>
aecd68ef5648c239f925018d73a929b5707e97898739ada978b9a77b2bb57272
def readtag(self, pos): 'Get the tag corresponding to the given index. Does parameter substitution.' if (not pos.current().isdigit()): Trace.error(('Function should be f0,...,f9: f' + pos.current())) return None index = int(pos.skipcurrent()) if ((2 + index) > len(self.translated)): Trace.error((('Function f' + unicode(index)) + ' is not defined')) return None tag = self.translated[(2 + index)] if (not ('$' in tag)): return tag for variable in self.params: if (variable in tag): param = self.params[variable] if (not param.literal): Trace.error((((('Parameters in tag ' + tag) + ' should be literal: {') + variable) + '!}')) continue if param.literalvalue: value = param.literalvalue else: value = '' tag = tag.replace(variable, value) return tag
Get the tag corresponding to the given index. Does parameter substitution.
Lib/site-packages/docutils/utils/math/math2html.py
readtag
edupyter/EDUPYTER
2
python
def readtag(self, pos): if (not pos.current().isdigit()): Trace.error(('Function should be f0,...,f9: f' + pos.current())) return None index = int(pos.skipcurrent()) if ((2 + index) > len(self.translated)): Trace.error((('Function f' + unicode(index)) + ' is not defined')) return None tag = self.translated[(2 + index)] if (not ('$' in tag)): return tag for variable in self.params: if (variable in tag): param = self.params[variable] if (not param.literal): Trace.error((((('Parameters in tag ' + tag) + ' should be literal: {') + variable) + '!}')) continue if param.literalvalue: value = param.literalvalue else: value = tag = tag.replace(variable, value) return tag
def readtag(self, pos): if (not pos.current().isdigit()): Trace.error(('Function should be f0,...,f9: f' + pos.current())) return None index = int(pos.skipcurrent()) if ((2 + index) > len(self.translated)): Trace.error((('Function f' + unicode(index)) + ' is not defined')) return None tag = self.translated[(2 + index)] if (not ('$' in tag)): return tag for variable in self.params: if (variable in tag): param = self.params[variable] if (not param.literal): Trace.error((((('Parameters in tag ' + tag) + ' should be literal: {') + variable) + '!}')) continue if param.literalvalue: value = param.literalvalue else: value = tag = tag.replace(variable, value) return tag<|docstring|>Get the tag corresponding to the given index. Does parameter substitution.<|endoftext|>
1a0feb13c8860701dfed5f8b05379fdc515d6bc7eada42f8e6addd72bcc27f99
def writebracket(self, direction, character): 'Return a new bracket looking at the given direction.' return self.factory.create(BracketCommand).create(direction, character)
Return a new bracket looking at the given direction.
Lib/site-packages/docutils/utils/math/math2html.py
writebracket
edupyter/EDUPYTER
2
python
def writebracket(self, direction, character): return self.factory.create(BracketCommand).create(direction, character)
def writebracket(self, direction, character): return self.factory.create(BracketCommand).create(direction, character)<|docstring|>Return a new bracket looking at the given direction.<|endoftext|>
5737e87a244d17f06c2a631cec1e8aef28fff22497538387dd2d979d5a678828
def computehybridsize(self): 'Compute the size of the hybrid function.' if (not (self.command in HybridSize.configsizes)): self.computesize() return self.size = HybridSize().getsize(self) for element in self.contents: element.size = self.size
Compute the size of the hybrid function.
Lib/site-packages/docutils/utils/math/math2html.py
computehybridsize
edupyter/EDUPYTER
2
python
def computehybridsize(self): if (not (self.command in HybridSize.configsizes)): self.computesize() return self.size = HybridSize().getsize(self) for element in self.contents: element.size = self.size
def computehybridsize(self): if (not (self.command in HybridSize.configsizes)): self.computesize() return self.size = HybridSize().getsize(self) for element in self.contents: element.size = self.size<|docstring|>Compute the size of the hybrid function.<|endoftext|>
77cbc2578546fbdd34ba21db5a8e035932c66634fbf201e55f50080d00a77192
def getsize(self, function): 'Read the size for a function and parse it.' sizestring = self.configsizes[function.command] for name in function.params: if (name in sizestring): size = function.params[name].value.computesize() sizestring = sizestring.replace(name, unicode(size)) if ('$' in sizestring): Trace.error(('Unconverted variable in hybrid size: ' + sizestring)) return 1 return eval(sizestring)
Read the size for a function and parse it.
Lib/site-packages/docutils/utils/math/math2html.py
getsize
edupyter/EDUPYTER
2
python
def getsize(self, function): sizestring = self.configsizes[function.command] for name in function.params: if (name in sizestring): size = function.params[name].value.computesize() sizestring = sizestring.replace(name, unicode(size)) if ('$' in sizestring): Trace.error(('Unconverted variable in hybrid size: ' + sizestring)) return 1 return eval(sizestring)
def getsize(self, function): sizestring = self.configsizes[function.command] for name in function.params: if (name in sizestring): size = function.params[name].value.computesize() sizestring = sizestring.replace(name, unicode(size)) if ('$' in sizestring): Trace.error(('Unconverted variable in hybrid size: ' + sizestring)) return 1 return eval(sizestring)<|docstring|>Read the size for a function and parse it.<|endoftext|>
9384ca1f961caab5916dcf021da3c372c231b9a5c90adeb9a1eb6fea203a667a
def open_dataset(fname): 'Open a single dataset from RAQMS netcdf output.\n Parameters\n ----------\n fname : string\n Filename to be opened.\n Returns\n -------\n xarray.Dataset\n ' (names, netcdf) = _ensure_mfdataset_filenames(fname) try: if netcdf: f = xr.open_dataset(names[0], drop_variables=['theta']) f = _fix_grid(f) f = _fix_time(f) else: raise ValueError except ValueError: print('File format not recognized. Please check that files are RAQMS real-time forecasts.') return f
Open a single dataset from RAQMS netcdf output. Parameters ---------- fname : string Filename to be opened. Returns ------- xarray.Dataset
monetio/models/raqms_rt.py
open_dataset
mebruckner/monetio
1
python
def open_dataset(fname): 'Open a single dataset from RAQMS netcdf output.\n Parameters\n ----------\n fname : string\n Filename to be opened.\n Returns\n -------\n xarray.Dataset\n ' (names, netcdf) = _ensure_mfdataset_filenames(fname) try: if netcdf: f = xr.open_dataset(names[0], drop_variables=['theta']) f = _fix_grid(f) f = _fix_time(f) else: raise ValueError except ValueError: print('File format not recognized. Please check that files are RAQMS real-time forecasts.') return f
def open_dataset(fname): 'Open a single dataset from RAQMS netcdf output.\n Parameters\n ----------\n fname : string\n Filename to be opened.\n Returns\n -------\n xarray.Dataset\n ' (names, netcdf) = _ensure_mfdataset_filenames(fname) try: if netcdf: f = xr.open_dataset(names[0], drop_variables=['theta']) f = _fix_grid(f) f = _fix_time(f) else: raise ValueError except ValueError: print('File format not recognized. Please check that files are RAQMS real-time forecasts.') return f<|docstring|>Open a single dataset from RAQMS netcdf output. Parameters ---------- fname : string Filename to be opened. Returns ------- xarray.Dataset<|endoftext|>
8155e422baf928b8245eeaa0482d5f3b8dc4fcee6683240ed077de8feb1c95aa
def open_mfdataset(fname): 'Open a multiple file dataset from RAQMS output.\n Parameters\n ----------\n fname : string\n Filenames to be opened\n Returns\n -------\n xarray.Dataset\n ' (names, netcdf) = _ensure_mfdataset_filenames(fname) try: if netcdf: f = xr.open_mfdataset(names, concat_dim='time', drop_variables=['theta'], combine='nested') f = _fix_grid(f) f = _fix_time(f) else: raise ValueError except ValueError: print('File format not recognized. Note that files should be in netcdf\n format. Do not mix and match file types.') return f
Open a multiple file dataset from RAQMS output. Parameters ---------- fname : string Filenames to be opened Returns ------- xarray.Dataset
monetio/models/raqms_rt.py
open_mfdataset
mebruckner/monetio
1
python
def open_mfdataset(fname): 'Open a multiple file dataset from RAQMS output.\n Parameters\n ----------\n fname : string\n Filenames to be opened\n Returns\n -------\n xarray.Dataset\n ' (names, netcdf) = _ensure_mfdataset_filenames(fname) try: if netcdf: f = xr.open_mfdataset(names, concat_dim='time', drop_variables=['theta'], combine='nested') f = _fix_grid(f) f = _fix_time(f) else: raise ValueError except ValueError: print('File format not recognized. Note that files should be in netcdf\n format. Do not mix and match file types.') return f
def open_mfdataset(fname): 'Open a multiple file dataset from RAQMS output.\n Parameters\n ----------\n fname : string\n Filenames to be opened\n Returns\n -------\n xarray.Dataset\n ' (names, netcdf) = _ensure_mfdataset_filenames(fname) try: if netcdf: f = xr.open_mfdataset(names, concat_dim='time', drop_variables=['theta'], combine='nested') f = _fix_grid(f) f = _fix_time(f) else: raise ValueError except ValueError: print('File format not recognized. Note that files should be in netcdf\n format. Do not mix and match file types.') return f<|docstring|>Open a multiple file dataset from RAQMS output. Parameters ---------- fname : string Filenames to be opened Returns ------- xarray.Dataset<|endoftext|>
d9e8f35ce0202a6100444aa0fa75b416fa1d8140c1dbc667e39e97193b77420f
def _ensure_mfdataset_filenames(fname): 'Checks if netcdf dataset for RAQMS real-time runs.\n \n Parameters\n ----------\n fname : string or list of strings\n Returns\n -------\n type\n ' from glob import glob from numpy import sort import six if isinstance(fname, six.string_types): names = sort(glob(fname)) else: names = sort(fname) netcdfs = [True for i in names if ('nc' in i) if ('uwhyb' in i)] netcdf = False if (len(netcdfs) >= 1): netcdf = True return (names, netcdf)
Checks if netcdf dataset for RAQMS real-time runs. Parameters ---------- fname : string or list of strings Returns ------- type
monetio/models/raqms_rt.py
_ensure_mfdataset_filenames
mebruckner/monetio
1
python
def _ensure_mfdataset_filenames(fname): 'Checks if netcdf dataset for RAQMS real-time runs.\n \n Parameters\n ----------\n fname : string or list of strings\n Returns\n -------\n type\n ' from glob import glob from numpy import sort import six if isinstance(fname, six.string_types): names = sort(glob(fname)) else: names = sort(fname) netcdfs = [True for i in names if ('nc' in i) if ('uwhyb' in i)] netcdf = False if (len(netcdfs) >= 1): netcdf = True return (names, netcdf)
def _ensure_mfdataset_filenames(fname): 'Checks if netcdf dataset for RAQMS real-time runs.\n \n Parameters\n ----------\n fname : string or list of strings\n Returns\n -------\n type\n ' from glob import glob from numpy import sort import six if isinstance(fname, six.string_types): names = sort(glob(fname)) else: names = sort(fname) netcdfs = [True for i in names if ('nc' in i) if ('uwhyb' in i)] netcdf = False if (len(netcdfs) >= 1): netcdf = True return (names, netcdf)<|docstring|>Checks if netcdf dataset for RAQMS real-time runs. Parameters ---------- fname : string or list of strings Returns ------- type<|endoftext|>
ad4323a426cf931e5cf66ea5822e4a748293e717f6175c0ba452ecfc1dd8d0e2
@hookimpl def tox_configure(config): '\n :param tox.config.Config config: Configuration object to observe.\n :rtype: tox.config.Config\n ' return _ensure_envs_recreated_on_requirements_update(config)
:param tox.config.Config config: Configuration object to observe. :rtype: tox.config.Config
toxbat/requirements.py
tox_configure
gaborbernat/tox-battery
29
python
@hookimpl def tox_configure(config): '\n :param tox.config.Config config: Configuration object to observe.\n :rtype: tox.config.Config\n ' return _ensure_envs_recreated_on_requirements_update(config)
@hookimpl def tox_configure(config): '\n :param tox.config.Config config: Configuration object to observe.\n :rtype: tox.config.Config\n ' return _ensure_envs_recreated_on_requirements_update(config)<|docstring|>:param tox.config.Config config: Configuration object to observe. :rtype: tox.config.Config<|endoftext|>
c2b325150deebd26d7938e2e89cfc9106bacf6594380c79dc03bb94dcc32b8bf
def all_nested_req_files(requirement_files): 'Get all nested req file names for a list of requirements files.\n\n :param iter requirements_files: list of requirements files to check.\n ' for reqfile in requirement_files: (yield reqfile) if (reqfile and os.path.isfile(reqfile)): parent_dir = os.path.dirname(reqfile) with open(reqfile) as f: (yield from all_nested_req_files((os.path.join(parent_dir, line[2:].strip()) for line in f if (line.startswith('-r') or line.startswith('-c')))))
Get all nested req file names for a list of requirements files. :param iter requirements_files: list of requirements files to check.
toxbat/requirements.py
all_nested_req_files
gaborbernat/tox-battery
29
python
def all_nested_req_files(requirement_files): 'Get all nested req file names for a list of requirements files.\n\n :param iter requirements_files: list of requirements files to check.\n ' for reqfile in requirement_files: (yield reqfile) if (reqfile and os.path.isfile(reqfile)): parent_dir = os.path.dirname(reqfile) with open(reqfile) as f: (yield from all_nested_req_files((os.path.join(parent_dir, line[2:].strip()) for line in f if (line.startswith('-r') or line.startswith('-c')))))
def all_nested_req_files(requirement_files): 'Get all nested req file names for a list of requirements files.\n\n :param iter requirements_files: list of requirements files to check.\n ' for reqfile in requirement_files: (yield reqfile) if (reqfile and os.path.isfile(reqfile)): parent_dir = os.path.dirname(reqfile) with open(reqfile) as f: (yield from all_nested_req_files((os.path.join(parent_dir, line[2:].strip()) for line in f if (line.startswith('-r') or line.startswith('-c')))))<|docstring|>Get all nested req file names for a list of requirements files. :param iter requirements_files: list of requirements files to check.<|endoftext|>
8a55c121d834a45fbee9cfcb5a6a4629b8ee383fe35bf1fc52518638f46bc6d9
def are_requirements_changed(config): 'Check if any of the requirement files used by testenv is updated.\n\n :param tox.config.TestenvConfig config: Configuration object to observe.\n :rtype: bool\n ' deps = (dep.name for dep in config.deps) def build_fpath_for_previous_version(fname): tox_dir = config.config.toxworkdir.strpath envdirkey = _str_to_sha1hex(str(config.envdir)) fname = '{0}.{1}.previous'.format(fname.replace('/', '-'), envdirkey) return os.path.join(tox_dir, fname) requirement_files = filter(bool, map(parse_requirements_fname, deps)) requirement_files = all_nested_req_files(requirement_files) return any([is_changed(reqfile, build_fpath_for_previous_version(reqfile)) for reqfile in set(requirement_files) if (reqfile and os.path.isfile(reqfile))])
Check if any of the requirement files used by testenv is updated. :param tox.config.TestenvConfig config: Configuration object to observe. :rtype: bool
toxbat/requirements.py
are_requirements_changed
gaborbernat/tox-battery
29
python
def are_requirements_changed(config): 'Check if any of the requirement files used by testenv is updated.\n\n :param tox.config.TestenvConfig config: Configuration object to observe.\n :rtype: bool\n ' deps = (dep.name for dep in config.deps) def build_fpath_for_previous_version(fname): tox_dir = config.config.toxworkdir.strpath envdirkey = _str_to_sha1hex(str(config.envdir)) fname = '{0}.{1}.previous'.format(fname.replace('/', '-'), envdirkey) return os.path.join(tox_dir, fname) requirement_files = filter(bool, map(parse_requirements_fname, deps)) requirement_files = all_nested_req_files(requirement_files) return any([is_changed(reqfile, build_fpath_for_previous_version(reqfile)) for reqfile in set(requirement_files) if (reqfile and os.path.isfile(reqfile))])
def are_requirements_changed(config): 'Check if any of the requirement files used by testenv is updated.\n\n :param tox.config.TestenvConfig config: Configuration object to observe.\n :rtype: bool\n ' deps = (dep.name for dep in config.deps) def build_fpath_for_previous_version(fname): tox_dir = config.config.toxworkdir.strpath envdirkey = _str_to_sha1hex(str(config.envdir)) fname = '{0}.{1}.previous'.format(fname.replace('/', '-'), envdirkey) return os.path.join(tox_dir, fname) requirement_files = filter(bool, map(parse_requirements_fname, deps)) requirement_files = all_nested_req_files(requirement_files) return any([is_changed(reqfile, build_fpath_for_previous_version(reqfile)) for reqfile in set(requirement_files) if (reqfile and os.path.isfile(reqfile))])<|docstring|>Check if any of the requirement files used by testenv is updated. :param tox.config.TestenvConfig config: Configuration object to observe. :rtype: bool<|endoftext|>
45fed5f7d1ba3ef120788209035d7984a1e1a25b5f9c6ce35e551796dfa37a31
def is_changed(fpath, prev_version_fpath): "Check requirements file is updated relatively to prev. version of the file.\n\n :param str fpath: Path to the requirements file.\n :param str prev_version_fpath: Path to the prev. version requirements file.\n :rtype: bool\n :raise ValueError: Requirements file doesn't exist.\n " if (not (fpath and os.path.isfile(fpath))): raise ValueError("Requirements file {0!r} doesn't exist.".format(fpath)) with open(fpath, 'r') as req_file: new_requirements_hash = _str_to_sha1hex(cleanup_requirements_content(req_file.read())) previous_requirements_hash = '' if os.path.exists(prev_version_fpath): with open(prev_version_fpath) as fd: previous_requirements_hash = fd.read() dirname = os.path.dirname(prev_version_fpath) if (not os.path.isdir(dirname)): os.makedirs(dirname) with open(prev_version_fpath, 'w+') as fd: fd.write(new_requirements_hash) return (previous_requirements_hash != new_requirements_hash)
Check requirements file is updated relatively to prev. version of the file. :param str fpath: Path to the requirements file. :param str prev_version_fpath: Path to the prev. version requirements file. :rtype: bool :raise ValueError: Requirements file doesn't exist.
toxbat/requirements.py
is_changed
gaborbernat/tox-battery
29
python
def is_changed(fpath, prev_version_fpath): "Check requirements file is updated relatively to prev. version of the file.\n\n :param str fpath: Path to the requirements file.\n :param str prev_version_fpath: Path to the prev. version requirements file.\n :rtype: bool\n :raise ValueError: Requirements file doesn't exist.\n " if (not (fpath and os.path.isfile(fpath))): raise ValueError("Requirements file {0!r} doesn't exist.".format(fpath)) with open(fpath, 'r') as req_file: new_requirements_hash = _str_to_sha1hex(cleanup_requirements_content(req_file.read())) previous_requirements_hash = if os.path.exists(prev_version_fpath): with open(prev_version_fpath) as fd: previous_requirements_hash = fd.read() dirname = os.path.dirname(prev_version_fpath) if (not os.path.isdir(dirname)): os.makedirs(dirname) with open(prev_version_fpath, 'w+') as fd: fd.write(new_requirements_hash) return (previous_requirements_hash != new_requirements_hash)
def is_changed(fpath, prev_version_fpath): "Check requirements file is updated relatively to prev. version of the file.\n\n :param str fpath: Path to the requirements file.\n :param str prev_version_fpath: Path to the prev. version requirements file.\n :rtype: bool\n :raise ValueError: Requirements file doesn't exist.\n " if (not (fpath and os.path.isfile(fpath))): raise ValueError("Requirements file {0!r} doesn't exist.".format(fpath)) with open(fpath, 'r') as req_file: new_requirements_hash = _str_to_sha1hex(cleanup_requirements_content(req_file.read())) previous_requirements_hash = if os.path.exists(prev_version_fpath): with open(prev_version_fpath) as fd: previous_requirements_hash = fd.read() dirname = os.path.dirname(prev_version_fpath) if (not os.path.isdir(dirname)): os.makedirs(dirname) with open(prev_version_fpath, 'w+') as fd: fd.write(new_requirements_hash) return (previous_requirements_hash != new_requirements_hash)<|docstring|>Check requirements file is updated relatively to prev. version of the file. :param str fpath: Path to the requirements file. :param str prev_version_fpath: Path to the prev. version requirements file. :rtype: bool :raise ValueError: Requirements file doesn't exist.<|endoftext|>
9cdb84837dc5923b55b58fe3f8b23a209407f284b04936d3243e7a14679282be
def parse_requirements_fname(dep_name): "Parse requirements file path from dependency declaration (-r<filepath>).\n\n >>> parse_requirements_fname('pep8')\n >>> parse_requirements_fname('-rrequirements.txt')\n 'requirements.txt'\n\n :param dep_name: Name of the dependency\n :return: Requirements file path specified in the dependency declaration\n if specified otherwise None\n :rtype: str or None\n " req_option = '-r' if dep_name.startswith(req_option): return dep_name[len(req_option):]
Parse requirements file path from dependency declaration (-r<filepath>). >>> parse_requirements_fname('pep8') >>> parse_requirements_fname('-rrequirements.txt') 'requirements.txt' :param dep_name: Name of the dependency :return: Requirements file path specified in the dependency declaration if specified otherwise None :rtype: str or None
toxbat/requirements.py
parse_requirements_fname
gaborbernat/tox-battery
29
python
def parse_requirements_fname(dep_name): "Parse requirements file path from dependency declaration (-r<filepath>).\n\n >>> parse_requirements_fname('pep8')\n >>> parse_requirements_fname('-rrequirements.txt')\n 'requirements.txt'\n\n :param dep_name: Name of the dependency\n :return: Requirements file path specified in the dependency declaration\n if specified otherwise None\n :rtype: str or None\n " req_option = '-r' if dep_name.startswith(req_option): return dep_name[len(req_option):]
def parse_requirements_fname(dep_name): "Parse requirements file path from dependency declaration (-r<filepath>).\n\n >>> parse_requirements_fname('pep8')\n >>> parse_requirements_fname('-rrequirements.txt')\n 'requirements.txt'\n\n :param dep_name: Name of the dependency\n :return: Requirements file path specified in the dependency declaration\n if specified otherwise None\n :rtype: str or None\n " req_option = '-r' if dep_name.startswith(req_option): return dep_name[len(req_option):]<|docstring|>Parse requirements file path from dependency declaration (-r<filepath>). >>> parse_requirements_fname('pep8') >>> parse_requirements_fname('-rrequirements.txt') 'requirements.txt' :param dep_name: Name of the dependency :return: Requirements file path specified in the dependency declaration if specified otherwise None :rtype: str or None<|endoftext|>
abde321af322791d45236ca08c2f882dcdebba04dcb0e8130f4723d6cabc9f4c
def _str_to_sha1hex(v): " Turn string into a SHA1 hex-digest.\n\n >>> _str_to_sha1hex('abc')\n 'a9993e364706816aba3e25717850c26c9cd0d89d'\n " return hashlib.sha1(v.encode('utf-8')).hexdigest()
Turn string into a SHA1 hex-digest. >>> _str_to_sha1hex('abc') 'a9993e364706816aba3e25717850c26c9cd0d89d'
toxbat/requirements.py
_str_to_sha1hex
gaborbernat/tox-battery
29
python
def _str_to_sha1hex(v): " Turn string into a SHA1 hex-digest.\n\n >>> _str_to_sha1hex('abc')\n 'a9993e364706816aba3e25717850c26c9cd0d89d'\n " return hashlib.sha1(v.encode('utf-8')).hexdigest()
def _str_to_sha1hex(v): " Turn string into a SHA1 hex-digest.\n\n >>> _str_to_sha1hex('abc')\n 'a9993e364706816aba3e25717850c26c9cd0d89d'\n " return hashlib.sha1(v.encode('utf-8')).hexdigest()<|docstring|>Turn string into a SHA1 hex-digest. >>> _str_to_sha1hex('abc') 'a9993e364706816aba3e25717850c26c9cd0d89d'<|endoftext|>
cfd31d1c9f4a138855304bc2bbe54e561d56e87db2bff6561bb9732f72caadd3
def isValid(self, s): '\n :type s: str\n :rtype: bool\n ' stack = [] mapping = {')': '(', '}': '{', ']': '['} for char in s: if (char in mapping): tmp = (stack.pop() if stack else '?') if (mapping[char] != tmp): return False else: stack.append(char) return (not stack)
:type s: str :rtype: bool
Python3.x/20-Valid Parentheses.py
isValid
ranchlin/Leetcode
0
python
def isValid(self, s): '\n :type s: str\n :rtype: bool\n ' stack = [] mapping = {')': '(', '}': '{', ']': '['} for char in s: if (char in mapping): tmp = (stack.pop() if stack else '?') if (mapping[char] != tmp): return False else: stack.append(char) return (not stack)
def isValid(self, s): '\n :type s: str\n :rtype: bool\n ' stack = [] mapping = {')': '(', '}': '{', ']': '['} for char in s: if (char in mapping): tmp = (stack.pop() if stack else '?') if (mapping[char] != tmp): return False else: stack.append(char) return (not stack)<|docstring|>:type s: str :rtype: bool<|endoftext|>
87961be40833eda567f50e51529e86ee0353fe4f218e14006f3ce2d4e92ba2c8
def package_node_sources(self, package: Package) -> typing.Mapping[(str, CMakeTarget)]: "\n Extracts the node -> source files mapping for the package with the\n source in ``package_path''\n\n Parameters\n ----------\n package: Package\n The package in the container filesystem that contains the package\n source\n\n Returns\n -------\n Mapping[str, NodeSourceInfo]\n A (possibly empty) mapping between node names provided by the\n package and their source information\n " return self._package_source_extractor.get_cmake_info(package).targets
Extracts the node -> source files mapping for the package with the source in ``package_path'' Parameters ---------- package: Package The package in the container filesystem that contains the package source Returns ------- Mapping[str, NodeSourceInfo] A (possibly empty) mapping between node names provided by the package and their source information
src/roswire/ros2/ros2.py
package_node_sources
ChrisTimperley/roswire
4
python
def package_node_sources(self, package: Package) -> typing.Mapping[(str, CMakeTarget)]: "\n Extracts the node -> source files mapping for the package with the\n source in ``package_path\n\n Parameters\n ----------\n package: Package\n The package in the container filesystem that contains the package\n source\n\n Returns\n -------\n Mapping[str, NodeSourceInfo]\n A (possibly empty) mapping between node names provided by the\n package and their source information\n " return self._package_source_extractor.get_cmake_info(package).targets
def package_node_sources(self, package: Package) -> typing.Mapping[(str, CMakeTarget)]: "\n Extracts the node -> source files mapping for the package with the\n source in ``package_path\n\n Parameters\n ----------\n package: Package\n The package in the container filesystem that contains the package\n source\n\n Returns\n -------\n Mapping[str, NodeSourceInfo]\n A (possibly empty) mapping between node names provided by the\n package and their source information\n " return self._package_source_extractor.get_cmake_info(package).targets<|docstring|>Extracts the node -> source files mapping for the package with the source in ``package_path'' Parameters ---------- package: Package The package in the container filesystem that contains the package source Returns ------- Mapping[str, NodeSourceInfo] A (possibly empty) mapping between node names provided by the package and their source information<|endoftext|>
6be104788c8bc57fc7470c0430ef2de4b45ecea1d98cea48c9fd26ce59df9615
@staticmethod def parse_parameter_string(parameter_string: str): "Parse a parameter string into its constituent name, type, and\n pattern\n\n For example::\n\n parse_parameter_string('<param_one:[A-z]>')` ->\n ('param_one', '[A-z]', <class 'str'>, '[A-z]')\n\n :param parameter_string: String to parse\n :return: tuple containing\n (parameter_name, parameter_type, parameter_pattern)\n " parameter_string = parameter_string.strip('<>') name = parameter_string label = 'string' if (':' in parameter_string): (name, label) = parameter_string.split(':', 1) if (not name): raise ValueError(f'Invalid parameter syntax: {parameter_string}') default = (str, label) (_type, pattern) = REGEX_TYPES.get(label, default) return (name, label, _type, pattern)
Parse a parameter string into its constituent name, type, and pattern For example:: parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', '[A-z]', <class 'str'>, '[A-z]') :param parameter_string: String to parse :return: tuple containing (parameter_name, parameter_type, parameter_pattern)
Eso.API.Statistics/statistics-env/Lib/site-packages/sanic_routing/route.py
parse_parameter_string
afgbeveridge/EsotericLanguagesToolkit
1
python
@staticmethod def parse_parameter_string(parameter_string: str): "Parse a parameter string into its constituent name, type, and\n pattern\n\n For example::\n\n parse_parameter_string('<param_one:[A-z]>')` ->\n ('param_one', '[A-z]', <class 'str'>, '[A-z]')\n\n :param parameter_string: String to parse\n :return: tuple containing\n (parameter_name, parameter_type, parameter_pattern)\n " parameter_string = parameter_string.strip('<>') name = parameter_string label = 'string' if (':' in parameter_string): (name, label) = parameter_string.split(':', 1) if (not name): raise ValueError(f'Invalid parameter syntax: {parameter_string}') default = (str, label) (_type, pattern) = REGEX_TYPES.get(label, default) return (name, label, _type, pattern)
@staticmethod def parse_parameter_string(parameter_string: str): "Parse a parameter string into its constituent name, type, and\n pattern\n\n For example::\n\n parse_parameter_string('<param_one:[A-z]>')` ->\n ('param_one', '[A-z]', <class 'str'>, '[A-z]')\n\n :param parameter_string: String to parse\n :return: tuple containing\n (parameter_name, parameter_type, parameter_pattern)\n " parameter_string = parameter_string.strip('<>') name = parameter_string label = 'string' if (':' in parameter_string): (name, label) = parameter_string.split(':', 1) if (not name): raise ValueError(f'Invalid parameter syntax: {parameter_string}') default = (str, label) (_type, pattern) = REGEX_TYPES.get(label, default) return (name, label, _type, pattern)<|docstring|>Parse a parameter string into its constituent name, type, and pattern For example:: parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', '[A-z]', <class 'str'>, '[A-z]') :param parameter_string: String to parse :return: tuple containing (parameter_name, parameter_type, parameter_pattern)<|endoftext|>
fc71e3c4876d9c4a7ed0772ffcc3e07f95863b272123b3654167de517b504f7c
def wait_for_srq(self, timeout=25000): '\n Wait for a serial request (SRQ) or the timeout to expire.\n\n Parameters\n ----------\n timeout : int or None, optional\n The maximum waiting time in milliseconds. \n None means waiting forever if necessary.\n \n Raises\n ------\n pyvisa.error.VisaIOError: if timeout has expired\n ' return self._instrument.wait_for_srq(timeout)
Wait for a serial request (SRQ) or the timeout to expire. Parameters ---------- timeout : int or None, optional The maximum waiting time in milliseconds. None means waiting forever if necessary. Raises ------ pyvisa.error.VisaIOError: if timeout has expired
uedinst/base.py
wait_for_srq
trbritt/uedinst
0
python
def wait_for_srq(self, timeout=25000): '\n Wait for a serial request (SRQ) or the timeout to expire.\n\n Parameters\n ----------\n timeout : int or None, optional\n The maximum waiting time in milliseconds. \n None means waiting forever if necessary.\n \n Raises\n ------\n pyvisa.error.VisaIOError: if timeout has expired\n ' return self._instrument.wait_for_srq(timeout)
def wait_for_srq(self, timeout=25000): '\n Wait for a serial request (SRQ) or the timeout to expire.\n\n Parameters\n ----------\n timeout : int or None, optional\n The maximum waiting time in milliseconds. \n None means waiting forever if necessary.\n \n Raises\n ------\n pyvisa.error.VisaIOError: if timeout has expired\n ' return self._instrument.wait_for_srq(timeout)<|docstring|>Wait for a serial request (SRQ) or the timeout to expire. Parameters ---------- timeout : int or None, optional The maximum waiting time in milliseconds. None means waiting forever if necessary. Raises ------ pyvisa.error.VisaIOError: if timeout has expired<|endoftext|>
464e0969462ce8252280179e5fd96fd8bbcbff79b0a5f8bac522325eed729acf
def clear(self): ' Clear buffers which might not be empty due to errors ' self.reset_input_buffer() self.reset_output_buffer()
Clear buffers which might not be empty due to errors
uedinst/base.py
clear
trbritt/uedinst
0
python
def clear(self): ' ' self.reset_input_buffer() self.reset_output_buffer()
def clear(self): ' ' self.reset_input_buffer() self.reset_output_buffer()<|docstring|>Clear buffers which might not be empty due to errors<|endoftext|>
000296b58f514ec978ca3494bd32bd7e7560df6cbe3ba7883a2fa2eb17dcacdf
def read_str(self, *args, **kwargs): "\n Read strings from instrument. Strings are automatically\n decoded.\n\n Parameters\n ----------\n size : int\n Number of bytes to read. Bytes are decoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n data : str\n Read information. If the instrument timeout was exceeded,\n ``data`` will be an empty or incomplete string.\n " return super().read(*args, **kwargs).decode(self.ENCODING)
Read strings from instrument. Strings are automatically decoded. Parameters ---------- size : int Number of bytes to read. Bytes are decoded in according to the instrument's ``ENCODING`` attribute. Returns ------- data : str Read information. If the instrument timeout was exceeded, ``data`` will be an empty or incomplete string.
uedinst/base.py
read_str
trbritt/uedinst
0
python
def read_str(self, *args, **kwargs): "\n Read strings from instrument. Strings are automatically\n decoded.\n\n Parameters\n ----------\n size : int\n Number of bytes to read. Bytes are decoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n data : str\n Read information. If the instrument timeout was exceeded,\n ``data`` will be an empty or incomplete string.\n " return super().read(*args, **kwargs).decode(self.ENCODING)
def read_str(self, *args, **kwargs): "\n Read strings from instrument. Strings are automatically\n decoded.\n\n Parameters\n ----------\n size : int\n Number of bytes to read. Bytes are decoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n data : str\n Read information. If the instrument timeout was exceeded,\n ``data`` will be an empty or incomplete string.\n " return super().read(*args, **kwargs).decode(self.ENCODING)<|docstring|>Read strings from instrument. Strings are automatically decoded. Parameters ---------- size : int Number of bytes to read. Bytes are decoded in according to the instrument's ``ENCODING`` attribute. Returns ------- data : str Read information. If the instrument timeout was exceeded, ``data`` will be an empty or incomplete string.<|endoftext|>
05fddc5e048b70c36da07154c99879abab485ec97e6b3b0f668464dd3c67d4c2
def write_str(self, data, *args, **kwargs): "\n Write strings to instrument. Strings are automatically\n encoded.\n\n Parameters\n ----------\n data : str\n Data to be sent. Strings are encoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n sent : int\n Number of bytes successfully written.\n\n Raises\n ------\n InstrumentException : incomplete write\n " returned = super().write(data.encode(self.ENCODING), *args, **kwargs) self.flush() return returned
Write strings to instrument. Strings are automatically encoded. Parameters ---------- data : str Data to be sent. Strings are encoded in according to the instrument's ``ENCODING`` attribute. Returns ------- sent : int Number of bytes successfully written. Raises ------ InstrumentException : incomplete write
uedinst/base.py
write_str
trbritt/uedinst
0
python
def write_str(self, data, *args, **kwargs): "\n Write strings to instrument. Strings are automatically\n encoded.\n\n Parameters\n ----------\n data : str\n Data to be sent. Strings are encoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n sent : int\n Number of bytes successfully written.\n\n Raises\n ------\n InstrumentException : incomplete write\n " returned = super().write(data.encode(self.ENCODING), *args, **kwargs) self.flush() return returned
def write_str(self, data, *args, **kwargs): "\n Write strings to instrument. Strings are automatically\n encoded.\n\n Parameters\n ----------\n data : str\n Data to be sent. Strings are encoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n sent : int\n Number of bytes successfully written.\n\n Raises\n ------\n InstrumentException : incomplete write\n " returned = super().write(data.encode(self.ENCODING), *args, **kwargs) self.flush() return returned<|docstring|>Write strings to instrument. Strings are automatically encoded. Parameters ---------- data : str Data to be sent. Strings are encoded in according to the instrument's ``ENCODING`` attribute. Returns ------- sent : int Number of bytes successfully written. Raises ------ InstrumentException : incomplete write<|endoftext|>
000296b58f514ec978ca3494bd32bd7e7560df6cbe3ba7883a2fa2eb17dcacdf
def read_str(self, *args, **kwargs): "\n Read strings from instrument. Strings are automatically\n decoded.\n\n Parameters\n ----------\n size : int\n Number of bytes to read. Bytes are decoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n data : str\n Read information. If the instrument timeout was exceeded,\n ``data`` will be an empty or incomplete string.\n " return super().read(*args, **kwargs).decode(self.ENCODING)
Read strings from instrument. Strings are automatically decoded. Parameters ---------- size : int Number of bytes to read. Bytes are decoded in according to the instrument's ``ENCODING`` attribute. Returns ------- data : str Read information. If the instrument timeout was exceeded, ``data`` will be an empty or incomplete string.
uedinst/base.py
read_str
trbritt/uedinst
0
python
def read_str(self, *args, **kwargs): "\n Read strings from instrument. Strings are automatically\n decoded.\n\n Parameters\n ----------\n size : int\n Number of bytes to read. Bytes are decoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n data : str\n Read information. If the instrument timeout was exceeded,\n ``data`` will be an empty or incomplete string.\n " return super().read(*args, **kwargs).decode(self.ENCODING)
def read_str(self, *args, **kwargs): "\n Read strings from instrument. Strings are automatically\n decoded.\n\n Parameters\n ----------\n size : int\n Number of bytes to read. Bytes are decoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n data : str\n Read information. If the instrument timeout was exceeded,\n ``data`` will be an empty or incomplete string.\n " return super().read(*args, **kwargs).decode(self.ENCODING)<|docstring|>Read strings from instrument. Strings are automatically decoded. Parameters ---------- size : int Number of bytes to read. Bytes are decoded in according to the instrument's ``ENCODING`` attribute. Returns ------- data : str Read information. If the instrument timeout was exceeded, ``data`` will be an empty or incomplete string.<|endoftext|>
05fddc5e048b70c36da07154c99879abab485ec97e6b3b0f668464dd3c67d4c2
def write_str(self, data, *args, **kwargs): "\n Write strings to instrument. Strings are automatically\n encoded.\n\n Parameters\n ----------\n data : str\n Data to be sent. Strings are encoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n sent : int\n Number of bytes successfully written.\n\n Raises\n ------\n InstrumentException : incomplete write\n " returned = super().write(data.encode(self.ENCODING), *args, **kwargs) self.flush() return returned
Write strings to instrument. Strings are automatically encoded. Parameters ---------- data : str Data to be sent. Strings are encoded in according to the instrument's ``ENCODING`` attribute. Returns ------- sent : int Number of bytes successfully written. Raises ------ InstrumentException : incomplete write
uedinst/base.py
write_str
trbritt/uedinst
0
python
def write_str(self, data, *args, **kwargs): "\n Write strings to instrument. Strings are automatically\n encoded.\n\n Parameters\n ----------\n data : str\n Data to be sent. Strings are encoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n sent : int\n Number of bytes successfully written.\n\n Raises\n ------\n InstrumentException : incomplete write\n " returned = super().write(data.encode(self.ENCODING), *args, **kwargs) self.flush() return returned
def write_str(self, data, *args, **kwargs): "\n Write strings to instrument. Strings are automatically\n encoded.\n\n Parameters\n ----------\n data : str\n Data to be sent. Strings are encoded in according to the \n instrument's ``ENCODING`` attribute.\n\n Returns\n -------\n sent : int\n Number of bytes successfully written.\n\n Raises\n ------\n InstrumentException : incomplete write\n " returned = super().write(data.encode(self.ENCODING), *args, **kwargs) self.flush() return returned<|docstring|>Write strings to instrument. Strings are automatically encoded. Parameters ---------- data : str Data to be sent. Strings are encoded in according to the instrument's ``ENCODING`` attribute. Returns ------- sent : int Number of bytes successfully written. Raises ------ InstrumentException : incomplete write<|endoftext|>
e83c4135d44c0b538bc159d3bb009de8d4b9848650f89f8565f5f8cb098a0a8d
@staticmethod def _add_system_time_interval(system_time, increment): "increment's unit: 10ns" file_time = cryptoapi.FILETIME() if (not cryptoapi.SystemTimeToFileTime(ctypes.byref(system_time), ctypes.byref(file_time))): raise cryptoapi.CryptoAPIException() t = (file_time.dwLowDateTime + (file_time.dwHighDateTime << 32)) t += increment file_time.dwLowDateTime = (t & 4294967295) file_time.dwHighDateTime = ((t >> 32) & 4294967295) new_system_time = cryptoapi.SYSTEMTIME() if (not cryptoapi.FileTimeToSystemTime(ctypes.byref(file_time), ctypes.byref(new_system_time))): raise cryptoapi.CryptoAPIException() return new_system_time
increment's unit: 10ns
cloudbaseinit/utils/windows/x509.py
_add_system_time_interval
kimbernator/cloudbase-init
160
python
@staticmethod def _add_system_time_interval(system_time, increment): file_time = cryptoapi.FILETIME() if (not cryptoapi.SystemTimeToFileTime(ctypes.byref(system_time), ctypes.byref(file_time))): raise cryptoapi.CryptoAPIException() t = (file_time.dwLowDateTime + (file_time.dwHighDateTime << 32)) t += increment file_time.dwLowDateTime = (t & 4294967295) file_time.dwHighDateTime = ((t >> 32) & 4294967295) new_system_time = cryptoapi.SYSTEMTIME() if (not cryptoapi.FileTimeToSystemTime(ctypes.byref(file_time), ctypes.byref(new_system_time))): raise cryptoapi.CryptoAPIException() return new_system_time
@staticmethod def _add_system_time_interval(system_time, increment): file_time = cryptoapi.FILETIME() if (not cryptoapi.SystemTimeToFileTime(ctypes.byref(system_time), ctypes.byref(file_time))): raise cryptoapi.CryptoAPIException() t = (file_time.dwLowDateTime + (file_time.dwHighDateTime << 32)) t += increment file_time.dwLowDateTime = (t & 4294967295) file_time.dwHighDateTime = ((t >> 32) & 4294967295) new_system_time = cryptoapi.SYSTEMTIME() if (not cryptoapi.FileTimeToSystemTime(ctypes.byref(file_time), ctypes.byref(new_system_time))): raise cryptoapi.CryptoAPIException() return new_system_time<|docstring|>increment's unit: 10ns<|endoftext|>
8a35d7c0fe19d35482a0af815325a8a1a010cf8fac860b224dabed70ae76eba7
def _get_cert_base64(self, cert_data): 'Remove certificate header and footer and also new lines.' removal = [x509constants.PEM_HEADER, x509constants.PEM_FOOTER, '\r', '\n'] for remove in removal: cert_data = cert_data.replace(remove, '') return cert_data
Remove certificate header and footer and also new lines.
cloudbaseinit/utils/windows/x509.py
_get_cert_base64
kimbernator/cloudbase-init
160
python
def _get_cert_base64(self, cert_data): removal = [x509constants.PEM_HEADER, x509constants.PEM_FOOTER, '\r', '\n'] for remove in removal: cert_data = cert_data.replace(remove, ) return cert_data
def _get_cert_base64(self, cert_data): removal = [x509constants.PEM_HEADER, x509constants.PEM_FOOTER, '\r', '\n'] for remove in removal: cert_data = cert_data.replace(remove, ) return cert_data<|docstring|>Remove certificate header and footer and also new lines.<|endoftext|>
d84244682b3de22170c540262ffa33eae013cf21f6f204faaf5ecf8abc0cc413
def multiline_replace(content: str) -> str: 'multiline_replace deals with more complicated statements which possibly span multiple lines' regexp = re.compile('^\\s*proc(\\s|\\\\\\n)*([a-zA-Z0-9-_]+)(\\s|\\\\\\n)*({([a-zA-Z0-9-_\\\\\\n ]*)}){0,1}(\\s|\\\\\\n)*{', ((re.IGNORECASE | re.MULTILINE) | re.DOTALL)) content = regexp.sub('proc \\2 {\\5 args} {', content) regexp = re.compile('^\\s*when\\s+(\\\\\\n|\\s)*(\\w+)(\\\\\\n|\\s)*(priority|timing|(\\d+)|on|off|\\\\\\n|\\s)*{', ((re.IGNORECASE | re.MULTILINE) | re.DOTALL)) content = regexp.sub('proc \\2 {args} {', content) regexp = re.compile('(?<!\\\\)\\n\\s*({|else|elseif)', re.IGNORECASE) content = regexp.sub(' \\1', content) return content
multiline_replace deals with more complicated statements which possibly span multiple lines
tclscanner/files/tclscanner.py
multiline_replace
simonkowallik/docker
2
python
def multiline_replace(content: str) -> str: regexp = re.compile('^\\s*proc(\\s|\\\\\\n)*([a-zA-Z0-9-_]+)(\\s|\\\\\\n)*({([a-zA-Z0-9-_\\\\\\n ]*)}){0,1}(\\s|\\\\\\n)*{', ((re.IGNORECASE | re.MULTILINE) | re.DOTALL)) content = regexp.sub('proc \\2 {\\5 args} {', content) regexp = re.compile('^\\s*when\\s+(\\\\\\n|\\s)*(\\w+)(\\\\\\n|\\s)*(priority|timing|(\\d+)|on|off|\\\\\\n|\\s)*{', ((re.IGNORECASE | re.MULTILINE) | re.DOTALL)) content = regexp.sub('proc \\2 {args} {', content) regexp = re.compile('(?<!\\\\)\\n\\s*({|else|elseif)', re.IGNORECASE) content = regexp.sub(' \\1', content) return content
def multiline_replace(content: str) -> str: regexp = re.compile('^\\s*proc(\\s|\\\\\\n)*([a-zA-Z0-9-_]+)(\\s|\\\\\\n)*({([a-zA-Z0-9-_\\\\\\n ]*)}){0,1}(\\s|\\\\\\n)*{', ((re.IGNORECASE | re.MULTILINE) | re.DOTALL)) content = regexp.sub('proc \\2 {\\5 args} {', content) regexp = re.compile('^\\s*when\\s+(\\\\\\n|\\s)*(\\w+)(\\\\\\n|\\s)*(priority|timing|(\\d+)|on|off|\\\\\\n|\\s)*{', ((re.IGNORECASE | re.MULTILINE) | re.DOTALL)) content = regexp.sub('proc \\2 {args} {', content) regexp = re.compile('(?<!\\\\)\\n\\s*({|else|elseif)', re.IGNORECASE) content = regexp.sub(' \\1', content) return content<|docstring|>multiline_replace deals with more complicated statements which possibly span multiple lines<|endoftext|>
4bdf6e0ac0b36133b4df980815f4d32e73773e3b4dac27f04b1e9733137ccf92
def singleline_replace(content: str) -> str: 'singleline_replace performs simple replacements' content_new: str = '' for line in content.splitlines(keepends=False): line = line.replace('equals', 'eq') line = line.replace('starts_with', 'eq') line = line.replace('ends_with', 'eq') line = line.replace('contains', 'eq') line = line.replace('matches_glob', 'eq') line = line.replace('matches_regex', 'eq') line = line.replace('call', '') line = line.replace('}{', '} {') line = line.replace('switch', '$switch') line = line.replace('static::', 'static__') line = re.sub('^(\\s*timing\\s+[OoNnFf]{2,3})$', 'set \\1', line) line = re.sub('^(\\s*priority\\s+\\d+)$', 'set \\1', line) content_new += line content_new += '\n' return content_new
singleline_replace performs simple replacements
tclscanner/files/tclscanner.py
singleline_replace
simonkowallik/docker
2
python
def singleline_replace(content: str) -> str: content_new: str = for line in content.splitlines(keepends=False): line = line.replace('equals', 'eq') line = line.replace('starts_with', 'eq') line = line.replace('ends_with', 'eq') line = line.replace('contains', 'eq') line = line.replace('matches_glob', 'eq') line = line.replace('matches_regex', 'eq') line = line.replace('call', ) line = line.replace('}{', '} {') line = line.replace('switch', '$switch') line = line.replace('static::', 'static__') line = re.sub('^(\\s*timing\\s+[OoNnFf]{2,3})$', 'set \\1', line) line = re.sub('^(\\s*priority\\s+\\d+)$', 'set \\1', line) content_new += line content_new += '\n' return content_new
def singleline_replace(content: str) -> str: content_new: str = for line in content.splitlines(keepends=False): line = line.replace('equals', 'eq') line = line.replace('starts_with', 'eq') line = line.replace('ends_with', 'eq') line = line.replace('contains', 'eq') line = line.replace('matches_glob', 'eq') line = line.replace('matches_regex', 'eq') line = line.replace('call', ) line = line.replace('}{', '} {') line = line.replace('switch', '$switch') line = line.replace('static::', 'static__') line = re.sub('^(\\s*timing\\s+[OoNnFf]{2,3})$', 'set \\1', line) line = re.sub('^(\\s*priority\\s+\\d+)$', 'set \\1', line) content_new += line content_new += '\n' return content_new<|docstring|>singleline_replace performs simple replacements<|endoftext|>
ccc1ff664e2f53007c9d2431d59f8275a16a40006d70f06382c3a5487b60ad5e
def checkascii(content: str) -> dict: 'checkascii expects content as str and checks whether it is ascii (True) or not (False).\n It returns True if content is ascii, False otherwise' try: content.encode('ascii') except UnicodeEncodeError as error: return {'isascii': False, 'error': f'{error}'} return {'isascii': True, 'error': ''}
checkascii expects content as str and checks whether it is ascii (True) or not (False). It returns True if content is ascii, False otherwise
tclscanner/files/tclscanner.py
checkascii
simonkowallik/docker
2
python
def checkascii(content: str) -> dict: 'checkascii expects content as str and checks whether it is ascii (True) or not (False).\n It returns True if content is ascii, False otherwise' try: content.encode('ascii') except UnicodeEncodeError as error: return {'isascii': False, 'error': f'{error}'} return {'isascii': True, 'error': }
def checkascii(content: str) -> dict: 'checkascii expects content as str and checks whether it is ascii (True) or not (False).\n It returns True if content is ascii, False otherwise' try: content.encode('ascii') except UnicodeEncodeError as error: return {'isascii': False, 'error': f'{error}'} return {'isascii': True, 'error': }<|docstring|>checkascii expects content as str and checks whether it is ascii (True) or not (False). It returns True if content is ascii, False otherwise<|endoftext|>
8ceedebf05abd073101ec338cb14e6cc7e48a9272d7cd77de10167db2896b7d5
def create_tmp_file(content: str) -> str: 'create_tmp_file creates a secure temp file and writes content to it.\n returns filename as str' (filedesciptor, filename) = mkstemp() with open(filedesciptor, 'w') as tmpfile: tmpfile.write(content) return str(filename)
create_tmp_file creates a secure temp file and writes content to it. returns filename as str
tclscanner/files/tclscanner.py
create_tmp_file
simonkowallik/docker
2
python
def create_tmp_file(content: str) -> str: 'create_tmp_file creates a secure temp file and writes content to it.\n returns filename as str' (filedesciptor, filename) = mkstemp() with open(filedesciptor, 'w') as tmpfile: tmpfile.write(content) return str(filename)
def create_tmp_file(content: str) -> str: 'create_tmp_file creates a secure temp file and writes content to it.\n returns filename as str' (filedesciptor, filename) = mkstemp() with open(filedesciptor, 'w') as tmpfile: tmpfile.write(content) return str(filename)<|docstring|>create_tmp_file creates a secure temp file and writes content to it. returns filename as str<|endoftext|>
e1e72bf8586a30bd04fec871265a7c30d529616ec2e56619471369efb5ebd3f1
def tclscan(filename: str) -> dict: 'tclscan executes tclscan in a subprocess.\n It expects filename as str and returns a dict with errors, warnings and dangerous as lists.\n ' results: dict = {'errors': [], 'warnings': [], 'dangerous': []} result = subprocess.run(['tclscan', 'check', shlex_quote(filename)], capture_output=True) try: result.check_returncode() except subprocess.CalledProcessError: err: str = 'ERROR: cannot scan, manual code verification required, error: ' err += result.stderr.decode('utf8') results['errors'].append(err) return results res = result.stdout.replace(b'\\\n', b'') res = res.decode('utf8') for line in res.splitlines(False): if (not line): continue elif line.startswith('WARNING: message:badly formed command'): results['errors'].append(line.replace('WARNING: message:', '')) elif line.startswith('DANGEROUS:'): results['dangerous'].append(line.replace('DANGEROUS: message:', '')) elif line.startswith('WARNING:'): results['warnings'].append(line.replace('WARNING: message:', '')) else: results['errors'].append(line[0:1024]) return results
tclscan executes tclscan in a subprocess. It expects filename as str and returns a dict with errors, warnings and dangerous as lists.
tclscanner/files/tclscanner.py
tclscan
simonkowallik/docker
2
python
def tclscan(filename: str) -> dict: 'tclscan executes tclscan in a subprocess.\n It expects filename as str and returns a dict with errors, warnings and dangerous as lists.\n ' results: dict = {'errors': [], 'warnings': [], 'dangerous': []} result = subprocess.run(['tclscan', 'check', shlex_quote(filename)], capture_output=True) try: result.check_returncode() except subprocess.CalledProcessError: err: str = 'ERROR: cannot scan, manual code verification required, error: ' err += result.stderr.decode('utf8') results['errors'].append(err) return results res = result.stdout.replace(b'\\\n', b) res = res.decode('utf8') for line in res.splitlines(False): if (not line): continue elif line.startswith('WARNING: message:badly formed command'): results['errors'].append(line.replace('WARNING: message:', )) elif line.startswith('DANGEROUS:'): results['dangerous'].append(line.replace('DANGEROUS: message:', )) elif line.startswith('WARNING:'): results['warnings'].append(line.replace('WARNING: message:', )) else: results['errors'].append(line[0:1024]) return results
def tclscan(filename: str) -> dict: 'tclscan executes tclscan in a subprocess.\n It expects filename as str and returns a dict with errors, warnings and dangerous as lists.\n ' results: dict = {'errors': [], 'warnings': [], 'dangerous': []} result = subprocess.run(['tclscan', 'check', shlex_quote(filename)], capture_output=True) try: result.check_returncode() except subprocess.CalledProcessError: err: str = 'ERROR: cannot scan, manual code verification required, error: ' err += result.stderr.decode('utf8') results['errors'].append(err) return results res = result.stdout.replace(b'\\\n', b) res = res.decode('utf8') for line in res.splitlines(False): if (not line): continue elif line.startswith('WARNING: message:badly formed command'): results['errors'].append(line.replace('WARNING: message:', )) elif line.startswith('DANGEROUS:'): results['dangerous'].append(line.replace('DANGEROUS: message:', )) elif line.startswith('WARNING:'): results['warnings'].append(line.replace('WARNING: message:', )) else: results['errors'].append(line[0:1024]) return results<|docstring|>tclscan executes tclscan in a subprocess. It expects filename as str and returns a dict with errors, warnings and dangerous as lists.<|endoftext|>
3e4569524b34bdb59227b5da9928d0ac920abbd6e2e714b05bb126cc078cfb4d
def convert_tclcode(tclcode: str) -> str: 'convert_tclcode applies replacements to DSL tclcode for standard tcl interpretation to work. it returns the re-formated code as str.\n ' tclcode = multiline_replace(tclcode) tclcode = singleline_replace(tclcode) return tclcode
convert_tclcode applies replacements to DSL tclcode for standard tcl interpretation to work. it returns the re-formated code as str.
tclscanner/files/tclscanner.py
convert_tclcode
simonkowallik/docker
2
python
def convert_tclcode(tclcode: str) -> str: '\n ' tclcode = multiline_replace(tclcode) tclcode = singleline_replace(tclcode) return tclcode
def convert_tclcode(tclcode: str) -> str: '\n ' tclcode = multiline_replace(tclcode) tclcode = singleline_replace(tclcode) return tclcode<|docstring|>convert_tclcode applies replacements to DSL tclcode for standard tcl interpretation to work. it returns the re-formated code as str.<|endoftext|>
37a39883434a25fbb02fa2cfb234f5e694367a9145787d30ded8b9a0fccb5124
def run_scan(tclcode: str) -> dict: 'run_scan expects tclcode as str. It runs several checks and reformats it before running tclscan.\n It returns a dict with all results. Dict contains errors, warnings and dangerous as lists.\n ' results: dict = {'errors': [], 'warnings': [], 'dangerous': []} tclsresults: dict = {} asciicheck: dict = checkascii(tclcode) if (not asciicheck['isascii']): results['warnings'].append(asciicheck['error']) tclcode = convert_tclcode(tclcode=tclcode) tmpfile = create_tmp_file(content=tclcode) tclsresults = tclscan(tmpfile) os.remove(tmpfile) results['errors'].extend(tclsresults['errors']) results['warnings'].extend(tclsresults['warnings']) results['dangerous'].extend(tclsresults['dangerous']) return results
run_scan expects tclcode as str. It runs several checks and reformats it before running tclscan. It returns a dict with all results. Dict contains errors, warnings and dangerous as lists.
tclscanner/files/tclscanner.py
run_scan
simonkowallik/docker
2
python
def run_scan(tclcode: str) -> dict: 'run_scan expects tclcode as str. It runs several checks and reformats it before running tclscan.\n It returns a dict with all results. Dict contains errors, warnings and dangerous as lists.\n ' results: dict = {'errors': [], 'warnings': [], 'dangerous': []} tclsresults: dict = {} asciicheck: dict = checkascii(tclcode) if (not asciicheck['isascii']): results['warnings'].append(asciicheck['error']) tclcode = convert_tclcode(tclcode=tclcode) tmpfile = create_tmp_file(content=tclcode) tclsresults = tclscan(tmpfile) os.remove(tmpfile) results['errors'].extend(tclsresults['errors']) results['warnings'].extend(tclsresults['warnings']) results['dangerous'].extend(tclsresults['dangerous']) return results
def run_scan(tclcode: str) -> dict: 'run_scan expects tclcode as str. It runs several checks and reformats it before running tclscan.\n It returns a dict with all results. Dict contains errors, warnings and dangerous as lists.\n ' results: dict = {'errors': [], 'warnings': [], 'dangerous': []} tclsresults: dict = {} asciicheck: dict = checkascii(tclcode) if (not asciicheck['isascii']): results['warnings'].append(asciicheck['error']) tclcode = convert_tclcode(tclcode=tclcode) tmpfile = create_tmp_file(content=tclcode) tclsresults = tclscan(tmpfile) os.remove(tmpfile) results['errors'].extend(tclsresults['errors']) results['warnings'].extend(tclsresults['warnings']) results['dangerous'].extend(tclsresults['dangerous']) return results<|docstring|>run_scan expects tclcode as str. It runs several checks and reformats it before running tclscan. It returns a dict with all results. Dict contains errors, warnings and dangerous as lists.<|endoftext|>
ac0d40de7f4a1fddf5173055dbb64271ae3df03fd568b597decd5e25f2c30b8d
def process_directory(directory: str, file_extensions: list) -> dict: 'process_directory recursively walks directory, copies files to tmpfiles, scans them and returns results as dict str' results: dict = {} for (dirpath, _, files) in os.walk(directory): for filename in files: if file_extensions: extension = filename.split('.')[(- 1)] extension = extension.lower() if (not (extension in file_extensions)): continue fname = os.path.join(dirpath, filename) filecontent: str = '' results[f'{fname}'] = {'errors': [], 'warnings': [], 'dangerous': []} try: with open(fname, 'rt') as workingfile: filecontent = workingfile.read() except UnicodeDecodeError as error: results[f'{fname}']['errors'].append(f'could not read file, error:{error}') continue results[fname] = run_scan(filecontent) return results
process_directory recursively walks directory, copies files to tmpfiles, scans them and returns results as dict str
tclscanner/files/tclscanner.py
process_directory
simonkowallik/docker
2
python
def process_directory(directory: str, file_extensions: list) -> dict: results: dict = {} for (dirpath, _, files) in os.walk(directory): for filename in files: if file_extensions: extension = filename.split('.')[(- 1)] extension = extension.lower() if (not (extension in file_extensions)): continue fname = os.path.join(dirpath, filename) filecontent: str = results[f'{fname}'] = {'errors': [], 'warnings': [], 'dangerous': []} try: with open(fname, 'rt') as workingfile: filecontent = workingfile.read() except UnicodeDecodeError as error: results[f'{fname}']['errors'].append(f'could not read file, error:{error}') continue results[fname] = run_scan(filecontent) return results
def process_directory(directory: str, file_extensions: list) -> dict: results: dict = {} for (dirpath, _, files) in os.walk(directory): for filename in files: if file_extensions: extension = filename.split('.')[(- 1)] extension = extension.lower() if (not (extension in file_extensions)): continue fname = os.path.join(dirpath, filename) filecontent: str = results[f'{fname}'] = {'errors': [], 'warnings': [], 'dangerous': []} try: with open(fname, 'rt') as workingfile: filecontent = workingfile.read() except UnicodeDecodeError as error: results[f'{fname}']['errors'].append(f'could not read file, error:{error}') continue results[fname] = run_scan(filecontent) return results<|docstring|>process_directory recursively walks directory, copies files to tmpfiles, scans them and returns results as dict str<|endoftext|>
b02b89b698b6d03122d94a2e9811ca1efe6b27346e6c8bddace5201ec5350367
def main(): 'main function reads directory argument and runs process_directory. prints results as json to stdout' parser = argparse.ArgumentParser() parser.add_argument('-d', '--directory', help='base directory to scan recursively', type=str, default='.') parser.add_argument('-f', '--file-extensions', nargs='*', help='filter for file extensions (case insensitive, default is to scan all files)') parser.add_argument('--code-convert-only', type=str, help='only convert code for the specified file (prints to stdout)') args = parser.parse_args() if args.code_convert_only: try: with open(args.code_convert_only, 'rt') as workingfile: filecontent = workingfile.read() print(convert_tclcode(filecontent), end='') except UnicodeDecodeError as error: print(f'ERROR: could not read file, error:{error}') return if (args.file_extensions is None): args.file_extensions = [] args.file_extensions = [x.lower() for x in args.file_extensions] results = process_directory(directory=args.directory, file_extensions=args.file_extensions) result_json = json.dumps(results) print(result_json)
main function reads directory argument and runs process_directory. prints results as json to stdout
tclscanner/files/tclscanner.py
main
simonkowallik/docker
2
python
def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--directory', help='base directory to scan recursively', type=str, default='.') parser.add_argument('-f', '--file-extensions', nargs='*', help='filter for file extensions (case insensitive, default is to scan all files)') parser.add_argument('--code-convert-only', type=str, help='only convert code for the specified file (prints to stdout)') args = parser.parse_args() if args.code_convert_only: try: with open(args.code_convert_only, 'rt') as workingfile: filecontent = workingfile.read() print(convert_tclcode(filecontent), end=) except UnicodeDecodeError as error: print(f'ERROR: could not read file, error:{error}') return if (args.file_extensions is None): args.file_extensions = [] args.file_extensions = [x.lower() for x in args.file_extensions] results = process_directory(directory=args.directory, file_extensions=args.file_extensions) result_json = json.dumps(results) print(result_json)
def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--directory', help='base directory to scan recursively', type=str, default='.') parser.add_argument('-f', '--file-extensions', nargs='*', help='filter for file extensions (case insensitive, default is to scan all files)') parser.add_argument('--code-convert-only', type=str, help='only convert code for the specified file (prints to stdout)') args = parser.parse_args() if args.code_convert_only: try: with open(args.code_convert_only, 'rt') as workingfile: filecontent = workingfile.read() print(convert_tclcode(filecontent), end=) except UnicodeDecodeError as error: print(f'ERROR: could not read file, error:{error}') return if (args.file_extensions is None): args.file_extensions = [] args.file_extensions = [x.lower() for x in args.file_extensions] results = process_directory(directory=args.directory, file_extensions=args.file_extensions) result_json = json.dumps(results) print(result_json)<|docstring|>main function reads directory argument and runs process_directory. prints results as json to stdout<|endoftext|>
53f6a8557bda8761d4eda7ea23ecf0715b65244f39e0c03bceee54e351ca9ac7
def sim_config(): '\n Example simulator configuration.\n ' return {'simulator': {'height': 256, 'width': 256, 'layers': [{'id': 'Back0', 'config_id': '0', 'filters': [{'type': 'RandomColorMeanFilter', 'params': {'dr': 100, 'dg': 100, 'db': 100}}]}, {'id': 'Sky0', 'config_id': '1', 'prob': 1, 'filters': [{'type': 'ConstantColorFilter', 'params': {'dr': 100, 'dg': 100, 'db': 100}}]}, {'id': 'Road0', 'config_id': '2', 'prob': 1, 'serialize': 1, 'filters': [{'type': 'ShiftRoadFilter', 'params': {'lb': (- 0.2), 'ub': 0.2}}, {'type': 'ShiftLanesFilter', 'params': {'lb': (- 0.02), 'ub': 0.02}}, {'type': 'TiltRoadFilter', 'params': {'lb': (- 1.5), 'ub': 1.5}}, {'type': 'LaneWidthFilter', 'params': {'lb': (- 0.01), 'ub': 0.01}}]}], 'layer_configs': {'0': {'layer_type': 'BackgroundLayer', 'layer_params': {'color_fct': {'type': 'random', 'params': {'mean': [0, 120, 80], 'range': 20}}}}, '1': {'layer_type': 'SkyLayer', 'layer_params': {'color_fct': {'type': 'constant', 'params': {'color': [0, 180, 180]}}, 'shape': [[0.0, 0.1], [0.0, 0.7], [0.3, 0.5], [0.0, 0.1]]}}, '2': {'layer_type': 'StraightRoadLayer', 'layer_params': {'road': [[1.0, 0.3], [0.0, 0.3]], 'road_width': 0.4, 'lanes': [[[1.0, 0.3], [0.0, 0.3]], [[1.0, 0.48], [0.0, 0.48]], [[1.0, 0.51], [0.0, 0.51]], [[1.0, 0.69], [0.0, 0.69]]], 'lane_widths': [0.01, 0.01, 0.01, 0.01], 'tilt': 0, 'transform_coordinates': {'src': [[0.0, 0.3], [0.0, 0.7], [1.0, 0.7], [1.0, 0.3]], 'tgt': [[0.3, 0.45], [0.3, 0.55], [1.0, 1.0], [1.0, 0.0]]}, 'color_fcts': [{'type': 'random', 'params': {'mean': [80, 80, 80], 'range': 10}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}]}}}}}
Example simulator configuration.
configs/config.py
sim_config
tayebiarasteh/lane-detection
0
python
def sim_config(): '\n \n ' return {'simulator': {'height': 256, 'width': 256, 'layers': [{'id': 'Back0', 'config_id': '0', 'filters': [{'type': 'RandomColorMeanFilter', 'params': {'dr': 100, 'dg': 100, 'db': 100}}]}, {'id': 'Sky0', 'config_id': '1', 'prob': 1, 'filters': [{'type': 'ConstantColorFilter', 'params': {'dr': 100, 'dg': 100, 'db': 100}}]}, {'id': 'Road0', 'config_id': '2', 'prob': 1, 'serialize': 1, 'filters': [{'type': 'ShiftRoadFilter', 'params': {'lb': (- 0.2), 'ub': 0.2}}, {'type': 'ShiftLanesFilter', 'params': {'lb': (- 0.02), 'ub': 0.02}}, {'type': 'TiltRoadFilter', 'params': {'lb': (- 1.5), 'ub': 1.5}}, {'type': 'LaneWidthFilter', 'params': {'lb': (- 0.01), 'ub': 0.01}}]}], 'layer_configs': {'0': {'layer_type': 'BackgroundLayer', 'layer_params': {'color_fct': {'type': 'random', 'params': {'mean': [0, 120, 80], 'range': 20}}}}, '1': {'layer_type': 'SkyLayer', 'layer_params': {'color_fct': {'type': 'constant', 'params': {'color': [0, 180, 180]}}, 'shape': [[0.0, 0.1], [0.0, 0.7], [0.3, 0.5], [0.0, 0.1]]}}, '2': {'layer_type': 'StraightRoadLayer', 'layer_params': {'road': [[1.0, 0.3], [0.0, 0.3]], 'road_width': 0.4, 'lanes': [[[1.0, 0.3], [0.0, 0.3]], [[1.0, 0.48], [0.0, 0.48]], [[1.0, 0.51], [0.0, 0.51]], [[1.0, 0.69], [0.0, 0.69]]], 'lane_widths': [0.01, 0.01, 0.01, 0.01], 'tilt': 0, 'transform_coordinates': {'src': [[0.0, 0.3], [0.0, 0.7], [1.0, 0.7], [1.0, 0.3]], 'tgt': [[0.3, 0.45], [0.3, 0.55], [1.0, 1.0], [1.0, 0.0]]}, 'color_fcts': [{'type': 'random', 'params': {'mean': [80, 80, 80], 'range': 10}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}]}}}}}
def sim_config(): '\n \n ' return {'simulator': {'height': 256, 'width': 256, 'layers': [{'id': 'Back0', 'config_id': '0', 'filters': [{'type': 'RandomColorMeanFilter', 'params': {'dr': 100, 'dg': 100, 'db': 100}}]}, {'id': 'Sky0', 'config_id': '1', 'prob': 1, 'filters': [{'type': 'ConstantColorFilter', 'params': {'dr': 100, 'dg': 100, 'db': 100}}]}, {'id': 'Road0', 'config_id': '2', 'prob': 1, 'serialize': 1, 'filters': [{'type': 'ShiftRoadFilter', 'params': {'lb': (- 0.2), 'ub': 0.2}}, {'type': 'ShiftLanesFilter', 'params': {'lb': (- 0.02), 'ub': 0.02}}, {'type': 'TiltRoadFilter', 'params': {'lb': (- 1.5), 'ub': 1.5}}, {'type': 'LaneWidthFilter', 'params': {'lb': (- 0.01), 'ub': 0.01}}]}], 'layer_configs': {'0': {'layer_type': 'BackgroundLayer', 'layer_params': {'color_fct': {'type': 'random', 'params': {'mean': [0, 120, 80], 'range': 20}}}}, '1': {'layer_type': 'SkyLayer', 'layer_params': {'color_fct': {'type': 'constant', 'params': {'color': [0, 180, 180]}}, 'shape': [[0.0, 0.1], [0.0, 0.7], [0.3, 0.5], [0.0, 0.1]]}}, '2': {'layer_type': 'StraightRoadLayer', 'layer_params': {'road': [[1.0, 0.3], [0.0, 0.3]], 'road_width': 0.4, 'lanes': [[[1.0, 0.3], [0.0, 0.3]], [[1.0, 0.48], [0.0, 0.48]], [[1.0, 0.51], [0.0, 0.51]], [[1.0, 0.69], [0.0, 0.69]]], 'lane_widths': [0.01, 0.01, 0.01, 0.01], 'tilt': 0, 'transform_coordinates': {'src': [[0.0, 0.3], [0.0, 0.7], [1.0, 0.7], [1.0, 0.3]], 'tgt': [[0.3, 0.45], [0.3, 0.55], [1.0, 1.0], [1.0, 0.0]]}, 'color_fcts': [{'type': 'random', 'params': {'mean': [80, 80, 80], 'range': 10}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}, {'type': 'constant_random_mean', 'params': {'mean': [229, 226, 52], 'lb': (- 100), 'ub': 100}}]}}}}}<|docstring|>Example simulator configuration.<|endoftext|>
75dc3f889dd563a07b78dde44c36d054c6a894c731b03abefebd73a66916041e
@local.command() @click.argument('benchmark', type=str) @click.argument('benchmark-input-size', type=click.Choice(['test', 'small', 'large'])) @click.argument('output', type=str) @click.option('--deployments', default=1, type=int, help='Number of deployed containers.') @click.option('--remove-containers/--no-remove-containers', default=True, help='Remove containers after stopping.') @simplified_common_params def start(benchmark, benchmark_input_size, output, deployments, remove_containers, **kwargs): '\n Start a given number of function instances and a storage instance.\n ' (config, output_dir, logging_filename, sebs_client, deployment_client) = parse_common_params(ignore_cache=True, update_code=False, update_storage=False, deployment='local', **kwargs) deployment_client = cast(sebs.local.Local, deployment_client) deployment_client.remove_containers = remove_containers result = sebs.local.Deployment() experiment_config = sebs_client.get_experiment_config(config['experiments']) benchmark_obj = sebs_client.get_benchmark(benchmark, deployment_client, experiment_config, logging_filename=logging_filename) storage = deployment_client.get_storage(replace_existing=experiment_config.update_storage) result.set_storage(storage) input_config = benchmark_obj.prepare_input(storage=storage, size=benchmark_input_size) result.add_input(input_config) for i in range(deployments): func = deployment_client.get_function(benchmark_obj, deployment_client.default_function_name(benchmark_obj)) result.add_function(func) deployment_client.shutdown_storage = False result.serialize(output) sebs_client.logging.info(f'Save results to {os.path.abspath(output)}')
Start a given number of function instances and a storage instance.
sebs.py
start
mcopik/serverless-benchmarks
0
python
@local.command() @click.argument('benchmark', type=str) @click.argument('benchmark-input-size', type=click.Choice(['test', 'small', 'large'])) @click.argument('output', type=str) @click.option('--deployments', default=1, type=int, help='Number of deployed containers.') @click.option('--remove-containers/--no-remove-containers', default=True, help='Remove containers after stopping.') @simplified_common_params def start(benchmark, benchmark_input_size, output, deployments, remove_containers, **kwargs): '\n \n ' (config, output_dir, logging_filename, sebs_client, deployment_client) = parse_common_params(ignore_cache=True, update_code=False, update_storage=False, deployment='local', **kwargs) deployment_client = cast(sebs.local.Local, deployment_client) deployment_client.remove_containers = remove_containers result = sebs.local.Deployment() experiment_config = sebs_client.get_experiment_config(config['experiments']) benchmark_obj = sebs_client.get_benchmark(benchmark, deployment_client, experiment_config, logging_filename=logging_filename) storage = deployment_client.get_storage(replace_existing=experiment_config.update_storage) result.set_storage(storage) input_config = benchmark_obj.prepare_input(storage=storage, size=benchmark_input_size) result.add_input(input_config) for i in range(deployments): func = deployment_client.get_function(benchmark_obj, deployment_client.default_function_name(benchmark_obj)) result.add_function(func) deployment_client.shutdown_storage = False result.serialize(output) sebs_client.logging.info(f'Save results to {os.path.abspath(output)}')
@local.command() @click.argument('benchmark', type=str) @click.argument('benchmark-input-size', type=click.Choice(['test', 'small', 'large'])) @click.argument('output', type=str) @click.option('--deployments', default=1, type=int, help='Number of deployed containers.') @click.option('--remove-containers/--no-remove-containers', default=True, help='Remove containers after stopping.') @simplified_common_params def start(benchmark, benchmark_input_size, output, deployments, remove_containers, **kwargs): '\n \n ' (config, output_dir, logging_filename, sebs_client, deployment_client) = parse_common_params(ignore_cache=True, update_code=False, update_storage=False, deployment='local', **kwargs) deployment_client = cast(sebs.local.Local, deployment_client) deployment_client.remove_containers = remove_containers result = sebs.local.Deployment() experiment_config = sebs_client.get_experiment_config(config['experiments']) benchmark_obj = sebs_client.get_benchmark(benchmark, deployment_client, experiment_config, logging_filename=logging_filename) storage = deployment_client.get_storage(replace_existing=experiment_config.update_storage) result.set_storage(storage) input_config = benchmark_obj.prepare_input(storage=storage, size=benchmark_input_size) result.add_input(input_config) for i in range(deployments): func = deployment_client.get_function(benchmark_obj, deployment_client.default_function_name(benchmark_obj)) result.add_function(func) deployment_client.shutdown_storage = False result.serialize(output) sebs_client.logging.info(f'Save results to {os.path.abspath(output)}')<|docstring|>Start a given number of function instances and a storage instance.<|endoftext|>
0b0bc0729e2d804010ffbc5369ac1a8b00f98dcbaefcd58697bb9e073ada3252
@local.command() @click.argument('input-json', type=str) def stop(input_json, **kwargs): '\n Stop function and storage containers.\n ' sebs.utils.global_logging() logging.info(f'Stopping deployment from {os.path.abspath(input_json)}') deployment = sebs.local.Deployment.deserialize(input_json, None) deployment.shutdown() logging.info(f'Stopped deployment from {os.path.abspath(input_json)}')
Stop function and storage containers.
sebs.py
stop
mcopik/serverless-benchmarks
0
python
@local.command() @click.argument('input-json', type=str) def stop(input_json, **kwargs): '\n \n ' sebs.utils.global_logging() logging.info(f'Stopping deployment from {os.path.abspath(input_json)}') deployment = sebs.local.Deployment.deserialize(input_json, None) deployment.shutdown() logging.info(f'Stopped deployment from {os.path.abspath(input_json)}')
@local.command() @click.argument('input-json', type=str) def stop(input_json, **kwargs): '\n \n ' sebs.utils.global_logging() logging.info(f'Stopping deployment from {os.path.abspath(input_json)}') deployment = sebs.local.Deployment.deserialize(input_json, None) deployment.shutdown() logging.info(f'Stopped deployment from {os.path.abspath(input_json)}')<|docstring|>Stop function and storage containers.<|endoftext|>
3357542290aac390400fa649b19df9e46e23627791119e5d494a86cbf25f7899
def output(self): '\n Retun the contents of /etc/passwd\n ' return luigi.LocalTarget('/etc/passwd')
Retun the contents of /etc/passwd
example/luigi/simple_pipeline.py
output
zachradtka/Lu
2
python
def output(self): '\n \n ' return luigi.LocalTarget('/etc/passwd')
def output(self): '\n \n ' return luigi.LocalTarget('/etc/passwd')<|docstring|>Retun the contents of /etc/passwd<|endoftext|>
9278bfe3b73d5396b3fd7bcc4eb01494eed580845e443f20f8f13719195fda55
def requires(self): '\n Specity the dependency of the input file\n ' return InputFile()
Specity the dependency of the input file
example/luigi/simple_pipeline.py
requires
zachradtka/Lu
2
python
def requires(self): '\n \n ' return InputFile()
def requires(self): '\n \n ' return InputFile()<|docstring|>Specity the dependency of the input file<|endoftext|>
b9f6aeade8e5fefeaa8d7e6030001c82d32b7de95e3374e4425a852b92dfb2b0
def output(self): '\n Specify the file to write to\n ' return luigi.LocalTarget('/tmp/userNames.txt')
Specify the file to write to
example/luigi/simple_pipeline.py
output
zachradtka/Lu
2
python
def output(self): '\n \n ' return luigi.LocalTarget('/tmp/userNames.txt')
def output(self): '\n \n ' return luigi.LocalTarget('/tmp/userNames.txt')<|docstring|>Specify the file to write to<|endoftext|>
b6a07ce39664fdb55c9f0aaf6c8cb742d07636a04b29caae9f3b4753b387e35b
def run(self): '\n Run the Task\n ' ifp = self.input().open('r') ofp = self.output().open('w') for line in ifp: ofp.write('{0}\n'.format(line.strip().split(':')[0])) ofp.close()
Run the Task
example/luigi/simple_pipeline.py
run
zachradtka/Lu
2
python
def run(self): '\n \n ' ifp = self.input().open('r') ofp = self.output().open('w') for line in ifp: ofp.write('{0}\n'.format(line.strip().split(':')[0])) ofp.close()
def run(self): '\n \n ' ifp = self.input().open('r') ofp = self.output().open('w') for line in ifp: ofp.write('{0}\n'.format(line.strip().split(':')[0])) ofp.close()<|docstring|>Run the Task<|endoftext|>
7b394d5b6ec4a325ba7ca7153d13ae691a9eb00af508023fe17879abaa13c820
def xyz_array_to_pointcloud2(points_sum, stamp=None, frame_id=None): '\n Create a sensor_msgs.PointCloud2 from an array of points.\n ' msg = PointCloud2() if stamp: msg.header.stamp = stamp if frame_id: msg.header.frame_id = frame_id print('cluster points shape:', points_sum.shape) msg.height = 1 msg.width = (points_sum.shape[1] * points_sum.shape[0]) msg.fields = [PointField('x', 0, PointField.FLOAT32, 1), PointField('y', 4, PointField.FLOAT32, 1), PointField('z', 8, PointField.FLOAT32, 1)] msg.is_bigendian = False msg.point_step = 4 msg.row_step = points_sum.shape[1] msg.is_dense = int(np.isfinite(points_sum).all()) print('msg.is_dense:', msg.is_dense) msg.data = points_sum.astype(np.float32).tobytes() return msg
Create a sensor_msgs.PointCloud2 from an array of points.
scripts/simple_inference.py
xyz_array_to_pointcloud2
muzi2045/second_TANET.pytorch
6
python
def xyz_array_to_pointcloud2(points_sum, stamp=None, frame_id=None): '\n \n ' msg = PointCloud2() if stamp: msg.header.stamp = stamp if frame_id: msg.header.frame_id = frame_id print('cluster points shape:', points_sum.shape) msg.height = 1 msg.width = (points_sum.shape[1] * points_sum.shape[0]) msg.fields = [PointField('x', 0, PointField.FLOAT32, 1), PointField('y', 4, PointField.FLOAT32, 1), PointField('z', 8, PointField.FLOAT32, 1)] msg.is_bigendian = False msg.point_step = 4 msg.row_step = points_sum.shape[1] msg.is_dense = int(np.isfinite(points_sum).all()) print('msg.is_dense:', msg.is_dense) msg.data = points_sum.astype(np.float32).tobytes() return msg
def xyz_array_to_pointcloud2(points_sum, stamp=None, frame_id=None): '\n \n ' msg = PointCloud2() if stamp: msg.header.stamp = stamp if frame_id: msg.header.frame_id = frame_id print('cluster points shape:', points_sum.shape) msg.height = 1 msg.width = (points_sum.shape[1] * points_sum.shape[0]) msg.fields = [PointField('x', 0, PointField.FLOAT32, 1), PointField('y', 4, PointField.FLOAT32, 1), PointField('z', 8, PointField.FLOAT32, 1)] msg.is_bigendian = False msg.point_step = 4 msg.row_step = points_sum.shape[1] msg.is_dense = int(np.isfinite(points_sum).all()) print('msg.is_dense:', msg.is_dense) msg.data = points_sum.astype(np.float32).tobytes() return msg<|docstring|>Create a sensor_msgs.PointCloud2 from an array of points.<|endoftext|>
6bc0160ff93da65074f896c92236f49124c65ba6c15dced7c1db14dd291380fd
def __init__(self, probability_of_false_positives, expected_number_of_elements): '\n Size of Bloom Filter is estimated from:\n m = (-n*ln(p))/(ln(2))^2,\n where m is size of Bloom Filter, n is number of expected elements, p is probability of false positives.\n\n :param probability_of_false_positives: probability of false positives.\n :param expected_number_of_elements: expected number of elements to be inserted to Bloom Filter.\n ' if (expected_number_of_elements <= 0): raise ValueError('Expected number of elements should be greater than 0!') self.size = math.ceil((((- expected_number_of_elements) * math.log(probability_of_false_positives)) / pow(math.log(2), 2))) if (self.size <= 0): raise ValueError('Size of Bloom Filter should be greater than 0!') self.expected_number_of_elements = expected_number_of_elements self.number_of_hash = math.ceil(((self.size / self.expected_number_of_elements) * math.log(2))) self.bits_per_element = (self.size / self.expected_number_of_elements) self.bit_set = bitarray(self.size) self.bit_set.setall(0) self.number_of_elements = 0
Size of Bloom Filter is estimated from: m = (-n*ln(p))/(ln(2))^2, where m is size of Bloom Filter, n is number of expected elements, p is probability of false positives. :param probability_of_false_positives: probability of false positives. :param expected_number_of_elements: expected number of elements to be inserted to Bloom Filter.
bloom_filter.py
__init__
DahDev/BloomFilter-Python
0
python
def __init__(self, probability_of_false_positives, expected_number_of_elements): '\n Size of Bloom Filter is estimated from:\n m = (-n*ln(p))/(ln(2))^2,\n where m is size of Bloom Filter, n is number of expected elements, p is probability of false positives.\n\n :param probability_of_false_positives: probability of false positives.\n :param expected_number_of_elements: expected number of elements to be inserted to Bloom Filter.\n ' if (expected_number_of_elements <= 0): raise ValueError('Expected number of elements should be greater than 0!') self.size = math.ceil((((- expected_number_of_elements) * math.log(probability_of_false_positives)) / pow(math.log(2), 2))) if (self.size <= 0): raise ValueError('Size of Bloom Filter should be greater than 0!') self.expected_number_of_elements = expected_number_of_elements self.number_of_hash = math.ceil(((self.size / self.expected_number_of_elements) * math.log(2))) self.bits_per_element = (self.size / self.expected_number_of_elements) self.bit_set = bitarray(self.size) self.bit_set.setall(0) self.number_of_elements = 0
def __init__(self, probability_of_false_positives, expected_number_of_elements): '\n Size of Bloom Filter is estimated from:\n m = (-n*ln(p))/(ln(2))^2,\n where m is size of Bloom Filter, n is number of expected elements, p is probability of false positives.\n\n :param probability_of_false_positives: probability of false positives.\n :param expected_number_of_elements: expected number of elements to be inserted to Bloom Filter.\n ' if (expected_number_of_elements <= 0): raise ValueError('Expected number of elements should be greater than 0!') self.size = math.ceil((((- expected_number_of_elements) * math.log(probability_of_false_positives)) / pow(math.log(2), 2))) if (self.size <= 0): raise ValueError('Size of Bloom Filter should be greater than 0!') self.expected_number_of_elements = expected_number_of_elements self.number_of_hash = math.ceil(((self.size / self.expected_number_of_elements) * math.log(2))) self.bits_per_element = (self.size / self.expected_number_of_elements) self.bit_set = bitarray(self.size) self.bit_set.setall(0) self.number_of_elements = 0<|docstring|>Size of Bloom Filter is estimated from: m = (-n*ln(p))/(ln(2))^2, where m is size of Bloom Filter, n is number of expected elements, p is probability of false positives. :param probability_of_false_positives: probability of false positives. :param expected_number_of_elements: expected number of elements to be inserted to Bloom Filter.<|endoftext|>
051758c2a40209a902e1b9405ad15fac4094060d69c0500034f5645974602310
def add(self, element): '\n The add method enables you to insert element to Bloom Filter.\n\n :param element: an element to be inserted to Bloom Filter\n ' hashes = self.create_hashes(str(element).encode('utf-8'), self.number_of_hash) for h in hashes: self.bit_set[h] = 1 self.number_of_elements += 1
The add method enables you to insert element to Bloom Filter. :param element: an element to be inserted to Bloom Filter
bloom_filter.py
add
DahDev/BloomFilter-Python
0
python
def add(self, element): '\n The add method enables you to insert element to Bloom Filter.\n\n :param element: an element to be inserted to Bloom Filter\n ' hashes = self.create_hashes(str(element).encode('utf-8'), self.number_of_hash) for h in hashes: self.bit_set[h] = 1 self.number_of_elements += 1
def add(self, element): '\n The add method enables you to insert element to Bloom Filter.\n\n :param element: an element to be inserted to Bloom Filter\n ' hashes = self.create_hashes(str(element).encode('utf-8'), self.number_of_hash) for h in hashes: self.bit_set[h] = 1 self.number_of_elements += 1<|docstring|>The add method enables you to insert element to Bloom Filter. :param element: an element to be inserted to Bloom Filter<|endoftext|>
6679574208e98e43e58f525c1491f8ff2606163e6d8814bd0d7e62f31590c908
def add_all(self, collection): '\n The add_all method enables you to insert each element from collection to Bloom Filter.\n\n :param collection: a collection with elements to be inserted to Bloom Filter.\n ' for item in collection: self.add(item)
The add_all method enables you to insert each element from collection to Bloom Filter. :param collection: a collection with elements to be inserted to Bloom Filter.
bloom_filter.py
add_all
DahDev/BloomFilter-Python
0
python
def add_all(self, collection): '\n The add_all method enables you to insert each element from collection to Bloom Filter.\n\n :param collection: a collection with elements to be inserted to Bloom Filter.\n ' for item in collection: self.add(item)
def add_all(self, collection): '\n The add_all method enables you to insert each element from collection to Bloom Filter.\n\n :param collection: a collection with elements to be inserted to Bloom Filter.\n ' for item in collection: self.add(item)<|docstring|>The add_all method enables you to insert each element from collection to Bloom Filter. :param collection: a collection with elements to be inserted to Bloom Filter.<|endoftext|>
ca6943bdc08c7a91f2c2a99cc6a7916ae0c6c1f03301bfeee50a1c51f0329beb
def might_contains(self, element): '\n The might_contains method enables you to check if Bloom Filter may contains element.\n\n :param element: an element to be checked\n :return: True if Bloom Filter can contains element (Remember that can be false positive result).\n False if Bloom Filter cannot contains element.\n ' hashes = self.create_hashes(str(element).encode('utf-8'), self.number_of_hash) for h in hashes: if (self.bit_set[h] == 0): return False return True
The might_contains method enables you to check if Bloom Filter may contains element. :param element: an element to be checked :return: True if Bloom Filter can contains element (Remember that can be false positive result). False if Bloom Filter cannot contains element.
bloom_filter.py
might_contains
DahDev/BloomFilter-Python
0
python
def might_contains(self, element): '\n The might_contains method enables you to check if Bloom Filter may contains element.\n\n :param element: an element to be checked\n :return: True if Bloom Filter can contains element (Remember that can be false positive result).\n False if Bloom Filter cannot contains element.\n ' hashes = self.create_hashes(str(element).encode('utf-8'), self.number_of_hash) for h in hashes: if (self.bit_set[h] == 0): return False return True
def might_contains(self, element): '\n The might_contains method enables you to check if Bloom Filter may contains element.\n\n :param element: an element to be checked\n :return: True if Bloom Filter can contains element (Remember that can be false positive result).\n False if Bloom Filter cannot contains element.\n ' hashes = self.create_hashes(str(element).encode('utf-8'), self.number_of_hash) for h in hashes: if (self.bit_set[h] == 0): return False return True<|docstring|>The might_contains method enables you to check if Bloom Filter may contains element. :param element: an element to be checked :return: True if Bloom Filter can contains element (Remember that can be false positive result). False if Bloom Filter cannot contains element.<|endoftext|>