id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,500 | casacore/python-casacore | casacore/tables/table.py | table.putkeyword | def putkeyword(self, keyword, value, makesubrecord=False):
"""Put the value of a table keyword.
The value of a keyword can be a:
- scalar which can be given a normal python scalar or numpy scalar.
- an array which can be given as a numpy array. A 1-dimensional array
can also be given as a sequence (tuple or list).
- a reference to a table which can be given as a table object or as a
string containing its name prefixed by 'Table :'.
- a struct which can be given as a dict. A struct is fully nestable,
thus each field in the dict can be one of the values described here.
The only exception is that a table value can only be given by the
string.
If the keyword already exists, the type of the new value should match
the existing one (e.g. a scalar cannot be replaced by an array).
Similar to method :func:`getkeyword` a keyword name can be given
consisting of multiple parts separated by dots. This represents nested
structs, thus puts the value into a field in a struct (in a struct,
etc.).
If `makesubrecord=True` structs will be created for the keyword name
parts that do not exist.
Instead of a keyword name an index can be given which returns the value
of the i-th keyword.
"""
val = value
if isinstance(val, table):
val = _add_prefix(val.name())
if isinstance(keyword, str):
return self._putkeyword('', keyword, -1, makesubrecord, val)
else:
return self._putkeyword('', '', keyword, makesubrecord, val) | python | def putkeyword(self, keyword, value, makesubrecord=False):
val = value
if isinstance(val, table):
val = _add_prefix(val.name())
if isinstance(keyword, str):
return self._putkeyword('', keyword, -1, makesubrecord, val)
else:
return self._putkeyword('', '', keyword, makesubrecord, val) | [
"def",
"putkeyword",
"(",
"self",
",",
"keyword",
",",
"value",
",",
"makesubrecord",
"=",
"False",
")",
":",
"val",
"=",
"value",
"if",
"isinstance",
"(",
"val",
",",
"table",
")",
":",
"val",
"=",
"_add_prefix",
"(",
"val",
".",
"name",
"(",
")",
... | Put the value of a table keyword.
The value of a keyword can be a:
- scalar which can be given a normal python scalar or numpy scalar.
- an array which can be given as a numpy array. A 1-dimensional array
can also be given as a sequence (tuple or list).
- a reference to a table which can be given as a table object or as a
string containing its name prefixed by 'Table :'.
- a struct which can be given as a dict. A struct is fully nestable,
thus each field in the dict can be one of the values described here.
The only exception is that a table value can only be given by the
string.
If the keyword already exists, the type of the new value should match
the existing one (e.g. a scalar cannot be replaced by an array).
Similar to method :func:`getkeyword` a keyword name can be given
consisting of multiple parts separated by dots. This represents nested
structs, thus puts the value into a field in a struct (in a struct,
etc.).
If `makesubrecord=True` structs will be created for the keyword name
parts that do not exist.
Instead of a keyword name an index can be given which returns the value
of the i-th keyword. | [
"Put",
"the",
"value",
"of",
"a",
"table",
"keyword",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1373-L1408 |
24,501 | casacore/python-casacore | casacore/tables/table.py | table.removekeyword | def removekeyword(self, keyword):
"""Remove a table keyword.
Similar to :func:`getkeyword` the name can consist of multiple parts.
In that case a field in a struct will be removed.
Instead of a keyword name an index can be given which removes
the i-th keyword.
"""
if isinstance(keyword, str):
self._removekeyword('', keyword, -1)
else:
self._removekeyword('', '', keyword) | python | def removekeyword(self, keyword):
if isinstance(keyword, str):
self._removekeyword('', keyword, -1)
else:
self._removekeyword('', '', keyword) | [
"def",
"removekeyword",
"(",
"self",
",",
"keyword",
")",
":",
"if",
"isinstance",
"(",
"keyword",
",",
"str",
")",
":",
"self",
".",
"_removekeyword",
"(",
"''",
",",
"keyword",
",",
"-",
"1",
")",
"else",
":",
"self",
".",
"_removekeyword",
"(",
"'... | Remove a table keyword.
Similar to :func:`getkeyword` the name can consist of multiple parts.
In that case a field in a struct will be removed.
Instead of a keyword name an index can be given which removes
the i-th keyword. | [
"Remove",
"a",
"table",
"keyword",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1444-L1457 |
24,502 | casacore/python-casacore | casacore/tables/table.py | table.removecolkeyword | def removecolkeyword(self, columnname, keyword):
"""Remove a column keyword.
It is similar to :func:`removekeyword`.
"""
if isinstance(keyword, str):
self._removekeyword(columnname, keyword, -1)
else:
self._removekeyword(columnname, '', keyword) | python | def removecolkeyword(self, columnname, keyword):
if isinstance(keyword, str):
self._removekeyword(columnname, keyword, -1)
else:
self._removekeyword(columnname, '', keyword) | [
"def",
"removecolkeyword",
"(",
"self",
",",
"columnname",
",",
"keyword",
")",
":",
"if",
"isinstance",
"(",
"keyword",
",",
"str",
")",
":",
"self",
".",
"_removekeyword",
"(",
"columnname",
",",
"keyword",
",",
"-",
"1",
")",
"else",
":",
"self",
".... | Remove a column keyword.
It is similar to :func:`removekeyword`. | [
"Remove",
"a",
"column",
"keyword",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1459-L1468 |
24,503 | casacore/python-casacore | casacore/tables/table.py | table.getdesc | def getdesc(self, actual=True):
"""Get the table description.
By default it returns the actual description (thus telling the
actual array shapes and data managers used).
`actual=False` means that the original description as made by
:func:`maketabdesc` is returned.
"""
tabledesc = self._getdesc(actual, True)
# Strip out 0 length "HCcoordnames" and "HCidnames"
# as these aren't valid. (See tabledefinehypercolumn)
hcdefs = tabledesc.get('_define_hypercolumn_', {})
for c, hcdef in hcdefs.iteritems():
if "HCcoordnames" in hcdef and len(hcdef["HCcoordnames"]) == 0:
del hcdef["HCcoordnames"]
if "HCidnames" in hcdef and len(hcdef["HCidnames"]) == 0:
del hcdef["HCidnames"]
return tabledesc | python | def getdesc(self, actual=True):
tabledesc = self._getdesc(actual, True)
# Strip out 0 length "HCcoordnames" and "HCidnames"
# as these aren't valid. (See tabledefinehypercolumn)
hcdefs = tabledesc.get('_define_hypercolumn_', {})
for c, hcdef in hcdefs.iteritems():
if "HCcoordnames" in hcdef and len(hcdef["HCcoordnames"]) == 0:
del hcdef["HCcoordnames"]
if "HCidnames" in hcdef and len(hcdef["HCidnames"]) == 0:
del hcdef["HCidnames"]
return tabledesc | [
"def",
"getdesc",
"(",
"self",
",",
"actual",
"=",
"True",
")",
":",
"tabledesc",
"=",
"self",
".",
"_getdesc",
"(",
"actual",
",",
"True",
")",
"# Strip out 0 length \"HCcoordnames\" and \"HCidnames\"",
"# as these aren't valid. (See tabledefinehypercolumn)",
"hcdefs",
... | Get the table description.
By default it returns the actual description (thus telling the
actual array shapes and data managers used).
`actual=False` means that the original description as made by
:func:`maketabdesc` is returned. | [
"Get",
"the",
"table",
"description",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1470-L1491 |
24,504 | casacore/python-casacore | casacore/tables/table.py | table.getcoldesc | def getcoldesc(self, columnname, actual=True):
"""Get the description of a column.
By default it returns the actual description (thus telling the
actual array shapes and data managers used).
`actual=False` means that the original description as made by
:func:`makescacoldesc` or :func:`makearrcoldesc` is returned.
"""
return self._getcoldesc(columnname, actual, True) | python | def getcoldesc(self, columnname, actual=True):
return self._getcoldesc(columnname, actual, True) | [
"def",
"getcoldesc",
"(",
"self",
",",
"columnname",
",",
"actual",
"=",
"True",
")",
":",
"return",
"self",
".",
"_getcoldesc",
"(",
"columnname",
",",
"actual",
",",
"True",
")"
] | Get the description of a column.
By default it returns the actual description (thus telling the
actual array shapes and data managers used).
`actual=False` means that the original description as made by
:func:`makescacoldesc` or :func:`makearrcoldesc` is returned. | [
"Get",
"the",
"description",
"of",
"a",
"column",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1493-L1502 |
24,505 | casacore/python-casacore | casacore/tables/table.py | table.coldesc | def coldesc(self, columnname, actual=True):
"""Make the description of a column.
Make the description object of the given column as
:func:`makecoldesc` is doing with the description given by
:func:`getcoldesc`.
"""
import casacore.tables.tableutil as pt
return pt.makecoldesc(columnname, self.getcoldesc(columnname, actual)) | python | def coldesc(self, columnname, actual=True):
import casacore.tables.tableutil as pt
return pt.makecoldesc(columnname, self.getcoldesc(columnname, actual)) | [
"def",
"coldesc",
"(",
"self",
",",
"columnname",
",",
"actual",
"=",
"True",
")",
":",
"import",
"casacore",
".",
"tables",
".",
"tableutil",
"as",
"pt",
"return",
"pt",
".",
"makecoldesc",
"(",
"columnname",
",",
"self",
".",
"getcoldesc",
"(",
"column... | Make the description of a column.
Make the description object of the given column as
:func:`makecoldesc` is doing with the description given by
:func:`getcoldesc`. | [
"Make",
"the",
"description",
"of",
"a",
"column",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1504-L1513 |
24,506 | casacore/python-casacore | casacore/tables/table.py | table.getdminfo | def getdminfo(self, columnname=None):
"""Get data manager info.
Each column in a table is stored using a data manager. A storage
manager is a data manager storing the physically in a file.
A virtual column engine is a data manager that does not store data
but calculates it on the fly (e.g. scaling floats to short to
reduce storage needs).
By default this method returns a dict telling the data managers used.
Each field in the dict is a dict containing:
- NAME telling the (unique) name of the data manager
- TYPE telling the type of data manager (e.g. TiledShapeStMan)
- SEQNR telling the sequence number of the data manager
(is ''i'' in table.f<i> for storage managers)
- SPEC is a dict holding the data manager specification
- COLUMNS is a list giving the columns stored by this data manager
When giving a column name the data manager info of that particular
column is returned (without the COLUMNS field).
It can, for instance, be used when adding a column using
:func:`addcols` that should use the same data manager type as an
existing column. However, when doing that care should be taken to
change the NAME because each data manager name has to be unique.
"""
dminfo = self._getdminfo()
if columnname is None:
return dminfo
# Find the info for the given column
for fld in dminfo.values():
if columnname in fld["COLUMNS"]:
fldc = fld.copy()
del fldc['COLUMNS'] # remove COLUMNS field
return fldc
raise KeyError("Column " + columnname + " does not exist") | python | def getdminfo(self, columnname=None):
dminfo = self._getdminfo()
if columnname is None:
return dminfo
# Find the info for the given column
for fld in dminfo.values():
if columnname in fld["COLUMNS"]:
fldc = fld.copy()
del fldc['COLUMNS'] # remove COLUMNS field
return fldc
raise KeyError("Column " + columnname + " does not exist") | [
"def",
"getdminfo",
"(",
"self",
",",
"columnname",
"=",
"None",
")",
":",
"dminfo",
"=",
"self",
".",
"_getdminfo",
"(",
")",
"if",
"columnname",
"is",
"None",
":",
"return",
"dminfo",
"# Find the info for the given column",
"for",
"fld",
"in",
"dminfo",
".... | Get data manager info.
Each column in a table is stored using a data manager. A storage
manager is a data manager storing the physically in a file.
A virtual column engine is a data manager that does not store data
but calculates it on the fly (e.g. scaling floats to short to
reduce storage needs).
By default this method returns a dict telling the data managers used.
Each field in the dict is a dict containing:
- NAME telling the (unique) name of the data manager
- TYPE telling the type of data manager (e.g. TiledShapeStMan)
- SEQNR telling the sequence number of the data manager
(is ''i'' in table.f<i> for storage managers)
- SPEC is a dict holding the data manager specification
- COLUMNS is a list giving the columns stored by this data manager
When giving a column name the data manager info of that particular
column is returned (without the COLUMNS field).
It can, for instance, be used when adding a column using
:func:`addcols` that should use the same data manager type as an
existing column. However, when doing that care should be taken to
change the NAME because each data manager name has to be unique. | [
"Get",
"data",
"manager",
"info",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1515-L1551 |
24,507 | casacore/python-casacore | casacore/tables/table.py | table.setdmprop | def setdmprop(self, name, properties, bycolumn=True):
"""Set properties of a data manager.
Properties (e.g. cachesize) of a data manager can be changed by
defining them appropriately in the properties argument (a dict).
Current values can be obtained using function :func:`getdmprop` which
also serves as a template. The dict can contain more fields; only
the fields with the names as returned by getdmprop are handled.
The data manager can be specified in two ways: by data manager name
or by the name of a column using the data manager. The argument
`bycolumn` defines which way is used (default is by column name).
"""
return self._setdmprop(name, properties, bycolumn) | python | def setdmprop(self, name, properties, bycolumn=True):
return self._setdmprop(name, properties, bycolumn) | [
"def",
"setdmprop",
"(",
"self",
",",
"name",
",",
"properties",
",",
"bycolumn",
"=",
"True",
")",
":",
"return",
"self",
".",
"_setdmprop",
"(",
"name",
",",
"properties",
",",
"bycolumn",
")"
] | Set properties of a data manager.
Properties (e.g. cachesize) of a data manager can be changed by
defining them appropriately in the properties argument (a dict).
Current values can be obtained using function :func:`getdmprop` which
also serves as a template. The dict can contain more fields; only
the fields with the names as returned by getdmprop are handled.
The data manager can be specified in two ways: by data manager name
or by the name of a column using the data manager. The argument
`bycolumn` defines which way is used (default is by column name). | [
"Set",
"properties",
"of",
"a",
"data",
"manager",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1575-L1589 |
24,508 | casacore/python-casacore | casacore/tables/table.py | table.showstructure | def showstructure(self, dataman=True, column=True, subtable=False,
sort=False):
"""Show table structure in a formatted string.
The structure of this table and optionally its subtables is shown.
It shows the data manager info and column descriptions.
Optionally the columns are sorted in alphabetical order.
`dataman`
Show data manager info? If False, only column info is shown.
If True, data manager info and columns per data manager are shown.
`column`
Show column description per data manager? Only takes effect if
dataman=True.
`subtable`
Show the structure of all subtables (recursively).
The names of subtables are always shown.
'sort'
Sort the columns in alphabetical order?
"""
return self._showstructure(dataman, column, subtable, sort) | python | def showstructure(self, dataman=True, column=True, subtable=False,
sort=False):
return self._showstructure(dataman, column, subtable, sort) | [
"def",
"showstructure",
"(",
"self",
",",
"dataman",
"=",
"True",
",",
"column",
"=",
"True",
",",
"subtable",
"=",
"False",
",",
"sort",
"=",
"False",
")",
":",
"return",
"self",
".",
"_showstructure",
"(",
"dataman",
",",
"column",
",",
"subtable",
"... | Show table structure in a formatted string.
The structure of this table and optionally its subtables is shown.
It shows the data manager info and column descriptions.
Optionally the columns are sorted in alphabetical order.
`dataman`
Show data manager info? If False, only column info is shown.
If True, data manager info and columns per data manager are shown.
`column`
Show column description per data manager? Only takes effect if
dataman=True.
`subtable`
Show the structure of all subtables (recursively).
The names of subtables are always shown.
'sort'
Sort the columns in alphabetical order? | [
"Show",
"table",
"structure",
"in",
"a",
"formatted",
"string",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1591-L1612 |
24,509 | casacore/python-casacore | casacore/tables/table.py | table.summary | def summary(self, recurse=False):
"""Print a summary of the table.
It prints the number of columns and rows, column names, and table and
column keywords.
If `recurse=True` it also prints the summary of all subtables, i.e.
tables referenced by table keywords.
"""
six.print_('Table summary:', self.name())
six.print_('Shape:', self.ncols(), 'columns by', self.nrows(), 'rows')
six.print_('Info:', self.info())
tkeys = self.getkeywords()
if (len(tkeys) > 0):
six.print_('Table keywords:', tkeys)
columns = self.colnames()
if (len(columns) > 0):
six.print_('Columns:', columns)
for column in columns:
ckeys = self.getcolkeywords(column)
if (len(ckeys) > 0):
six.print_(column, 'keywords:', ckeys)
if (recurse):
for key, value in tkeys.items():
tabname = _remove_prefix(value)
six.print_('Summarizing subtable:', tabname)
lt = table(tabname)
if (not lt.summary(recurse)):
break
return True | python | def summary(self, recurse=False):
six.print_('Table summary:', self.name())
six.print_('Shape:', self.ncols(), 'columns by', self.nrows(), 'rows')
six.print_('Info:', self.info())
tkeys = self.getkeywords()
if (len(tkeys) > 0):
six.print_('Table keywords:', tkeys)
columns = self.colnames()
if (len(columns) > 0):
six.print_('Columns:', columns)
for column in columns:
ckeys = self.getcolkeywords(column)
if (len(ckeys) > 0):
six.print_(column, 'keywords:', ckeys)
if (recurse):
for key, value in tkeys.items():
tabname = _remove_prefix(value)
six.print_('Summarizing subtable:', tabname)
lt = table(tabname)
if (not lt.summary(recurse)):
break
return True | [
"def",
"summary",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"six",
".",
"print_",
"(",
"'Table summary:'",
",",
"self",
".",
"name",
"(",
")",
")",
"six",
".",
"print_",
"(",
"'Shape:'",
",",
"self",
".",
"ncols",
"(",
")",
",",
"'column... | Print a summary of the table.
It prints the number of columns and rows, column names, and table and
column keywords.
If `recurse=True` it also prints the summary of all subtables, i.e.
tables referenced by table keywords. | [
"Print",
"a",
"summary",
"of",
"the",
"table",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1614-L1643 |
24,510 | casacore/python-casacore | casacore/tables/table.py | table.selectrows | def selectrows(self, rownrs):
"""Return a reference table containing the given rows."""
t = self._selectrows(rownrs, name='')
# selectrows returns a Table object, so turn that into table.
return table(t, _oper=3) | python | def selectrows(self, rownrs):
t = self._selectrows(rownrs, name='')
# selectrows returns a Table object, so turn that into table.
return table(t, _oper=3) | [
"def",
"selectrows",
"(",
"self",
",",
"rownrs",
")",
":",
"t",
"=",
"self",
".",
"_selectrows",
"(",
"rownrs",
",",
"name",
"=",
"''",
")",
"# selectrows returns a Table object, so turn that into table.",
"return",
"table",
"(",
"t",
",",
"_oper",
"=",
"3",
... | Return a reference table containing the given rows. | [
"Return",
"a",
"reference",
"table",
"containing",
"the",
"given",
"rows",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1645-L1649 |
24,511 | casacore/python-casacore | casacore/tables/table.py | table.query | def query(self, query='', name='', sortlist='', columns='',
limit=0, offset=0, style='Python'):
"""Query the table and return the result as a reference table.
This method queries the table. It forms a
`TaQL <../../doc/199.html>`_
command from the given arguments and executes it using the
:func:`taql` function.
The result is returned in a so-called reference table which
references the selected columns and rows in the original table.
Usually a reference table is temporary, but it can be made
persistent by giving it a name.
Note that a reference table is handled as any table, thus can be
queried again.
All arguments are optional, but at least one of `query`, `name`,
`sortlist`, and `columns` should be used.
See the `TaQL note <../../doc/199.html>`_ for the
detailed description of the the arguments representing the various
parts of a TaQL command.
`query`
The WHERE part of a TaQL command.
`name`
The name of the reference table if it is to be made persistent.
`sortlist`
The ORDERBY part of a TaQL command. It is a single string in which
commas have to be used to separate sort keys.
`columns`
The columns to be selected (projection in data base terms). It is a
single string in which commas have to be used to separate column
names. Apart from column names, expressions can be given as well.
`limit`
If > 0, maximum number of rows to be selected.
`offset`
If > 0, ignore the first N matches.
`style`
The TaQL syntax style to be used (defaults to Python).
"""
if not query and not sortlist and not columns and \
limit <= 0 and offset <= 0:
raise ValueError('No selection done (arguments query, ' +
'sortlist, columns, limit, and offset are empty)')
command = 'select '
if columns:
command += columns
command += ' from $1'
if query:
command += ' where ' + query
if sortlist:
command += ' orderby ' + sortlist
if limit > 0:
command += ' limit %d' % limit
if offset > 0:
command += ' offset %d' % offset
if name:
command += ' giving ' + name
return tablecommand(command, style, [self]) | python | def query(self, query='', name='', sortlist='', columns='',
limit=0, offset=0, style='Python'):
if not query and not sortlist and not columns and \
limit <= 0 and offset <= 0:
raise ValueError('No selection done (arguments query, ' +
'sortlist, columns, limit, and offset are empty)')
command = 'select '
if columns:
command += columns
command += ' from $1'
if query:
command += ' where ' + query
if sortlist:
command += ' orderby ' + sortlist
if limit > 0:
command += ' limit %d' % limit
if offset > 0:
command += ' offset %d' % offset
if name:
command += ' giving ' + name
return tablecommand(command, style, [self]) | [
"def",
"query",
"(",
"self",
",",
"query",
"=",
"''",
",",
"name",
"=",
"''",
",",
"sortlist",
"=",
"''",
",",
"columns",
"=",
"''",
",",
"limit",
"=",
"0",
",",
"offset",
"=",
"0",
",",
"style",
"=",
"'Python'",
")",
":",
"if",
"not",
"query",... | Query the table and return the result as a reference table.
This method queries the table. It forms a
`TaQL <../../doc/199.html>`_
command from the given arguments and executes it using the
:func:`taql` function.
The result is returned in a so-called reference table which
references the selected columns and rows in the original table.
Usually a reference table is temporary, but it can be made
persistent by giving it a name.
Note that a reference table is handled as any table, thus can be
queried again.
All arguments are optional, but at least one of `query`, `name`,
`sortlist`, and `columns` should be used.
See the `TaQL note <../../doc/199.html>`_ for the
detailed description of the the arguments representing the various
parts of a TaQL command.
`query`
The WHERE part of a TaQL command.
`name`
The name of the reference table if it is to be made persistent.
`sortlist`
The ORDERBY part of a TaQL command. It is a single string in which
commas have to be used to separate sort keys.
`columns`
The columns to be selected (projection in data base terms). It is a
single string in which commas have to be used to separate column
names. Apart from column names, expressions can be given as well.
`limit`
If > 0, maximum number of rows to be selected.
`offset`
If > 0, ignore the first N matches.
`style`
The TaQL syntax style to be used (defaults to Python). | [
"Query",
"the",
"table",
"and",
"return",
"the",
"result",
"as",
"a",
"reference",
"table",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1651-L1709 |
24,512 | casacore/python-casacore | casacore/tables/table.py | table.sort | def sort(self, sortlist, name='',
limit=0, offset=0, style='Python'):
"""Sort the table and return the result as a reference table.
This method sorts the table. It forms a
`TaQL <../../doc/199.html>`_
command from the given arguments and executes it using the
:func:`taql` function.
The result is returned in a so-called reference table which references
the columns and rows in the original table. Usually a reference
table is temporary, but it can be made persistent by giving it a name.
Note that a reference table is handled as any table, thus can be
queried again.
`sortlist`
The ORDERBY part of a TaQL command. It is a single string in which
commas have to be used to separate sort keys. A sort key can be the
name of a column, but it can be an expression as well.
`name`
The name of the reference table if it is to be made persistent.
`limit`
If > 0, maximum number of rows to be selected after the sort step.
It can, for instance, be used to select the N highest values.
`offset`
If > 0, ignore the first `offset` matches after the sort step.
`style`
The TaQL syntax style to be used (defaults to Python).
"""
command = 'select from $1 orderby ' + sortlist
if limit > 0:
command += ' limit %d' % limit
if offset > 0:
command += ' offset %d' % offset
if name:
command += ' giving ' + name
return tablecommand(command, style, [self]) | python | def sort(self, sortlist, name='',
limit=0, offset=0, style='Python'):
command = 'select from $1 orderby ' + sortlist
if limit > 0:
command += ' limit %d' % limit
if offset > 0:
command += ' offset %d' % offset
if name:
command += ' giving ' + name
return tablecommand(command, style, [self]) | [
"def",
"sort",
"(",
"self",
",",
"sortlist",
",",
"name",
"=",
"''",
",",
"limit",
"=",
"0",
",",
"offset",
"=",
"0",
",",
"style",
"=",
"'Python'",
")",
":",
"command",
"=",
"'select from $1 orderby '",
"+",
"sortlist",
"if",
"limit",
">",
"0",
":",... | Sort the table and return the result as a reference table.
This method sorts the table. It forms a
`TaQL <../../doc/199.html>`_
command from the given arguments and executes it using the
:func:`taql` function.
The result is returned in a so-called reference table which references
the columns and rows in the original table. Usually a reference
table is temporary, but it can be made persistent by giving it a name.
Note that a reference table is handled as any table, thus can be
queried again.
`sortlist`
The ORDERBY part of a TaQL command. It is a single string in which
commas have to be used to separate sort keys. A sort key can be the
name of a column, but it can be an expression as well.
`name`
The name of the reference table if it is to be made persistent.
`limit`
If > 0, maximum number of rows to be selected after the sort step.
It can, for instance, be used to select the N highest values.
`offset`
If > 0, ignore the first `offset` matches after the sort step.
`style`
The TaQL syntax style to be used (defaults to Python). | [
"Sort",
"the",
"table",
"and",
"return",
"the",
"result",
"as",
"a",
"reference",
"table",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1711-L1747 |
24,513 | casacore/python-casacore | casacore/tables/table.py | table.select | def select(self, columns, name='', style='Python'):
"""Select columns and return the result as a reference table.
This method represents the SELECT part of a TaQL command using the
given columns (or column expressions). It forms a
`TaQL <../../doc/199.html>`_
command from the given arguments and executes it using the
:func:`taql` function.
The result is returned in a so-called reference table which references
the columns and rows in the original table. Usually a reference
table is temporary, but it can be made persistent by giving it a name.
Note that a reference table is handled as any table, thus can be
queried again.
`columns`
The columns to be selected (projection in data base terms). It is a
single string in which commas have to be used to separate column
names. Apart from column names, expressions can be given as well.
`name`
The name of the reference table if it is to be made persistent.
`style`
The TaQL syntax style to be used (defaults to Python).
"""
command = 'select ' + columns + ' from $1'
if name:
command += ' giving ' + name
return tablecommand(command, style, [self]) | python | def select(self, columns, name='', style='Python'):
command = 'select ' + columns + ' from $1'
if name:
command += ' giving ' + name
return tablecommand(command, style, [self]) | [
"def",
"select",
"(",
"self",
",",
"columns",
",",
"name",
"=",
"''",
",",
"style",
"=",
"'Python'",
")",
":",
"command",
"=",
"'select '",
"+",
"columns",
"+",
"' from $1'",
"if",
"name",
":",
"command",
"+=",
"' giving '",
"+",
"name",
"return",
"tab... | Select columns and return the result as a reference table.
This method represents the SELECT part of a TaQL command using the
given columns (or column expressions). It forms a
`TaQL <../../doc/199.html>`_
command from the given arguments and executes it using the
:func:`taql` function.
The result is returned in a so-called reference table which references
the columns and rows in the original table. Usually a reference
table is temporary, but it can be made persistent by giving it a name.
Note that a reference table is handled as any table, thus can be
queried again.
`columns`
The columns to be selected (projection in data base terms). It is a
single string in which commas have to be used to separate column
names. Apart from column names, expressions can be given as well.
`name`
The name of the reference table if it is to be made persistent.
`style`
The TaQL syntax style to be used (defaults to Python). | [
"Select",
"columns",
"and",
"return",
"the",
"result",
"as",
"a",
"reference",
"table",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1749-L1776 |
24,514 | casacore/python-casacore | casacore/tables/table.py | table.browse | def browse(self, wait=True, tempname="/tmp/seltable"):
""" Browse a table using casabrowser or a simple wxwidget
based browser.
By default the casabrowser is used if it can be found (in your PATH).
Otherwise the wxwidget one is used if wx can be loaded.
The casabrowser can only browse tables that are persistent on disk.
This gives problems for tables resulting from a query because they are
held in memory only (unless an output table name was given).
To make browsing of such tables possible, the argument `tempname` can
be used to specify a table name that will be used to form a persistent
table that can be browsed. Note that such a table is very small as it
does not contain data, but only references to rows in the original
table.
The default for `tempname` is '/tmp/seltable'.
If needed, the table can be deleted using the :func:`tabledelete`
function.
If `wait=False`, the casabrowser is started in the background.
In that case the user should delete a possibly created copy of a
temporary table.
"""
import os
# Test if casabrowser can be found.
# On OS-X 'which' always returns 0, so use test on top of it.
# Nothing is written on stdout if not found.
if os.system('test `which casabrowser`x != x') == 0:
waitstr1 = ""
waitstr2 = "foreground ..."
if not wait:
waitstr1 = " &"
waitstr2 = "background ..."
if self.iswritable():
six.print_("Flushing data and starting casabrowser in the " +
waitstr2)
else:
six.print_("Starting casabrowser in the " + waitstr2)
self.flush()
self.unlock()
if os.system('test -e ' + self.name() + '/table.dat') == 0:
os.system('casabrowser ' + self.name() + waitstr1)
elif len(tempname) > 0:
six.print_(" making a persistent copy in table " + tempname)
self.copy(tempname)
os.system('casabrowser ' + tempname + waitstr1)
if wait:
from casacore.tables import tabledelete
six.print_(" finished browsing")
tabledelete(tempname)
else:
six.print_(" after browsing use tabledelete('" + tempname +
"') to delete the copy")
else:
six.print_("Cannot browse because the table is in memory only")
six.print_("You can browse a (shallow) persistent copy " +
"of the table like: ")
six.print_(" t.browse(True, '/tmp/tab1')")
else:
try:
import wxPython
except ImportError:
six.print_('casabrowser nor wxPython can be found')
return
from wxPython.wx import wxPySimpleApp
import sys
app = wxPySimpleApp()
from wxtablebrowser import CasaTestFrame
frame = CasaTestFrame(None, sys.stdout, self)
frame.Show(True)
app.MainLoop() | python | def browse(self, wait=True, tempname="/tmp/seltable"):
import os
# Test if casabrowser can be found.
# On OS-X 'which' always returns 0, so use test on top of it.
# Nothing is written on stdout if not found.
if os.system('test `which casabrowser`x != x') == 0:
waitstr1 = ""
waitstr2 = "foreground ..."
if not wait:
waitstr1 = " &"
waitstr2 = "background ..."
if self.iswritable():
six.print_("Flushing data and starting casabrowser in the " +
waitstr2)
else:
six.print_("Starting casabrowser in the " + waitstr2)
self.flush()
self.unlock()
if os.system('test -e ' + self.name() + '/table.dat') == 0:
os.system('casabrowser ' + self.name() + waitstr1)
elif len(tempname) > 0:
six.print_(" making a persistent copy in table " + tempname)
self.copy(tempname)
os.system('casabrowser ' + tempname + waitstr1)
if wait:
from casacore.tables import tabledelete
six.print_(" finished browsing")
tabledelete(tempname)
else:
six.print_(" after browsing use tabledelete('" + tempname +
"') to delete the copy")
else:
six.print_("Cannot browse because the table is in memory only")
six.print_("You can browse a (shallow) persistent copy " +
"of the table like: ")
six.print_(" t.browse(True, '/tmp/tab1')")
else:
try:
import wxPython
except ImportError:
six.print_('casabrowser nor wxPython can be found')
return
from wxPython.wx import wxPySimpleApp
import sys
app = wxPySimpleApp()
from wxtablebrowser import CasaTestFrame
frame = CasaTestFrame(None, sys.stdout, self)
frame.Show(True)
app.MainLoop() | [
"def",
"browse",
"(",
"self",
",",
"wait",
"=",
"True",
",",
"tempname",
"=",
"\"/tmp/seltable\"",
")",
":",
"import",
"os",
"# Test if casabrowser can be found.",
"# On OS-X 'which' always returns 0, so use test on top of it.",
"# Nothing is written on stdout if not found.",
"... | Browse a table using casabrowser or a simple wxwidget
based browser.
By default the casabrowser is used if it can be found (in your PATH).
Otherwise the wxwidget one is used if wx can be loaded.
The casabrowser can only browse tables that are persistent on disk.
This gives problems for tables resulting from a query because they are
held in memory only (unless an output table name was given).
To make browsing of such tables possible, the argument `tempname` can
be used to specify a table name that will be used to form a persistent
table that can be browsed. Note that such a table is very small as it
does not contain data, but only references to rows in the original
table.
The default for `tempname` is '/tmp/seltable'.
If needed, the table can be deleted using the :func:`tabledelete`
function.
If `wait=False`, the casabrowser is started in the background.
In that case the user should delete a possibly created copy of a
temporary table. | [
"Browse",
"a",
"table",
"using",
"casabrowser",
"or",
"a",
"simple",
"wxwidget",
"based",
"browser",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1797-L1871 |
24,515 | casacore/python-casacore | casacore/tables/table.py | table.view | def view(self, wait=True, tempname="/tmp/seltable"):
""" View a table using casaviewer, casabrowser, or wxwidget
based browser.
The table is viewed depending on the type:
MeasurementSet
is viewed using casaviewer.
Image
is viewed using casaviewer.
other
are browsed using the :func:`browse` function.
If the casaviewer cannot be found, all tables are browsed.
The casaviewer can only display tables that are persistent on disk.
This gives problems for tables resulting from a query because they are
held in memory only (unless an output table name was given).
To make viewing of such tables possible, the argument `tempname` can
be used to specify a table name that will be used to form a persistent
table that can be browsed. Note that such a table is very small as it
does not contain data, but only references to rows in the original
table. The default for `tempname` is '/tmp/seltable'.
If needed, the table can be deleted using the :func:`tabledelete`
function.
If `wait=False`, the casaviewer is started in the background.
In that case the user should delete a possibly created copy of a
temporary table.
"""
import os
# Determine the table type.
# Test if casaviewer can be found.
# On OS-X 'which' always returns 0, so use test on top of it.
viewed = False
type = self.info()["type"]
if type == "Measurement Set" or type == "Image":
if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0:
waitstr1 = ""
waitstr2 = "foreground ..."
if not wait:
waitstr1 = " &"
waitstr2 = "background ..."
if self.iswritable():
six.print_("Flushing data and starting casaviewer " +
"in the " + waitstr2)
else:
six.print_("Starting casaviewer in the " + waitstr2)
self.flush()
self.unlock()
if os.system('test -e ' + self.name() + '/table.dat') == 0:
os.system('casaviewer ' + self.name() + waitstr1)
viewed = True
elif len(tempname) > 0:
six.print_(" making a persistent copy in table " +
tempname)
self.copy(tempname)
os.system('casaviewer ' + tempname + waitstr1)
viewed = True
if wait:
from casacore.tables import tabledelete
six.print_(" finished viewing")
tabledelete(tempname)
else:
six.print_(" after viewing use tabledelete('" +
tempname + "') to delete the copy")
else:
six.print_("Cannot browse because the table is " +
"in memory only.")
six.print_("You can browse a (shallow) persistent " +
"copy of the table like:")
six.print_(" t.view(True, '/tmp/tab1')")
# Could not view the table, so browse it.
if not viewed:
self.browse(wait, tempname) | python | def view(self, wait=True, tempname="/tmp/seltable"):
import os
# Determine the table type.
# Test if casaviewer can be found.
# On OS-X 'which' always returns 0, so use test on top of it.
viewed = False
type = self.info()["type"]
if type == "Measurement Set" or type == "Image":
if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0:
waitstr1 = ""
waitstr2 = "foreground ..."
if not wait:
waitstr1 = " &"
waitstr2 = "background ..."
if self.iswritable():
six.print_("Flushing data and starting casaviewer " +
"in the " + waitstr2)
else:
six.print_("Starting casaviewer in the " + waitstr2)
self.flush()
self.unlock()
if os.system('test -e ' + self.name() + '/table.dat') == 0:
os.system('casaviewer ' + self.name() + waitstr1)
viewed = True
elif len(tempname) > 0:
six.print_(" making a persistent copy in table " +
tempname)
self.copy(tempname)
os.system('casaviewer ' + tempname + waitstr1)
viewed = True
if wait:
from casacore.tables import tabledelete
six.print_(" finished viewing")
tabledelete(tempname)
else:
six.print_(" after viewing use tabledelete('" +
tempname + "') to delete the copy")
else:
six.print_("Cannot browse because the table is " +
"in memory only.")
six.print_("You can browse a (shallow) persistent " +
"copy of the table like:")
six.print_(" t.view(True, '/tmp/tab1')")
# Could not view the table, so browse it.
if not viewed:
self.browse(wait, tempname) | [
"def",
"view",
"(",
"self",
",",
"wait",
"=",
"True",
",",
"tempname",
"=",
"\"/tmp/seltable\"",
")",
":",
"import",
"os",
"# Determine the table type.",
"# Test if casaviewer can be found.",
"# On OS-X 'which' always returns 0, so use test on top of it.",
"viewed",
"=",
"F... | View a table using casaviewer, casabrowser, or wxwidget
based browser.
The table is viewed depending on the type:
MeasurementSet
is viewed using casaviewer.
Image
is viewed using casaviewer.
other
are browsed using the :func:`browse` function.
If the casaviewer cannot be found, all tables are browsed.
The casaviewer can only display tables that are persistent on disk.
This gives problems for tables resulting from a query because they are
held in memory only (unless an output table name was given).
To make viewing of such tables possible, the argument `tempname` can
be used to specify a table name that will be used to form a persistent
table that can be browsed. Note that such a table is very small as it
does not contain data, but only references to rows in the original
table. The default for `tempname` is '/tmp/seltable'.
If needed, the table can be deleted using the :func:`tabledelete`
function.
If `wait=False`, the casaviewer is started in the background.
In that case the user should delete a possibly created copy of a
temporary table. | [
"View",
"a",
"table",
"using",
"casaviewer",
"casabrowser",
"or",
"wxwidget",
"based",
"browser",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1873-L1950 |
24,516 | casacore/python-casacore | casacore/tables/table.py | table._repr_html_ | def _repr_html_(self):
"""Give a nice representation of tables in notebooks."""
out = "<table class='taqltable' style='overflow-x:auto'>\n"
# Print column names (not if they are all auto-generated)
if not(all([colname[:4] == "Col_" for colname in self.colnames()])):
out += "<tr>"
for colname in self.colnames():
out += "<th><b>"+colname+"</b></th>"
out += "</tr>"
cropped = False
rowcount = 0
for row in self:
rowout = _format_row(row, self.colnames(), self)
rowcount += 1
out += rowout
if "\n" in rowout: # Double space after multiline rows
out += "\n"
out += "\n"
if rowcount >= 20:
cropped = True
break
if out[-2:] == "\n\n":
out = out[:-1]
out += "</table>"
if cropped:
out += ("<p style='text-align:center'>(" +
str(self.nrows()-20)+" more rows)</p>\n")
return out | python | def _repr_html_(self):
out = "<table class='taqltable' style='overflow-x:auto'>\n"
# Print column names (not if they are all auto-generated)
if not(all([colname[:4] == "Col_" for colname in self.colnames()])):
out += "<tr>"
for colname in self.colnames():
out += "<th><b>"+colname+"</b></th>"
out += "</tr>"
cropped = False
rowcount = 0
for row in self:
rowout = _format_row(row, self.colnames(), self)
rowcount += 1
out += rowout
if "\n" in rowout: # Double space after multiline rows
out += "\n"
out += "\n"
if rowcount >= 20:
cropped = True
break
if out[-2:] == "\n\n":
out = out[:-1]
out += "</table>"
if cropped:
out += ("<p style='text-align:center'>(" +
str(self.nrows()-20)+" more rows)</p>\n")
return out | [
"def",
"_repr_html_",
"(",
"self",
")",
":",
"out",
"=",
"\"<table class='taqltable' style='overflow-x:auto'>\\n\"",
"# Print column names (not if they are all auto-generated)",
"if",
"not",
"(",
"all",
"(",
"[",
"colname",
"[",
":",
"4",
"]",
"==",
"\"Col_\"",
"for",
... | Give a nice representation of tables in notebooks. | [
"Give",
"a",
"nice",
"representation",
"of",
"tables",
"in",
"notebooks",
"."
] | 975510861ea005f7919dd9e438b5f98a1682eebe | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1952-L1985 |
24,517 | Kronuz/pyScss | scss/extension/core.py | nth | def nth(lst, n):
"""Return the nth item in the list."""
expect_type(n, (String, Number), unit=None)
if isinstance(n, String):
if n.value.lower() == 'first':
i = 0
elif n.value.lower() == 'last':
i = -1
else:
raise ValueError("Invalid index %r" % (n,))
else:
# DEVIATION: nth treats lists as circular lists
i = n.to_python_index(len(lst), circular=True)
return lst[i] | python | def nth(lst, n):
expect_type(n, (String, Number), unit=None)
if isinstance(n, String):
if n.value.lower() == 'first':
i = 0
elif n.value.lower() == 'last':
i = -1
else:
raise ValueError("Invalid index %r" % (n,))
else:
# DEVIATION: nth treats lists as circular lists
i = n.to_python_index(len(lst), circular=True)
return lst[i] | [
"def",
"nth",
"(",
"lst",
",",
"n",
")",
":",
"expect_type",
"(",
"n",
",",
"(",
"String",
",",
"Number",
")",
",",
"unit",
"=",
"None",
")",
"if",
"isinstance",
"(",
"n",
",",
"String",
")",
":",
"if",
"n",
".",
"value",
".",
"lower",
"(",
"... | Return the nth item in the list. | [
"Return",
"the",
"nth",
"item",
"in",
"the",
"list",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/core.py#L657-L672 |
24,518 | Kronuz/pyScss | scss/extension/core.py | CoreExtension.handle_import | def handle_import(self, name, compilation, rule):
"""Implementation of the core Sass import mechanism, which just looks
for files on disk.
"""
# TODO this is all not terribly well-specified by Sass. at worst,
# it's unclear how far "upwards" we should be allowed to go. but i'm
# also a little fuzzy on e.g. how relative imports work from within a
# file that's not actually in the search path.
# TODO i think with the new origin semantics, i've made it possible to
# import relative to the current file even if the current file isn't
# anywhere in the search path. is that right?
path = PurePosixPath(name)
search_exts = list(compilation.compiler.dynamic_extensions)
if path.suffix and path.suffix in search_exts:
basename = path.stem
else:
basename = path.name
relative_to = path.parent
search_path = [] # tuple of (origin, start_from)
if relative_to.is_absolute():
relative_to = PurePosixPath(*relative_to.parts[1:])
elif rule.source_file.origin:
# Search relative to the current file first, only if not doing an
# absolute import
search_path.append((
rule.source_file.origin,
rule.source_file.relpath.parent / relative_to,
))
search_path.extend(
(origin, relative_to)
for origin in compilation.compiler.search_path
)
for prefix, suffix in product(('_', ''), search_exts):
filename = prefix + basename + suffix
for origin, relative_to in search_path:
relpath = relative_to / filename
# Lexically (ignoring symlinks!) eliminate .. from the part
# of the path that exists within Sass-space. pathlib
# deliberately doesn't do this, but os.path does.
relpath = PurePosixPath(os.path.normpath(str(relpath)))
if rule.source_file.key == (origin, relpath):
# Avoid self-import
# TODO is this what ruby does?
continue
path = origin / relpath
if not path.exists():
continue
# All good!
# TODO if this file has already been imported, we'll do the
# source preparation twice. make it lazy.
return SourceFile.read(origin, relpath) | python | def handle_import(self, name, compilation, rule):
# TODO this is all not terribly well-specified by Sass. at worst,
# it's unclear how far "upwards" we should be allowed to go. but i'm
# also a little fuzzy on e.g. how relative imports work from within a
# file that's not actually in the search path.
# TODO i think with the new origin semantics, i've made it possible to
# import relative to the current file even if the current file isn't
# anywhere in the search path. is that right?
path = PurePosixPath(name)
search_exts = list(compilation.compiler.dynamic_extensions)
if path.suffix and path.suffix in search_exts:
basename = path.stem
else:
basename = path.name
relative_to = path.parent
search_path = [] # tuple of (origin, start_from)
if relative_to.is_absolute():
relative_to = PurePosixPath(*relative_to.parts[1:])
elif rule.source_file.origin:
# Search relative to the current file first, only if not doing an
# absolute import
search_path.append((
rule.source_file.origin,
rule.source_file.relpath.parent / relative_to,
))
search_path.extend(
(origin, relative_to)
for origin in compilation.compiler.search_path
)
for prefix, suffix in product(('_', ''), search_exts):
filename = prefix + basename + suffix
for origin, relative_to in search_path:
relpath = relative_to / filename
# Lexically (ignoring symlinks!) eliminate .. from the part
# of the path that exists within Sass-space. pathlib
# deliberately doesn't do this, but os.path does.
relpath = PurePosixPath(os.path.normpath(str(relpath)))
if rule.source_file.key == (origin, relpath):
# Avoid self-import
# TODO is this what ruby does?
continue
path = origin / relpath
if not path.exists():
continue
# All good!
# TODO if this file has already been imported, we'll do the
# source preparation twice. make it lazy.
return SourceFile.read(origin, relpath) | [
"def",
"handle_import",
"(",
"self",
",",
"name",
",",
"compilation",
",",
"rule",
")",
":",
"# TODO this is all not terribly well-specified by Sass. at worst,",
"# it's unclear how far \"upwards\" we should be allowed to go. but i'm",
"# also a little fuzzy on e.g. how relative import... | Implementation of the core Sass import mechanism, which just looks
for files on disk. | [
"Implementation",
"of",
"the",
"core",
"Sass",
"import",
"mechanism",
"which",
"just",
"looks",
"for",
"files",
"on",
"disk",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/core.py#L25-L80 |
24,519 | Kronuz/pyScss | yapps2.py | print_error | def print_error(input, err, scanner):
"""This is a really dumb long function to print error messages nicely."""
p = err.pos
# Figure out the line number
line = input[:p].count('\n')
print err.msg + " on line " + repr(line + 1) + ":"
# Now try printing part of the line
text = input[max(p - 80, 0):
p + 80]
p = p - max(p - 80, 0)
# Strip to the left
i = text[:p].rfind('\n')
j = text[:p].rfind('\r')
if i < 0 or (0 <= j < i):
i = j
if 0 <= i < p:
p = p - i - 1
text = text[i + 1:]
# Strip to the right
i = text.find('\n', p)
j = text.find('\r', p)
if i < 0 or (0 <= j < i):
i = j
if i >= 0:
text = text[:i]
# Now shorten the text
while len(text) > 70 and p > 60:
# Cut off 10 chars
text = "..." + text[10:]
p = p - 7
# Now print the string, along with an indicator
print '> ', text
print '> ', ' ' * p + '^'
print 'List of nearby tokens:', scanner | python | def print_error(input, err, scanner):
p = err.pos
# Figure out the line number
line = input[:p].count('\n')
print err.msg + " on line " + repr(line + 1) + ":"
# Now try printing part of the line
text = input[max(p - 80, 0):
p + 80]
p = p - max(p - 80, 0)
# Strip to the left
i = text[:p].rfind('\n')
j = text[:p].rfind('\r')
if i < 0 or (0 <= j < i):
i = j
if 0 <= i < p:
p = p - i - 1
text = text[i + 1:]
# Strip to the right
i = text.find('\n', p)
j = text.find('\r', p)
if i < 0 or (0 <= j < i):
i = j
if i >= 0:
text = text[:i]
# Now shorten the text
while len(text) > 70 and p > 60:
# Cut off 10 chars
text = "..." + text[10:]
p = p - 7
# Now print the string, along with an indicator
print '> ', text
print '> ', ' ' * p + '^'
print 'List of nearby tokens:', scanner | [
"def",
"print_error",
"(",
"input",
",",
"err",
",",
"scanner",
")",
":",
"p",
"=",
"err",
".",
"pos",
"# Figure out the line number",
"line",
"=",
"input",
"[",
":",
"p",
"]",
".",
"count",
"(",
"'\\n'",
")",
"print",
"err",
".",
"msg",
"+",
"\" on ... | This is a really dumb long function to print error messages nicely. | [
"This",
"is",
"a",
"really",
"dumb",
"long",
"function",
"to",
"print",
"error",
"messages",
"nicely",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L892-L929 |
24,520 | Kronuz/pyScss | yapps2.py | Generator.equal_set | def equal_set(self, a, b):
"See if a and b have the same elements"
if len(a) != len(b):
return 0
if a == b:
return 1
return self.subset(a, b) and self.subset(b, a) | python | def equal_set(self, a, b):
"See if a and b have the same elements"
if len(a) != len(b):
return 0
if a == b:
return 1
return self.subset(a, b) and self.subset(b, a) | [
"def",
"equal_set",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"return",
"0",
"if",
"a",
"==",
"b",
":",
"return",
"1",
"return",
"self",
".",
"subset",
"(",
"a",
",",
"b",
")",
... | See if a and b have the same elements | [
"See",
"if",
"a",
"and",
"b",
"have",
"the",
"same",
"elements"
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L111-L117 |
24,521 | Kronuz/pyScss | yapps2.py | Generator.add_to | def add_to(self, parent, additions):
"Modify parent to include all elements in additions"
for x in additions:
if x not in parent:
parent.append(x)
self.changed() | python | def add_to(self, parent, additions):
"Modify parent to include all elements in additions"
for x in additions:
if x not in parent:
parent.append(x)
self.changed() | [
"def",
"add_to",
"(",
"self",
",",
"parent",
",",
"additions",
")",
":",
"for",
"x",
"in",
"additions",
":",
"if",
"x",
"not",
"in",
"parent",
":",
"parent",
".",
"append",
"(",
"x",
")",
"self",
".",
"changed",
"(",
")"
] | Modify parent to include all elements in additions | [
"Modify",
"parent",
"to",
"include",
"all",
"elements",
"in",
"additions"
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L119-L124 |
24,522 | Kronuz/pyScss | scss/namespace.py | Namespace.declare_alias | def declare_alias(self, name):
"""Insert a Python function into this Namespace with an
explicitly-given name, but detect its argument count automatically.
"""
def decorator(f):
self._auto_register_function(f, name)
return f
return decorator | python | def declare_alias(self, name):
def decorator(f):
self._auto_register_function(f, name)
return f
return decorator | [
"def",
"declare_alias",
"(",
"self",
",",
"name",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"_auto_register_function",
"(",
"f",
",",
"name",
")",
"return",
"f",
"return",
"decorator"
] | Insert a Python function into this Namespace with an
explicitly-given name, but detect its argument count automatically. | [
"Insert",
"a",
"Python",
"function",
"into",
"this",
"Namespace",
"with",
"an",
"explicitly",
"-",
"given",
"name",
"but",
"detect",
"its",
"argument",
"count",
"automatically",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/namespace.py#L150-L158 |
24,523 | Kronuz/pyScss | scss/util.py | tmemoize.collect | def collect(self):
"""Clear cache of results which have timed out"""
for func in self._caches:
cache = {}
for key in self._caches[func]:
if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
cache[key] = self._caches[func][key]
self._caches[func] = cache | python | def collect(self):
for func in self._caches:
cache = {}
for key in self._caches[func]:
if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
cache[key] = self._caches[func][key]
self._caches[func] = cache | [
"def",
"collect",
"(",
"self",
")",
":",
"for",
"func",
"in",
"self",
".",
"_caches",
":",
"cache",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_caches",
"[",
"func",
"]",
":",
"if",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
... | Clear cache of results which have timed out | [
"Clear",
"cache",
"of",
"results",
"which",
"have",
"timed",
"out"
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/util.py#L206-L213 |
24,524 | Kronuz/pyScss | scss/rule.py | extend_unique | def extend_unique(seq, more):
"""Return a new sequence containing the items in `seq` plus any items in
`more` that aren't already in `seq`, preserving the order of both.
"""
seen = set(seq)
new = []
for item in more:
if item not in seen:
seen.add(item)
new.append(item)
return seq + type(seq)(new) | python | def extend_unique(seq, more):
seen = set(seq)
new = []
for item in more:
if item not in seen:
seen.add(item)
new.append(item)
return seq + type(seq)(new) | [
"def",
"extend_unique",
"(",
"seq",
",",
"more",
")",
":",
"seen",
"=",
"set",
"(",
"seq",
")",
"new",
"=",
"[",
"]",
"for",
"item",
"in",
"more",
":",
"if",
"item",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"item",
")",
"new",
".",
... | Return a new sequence containing the items in `seq` plus any items in
`more` that aren't already in `seq`, preserving the order of both. | [
"Return",
"a",
"new",
"sequence",
"containing",
"the",
"items",
"in",
"seq",
"plus",
"any",
"items",
"in",
"more",
"that",
"aren",
"t",
"already",
"in",
"seq",
"preserving",
"the",
"order",
"of",
"both",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/rule.py#L17-L28 |
24,525 | Kronuz/pyScss | scss/rule.py | RuleAncestry.with_more_selectors | def with_more_selectors(self, selectors):
"""Return a new ancestry that also matches the given selectors. No
nesting is done.
"""
if self.headers and self.headers[-1].is_selector:
new_selectors = extend_unique(
self.headers[-1].selectors,
selectors)
new_headers = self.headers[:-1] + (
BlockSelectorHeader(new_selectors),)
return RuleAncestry(new_headers)
else:
new_headers = self.headers + (BlockSelectorHeader(selectors),)
return RuleAncestry(new_headers) | python | def with_more_selectors(self, selectors):
if self.headers and self.headers[-1].is_selector:
new_selectors = extend_unique(
self.headers[-1].selectors,
selectors)
new_headers = self.headers[:-1] + (
BlockSelectorHeader(new_selectors),)
return RuleAncestry(new_headers)
else:
new_headers = self.headers + (BlockSelectorHeader(selectors),)
return RuleAncestry(new_headers) | [
"def",
"with_more_selectors",
"(",
"self",
",",
"selectors",
")",
":",
"if",
"self",
".",
"headers",
"and",
"self",
".",
"headers",
"[",
"-",
"1",
"]",
".",
"is_selector",
":",
"new_selectors",
"=",
"extend_unique",
"(",
"self",
".",
"headers",
"[",
"-",... | Return a new ancestry that also matches the given selectors. No
nesting is done. | [
"Return",
"a",
"new",
"ancestry",
"that",
"also",
"matches",
"the",
"given",
"selectors",
".",
"No",
"nesting",
"is",
"done",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/rule.py#L194-L207 |
24,526 | Kronuz/pyScss | scss/calculator.py | Calculator.parse_interpolations | def parse_interpolations(self, string):
"""Parse a string for interpolations, but don't treat anything else as
Sass syntax. Returns an AST node.
"""
# Shortcut: if there are no #s in the string in the first place, it
# must not have any interpolations, right?
if '#' not in string:
return Literal(String.unquoted(string))
return self.parse_expression(string, 'goal_interpolated_literal') | python | def parse_interpolations(self, string):
# Shortcut: if there are no #s in the string in the first place, it
# must not have any interpolations, right?
if '#' not in string:
return Literal(String.unquoted(string))
return self.parse_expression(string, 'goal_interpolated_literal') | [
"def",
"parse_interpolations",
"(",
"self",
",",
"string",
")",
":",
"# Shortcut: if there are no #s in the string in the first place, it",
"# must not have any interpolations, right?",
"if",
"'#'",
"not",
"in",
"string",
":",
"return",
"Literal",
"(",
"String",
".",
"unquo... | Parse a string for interpolations, but don't treat anything else as
Sass syntax. Returns an AST node. | [
"Parse",
"a",
"string",
"for",
"interpolations",
"but",
"don",
"t",
"treat",
"anything",
"else",
"as",
"Sass",
"syntax",
".",
"Returns",
"an",
"AST",
"node",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/calculator.py#L174-L182 |
24,527 | Kronuz/pyScss | scss/calculator.py | Calculator.parse_vars_and_interpolations | def parse_vars_and_interpolations(self, string):
"""Parse a string for variables and interpolations, but don't treat
anything else as Sass syntax. Returns an AST node.
"""
# Shortcut: if there are no #s or $s in the string in the first place,
# it must not have anything of interest.
if '#' not in string and '$' not in string:
return Literal(String.unquoted(string))
return self.parse_expression(
string, 'goal_interpolated_literal_with_vars') | python | def parse_vars_and_interpolations(self, string):
# Shortcut: if there are no #s or $s in the string in the first place,
# it must not have anything of interest.
if '#' not in string and '$' not in string:
return Literal(String.unquoted(string))
return self.parse_expression(
string, 'goal_interpolated_literal_with_vars') | [
"def",
"parse_vars_and_interpolations",
"(",
"self",
",",
"string",
")",
":",
"# Shortcut: if there are no #s or $s in the string in the first place,",
"# it must not have anything of interest.",
"if",
"'#'",
"not",
"in",
"string",
"and",
"'$'",
"not",
"in",
"string",
":",
... | Parse a string for variables and interpolations, but don't treat
anything else as Sass syntax. Returns an AST node. | [
"Parse",
"a",
"string",
"for",
"variables",
"and",
"interpolations",
"but",
"don",
"t",
"treat",
"anything",
"else",
"as",
"Sass",
"syntax",
".",
"Returns",
"an",
"AST",
"node",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/calculator.py#L184-L193 |
24,528 | Kronuz/pyScss | scss/extension/compass/helpers.py | reject | def reject(lst, *values):
"""Removes the given values from the list"""
lst = List.from_maybe(lst)
values = frozenset(List.from_maybe_starargs(values))
ret = []
for item in lst:
if item not in values:
ret.append(item)
return List(ret, use_comma=lst.use_comma) | python | def reject(lst, *values):
lst = List.from_maybe(lst)
values = frozenset(List.from_maybe_starargs(values))
ret = []
for item in lst:
if item not in values:
ret.append(item)
return List(ret, use_comma=lst.use_comma) | [
"def",
"reject",
"(",
"lst",
",",
"*",
"values",
")",
":",
"lst",
"=",
"List",
".",
"from_maybe",
"(",
"lst",
")",
"values",
"=",
"frozenset",
"(",
"List",
".",
"from_maybe_starargs",
"(",
"values",
")",
")",
"ret",
"=",
"[",
"]",
"for",
"item",
"i... | Removes the given values from the list | [
"Removes",
"the",
"given",
"values",
"from",
"the",
"list"
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/helpers.py#L87-L96 |
24,529 | Kronuz/pyScss | scss/errors.py | add_error_marker | def add_error_marker(text, position, start_line=1):
"""Add a caret marking a given position in a string of input.
Returns (new_text, caret_line).
"""
indent = " "
lines = []
caret_line = start_line
for line in text.split("\n"):
lines.append(indent + line)
if 0 <= position <= len(line):
lines.append(indent + (" " * position) + "^")
caret_line = start_line
position -= len(line)
position -= 1 # for the newline
start_line += 1
return "\n".join(lines), caret_line | python | def add_error_marker(text, position, start_line=1):
indent = " "
lines = []
caret_line = start_line
for line in text.split("\n"):
lines.append(indent + line)
if 0 <= position <= len(line):
lines.append(indent + (" " * position) + "^")
caret_line = start_line
position -= len(line)
position -= 1 # for the newline
start_line += 1
return "\n".join(lines), caret_line | [
"def",
"add_error_marker",
"(",
"text",
",",
"position",
",",
"start_line",
"=",
"1",
")",
":",
"indent",
"=",
"\" \"",
"lines",
"=",
"[",
"]",
"caret_line",
"=",
"start_line",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"li... | Add a caret marking a given position in a string of input.
Returns (new_text, caret_line). | [
"Add",
"a",
"caret",
"marking",
"a",
"given",
"position",
"in",
"a",
"string",
"of",
"input",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L34-L53 |
24,530 | Kronuz/pyScss | scss/errors.py | SassBaseError.format_sass_stack | def format_sass_stack(self):
"""Return a "traceback" of Sass imports."""
if not self.rule_stack:
return ""
ret = ["on ", self.format_file_and_line(self.rule_stack[0]), "\n"]
last_file = self.rule_stack[0].source_file
# TODO this could go away if rules knew their import chains...
# TODO this doesn't mention mixins or function calls. really need to
# track the call stack better. atm we skip other calls in the same
# file because most of them are just nesting, but they might not be!
# TODO the line number is wrong here for @imports, because we don't
# have access to the UnparsedBlock representing the import!
# TODO @content is completely broken; it's basically textual inclusion
for rule in self.rule_stack[1:]:
if rule.source_file is not last_file:
ret.extend((
"imported from ", self.format_file_and_line(rule), "\n"))
last_file = rule.source_file
return "".join(ret) | python | def format_sass_stack(self):
if not self.rule_stack:
return ""
ret = ["on ", self.format_file_and_line(self.rule_stack[0]), "\n"]
last_file = self.rule_stack[0].source_file
# TODO this could go away if rules knew their import chains...
# TODO this doesn't mention mixins or function calls. really need to
# track the call stack better. atm we skip other calls in the same
# file because most of them are just nesting, but they might not be!
# TODO the line number is wrong here for @imports, because we don't
# have access to the UnparsedBlock representing the import!
# TODO @content is completely broken; it's basically textual inclusion
for rule in self.rule_stack[1:]:
if rule.source_file is not last_file:
ret.extend((
"imported from ", self.format_file_and_line(rule), "\n"))
last_file = rule.source_file
return "".join(ret) | [
"def",
"format_sass_stack",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"rule_stack",
":",
"return",
"\"\"",
"ret",
"=",
"[",
"\"on \"",
",",
"self",
".",
"format_file_and_line",
"(",
"self",
".",
"rule_stack",
"[",
"0",
"]",
")",
",",
"\"\\n\"",
... | Return a "traceback" of Sass imports. | [
"Return",
"a",
"traceback",
"of",
"Sass",
"imports",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L80-L101 |
24,531 | Kronuz/pyScss | scss/errors.py | SassError.format_python_stack | def format_python_stack(self):
"""Return a traceback of Python frames, from where the error occurred
to where it was first caught and wrapped.
"""
ret = ["Traceback:\n"]
ret.extend(traceback.format_tb(self.original_traceback))
return "".join(ret) | python | def format_python_stack(self):
ret = ["Traceback:\n"]
ret.extend(traceback.format_tb(self.original_traceback))
return "".join(ret) | [
"def",
"format_python_stack",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"\"Traceback:\\n\"",
"]",
"ret",
".",
"extend",
"(",
"traceback",
".",
"format_tb",
"(",
"self",
".",
"original_traceback",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"ret",
")"
] | Return a traceback of Python frames, from where the error occurred
to where it was first caught and wrapped. | [
"Return",
"a",
"traceback",
"of",
"Python",
"frames",
"from",
"where",
"the",
"error",
"occurred",
"to",
"where",
"it",
"was",
"first",
"caught",
"and",
"wrapped",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L217-L223 |
24,532 | Kronuz/pyScss | scss/errors.py | SassError.to_css | def to_css(self):
"""Return a stylesheet that will show the wrapped error at the top of
the browser window.
"""
# TODO should this include the traceback? any security concerns?
prefix = self.format_prefix()
original_error = self.format_original_error()
sass_stack = self.format_sass_stack()
message = prefix + "\n" + sass_stack + original_error
# Super simple escaping: only quotes and newlines are illegal in css
# strings
message = message.replace('\\', '\\\\')
message = message.replace('"', '\\"')
# use the maximum six digits here so it doesn't eat any following
# characters that happen to look like hex
message = message.replace('\n', '\\00000A')
return BROWSER_ERROR_TEMPLATE.format('"' + message + '"') | python | def to_css(self):
# TODO should this include the traceback? any security concerns?
prefix = self.format_prefix()
original_error = self.format_original_error()
sass_stack = self.format_sass_stack()
message = prefix + "\n" + sass_stack + original_error
# Super simple escaping: only quotes and newlines are illegal in css
# strings
message = message.replace('\\', '\\\\')
message = message.replace('"', '\\"')
# use the maximum six digits here so it doesn't eat any following
# characters that happen to look like hex
message = message.replace('\n', '\\00000A')
return BROWSER_ERROR_TEMPLATE.format('"' + message + '"') | [
"def",
"to_css",
"(",
"self",
")",
":",
"# TODO should this include the traceback? any security concerns?",
"prefix",
"=",
"self",
".",
"format_prefix",
"(",
")",
"original_error",
"=",
"self",
".",
"format_original_error",
"(",
")",
"sass_stack",
"=",
"self",
".",
... | Return a stylesheet that will show the wrapped error at the top of
the browser window. | [
"Return",
"a",
"stylesheet",
"that",
"will",
"show",
"the",
"wrapped",
"error",
"at",
"the",
"top",
"of",
"the",
"browser",
"window",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L249-L268 |
24,533 | Kronuz/pyScss | scss/compiler.py | compile_string | def compile_string(string, compiler_class=Compiler, **kwargs):
"""Compile a single string, and return a string of CSS.
Keyword arguments are passed along to the underlying `Compiler`.
"""
compiler = compiler_class(**kwargs)
return compiler.compile_string(string) | python | def compile_string(string, compiler_class=Compiler, **kwargs):
compiler = compiler_class(**kwargs)
return compiler.compile_string(string) | [
"def",
"compile_string",
"(",
"string",
",",
"compiler_class",
"=",
"Compiler",
",",
"*",
"*",
"kwargs",
")",
":",
"compiler",
"=",
"compiler_class",
"(",
"*",
"*",
"kwargs",
")",
"return",
"compiler",
".",
"compile_string",
"(",
"string",
")"
] | Compile a single string, and return a string of CSS.
Keyword arguments are passed along to the underlying `Compiler`. | [
"Compile",
"a",
"single",
"string",
"and",
"return",
"a",
"string",
"of",
"CSS",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L240-L246 |
24,534 | Kronuz/pyScss | scss/compiler.py | Compilation.parse_selectors | def parse_selectors(self, raw_selectors):
"""
Parses out the old xCSS "foo extends bar" syntax.
Returns a 2-tuple: a set of selectors, and a set of extended selectors.
"""
# Fix tabs and spaces in selectors
raw_selectors = _spaces_re.sub(' ', raw_selectors)
parts = _xcss_extends_re.split(raw_selectors, 1) # handle old xCSS extends
if len(parts) > 1:
unparsed_selectors, unsplit_parents = parts
# Multiple `extends` are delimited by `&`
unparsed_parents = unsplit_parents.split('&')
else:
unparsed_selectors, = parts
unparsed_parents = ()
selectors = Selector.parse_many(unparsed_selectors)
parents = [Selector.parse_one(parent) for parent in unparsed_parents]
return selectors, parents | python | def parse_selectors(self, raw_selectors):
# Fix tabs and spaces in selectors
raw_selectors = _spaces_re.sub(' ', raw_selectors)
parts = _xcss_extends_re.split(raw_selectors, 1) # handle old xCSS extends
if len(parts) > 1:
unparsed_selectors, unsplit_parents = parts
# Multiple `extends` are delimited by `&`
unparsed_parents = unsplit_parents.split('&')
else:
unparsed_selectors, = parts
unparsed_parents = ()
selectors = Selector.parse_many(unparsed_selectors)
parents = [Selector.parse_one(parent) for parent in unparsed_parents]
return selectors, parents | [
"def",
"parse_selectors",
"(",
"self",
",",
"raw_selectors",
")",
":",
"# Fix tabs and spaces in selectors",
"raw_selectors",
"=",
"_spaces_re",
".",
"sub",
"(",
"' '",
",",
"raw_selectors",
")",
"parts",
"=",
"_xcss_extends_re",
".",
"split",
"(",
"raw_selectors",
... | Parses out the old xCSS "foo extends bar" syntax.
Returns a 2-tuple: a set of selectors, and a set of extended selectors. | [
"Parses",
"out",
"the",
"old",
"xCSS",
"foo",
"extends",
"bar",
"syntax",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L308-L329 |
24,535 | Kronuz/pyScss | scss/compiler.py | Compilation._get_properties | def _get_properties(self, rule, scope, block):
"""
Implements properties and variables extraction and assignment
"""
prop, raw_value = (_prop_split_re.split(block.prop, 1) + [None])[:2]
if raw_value is not None:
raw_value = raw_value.strip()
try:
is_var = (block.prop[len(prop)] == '=')
except IndexError:
is_var = False
if is_var:
warn_deprecated(rule, "Assignment with = is deprecated; use : instead.")
calculator = self._make_calculator(rule.namespace)
prop = prop.strip()
prop = calculator.do_glob_math(prop)
if not prop:
return
_prop = (scope or '') + prop
if is_var or prop.startswith('$') and raw_value is not None:
# Pop off any flags: !default, !global
is_default = False
is_global = True # eventually sass will default this to false
while True:
splits = raw_value.rsplit(None, 1)
if len(splits) < 2 or not splits[1].startswith('!'):
break
raw_value, flag = splits
if flag == '!default':
is_default = True
elif flag == '!global':
is_global = True
else:
raise ValueError("Unrecognized flag: {0}".format(flag))
# Variable assignment
_prop = normalize_var(_prop)
try:
existing_value = rule.namespace.variable(_prop)
except KeyError:
existing_value = None
is_defined = existing_value is not None and not existing_value.is_null
if is_default and is_defined:
pass
else:
if is_defined and prop.startswith('$') and prop[1].isupper():
log.warn("Constant %r redefined", prop)
# Variable assignment is an expression, so it always performs
# real division
value = calculator.calculate(raw_value, divide=True)
rule.namespace.set_variable(
_prop, value, local_only=not is_global)
else:
# Regular property destined for output
_prop = calculator.apply_vars(_prop)
if raw_value is None:
value = None
else:
value = calculator.calculate(raw_value)
if value is None:
pass
elif isinstance(value, six.string_types):
# TODO kill this branch
pass
else:
if value.is_null:
return
style = rule.legacy_compiler_options.get(
'style', self.compiler.output_style)
compress = style == 'compressed'
value = value.render(compress=compress)
rule.properties.append((_prop, value)) | python | def _get_properties(self, rule, scope, block):
prop, raw_value = (_prop_split_re.split(block.prop, 1) + [None])[:2]
if raw_value is not None:
raw_value = raw_value.strip()
try:
is_var = (block.prop[len(prop)] == '=')
except IndexError:
is_var = False
if is_var:
warn_deprecated(rule, "Assignment with = is deprecated; use : instead.")
calculator = self._make_calculator(rule.namespace)
prop = prop.strip()
prop = calculator.do_glob_math(prop)
if not prop:
return
_prop = (scope or '') + prop
if is_var or prop.startswith('$') and raw_value is not None:
# Pop off any flags: !default, !global
is_default = False
is_global = True # eventually sass will default this to false
while True:
splits = raw_value.rsplit(None, 1)
if len(splits) < 2 or not splits[1].startswith('!'):
break
raw_value, flag = splits
if flag == '!default':
is_default = True
elif flag == '!global':
is_global = True
else:
raise ValueError("Unrecognized flag: {0}".format(flag))
# Variable assignment
_prop = normalize_var(_prop)
try:
existing_value = rule.namespace.variable(_prop)
except KeyError:
existing_value = None
is_defined = existing_value is not None and not existing_value.is_null
if is_default and is_defined:
pass
else:
if is_defined and prop.startswith('$') and prop[1].isupper():
log.warn("Constant %r redefined", prop)
# Variable assignment is an expression, so it always performs
# real division
value = calculator.calculate(raw_value, divide=True)
rule.namespace.set_variable(
_prop, value, local_only=not is_global)
else:
# Regular property destined for output
_prop = calculator.apply_vars(_prop)
if raw_value is None:
value = None
else:
value = calculator.calculate(raw_value)
if value is None:
pass
elif isinstance(value, six.string_types):
# TODO kill this branch
pass
else:
if value.is_null:
return
style = rule.legacy_compiler_options.get(
'style', self.compiler.output_style)
compress = style == 'compressed'
value = value.render(compress=compress)
rule.properties.append((_prop, value)) | [
"def",
"_get_properties",
"(",
"self",
",",
"rule",
",",
"scope",
",",
"block",
")",
":",
"prop",
",",
"raw_value",
"=",
"(",
"_prop_split_re",
".",
"split",
"(",
"block",
".",
"prop",
",",
"1",
")",
"+",
"[",
"None",
"]",
")",
"[",
":",
"2",
"]"... | Implements properties and variables extraction and assignment | [
"Implements",
"properties",
"and",
"variables",
"extraction",
"and",
"assignment"
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L1027-L1105 |
24,536 | Kronuz/pyScss | scss/types.py | _constrain | def _constrain(value, lb=0, ub=1):
"""Helper for Color constructors. Constrains a value to a range."""
if value < lb:
return lb
elif value > ub:
return ub
else:
return value | python | def _constrain(value, lb=0, ub=1):
if value < lb:
return lb
elif value > ub:
return ub
else:
return value | [
"def",
"_constrain",
"(",
"value",
",",
"lb",
"=",
"0",
",",
"ub",
"=",
"1",
")",
":",
"if",
"value",
"<",
"lb",
":",
"return",
"lb",
"elif",
"value",
">",
"ub",
":",
"return",
"ub",
"else",
":",
"return",
"value"
] | Helper for Color constructors. Constrains a value to a range. | [
"Helper",
"for",
"Color",
"constructors",
".",
"Constrains",
"a",
"value",
"to",
"a",
"range",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L808-L815 |
24,537 | Kronuz/pyScss | scss/types.py | Number._add_sub | def _add_sub(self, other, op):
"""Implements both addition and subtraction."""
if not isinstance(other, Number):
return NotImplemented
# If either side is unitless, inherit the other side's units. Skip all
# the rest of the conversion math, too.
if self.is_unitless or other.is_unitless:
return Number(
op(self.value, other.value),
unit_numer=self.unit_numer or other.unit_numer,
unit_denom=self.unit_denom or other.unit_denom,
)
# Likewise, if either side is zero, it can auto-cast to any units
if self.value == 0:
return Number(
op(self.value, other.value),
unit_numer=other.unit_numer,
unit_denom=other.unit_denom,
)
elif other.value == 0:
return Number(
op(self.value, other.value),
unit_numer=self.unit_numer,
unit_denom=self.unit_denom,
)
# Reduce both operands to the same units
left = self.to_base_units()
right = other.to_base_units()
if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom:
raise ValueError("Can't reconcile units: %r and %r" % (self, other))
new_amount = op(left.value, right.value)
# Convert back to the left side's units
if left.value != 0:
new_amount = new_amount * self.value / left.value
return Number(new_amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom) | python | def _add_sub(self, other, op):
if not isinstance(other, Number):
return NotImplemented
# If either side is unitless, inherit the other side's units. Skip all
# the rest of the conversion math, too.
if self.is_unitless or other.is_unitless:
return Number(
op(self.value, other.value),
unit_numer=self.unit_numer or other.unit_numer,
unit_denom=self.unit_denom or other.unit_denom,
)
# Likewise, if either side is zero, it can auto-cast to any units
if self.value == 0:
return Number(
op(self.value, other.value),
unit_numer=other.unit_numer,
unit_denom=other.unit_denom,
)
elif other.value == 0:
return Number(
op(self.value, other.value),
unit_numer=self.unit_numer,
unit_denom=self.unit_denom,
)
# Reduce both operands to the same units
left = self.to_base_units()
right = other.to_base_units()
if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom:
raise ValueError("Can't reconcile units: %r and %r" % (self, other))
new_amount = op(left.value, right.value)
# Convert back to the left side's units
if left.value != 0:
new_amount = new_amount * self.value / left.value
return Number(new_amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom) | [
"def",
"_add_sub",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Number",
")",
":",
"return",
"NotImplemented",
"# If either side is unitless, inherit the other side's units. Skip all",
"# the rest of the conversion math, ... | Implements both addition and subtraction. | [
"Implements",
"both",
"addition",
"and",
"subtraction",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L442-L483 |
24,538 | Kronuz/pyScss | scss/types.py | Number.to_base_units | def to_base_units(self):
"""Convert to a fixed set of "base" units. The particular units are
arbitrary; what's important is that they're consistent.
Used for addition and comparisons.
"""
# Convert to "standard" units, as defined by the conversions dict above
amount = self.value
numer_factor, numer_units = convert_units_to_base_units(self.unit_numer)
denom_factor, denom_units = convert_units_to_base_units(self.unit_denom)
return Number(
amount * numer_factor / denom_factor,
unit_numer=numer_units,
unit_denom=denom_units,
) | python | def to_base_units(self):
# Convert to "standard" units, as defined by the conversions dict above
amount = self.value
numer_factor, numer_units = convert_units_to_base_units(self.unit_numer)
denom_factor, denom_units = convert_units_to_base_units(self.unit_denom)
return Number(
amount * numer_factor / denom_factor,
unit_numer=numer_units,
unit_denom=denom_units,
) | [
"def",
"to_base_units",
"(",
"self",
")",
":",
"# Convert to \"standard\" units, as defined by the conversions dict above",
"amount",
"=",
"self",
".",
"value",
"numer_factor",
",",
"numer_units",
"=",
"convert_units_to_base_units",
"(",
"self",
".",
"unit_numer",
")",
"d... | Convert to a fixed set of "base" units. The particular units are
arbitrary; what's important is that they're consistent.
Used for addition and comparisons. | [
"Convert",
"to",
"a",
"fixed",
"set",
"of",
"base",
"units",
".",
"The",
"particular",
"units",
"are",
"arbitrary",
";",
"what",
"s",
"important",
"is",
"that",
"they",
"re",
"consistent",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L487-L503 |
24,539 | Kronuz/pyScss | scss/types.py | Number.wrap_python_function | def wrap_python_function(cls, fn):
"""Wraps an unary Python math function, translating the argument from
Sass to Python on the way in, and vice versa for the return value.
Used to wrap simple Python functions like `ceil`, `floor`, etc.
"""
def wrapped(sass_arg):
# TODO enforce no units for trig?
python_arg = sass_arg.value
python_ret = fn(python_arg)
sass_ret = cls(
python_ret,
unit_numer=sass_arg.unit_numer,
unit_denom=sass_arg.unit_denom)
return sass_ret
return wrapped | python | def wrap_python_function(cls, fn):
def wrapped(sass_arg):
# TODO enforce no units for trig?
python_arg = sass_arg.value
python_ret = fn(python_arg)
sass_ret = cls(
python_ret,
unit_numer=sass_arg.unit_numer,
unit_denom=sass_arg.unit_denom)
return sass_ret
return wrapped | [
"def",
"wrap_python_function",
"(",
"cls",
",",
"fn",
")",
":",
"def",
"wrapped",
"(",
"sass_arg",
")",
":",
"# TODO enforce no units for trig?",
"python_arg",
"=",
"sass_arg",
".",
"value",
"python_ret",
"=",
"fn",
"(",
"python_arg",
")",
"sass_ret",
"=",
"cl... | Wraps an unary Python math function, translating the argument from
Sass to Python on the way in, and vice versa for the return value.
Used to wrap simple Python functions like `ceil`, `floor`, etc. | [
"Wraps",
"an",
"unary",
"Python",
"math",
"function",
"translating",
"the",
"argument",
"from",
"Sass",
"to",
"Python",
"on",
"the",
"way",
"in",
"and",
"vice",
"versa",
"for",
"the",
"return",
"value",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L508-L524 |
24,540 | Kronuz/pyScss | scss/types.py | Number.to_python_index | def to_python_index(self, length, check_bounds=True, circular=False):
"""Return a plain Python integer appropriate for indexing a sequence of
the given length. Raise if this is impossible for any reason
whatsoever.
"""
if not self.is_unitless:
raise ValueError("Index cannot have units: {0!r}".format(self))
ret = int(self.value)
if ret != self.value:
raise ValueError("Index must be an integer: {0!r}".format(ret))
if ret == 0:
raise ValueError("Index cannot be zero")
if check_bounds and not circular and abs(ret) > length:
raise ValueError("Index {0!r} out of bounds for length {1}".format(ret, length))
if ret > 0:
ret -= 1
if circular:
ret = ret % length
return ret | python | def to_python_index(self, length, check_bounds=True, circular=False):
if not self.is_unitless:
raise ValueError("Index cannot have units: {0!r}".format(self))
ret = int(self.value)
if ret != self.value:
raise ValueError("Index must be an integer: {0!r}".format(ret))
if ret == 0:
raise ValueError("Index cannot be zero")
if check_bounds and not circular and abs(ret) > length:
raise ValueError("Index {0!r} out of bounds for length {1}".format(ret, length))
if ret > 0:
ret -= 1
if circular:
ret = ret % length
return ret | [
"def",
"to_python_index",
"(",
"self",
",",
"length",
",",
"check_bounds",
"=",
"True",
",",
"circular",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"is_unitless",
":",
"raise",
"ValueError",
"(",
"\"Index cannot have units: {0!r}\"",
".",
"format",
"(",... | Return a plain Python integer appropriate for indexing a sequence of
the given length. Raise if this is impossible for any reason
whatsoever. | [
"Return",
"a",
"plain",
"Python",
"integer",
"appropriate",
"for",
"indexing",
"a",
"sequence",
"of",
"the",
"given",
"length",
".",
"Raise",
"if",
"this",
"is",
"impossible",
"for",
"any",
"reason",
"whatsoever",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L526-L550 |
24,541 | Kronuz/pyScss | scss/types.py | List.maybe_new | def maybe_new(cls, values, use_comma=True):
"""If `values` contains only one item, return that item. Otherwise,
return a List as normal.
"""
if len(values) == 1:
return values[0]
else:
return cls(values, use_comma=use_comma) | python | def maybe_new(cls, values, use_comma=True):
if len(values) == 1:
return values[0]
else:
return cls(values, use_comma=use_comma) | [
"def",
"maybe_new",
"(",
"cls",
",",
"values",
",",
"use_comma",
"=",
"True",
")",
":",
"if",
"len",
"(",
"values",
")",
"==",
"1",
":",
"return",
"values",
"[",
"0",
"]",
"else",
":",
"return",
"cls",
"(",
"values",
",",
"use_comma",
"=",
"use_com... | If `values` contains only one item, return that item. Otherwise,
return a List as normal. | [
"If",
"values",
"contains",
"only",
"one",
"item",
"return",
"that",
"item",
".",
"Otherwise",
"return",
"a",
"List",
"as",
"normal",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L636-L643 |
24,542 | Kronuz/pyScss | scss/types.py | List.from_maybe_starargs | def from_maybe_starargs(cls, args, use_comma=True):
"""If `args` has one element which appears to be a list, return it.
Otherwise, return a list as normal.
Mainly used by Sass function implementations that predate `...`
support, so they can accept both a list of arguments and a single list
stored in a variable.
"""
if len(args) == 1:
if isinstance(args[0], cls):
return args[0]
elif isinstance(args[0], (list, tuple)):
return cls(args[0], use_comma=use_comma)
return cls(args, use_comma=use_comma) | python | def from_maybe_starargs(cls, args, use_comma=True):
if len(args) == 1:
if isinstance(args[0], cls):
return args[0]
elif isinstance(args[0], (list, tuple)):
return cls(args[0], use_comma=use_comma)
return cls(args, use_comma=use_comma) | [
"def",
"from_maybe_starargs",
"(",
"cls",
",",
"args",
",",
"use_comma",
"=",
"True",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"cls",
")",
":",
"return",
"args",
"[",
"0",
"]",
... | If `args` has one element which appears to be a list, return it.
Otherwise, return a list as normal.
Mainly used by Sass function implementations that predate `...`
support, so they can accept both a list of arguments and a single list
stored in a variable. | [
"If",
"args",
"has",
"one",
"element",
"which",
"appears",
"to",
"be",
"a",
"list",
"return",
"it",
".",
"Otherwise",
"return",
"a",
"list",
"as",
"normal",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L664-L678 |
24,543 | Kronuz/pyScss | scss/types.py | Color.from_name | def from_name(cls, name):
"""Build a Color from a CSS color name."""
self = cls.__new__(cls) # TODO
self.original_literal = name
r, g, b, a = COLOR_NAMES[name]
self.value = r, g, b, a
return self | python | def from_name(cls, name):
self = cls.__new__(cls) # TODO
self.original_literal = name
r, g, b, a = COLOR_NAMES[name]
self.value = r, g, b, a
return self | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"self",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"# TODO",
"self",
".",
"original_literal",
"=",
"name",
"r",
",",
"g",
",",
"b",
",",
"a",
"=",
"COLOR_NAMES",
"[",
"name",
"]",
"self",
"... | Build a Color from a CSS color name. | [
"Build",
"a",
"Color",
"from",
"a",
"CSS",
"color",
"name",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L893-L901 |
24,544 | Kronuz/pyScss | scss/types.py | String.unquoted | def unquoted(cls, value, literal=False):
"""Helper to create a string with no quotes."""
return cls(value, quotes=None, literal=literal) | python | def unquoted(cls, value, literal=False):
return cls(value, quotes=None, literal=literal) | [
"def",
"unquoted",
"(",
"cls",
",",
"value",
",",
"literal",
"=",
"False",
")",
":",
"return",
"cls",
"(",
"value",
",",
"quotes",
"=",
"None",
",",
"literal",
"=",
"literal",
")"
] | Helper to create a string with no quotes. | [
"Helper",
"to",
"create",
"a",
"string",
"with",
"no",
"quotes",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L1096-L1098 |
24,545 | Kronuz/pyScss | scss/selector.py | _is_combinator_subset_of | def _is_combinator_subset_of(specific, general, is_first=True):
"""Return whether `specific` matches a non-strict subset of what `general`
matches.
"""
if is_first and general == ' ':
# First selector always has a space to mean "descendent of root", which
# still holds if any other selector appears above it
return True
if specific == general:
return True
if specific == '>' and general == ' ':
return True
if specific == '+' and general == '~':
return True
return False | python | def _is_combinator_subset_of(specific, general, is_first=True):
if is_first and general == ' ':
# First selector always has a space to mean "descendent of root", which
# still holds if any other selector appears above it
return True
if specific == general:
return True
if specific == '>' and general == ' ':
return True
if specific == '+' and general == '~':
return True
return False | [
"def",
"_is_combinator_subset_of",
"(",
"specific",
",",
"general",
",",
"is_first",
"=",
"True",
")",
":",
"if",
"is_first",
"and",
"general",
"==",
"' '",
":",
"# First selector always has a space to mean \"descendent of root\", which",
"# still holds if any other selector ... | Return whether `specific` matches a non-strict subset of what `general`
matches. | [
"Return",
"whether",
"specific",
"matches",
"a",
"non",
"-",
"strict",
"subset",
"of",
"what",
"general",
"matches",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L62-L80 |
24,546 | Kronuz/pyScss | scss/selector.py | _weave_conflicting_selectors | def _weave_conflicting_selectors(prefixes, a, b, suffix=()):
"""Part of the selector merge algorithm above. Not useful on its own. Pay
no attention to the man behind the curtain.
"""
# OK, what this actually does: given a list of selector chains, two
# "conflicting" selector chains, and an optional suffix, return a new list
# of chains like this:
# prefix[0] + a + b + suffix,
# prefix[0] + b + a + suffix,
# prefix[1] + a + b + suffix,
# ...
# In other words, this just appends a new chain to each of a list of given
# chains, except that the new chain might be the superposition of two
# other incompatible chains.
both = a and b
for prefix in prefixes:
yield prefix + a + b + suffix
if both:
# Only use both orderings if there's an actual conflict!
yield prefix + b + a + suffix | python | def _weave_conflicting_selectors(prefixes, a, b, suffix=()):
# OK, what this actually does: given a list of selector chains, two
# "conflicting" selector chains, and an optional suffix, return a new list
# of chains like this:
# prefix[0] + a + b + suffix,
# prefix[0] + b + a + suffix,
# prefix[1] + a + b + suffix,
# ...
# In other words, this just appends a new chain to each of a list of given
# chains, except that the new chain might be the superposition of two
# other incompatible chains.
both = a and b
for prefix in prefixes:
yield prefix + a + b + suffix
if both:
# Only use both orderings if there's an actual conflict!
yield prefix + b + a + suffix | [
"def",
"_weave_conflicting_selectors",
"(",
"prefixes",
",",
"a",
",",
"b",
",",
"suffix",
"=",
"(",
")",
")",
":",
"# OK, what this actually does: given a list of selector chains, two",
"# \"conflicting\" selector chains, and an optional suffix, return a new list",
"# of chains li... | Part of the selector merge algorithm above. Not useful on its own. Pay
no attention to the man behind the curtain. | [
"Part",
"of",
"the",
"selector",
"merge",
"algorithm",
"above",
".",
"Not",
"useful",
"on",
"its",
"own",
".",
"Pay",
"no",
"attention",
"to",
"the",
"man",
"behind",
"the",
"curtain",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L550-L569 |
24,547 | Kronuz/pyScss | scss/selector.py | _merge_simple_selectors | def _merge_simple_selectors(a, b):
"""Merge two simple selectors, for the purposes of the LCS algorithm below.
In practice this returns the more specific selector if one is a subset of
the other, else it returns None.
"""
# TODO what about combinators
if a.is_superset_of(b):
return b
elif b.is_superset_of(a):
return a
else:
return None | python | def _merge_simple_selectors(a, b):
# TODO what about combinators
if a.is_superset_of(b):
return b
elif b.is_superset_of(a):
return a
else:
return None | [
"def",
"_merge_simple_selectors",
"(",
"a",
",",
"b",
")",
":",
"# TODO what about combinators",
"if",
"a",
".",
"is_superset_of",
"(",
"b",
")",
":",
"return",
"b",
"elif",
"b",
".",
"is_superset_of",
"(",
"a",
")",
":",
"return",
"a",
"else",
":",
"ret... | Merge two simple selectors, for the purposes of the LCS algorithm below.
In practice this returns the more specific selector if one is a subset of
the other, else it returns None. | [
"Merge",
"two",
"simple",
"selectors",
"for",
"the",
"purposes",
"of",
"the",
"LCS",
"algorithm",
"below",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L572-L584 |
24,548 | Kronuz/pyScss | scss/selector.py | longest_common_subsequence | def longest_common_subsequence(a, b, mergefunc=None):
"""Find the longest common subsequence between two iterables.
The longest common subsequence is the core of any diff algorithm: it's the
longest sequence of elements that appears in both parent sequences in the
same order, but NOT necessarily consecutively.
Original algorithm borrowed from Wikipedia:
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution
This function is used only to implement @extend, largely because that's
what the Ruby implementation does. Thus it's been extended slightly from
the simple diff-friendly algorithm given above.
What @extend wants to know is whether two simple selectors are compatible,
not just equal. To that end, you must pass in a "merge" function to
compare a pair of elements manually. It should return `None` if they are
incompatible, and a MERGED element if they are compatible -- in the case of
selectors, this is whichever one is more specific.
Because of this fuzzier notion of equality, the return value is a list of
``(a_index, b_index, value)`` tuples rather than items alone.
"""
if mergefunc is None:
# Stupid default, just in case
def mergefunc(a, b):
if a == b:
return a
return None
# Precalculate equality, since it can be a tad expensive and every pair is
# compared at least once
eq = {}
for ai, aval in enumerate(a):
for bi, bval in enumerate(b):
eq[ai, bi] = mergefunc(aval, bval)
# Build the "length" matrix, which provides the length of the LCS for
# arbitrary-length prefixes. -1 exists only to support the base case
prefix_lcs_length = {}
for ai in range(-1, len(a)):
for bi in range(-1, len(b)):
if ai == -1 or bi == -1:
l = 0
elif eq[ai, bi]:
l = prefix_lcs_length[ai - 1, bi - 1] + 1
else:
l = max(
prefix_lcs_length[ai, bi - 1],
prefix_lcs_length[ai - 1, bi])
prefix_lcs_length[ai, bi] = l
# The interesting part. The key insight is that the bottom-right value in
# the length matrix must be the length of the LCS because of how the matrix
# is defined, so all that's left to do is backtrack from the ends of both
# sequences in whatever way keeps the LCS as long as possible, and keep
# track of the equal pairs of elements we see along the way.
# Wikipedia does this with recursion, but the algorithm is trivial to
# rewrite as a loop, as below.
ai = len(a) - 1
bi = len(b) - 1
ret = []
while ai >= 0 and bi >= 0:
merged = eq[ai, bi]
if merged is not None:
ret.append((ai, bi, merged))
ai -= 1
bi -= 1
elif prefix_lcs_length[ai, bi - 1] > prefix_lcs_length[ai - 1, bi]:
bi -= 1
else:
ai -= 1
# ret has the latest items first, which is backwards
ret.reverse()
return ret | python | def longest_common_subsequence(a, b, mergefunc=None):
if mergefunc is None:
# Stupid default, just in case
def mergefunc(a, b):
if a == b:
return a
return None
# Precalculate equality, since it can be a tad expensive and every pair is
# compared at least once
eq = {}
for ai, aval in enumerate(a):
for bi, bval in enumerate(b):
eq[ai, bi] = mergefunc(aval, bval)
# Build the "length" matrix, which provides the length of the LCS for
# arbitrary-length prefixes. -1 exists only to support the base case
prefix_lcs_length = {}
for ai in range(-1, len(a)):
for bi in range(-1, len(b)):
if ai == -1 or bi == -1:
l = 0
elif eq[ai, bi]:
l = prefix_lcs_length[ai - 1, bi - 1] + 1
else:
l = max(
prefix_lcs_length[ai, bi - 1],
prefix_lcs_length[ai - 1, bi])
prefix_lcs_length[ai, bi] = l
# The interesting part. The key insight is that the bottom-right value in
# the length matrix must be the length of the LCS because of how the matrix
# is defined, so all that's left to do is backtrack from the ends of both
# sequences in whatever way keeps the LCS as long as possible, and keep
# track of the equal pairs of elements we see along the way.
# Wikipedia does this with recursion, but the algorithm is trivial to
# rewrite as a loop, as below.
ai = len(a) - 1
bi = len(b) - 1
ret = []
while ai >= 0 and bi >= 0:
merged = eq[ai, bi]
if merged is not None:
ret.append((ai, bi, merged))
ai -= 1
bi -= 1
elif prefix_lcs_length[ai, bi - 1] > prefix_lcs_length[ai - 1, bi]:
bi -= 1
else:
ai -= 1
# ret has the latest items first, which is backwards
ret.reverse()
return ret | [
"def",
"longest_common_subsequence",
"(",
"a",
",",
"b",
",",
"mergefunc",
"=",
"None",
")",
":",
"if",
"mergefunc",
"is",
"None",
":",
"# Stupid default, just in case",
"def",
"mergefunc",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"==",
"b",
":",
"return... | Find the longest common subsequence between two iterables.
The longest common subsequence is the core of any diff algorithm: it's the
longest sequence of elements that appears in both parent sequences in the
same order, but NOT necessarily consecutively.
Original algorithm borrowed from Wikipedia:
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution
This function is used only to implement @extend, largely because that's
what the Ruby implementation does. Thus it's been extended slightly from
the simple diff-friendly algorithm given above.
What @extend wants to know is whether two simple selectors are compatible,
not just equal. To that end, you must pass in a "merge" function to
compare a pair of elements manually. It should return `None` if they are
incompatible, and a MERGED element if they are compatible -- in the case of
selectors, this is whichever one is more specific.
Because of this fuzzier notion of equality, the return value is a list of
``(a_index, b_index, value)`` tuples rather than items alone. | [
"Find",
"the",
"longest",
"common",
"subsequence",
"between",
"two",
"iterables",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L587-L664 |
24,549 | Kronuz/pyScss | scss/selector.py | SimpleSelector.is_superset_of | def is_superset_of(self, other, soft_combinator=False):
"""Return True iff this selector matches the same elements as `other`,
and perhaps others.
That is, ``.foo`` is a superset of ``.foo.bar``, because the latter is
more specific.
Set `soft_combinator` true to ignore the specific case of this selector
having a descendent combinator and `other` having anything else. This
is for superset checking for ``@extend``, where a space combinator
really means "none".
"""
# Combinators must match, OR be compatible -- space is a superset of >,
# ~ is a superset of +
if soft_combinator and self.combinator == ' ':
combinator_superset = True
else:
combinator_superset = (
self.combinator == other.combinator or
(self.combinator == ' ' and other.combinator == '>') or
(self.combinator == '~' and other.combinator == '+'))
return (
combinator_superset and
set(self.tokens) <= set(other.tokens)) | python | def is_superset_of(self, other, soft_combinator=False):
# Combinators must match, OR be compatible -- space is a superset of >,
# ~ is a superset of +
if soft_combinator and self.combinator == ' ':
combinator_superset = True
else:
combinator_superset = (
self.combinator == other.combinator or
(self.combinator == ' ' and other.combinator == '>') or
(self.combinator == '~' and other.combinator == '+'))
return (
combinator_superset and
set(self.tokens) <= set(other.tokens)) | [
"def",
"is_superset_of",
"(",
"self",
",",
"other",
",",
"soft_combinator",
"=",
"False",
")",
":",
"# Combinators must match, OR be compatible -- space is a superset of >,",
"# ~ is a superset of +",
"if",
"soft_combinator",
"and",
"self",
".",
"combinator",
"==",
"' '",
... | Return True iff this selector matches the same elements as `other`,
and perhaps others.
That is, ``.foo`` is a superset of ``.foo.bar``, because the latter is
more specific.
Set `soft_combinator` true to ignore the specific case of this selector
having a descendent combinator and `other` having anything else. This
is for superset checking for ``@extend``, where a space combinator
really means "none". | [
"Return",
"True",
"iff",
"this",
"selector",
"matches",
"the",
"same",
"elements",
"as",
"other",
"and",
"perhaps",
"others",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L136-L160 |
24,550 | Kronuz/pyScss | scss/selector.py | Selector.substitute | def substitute(self, target, replacement):
"""Return a list of selectors obtained by replacing the `target`
selector with `replacement`.
Herein lie the guts of the Sass @extend directive.
In general, for a selector ``a X b Y c``, a target ``X Y``, and a
replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b
Z c``. Note in particular that no more than two selectors will be
returned, and the permutation of ancestors will never insert new simple
selectors "inside" the target selector.
"""
# Find the target in the parent selector, and split it into
# before/after
p_before, p_extras, p_after = self.break_around(target.simple_selectors)
# The replacement has no hinge; it only has the most specific simple
# selector (which is the part that replaces "self" in the parent) and
# whatever preceding simple selectors there may be
r_trail = replacement.simple_selectors[:-1]
r_extras = replacement.simple_selectors[-1]
# TODO what if the prefix doesn't match? who wins? should we even get
# this far?
focal_nodes = (p_extras.merge_into(r_extras),)
befores = _merge_selectors(p_before, r_trail)
cls = type(self)
return [
cls(before + focal_nodes + p_after)
for before in befores] | python | def substitute(self, target, replacement):
# Find the target in the parent selector, and split it into
# before/after
p_before, p_extras, p_after = self.break_around(target.simple_selectors)
# The replacement has no hinge; it only has the most specific simple
# selector (which is the part that replaces "self" in the parent) and
# whatever preceding simple selectors there may be
r_trail = replacement.simple_selectors[:-1]
r_extras = replacement.simple_selectors[-1]
# TODO what if the prefix doesn't match? who wins? should we even get
# this far?
focal_nodes = (p_extras.merge_into(r_extras),)
befores = _merge_selectors(p_before, r_trail)
cls = type(self)
return [
cls(before + focal_nodes + p_after)
for before in befores] | [
"def",
"substitute",
"(",
"self",
",",
"target",
",",
"replacement",
")",
":",
"# Find the target in the parent selector, and split it into",
"# before/after",
"p_before",
",",
"p_extras",
",",
"p_after",
"=",
"self",
".",
"break_around",
"(",
"target",
".",
"simple_s... | Return a list of selectors obtained by replacing the `target`
selector with `replacement`.
Herein lie the guts of the Sass @extend directive.
In general, for a selector ``a X b Y c``, a target ``X Y``, and a
replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b
Z c``. Note in particular that no more than two selectors will be
returned, and the permutation of ancestors will never insert new simple
selectors "inside" the target selector. | [
"Return",
"a",
"list",
"of",
"selectors",
"obtained",
"by",
"replacing",
"the",
"target",
"selector",
"with",
"replacement",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L428-L459 |
24,551 | Kronuz/pyScss | scss/cssdefs.py | convert_units_to_base_units | def convert_units_to_base_units(units):
"""Convert a set of units into a set of "base" units.
Returns a 2-tuple of `factor, new_units`.
"""
total_factor = 1
new_units = []
for unit in units:
if unit not in BASE_UNIT_CONVERSIONS:
continue
factor, new_unit = BASE_UNIT_CONVERSIONS[unit]
total_factor *= factor
new_units.append(new_unit)
new_units.sort()
return total_factor, tuple(new_units) | python | def convert_units_to_base_units(units):
total_factor = 1
new_units = []
for unit in units:
if unit not in BASE_UNIT_CONVERSIONS:
continue
factor, new_unit = BASE_UNIT_CONVERSIONS[unit]
total_factor *= factor
new_units.append(new_unit)
new_units.sort()
return total_factor, tuple(new_units) | [
"def",
"convert_units_to_base_units",
"(",
"units",
")",
":",
"total_factor",
"=",
"1",
"new_units",
"=",
"[",
"]",
"for",
"unit",
"in",
"units",
":",
"if",
"unit",
"not",
"in",
"BASE_UNIT_CONVERSIONS",
":",
"continue",
"factor",
",",
"new_unit",
"=",
"BASE_... | Convert a set of units into a set of "base" units.
Returns a 2-tuple of `factor, new_units`. | [
"Convert",
"a",
"set",
"of",
"units",
"into",
"a",
"set",
"of",
"base",
"units",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L208-L224 |
24,552 | Kronuz/pyScss | scss/cssdefs.py | count_base_units | def count_base_units(units):
"""Returns a dict mapping names of base units to how many times they
appear in the given iterable of units. Effectively this counts how
many length units you have, how many time units, and so forth.
"""
ret = {}
for unit in units:
factor, base_unit = get_conversion_factor(unit)
ret.setdefault(base_unit, 0)
ret[base_unit] += 1
return ret | python | def count_base_units(units):
ret = {}
for unit in units:
factor, base_unit = get_conversion_factor(unit)
ret.setdefault(base_unit, 0)
ret[base_unit] += 1
return ret | [
"def",
"count_base_units",
"(",
"units",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"unit",
"in",
"units",
":",
"factor",
",",
"base_unit",
"=",
"get_conversion_factor",
"(",
"unit",
")",
"ret",
".",
"setdefault",
"(",
"base_unit",
",",
"0",
")",
"ret",
"[... | Returns a dict mapping names of base units to how many times they
appear in the given iterable of units. Effectively this counts how
many length units you have, how many time units, and so forth. | [
"Returns",
"a",
"dict",
"mapping",
"names",
"of",
"base",
"units",
"to",
"how",
"many",
"times",
"they",
"appear",
"in",
"the",
"given",
"iterable",
"of",
"units",
".",
"Effectively",
"this",
"counts",
"how",
"many",
"length",
"units",
"you",
"have",
"how"... | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L227-L239 |
24,553 | Kronuz/pyScss | scss/cssdefs.py | cancel_base_units | def cancel_base_units(units, to_remove):
"""Given a list of units, remove a specified number of each base unit.
Arguments:
units: an iterable of units
to_remove: a mapping of base_unit => count, such as that returned from
count_base_units
Returns a 2-tuple of (factor, remaining_units).
"""
# Copy the dict since we're about to mutate it
to_remove = to_remove.copy()
remaining_units = []
total_factor = Fraction(1)
for unit in units:
factor, base_unit = get_conversion_factor(unit)
if not to_remove.get(base_unit, 0):
remaining_units.append(unit)
continue
total_factor *= factor
to_remove[base_unit] -= 1
return total_factor, remaining_units | python | def cancel_base_units(units, to_remove):
# Copy the dict since we're about to mutate it
to_remove = to_remove.copy()
remaining_units = []
total_factor = Fraction(1)
for unit in units:
factor, base_unit = get_conversion_factor(unit)
if not to_remove.get(base_unit, 0):
remaining_units.append(unit)
continue
total_factor *= factor
to_remove[base_unit] -= 1
return total_factor, remaining_units | [
"def",
"cancel_base_units",
"(",
"units",
",",
"to_remove",
")",
":",
"# Copy the dict since we're about to mutate it",
"to_remove",
"=",
"to_remove",
".",
"copy",
"(",
")",
"remaining_units",
"=",
"[",
"]",
"total_factor",
"=",
"Fraction",
"(",
"1",
")",
"for",
... | Given a list of units, remove a specified number of each base unit.
Arguments:
units: an iterable of units
to_remove: a mapping of base_unit => count, such as that returned from
count_base_units
Returns a 2-tuple of (factor, remaining_units). | [
"Given",
"a",
"list",
"of",
"units",
"remove",
"a",
"specified",
"number",
"of",
"each",
"base",
"unit",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L242-L267 |
24,554 | Kronuz/pyScss | scss/cssdefs.py | is_builtin_css_function | def is_builtin_css_function(name):
"""Returns whether the given `name` looks like the name of a builtin CSS
function.
Unrecognized functions not in this list produce warnings.
"""
name = name.replace('_', '-')
if name in BUILTIN_FUNCTIONS:
return True
# Vendor-specific functions (-foo-bar) are always okay
if name[0] == '-' and '-' in name[1:]:
return True
return False | python | def is_builtin_css_function(name):
name = name.replace('_', '-')
if name in BUILTIN_FUNCTIONS:
return True
# Vendor-specific functions (-foo-bar) are always okay
if name[0] == '-' and '-' in name[1:]:
return True
return False | [
"def",
"is_builtin_css_function",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"name",
"in",
"BUILTIN_FUNCTIONS",
":",
"return",
"True",
"# Vendor-specific functions (-foo-bar) are always okay",
"if",
"name",
"[",
... | Returns whether the given `name` looks like the name of a builtin CSS
function.
Unrecognized functions not in this list produce warnings. | [
"Returns",
"whether",
"the",
"given",
"name",
"looks",
"like",
"the",
"name",
"of",
"a",
"builtin",
"CSS",
"function",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L336-L351 |
24,555 | Kronuz/pyScss | scss/cssdefs.py | determine_encoding | def determine_encoding(buf):
"""Return the appropriate encoding for the given CSS source, according to
the CSS charset rules.
`buf` may be either a string or bytes.
"""
# The ultimate default is utf8; bravo, W3C
bom_encoding = 'UTF-8'
if not buf:
# What
return bom_encoding
if isinstance(buf, six.text_type):
# We got a file that, for whatever reason, produces already-decoded
# text. Check for the BOM (which is useless now) and believe
# whatever's in the @charset.
if buf[0] == '\ufeff':
buf = buf[0:]
# This is pretty similar to the code below, but without any encoding
# double-checking.
charset_start = '@charset "'
charset_end = '";'
if buf.startswith(charset_start):
start = len(charset_start)
end = buf.index(charset_end, start)
return buf[start:end]
else:
return bom_encoding
# BOMs
if buf[:3] == b'\xef\xbb\xbf':
bom_encoding = 'UTF-8'
buf = buf[3:]
if buf[:4] == b'\x00\x00\xfe\xff':
bom_encoding = 'UTF-32BE'
buf = buf[4:]
elif buf[:4] == b'\xff\xfe\x00\x00':
bom_encoding = 'UTF-32LE'
buf = buf[4:]
if buf[:4] == b'\x00\x00\xff\xfe':
raise UnicodeError("UTF-32-2143 is not supported")
elif buf[:4] == b'\xfe\xff\x00\x00':
raise UnicodeError("UTF-32-2143 is not supported")
elif buf[:2] == b'\xfe\xff':
bom_encoding = 'UTF-16BE'
buf = buf[2:]
elif buf[:2] == b'\xff\xfe':
bom_encoding = 'UTF-16LE'
buf = buf[2:]
# The spec requires exactly this syntax; no escapes or extra spaces or
# other shenanigans, thank goodness.
charset_start = '@charset "'.encode(bom_encoding)
charset_end = '";'.encode(bom_encoding)
if buf.startswith(charset_start):
start = len(charset_start)
end = buf.index(charset_end, start)
encoded_encoding = buf[start:end]
encoding = encoded_encoding.decode(bom_encoding)
# Ensure that decoding with the specified encoding actually produces
# the same @charset rule
encoded_charset = buf[:end + len(charset_end)]
if (encoded_charset.decode(encoding) !=
encoded_charset.decode(bom_encoding)):
raise UnicodeError(
"@charset {0} is incompatible with detected encoding {1}"
.format(bom_encoding, encoding))
else:
# With no @charset, believe the BOM
encoding = bom_encoding
return encoding | python | def determine_encoding(buf):
# The ultimate default is utf8; bravo, W3C
bom_encoding = 'UTF-8'
if not buf:
# What
return bom_encoding
if isinstance(buf, six.text_type):
# We got a file that, for whatever reason, produces already-decoded
# text. Check for the BOM (which is useless now) and believe
# whatever's in the @charset.
if buf[0] == '\ufeff':
buf = buf[0:]
# This is pretty similar to the code below, but without any encoding
# double-checking.
charset_start = '@charset "'
charset_end = '";'
if buf.startswith(charset_start):
start = len(charset_start)
end = buf.index(charset_end, start)
return buf[start:end]
else:
return bom_encoding
# BOMs
if buf[:3] == b'\xef\xbb\xbf':
bom_encoding = 'UTF-8'
buf = buf[3:]
if buf[:4] == b'\x00\x00\xfe\xff':
bom_encoding = 'UTF-32BE'
buf = buf[4:]
elif buf[:4] == b'\xff\xfe\x00\x00':
bom_encoding = 'UTF-32LE'
buf = buf[4:]
if buf[:4] == b'\x00\x00\xff\xfe':
raise UnicodeError("UTF-32-2143 is not supported")
elif buf[:4] == b'\xfe\xff\x00\x00':
raise UnicodeError("UTF-32-2143 is not supported")
elif buf[:2] == b'\xfe\xff':
bom_encoding = 'UTF-16BE'
buf = buf[2:]
elif buf[:2] == b'\xff\xfe':
bom_encoding = 'UTF-16LE'
buf = buf[2:]
# The spec requires exactly this syntax; no escapes or extra spaces or
# other shenanigans, thank goodness.
charset_start = '@charset "'.encode(bom_encoding)
charset_end = '";'.encode(bom_encoding)
if buf.startswith(charset_start):
start = len(charset_start)
end = buf.index(charset_end, start)
encoded_encoding = buf[start:end]
encoding = encoded_encoding.decode(bom_encoding)
# Ensure that decoding with the specified encoding actually produces
# the same @charset rule
encoded_charset = buf[:end + len(charset_end)]
if (encoded_charset.decode(encoding) !=
encoded_charset.decode(bom_encoding)):
raise UnicodeError(
"@charset {0} is incompatible with detected encoding {1}"
.format(bom_encoding, encoding))
else:
# With no @charset, believe the BOM
encoding = bom_encoding
return encoding | [
"def",
"determine_encoding",
"(",
"buf",
")",
":",
"# The ultimate default is utf8; bravo, W3C",
"bom_encoding",
"=",
"'UTF-8'",
"if",
"not",
"buf",
":",
"# What",
"return",
"bom_encoding",
"if",
"isinstance",
"(",
"buf",
",",
"six",
".",
"text_type",
")",
":",
... | Return the appropriate encoding for the given CSS source, according to
the CSS charset rules.
`buf` may be either a string or bytes. | [
"Return",
"the",
"appropriate",
"encoding",
"for",
"the",
"given",
"CSS",
"source",
"according",
"to",
"the",
"CSS",
"charset",
"rules",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L358-L432 |
24,556 | Kronuz/pyScss | scss/ast.py | Interpolation.maybe | def maybe(cls, parts, quotes=None, type=String, **kwargs):
"""Returns an interpolation if there are multiple parts, otherwise a
plain Literal. This keeps the AST somewhat simpler, but also is the
only way `Literal.from_bareword` gets called.
"""
if len(parts) > 1:
return cls(parts, quotes=quotes, type=type, **kwargs)
if quotes is None and type is String:
return Literal.from_bareword(parts[0])
return Literal(type(parts[0], quotes=quotes, **kwargs)) | python | def maybe(cls, parts, quotes=None, type=String, **kwargs):
if len(parts) > 1:
return cls(parts, quotes=quotes, type=type, **kwargs)
if quotes is None and type is String:
return Literal.from_bareword(parts[0])
return Literal(type(parts[0], quotes=quotes, **kwargs)) | [
"def",
"maybe",
"(",
"cls",
",",
"parts",
",",
"quotes",
"=",
"None",
",",
"type",
"=",
"String",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"return",
"cls",
"(",
"parts",
",",
"quotes",
"=",
"quotes",
","... | Returns an interpolation if there are multiple parts, otherwise a
plain Literal. This keeps the AST somewhat simpler, but also is the
only way `Literal.from_bareword` gets called. | [
"Returns",
"an",
"interpolation",
"if",
"there",
"are",
"multiple",
"parts",
"otherwise",
"a",
"plain",
"Literal",
".",
"This",
"keeps",
"the",
"AST",
"somewhat",
"simpler",
"but",
"also",
"is",
"the",
"only",
"way",
"Literal",
".",
"from_bareword",
"gets",
... | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/ast.py#L274-L285 |
24,557 | Kronuz/pyScss | scss/extension/compass/images.py | image_height | def image_height(image):
"""
Returns the height of the image found at the path supplied by `image`
relative to your project's images directory.
"""
image_size_cache = _get_cache('image_size_cache')
if not Image:
raise SassMissingDependency('PIL', 'image manipulation')
filepath = String.unquoted(image).value
path = None
try:
height = image_size_cache[filepath][1]
except KeyError:
height = 0
IMAGES_ROOT = _images_root()
if callable(IMAGES_ROOT):
try:
_file, _storage = list(IMAGES_ROOT(filepath))[0]
except IndexError:
pass
else:
path = _storage.open(_file)
else:
_path = os.path.join(IMAGES_ROOT, filepath.strip(os.sep))
if os.path.exists(_path):
path = open(_path, 'rb')
if path:
image = Image.open(path)
size = image.size
height = size[1]
image_size_cache[filepath] = size
return Number(height, 'px') | python | def image_height(image):
image_size_cache = _get_cache('image_size_cache')
if not Image:
raise SassMissingDependency('PIL', 'image manipulation')
filepath = String.unquoted(image).value
path = None
try:
height = image_size_cache[filepath][1]
except KeyError:
height = 0
IMAGES_ROOT = _images_root()
if callable(IMAGES_ROOT):
try:
_file, _storage = list(IMAGES_ROOT(filepath))[0]
except IndexError:
pass
else:
path = _storage.open(_file)
else:
_path = os.path.join(IMAGES_ROOT, filepath.strip(os.sep))
if os.path.exists(_path):
path = open(_path, 'rb')
if path:
image = Image.open(path)
size = image.size
height = size[1]
image_size_cache[filepath] = size
return Number(height, 'px') | [
"def",
"image_height",
"(",
"image",
")",
":",
"image_size_cache",
"=",
"_get_cache",
"(",
"'image_size_cache'",
")",
"if",
"not",
"Image",
":",
"raise",
"SassMissingDependency",
"(",
"'PIL'",
",",
"'image manipulation'",
")",
"filepath",
"=",
"String",
".",
"un... | Returns the height of the image found at the path supplied by `image`
relative to your project's images directory. | [
"Returns",
"the",
"height",
"of",
"the",
"image",
"found",
"at",
"the",
"path",
"supplied",
"by",
"image",
"relative",
"to",
"your",
"project",
"s",
"images",
"directory",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/images.py#L258-L289 |
24,558 | Kronuz/pyScss | scss/source.py | SourceFile.path | def path(self):
"""Concatenation of ``origin`` and ``relpath``, as a string. Used in
stack traces and other debugging places.
"""
if self.origin:
return six.text_type(self.origin / self.relpath)
else:
return six.text_type(self.relpath) | python | def path(self):
if self.origin:
return six.text_type(self.origin / self.relpath)
else:
return six.text_type(self.relpath) | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"self",
".",
"origin",
":",
"return",
"six",
".",
"text_type",
"(",
"self",
".",
"origin",
"/",
"self",
".",
"relpath",
")",
"else",
":",
"return",
"six",
".",
"text_type",
"(",
"self",
".",
"relpath",
")... | Concatenation of ``origin`` and ``relpath``, as a string. Used in
stack traces and other debugging places. | [
"Concatenation",
"of",
"origin",
"and",
"relpath",
"as",
"a",
"string",
".",
"Used",
"in",
"stack",
"traces",
"and",
"other",
"debugging",
"places",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L125-L132 |
24,559 | Kronuz/pyScss | scss/source.py | SourceFile.from_filename | def from_filename(cls, path_string, origin=MISSING, **kwargs):
""" Read Sass source from a String specifying the path
"""
path = Path(path_string)
return cls.from_path(path, origin, **kwargs) | python | def from_filename(cls, path_string, origin=MISSING, **kwargs):
path = Path(path_string)
return cls.from_path(path, origin, **kwargs) | [
"def",
"from_filename",
"(",
"cls",
",",
"path_string",
",",
"origin",
"=",
"MISSING",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"Path",
"(",
"path_string",
")",
"return",
"cls",
".",
"from_path",
"(",
"path",
",",
"origin",
",",
"*",
"*",
"kwa... | Read Sass source from a String specifying the path | [
"Read",
"Sass",
"source",
"from",
"a",
"String",
"specifying",
"the",
"path"
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L194-L198 |
24,560 | Kronuz/pyScss | scss/source.py | SourceFile.from_file | def from_file(cls, f, origin=MISSING, relpath=MISSING, **kwargs):
"""Read Sass source from a file or file-like object.
If `origin` or `relpath` are missing, they are derived from the file's
``.name`` attribute as with `from_path`. If it doesn't have one, the
origin becomes None and the relpath becomes the file's repr.
"""
contents = f.read()
encoding = determine_encoding(contents)
if isinstance(contents, six.binary_type):
contents = contents.decode(encoding)
if origin is MISSING or relpath is MISSING:
filename = getattr(f, 'name', None)
if filename is None:
origin = None
relpath = repr(f)
else:
origin, relpath = cls._key_from_path(Path(filename), origin)
return cls(origin, relpath, contents, encoding=encoding, **kwargs) | python | def from_file(cls, f, origin=MISSING, relpath=MISSING, **kwargs):
contents = f.read()
encoding = determine_encoding(contents)
if isinstance(contents, six.binary_type):
contents = contents.decode(encoding)
if origin is MISSING or relpath is MISSING:
filename = getattr(f, 'name', None)
if filename is None:
origin = None
relpath = repr(f)
else:
origin, relpath = cls._key_from_path(Path(filename), origin)
return cls(origin, relpath, contents, encoding=encoding, **kwargs) | [
"def",
"from_file",
"(",
"cls",
",",
"f",
",",
"origin",
"=",
"MISSING",
",",
"relpath",
"=",
"MISSING",
",",
"*",
"*",
"kwargs",
")",
":",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"encoding",
"=",
"determine_encoding",
"(",
"contents",
")",
"if"... | Read Sass source from a file or file-like object.
If `origin` or `relpath` are missing, they are derived from the file's
``.name`` attribute as with `from_path`. If it doesn't have one, the
origin becomes None and the relpath becomes the file's repr. | [
"Read",
"Sass",
"source",
"from",
"a",
"file",
"or",
"file",
"-",
"like",
"object",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L201-L221 |
24,561 | Kronuz/pyScss | scss/source.py | SourceFile.from_string | def from_string(cls, string, relpath=None, encoding=None, is_sass=None):
"""Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...".
"""
if isinstance(string, six.text_type):
# Already decoded; we don't know what encoding to use for output,
# though, so still check for a @charset.
# TODO what if the given encoding conflicts with the one in the
# file? do we care?
if encoding is None:
encoding = determine_encoding(string)
byte_contents = string.encode(encoding)
text_contents = string
elif isinstance(string, six.binary_type):
encoding = determine_encoding(string)
byte_contents = string
text_contents = string.decode(encoding)
else:
raise TypeError("Expected text or bytes, got {0!r}".format(string))
origin = None
if relpath is None:
m = hashlib.sha256()
m.update(byte_contents)
relpath = repr("string:{0}:{1}".format(
m.hexdigest()[:16], text_contents[:100]))
return cls(
origin, relpath, text_contents, encoding=encoding,
is_sass=is_sass,
) | python | def from_string(cls, string, relpath=None, encoding=None, is_sass=None):
if isinstance(string, six.text_type):
# Already decoded; we don't know what encoding to use for output,
# though, so still check for a @charset.
# TODO what if the given encoding conflicts with the one in the
# file? do we care?
if encoding is None:
encoding = determine_encoding(string)
byte_contents = string.encode(encoding)
text_contents = string
elif isinstance(string, six.binary_type):
encoding = determine_encoding(string)
byte_contents = string
text_contents = string.decode(encoding)
else:
raise TypeError("Expected text or bytes, got {0!r}".format(string))
origin = None
if relpath is None:
m = hashlib.sha256()
m.update(byte_contents)
relpath = repr("string:{0}:{1}".format(
m.hexdigest()[:16], text_contents[:100]))
return cls(
origin, relpath, text_contents, encoding=encoding,
is_sass=is_sass,
) | [
"def",
"from_string",
"(",
"cls",
",",
"string",
",",
"relpath",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"is_sass",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"# Already decoded; we don't know ... | Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...". | [
"Read",
"Sass",
"source",
"from",
"the",
"contents",
"of",
"a",
"string",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L224-L256 |
24,562 | bitcraft/pyscroll | pyscroll/quadtree.py | FastQuadTree.hit | def hit(self, rect):
"""Returns the items that overlap a bounding rectangle.
Returns the set of all items in the quad-tree that overlap with a
bounding rectangle.
@param rect:
The bounding rectangle being tested against the quad-tree. This
must possess left, top, right and bottom attributes.
"""
# Find the hits at the current level.
hits = {tuple(self.items[i]) for i in rect.collidelistall(self.items)}
# Recursively check the lower quadrants.
if self.nw and rect.left <= self.cx and rect.top <= self.cy:
hits |= self.nw.hit(rect)
if self.sw and rect.left <= self.cx and rect.bottom >= self.cy:
hits |= self.sw.hit(rect)
if self.ne and rect.right >= self.cx and rect.top <= self.cy:
hits |= self.ne.hit(rect)
if self.se and rect.right >= self.cx and rect.bottom >= self.cy:
hits |= self.se.hit(rect)
return hits | python | def hit(self, rect):
# Find the hits at the current level.
hits = {tuple(self.items[i]) for i in rect.collidelistall(self.items)}
# Recursively check the lower quadrants.
if self.nw and rect.left <= self.cx and rect.top <= self.cy:
hits |= self.nw.hit(rect)
if self.sw and rect.left <= self.cx and rect.bottom >= self.cy:
hits |= self.sw.hit(rect)
if self.ne and rect.right >= self.cx and rect.top <= self.cy:
hits |= self.ne.hit(rect)
if self.se and rect.right >= self.cx and rect.bottom >= self.cy:
hits |= self.se.hit(rect)
return hits | [
"def",
"hit",
"(",
"self",
",",
"rect",
")",
":",
"# Find the hits at the current level.",
"hits",
"=",
"{",
"tuple",
"(",
"self",
".",
"items",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"rect",
".",
"collidelistall",
"(",
"self",
".",
"items",
")",
"}",
... | Returns the items that overlap a bounding rectangle.
Returns the set of all items in the quad-tree that overlap with a
bounding rectangle.
@param rect:
The bounding rectangle being tested against the quad-tree. This
must possess left, top, right and bottom attributes. | [
"Returns",
"the",
"items",
"that",
"overlap",
"a",
"bounding",
"rectangle",
"."
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/quadtree.py#L105-L129 |
24,563 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.scroll | def scroll(self, vector):
""" scroll the background in pixels
:param vector: (int, int)
"""
self.center((vector[0] + self.view_rect.centerx,
vector[1] + self.view_rect.centery)) | python | def scroll(self, vector):
self.center((vector[0] + self.view_rect.centerx,
vector[1] + self.view_rect.centery)) | [
"def",
"scroll",
"(",
"self",
",",
"vector",
")",
":",
"self",
".",
"center",
"(",
"(",
"vector",
"[",
"0",
"]",
"+",
"self",
".",
"view_rect",
".",
"centerx",
",",
"vector",
"[",
"1",
"]",
"+",
"self",
".",
"view_rect",
".",
"centery",
")",
")"
... | scroll the background in pixels
:param vector: (int, int) | [
"scroll",
"the",
"background",
"in",
"pixels"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L87-L93 |
24,564 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.center | def center(self, coords):
""" center the map on a pixel
float numbers will be rounded.
:param coords: (number, number)
"""
x, y = round(coords[0]), round(coords[1])
self.view_rect.center = x, y
mw, mh = self.data.map_size
tw, th = self.data.tile_size
vw, vh = self._tile_view.size
# prevent camera from exposing edges of the map
if self.clamp_camera:
self._anchored_view = True
self.view_rect.clamp_ip(self.map_rect)
x, y = self.view_rect.center
# calc the new position in tiles and pixel offset
left, self._x_offset = divmod(x - self._half_width, tw)
top, self._y_offset = divmod(y - self._half_height, th)
right = left + vw
bottom = top + vh
if not self.clamp_camera:
# not anchored, so the rendered map is being offset by values larger
# than the tile size. this occurs when the edges of the map are inside
# the screen. a situation like is shows a background under the map.
self._anchored_view = True
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
if mw < vw or left < 0:
left = 0
self._x_offset = x - self._half_width
self._anchored_view = False
elif right > mw:
left = mw - vw
self._x_offset += dx * tw
self._anchored_view = False
if mh < vh or top < 0:
top = 0
self._y_offset = y - self._half_height
self._anchored_view = False
elif bottom > mh:
top = mh - vh
self._y_offset += dy * th
self._anchored_view = False
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue(self._buffer)
elif view_change > self._redraw_cutoff:
logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles(self._buffer) | python | def center(self, coords):
x, y = round(coords[0]), round(coords[1])
self.view_rect.center = x, y
mw, mh = self.data.map_size
tw, th = self.data.tile_size
vw, vh = self._tile_view.size
# prevent camera from exposing edges of the map
if self.clamp_camera:
self._anchored_view = True
self.view_rect.clamp_ip(self.map_rect)
x, y = self.view_rect.center
# calc the new position in tiles and pixel offset
left, self._x_offset = divmod(x - self._half_width, tw)
top, self._y_offset = divmod(y - self._half_height, th)
right = left + vw
bottom = top + vh
if not self.clamp_camera:
# not anchored, so the rendered map is being offset by values larger
# than the tile size. this occurs when the edges of the map are inside
# the screen. a situation like is shows a background under the map.
self._anchored_view = True
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
if mw < vw or left < 0:
left = 0
self._x_offset = x - self._half_width
self._anchored_view = False
elif right > mw:
left = mw - vw
self._x_offset += dx * tw
self._anchored_view = False
if mh < vh or top < 0:
top = 0
self._y_offset = y - self._half_height
self._anchored_view = False
elif bottom > mh:
top = mh - vh
self._y_offset += dy * th
self._anchored_view = False
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue(self._buffer)
elif view_change > self._redraw_cutoff:
logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles(self._buffer) | [
"def",
"center",
"(",
"self",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"round",
"(",
"coords",
"[",
"0",
"]",
")",
",",
"round",
"(",
"coords",
"[",
"1",
"]",
")",
"self",
".",
"view_rect",
".",
"center",
"=",
"x",
",",
"y",
"mw",
",",
... | center the map on a pixel
float numbers will be rounded.
:param coords: (number, number) | [
"center",
"the",
"map",
"on",
"a",
"pixel"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L95-L163 |
24,565 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.draw | def draw(self, surface, rect, surfaces=None):
""" Draw the map onto a surface
pass a rect that defines the draw area for:
drawing to an area smaller that the whole window/screen
surfaces may optionally be passed that will be blitted onto the surface.
this must be a sequence of tuples containing a layer number, image, and
rect in screen coordinates. surfaces will be drawn in order passed,
and will be correctly drawn with tiles from a higher layer overlapping
the surface.
surfaces list should be in the following format:
[ (layer, surface, rect), ... ]
or this:
[ (layer, surface, rect, blendmode_flags), ... ]
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
:return rect: area that was drawn over
"""
if self._zoom_level == 1.0:
self._render_map(surface, rect, surfaces)
else:
self._render_map(self._zoom_buffer, self._zoom_buffer.get_rect(), surfaces)
self.scaling_function(self._zoom_buffer, rect.size, surface)
return self._previous_blit.copy() | python | def draw(self, surface, rect, surfaces=None):
if self._zoom_level == 1.0:
self._render_map(surface, rect, surfaces)
else:
self._render_map(self._zoom_buffer, self._zoom_buffer.get_rect(), surfaces)
self.scaling_function(self._zoom_buffer, rect.size, surface)
return self._previous_blit.copy() | [
"def",
"draw",
"(",
"self",
",",
"surface",
",",
"rect",
",",
"surfaces",
"=",
"None",
")",
":",
"if",
"self",
".",
"_zoom_level",
"==",
"1.0",
":",
"self",
".",
"_render_map",
"(",
"surface",
",",
"rect",
",",
"surfaces",
")",
"else",
":",
"self",
... | Draw the map onto a surface
pass a rect that defines the draw area for:
drawing to an area smaller that the whole window/screen
surfaces may optionally be passed that will be blitted onto the surface.
this must be a sequence of tuples containing a layer number, image, and
rect in screen coordinates. surfaces will be drawn in order passed,
and will be correctly drawn with tiles from a higher layer overlapping
the surface.
surfaces list should be in the following format:
[ (layer, surface, rect), ... ]
or this:
[ (layer, surface, rect, blendmode_flags), ... ]
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
:return rect: area that was drawn over | [
"Draw",
"the",
"map",
"onto",
"a",
"surface"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L165-L193 |
24,566 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.set_size | def set_size(self, size):
""" Set the size of the map in pixels
This is an expensive operation, do only when absolutely needed.
:param size: (width, height) pixel size of camera/view of the group
"""
buffer_size = self._calculate_zoom_buffer_size(size, self._zoom_level)
self._size = size
self._initialize_buffers(buffer_size) | python | def set_size(self, size):
buffer_size = self._calculate_zoom_buffer_size(size, self._zoom_level)
self._size = size
self._initialize_buffers(buffer_size) | [
"def",
"set_size",
"(",
"self",
",",
"size",
")",
":",
"buffer_size",
"=",
"self",
".",
"_calculate_zoom_buffer_size",
"(",
"size",
",",
"self",
".",
"_zoom_level",
")",
"self",
".",
"_size",
"=",
"size",
"self",
".",
"_initialize_buffers",
"(",
"buffer_size... | Set the size of the map in pixels
This is an expensive operation, do only when absolutely needed.
:param size: (width, height) pixel size of camera/view of the group | [
"Set",
"the",
"size",
"of",
"the",
"map",
"in",
"pixels"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L219-L228 |
24,567 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.translate_point | def translate_point(self, point):
""" Translate world coordinates and return screen coordinates. Respects zoom level
Will be returned as tuple.
:rtype: tuple
"""
mx, my = self.get_center_offset()
if self._zoom_level == 1.0:
return point[0] + mx, point[1] + my
else:
return int(round((point[0] + mx)) * self._real_ratio_x), int(round((point[1] + my) * self._real_ratio_y)) | python | def translate_point(self, point):
mx, my = self.get_center_offset()
if self._zoom_level == 1.0:
return point[0] + mx, point[1] + my
else:
return int(round((point[0] + mx)) * self._real_ratio_x), int(round((point[1] + my) * self._real_ratio_y)) | [
"def",
"translate_point",
"(",
"self",
",",
"point",
")",
":",
"mx",
",",
"my",
"=",
"self",
".",
"get_center_offset",
"(",
")",
"if",
"self",
".",
"_zoom_level",
"==",
"1.0",
":",
"return",
"point",
"[",
"0",
"]",
"+",
"mx",
",",
"point",
"[",
"1"... | Translate world coordinates and return screen coordinates. Respects zoom level
Will be returned as tuple.
:rtype: tuple | [
"Translate",
"world",
"coordinates",
"and",
"return",
"screen",
"coordinates",
".",
"Respects",
"zoom",
"level"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L246-L257 |
24,568 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.translate_points | def translate_points(self, points):
""" Translate coordinates and return screen coordinates
Will be returned in order passed as tuples.
:return: list
"""
retval = list()
append = retval.append
sx, sy = self.get_center_offset()
if self._zoom_level == 1.0:
for c in points:
append((c[0] + sx, c[1] + sy))
else:
rx = self._real_ratio_x
ry = self._real_ratio_y
for c in points:
append((int(round((c[0] + sx) * rx)), int(round((c[1] + sy) * ry))))
return retval | python | def translate_points(self, points):
retval = list()
append = retval.append
sx, sy = self.get_center_offset()
if self._zoom_level == 1.0:
for c in points:
append((c[0] + sx, c[1] + sy))
else:
rx = self._real_ratio_x
ry = self._real_ratio_y
for c in points:
append((int(round((c[0] + sx) * rx)), int(round((c[1] + sy) * ry))))
return retval | [
"def",
"translate_points",
"(",
"self",
",",
"points",
")",
":",
"retval",
"=",
"list",
"(",
")",
"append",
"=",
"retval",
".",
"append",
"sx",
",",
"sy",
"=",
"self",
".",
"get_center_offset",
"(",
")",
"if",
"self",
".",
"_zoom_level",
"==",
"1.0",
... | Translate coordinates and return screen coordinates
Will be returned in order passed as tuples.
:return: list | [
"Translate",
"coordinates",
"and",
"return",
"screen",
"coordinates"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L273-L291 |
24,569 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._render_map | def _render_map(self, surface, rect, surfaces):
""" Render the map and optional surfaces to destination surface
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
"""
self._tile_queue = self.data.process_animation_queue(self._tile_view)
self._tile_queue and self._flush_tile_queue(self._buffer)
# TODO: could maybe optimize to remove just the edges, ideally by drawing lines
# if not self.anchored_view:
# surface.fill(self._clear_color, self._previous_blit)
if not self._anchored_view:
self._clear_surface(surface, self._previous_blit)
offset = -self._x_offset + rect.left, -self._y_offset + rect.top
with surface_clipping_context(surface, rect):
self._previous_blit = surface.blit(self._buffer, offset)
if surfaces:
surfaces_offset = -offset[0], -offset[1]
self._draw_surfaces(surface, surfaces_offset, surfaces) | python | def _render_map(self, surface, rect, surfaces):
self._tile_queue = self.data.process_animation_queue(self._tile_view)
self._tile_queue and self._flush_tile_queue(self._buffer)
# TODO: could maybe optimize to remove just the edges, ideally by drawing lines
# if not self.anchored_view:
# surface.fill(self._clear_color, self._previous_blit)
if not self._anchored_view:
self._clear_surface(surface, self._previous_blit)
offset = -self._x_offset + rect.left, -self._y_offset + rect.top
with surface_clipping_context(surface, rect):
self._previous_blit = surface.blit(self._buffer, offset)
if surfaces:
surfaces_offset = -offset[0], -offset[1]
self._draw_surfaces(surface, surfaces_offset, surfaces) | [
"def",
"_render_map",
"(",
"self",
",",
"surface",
",",
"rect",
",",
"surfaces",
")",
":",
"self",
".",
"_tile_queue",
"=",
"self",
".",
"data",
".",
"process_animation_queue",
"(",
"self",
".",
"_tile_view",
")",
"self",
".",
"_tile_queue",
"and",
"self",... | Render the map and optional surfaces to destination surface
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles | [
"Render",
"the",
"map",
"and",
"optional",
"surfaces",
"to",
"destination",
"surface"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L315-L337 |
24,570 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._clear_surface | def _clear_surface(self, surface, rect=None):
""" Clear the buffer, taking in account colorkey or alpha
:return:
"""
clear_color = self._rgb_clear_color if self._clear_color is None else self._clear_color
surface.fill(clear_color, rect) | python | def _clear_surface(self, surface, rect=None):
clear_color = self._rgb_clear_color if self._clear_color is None else self._clear_color
surface.fill(clear_color, rect) | [
"def",
"_clear_surface",
"(",
"self",
",",
"surface",
",",
"rect",
"=",
"None",
")",
":",
"clear_color",
"=",
"self",
".",
"_rgb_clear_color",
"if",
"self",
".",
"_clear_color",
"is",
"None",
"else",
"self",
".",
"_clear_color",
"surface",
".",
"fill",
"("... | Clear the buffer, taking in account colorkey or alpha
:return: | [
"Clear",
"the",
"buffer",
"taking",
"in",
"account",
"colorkey",
"or",
"alpha"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L339-L345 |
24,571 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._draw_surfaces | def _draw_surfaces(self, surface, offset, surfaces):
""" Draw surfaces onto buffer, then redraw tiles that cover them
:param surface: destination
:param offset: offset to compensate for buffer alignment
:param surfaces: sequence of surfaces to blit
"""
surface_blit = surface.blit
ox, oy = offset
left, top = self._tile_view.topleft
hit = self._layer_quadtree.hit
get_tile = self.data.get_tile_image
tile_layers = tuple(self.data.visible_tile_layers)
dirty = list()
dirty_append = dirty.append
# TODO: check to avoid sorting overhead
# sort layers, then the y value
def sprite_sort(i):
return i[2], i[1][1] + i[0].get_height()
surfaces.sort(key=sprite_sort)
layer_getter = itemgetter(2)
for layer, group in groupby(surfaces, layer_getter):
del dirty[:]
for i in group:
try:
flags = i[3]
except IndexError:
dirty_append(surface_blit(i[0], i[1]))
else:
dirty_append(surface_blit(i[0], i[1], None, flags))
# TODO: make set of covered tiles, in the case where a cluster
# of sprite surfaces causes excessive over tile overdrawing
for dirty_rect in dirty:
for r in hit(dirty_rect.move(ox, oy)):
x, y, tw, th = r
for l in [i for i in tile_layers if gt(i, layer)]:
if self.tall_sprites and l == layer + 1:
if y - oy + th <= dirty_rect.bottom - self.tall_sprites:
continue
tile = get_tile(x // tw + left, y // th + top, l)
tile and surface_blit(tile, (x - ox, y - oy)) | python | def _draw_surfaces(self, surface, offset, surfaces):
surface_blit = surface.blit
ox, oy = offset
left, top = self._tile_view.topleft
hit = self._layer_quadtree.hit
get_tile = self.data.get_tile_image
tile_layers = tuple(self.data.visible_tile_layers)
dirty = list()
dirty_append = dirty.append
# TODO: check to avoid sorting overhead
# sort layers, then the y value
def sprite_sort(i):
return i[2], i[1][1] + i[0].get_height()
surfaces.sort(key=sprite_sort)
layer_getter = itemgetter(2)
for layer, group in groupby(surfaces, layer_getter):
del dirty[:]
for i in group:
try:
flags = i[3]
except IndexError:
dirty_append(surface_blit(i[0], i[1]))
else:
dirty_append(surface_blit(i[0], i[1], None, flags))
# TODO: make set of covered tiles, in the case where a cluster
# of sprite surfaces causes excessive over tile overdrawing
for dirty_rect in dirty:
for r in hit(dirty_rect.move(ox, oy)):
x, y, tw, th = r
for l in [i for i in tile_layers if gt(i, layer)]:
if self.tall_sprites and l == layer + 1:
if y - oy + th <= dirty_rect.bottom - self.tall_sprites:
continue
tile = get_tile(x // tw + left, y // th + top, l)
tile and surface_blit(tile, (x - ox, y - oy)) | [
"def",
"_draw_surfaces",
"(",
"self",
",",
"surface",
",",
"offset",
",",
"surfaces",
")",
":",
"surface_blit",
"=",
"surface",
".",
"blit",
"ox",
",",
"oy",
"=",
"offset",
"left",
",",
"top",
"=",
"self",
".",
"_tile_view",
".",
"topleft",
"hit",
"=",... | Draw surfaces onto buffer, then redraw tiles that cover them
:param surface: destination
:param offset: offset to compensate for buffer alignment
:param surfaces: sequence of surfaces to blit | [
"Draw",
"surfaces",
"onto",
"buffer",
"then",
"redraw",
"tiles",
"that",
"cover",
"them"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L347-L394 |
24,572 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._queue_edge_tiles | def _queue_edge_tiles(self, dx, dy):
""" Queue edge tiles and clear edge areas on buffer if needed
:param dx: Edge along X axis to enqueue
:param dy: Edge along Y axis to enqueue
:return: None
"""
v = self._tile_view
tw, th = self.data.tile_size
self._tile_queue = iter([])
def append(rect):
self._tile_queue = chain(self._tile_queue, self.data.get_tile_images_by_rect(rect))
# TODO: optimize so fill is only used when map is smaller than buffer
self._clear_surface(self._buffer, ((rect[0] - v.left) * tw, (rect[1] - v.top) * th,
rect[2] * tw, rect[3] * th))
if dx > 0: # right side
append((v.right - 1, v.top, dx, v.height))
elif dx < 0: # left side
append((v.left, v.top, -dx, v.height))
if dy > 0: # bottom side
append((v.left, v.bottom - 1, v.width, dy))
elif dy < 0: # top side
append((v.left, v.top, v.width, -dy)) | python | def _queue_edge_tiles(self, dx, dy):
v = self._tile_view
tw, th = self.data.tile_size
self._tile_queue = iter([])
def append(rect):
self._tile_queue = chain(self._tile_queue, self.data.get_tile_images_by_rect(rect))
# TODO: optimize so fill is only used when map is smaller than buffer
self._clear_surface(self._buffer, ((rect[0] - v.left) * tw, (rect[1] - v.top) * th,
rect[2] * tw, rect[3] * th))
if dx > 0: # right side
append((v.right - 1, v.top, dx, v.height))
elif dx < 0: # left side
append((v.left, v.top, -dx, v.height))
if dy > 0: # bottom side
append((v.left, v.bottom - 1, v.width, dy))
elif dy < 0: # top side
append((v.left, v.top, v.width, -dy)) | [
"def",
"_queue_edge_tiles",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"v",
"=",
"self",
".",
"_tile_view",
"tw",
",",
"th",
"=",
"self",
".",
"data",
".",
"tile_size",
"self",
".",
"_tile_queue",
"=",
"iter",
"(",
"[",
"]",
")",
"def",
"append",... | Queue edge tiles and clear edge areas on buffer if needed
:param dx: Edge along X axis to enqueue
:param dy: Edge along Y axis to enqueue
:return: None | [
"Queue",
"edge",
"tiles",
"and",
"clear",
"edge",
"areas",
"on",
"buffer",
"if",
"needed"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L396-L423 |
24,573 | bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._create_buffers | def _create_buffers(self, view_size, buffer_size):
""" Create the buffers, taking in account pixel alpha or colorkey
:param view_size: pixel size of the view
:param buffer_size: pixel size of the buffer
"""
requires_zoom_buffer = not view_size == buffer_size
self._zoom_buffer = None
if self._clear_color is None:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size)
self._buffer = Surface(buffer_size)
elif self._clear_color == self._rgba_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.SRCALPHA)
self._buffer = Surface(buffer_size, flags=pygame.SRCALPHA)
self.data.convert_surfaces(self._buffer, True)
elif self._clear_color is not self._rgb_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.RLEACCEL)
self._zoom_buffer.set_colorkey(self._clear_color)
self._buffer = Surface(buffer_size, flags=pygame.RLEACCEL)
self._buffer.set_colorkey(self._clear_color)
self._buffer.fill(self._clear_color) | python | def _create_buffers(self, view_size, buffer_size):
requires_zoom_buffer = not view_size == buffer_size
self._zoom_buffer = None
if self._clear_color is None:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size)
self._buffer = Surface(buffer_size)
elif self._clear_color == self._rgba_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.SRCALPHA)
self._buffer = Surface(buffer_size, flags=pygame.SRCALPHA)
self.data.convert_surfaces(self._buffer, True)
elif self._clear_color is not self._rgb_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.RLEACCEL)
self._zoom_buffer.set_colorkey(self._clear_color)
self._buffer = Surface(buffer_size, flags=pygame.RLEACCEL)
self._buffer.set_colorkey(self._clear_color)
self._buffer.fill(self._clear_color) | [
"def",
"_create_buffers",
"(",
"self",
",",
"view_size",
",",
"buffer_size",
")",
":",
"requires_zoom_buffer",
"=",
"not",
"view_size",
"==",
"buffer_size",
"self",
".",
"_zoom_buffer",
"=",
"None",
"if",
"self",
".",
"_clear_color",
"is",
"None",
":",
"if",
... | Create the buffers, taking in account pixel alpha or colorkey
:param view_size: pixel size of the view
:param buffer_size: pixel size of the buffer | [
"Create",
"the",
"buffers",
"taking",
"in",
"account",
"pixel",
"alpha",
"or",
"colorkey"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L433-L457 |
24,574 | bitcraft/pyscroll | pyscroll/data.py | PyscrollDataAdapter.reload_animations | def reload_animations(self):
""" Reload animation information
PyscrollDataAdapter.get_animations must be implemented
"""
self._update_time()
self._animation_queue = list()
self._tracked_gids = set()
self._animation_map = dict()
for gid, frame_data in self.get_animations():
self._tracked_gids.add(gid)
frames = list()
for frame_gid, frame_duration in frame_data:
image = self._get_tile_image_by_id(frame_gid)
frames.append(AnimationFrame(image, frame_duration))
# the following line is slow when loading maps, but avoids overhead when rendering
# positions = set(self.tmx.get_tile_locations_by_gid(gid))
# ideally, positions would be populated with all the known
# locations of an animation, but searching for their locations
# is slow. so it will be updated as the map is drawn.
positions = set()
ani = AnimationToken(positions, frames, self._last_time)
self._animation_map[gid] = ani
heappush(self._animation_queue, ani) | python | def reload_animations(self):
self._update_time()
self._animation_queue = list()
self._tracked_gids = set()
self._animation_map = dict()
for gid, frame_data in self.get_animations():
self._tracked_gids.add(gid)
frames = list()
for frame_gid, frame_duration in frame_data:
image = self._get_tile_image_by_id(frame_gid)
frames.append(AnimationFrame(image, frame_duration))
# the following line is slow when loading maps, but avoids overhead when rendering
# positions = set(self.tmx.get_tile_locations_by_gid(gid))
# ideally, positions would be populated with all the known
# locations of an animation, but searching for their locations
# is slow. so it will be updated as the map is drawn.
positions = set()
ani = AnimationToken(positions, frames, self._last_time)
self._animation_map[gid] = ani
heappush(self._animation_queue, ani) | [
"def",
"reload_animations",
"(",
"self",
")",
":",
"self",
".",
"_update_time",
"(",
")",
"self",
".",
"_animation_queue",
"=",
"list",
"(",
")",
"self",
".",
"_tracked_gids",
"=",
"set",
"(",
")",
"self",
".",
"_animation_map",
"=",
"dict",
"(",
")",
... | Reload animation information
PyscrollDataAdapter.get_animations must be implemented | [
"Reload",
"animation",
"information"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L132-L161 |
24,575 | bitcraft/pyscroll | pyscroll/data.py | PyscrollDataAdapter.get_tile_image | def get_tile_image(self, x, y, l):
""" Get a tile image, respecting current animations
:param x: x coordinate
:param y: y coordinate
:param l: layer
:type x: int
:type y: int
:type l: int
:rtype: pygame.Surface
"""
# disabled for now, re-enable when support for generic maps is restored
# # since the tile has been queried, assume it wants to be checked
# # for animations sometime in the future
# if self._animation_queue:
# self._tracked_tiles.add((x, y, l))
try:
# animated, so return the correct frame
return self._animated_tile[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
return self._get_tile_image(x, y, l) | python | def get_tile_image(self, x, y, l):
# disabled for now, re-enable when support for generic maps is restored
# # since the tile has been queried, assume it wants to be checked
# # for animations sometime in the future
# if self._animation_queue:
# self._tracked_tiles.add((x, y, l))
try:
# animated, so return the correct frame
return self._animated_tile[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
return self._get_tile_image(x, y, l) | [
"def",
"get_tile_image",
"(",
"self",
",",
"x",
",",
"y",
",",
"l",
")",
":",
"# disabled for now, re-enable when support for generic maps is restored",
"# # since the tile has been queried, assume it wants to be checked",
"# # for animations sometime in the future",
"# if self._animat... | Get a tile image, respecting current animations
:param x: x coordinate
:param y: y coordinate
:param l: layer
:type x: int
:type y: int
:type l: int
:rtype: pygame.Surface | [
"Get",
"a",
"tile",
"image",
"respecting",
"current",
"animations"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L163-L189 |
24,576 | bitcraft/pyscroll | pyscroll/data.py | PyscrollDataAdapter.get_tile_images_by_rect | def get_tile_images_by_rect(self, rect):
""" Given a 2d area, return generator of tile images inside
Given the coordinates, yield the following tuple for each tile:
X, Y, Layer Number, pygame Surface
This method also defines render order by re arranging the
positions of each tile as it is yielded to the renderer.
There is an optimization that you can make for your data:
If you can provide access to tile information in a batch,
then pyscroll can access data faster and render quicker.
To implement this optimization, override this method.
Not like python 'Range': should include the end index!
:param rect: a rect-like object that defines tiles to draw
:return: generator
"""
x1, y1, x2, y2 = rect_to_bb(rect)
for layer in self.visible_tile_layers:
for y, x in product(range(y1, y2 + 1),
range(x1, x2 + 1)):
tile = self.get_tile_image(x, y, layer)
if tile:
yield x, y, layer, tile | python | def get_tile_images_by_rect(self, rect):
x1, y1, x2, y2 = rect_to_bb(rect)
for layer in self.visible_tile_layers:
for y, x in product(range(y1, y2 + 1),
range(x1, x2 + 1)):
tile = self.get_tile_image(x, y, layer)
if tile:
yield x, y, layer, tile | [
"def",
"get_tile_images_by_rect",
"(",
"self",
",",
"rect",
")",
":",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"=",
"rect_to_bb",
"(",
"rect",
")",
"for",
"layer",
"in",
"self",
".",
"visible_tile_layers",
":",
"for",
"y",
",",
"x",
"in",
"product",
"(... | Given a 2d area, return generator of tile images inside
Given the coordinates, yield the following tuple for each tile:
X, Y, Layer Number, pygame Surface
This method also defines render order by re arranging the
positions of each tile as it is yielded to the renderer.
There is an optimization that you can make for your data:
If you can provide access to tile information in a batch,
then pyscroll can access data faster and render quicker.
To implement this optimization, override this method.
Not like python 'Range': should include the end index!
:param rect: a rect-like object that defines tiles to draw
:return: generator | [
"Given",
"a",
"2d",
"area",
"return",
"generator",
"of",
"tile",
"images",
"inside"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L251-L277 |
24,577 | bitcraft/pyscroll | pyscroll/data.py | TiledMapData.convert_surfaces | def convert_surfaces(self, parent, alpha=False):
""" Convert all images in the data to match the parent
:param parent: pygame.Surface
:param alpha: preserve alpha channel or not
:return: None
"""
images = list()
for i in self.tmx.images:
try:
if alpha:
images.append(i.convert_alpha(parent))
else:
images.append(i.convert(parent))
except AttributeError:
images.append(None)
self.tmx.images = images | python | def convert_surfaces(self, parent, alpha=False):
images = list()
for i in self.tmx.images:
try:
if alpha:
images.append(i.convert_alpha(parent))
else:
images.append(i.convert(parent))
except AttributeError:
images.append(None)
self.tmx.images = images | [
"def",
"convert_surfaces",
"(",
"self",
",",
"parent",
",",
"alpha",
"=",
"False",
")",
":",
"images",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"self",
".",
"tmx",
".",
"images",
":",
"try",
":",
"if",
"alpha",
":",
"images",
".",
"append",
"(",
... | Convert all images in the data to match the parent
:param parent: pygame.Surface
:param alpha: preserve alpha channel or not
:return: None | [
"Convert",
"all",
"images",
"in",
"the",
"data",
"to",
"match",
"the",
"parent"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L301-L317 |
24,578 | bitcraft/pyscroll | pyscroll/data.py | TiledMapData.visible_object_layers | def visible_object_layers(self):
""" This must return layer objects
This is not required for custom data formats.
:return: Sequence of pytmx object layers/groups
"""
return (layer for layer in self.tmx.visible_layers
if isinstance(layer, pytmx.TiledObjectGroup)) | python | def visible_object_layers(self):
return (layer for layer in self.tmx.visible_layers
if isinstance(layer, pytmx.TiledObjectGroup)) | [
"def",
"visible_object_layers",
"(",
"self",
")",
":",
"return",
"(",
"layer",
"for",
"layer",
"in",
"self",
".",
"tmx",
".",
"visible_layers",
"if",
"isinstance",
"(",
"layer",
",",
"pytmx",
".",
"TiledObjectGroup",
")",
")"
] | This must return layer objects
This is not required for custom data formats.
:return: Sequence of pytmx object layers/groups | [
"This",
"must",
"return",
"layer",
"objects"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L344-L352 |
24,579 | bitcraft/pyscroll | pyscroll/data.py | TiledMapData.get_tile_images_by_rect | def get_tile_images_by_rect(self, rect):
""" Speed up data access
More efficient because data is accessed and cached locally
"""
def rev(seq, start, stop):
if start < 0:
start = 0
return enumerate(seq[start:stop + 1], start)
x1, y1, x2, y2 = rect_to_bb(rect)
images = self.tmx.images
layers = self.tmx.layers
at = self._animated_tile
tracked_gids = self._tracked_gids
anim_map = self._animation_map
track = bool(self._animation_queue)
for l in self.tmx.visible_tile_layers:
for y, row in rev(layers[l].data, y1, y2):
for x, gid in [i for i in rev(row, x1, x2) if i[1]]:
# since the tile has been queried, assume it wants to be checked
# for animations sometime in the future
if track and gid in tracked_gids:
anim_map[gid].positions.add((x, y, l))
try:
# animated, so return the correct frame
yield x, y, l, at[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
yield x, y, l, images[gid] | python | def get_tile_images_by_rect(self, rect):
def rev(seq, start, stop):
if start < 0:
start = 0
return enumerate(seq[start:stop + 1], start)
x1, y1, x2, y2 = rect_to_bb(rect)
images = self.tmx.images
layers = self.tmx.layers
at = self._animated_tile
tracked_gids = self._tracked_gids
anim_map = self._animation_map
track = bool(self._animation_queue)
for l in self.tmx.visible_tile_layers:
for y, row in rev(layers[l].data, y1, y2):
for x, gid in [i for i in rev(row, x1, x2) if i[1]]:
# since the tile has been queried, assume it wants to be checked
# for animations sometime in the future
if track and gid in tracked_gids:
anim_map[gid].positions.add((x, y, l))
try:
# animated, so return the correct frame
yield x, y, l, at[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
yield x, y, l, images[gid] | [
"def",
"get_tile_images_by_rect",
"(",
"self",
",",
"rect",
")",
":",
"def",
"rev",
"(",
"seq",
",",
"start",
",",
"stop",
")",
":",
"if",
"start",
"<",
"0",
":",
"start",
"=",
"0",
"return",
"enumerate",
"(",
"seq",
"[",
"start",
":",
"stop",
"+",... | Speed up data access
More efficient because data is accessed and cached locally | [
"Speed",
"up",
"data",
"access"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L370-L404 |
24,580 | bitcraft/pyscroll | tutorial/quest.py | Hero.move_back | def move_back(self, dt):
""" If called after an update, the sprite can move back
"""
self._position = self._old_position
self.rect.topleft = self._position
self.feet.midbottom = self.rect.midbottom | python | def move_back(self, dt):
self._position = self._old_position
self.rect.topleft = self._position
self.feet.midbottom = self.rect.midbottom | [
"def",
"move_back",
"(",
"self",
",",
"dt",
")",
":",
"self",
".",
"_position",
"=",
"self",
".",
"_old_position",
"self",
".",
"rect",
".",
"topleft",
"=",
"self",
".",
"_position",
"self",
".",
"feet",
".",
"midbottom",
"=",
"self",
".",
"rect",
".... | If called after an update, the sprite can move back | [
"If",
"called",
"after",
"an",
"update",
"the",
"sprite",
"can",
"move",
"back"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L86-L91 |
24,581 | bitcraft/pyscroll | tutorial/quest.py | QuestGame.handle_input | def handle_input(self):
""" Handle pygame input events
"""
poll = pygame.event.poll
event = poll()
while event:
if event.type == QUIT:
self.running = False
break
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.running = False
break
elif event.key == K_EQUALS:
self.map_layer.zoom += .25
elif event.key == K_MINUS:
value = self.map_layer.zoom - .25
if value > 0:
self.map_layer.zoom = value
# this will be handled if the window is resized
elif event.type == VIDEORESIZE:
init_screen(event.w, event.h)
self.map_layer.set_size((event.w, event.h))
event = poll()
# using get_pressed is slightly less accurate than testing for events
# but is much easier to use.
pressed = pygame.key.get_pressed()
if pressed[K_UP]:
self.hero.velocity[1] = -HERO_MOVE_SPEED
elif pressed[K_DOWN]:
self.hero.velocity[1] = HERO_MOVE_SPEED
else:
self.hero.velocity[1] = 0
if pressed[K_LEFT]:
self.hero.velocity[0] = -HERO_MOVE_SPEED
elif pressed[K_RIGHT]:
self.hero.velocity[0] = HERO_MOVE_SPEED
else:
self.hero.velocity[0] = 0 | python | def handle_input(self):
poll = pygame.event.poll
event = poll()
while event:
if event.type == QUIT:
self.running = False
break
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.running = False
break
elif event.key == K_EQUALS:
self.map_layer.zoom += .25
elif event.key == K_MINUS:
value = self.map_layer.zoom - .25
if value > 0:
self.map_layer.zoom = value
# this will be handled if the window is resized
elif event.type == VIDEORESIZE:
init_screen(event.w, event.h)
self.map_layer.set_size((event.w, event.h))
event = poll()
# using get_pressed is slightly less accurate than testing for events
# but is much easier to use.
pressed = pygame.key.get_pressed()
if pressed[K_UP]:
self.hero.velocity[1] = -HERO_MOVE_SPEED
elif pressed[K_DOWN]:
self.hero.velocity[1] = HERO_MOVE_SPEED
else:
self.hero.velocity[1] = 0
if pressed[K_LEFT]:
self.hero.velocity[0] = -HERO_MOVE_SPEED
elif pressed[K_RIGHT]:
self.hero.velocity[0] = HERO_MOVE_SPEED
else:
self.hero.velocity[0] = 0 | [
"def",
"handle_input",
"(",
"self",
")",
":",
"poll",
"=",
"pygame",
".",
"event",
".",
"poll",
"event",
"=",
"poll",
"(",
")",
"while",
"event",
":",
"if",
"event",
".",
"type",
"==",
"QUIT",
":",
"self",
".",
"running",
"=",
"False",
"break",
"el... | Handle pygame input events | [
"Handle",
"pygame",
"input",
"events"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L149-L195 |
24,582 | bitcraft/pyscroll | tutorial/quest.py | QuestGame.update | def update(self, dt):
""" Tasks that occur over time should be handled here
"""
self.group.update(dt)
# check if the sprite's feet are colliding with wall
# sprite must have a rect called feet, and move_back method,
# otherwise this will fail
for sprite in self.group.sprites():
if sprite.feet.collidelist(self.walls) > -1:
sprite.move_back(dt) | python | def update(self, dt):
self.group.update(dt)
# check if the sprite's feet are colliding with wall
# sprite must have a rect called feet, and move_back method,
# otherwise this will fail
for sprite in self.group.sprites():
if sprite.feet.collidelist(self.walls) > -1:
sprite.move_back(dt) | [
"def",
"update",
"(",
"self",
",",
"dt",
")",
":",
"self",
".",
"group",
".",
"update",
"(",
"dt",
")",
"# check if the sprite's feet are colliding with wall",
"# sprite must have a rect called feet, and move_back method,",
"# otherwise this will fail",
"for",
"sprite",
"in... | Tasks that occur over time should be handled here | [
"Tasks",
"that",
"occur",
"over",
"time",
"should",
"be",
"handled",
"here"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L197-L207 |
24,583 | bitcraft/pyscroll | tutorial/quest.py | QuestGame.run | def run(self):
""" Run the game loop
"""
clock = pygame.time.Clock()
self.running = True
from collections import deque
times = deque(maxlen=30)
try:
while self.running:
dt = clock.tick() / 1000.
times.append(clock.get_fps())
# print(sum(times)/len(times))
self.handle_input()
self.update(dt)
self.draw(screen)
pygame.display.flip()
except KeyboardInterrupt:
self.running = False | python | def run(self):
clock = pygame.time.Clock()
self.running = True
from collections import deque
times = deque(maxlen=30)
try:
while self.running:
dt = clock.tick() / 1000.
times.append(clock.get_fps())
# print(sum(times)/len(times))
self.handle_input()
self.update(dt)
self.draw(screen)
pygame.display.flip()
except KeyboardInterrupt:
self.running = False | [
"def",
"run",
"(",
"self",
")",
":",
"clock",
"=",
"pygame",
".",
"time",
".",
"Clock",
"(",
")",
"self",
".",
"running",
"=",
"True",
"from",
"collections",
"import",
"deque",
"times",
"=",
"deque",
"(",
"maxlen",
"=",
"30",
")",
"try",
":",
"whil... | Run the game loop | [
"Run",
"the",
"game",
"loop"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L209-L230 |
24,584 | bitcraft/pyscroll | pyscroll/group.py | PyscrollGroup.draw | def draw(self, surface):
""" Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface
"""
ox, oy = self._map_layer.get_center_offset()
new_surfaces = list()
spritedict = self.spritedict
gl = self.get_layer_of_sprite
new_surfaces_append = new_surfaces.append
for spr in self.sprites():
new_rect = spr.rect.move(ox, oy)
try:
new_surfaces_append((spr.image, new_rect, gl(spr), spr.blendmode))
except AttributeError: # generally should only fail when no blendmode available
new_surfaces_append((spr.image, new_rect, gl(spr)))
spritedict[spr] = new_rect
self.lostsprites = []
return self._map_layer.draw(surface, surface.get_rect(), new_surfaces) | python | def draw(self, surface):
ox, oy = self._map_layer.get_center_offset()
new_surfaces = list()
spritedict = self.spritedict
gl = self.get_layer_of_sprite
new_surfaces_append = new_surfaces.append
for spr in self.sprites():
new_rect = spr.rect.move(ox, oy)
try:
new_surfaces_append((spr.image, new_rect, gl(spr), spr.blendmode))
except AttributeError: # generally should only fail when no blendmode available
new_surfaces_append((spr.image, new_rect, gl(spr)))
spritedict[spr] = new_rect
self.lostsprites = []
return self._map_layer.draw(surface, surface.get_rect(), new_surfaces) | [
"def",
"draw",
"(",
"self",
",",
"surface",
")",
":",
"ox",
",",
"oy",
"=",
"self",
".",
"_map_layer",
".",
"get_center_offset",
"(",
")",
"new_surfaces",
"=",
"list",
"(",
")",
"spritedict",
"=",
"self",
".",
"spritedict",
"gl",
"=",
"self",
".",
"g... | Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface | [
"Draw",
"all",
"sprites",
"and",
"map",
"onto",
"the",
"surface"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/group.py#L34-L56 |
24,585 | bitcraft/pyscroll | pyscroll/isometric.py | IsometricBufferedRenderer.center | def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = vector2_to_iso(vec)
self._x_offset = iso[0]
self._y_offset = iso[1]
print(self._tile_view.size)
print(self._buffer.get_size())
# center the buffer on the screen
self._x_offset += (self._buffer.get_width() - self.view_rect.width) // 2
self._y_offset += (self._buffer.get_height() - self.view_rect.height) // 4
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
# force redraw every time: edge queuing not supported yet
self._redraw_cutoff = 0
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue()
elif view_change > self._redraw_cutoff:
# logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles() | python | def center(self, coords):
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = vector2_to_iso(vec)
self._x_offset = iso[0]
self._y_offset = iso[1]
print(self._tile_view.size)
print(self._buffer.get_size())
# center the buffer on the screen
self._x_offset += (self._buffer.get_width() - self.view_rect.width) // 2
self._y_offset += (self._buffer.get_height() - self.view_rect.height) // 4
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
# force redraw every time: edge queuing not supported yet
self._redraw_cutoff = 0
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue()
elif view_change > self._redraw_cutoff:
# logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles() | [
"def",
"center",
"(",
"self",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"[",
"round",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"coords",
"]",
"self",
".",
"view_rect",
".",
"center",
"=",
"x",
",",
"y",
"tw",
",",
"th",
"=",
"self",
".... | center the map on a "map pixel" | [
"center",
"the",
"map",
"on",
"a",
"map",
"pixel"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/isometric.py#L86-L127 |
24,586 | acsone/click-odoo | click_odoo/env_options.py | env_options.get_odoo_args | def get_odoo_args(self, ctx):
"""Return a list of Odoo command line arguments from the Click context."""
config = ctx.params.get("config")
addons_path = ctx.params.get("addons_path")
database = ctx.params.get("database")
log_level = ctx.params.get("log_level")
logfile = ctx.params.get("logfile")
odoo_args = []
if config:
odoo_args.extend(["--config", config])
if addons_path:
odoo_args.extend(["--addons-path", addons_path])
if database:
odoo_args.extend(["--database", database])
if log_level:
odoo_args.extend(["--log-level", log_level])
if logfile:
odoo_args.extend(["--logfile", logfile])
return odoo_args | python | def get_odoo_args(self, ctx):
config = ctx.params.get("config")
addons_path = ctx.params.get("addons_path")
database = ctx.params.get("database")
log_level = ctx.params.get("log_level")
logfile = ctx.params.get("logfile")
odoo_args = []
if config:
odoo_args.extend(["--config", config])
if addons_path:
odoo_args.extend(["--addons-path", addons_path])
if database:
odoo_args.extend(["--database", database])
if log_level:
odoo_args.extend(["--log-level", log_level])
if logfile:
odoo_args.extend(["--logfile", logfile])
return odoo_args | [
"def",
"get_odoo_args",
"(",
"self",
",",
"ctx",
")",
":",
"config",
"=",
"ctx",
".",
"params",
".",
"get",
"(",
"\"config\"",
")",
"addons_path",
"=",
"ctx",
".",
"params",
".",
"get",
"(",
"\"addons_path\"",
")",
"database",
"=",
"ctx",
".",
"params"... | Return a list of Odoo command line arguments from the Click context. | [
"Return",
"a",
"list",
"of",
"Odoo",
"command",
"line",
"arguments",
"from",
"the",
"Click",
"context",
"."
] | 7335f722bb6edbaf34cee29e027a49f47e83e052 | https://github.com/acsone/click-odoo/blob/7335f722bb6edbaf34cee29e027a49f47e83e052/click_odoo/env_options.py#L123-L144 |
24,587 | williamgilpin/pypdb | pypdb/pypdb.py | make_query | def make_query(search_term, querytype='AdvancedKeywordQuery'):
''' Repackage strings into a search dictionary
This function takes a list of search terms and specifications
and repackages it as a dictionary object that can be used to conduct a search
Parameters
----------
search_term : str
The specific term to search in the database. For specific query types,
the strings that will yield valid results are limited to:
'HoldingsQuery' : A Ggeneral search of the metadata associated with PDB IDs
'ExpTypeQuery' : Experimental Method such as 'X-RAY', 'SOLID-STATE NMR', etc
'AdvancedKeywordQuery' : Any string that appears in the title or abstract
'StructureIdQuery' : Perform a search for a specific Structure ID
'ModifiedStructuresQuery' : Search for related structures
'AdvancedAuthorQuery' : Search by the names of authors associated with entries
'MotifQuery' : Search for a specific motif
'NoLigandQuery' : Find full list of PDB IDs without free ligrands
querytype : str
The type of query to perform, the easiest is an AdvancedKeywordQuery but more
specific types of searches may also be performed
Returns
-------
scan_params : dict
A dictionary representing the query
Examples
--------
This method usually gets used in tandem with do_search
>>> a = make_query('actin network')
>>> print (a)
{'orgPdbQuery': {'description': 'Text Search for: actin',
'keywords': 'actin',
'queryType': 'AdvancedKeywordQuery'}}
>>> search_dict = make_query('actin network')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['1D7M', '3W3D', '4A7H', '4A7L', '4A7N']
>>> search_dict = make_query('T[AG]AGGY',querytype='MotifQuery')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['3LEZ', '3SGH', '4F47']
'''
assert querytype in {'HoldingsQuery', 'ExpTypeQuery',
'AdvancedKeywordQuery','StructureIdQuery',
'ModifiedStructuresQuery', 'AdvancedAuthorQuery', 'MotifQuery',
'NoLigandQuery', 'PubmedIdQuery'
}, 'Query type %s not supported yet' % querytype
query_params = dict()
query_params['queryType'] = querytype
if querytype=='AdvancedKeywordQuery':
query_params['description'] = 'Text Search for: '+ search_term
query_params['keywords'] = search_term
elif querytype=='NoLigandQuery':
query_params['haveLigands'] = 'yes'
elif querytype=='AdvancedAuthorQuery':
query_params['description'] = 'Author Name: '+ search_term
query_params['searchType'] = 'All Authors'
query_params['audit_author.name'] = search_term
query_params['exactMatch'] = 'false'
elif querytype=='MotifQuery':
query_params['description'] = 'Motif Query For: '+ search_term
query_params['motif'] = search_term
# search for a specific structure
elif querytype in ['StructureIdQuery','ModifiedStructuresQuery']:
query_params['structureIdList'] = search_term
elif querytype=='ExpTypeQuery':
query_params['experimentalMethod'] = search_term
query_params['description'] = 'Experimental Method Search : Experimental Method='+ search_term
query_params['mvStructure.expMethod.value']= search_term
elif querytype=='PubmedIdQuery':
query_params['description'] = 'Pubmed Id Search for Pubmed Id '+ search_term
query_params['pubMedIdList'] = search_term
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
return scan_params | python | def make_query(search_term, querytype='AdvancedKeywordQuery'):
''' Repackage strings into a search dictionary
This function takes a list of search terms and specifications
and repackages it as a dictionary object that can be used to conduct a search
Parameters
----------
search_term : str
The specific term to search in the database. For specific query types,
the strings that will yield valid results are limited to:
'HoldingsQuery' : A Ggeneral search of the metadata associated with PDB IDs
'ExpTypeQuery' : Experimental Method such as 'X-RAY', 'SOLID-STATE NMR', etc
'AdvancedKeywordQuery' : Any string that appears in the title or abstract
'StructureIdQuery' : Perform a search for a specific Structure ID
'ModifiedStructuresQuery' : Search for related structures
'AdvancedAuthorQuery' : Search by the names of authors associated with entries
'MotifQuery' : Search for a specific motif
'NoLigandQuery' : Find full list of PDB IDs without free ligrands
querytype : str
The type of query to perform, the easiest is an AdvancedKeywordQuery but more
specific types of searches may also be performed
Returns
-------
scan_params : dict
A dictionary representing the query
Examples
--------
This method usually gets used in tandem with do_search
>>> a = make_query('actin network')
>>> print (a)
{'orgPdbQuery': {'description': 'Text Search for: actin',
'keywords': 'actin',
'queryType': 'AdvancedKeywordQuery'}}
>>> search_dict = make_query('actin network')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['1D7M', '3W3D', '4A7H', '4A7L', '4A7N']
>>> search_dict = make_query('T[AG]AGGY',querytype='MotifQuery')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['3LEZ', '3SGH', '4F47']
'''
assert querytype in {'HoldingsQuery', 'ExpTypeQuery',
'AdvancedKeywordQuery','StructureIdQuery',
'ModifiedStructuresQuery', 'AdvancedAuthorQuery', 'MotifQuery',
'NoLigandQuery', 'PubmedIdQuery'
}, 'Query type %s not supported yet' % querytype
query_params = dict()
query_params['queryType'] = querytype
if querytype=='AdvancedKeywordQuery':
query_params['description'] = 'Text Search for: '+ search_term
query_params['keywords'] = search_term
elif querytype=='NoLigandQuery':
query_params['haveLigands'] = 'yes'
elif querytype=='AdvancedAuthorQuery':
query_params['description'] = 'Author Name: '+ search_term
query_params['searchType'] = 'All Authors'
query_params['audit_author.name'] = search_term
query_params['exactMatch'] = 'false'
elif querytype=='MotifQuery':
query_params['description'] = 'Motif Query For: '+ search_term
query_params['motif'] = search_term
# search for a specific structure
elif querytype in ['StructureIdQuery','ModifiedStructuresQuery']:
query_params['structureIdList'] = search_term
elif querytype=='ExpTypeQuery':
query_params['experimentalMethod'] = search_term
query_params['description'] = 'Experimental Method Search : Experimental Method='+ search_term
query_params['mvStructure.expMethod.value']= search_term
elif querytype=='PubmedIdQuery':
query_params['description'] = 'Pubmed Id Search for Pubmed Id '+ search_term
query_params['pubMedIdList'] = search_term
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
return scan_params | [
"def",
"make_query",
"(",
"search_term",
",",
"querytype",
"=",
"'AdvancedKeywordQuery'",
")",
":",
"assert",
"querytype",
"in",
"{",
"'HoldingsQuery'",
",",
"'ExpTypeQuery'",
",",
"'AdvancedKeywordQuery'",
",",
"'StructureIdQuery'",
",",
"'ModifiedStructuresQuery'",
",... | Repackage strings into a search dictionary
This function takes a list of search terms and specifications
and repackages it as a dictionary object that can be used to conduct a search
Parameters
----------
search_term : str
The specific term to search in the database. For specific query types,
the strings that will yield valid results are limited to:
'HoldingsQuery' : A Ggeneral search of the metadata associated with PDB IDs
'ExpTypeQuery' : Experimental Method such as 'X-RAY', 'SOLID-STATE NMR', etc
'AdvancedKeywordQuery' : Any string that appears in the title or abstract
'StructureIdQuery' : Perform a search for a specific Structure ID
'ModifiedStructuresQuery' : Search for related structures
'AdvancedAuthorQuery' : Search by the names of authors associated with entries
'MotifQuery' : Search for a specific motif
'NoLigandQuery' : Find full list of PDB IDs without free ligrands
querytype : str
The type of query to perform, the easiest is an AdvancedKeywordQuery but more
specific types of searches may also be performed
Returns
-------
scan_params : dict
A dictionary representing the query
Examples
--------
This method usually gets used in tandem with do_search
>>> a = make_query('actin network')
>>> print (a)
{'orgPdbQuery': {'description': 'Text Search for: actin',
'keywords': 'actin',
'queryType': 'AdvancedKeywordQuery'}}
>>> search_dict = make_query('actin network')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['1D7M', '3W3D', '4A7H', '4A7L', '4A7N']
>>> search_dict = make_query('T[AG]AGGY',querytype='MotifQuery')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['3LEZ', '3SGH', '4F47'] | [
"Repackage",
"strings",
"into",
"a",
"search",
"dictionary"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L51-L159 |
24,588 | williamgilpin/pypdb | pypdb/pypdb.py | do_protsym_search | def do_protsym_search(point_group, min_rmsd=0.0, max_rmsd=7.0):
'''Performs a protein symmetry search of the PDB
This function can search the Protein Data Bank based on how closely entries
match the user-specified symmetry group
Parameters
----------
point_group : str
The name of the symmetry point group to search. This includes all the standard
abbreviations for symmetry point groups (e.g., C1, C2, D2, T, O, I, H, A1)
min_rmsd : float
The smallest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
max_rmsd : float
The largest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
Returns
-------
idlist : list of strings
A list of PDB IDs resulting from the search
Examples
--------
>>> kk = do_protsym_search('C9', min_rmsd=0.0, max_rmsd=1.0)
>>> print(kk[:5])
['1KZU', '1NKZ', '2FKW', '3B8M', '3B8N']
'''
query_params = dict()
query_params['queryType'] = 'PointGroupQuery'
query_params['rMSDComparator'] = 'between'
query_params['pointGroup'] = point_group
query_params['rMSDMin'] = min_rmsd
query_params['rMSDMax'] = max_rmsd
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
idlist = do_search(scan_params)
return idlist | python | def do_protsym_search(point_group, min_rmsd=0.0, max_rmsd=7.0):
'''Performs a protein symmetry search of the PDB
This function can search the Protein Data Bank based on how closely entries
match the user-specified symmetry group
Parameters
----------
point_group : str
The name of the symmetry point group to search. This includes all the standard
abbreviations for symmetry point groups (e.g., C1, C2, D2, T, O, I, H, A1)
min_rmsd : float
The smallest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
max_rmsd : float
The largest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
Returns
-------
idlist : list of strings
A list of PDB IDs resulting from the search
Examples
--------
>>> kk = do_protsym_search('C9', min_rmsd=0.0, max_rmsd=1.0)
>>> print(kk[:5])
['1KZU', '1NKZ', '2FKW', '3B8M', '3B8N']
'''
query_params = dict()
query_params['queryType'] = 'PointGroupQuery'
query_params['rMSDComparator'] = 'between'
query_params['pointGroup'] = point_group
query_params['rMSDMin'] = min_rmsd
query_params['rMSDMax'] = max_rmsd
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
idlist = do_search(scan_params)
return idlist | [
"def",
"do_protsym_search",
"(",
"point_group",
",",
"min_rmsd",
"=",
"0.0",
",",
"max_rmsd",
"=",
"7.0",
")",
":",
"query_params",
"=",
"dict",
"(",
")",
"query_params",
"[",
"'queryType'",
"]",
"=",
"'PointGroupQuery'",
"query_params",
"[",
"'rMSDComparator'",... | Performs a protein symmetry search of the PDB
This function can search the Protein Data Bank based on how closely entries
match the user-specified symmetry group
Parameters
----------
point_group : str
The name of the symmetry point group to search. This includes all the standard
abbreviations for symmetry point groups (e.g., C1, C2, D2, T, O, I, H, A1)
min_rmsd : float
The smallest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
max_rmsd : float
The largest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
Returns
-------
idlist : list of strings
A list of PDB IDs resulting from the search
Examples
--------
>>> kk = do_protsym_search('C9', min_rmsd=0.0, max_rmsd=1.0)
>>> print(kk[:5])
['1KZU', '1NKZ', '2FKW', '3B8M', '3B8N'] | [
"Performs",
"a",
"protein",
"symmetry",
"search",
"of",
"the",
"PDB"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L222-L270 |
24,589 | williamgilpin/pypdb | pypdb/pypdb.py | get_all | def get_all():
"""Return a list of all PDB entries currently in the RCSB Protein Data Bank
Returns
-------
out : list of str
A list of all of the PDB IDs currently in the RCSB PDB
Examples
--------
>>> print(get_all()[:10])
['100D', '101D', '101M', '102D', '102L', '102M', '103D', '103L', '103M', '104D']
"""
url = 'http://www.rcsb.org/pdb/rest/getCurrent'
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
kk = str(result)
p = re.compile('structureId=\"...."')
matches = p.findall(str(result))
out = list()
for item in matches:
out.append(item[-5:-1])
return out | python | def get_all():
url = 'http://www.rcsb.org/pdb/rest/getCurrent'
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
kk = str(result)
p = re.compile('structureId=\"...."')
matches = p.findall(str(result))
out = list()
for item in matches:
out.append(item[-5:-1])
return out | [
"def",
"get_all",
"(",
")",
":",
"url",
"=",
"'http://www.rcsb.org/pdb/rest/getCurrent'",
"req",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"url",
")",
"f",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"req",
")",
"result",
"=",
"f",
".",... | Return a list of all PDB entries currently in the RCSB Protein Data Bank
Returns
-------
out : list of str
A list of all of the PDB IDs currently in the RCSB PDB
Examples
--------
>>> print(get_all()[:10])
['100D', '101D', '101M', '102D', '102L', '102M', '103D', '103L', '103M', '104D'] | [
"Return",
"a",
"list",
"of",
"all",
"PDB",
"entries",
"currently",
"in",
"the",
"RCSB",
"Protein",
"Data",
"Bank"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L273-L305 |
24,590 | williamgilpin/pypdb | pypdb/pypdb.py | get_info | def get_info(pdb_id, url_root='http://www.rcsb.org/pdb/rest/describeMol?structureId='):
'''Look up all information about a given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
url_root : string
The string root of the specific url for the request type
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url = url_root + pdb_id
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
out = xmltodict.parse(result,process_namespaces=True)
return out | python | def get_info(pdb_id, url_root='http://www.rcsb.org/pdb/rest/describeMol?structureId='):
'''Look up all information about a given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
url_root : string
The string root of the specific url for the request type
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url = url_root + pdb_id
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
out = xmltodict.parse(result,process_namespaces=True)
return out | [
"def",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/describeMol?structureId='",
")",
":",
"url",
"=",
"url_root",
"+",
"pdb_id",
"req",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"url",
")",
"f",
"=",
"urllib",
".",
... | Look up all information about a given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
url_root : string
The string root of the specific url for the request type
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml | [
"Look",
"up",
"all",
"information",
"about",
"a",
"given",
"PDB",
"ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L313-L341 |
24,591 | williamgilpin/pypdb | pypdb/pypdb.py | get_pdb_file | def get_pdb_file(pdb_id, filetype='pdb', compression=False):
'''Get the full PDB file associated with a PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
filetype: string
The file type.
'pdb' is the older file format,
'cif' is the newer replacement.
'xml' an also be obtained and parsed using the various xml tools included in PyPDB
'structfact' retrieves structure factors (only available for certain PDB entries)
compression : bool
Retrieve a compressed (gz) version of the file
Returns
-------
result : string
The string representing the full PDB file in the given format
Examples
--------
>>> pdb_file = get_pdb_file('4lza', filetype='cif', compression=True)
>>> print(pdb_file[:200])
data_4LZA
#
_entry.id 4LZA
#
_audit_conform.dict_name mmcif_pdbx.dic
_audit_conform.dict_version 4.032
_audit_conform.dict_location http://mmcif.pdb.org/dictionaries/ascii/mmcif_pdbx
'''
full_url = "https://files.rcsb.org/download/"
full_url += pdb_id
if (filetype == 'structfact'):
full_url += "-sf.cif"
else:
full_url += "." + filetype
if compression:
full_url += ".gz"
else:
pass
req = urllib.request.Request(full_url)
f = urllib.request.urlopen(req)
result = f.read()
if not compression:
result = result.decode('ascii')
else:
pass
return result | python | def get_pdb_file(pdb_id, filetype='pdb', compression=False):
'''Get the full PDB file associated with a PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
filetype: string
The file type.
'pdb' is the older file format,
'cif' is the newer replacement.
'xml' an also be obtained and parsed using the various xml tools included in PyPDB
'structfact' retrieves structure factors (only available for certain PDB entries)
compression : bool
Retrieve a compressed (gz) version of the file
Returns
-------
result : string
The string representing the full PDB file in the given format
Examples
--------
>>> pdb_file = get_pdb_file('4lza', filetype='cif', compression=True)
>>> print(pdb_file[:200])
data_4LZA
#
_entry.id 4LZA
#
_audit_conform.dict_name mmcif_pdbx.dic
_audit_conform.dict_version 4.032
_audit_conform.dict_location http://mmcif.pdb.org/dictionaries/ascii/mmcif_pdbx
'''
full_url = "https://files.rcsb.org/download/"
full_url += pdb_id
if (filetype == 'structfact'):
full_url += "-sf.cif"
else:
full_url += "." + filetype
if compression:
full_url += ".gz"
else:
pass
req = urllib.request.Request(full_url)
f = urllib.request.urlopen(req)
result = f.read()
if not compression:
result = result.decode('ascii')
else:
pass
return result | [
"def",
"get_pdb_file",
"(",
"pdb_id",
",",
"filetype",
"=",
"'pdb'",
",",
"compression",
"=",
"False",
")",
":",
"full_url",
"=",
"\"https://files.rcsb.org/download/\"",
"full_url",
"+=",
"pdb_id",
"if",
"(",
"filetype",
"==",
"'structfact'",
")",
":",
"full_url... | Get the full PDB file associated with a PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
filetype: string
The file type.
'pdb' is the older file format,
'cif' is the newer replacement.
'xml' an also be obtained and parsed using the various xml tools included in PyPDB
'structfact' retrieves structure factors (only available for certain PDB entries)
compression : bool
Retrieve a compressed (gz) version of the file
Returns
-------
result : string
The string representing the full PDB file in the given format
Examples
--------
>>> pdb_file = get_pdb_file('4lza', filetype='cif', compression=True)
>>> print(pdb_file[:200])
data_4LZA
#
_entry.id 4LZA
#
_audit_conform.dict_name mmcif_pdbx.dic
_audit_conform.dict_version 4.032
_audit_conform.dict_location http://mmcif.pdb.org/dictionaries/ascii/mmcif_pdbx | [
"Get",
"the",
"full",
"PDB",
"file",
"associated",
"with",
"a",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L343-L406 |
24,592 | williamgilpin/pypdb | pypdb/pypdb.py | get_all_info | def get_all_info(pdb_id):
'''A wrapper for get_info that cleans up the output slighly
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing all the information stored in the entry
Examples
--------
>>> all_info = get_all_info('4lza')
>>> print(all_info)
{'polymer': {'macroMolecule': {'@name': 'Adenine phosphoribosyltransferase', '
accession': {'@id': 'B0K969'}}, '@entityNr': '1', '@type': 'protein',
'polymerDescription': {'@description': 'Adenine phosphoribosyltransferase'},
'synonym': {'@name': 'APRT'}, '@length': '195', 'enzClass': {'@ec': '2.4.2.7'},
'chain': [{'@id': 'A'}, {'@id': 'B'}],
'Taxonomy': {'@name': 'Thermoanaerobacter pseudethanolicus ATCC 33223',
'@id': '340099'}, '@weight': '22023.9'}, 'id': '4LZA'}
>>> results = get_all_info('2F5N')
>>> first_polymer = results['polymer'][0]
>>> first_polymer['polymerDescription']
{'@description': "5'-D(*AP*GP*GP*TP*AP*GP*AP*CP*CP*TP*GP*GP*AP*CP*GP*C)-3'"}
'''
out = to_dict( get_info(pdb_id) )['molDescription']['structureId']
out = remove_at_sign(out)
return out | python | def get_all_info(pdb_id):
'''A wrapper for get_info that cleans up the output slighly
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing all the information stored in the entry
Examples
--------
>>> all_info = get_all_info('4lza')
>>> print(all_info)
{'polymer': {'macroMolecule': {'@name': 'Adenine phosphoribosyltransferase', '
accession': {'@id': 'B0K969'}}, '@entityNr': '1', '@type': 'protein',
'polymerDescription': {'@description': 'Adenine phosphoribosyltransferase'},
'synonym': {'@name': 'APRT'}, '@length': '195', 'enzClass': {'@ec': '2.4.2.7'},
'chain': [{'@id': 'A'}, {'@id': 'B'}],
'Taxonomy': {'@name': 'Thermoanaerobacter pseudethanolicus ATCC 33223',
'@id': '340099'}, '@weight': '22023.9'}, 'id': '4LZA'}
>>> results = get_all_info('2F5N')
>>> first_polymer = results['polymer'][0]
>>> first_polymer['polymerDescription']
{'@description': "5'-D(*AP*GP*GP*TP*AP*GP*AP*CP*CP*TP*GP*GP*AP*CP*GP*C)-3'"}
'''
out = to_dict( get_info(pdb_id) )['molDescription']['structureId']
out = remove_at_sign(out)
return out | [
"def",
"get_all_info",
"(",
"pdb_id",
")",
":",
"out",
"=",
"to_dict",
"(",
"get_info",
"(",
"pdb_id",
")",
")",
"[",
"'molDescription'",
"]",
"[",
"'structureId'",
"]",
"out",
"=",
"remove_at_sign",
"(",
"out",
")",
"return",
"out"
] | A wrapper for get_info that cleans up the output slighly
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing all the information stored in the entry
Examples
--------
>>> all_info = get_all_info('4lza')
>>> print(all_info)
{'polymer': {'macroMolecule': {'@name': 'Adenine phosphoribosyltransferase', '
accession': {'@id': 'B0K969'}}, '@entityNr': '1', '@type': 'protein',
'polymerDescription': {'@description': 'Adenine phosphoribosyltransferase'},
'synonym': {'@name': 'APRT'}, '@length': '195', 'enzClass': {'@ec': '2.4.2.7'},
'chain': [{'@id': 'A'}, {'@id': 'B'}],
'Taxonomy': {'@name': 'Thermoanaerobacter pseudethanolicus ATCC 33223',
'@id': '340099'}, '@weight': '22023.9'}, 'id': '4LZA'}
>>> results = get_all_info('2F5N')
>>> first_polymer = results['polymer'][0]
>>> first_polymer['polymerDescription']
{'@description': "5'-D(*AP*GP*GP*TP*AP*GP*AP*CP*CP*TP*GP*GP*AP*CP*GP*C)-3'"} | [
"A",
"wrapper",
"for",
"get_info",
"that",
"cleans",
"up",
"the",
"output",
"slighly"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L409-L445 |
24,593 | williamgilpin/pypdb | pypdb/pypdb.py | get_raw_blast | def get_raw_blast(pdb_id, output_form='HTML', chain_id='A'):
'''Look up full BLAST page for a given PDB ID
get_blast() uses this function internally
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the outputs
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url_root = 'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='
url = url_root + pdb_id + '&chainId='+ chain_id +'&outputFormat=' + output_form
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
result = result.decode('unicode_escape')
assert result
return result | python | def get_raw_blast(pdb_id, output_form='HTML', chain_id='A'):
'''Look up full BLAST page for a given PDB ID
get_blast() uses this function internally
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the outputs
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url_root = 'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='
url = url_root + pdb_id + '&chainId='+ chain_id +'&outputFormat=' + output_form
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
result = result.decode('unicode_escape')
assert result
return result | [
"def",
"get_raw_blast",
"(",
"pdb_id",
",",
"output_form",
"=",
"'HTML'",
",",
"chain_id",
"=",
"'A'",
")",
":",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='",
"url",
"=",
"url_root",
"+",
"pdb_id",
"+",
"'&chainId='",
"+",
"chain_id",
... | Look up full BLAST page for a given PDB ID
get_blast() uses this function internally
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the outputs
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml | [
"Look",
"up",
"full",
"BLAST",
"page",
"for",
"a",
"given",
"PDB",
"ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L447-L481 |
24,594 | williamgilpin/pypdb | pypdb/pypdb.py | parse_blast | def parse_blast(blast_string):
'''Clean up HTML BLAST results
This function requires BeautifulSoup and the re module
It goes throught the complicated output returned by the BLAST
search and provides a list of matches, as well as the raw
text file showing the alignments for each of the matches.
This function works best with HTML formatted Inputs
------
get_blast() uses this function internally
Parameters
----------
blast_string : str
A complete webpage of standard BLAST results
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
'''
soup = BeautifulSoup(str(blast_string), "html.parser")
all_blasts = list()
all_blast_ids = list()
pattern = '></a>....:'
prog = re.compile(pattern)
for item in soup.find_all('pre'):
if len(item.find_all('a'))==1:
all_blasts.append(item)
blast_id = re.findall(pattern, str(item) )[0][-5:-1]
all_blast_ids.append(blast_id)
out = (all_blast_ids, all_blasts)
return out | python | def parse_blast(blast_string):
'''Clean up HTML BLAST results
This function requires BeautifulSoup and the re module
It goes throught the complicated output returned by the BLAST
search and provides a list of matches, as well as the raw
text file showing the alignments for each of the matches.
This function works best with HTML formatted Inputs
------
get_blast() uses this function internally
Parameters
----------
blast_string : str
A complete webpage of standard BLAST results
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
'''
soup = BeautifulSoup(str(blast_string), "html.parser")
all_blasts = list()
all_blast_ids = list()
pattern = '></a>....:'
prog = re.compile(pattern)
for item in soup.find_all('pre'):
if len(item.find_all('a'))==1:
all_blasts.append(item)
blast_id = re.findall(pattern, str(item) )[0][-5:-1]
all_blast_ids.append(blast_id)
out = (all_blast_ids, all_blasts)
return out | [
"def",
"parse_blast",
"(",
"blast_string",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"str",
"(",
"blast_string",
")",
",",
"\"html.parser\"",
")",
"all_blasts",
"=",
"list",
"(",
")",
"all_blast_ids",
"=",
"list",
"(",
")",
"pattern",
"=",
"'></a>....:'",... | Clean up HTML BLAST results
This function requires BeautifulSoup and the re module
It goes throught the complicated output returned by the BLAST
search and provides a list of matches, as well as the raw
text file showing the alignments for each of the matches.
This function works best with HTML formatted Inputs
------
get_blast() uses this function internally
Parameters
----------
blast_string : str
A complete webpage of standard BLAST results
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted) | [
"Clean",
"up",
"HTML",
"BLAST",
"results"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L484-L528 |
24,595 | williamgilpin/pypdb | pypdb/pypdb.py | get_blast2 | def get_blast2(pdb_id, chain_id='A', output_form='HTML'):
'''Alternative way to look up BLAST for a given PDB ID. This function is a wrapper
for get_raw_blast and parse_blast
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the BLAST page
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
Examples
--------
>>> blast_results = get_blast2('2F5N', chain_id='A', output_form='HTML')
>>> print('Total Results: ' + str(len(blast_results[0])) +'\n')
>>> print(blast_results[1][0])
Total Results: 84
<pre>
><a name="45354"></a>2F5P:3:A|pdbid|entity|chain(s)|sequence
Length = 274
Score = 545 bits (1404), Expect = e-155, Method: Composition-based stats.
Identities = 274/274 (100%), Positives = 274/274 (100%)
Query: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK
Sbjct: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
...
'''
raw_results = get_raw_blast(pdb_id, chain_id=chain_id, output_form=output_form)
out = parse_blast(raw_results)
return out | python | def get_blast2(pdb_id, chain_id='A', output_form='HTML'):
'''Alternative way to look up BLAST for a given PDB ID. This function is a wrapper
for get_raw_blast and parse_blast
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the BLAST page
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
Examples
--------
>>> blast_results = get_blast2('2F5N', chain_id='A', output_form='HTML')
>>> print('Total Results: ' + str(len(blast_results[0])) +'\n')
>>> print(blast_results[1][0])
Total Results: 84
<pre>
><a name="45354"></a>2F5P:3:A|pdbid|entity|chain(s)|sequence
Length = 274
Score = 545 bits (1404), Expect = e-155, Method: Composition-based stats.
Identities = 274/274 (100%), Positives = 274/274 (100%)
Query: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK
Sbjct: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
...
'''
raw_results = get_raw_blast(pdb_id, chain_id=chain_id, output_form=output_form)
out = parse_blast(raw_results)
return out | [
"def",
"get_blast2",
"(",
"pdb_id",
",",
"chain_id",
"=",
"'A'",
",",
"output_form",
"=",
"'HTML'",
")",
":",
"raw_results",
"=",
"get_raw_blast",
"(",
"pdb_id",
",",
"chain_id",
"=",
"chain_id",
",",
"output_form",
"=",
"output_form",
")",
"out",
"=",
"pa... | Alternative way to look up BLAST for a given PDB ID. This function is a wrapper
for get_raw_blast and parse_blast
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the BLAST page
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
Examples
--------
>>> blast_results = get_blast2('2F5N', chain_id='A', output_form='HTML')
>>> print('Total Results: ' + str(len(blast_results[0])) +'\n')
>>> print(blast_results[1][0])
Total Results: 84
<pre>
><a name="45354"></a>2F5P:3:A|pdbid|entity|chain(s)|sequence
Length = 274
Score = 545 bits (1404), Expect = e-155, Method: Composition-based stats.
Identities = 274/274 (100%), Positives = 274/274 (100%)
Query: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK
Sbjct: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
... | [
"Alternative",
"way",
"to",
"look",
"up",
"BLAST",
"for",
"a",
"given",
"PDB",
"ID",
".",
"This",
"function",
"is",
"a",
"wrapper",
"for",
"get_raw_blast",
"and",
"parse_blast"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L531-L576 |
24,596 | williamgilpin/pypdb | pypdb/pypdb.py | describe_pdb | def describe_pdb(pdb_id):
"""Get description and metadata of a PDB entry
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : string
A text pdb description from PDB
Examples
--------
>>> describe_pdb('4lza')
{'citation_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C.',
'deposition_date': '2013-07-31',
'expMethod': 'X-RAY DIFFRACTION',
'keywords': 'TRANSFERASE',
'last_modification_date': '2013-08-14',
'nr_atoms': '0',
'nr_entities': '1',
'nr_residues': '390',
'release_date': '2013-08-14',
'resolution': '1.84',
'status': 'CURRENT',
'structureId': '4LZA',
'structure_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C., New York Structural Genomics Research Consortium (NYSGRC)',
'title': 'Crystal structure of adenine phosphoribosyltransferase from Thermoanaerobacter pseudethanolicus ATCC 33223, NYSGRC Target 029700.'}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/describePDB?structureId=')
out = to_dict(out)
out = remove_at_sign(out['PDBdescription']['PDB'])
return out | python | def describe_pdb(pdb_id):
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/describePDB?structureId=')
out = to_dict(out)
out = remove_at_sign(out['PDBdescription']['PDB'])
return out | [
"def",
"describe_pdb",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/describePDB?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"out",
"=",
"remove_at_sign",
"(",
"out",
"[",
... | Get description and metadata of a PDB entry
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : string
A text pdb description from PDB
Examples
--------
>>> describe_pdb('4lza')
{'citation_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C.',
'deposition_date': '2013-07-31',
'expMethod': 'X-RAY DIFFRACTION',
'keywords': 'TRANSFERASE',
'last_modification_date': '2013-08-14',
'nr_atoms': '0',
'nr_entities': '1',
'nr_residues': '390',
'release_date': '2013-08-14',
'resolution': '1.84',
'status': 'CURRENT',
'structureId': '4LZA',
'structure_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C., New York Structural Genomics Research Consortium (NYSGRC)',
'title': 'Crystal structure of adenine phosphoribosyltransferase from Thermoanaerobacter pseudethanolicus ATCC 33223, NYSGRC Target 029700.'} | [
"Get",
"description",
"and",
"metadata",
"of",
"a",
"PDB",
"entry"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L578-L615 |
24,597 | williamgilpin/pypdb | pypdb/pypdb.py | get_entity_info | def get_entity_info(pdb_id):
"""Return pdb id information
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a description the entry
Examples
--------
>>> get_entity_info('4lza')
{'Entity': {'@id': '1',
'@type': 'protein',
'Chain': [{'@id': 'A'}, {'@id': 'B'}]},
'Method': {'@name': 'xray'},
'bioAssemblies': '1',
'release_date': 'Wed Aug 14 00:00:00 PDT 2013',
'resolution': '1.84',
'structureId': '4lza'}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId=')
out = to_dict(out)
return remove_at_sign( out['entityInfo']['PDB'] ) | python | def get_entity_info(pdb_id):
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId=')
out = to_dict(out)
return remove_at_sign( out['entityInfo']['PDB'] ) | [
"def",
"get_entity_info",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
... | Return pdb id information
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a description the entry
Examples
--------
>>> get_entity_info('4lza')
{'Entity': {'@id': '1',
'@type': 'protein',
'Chain': [{'@id': 'A'}, {'@id': 'B'}]},
'Method': {'@name': 'xray'},
'bioAssemblies': '1',
'release_date': 'Wed Aug 14 00:00:00 PDT 2013',
'resolution': '1.84',
'structureId': '4lza'} | [
"Return",
"pdb",
"id",
"information"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L617-L647 |
24,598 | williamgilpin/pypdb | pypdb/pypdb.py | get_ligands | def get_ligands(pdb_id):
"""Return ligands of given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a list of ligands associated with the entry
Examples
--------
>>> ligand_dict = get_ligands('100D')
>>> print(ligand_dict)
{'id': '100D',
'ligandInfo': {'ligand': {'@chemicalID': 'SPM',
'@molecularWeight': '202.34',
'@structureId': '100D',
'@type': 'non-polymer',
'InChI': 'InChI=1S/C10H26N4/c11-5-3-9-13-7-1-2-8-14-10-4-6-12/h13-14H,1-12H2',
'InChIKey': 'PFNFFQXMRSDOHW-UHFFFAOYSA-N',
'chemicalName': 'SPERMINE',
'formula': 'C10 H26 N4',
'smiles': 'C(CCNCCCN)CNCCCN'}}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/ligandInfo?structureId=')
out = to_dict(out)
return remove_at_sign(out['structureId']) | python | def get_ligands(pdb_id):
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/ligandInfo?structureId=')
out = to_dict(out)
return remove_at_sign(out['structureId']) | [
"def",
"get_ligands",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/ligandInfo?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
"'stru... | Return ligands of given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a list of ligands associated with the entry
Examples
--------
>>> ligand_dict = get_ligands('100D')
>>> print(ligand_dict)
{'id': '100D',
'ligandInfo': {'ligand': {'@chemicalID': 'SPM',
'@molecularWeight': '202.34',
'@structureId': '100D',
'@type': 'non-polymer',
'InChI': 'InChI=1S/C10H26N4/c11-5-3-9-13-7-1-2-8-14-10-4-6-12/h13-14H,1-12H2',
'InChIKey': 'PFNFFQXMRSDOHW-UHFFFAOYSA-N',
'chemicalName': 'SPERMINE',
'formula': 'C10 H26 N4',
'smiles': 'C(CCNCCCN)CNCCCN'}}} | [
"Return",
"ligands",
"of",
"given",
"PDB",
"ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L681-L715 |
24,599 | williamgilpin/pypdb | pypdb/pypdb.py | get_gene_onto | def get_gene_onto(pdb_id):
"""Return ligands of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the gene ontology information associated with the entry
Examples
--------
>>> gene_info = get_gene_onto('4Z0L')
>>> print(gene_info['term'][0])
{'@chainId': 'A',
'@id': 'GO:0001516',
'@structureId': '4Z0L',
'detail': {'@definition': 'The chemical reactions and pathways resulting '
'in the formation of prostaglandins, any of a '
'group of biologically active metabolites which '
'contain a cyclopentane ring.',
'@name': 'prostaglandin biosynthetic process',
'@ontology': 'B',
'@synonyms': 'prostaglandin anabolism, prostaglandin '
'biosynthesis, prostaglandin formation, '
'prostaglandin synthesis'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/goTerms?structureId=')
out = to_dict(out)
if not out['goTerms']:
return None
out = remove_at_sign(out['goTerms'])
return out | python | def get_gene_onto(pdb_id):
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/goTerms?structureId=')
out = to_dict(out)
if not out['goTerms']:
return None
out = remove_at_sign(out['goTerms'])
return out | [
"def",
"get_gene_onto",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/goTerms?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"if",
"not",
"out",
"[",
"'goTerms'",
"]",
":",
... | Return ligands of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the gene ontology information associated with the entry
Examples
--------
>>> gene_info = get_gene_onto('4Z0L')
>>> print(gene_info['term'][0])
{'@chainId': 'A',
'@id': 'GO:0001516',
'@structureId': '4Z0L',
'detail': {'@definition': 'The chemical reactions and pathways resulting '
'in the formation of prostaglandins, any of a '
'group of biologically active metabolites which '
'contain a cyclopentane ring.',
'@name': 'prostaglandin biosynthetic process',
'@ontology': 'B',
'@synonyms': 'prostaglandin anabolism, prostaglandin '
'biosynthesis, prostaglandin formation, '
'prostaglandin synthesis'}} | [
"Return",
"ligands",
"of",
"given",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L717-L755 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.