repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
trevisanj/f311 | f311/filetypes/filesqlitedb.py | FileSQLiteDB.get_table_info | def get_table_info(self, tablename):
"""Returns information about fields of a specific table
Returns: OrderedDict(("fieldname", MyDBRow), ...))
**Note** Fields "caption" and "tooltip" are added to rows using information in moldb.gui_info
"""
conn = self.__get_conn()
r... | python | def get_table_info(self, tablename):
"""Returns information about fields of a specific table
Returns: OrderedDict(("fieldname", MyDBRow), ...))
**Note** Fields "caption" and "tooltip" are added to rows using information in moldb.gui_info
"""
conn = self.__get_conn()
r... | [
"def",
"get_table_info",
"(",
"self",
",",
"tablename",
")",
":",
"conn",
"=",
"self",
".",
"__get_conn",
"(",
")",
"ret",
"=",
"a99",
".",
"get_table_info",
"(",
"conn",
",",
"tablename",
")",
"if",
"len",
"(",
"ret",
")",
"==",
"0",
":",
"raise",
... | Returns information about fields of a specific table
Returns: OrderedDict(("fieldname", MyDBRow), ...))
**Note** Fields "caption" and "tooltip" are added to rows using information in moldb.gui_info | [
"Returns",
"information",
"about",
"fields",
"of",
"a",
"specific",
"table"
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/filetypes/filesqlitedb.py#L143-L167 | train | 57,200 |
trevisanj/f311 | f311/filetypes/filesqlitedb.py | FileSQLiteDB.__get_conn | def __get_conn(self, flag_force_new=False, filename=None):
"""Returns connection to database. Tries to return existing connection, unless flag_force_new
Args:
flag_force_new:
filename:
Returns: sqlite3.Connection object
**Note** this is a private method because... | python | def __get_conn(self, flag_force_new=False, filename=None):
"""Returns connection to database. Tries to return existing connection, unless flag_force_new
Args:
flag_force_new:
filename:
Returns: sqlite3.Connection object
**Note** this is a private method because... | [
"def",
"__get_conn",
"(",
"self",
",",
"flag_force_new",
"=",
"False",
",",
"filename",
"=",
"None",
")",
":",
"flag_open_new",
"=",
"flag_force_new",
"or",
"not",
"self",
".",
"_conn_is_open",
"(",
")",
"if",
"flag_open_new",
":",
"if",
"filename",
"is",
... | Returns connection to database. Tries to return existing connection, unless flag_force_new
Args:
flag_force_new:
filename:
Returns: sqlite3.Connection object
**Note** this is a private method because you can get a connection to any file, so it has to
b... | [
"Returns",
"connection",
"to",
"database",
".",
"Tries",
"to",
"return",
"existing",
"connection",
"unless",
"flag_force_new"
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/filetypes/filesqlitedb.py#L179-L201 | train | 57,201 |
inveniosoftware-attic/invenio-utils | invenio_utils/datastructures.py | flatten_multidict | def flatten_multidict(multidict):
"""Return flattened dictionary from ``MultiDict``."""
return dict([(key, value if len(value) > 1 else value[0])
for (key, value) in multidict.iterlists()]) | python | def flatten_multidict(multidict):
"""Return flattened dictionary from ``MultiDict``."""
return dict([(key, value if len(value) > 1 else value[0])
for (key, value) in multidict.iterlists()]) | [
"def",
"flatten_multidict",
"(",
"multidict",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"key",
",",
"value",
"if",
"len",
"(",
"value",
")",
">",
"1",
"else",
"value",
"[",
"0",
"]",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"multidict",
... | Return flattened dictionary from ``MultiDict``. | [
"Return",
"flattened",
"dictionary",
"from",
"MultiDict",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/datastructures.py#L418-L421 | train | 57,202 |
inveniosoftware-attic/invenio-utils | invenio_utils/datastructures.py | SmartDict.__setitem | def __setitem(self, chunk, key, keys, value, extend=False):
"""Helper function to fill up the dictionary."""
def setitem(chunk):
if keys:
return self.__setitem(chunk, keys[0], keys[1:], value, extend)
else:
return value
if key in ['.', ']'... | python | def __setitem(self, chunk, key, keys, value, extend=False):
"""Helper function to fill up the dictionary."""
def setitem(chunk):
if keys:
return self.__setitem(chunk, keys[0], keys[1:], value, extend)
else:
return value
if key in ['.', ']'... | [
"def",
"__setitem",
"(",
"self",
",",
"chunk",
",",
"key",
",",
"keys",
",",
"value",
",",
"extend",
"=",
"False",
")",
":",
"def",
"setitem",
"(",
"chunk",
")",
":",
"if",
"keys",
":",
"return",
"self",
".",
"__setitem",
"(",
"chunk",
",",
"keys",... | Helper function to fill up the dictionary. | [
"Helper",
"function",
"to",
"fill",
"up",
"the",
"dictionary",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/datastructures.py#L323-L373 | train | 57,203 |
inveniosoftware-attic/invenio-utils | invenio_utils/datastructures.py | SmartDict.set | def set(self, key, value, extend=False, **kwargs):
"""Extended standard set function."""
self.__setitem__(key, value, extend, **kwargs) | python | def set(self, key, value, extend=False, **kwargs):
"""Extended standard set function."""
self.__setitem__(key, value, extend, **kwargs) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"extend",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__setitem__",
"(",
"key",
",",
"value",
",",
"extend",
",",
"*",
"*",
"kwargs",
")"
] | Extended standard set function. | [
"Extended",
"standard",
"set",
"function",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/datastructures.py#L382-L384 | train | 57,204 |
volfpeter/graphscraper | src/graphscraper/spotifyartist.py | SpotifyArtistGraph.create_default_database | def create_default_database(reset: bool = False) -> GraphDatabaseInterface:
"""
Creates and returns a default SQLAlchemy database interface to use.
Arguments:
reset (bool): Whether to reset the database if it happens to exist already.
"""
import sqlalchemy
fr... | python | def create_default_database(reset: bool = False) -> GraphDatabaseInterface:
"""
Creates and returns a default SQLAlchemy database interface to use.
Arguments:
reset (bool): Whether to reset the database if it happens to exist already.
"""
import sqlalchemy
fr... | [
"def",
"create_default_database",
"(",
"reset",
":",
"bool",
"=",
"False",
")",
"->",
"GraphDatabaseInterface",
":",
"import",
"sqlalchemy",
"from",
"sqlalchemy",
".",
"ext",
".",
"declarative",
"import",
"declarative_base",
"from",
"sqlalchemy",
".",
"orm",
"impo... | Creates and returns a default SQLAlchemy database interface to use.
Arguments:
reset (bool): Whether to reset the database if it happens to exist already. | [
"Creates",
"and",
"returns",
"a",
"default",
"SQLAlchemy",
"database",
"interface",
"to",
"use",
"."
] | 11d407509956a282ee25190ed6491a162fc0fe7f | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/spotifyartist.py#L95-L119 | train | 57,205 |
volfpeter/graphscraper | src/graphscraper/spotifyartist.py | SpotifyArtistNodeList._create_node | def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> SpotifyArtistNode:
"""
Returns a new `SpotifyArtistNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node ... | python | def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> SpotifyArtistNode:
"""
Returns a new `SpotifyArtistNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node ... | [
"def",
"_create_node",
"(",
"self",
",",
"index",
":",
"int",
",",
"name",
":",
"str",
",",
"external_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"SpotifyArtistNode",
":",
"if",
"external_id",
"is",
"None",
":",
"graph",
":",
"Spotif... | Returns a new `SpotifyArtistNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node to create.
external_id (Optional[str]): The external ID of the node. | [
"Returns",
"a",
"new",
"SpotifyArtistNode",
"instance",
"with",
"the",
"given",
"index",
"and",
"name",
"."
] | 11d407509956a282ee25190ed6491a162fc0fe7f | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/spotifyartist.py#L222-L239 | train | 57,206 |
volfpeter/graphscraper | src/graphscraper/spotifyartist.py | SpotifyClientTokenWrapper.access_token | def access_token(self) -> str:
"""
The access token stored within the requested token.
"""
if self._token_expires_at < time.time() + self._REFRESH_THRESHOLD:
self.request_token()
return self._token["access_token"] | python | def access_token(self) -> str:
"""
The access token stored within the requested token.
"""
if self._token_expires_at < time.time() + self._REFRESH_THRESHOLD:
self.request_token()
return self._token["access_token"] | [
"def",
"access_token",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_token_expires_at",
"<",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"_REFRESH_THRESHOLD",
":",
"self",
".",
"request_token",
"(",
")",
"return",
"self",
".",
"_token",
... | The access token stored within the requested token. | [
"The",
"access",
"token",
"stored",
"within",
"the",
"requested",
"token",
"."
] | 11d407509956a282ee25190ed6491a162fc0fe7f | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/spotifyartist.py#L296-L303 | train | 57,207 |
volfpeter/graphscraper | src/graphscraper/spotifyartist.py | SpotifyClientTokenWrapper.request_token | def request_token(self) -> None:
"""
Requests a new Client Credentials Flow authentication token from the Spotify API
and stores it in the `token` property of the object.
Raises:
requests.HTTPError: If an HTTP error occurred during the request.
"""
response: ... | python | def request_token(self) -> None:
"""
Requests a new Client Credentials Flow authentication token from the Spotify API
and stores it in the `token` property of the object.
Raises:
requests.HTTPError: If an HTTP error occurred during the request.
"""
response: ... | [
"def",
"request_token",
"(",
"self",
")",
"->",
"None",
":",
"response",
":",
"requests",
".",
"Response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"_TOKEN_URL",
",",
"auth",
"=",
"HTTPBasicAuth",
"(",
"self",
".",
"_client_id",
",",
"self",
".",
... | Requests a new Client Credentials Flow authentication token from the Spotify API
and stores it in the `token` property of the object.
Raises:
requests.HTTPError: If an HTTP error occurred during the request. | [
"Requests",
"a",
"new",
"Client",
"Credentials",
"Flow",
"authentication",
"token",
"from",
"the",
"Spotify",
"API",
"and",
"stores",
"it",
"in",
"the",
"token",
"property",
"of",
"the",
"object",
"."
] | 11d407509956a282ee25190ed6491a162fc0fe7f | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/spotifyartist.py#L305-L321 | train | 57,208 |
volfpeter/graphscraper | src/graphscraper/spotifyartist.py | SpotifyClient.search_artists_by_name | def search_artists_by_name(self, artist_name: str, limit: int = 5) -> List[NameExternalIDPair]:
"""
Returns zero or more artist name - external ID pairs that match the specified artist name.
Arguments:
artist_name (str): The artist name to search in the Spotify API.
limi... | python | def search_artists_by_name(self, artist_name: str, limit: int = 5) -> List[NameExternalIDPair]:
"""
Returns zero or more artist name - external ID pairs that match the specified artist name.
Arguments:
artist_name (str): The artist name to search in the Spotify API.
limi... | [
"def",
"search_artists_by_name",
"(",
"self",
",",
"artist_name",
":",
"str",
",",
"limit",
":",
"int",
"=",
"5",
")",
"->",
"List",
"[",
"NameExternalIDPair",
"]",
":",
"response",
":",
"requests",
".",
"Response",
"=",
"requests",
".",
"get",
"(",
"sel... | Returns zero or more artist name - external ID pairs that match the specified artist name.
Arguments:
artist_name (str): The artist name to search in the Spotify API.
limit (int): The maximum number of results to return.
Returns:
Zero or more artist name - external ... | [
"Returns",
"zero",
"or",
"more",
"artist",
"name",
"-",
"external",
"ID",
"pairs",
"that",
"match",
"the",
"specified",
"artist",
"name",
"."
] | 11d407509956a282ee25190ed6491a162fc0fe7f | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/spotifyartist.py#L347-L382 | train | 57,209 |
hackedd/gw2api | gw2api/misc.py | colors | def colors(lang="en"):
"""This resource returns all dyes in the game, including localized names
and their color component information.
:param lang: The language to query the names for.
The response is a dictionary where color ids are mapped to an dictionary
containing the following properties:
... | python | def colors(lang="en"):
"""This resource returns all dyes in the game, including localized names
and their color component information.
:param lang: The language to query the names for.
The response is a dictionary where color ids are mapped to an dictionary
containing the following properties:
... | [
"def",
"colors",
"(",
"lang",
"=",
"\"en\"",
")",
":",
"cache_name",
"=",
"\"colors.%s.json\"",
"%",
"lang",
"data",
"=",
"get_cached",
"(",
"\"colors.json\"",
",",
"cache_name",
",",
"params",
"=",
"dict",
"(",
"lang",
"=",
"lang",
")",
")",
"return",
"... | This resource returns all dyes in the game, including localized names
and their color component information.
:param lang: The language to query the names for.
The response is a dictionary where color ids are mapped to an dictionary
containing the following properties:
name (string):
The n... | [
"This",
"resource",
"returns",
"all",
"dyes",
"in",
"the",
"game",
"including",
"localized",
"names",
"and",
"their",
"color",
"component",
"information",
"."
] | 5543a78e6e3ed0573b7e84c142c44004b4779eac | https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/misc.py#L15-L62 | train | 57,210 |
hackedd/gw2api | gw2api/events.py | event_names | def event_names(lang="en"):
"""This resource returns an unordered list of the localized event names
for the specified language.
:param lang: The language to query the names for.
:return: A dictionary where the key is the event id and the value is the
name of the event in the specified lang... | python | def event_names(lang="en"):
"""This resource returns an unordered list of the localized event names
for the specified language.
:param lang: The language to query the names for.
:return: A dictionary where the key is the event id and the value is the
name of the event in the specified lang... | [
"def",
"event_names",
"(",
"lang",
"=",
"\"en\"",
")",
":",
"cache_name",
"=",
"\"event_names.%s.json\"",
"%",
"lang",
"data",
"=",
"get_cached",
"(",
"\"event_names.json\"",
",",
"cache_name",
",",
"params",
"=",
"dict",
"(",
"lang",
"=",
"lang",
")",
")",
... | This resource returns an unordered list of the localized event names
for the specified language.
:param lang: The language to query the names for.
:return: A dictionary where the key is the event id and the value is the
name of the event in the specified language. | [
"This",
"resource",
"returns",
"an",
"unordered",
"list",
"of",
"the",
"localized",
"event",
"names",
"for",
"the",
"specified",
"language",
"."
] | 5543a78e6e3ed0573b7e84c142c44004b4779eac | https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/events.py#L7-L18 | train | 57,211 |
hackedd/gw2api | gw2api/events.py | event_details | def event_details(event_id=None, lang="en"):
"""This resource returns static details about available events.
:param event_id: Only list this event.
:param lang: Show localized texts in the specified language.
The response is a dictionary where the key is the event id, and the value
is a dictionary... | python | def event_details(event_id=None, lang="en"):
"""This resource returns static details about available events.
:param event_id: Only list this event.
:param lang: Show localized texts in the specified language.
The response is a dictionary where the key is the event id, and the value
is a dictionary... | [
"def",
"event_details",
"(",
"event_id",
"=",
"None",
",",
"lang",
"=",
"\"en\"",
")",
":",
"if",
"event_id",
":",
"cache_name",
"=",
"\"event_details.%s.%s.json\"",
"%",
"(",
"event_id",
",",
"lang",
")",
"params",
"=",
"{",
"\"event_id\"",
":",
"event_id",... | This resource returns static details about available events.
:param event_id: Only list this event.
:param lang: Show localized texts in the specified language.
The response is a dictionary where the key is the event id, and the value
is a dictionary containing the following properties:
name (str... | [
"This",
"resource",
"returns",
"static",
"details",
"about",
"available",
"events",
"."
] | 5543a78e6e3ed0573b7e84c142c44004b4779eac | https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/events.py#L21-L79 | train | 57,212 |
nuSTORM/gnomon | gnomon/MagneticField.py | WandsToroidField.PhenomModel | def PhenomModel(self, r):
"""Fit to field map
A phenomenological fit by Ryan Bayes (Glasgow) to a field map
generated by Bob Wands (FNAL). It assumes a 1 cm plate. This is dated
January 30th, 2012. Not defined for r <= 0"""
if r <= 0:
raise ValueError
fiel... | python | def PhenomModel(self, r):
"""Fit to field map
A phenomenological fit by Ryan Bayes (Glasgow) to a field map
generated by Bob Wands (FNAL). It assumes a 1 cm plate. This is dated
January 30th, 2012. Not defined for r <= 0"""
if r <= 0:
raise ValueError
fiel... | [
"def",
"PhenomModel",
"(",
"self",
",",
"r",
")",
":",
"if",
"r",
"<=",
"0",
":",
"raise",
"ValueError",
"field",
"=",
"self",
".",
"B0",
"+",
"self",
".",
"B1",
"*",
"G4",
".",
"m",
"/",
"r",
"+",
"self",
".",
"B2",
"*",
"math",
".",
"exp",
... | Fit to field map
A phenomenological fit by Ryan Bayes (Glasgow) to a field map
generated by Bob Wands (FNAL). It assumes a 1 cm plate. This is dated
January 30th, 2012. Not defined for r <= 0 | [
"Fit",
"to",
"field",
"map"
] | 7616486ecd6e26b76f677c380e62db1c0ade558a | https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/MagneticField.py#L37-L46 | train | 57,213 |
trevisanj/f311 | f311/explorer/gui/a_XExplorer.py | XExplorer.set_dir | def set_dir(self, dir_):
"""Sets directory, auto-loads, updates all GUI contents."""
self.__lock_set_dir(dir_)
self.__lock_auto_load()
self.__lock_update_table()
self.__update_info()
self.__update_window_title() | python | def set_dir(self, dir_):
"""Sets directory, auto-loads, updates all GUI contents."""
self.__lock_set_dir(dir_)
self.__lock_auto_load()
self.__lock_update_table()
self.__update_info()
self.__update_window_title() | [
"def",
"set_dir",
"(",
"self",
",",
"dir_",
")",
":",
"self",
".",
"__lock_set_dir",
"(",
"dir_",
")",
"self",
".",
"__lock_auto_load",
"(",
")",
"self",
".",
"__lock_update_table",
"(",
")",
"self",
".",
"__update_info",
"(",
")",
"self",
".",
"__update... | Sets directory, auto-loads, updates all GUI contents. | [
"Sets",
"directory",
"auto",
"-",
"loads",
"updates",
"all",
"GUI",
"contents",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XExplorer.py#L320-L327 | train | 57,214 |
trevisanj/f311 | f311/explorer/gui/a_XExplorer.py | XExplorer.__update_info | def __update_info(self):
"""Updates "visualization options" and "file info" areas."""
from f311 import explorer as ex
import f311
t = self.tableWidget
z = self.listWidgetVis
z.clear()
classes = self.__vis_classes = []
propss = self.__lock_get_current_pro... | python | def __update_info(self):
"""Updates "visualization options" and "file info" areas."""
from f311 import explorer as ex
import f311
t = self.tableWidget
z = self.listWidgetVis
z.clear()
classes = self.__vis_classes = []
propss = self.__lock_get_current_pro... | [
"def",
"__update_info",
"(",
"self",
")",
":",
"from",
"f311",
"import",
"explorer",
"as",
"ex",
"import",
"f311",
"t",
"=",
"self",
".",
"tableWidget",
"z",
"=",
"self",
".",
"listWidgetVis",
"z",
".",
"clear",
"(",
")",
"classes",
"=",
"self",
".",
... | Updates "visualization options" and "file info" areas. | [
"Updates",
"visualization",
"options",
"and",
"file",
"info",
"areas",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XExplorer.py#L454-L524 | train | 57,215 |
wuher/devil | devil/fields/fields.py | DevilField.validate | def validate(self, value):
""" This was overridden to have our own ``empty_values``. """
if value in self.empty_values and self.required:
raise ValidationError(self.error_messages['required']) | python | def validate(self, value):
""" This was overridden to have our own ``empty_values``. """
if value in self.empty_values and self.required:
raise ValidationError(self.error_messages['required']) | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
"and",
"self",
".",
"required",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"error_messages",
"[",
"'required'",
"]",
")"
] | This was overridden to have our own ``empty_values``. | [
"This",
"was",
"overridden",
"to",
"have",
"our",
"own",
"empty_values",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/fields.py#L72-L75 | train | 57,216 |
wuher/devil | devil/fields/fields.py | NestedField.clean | def clean(self, value):
""" Clean the data and validate the nested spec.
Implementation is the same as for other fields but in addition,
this will propagate the validation to the nested spec.
"""
obj = self.factory.create(value)
# todo: what if the field defines proper... | python | def clean(self, value):
""" Clean the data and validate the nested spec.
Implementation is the same as for other fields but in addition,
this will propagate the validation to the nested spec.
"""
obj = self.factory.create(value)
# todo: what if the field defines proper... | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"obj",
"=",
"self",
".",
"factory",
".",
"create",
"(",
"value",
")",
"# todo: what if the field defines properties that have any of",
"# these names:",
"if",
"obj",
":",
"del",
"obj",
".",
"fields",
"del",
... | Clean the data and validate the nested spec.
Implementation is the same as for other fields but in addition,
this will propagate the validation to the nested spec. | [
"Clean",
"the",
"data",
"and",
"validate",
"the",
"nested",
"spec",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/fields.py#L102-L128 | train | 57,217 |
wuher/devil | devil/fields/fields.py | NestedField.serialize | def serialize(self, value, entity, request):
""" Propagate to nested fields.
:returns: data dictionary or ``None`` if no fields are present.
"""
self._validate_existence(value)
self._run_validators(value)
if not value:
return value
return self.fact... | python | def serialize(self, value, entity, request):
""" Propagate to nested fields.
:returns: data dictionary or ``None`` if no fields are present.
"""
self._validate_existence(value)
self._run_validators(value)
if not value:
return value
return self.fact... | [
"def",
"serialize",
"(",
"self",
",",
"value",
",",
"entity",
",",
"request",
")",
":",
"self",
".",
"_validate_existence",
"(",
"value",
")",
"self",
".",
"_run_validators",
"(",
"value",
")",
"if",
"not",
"value",
":",
"return",
"value",
"return",
"sel... | Propagate to nested fields.
:returns: data dictionary or ``None`` if no fields are present. | [
"Propagate",
"to",
"nested",
"fields",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/fields.py#L130-L142 | train | 57,218 |
wuher/devil | devil/fields/fields.py | NestedField._run_validators | def _run_validators(self, value):
""" Execute all associated validators. """
errors = []
for v in self.validators:
try:
v(value)
except ValidationError, e:
errors.extend(e.messages)
if errors:
raise ValidationError(error... | python | def _run_validators(self, value):
""" Execute all associated validators. """
errors = []
for v in self.validators:
try:
v(value)
except ValidationError, e:
errors.extend(e.messages)
if errors:
raise ValidationError(error... | [
"def",
"_run_validators",
"(",
"self",
",",
"value",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"v",
"in",
"self",
".",
"validators",
":",
"try",
":",
"v",
"(",
"value",
")",
"except",
"ValidationError",
",",
"e",
":",
"errors",
".",
"extend",
"(",
... | Execute all associated validators. | [
"Execute",
"all",
"associated",
"validators",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/fields.py#L155-L164 | train | 57,219 |
rlepore/django-sticky-messages | stickymessages/models.py | MessageManager.get_all_active | def get_all_active(self):
"""
Get all of the active messages ordered by the active_datetime.
"""
now = timezone.now()
return self.select_related().filter(active_datetime__lte=now,
inactive_datetime__gte=now).order_by('active_datetime'... | python | def get_all_active(self):
"""
Get all of the active messages ordered by the active_datetime.
"""
now = timezone.now()
return self.select_related().filter(active_datetime__lte=now,
inactive_datetime__gte=now).order_by('active_datetime'... | [
"def",
"get_all_active",
"(",
"self",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"return",
"self",
".",
"select_related",
"(",
")",
".",
"filter",
"(",
"active_datetime__lte",
"=",
"now",
",",
"inactive_datetime__gte",
"=",
"now",
")",
".",
... | Get all of the active messages ordered by the active_datetime. | [
"Get",
"all",
"of",
"the",
"active",
"messages",
"ordered",
"by",
"the",
"active_datetime",
"."
] | 6e8c519b982c2ff6c18bc5002160ac7108320652 | https://github.com/rlepore/django-sticky-messages/blob/6e8c519b982c2ff6c18bc5002160ac7108320652/stickymessages/models.py#L8-L14 | train | 57,220 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.render_word | def render_word(self,word,size,color):
'''Creates a surface that contains a word.'''
pygame.font.init()
font = pygame.font.Font(None,size)
self.rendered_word = font.render(word,0,color)
self.word_size = font.size(word) | python | def render_word(self,word,size,color):
'''Creates a surface that contains a word.'''
pygame.font.init()
font = pygame.font.Font(None,size)
self.rendered_word = font.render(word,0,color)
self.word_size = font.size(word) | [
"def",
"render_word",
"(",
"self",
",",
"word",
",",
"size",
",",
"color",
")",
":",
"pygame",
".",
"font",
".",
"init",
"(",
")",
"font",
"=",
"pygame",
".",
"font",
".",
"Font",
"(",
"None",
",",
"size",
")",
"self",
".",
"rendered_word",
"=",
... | Creates a surface that contains a word. | [
"Creates",
"a",
"surface",
"that",
"contains",
"a",
"word",
"."
] | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L16-L21 | train | 57,221 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.plot_word | def plot_word(self,position):
'''Blits a rendered word on to the main display surface'''
posrectangle = pygame.Rect(position,self.word_size)
self.used_pos.append(posrectangle)
self.cloud.blit(self.rendered_word,position) | python | def plot_word(self,position):
'''Blits a rendered word on to the main display surface'''
posrectangle = pygame.Rect(position,self.word_size)
self.used_pos.append(posrectangle)
self.cloud.blit(self.rendered_word,position) | [
"def",
"plot_word",
"(",
"self",
",",
"position",
")",
":",
"posrectangle",
"=",
"pygame",
".",
"Rect",
"(",
"position",
",",
"self",
".",
"word_size",
")",
"self",
".",
"used_pos",
".",
"append",
"(",
"posrectangle",
")",
"self",
".",
"cloud",
".",
"b... | Blits a rendered word on to the main display surface | [
"Blits",
"a",
"rendered",
"word",
"on",
"to",
"the",
"main",
"display",
"surface"
] | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L23-L27 | train | 57,222 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.collides | def collides(self,position,size):
'''Returns True if the word collides with another plotted word.'''
word_rect = pygame.Rect(position,self.word_size)
if word_rect.collidelistall(self.used_pos) == []:
return False
else:
return True | python | def collides(self,position,size):
'''Returns True if the word collides with another plotted word.'''
word_rect = pygame.Rect(position,self.word_size)
if word_rect.collidelistall(self.used_pos) == []:
return False
else:
return True | [
"def",
"collides",
"(",
"self",
",",
"position",
",",
"size",
")",
":",
"word_rect",
"=",
"pygame",
".",
"Rect",
"(",
"position",
",",
"self",
".",
"word_size",
")",
"if",
"word_rect",
".",
"collidelistall",
"(",
"self",
".",
"used_pos",
")",
"==",
"["... | Returns True if the word collides with another plotted word. | [
"Returns",
"True",
"if",
"the",
"word",
"collides",
"with",
"another",
"plotted",
"word",
"."
] | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L29-L35 | train | 57,223 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.expand | def expand(self,delta_width,delta_height):
'''Makes the cloud surface bigger. Maintains all word positions.'''
temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height))
(self.width,self.height) = (self.width + delta_width, self.height + delta_height)
temp_surfa... | python | def expand(self,delta_width,delta_height):
'''Makes the cloud surface bigger. Maintains all word positions.'''
temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height))
(self.width,self.height) = (self.width + delta_width, self.height + delta_height)
temp_surfa... | [
"def",
"expand",
"(",
"self",
",",
"delta_width",
",",
"delta_height",
")",
":",
"temp_surface",
"=",
"pygame",
".",
"Surface",
"(",
"(",
"self",
".",
"width",
"+",
"delta_width",
",",
"self",
".",
"height",
"+",
"delta_height",
")",
")",
"(",
"self",
... | Makes the cloud surface bigger. Maintains all word positions. | [
"Makes",
"the",
"cloud",
"surface",
"bigger",
".",
"Maintains",
"all",
"word",
"positions",
"."
] | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L37-L42 | train | 57,224 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.smart_cloud | def smart_cloud(self,input,max_text_size=72,min_text_size=12,exclude_words = True):
'''Creates a word cloud using the input.
Input can be a file, directory, or text.
Set exclude_words to true if you want to eliminate words that only occur once.'''
self.exclude_words = exclude_words... | python | def smart_cloud(self,input,max_text_size=72,min_text_size=12,exclude_words = True):
'''Creates a word cloud using the input.
Input can be a file, directory, or text.
Set exclude_words to true if you want to eliminate words that only occur once.'''
self.exclude_words = exclude_words... | [
"def",
"smart_cloud",
"(",
"self",
",",
"input",
",",
"max_text_size",
"=",
"72",
",",
"min_text_size",
"=",
"12",
",",
"exclude_words",
"=",
"True",
")",
":",
"self",
".",
"exclude_words",
"=",
"exclude_words",
"if",
"isdir",
"(",
"input",
")",
":",
"se... | Creates a word cloud using the input.
Input can be a file, directory, or text.
Set exclude_words to true if you want to eliminate words that only occur once. | [
"Creates",
"a",
"word",
"cloud",
"using",
"the",
"input",
".",
"Input",
"can",
"be",
"a",
"file",
"directory",
"or",
"text",
".",
"Set",
"exclude_words",
"to",
"true",
"if",
"you",
"want",
"to",
"eliminate",
"words",
"that",
"only",
"occur",
"once",
"."
... | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L44-L58 | train | 57,225 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.directory_cloud | def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):
'''Creates a word cloud using files from a directory.
The color of the words correspond to the amount of documents the word occurs in.'''
worddict = assign_fonts(tuplecount(re... | python | def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):
'''Creates a word cloud using files from a directory.
The color of the words correspond to the amount of documents the word occurs in.'''
worddict = assign_fonts(tuplecount(re... | [
"def",
"directory_cloud",
"(",
"self",
",",
"directory",
",",
"max_text_size",
"=",
"72",
",",
"min_text_size",
"=",
"12",
",",
"expand_width",
"=",
"50",
",",
"expand_height",
"=",
"50",
",",
"max_count",
"=",
"100000",
")",
":",
"worddict",
"=",
"assign_... | Creates a word cloud using files from a directory.
The color of the words correspond to the amount of documents the word occurs in. | [
"Creates",
"a",
"word",
"cloud",
"using",
"files",
"from",
"a",
"directory",
".",
"The",
"color",
"of",
"the",
"words",
"correspond",
"to",
"the",
"amount",
"of",
"documents",
"the",
"word",
"occurs",
"in",
"."
] | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L60-L85 | train | 57,226 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.text_cloud | def text_cloud(self,text,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):
'''Creates a word cloud using plain text.'''
worddict = assign_fonts(tuplecount(text),max_text_size,min_text_size,self.exclude_words)
sorted_worddict = list(reversed(sorted(worddict.key... | python | def text_cloud(self,text,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):
'''Creates a word cloud using plain text.'''
worddict = assign_fonts(tuplecount(text),max_text_size,min_text_size,self.exclude_words)
sorted_worddict = list(reversed(sorted(worddict.key... | [
"def",
"text_cloud",
"(",
"self",
",",
"text",
",",
"max_text_size",
"=",
"72",
",",
"min_text_size",
"=",
"12",
",",
"expand_width",
"=",
"50",
",",
"expand_height",
"=",
"50",
",",
"max_count",
"=",
"100000",
")",
":",
"worddict",
"=",
"assign_fonts",
... | Creates a word cloud using plain text. | [
"Creates",
"a",
"word",
"cloud",
"using",
"plain",
"text",
"."
] | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L87-L107 | train | 57,227 |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.display | def display(self):
'''Displays the word cloud to the screen.'''
pygame.init()
self.display = pygame.display.set_mode((self.width,self.height))
self.display.blit(self.cloud,(0,0))
pygame.display.update()
while True:
for event in pygame.event.get():
... | python | def display(self):
'''Displays the word cloud to the screen.'''
pygame.init()
self.display = pygame.display.set_mode((self.width,self.height))
self.display.blit(self.cloud,(0,0))
pygame.display.update()
while True:
for event in pygame.event.get():
... | [
"def",
"display",
"(",
"self",
")",
":",
"pygame",
".",
"init",
"(",
")",
"self",
".",
"display",
"=",
"pygame",
".",
"display",
".",
"set_mode",
"(",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
")",
"self",
".",
"display",
".",
"... | Displays the word cloud to the screen. | [
"Displays",
"the",
"word",
"cloud",
"to",
"the",
"screen",
"."
] | 481d1ef428427b452a8a787999c1d4a8868a3824 | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L109-L119 | train | 57,228 |
Titan-C/slaveparticles | slaveparticles/quantum/operators.py | fermi_dist | def fermi_dist(energy, beta):
""" Fermi Dirac distribution"""
exponent = np.asarray(beta*energy).clip(-600, 600)
return 1./(np.exp(exponent) + 1) | python | def fermi_dist(energy, beta):
""" Fermi Dirac distribution"""
exponent = np.asarray(beta*energy).clip(-600, 600)
return 1./(np.exp(exponent) + 1) | [
"def",
"fermi_dist",
"(",
"energy",
",",
"beta",
")",
":",
"exponent",
"=",
"np",
".",
"asarray",
"(",
"beta",
"*",
"energy",
")",
".",
"clip",
"(",
"-",
"600",
",",
"600",
")",
"return",
"1.",
"/",
"(",
"np",
".",
"exp",
"(",
"exponent",
")",
... | Fermi Dirac distribution | [
"Fermi",
"Dirac",
"distribution"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/quantum/operators.py#L12-L15 | train | 57,229 |
Titan-C/slaveparticles | slaveparticles/quantum/operators.py | diagonalize | def diagonalize(operator):
"""diagonalizes single site Spin Hamiltonian"""
eig_values, eig_vecs = LA.eigh(operator)
emin = np.amin(eig_values)
eig_values -= emin
return eig_values, eig_vecs | python | def diagonalize(operator):
"""diagonalizes single site Spin Hamiltonian"""
eig_values, eig_vecs = LA.eigh(operator)
emin = np.amin(eig_values)
eig_values -= emin
return eig_values, eig_vecs | [
"def",
"diagonalize",
"(",
"operator",
")",
":",
"eig_values",
",",
"eig_vecs",
"=",
"LA",
".",
"eigh",
"(",
"operator",
")",
"emin",
"=",
"np",
".",
"amin",
"(",
"eig_values",
")",
"eig_values",
"-=",
"emin",
"return",
"eig_values",
",",
"eig_vecs"
] | diagonalizes single site Spin Hamiltonian | [
"diagonalizes",
"single",
"site",
"Spin",
"Hamiltonian"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/quantum/operators.py#L35-L41 | train | 57,230 |
Titan-C/slaveparticles | slaveparticles/quantum/operators.py | gf_lehmann | def gf_lehmann(eig_e, eig_states, d_dag, beta, omega, d=None):
"""Outputs the lehmann representation of the greens function
omega has to be given, as matsubara or real frequencies"""
ew = np.exp(-beta*eig_e)
zet = ew.sum()
G = np.zeros_like(omega)
basis_create = np.dot(eig_states.T, d_dag.do... | python | def gf_lehmann(eig_e, eig_states, d_dag, beta, omega, d=None):
"""Outputs the lehmann representation of the greens function
omega has to be given, as matsubara or real frequencies"""
ew = np.exp(-beta*eig_e)
zet = ew.sum()
G = np.zeros_like(omega)
basis_create = np.dot(eig_states.T, d_dag.do... | [
"def",
"gf_lehmann",
"(",
"eig_e",
",",
"eig_states",
",",
"d_dag",
",",
"beta",
",",
"omega",
",",
"d",
"=",
"None",
")",
":",
"ew",
"=",
"np",
".",
"exp",
"(",
"-",
"beta",
"*",
"eig_e",
")",
"zet",
"=",
"ew",
".",
"sum",
"(",
")",
"G",
"="... | Outputs the lehmann representation of the greens function
omega has to be given, as matsubara or real frequencies | [
"Outputs",
"the",
"lehmann",
"representation",
"of",
"the",
"greens",
"function",
"omega",
"has",
"to",
"be",
"given",
"as",
"matsubara",
"or",
"real",
"frequencies"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/quantum/operators.py#L44-L63 | train | 57,231 |
Titan-C/slaveparticles | slaveparticles/quantum/operators.py | expected_value | def expected_value(operator, eig_values, eig_states, beta):
"""Calculates the average value of an observable
it requires that states and operators have the same base"""
aux = np.einsum('i,ji,ji', np.exp(-beta*eig_values),
eig_states, operator.dot(eig_states))
return aux / partiti... | python | def expected_value(operator, eig_values, eig_states, beta):
"""Calculates the average value of an observable
it requires that states and operators have the same base"""
aux = np.einsum('i,ji,ji', np.exp(-beta*eig_values),
eig_states, operator.dot(eig_states))
return aux / partiti... | [
"def",
"expected_value",
"(",
"operator",
",",
"eig_values",
",",
"eig_states",
",",
"beta",
")",
":",
"aux",
"=",
"np",
".",
"einsum",
"(",
"'i,ji,ji'",
",",
"np",
".",
"exp",
"(",
"-",
"beta",
"*",
"eig_values",
")",
",",
"eig_states",
",",
"operator... | Calculates the average value of an observable
it requires that states and operators have the same base | [
"Calculates",
"the",
"average",
"value",
"of",
"an",
"observable",
"it",
"requires",
"that",
"states",
"and",
"operators",
"have",
"the",
"same",
"base"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/quantum/operators.py#L66-L72 | train | 57,232 |
trevisanj/a99 | a99/gui/errorcollector.py | Occurrence.get_plain_text | def get_plain_text(self):
"""Returns a list"""
_msg = self.message if self.message is not None else [""]
msg = _msg if isinstance(_msg, list) else [_msg]
line = "" if not self.line else ", line {}".format(self.line)
ret = ["{} found in file '{}'{}::".format(self.type.capital... | python | def get_plain_text(self):
"""Returns a list"""
_msg = self.message if self.message is not None else [""]
msg = _msg if isinstance(_msg, list) else [_msg]
line = "" if not self.line else ", line {}".format(self.line)
ret = ["{} found in file '{}'{}::".format(self.type.capital... | [
"def",
"get_plain_text",
"(",
"self",
")",
":",
"_msg",
"=",
"self",
".",
"message",
"if",
"self",
".",
"message",
"is",
"not",
"None",
"else",
"[",
"\"\"",
"]",
"msg",
"=",
"_msg",
"if",
"isinstance",
"(",
"_msg",
",",
"list",
")",
"else",
"[",
"_... | Returns a list | [
"Returns",
"a",
"list"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/errorcollector.py#L23-L32 | train | 57,233 |
trevisanj/a99 | a99/gui/errorcollector.py | ErrorCollector.get_plain_text | def get_plain_text(self):
"""Returns a list of strings"""
ret = []
for occ in self.occurrences:
ret.extend(occ.get_plain_text())
return ret | python | def get_plain_text(self):
"""Returns a list of strings"""
ret = []
for occ in self.occurrences:
ret.extend(occ.get_plain_text())
return ret | [
"def",
"get_plain_text",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"occ",
"in",
"self",
".",
"occurrences",
":",
"ret",
".",
"extend",
"(",
"occ",
".",
"get_plain_text",
"(",
")",
")",
"return",
"ret"
] | Returns a list of strings | [
"Returns",
"a",
"list",
"of",
"strings"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/errorcollector.py#L96-L101 | train | 57,234 |
trevisanj/a99 | a99/fileio.py | crunch_dir | def crunch_dir(name, n=50):
"""Puts "..." in the middle of a directory name if lengh > n."""
if len(name) > n + 3:
name = "..." + name[-n:]
return name | python | def crunch_dir(name, n=50):
"""Puts "..." in the middle of a directory name if lengh > n."""
if len(name) > n + 3:
name = "..." + name[-n:]
return name | [
"def",
"crunch_dir",
"(",
"name",
",",
"n",
"=",
"50",
")",
":",
"if",
"len",
"(",
"name",
")",
">",
"n",
"+",
"3",
":",
"name",
"=",
"\"...\"",
"+",
"name",
"[",
"-",
"n",
":",
"]",
"return",
"name"
] | Puts "..." in the middle of a directory name if lengh > n. | [
"Puts",
"...",
"in",
"the",
"middle",
"of",
"a",
"directory",
"name",
"if",
"lengh",
">",
"n",
"."
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/fileio.py#L32-L36 | train | 57,235 |
trevisanj/f311 | f311/explorer/gui/a_XFileMainWindow.py | XFileMainWindowBase._add_log_tab | def _add_log_tab(self):
"""Adds element to pages and new tab"""
# text_tab = "Log (Alt+&{})".format(len(self.pages)+1)
text_tab = "Log"
self.pages.append(MyPage(text_tab=text_tab))
# ### Log tab
te = self.textEdit_log = self.keep_ref(QTextEdit())
te.s... | python | def _add_log_tab(self):
"""Adds element to pages and new tab"""
# text_tab = "Log (Alt+&{})".format(len(self.pages)+1)
text_tab = "Log"
self.pages.append(MyPage(text_tab=text_tab))
# ### Log tab
te = self.textEdit_log = self.keep_ref(QTextEdit())
te.s... | [
"def",
"_add_log_tab",
"(",
"self",
")",
":",
"# text_tab = \"Log (Alt+&{})\".format(len(self.pages)+1)\r",
"text_tab",
"=",
"\"Log\"",
"self",
".",
"pages",
".",
"append",
"(",
"MyPage",
"(",
"text_tab",
"=",
"text_tab",
")",
")",
"# ### Log tab\r",
"te",
"=",
"s... | Adds element to pages and new tab | [
"Adds",
"element",
"to",
"pages",
"and",
"new",
"tab"
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XFileMainWindow.py#L165-L176 | train | 57,236 |
trevisanj/f311 | f311/explorer/gui/a_XFileMainWindow.py | XFileMainWindowBase.keyPressEvent | def keyPressEvent(self, evt):
"""This handles Ctrl+PageUp, Ctrl+PageDown, Ctrl+Tab, Ctrl+Shift+Tab"""
incr = 0
if evt.modifiers() == Qt.ControlModifier:
n = self.tabWidget.count()
if evt.key() in [Qt.Key_PageUp, Qt.Key_Backtab]:
incr = -1
... | python | def keyPressEvent(self, evt):
"""This handles Ctrl+PageUp, Ctrl+PageDown, Ctrl+Tab, Ctrl+Shift+Tab"""
incr = 0
if evt.modifiers() == Qt.ControlModifier:
n = self.tabWidget.count()
if evt.key() in [Qt.Key_PageUp, Qt.Key_Backtab]:
incr = -1
... | [
"def",
"keyPressEvent",
"(",
"self",
",",
"evt",
")",
":",
"incr",
"=",
"0",
"if",
"evt",
".",
"modifiers",
"(",
")",
"==",
"Qt",
".",
"ControlModifier",
":",
"n",
"=",
"self",
".",
"tabWidget",
".",
"count",
"(",
")",
"if",
"evt",
".",
"key",
"(... | This handles Ctrl+PageUp, Ctrl+PageDown, Ctrl+Tab, Ctrl+Shift+Tab | [
"This",
"handles",
"Ctrl",
"+",
"PageUp",
"Ctrl",
"+",
"PageDown",
"Ctrl",
"+",
"Tab",
"Ctrl",
"+",
"Shift",
"+",
"Tab"
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XFileMainWindow.py#L252-L267 | train | 57,237 |
trevisanj/f311 | f311/explorer/gui/a_XFileMainWindow.py | XFileMainWindowBase._on_changed | def _on_changed(self):
"""Slot for changed events"""
page = self._get_page()
if not page.flag_autosave:
page.flag_changed = True
self._update_gui_text_tabs() | python | def _on_changed(self):
"""Slot for changed events"""
page = self._get_page()
if not page.flag_autosave:
page.flag_changed = True
self._update_gui_text_tabs() | [
"def",
"_on_changed",
"(",
"self",
")",
":",
"page",
"=",
"self",
".",
"_get_page",
"(",
")",
"if",
"not",
"page",
".",
"flag_autosave",
":",
"page",
".",
"flag_changed",
"=",
"True",
"self",
".",
"_update_gui_text_tabs",
"(",
")"
] | Slot for changed events | [
"Slot",
"for",
"changed",
"events"
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XFileMainWindow.py#L329-L334 | train | 57,238 |
trevisanj/f311 | f311/explorer/gui/a_XFileMainWindow.py | XFileMainWindowBase._update_gui_text_tabs | def _update_gui_text_tabs(self):
"""Iterates through pages to update tab texts"""
for index, page in enumerate(self.pages):
self.tabWidget.setTabText(index, "{} (Alt+&{}){}".format(page.text_tab, index+1, (" (changed)" if page.flag_changed else ""))) | python | def _update_gui_text_tabs(self):
"""Iterates through pages to update tab texts"""
for index, page in enumerate(self.pages):
self.tabWidget.setTabText(index, "{} (Alt+&{}){}".format(page.text_tab, index+1, (" (changed)" if page.flag_changed else ""))) | [
"def",
"_update_gui_text_tabs",
"(",
"self",
")",
":",
"for",
"index",
",",
"page",
"in",
"enumerate",
"(",
"self",
".",
"pages",
")",
":",
"self",
".",
"tabWidget",
".",
"setTabText",
"(",
"index",
",",
"\"{} (Alt+&{}){}\"",
".",
"format",
"(",
"page",
... | Iterates through pages to update tab texts | [
"Iterates",
"through",
"pages",
"to",
"update",
"tab",
"texts"
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XFileMainWindow.py#L355-L358 | train | 57,239 |
trevisanj/f311 | f311/explorer/gui/a_XFileMainWindow.py | XFileMainWindowBase.__generic_save | def __generic_save(self):
"""Returns False if user has cancelled a "save as" operation, otherwise True."""
page = self._get_page()
f = page.editor.f
if not f:
return True
if not page.editor.flag_valid:
a99.show_error("Cannot save, {0!s} has error(s)... | python | def __generic_save(self):
"""Returns False if user has cancelled a "save as" operation, otherwise True."""
page = self._get_page()
f = page.editor.f
if not f:
return True
if not page.editor.flag_valid:
a99.show_error("Cannot save, {0!s} has error(s)... | [
"def",
"__generic_save",
"(",
"self",
")",
":",
"page",
"=",
"self",
".",
"_get_page",
"(",
")",
"f",
"=",
"page",
".",
"editor",
".",
"f",
"if",
"not",
"f",
":",
"return",
"True",
"if",
"not",
"page",
".",
"editor",
".",
"flag_valid",
":",
"a99",
... | Returns False if user has cancelled a "save as" operation, otherwise True. | [
"Returns",
"False",
"if",
"user",
"has",
"cancelled",
"a",
"save",
"as",
"operation",
"otherwise",
"True",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XFileMainWindow.py#L373-L393 | train | 57,240 |
trevisanj/f311 | f311/explorer/gui/a_XFileMainWindow.py | XFileMainWindowBase.__generic_save_as | def __generic_save_as(self):
"""Returns False if user has cancelled operation, otherwise True."""
page = self._get_page()
if not page.editor.f:
return True
if page.editor.f.filename:
d = page.editor.f.filename
else:
d = os.path.join(sel... | python | def __generic_save_as(self):
"""Returns False if user has cancelled operation, otherwise True."""
page = self._get_page()
if not page.editor.f:
return True
if page.editor.f.filename:
d = page.editor.f.filename
else:
d = os.path.join(sel... | [
"def",
"__generic_save_as",
"(",
"self",
")",
":",
"page",
"=",
"self",
".",
"_get_page",
"(",
")",
"if",
"not",
"page",
".",
"editor",
".",
"f",
":",
"return",
"True",
"if",
"page",
".",
"editor",
".",
"f",
".",
"filename",
":",
"d",
"=",
"page",
... | Returns False if user has cancelled operation, otherwise True. | [
"Returns",
"False",
"if",
"user",
"has",
"cancelled",
"operation",
"otherwise",
"True",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XFileMainWindow.py#L395-L414 | train | 57,241 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | Cluster._start_nodes_sequentially | def _start_nodes_sequentially(self, nodes):
"""
Start the nodes sequentially without forking.
Return set of nodes that were actually started.
"""
started_nodes = set()
for node in copy(nodes):
started = self._start_node(node)
if started:
... | python | def _start_nodes_sequentially(self, nodes):
"""
Start the nodes sequentially without forking.
Return set of nodes that were actually started.
"""
started_nodes = set()
for node in copy(nodes):
started = self._start_node(node)
if started:
... | [
"def",
"_start_nodes_sequentially",
"(",
"self",
",",
"nodes",
")",
":",
"started_nodes",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"copy",
"(",
"nodes",
")",
":",
"started",
"=",
"self",
".",
"_start_node",
"(",
"node",
")",
"if",
"started",
":",
"st... | Start the nodes sequentially without forking.
Return set of nodes that were actually started. | [
"Start",
"the",
"nodes",
"sequentially",
"without",
"forking",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L415-L428 | train | 57,242 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | Cluster._start_nodes_parallel | def _start_nodes_parallel(self, nodes, max_thread_pool_size):
"""
Start the nodes using a pool of multiprocessing threads for speed-up.
Return set of nodes that were actually started.
"""
# Create one thread for each node to start
thread_pool_size = min(len(nodes), max_t... | python | def _start_nodes_parallel(self, nodes, max_thread_pool_size):
"""
Start the nodes using a pool of multiprocessing threads for speed-up.
Return set of nodes that were actually started.
"""
# Create one thread for each node to start
thread_pool_size = min(len(nodes), max_t... | [
"def",
"_start_nodes_parallel",
"(",
"self",
",",
"nodes",
",",
"max_thread_pool_size",
")",
":",
"# Create one thread for each node to start",
"thread_pool_size",
"=",
"min",
"(",
"len",
"(",
"nodes",
")",
",",
"max_thread_pool_size",
")",
"thread_pool",
"=",
"Pool",... | Start the nodes using a pool of multiprocessing threads for speed-up.
Return set of nodes that were actually started. | [
"Start",
"the",
"nodes",
"using",
"a",
"pool",
"of",
"multiprocessing",
"threads",
"for",
"speed",
"-",
"up",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L430-L474 | train | 57,243 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | Cluster._start_node | def _start_node(node):
"""
Start the given node VM.
:return: bool -- True on success, False otherwise
"""
log.debug("_start_node: working on node `%s`", node.name)
# FIXME: the following check is not optimal yet. When a node is still
# in a starting state, it wil... | python | def _start_node(node):
"""
Start the given node VM.
:return: bool -- True on success, False otherwise
"""
log.debug("_start_node: working on node `%s`", node.name)
# FIXME: the following check is not optimal yet. When a node is still
# in a starting state, it wil... | [
"def",
"_start_node",
"(",
"node",
")",
":",
"log",
".",
"debug",
"(",
"\"_start_node: working on node `%s`\"",
",",
"node",
".",
"name",
")",
"# FIXME: the following check is not optimal yet. When a node is still",
"# in a starting state, it will start another node here, since the... | Start the given node VM.
:return: bool -- True on success, False otherwise | [
"Start",
"the",
"given",
"node",
"VM",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L477-L499 | train | 57,244 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | Cluster.get_all_nodes | def get_all_nodes(self):
"""Returns a list of all nodes in this cluster as a mixed list of
different node kinds.
:return: list of :py:class:`Node`
"""
nodes = self.nodes.values()
if nodes:
return reduce(operator.add, nodes, list())
else:
r... | python | def get_all_nodes(self):
"""Returns a list of all nodes in this cluster as a mixed list of
different node kinds.
:return: list of :py:class:`Node`
"""
nodes = self.nodes.values()
if nodes:
return reduce(operator.add, nodes, list())
else:
r... | [
"def",
"get_all_nodes",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"nodes",
".",
"values",
"(",
")",
"if",
"nodes",
":",
"return",
"reduce",
"(",
"operator",
".",
"add",
",",
"nodes",
",",
"list",
"(",
")",
")",
"else",
":",
"return",
"[",
... | Returns a list of all nodes in this cluster as a mixed list of
different node kinds.
:return: list of :py:class:`Node` | [
"Returns",
"a",
"list",
"of",
"all",
"nodes",
"in",
"this",
"cluster",
"as",
"a",
"mixed",
"list",
"of",
"different",
"node",
"kinds",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L641-L651 | train | 57,245 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | Cluster.get_frontend_node | def get_frontend_node(self):
"""Returns the first node of the class specified in the
configuration file as `ssh_to`, or the first node of
the first class in alphabetic order.
:return: :py:class:`Node`
:raise: :py:class:`elasticluster.exceptions.NodeNotFound` if no
... | python | def get_frontend_node(self):
"""Returns the first node of the class specified in the
configuration file as `ssh_to`, or the first node of
the first class in alphabetic order.
:return: :py:class:`Node`
:raise: :py:class:`elasticluster.exceptions.NodeNotFound` if no
... | [
"def",
"get_frontend_node",
"(",
"self",
")",
":",
"if",
"self",
".",
"ssh_to",
":",
"if",
"self",
".",
"ssh_to",
"in",
"self",
".",
"nodes",
":",
"cls",
"=",
"self",
".",
"nodes",
"[",
"self",
".",
"ssh_to",
"]",
"if",
"cls",
":",
"return",
"cls",... | Returns the first node of the class specified in the
configuration file as `ssh_to`, or the first node of
the first class in alphabetic order.
:return: :py:class:`Node`
:raise: :py:class:`elasticluster.exceptions.NodeNotFound` if no
valid frontend node is found | [
"Returns",
"the",
"first",
"node",
"of",
"the",
"class",
"specified",
"in",
"the",
"configuration",
"file",
"as",
"ssh_to",
"or",
"the",
"first",
"node",
"of",
"the",
"first",
"class",
"in",
"alphabetic",
"order",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L731-L762 | train | 57,246 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | NodeNamingPolicy.new | def new(self, kind, **extra):
"""
Return a host name for a new node of the given kind.
The new name is formed by interpolating ``{}``-format
specifiers in the string given as ``pattern`` argument to the
class constructor. The following names can be used in the
``{}``-fo... | python | def new(self, kind, **extra):
"""
Return a host name for a new node of the given kind.
The new name is formed by interpolating ``{}``-format
specifiers in the string given as ``pattern`` argument to the
class constructor. The following names can be used in the
``{}``-fo... | [
"def",
"new",
"(",
"self",
",",
"kind",
",",
"*",
"*",
"extra",
")",
":",
"if",
"self",
".",
"_free",
"[",
"kind",
"]",
":",
"index",
"=",
"self",
".",
"_free",
"[",
"kind",
"]",
".",
"pop",
"(",
")",
"else",
":",
"self",
".",
"_top",
"[",
... | Return a host name for a new node of the given kind.
The new name is formed by interpolating ``{}``-format
specifiers in the string given as ``pattern`` argument to the
class constructor. The following names can be used in the
``{}``-format specifiers:
* ``kind`` -- the `kind`... | [
"Return",
"a",
"host",
"name",
"for",
"a",
"new",
"node",
"of",
"the",
"given",
"kind",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L933-L959 | train | 57,247 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | NodeNamingPolicy.use | def use(self, kind, name):
"""
Mark a node name as used.
"""
try:
params = self._parse(name)
index = int(params['index'], 10)
if index in self._free[kind]:
self._free[kind].remove(index)
top = self._top[kind]
if ... | python | def use(self, kind, name):
"""
Mark a node name as used.
"""
try:
params = self._parse(name)
index = int(params['index'], 10)
if index in self._free[kind]:
self._free[kind].remove(index)
top = self._top[kind]
if ... | [
"def",
"use",
"(",
"self",
",",
"kind",
",",
"name",
")",
":",
"try",
":",
"params",
"=",
"self",
".",
"_parse",
"(",
"name",
")",
"index",
"=",
"int",
"(",
"params",
"[",
"'index'",
"]",
",",
"10",
")",
"if",
"index",
"in",
"self",
".",
"_free... | Mark a node name as used. | [
"Mark",
"a",
"node",
"name",
"as",
"used",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L961-L977 | train | 57,248 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | NodeNamingPolicy.free | def free(self, kind, name):
"""
Mark a node name as no longer in use.
It could thus be recycled to name a new node.
"""
try:
params = self._parse(name)
index = int(params['index'], 10)
self._free[kind].add(index)
assert index <= se... | python | def free(self, kind, name):
"""
Mark a node name as no longer in use.
It could thus be recycled to name a new node.
"""
try:
params = self._parse(name)
index = int(params['index'], 10)
self._free[kind].add(index)
assert index <= se... | [
"def",
"free",
"(",
"self",
",",
"kind",
",",
"name",
")",
":",
"try",
":",
"params",
"=",
"self",
".",
"_parse",
"(",
"name",
")",
"index",
"=",
"int",
"(",
"params",
"[",
"'index'",
"]",
",",
"10",
")",
"self",
".",
"_free",
"[",
"kind",
"]",... | Mark a node name as no longer in use.
It could thus be recycled to name a new node. | [
"Mark",
"a",
"node",
"name",
"as",
"no",
"longer",
"in",
"use",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L979-L994 | train | 57,249 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | Node.is_alive | def is_alive(self):
"""Checks if the current node is up and running in the cloud. It
only checks the status provided by the cloud interface. Therefore a
node might be running, but not yet ready to ssh into it.
"""
running = False
if not self.instance_id:
retur... | python | def is_alive(self):
"""Checks if the current node is up and running in the cloud. It
only checks the status provided by the cloud interface. Therefore a
node might be running, but not yet ready to ssh into it.
"""
running = False
if not self.instance_id:
retur... | [
"def",
"is_alive",
"(",
"self",
")",
":",
"running",
"=",
"False",
"if",
"not",
"self",
".",
"instance_id",
":",
"return",
"False",
"try",
":",
"log",
".",
"debug",
"(",
"\"Getting information for instance %s\"",
",",
"self",
".",
"instance_id",
")",
"runnin... | Checks if the current node is up and running in the cloud. It
only checks the status provided by the cloud interface. Therefore a
node might be running, but not yet ready to ssh into it. | [
"Checks",
"if",
"the",
"current",
"node",
"is",
"up",
"and",
"running",
"in",
"the",
"cloud",
".",
"It",
"only",
"checks",
"the",
"status",
"provided",
"by",
"the",
"cloud",
"interface",
".",
"Therefore",
"a",
"node",
"might",
"be",
"running",
"but",
"no... | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L1107-L1132 | train | 57,250 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | Node.connect | def connect(self, keyfile=None):
"""Connect to the node via ssh using the paramiko library.
:return: :py:class:`paramiko.SSHClient` - ssh connection or None on
failure
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
... | python | def connect(self, keyfile=None):
"""Connect to the node via ssh using the paramiko library.
:return: :py:class:`paramiko.SSHClient` - ssh connection or None on
failure
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
... | [
"def",
"connect",
"(",
"self",
",",
"keyfile",
"=",
"None",
")",
":",
"ssh",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"ssh",
".",
"set_missing_host_key_policy",
"(",
"paramiko",
".",
"AutoAddPolicy",
"(",
")",
")",
"if",
"keyfile",
"and",
"os",
".",
... | Connect to the node via ssh using the paramiko library.
:return: :py:class:`paramiko.SSHClient` - ssh connection or None on
failure | [
"Connect",
"to",
"the",
"node",
"via",
"ssh",
"using",
"the",
"paramiko",
"library",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L1141-L1194 | train | 57,251 |
trevisanj/a99 | a99/config.py | AAConfigObj.set_item | def set_item(self, path_, value):
"""Sets item and automatically saves file"""
section, path_ = self._get_section(path_)
section[path_[-1]] = value
self.write() | python | def set_item(self, path_, value):
"""Sets item and automatically saves file"""
section, path_ = self._get_section(path_)
section[path_[-1]] = value
self.write() | [
"def",
"set_item",
"(",
"self",
",",
"path_",
",",
"value",
")",
":",
"section",
",",
"path_",
"=",
"self",
".",
"_get_section",
"(",
"path_",
")",
"section",
"[",
"path_",
"[",
"-",
"1",
"]",
"]",
"=",
"value",
"self",
".",
"write",
"(",
")"
] | Sets item and automatically saves file | [
"Sets",
"item",
"and",
"automatically",
"saves",
"file"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/config.py#L80-L84 | train | 57,252 |
CodyKochmann/generators | generators/all_subslices.py | all_subslices | def all_subslices(itr):
""" generates every possible slice that can be generated from an iterable """
assert iterable(itr), 'generators.all_subslices only accepts iterable arguments, not {}'.format(itr)
if not hasattr(itr, '__len__'): # if itr isnt materialized, make it a deque
itr = deque(itr)
... | python | def all_subslices(itr):
""" generates every possible slice that can be generated from an iterable """
assert iterable(itr), 'generators.all_subslices only accepts iterable arguments, not {}'.format(itr)
if not hasattr(itr, '__len__'): # if itr isnt materialized, make it a deque
itr = deque(itr)
... | [
"def",
"all_subslices",
"(",
"itr",
")",
":",
"assert",
"iterable",
"(",
"itr",
")",
",",
"'generators.all_subslices only accepts iterable arguments, not {}'",
".",
"format",
"(",
"itr",
")",
"if",
"not",
"hasattr",
"(",
"itr",
",",
"'__len__'",
")",
":",
"# if ... | generates every possible slice that can be generated from an iterable | [
"generates",
"every",
"possible",
"slice",
"that",
"can",
"be",
"generated",
"from",
"an",
"iterable"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/all_subslices.py#L22-L32 | train | 57,253 |
jkitzes/macroeco | macroeco/misc/format_data.py | data_read_write | def data_read_write(data_path_in, data_path_out, format_type, **kwargs):
"""
General function to read, format, and write data.
Parameters
----------
data_path_in : str
Path to the file that will be read
data_path_out : str
Path of the file that will be output
format_type : s... | python | def data_read_write(data_path_in, data_path_out, format_type, **kwargs):
"""
General function to read, format, and write data.
Parameters
----------
data_path_in : str
Path to the file that will be read
data_path_out : str
Path of the file that will be output
format_type : s... | [
"def",
"data_read_write",
"(",
"data_path_in",
",",
"data_path_out",
",",
"format_type",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"format_type",
"==",
"\"dense\"",
":",
"# Set dense defaults",
"kwargs",
"=",
"_set_dense_defaults_and_eval",
"(",
"kwargs",
")",
"# T... | General function to read, format, and write data.
Parameters
----------
data_path_in : str
Path to the file that will be read
data_path_out : str
Path of the file that will be output
format_type : str
Either 'dense', 'grid', 'columnar', or 'transect'
kwargs
Speci... | [
"General",
"function",
"to",
"read",
"format",
"and",
"write",
"data",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/misc/format_data.py#L4-L61 | train | 57,254 |
jkitzes/macroeco | macroeco/misc/format_data.py | format_dense | def format_dense(base_data, non_label_cols, **kwargs):
"""
Formats dense data type to stacked data type.
Takes in a dense data type and converts into a stacked data type.
Parameters
----------
data : DataFrame
The dense data
non_label_cols : list
A list of columns in the da... | python | def format_dense(base_data, non_label_cols, **kwargs):
"""
Formats dense data type to stacked data type.
Takes in a dense data type and converts into a stacked data type.
Parameters
----------
data : DataFrame
The dense data
non_label_cols : list
A list of columns in the da... | [
"def",
"format_dense",
"(",
"base_data",
",",
"non_label_cols",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"_set_dense_defaults_and_eval",
"(",
"kwargs",
")",
"# Stack data in columnar form.",
"indexed_data",
"=",
"base_data",
".",
"set_index",
"(",
"keys",
... | Formats dense data type to stacked data type.
Takes in a dense data type and converts into a stacked data type.
Parameters
----------
data : DataFrame
The dense data
non_label_cols : list
A list of columns in the data that are not label columns
label_col : str
Name of t... | [
"Formats",
"dense",
"data",
"type",
"to",
"stacked",
"data",
"type",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/misc/format_data.py#L64-L151 | train | 57,255 |
jkitzes/macroeco | macroeco/misc/format_data.py | _set_dense_defaults_and_eval | def _set_dense_defaults_and_eval(kwargs):
"""
Sets default values in kwargs if kwargs are not already given.
Evaluates all values using eval
Parameters
-----------
kwargs : dict
Dictionary of dense specific keyword args
Returns
-------
: dict
Default, evaluated dic... | python | def _set_dense_defaults_and_eval(kwargs):
"""
Sets default values in kwargs if kwargs are not already given.
Evaluates all values using eval
Parameters
-----------
kwargs : dict
Dictionary of dense specific keyword args
Returns
-------
: dict
Default, evaluated dic... | [
"def",
"_set_dense_defaults_and_eval",
"(",
"kwargs",
")",
":",
"kwargs",
"[",
"'delimiter'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'delimiter'",
",",
"','",
")",
"kwargs",
"[",
"'na_values'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'na_values'",
",",
"''",
... | Sets default values in kwargs if kwargs are not already given.
Evaluates all values using eval
Parameters
-----------
kwargs : dict
Dictionary of dense specific keyword args
Returns
-------
: dict
Default, evaluated dictionary | [
"Sets",
"default",
"values",
"in",
"kwargs",
"if",
"kwargs",
"are",
"not",
"already",
"given",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/misc/format_data.py#L154-L185 | train | 57,256 |
trevisanj/f311 | f311/explorer/vis/plotsp.py | plot_spectra_stacked | def plot_spectra_stacked(ss, title=None, num_rows=None, setup=_default_setup):
"""
Plots one or more stacked in subplots sharing same x-axis.
Args:
ss: list of Spectrum objects
title=None: window title
num_rows=None: (optional) number of rows for subplot grid. If not passed,
num_r... | python | def plot_spectra_stacked(ss, title=None, num_rows=None, setup=_default_setup):
"""
Plots one or more stacked in subplots sharing same x-axis.
Args:
ss: list of Spectrum objects
title=None: window title
num_rows=None: (optional) number of rows for subplot grid. If not passed,
num_r... | [
"def",
"plot_spectra_stacked",
"(",
"ss",
",",
"title",
"=",
"None",
",",
"num_rows",
"=",
"None",
",",
"setup",
"=",
"_default_setup",
")",
":",
"draw_spectra_stacked",
"(",
"ss",
",",
"title",
",",
"num_rows",
",",
"setup",
")",
"plt",
".",
"show",
"("... | Plots one or more stacked in subplots sharing same x-axis.
Args:
ss: list of Spectrum objects
title=None: window title
num_rows=None: (optional) number of rows for subplot grid. If not passed,
num_rows will be the number of plots, and the number of columns will be 1.
If passed, nu... | [
"Plots",
"one",
"or",
"more",
"stacked",
"in",
"subplots",
"sharing",
"same",
"x",
"-",
"axis",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/vis/plotsp.py#L61-L76 | train | 57,257 |
trevisanj/f311 | f311/explorer/vis/plotsp.py | plot_spectra_overlapped | def plot_spectra_overlapped(ss, title=None, setup=_default_setup):
"""
Plots one or more spectra in the same plot.
Args:
ss: list of Spectrum objects
title=None: window title
setup: PlotSpectrumSetup object
"""
plt.figure()
draw_spectra_overlapped(ss, title, setup)
plt.sh... | python | def plot_spectra_overlapped(ss, title=None, setup=_default_setup):
"""
Plots one or more spectra in the same plot.
Args:
ss: list of Spectrum objects
title=None: window title
setup: PlotSpectrumSetup object
"""
plt.figure()
draw_spectra_overlapped(ss, title, setup)
plt.sh... | [
"def",
"plot_spectra_overlapped",
"(",
"ss",
",",
"title",
"=",
"None",
",",
"setup",
"=",
"_default_setup",
")",
":",
"plt",
".",
"figure",
"(",
")",
"draw_spectra_overlapped",
"(",
"ss",
",",
"title",
",",
"setup",
")",
"plt",
".",
"show",
"(",
")"
] | Plots one or more spectra in the same plot.
Args:
ss: list of Spectrum objects
title=None: window title
setup: PlotSpectrumSetup object | [
"Plots",
"one",
"or",
"more",
"spectra",
"in",
"the",
"same",
"plot",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/vis/plotsp.py#L80-L92 | train | 57,258 |
trevisanj/f311 | f311/explorer/vis/plotsp.py | plot_spectra_pieces_pdf | def plot_spectra_pieces_pdf(ss, aint=10, pdf_filename='pieces.pdf', setup=_default_setup):
"""
Plots spectra, overlapped, in small wavelength intervals into a PDF file,
one interval per page of the PDF file.
Args:
ss: list of Spectrum objects
aint: wavelength interval for each plot
pd... | python | def plot_spectra_pieces_pdf(ss, aint=10, pdf_filename='pieces.pdf', setup=_default_setup):
"""
Plots spectra, overlapped, in small wavelength intervals into a PDF file,
one interval per page of the PDF file.
Args:
ss: list of Spectrum objects
aint: wavelength interval for each plot
pd... | [
"def",
"plot_spectra_pieces_pdf",
"(",
"ss",
",",
"aint",
"=",
"10",
",",
"pdf_filename",
"=",
"'pieces.pdf'",
",",
"setup",
"=",
"_default_setup",
")",
":",
"import",
"f311",
".",
"explorer",
"as",
"ex",
"xmin",
",",
"xmax",
",",
"ymin_",
",",
"ymax",
"... | Plots spectra, overlapped, in small wavelength intervals into a PDF file,
one interval per page of the PDF file.
Args:
ss: list of Spectrum objects
aint: wavelength interval for each plot
pdf_filename: name of output file
setup: PlotSpectrumSetup object
**Note** overrides setup.fmt... | [
"Plots",
"spectra",
"overlapped",
"in",
"small",
"wavelength",
"intervals",
"into",
"a",
"PDF",
"file",
"one",
"interval",
"per",
"page",
"of",
"the",
"PDF",
"file",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/vis/plotsp.py#L133-L184 | train | 57,259 |
trevisanj/f311 | f311/explorer/vis/plotsp.py | plot_spectra_pages_pdf | def plot_spectra_pages_pdf(ss, pdf_filename='pages.pdf', setup=_default_setup):
"""
Plots spectra into a PDF file, one spectrum per page.
Splits into several pieces of width
Args:
ss: list of Spectrum objects
pdf_filename: name of output file
"""
logger = a99.get_python_logger()
... | python | def plot_spectra_pages_pdf(ss, pdf_filename='pages.pdf', setup=_default_setup):
"""
Plots spectra into a PDF file, one spectrum per page.
Splits into several pieces of width
Args:
ss: list of Spectrum objects
pdf_filename: name of output file
"""
logger = a99.get_python_logger()
... | [
"def",
"plot_spectra_pages_pdf",
"(",
"ss",
",",
"pdf_filename",
"=",
"'pages.pdf'",
",",
"setup",
"=",
"_default_setup",
")",
":",
"logger",
"=",
"a99",
".",
"get_python_logger",
"(",
")",
"xmin",
",",
"xmax",
",",
"ymin_",
",",
"ymax",
",",
"xspan",
",",... | Plots spectra into a PDF file, one spectrum per page.
Splits into several pieces of width
Args:
ss: list of Spectrum objects
pdf_filename: name of output file | [
"Plots",
"spectra",
"into",
"a",
"PDF",
"file",
"one",
"spectrum",
"per",
"page",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/vis/plotsp.py#L187-L220 | train | 57,260 |
micha030201/aionationstates | aionationstates/wa_.py | _ProposalResolution.repeal_target | def repeal_target(self):
"""The resolution this resolution has repealed, or is attempting
to repeal.
Returns
-------
:class:`ApiQuery` of :class:`Resolution`
Raises
------
TypeError:
If the resolution doesn't repeal anything.
"""
... | python | def repeal_target(self):
"""The resolution this resolution has repealed, or is attempting
to repeal.
Returns
-------
:class:`ApiQuery` of :class:`Resolution`
Raises
------
TypeError:
If the resolution doesn't repeal anything.
"""
... | [
"def",
"repeal_target",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"category",
"==",
"'Repeal'",
":",
"raise",
"TypeError",
"(",
"\"This resolution doesn't repeal anything\"",
")",
"return",
"wa",
".",
"resolution",
"(",
"int",
"(",
"self",
".",
"option"... | The resolution this resolution has repealed, or is attempting
to repeal.
Returns
-------
:class:`ApiQuery` of :class:`Resolution`
Raises
------
TypeError:
If the resolution doesn't repeal anything. | [
"The",
"resolution",
"this",
"resolution",
"has",
"repealed",
"or",
"is",
"attempting",
"to",
"repeal",
"."
] | dc86b86d994cbab830b69ab8023601c73e778b3a | https://github.com/micha030201/aionationstates/blob/dc86b86d994cbab830b69ab8023601c73e778b3a/aionationstates/wa_.py#L68-L83 | train | 57,261 |
micha030201/aionationstates | aionationstates/wa_.py | _WAShared.resolution | def resolution(self, index):
"""Resolution with a given index.
Parameters
----------
index : int
Resolution index.
Global if this is the ``aionationstates.wa`` object, local
if this is ``aionationstates.ga`` or ``aionationstates.sc``.
Return... | python | def resolution(self, index):
"""Resolution with a given index.
Parameters
----------
index : int
Resolution index.
Global if this is the ``aionationstates.wa`` object, local
if this is ``aionationstates.ga`` or ``aionationstates.sc``.
Return... | [
"def",
"resolution",
"(",
"self",
",",
"index",
")",
":",
"@",
"api_query",
"(",
"'resolution'",
",",
"id",
"=",
"str",
"(",
"index",
")",
")",
"async",
"def",
"result",
"(",
"_",
",",
"root",
")",
":",
"elem",
"=",
"root",
".",
"find",
"(",
"'RE... | Resolution with a given index.
Parameters
----------
index : int
Resolution index.
Global if this is the ``aionationstates.wa`` object, local
if this is ``aionationstates.ga`` or ``aionationstates.sc``.
Returns
-------
:class:`ApiQue... | [
"Resolution",
"with",
"a",
"given",
"index",
"."
] | dc86b86d994cbab830b69ab8023601c73e778b3a | https://github.com/micha030201/aionationstates/blob/dc86b86d994cbab830b69ab8023601c73e778b3a/aionationstates/wa_.py#L339-L365 | train | 57,262 |
micha030201/aionationstates | aionationstates/wa_.py | _WACouncil.resolution_at_vote | async def resolution_at_vote(self, root):
"""The proposal currently being voted on.
Returns
-------
:class:`ApiQuery` of :class:`ResolutionAtVote`
:class:`ApiQuery` of None
If no resolution is currently at vote.
"""
elem = root.find('RESOLUTION')
... | python | async def resolution_at_vote(self, root):
"""The proposal currently being voted on.
Returns
-------
:class:`ApiQuery` of :class:`ResolutionAtVote`
:class:`ApiQuery` of None
If no resolution is currently at vote.
"""
elem = root.find('RESOLUTION')
... | [
"async",
"def",
"resolution_at_vote",
"(",
"self",
",",
"root",
")",
":",
"elem",
"=",
"root",
".",
"find",
"(",
"'RESOLUTION'",
")",
"if",
"elem",
":",
"resolution",
"=",
"ResolutionAtVote",
"(",
"elem",
")",
"resolution",
".",
"_council_id",
"=",
"self",... | The proposal currently being voted on.
Returns
-------
:class:`ApiQuery` of :class:`ResolutionAtVote`
:class:`ApiQuery` of None
If no resolution is currently at vote. | [
"The",
"proposal",
"currently",
"being",
"voted",
"on",
"."
] | dc86b86d994cbab830b69ab8023601c73e778b3a | https://github.com/micha030201/aionationstates/blob/dc86b86d994cbab830b69ab8023601c73e778b3a/aionationstates/wa_.py#L437-L450 | train | 57,263 |
benoitbryon/rst2rst | rst2rst/writer.py | RSTTranslator.indent | def indent(self, levels, first_line=None):
"""Increase indentation by ``levels`` levels."""
self._indentation_levels.append(levels)
self._indent_first_line.append(first_line) | python | def indent(self, levels, first_line=None):
"""Increase indentation by ``levels`` levels."""
self._indentation_levels.append(levels)
self._indent_first_line.append(first_line) | [
"def",
"indent",
"(",
"self",
",",
"levels",
",",
"first_line",
"=",
"None",
")",
":",
"self",
".",
"_indentation_levels",
".",
"append",
"(",
"levels",
")",
"self",
".",
"_indent_first_line",
".",
"append",
"(",
"first_line",
")"
] | Increase indentation by ``levels`` levels. | [
"Increase",
"indentation",
"by",
"levels",
"levels",
"."
] | 976eef709aacb1facc8dca87cf7032f01d53adfe | https://github.com/benoitbryon/rst2rst/blob/976eef709aacb1facc8dca87cf7032f01d53adfe/rst2rst/writer.py#L156-L159 | train | 57,264 |
benoitbryon/rst2rst | rst2rst/writer.py | RSTTranslator.wrap | def wrap(self, text, width=None, indent=None):
"""Return ``text`` wrapped to ``width`` and indented with ``indent``.
By default:
* ``width`` is ``self.options.wrap_length``
* ``indent`` is ``self.indentation``.
"""
width = width if width is not None else self.options.w... | python | def wrap(self, text, width=None, indent=None):
"""Return ``text`` wrapped to ``width`` and indented with ``indent``.
By default:
* ``width`` is ``self.options.wrap_length``
* ``indent`` is ``self.indentation``.
"""
width = width if width is not None else self.options.w... | [
"def",
"wrap",
"(",
"self",
",",
"text",
",",
"width",
"=",
"None",
",",
"indent",
"=",
"None",
")",
":",
"width",
"=",
"width",
"if",
"width",
"is",
"not",
"None",
"else",
"self",
".",
"options",
".",
"wrap_length",
"indent",
"=",
"indent",
"if",
... | Return ``text`` wrapped to ``width`` and indented with ``indent``.
By default:
* ``width`` is ``self.options.wrap_length``
* ``indent`` is ``self.indentation``. | [
"Return",
"text",
"wrapped",
"to",
"width",
"and",
"indented",
"with",
"indent",
"."
] | 976eef709aacb1facc8dca87cf7032f01d53adfe | https://github.com/benoitbryon/rst2rst/blob/976eef709aacb1facc8dca87cf7032f01d53adfe/rst2rst/writer.py#L171-L185 | train | 57,265 |
nuSTORM/gnomon | gnomon/DetectorConstruction.py | BoxDetectorConstruction.Construct | def Construct(self): # pylint: disable-msg=C0103
"""Construct a cuboid from a GDML file without sensitive detector"""
# Parse the GDML
self.gdml_parser.Read(self.filename)
self.world = self.gdml_parser.GetWorldVolume()
self.log.info("Materials:")
self.log.info(G4.G4Mate... | python | def Construct(self): # pylint: disable-msg=C0103
"""Construct a cuboid from a GDML file without sensitive detector"""
# Parse the GDML
self.gdml_parser.Read(self.filename)
self.world = self.gdml_parser.GetWorldVolume()
self.log.info("Materials:")
self.log.info(G4.G4Mate... | [
"def",
"Construct",
"(",
"self",
")",
":",
"# pylint: disable-msg=C0103",
"# Parse the GDML",
"self",
".",
"gdml_parser",
".",
"Read",
"(",
"self",
".",
"filename",
")",
"self",
".",
"world",
"=",
"self",
".",
"gdml_parser",
".",
"GetWorldVolume",
"(",
")",
... | Construct a cuboid from a GDML file without sensitive detector | [
"Construct",
"a",
"cuboid",
"from",
"a",
"GDML",
"file",
"without",
"sensitive",
"detector"
] | 7616486ecd6e26b76f677c380e62db1c0ade558a | https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/DetectorConstruction.py#L38-L48 | train | 57,266 |
nuSTORM/gnomon | gnomon/DetectorConstruction.py | MagIronSamplingCaloDetectorConstruction.Construct | def Construct(self): # pylint: disable-msg=C0103
"""Construct nuSTORM from a GDML file"""
# Parse the GDML
self.world = self.gdml_parser.GetWorldVolume()
# Create sensitive detector
self.sensitive_detector = ScintSD()
# Get logical volume for X view, then attach SD
... | python | def Construct(self): # pylint: disable-msg=C0103
"""Construct nuSTORM from a GDML file"""
# Parse the GDML
self.world = self.gdml_parser.GetWorldVolume()
# Create sensitive detector
self.sensitive_detector = ScintSD()
# Get logical volume for X view, then attach SD
... | [
"def",
"Construct",
"(",
"self",
")",
":",
"# pylint: disable-msg=C0103",
"# Parse the GDML",
"self",
".",
"world",
"=",
"self",
".",
"gdml_parser",
".",
"GetWorldVolume",
"(",
")",
"# Create sensitive detector",
"self",
".",
"sensitive_detector",
"=",
"ScintSD",
"(... | Construct nuSTORM from a GDML file | [
"Construct",
"nuSTORM",
"from",
"a",
"GDML",
"file"
] | 7616486ecd6e26b76f677c380e62db1c0ade558a | https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/DetectorConstruction.py#L94-L126 | train | 57,267 |
Aluriak/bubble-tools | bubbletools/validator.py | validate | def validate(bbllines:iter, *, profiling=False):
"""Yield lines of warnings and errors about input bbl lines.
profiling -- yield also info lines about input bbl file.
If bbllines is a valid file name, it will be read.
Else, it should be an iterable of bubble file lines.
"""
if isinstance(bbll... | python | def validate(bbllines:iter, *, profiling=False):
"""Yield lines of warnings and errors about input bbl lines.
profiling -- yield also info lines about input bbl file.
If bbllines is a valid file name, it will be read.
Else, it should be an iterable of bubble file lines.
"""
if isinstance(bbll... | [
"def",
"validate",
"(",
"bbllines",
":",
"iter",
",",
"*",
",",
"profiling",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"bbllines",
",",
"str",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"bbllines",
")",
":",
"# filename containing bu... | Yield lines of warnings and errors about input bbl lines.
profiling -- yield also info lines about input bbl file.
If bbllines is a valid file name, it will be read.
Else, it should be an iterable of bubble file lines. | [
"Yield",
"lines",
"of",
"warnings",
"and",
"errors",
"about",
"input",
"bbl",
"lines",
"."
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/validator.py#L11-L55 | train | 57,268 |
Aluriak/bubble-tools | bubbletools/validator.py | inclusions_validation | def inclusions_validation(tree:BubbleTree) -> iter:
"""Yield message about inclusions inconsistancies"""
# search for powernode overlapping
for one, two in it.combinations(tree.inclusions, 2):
assert len(one) == len(one.strip())
assert len(two) == len(two.strip())
one_inc = set(inclu... | python | def inclusions_validation(tree:BubbleTree) -> iter:
"""Yield message about inclusions inconsistancies"""
# search for powernode overlapping
for one, two in it.combinations(tree.inclusions, 2):
assert len(one) == len(one.strip())
assert len(two) == len(two.strip())
one_inc = set(inclu... | [
"def",
"inclusions_validation",
"(",
"tree",
":",
"BubbleTree",
")",
"->",
"iter",
":",
"# search for powernode overlapping",
"for",
"one",
",",
"two",
"in",
"it",
".",
"combinations",
"(",
"tree",
".",
"inclusions",
",",
"2",
")",
":",
"assert",
"len",
"(",... | Yield message about inclusions inconsistancies | [
"Yield",
"message",
"about",
"inclusions",
"inconsistancies"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/validator.py#L58-L99 | train | 57,269 |
Aluriak/bubble-tools | bubbletools/validator.py | mergeability_validation | def mergeability_validation(tree:BubbleTree) -> iter:
"""Yield message about mergables powernodes"""
def gen_warnings(one, two, inc_message:str) -> [str]:
"Yield the warning for given (power)nodes if necessary"
nodetype = ''
if tree.inclusions[one] and tree.inclusions[two]:
n... | python | def mergeability_validation(tree:BubbleTree) -> iter:
"""Yield message about mergables powernodes"""
def gen_warnings(one, two, inc_message:str) -> [str]:
"Yield the warning for given (power)nodes if necessary"
nodetype = ''
if tree.inclusions[one] and tree.inclusions[two]:
n... | [
"def",
"mergeability_validation",
"(",
"tree",
":",
"BubbleTree",
")",
"->",
"iter",
":",
"def",
"gen_warnings",
"(",
"one",
",",
"two",
",",
"inc_message",
":",
"str",
")",
"->",
"[",
"str",
"]",
":",
"\"Yield the warning for given (power)nodes if necessary\"",
... | Yield message about mergables powernodes | [
"Yield",
"message",
"about",
"mergables",
"powernodes"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/validator.py#L120-L139 | train | 57,270 |
hackedd/gw2api | gw2api/guild.py | guild_details | def guild_details(guild_id=None, name=None):
"""This resource returns details about a guild.
:param guild_id: The guild id to query for.
:param name: The guild name to query for.
*Note: Only one parameter is required; if both are set, the guild Id takes
precedence and a warning will be logged.*
... | python | def guild_details(guild_id=None, name=None):
"""This resource returns details about a guild.
:param guild_id: The guild id to query for.
:param name: The guild name to query for.
*Note: Only one parameter is required; if both are set, the guild Id takes
precedence and a warning will be logged.*
... | [
"def",
"guild_details",
"(",
"guild_id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"guild_id",
"and",
"name",
":",
"warnings",
".",
"warn",
"(",
"\"both guild_id and name are specified, \"",
"\"name will be ignored\"",
")",
"if",
"guild_id",
":",
"p... | This resource returns details about a guild.
:param guild_id: The guild id to query for.
:param name: The guild name to query for.
*Note: Only one parameter is required; if both are set, the guild Id takes
precedence and a warning will be logged.*
The response is a dictionary with the following k... | [
"This",
"resource",
"returns",
"details",
"about",
"a",
"guild",
"."
] | 5543a78e6e3ed0573b7e84c142c44004b4779eac | https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/guild.py#L9-L68 | train | 57,271 |
CodyKochmann/generators | generators/chunks.py | chunks | def chunks(stream, chunk_size, output_type=tuple):
''' returns chunks of a stream '''
assert iterable(stream), 'chunks needs stream to be iterable'
assert (isinstance(chunk_size, int) and chunk_size > 0) or callable(chunk_size), 'chunks needs chunk_size to be a positive int or callable'
assert callable(... | python | def chunks(stream, chunk_size, output_type=tuple):
''' returns chunks of a stream '''
assert iterable(stream), 'chunks needs stream to be iterable'
assert (isinstance(chunk_size, int) and chunk_size > 0) or callable(chunk_size), 'chunks needs chunk_size to be a positive int or callable'
assert callable(... | [
"def",
"chunks",
"(",
"stream",
",",
"chunk_size",
",",
"output_type",
"=",
"tuple",
")",
":",
"assert",
"iterable",
"(",
"stream",
")",
",",
"'chunks needs stream to be iterable'",
"assert",
"(",
"isinstance",
"(",
"chunk_size",
",",
"int",
")",
"and",
"chunk... | returns chunks of a stream | [
"returns",
"chunks",
"of",
"a",
"stream"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/chunks.py#L20-L40 | train | 57,272 |
wuher/devil | devil/util.py | get_charset | def get_charset(request):
""" Extract charset from the content type
"""
content_type = request.META.get('CONTENT_TYPE', None)
if content_type:
return extract_charset(content_type) if content_type else None
else:
return None | python | def get_charset(request):
""" Extract charset from the content type
"""
content_type = request.META.get('CONTENT_TYPE', None)
if content_type:
return extract_charset(content_type) if content_type else None
else:
return None | [
"def",
"get_charset",
"(",
"request",
")",
":",
"content_type",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'CONTENT_TYPE'",
",",
"None",
")",
"if",
"content_type",
":",
"return",
"extract_charset",
"(",
"content_type",
")",
"if",
"content_type",
"else",
... | Extract charset from the content type | [
"Extract",
"charset",
"from",
"the",
"content",
"type"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/util.py#L48-L56 | train | 57,273 |
wuher/devil | devil/util.py | parse_accept_header | def parse_accept_header(accept):
""" Parse the Accept header
todo: memoize
:returns: list with pairs of (media_type, q_value), ordered by q
values.
"""
def parse_media_range(accept_item):
""" Parse media range and subtype """
return accept_item.split('/', 1)
def comparat... | python | def parse_accept_header(accept):
""" Parse the Accept header
todo: memoize
:returns: list with pairs of (media_type, q_value), ordered by q
values.
"""
def parse_media_range(accept_item):
""" Parse media range and subtype """
return accept_item.split('/', 1)
def comparat... | [
"def",
"parse_accept_header",
"(",
"accept",
")",
":",
"def",
"parse_media_range",
"(",
"accept_item",
")",
":",
"\"\"\" Parse media range and subtype \"\"\"",
"return",
"accept_item",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"def",
"comparator",
"(",
"a",
",",
... | Parse the Accept header
todo: memoize
:returns: list with pairs of (media_type, q_value), ordered by q
values. | [
"Parse",
"the",
"Accept",
"header"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/util.py#L59-L112 | train | 57,274 |
openstack/stacktach-winchester | winchester/db/interface.py | DBInterface.in_session | def in_session(self):
"""Provide a session scope around a series of operations."""
session = self.get_session()
try:
yield session
session.commit()
except IntegrityError:
session.rollback()
raise DuplicateError("Duplicate unique value detec... | python | def in_session(self):
"""Provide a session scope around a series of operations."""
session = self.get_session()
try:
yield session
session.commit()
except IntegrityError:
session.rollback()
raise DuplicateError("Duplicate unique value detec... | [
"def",
"in_session",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"get_session",
"(",
")",
"try",
":",
"yield",
"session",
"session",
".",
"commit",
"(",
")",
"except",
"IntegrityError",
":",
"session",
".",
"rollback",
"(",
")",
"raise",
"Duplica... | Provide a session scope around a series of operations. | [
"Provide",
"a",
"session",
"scope",
"around",
"a",
"series",
"of",
"operations",
"."
] | 54f3ffc4a8fd84b6fb29ad9b65adb018e8927956 | https://github.com/openstack/stacktach-winchester/blob/54f3ffc4a8fd84b6fb29ad9b65adb018e8927956/winchester/db/interface.py#L111-L129 | train | 57,275 |
robinagist/ezo | ezo/core/tm_utils.py | EzoABCI.info | def info(self, req) -> ResponseInfo:
"""
Since this will always respond with height=0, Tendermint
will resync this app from the begining
"""
r = ResponseInfo()
r.version = "1.0"
r.last_block_height = 0
r.last_block_app_hash = b''
return r | python | def info(self, req) -> ResponseInfo:
"""
Since this will always respond with height=0, Tendermint
will resync this app from the begining
"""
r = ResponseInfo()
r.version = "1.0"
r.last_block_height = 0
r.last_block_app_hash = b''
return r | [
"def",
"info",
"(",
"self",
",",
"req",
")",
"->",
"ResponseInfo",
":",
"r",
"=",
"ResponseInfo",
"(",
")",
"r",
".",
"version",
"=",
"\"1.0\"",
"r",
".",
"last_block_height",
"=",
"0",
"r",
".",
"last_block_app_hash",
"=",
"b''",
"return",
"r"
] | Since this will always respond with height=0, Tendermint
will resync this app from the begining | [
"Since",
"this",
"will",
"always",
"respond",
"with",
"height",
"=",
"0",
"Tendermint",
"will",
"resync",
"this",
"app",
"from",
"the",
"begining"
] | fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986 | https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/tm_utils.py#L34-L43 | train | 57,276 |
robinagist/ezo | ezo/core/tm_utils.py | EzoABCI.check_tx | def check_tx(self, tx) -> ResponseCheckTx:
"""
Validate the Tx before entry into the mempool
Checks the txs are submitted in order 1,2,3...
If not an order, a non-zero code is returned and the tx
will be dropped.
"""
value = decode_number(tx)
if not value ... | python | def check_tx(self, tx) -> ResponseCheckTx:
"""
Validate the Tx before entry into the mempool
Checks the txs are submitted in order 1,2,3...
If not an order, a non-zero code is returned and the tx
will be dropped.
"""
value = decode_number(tx)
if not value ... | [
"def",
"check_tx",
"(",
"self",
",",
"tx",
")",
"->",
"ResponseCheckTx",
":",
"value",
"=",
"decode_number",
"(",
"tx",
")",
"if",
"not",
"value",
"==",
"(",
"self",
".",
"txCount",
"+",
"1",
")",
":",
"# respond with non-zero code",
"return",
"ResponseChe... | Validate the Tx before entry into the mempool
Checks the txs are submitted in order 1,2,3...
If not an order, a non-zero code is returned and the tx
will be dropped. | [
"Validate",
"the",
"Tx",
"before",
"entry",
"into",
"the",
"mempool",
"Checks",
"the",
"txs",
"are",
"submitted",
"in",
"order",
"1",
"2",
"3",
"...",
"If",
"not",
"an",
"order",
"a",
"non",
"-",
"zero",
"code",
"is",
"returned",
"and",
"the",
"tx",
... | fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986 | https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/tm_utils.py#L51-L62 | train | 57,277 |
robinagist/ezo | ezo/core/tm_utils.py | EzoABCI.query | def query(self, req) -> ResponseQuery:
"""Return the last tx count"""
v = encode_number(self.txCount)
return ResponseQuery(code=CodeTypeOk, value=v, height=self.last_block_height) | python | def query(self, req) -> ResponseQuery:
"""Return the last tx count"""
v = encode_number(self.txCount)
return ResponseQuery(code=CodeTypeOk, value=v, height=self.last_block_height) | [
"def",
"query",
"(",
"self",
",",
"req",
")",
"->",
"ResponseQuery",
":",
"v",
"=",
"encode_number",
"(",
"self",
".",
"txCount",
")",
"return",
"ResponseQuery",
"(",
"code",
"=",
"CodeTypeOk",
",",
"value",
"=",
"v",
",",
"height",
"=",
"self",
".",
... | Return the last tx count | [
"Return",
"the",
"last",
"tx",
"count"
] | fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986 | https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/tm_utils.py#L70-L73 | train | 57,278 |
robinagist/ezo | ezo/core/tm_utils.py | EzoABCI.commit | def commit(self) -> ResponseCommit:
"""Return the current encode state value to tendermint"""
hash = struct.pack('>Q', self.txCount)
return ResponseCommit(data=hash) | python | def commit(self) -> ResponseCommit:
"""Return the current encode state value to tendermint"""
hash = struct.pack('>Q', self.txCount)
return ResponseCommit(data=hash) | [
"def",
"commit",
"(",
"self",
")",
"->",
"ResponseCommit",
":",
"hash",
"=",
"struct",
".",
"pack",
"(",
"'>Q'",
",",
"self",
".",
"txCount",
")",
"return",
"ResponseCommit",
"(",
"data",
"=",
"hash",
")"
] | Return the current encode state value to tendermint | [
"Return",
"the",
"current",
"encode",
"state",
"value",
"to",
"tendermint"
] | fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986 | https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/tm_utils.py#L75-L78 | train | 57,279 |
chengsoonong/wib | wib/cli.py | track | def track(context, file_names):
"""Keep track of each file in list file_names.
Tracking does not create or delete the actual file, it only tells the
version control system whether to maintain versions (to keep track) of
the file.
"""
context.obj.find_repo_type()
for fn in file_names:
... | python | def track(context, file_names):
"""Keep track of each file in list file_names.
Tracking does not create or delete the actual file, it only tells the
version control system whether to maintain versions (to keep track) of
the file.
"""
context.obj.find_repo_type()
for fn in file_names:
... | [
"def",
"track",
"(",
"context",
",",
"file_names",
")",
":",
"context",
".",
"obj",
".",
"find_repo_type",
"(",
")",
"for",
"fn",
"in",
"file_names",
":",
"context",
".",
"obj",
".",
"call",
"(",
"[",
"context",
".",
"obj",
".",
"vc_name",
",",
"'add... | Keep track of each file in list file_names.
Tracking does not create or delete the actual file, it only tells the
version control system whether to maintain versions (to keep track) of
the file. | [
"Keep",
"track",
"of",
"each",
"file",
"in",
"list",
"file_names",
"."
] | ca701ed72cd9f23a8e887f72f36c0fb0af42ef70 | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L58-L67 | train | 57,280 |
chengsoonong/wib | wib/cli.py | untrack | def untrack(context, file_names):
"""Forget about tracking each file in the list file_names
Tracking does not create or delete the actual file, it only tells the
version control system whether to maintain versions (to keep track) of
the file.
"""
context.obj.find_repo_type()
for fn in file_... | python | def untrack(context, file_names):
"""Forget about tracking each file in the list file_names
Tracking does not create or delete the actual file, it only tells the
version control system whether to maintain versions (to keep track) of
the file.
"""
context.obj.find_repo_type()
for fn in file_... | [
"def",
"untrack",
"(",
"context",
",",
"file_names",
")",
":",
"context",
".",
"obj",
".",
"find_repo_type",
"(",
")",
"for",
"fn",
"in",
"file_names",
":",
"if",
"context",
".",
"obj",
".",
"vc_name",
"==",
"'git'",
":",
"context",
".",
"obj",
".",
... | Forget about tracking each file in the list file_names
Tracking does not create or delete the actual file, it only tells the
version control system whether to maintain versions (to keep track) of
the file. | [
"Forget",
"about",
"tracking",
"each",
"file",
"in",
"the",
"list",
"file_names"
] | ca701ed72cd9f23a8e887f72f36c0fb0af42ef70 | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L73-L85 | train | 57,281 |
chengsoonong/wib | wib/cli.py | commit | def commit(context, message, name):
"""Commit saved changes to the repository.
message - commit message
name - tag name
"""
context.obj.find_repo_type()
if context.obj.vc_name == 'git':
context.obj.call(['git', 'commit', '-a', '-m', message])
elif context.obj.vc_name == 'hg':
... | python | def commit(context, message, name):
"""Commit saved changes to the repository.
message - commit message
name - tag name
"""
context.obj.find_repo_type()
if context.obj.vc_name == 'git':
context.obj.call(['git', 'commit', '-a', '-m', message])
elif context.obj.vc_name == 'hg':
... | [
"def",
"commit",
"(",
"context",
",",
"message",
",",
"name",
")",
":",
"context",
".",
"obj",
".",
"find_repo_type",
"(",
")",
"if",
"context",
".",
"obj",
".",
"vc_name",
"==",
"'git'",
":",
"context",
".",
"obj",
".",
"call",
"(",
"[",
"'git'",
... | Commit saved changes to the repository.
message - commit message
name - tag name | [
"Commit",
"saved",
"changes",
"to",
"the",
"repository",
".",
"message",
"-",
"commit",
"message",
"name",
"-",
"tag",
"name"
] | ca701ed72cd9f23a8e887f72f36c0fb0af42ef70 | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L92-L105 | train | 57,282 |
chengsoonong/wib | wib/cli.py | revert | def revert(context, file_names):
"""Revert each file in the list file_names back to version in repo"""
context.obj.find_repo_type()
if len(file_names) == 0:
click.echo('No file names to checkout specified.')
click.echo('The following have changed since the last check in.')
context.in... | python | def revert(context, file_names):
"""Revert each file in the list file_names back to version in repo"""
context.obj.find_repo_type()
if len(file_names) == 0:
click.echo('No file names to checkout specified.')
click.echo('The following have changed since the last check in.')
context.in... | [
"def",
"revert",
"(",
"context",
",",
"file_names",
")",
":",
"context",
".",
"obj",
".",
"find_repo_type",
"(",
")",
"if",
"len",
"(",
"file_names",
")",
"==",
"0",
":",
"click",
".",
"echo",
"(",
"'No file names to checkout specified.'",
")",
"click",
".... | Revert each file in the list file_names back to version in repo | [
"Revert",
"each",
"file",
"in",
"the",
"list",
"file_names",
"back",
"to",
"version",
"in",
"repo"
] | ca701ed72cd9f23a8e887f72f36c0fb0af42ef70 | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L120-L131 | train | 57,283 |
chengsoonong/wib | wib/cli.py | status | def status(context):
"""See which files have changed, checked in, and uploaded"""
context.obj.find_repo_type()
context.obj.call([context.obj.vc_name, 'status']) | python | def status(context):
"""See which files have changed, checked in, and uploaded"""
context.obj.find_repo_type()
context.obj.call([context.obj.vc_name, 'status']) | [
"def",
"status",
"(",
"context",
")",
":",
"context",
".",
"obj",
".",
"find_repo_type",
"(",
")",
"context",
".",
"obj",
".",
"call",
"(",
"[",
"context",
".",
"obj",
".",
"vc_name",
",",
"'status'",
"]",
")"
] | See which files have changed, checked in, and uploaded | [
"See",
"which",
"files",
"have",
"changed",
"checked",
"in",
"and",
"uploaded"
] | ca701ed72cd9f23a8e887f72f36c0fb0af42ef70 | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L166-L169 | train | 57,284 |
chengsoonong/wib | wib/cli.py | diff | def diff(context, file_name):
"""See changes that occured since last check in"""
context.obj.find_repo_type()
if context.obj.vc_name == 'git':
context.obj.call(['git', 'diff', '--color-words',
'--ignore-space-change', file_name])
elif context.obj.vc_name == 'hg':
... | python | def diff(context, file_name):
"""See changes that occured since last check in"""
context.obj.find_repo_type()
if context.obj.vc_name == 'git':
context.obj.call(['git', 'diff', '--color-words',
'--ignore-space-change', file_name])
elif context.obj.vc_name == 'hg':
... | [
"def",
"diff",
"(",
"context",
",",
"file_name",
")",
":",
"context",
".",
"obj",
".",
"find_repo_type",
"(",
")",
"if",
"context",
".",
"obj",
".",
"vc_name",
"==",
"'git'",
":",
"context",
".",
"obj",
".",
"call",
"(",
"[",
"'git'",
",",
"'diff'",
... | See changes that occured since last check in | [
"See",
"changes",
"that",
"occured",
"since",
"last",
"check",
"in"
] | ca701ed72cd9f23a8e887f72f36c0fb0af42ef70 | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L192-L199 | train | 57,285 |
chengsoonong/wib | wib/cli.py | Repo.find_repo_type | def find_repo_type(self):
"""Check for git or hg repository"""
is_git = self.call(['git', 'rev-parse', '--is-inside-work-tree'],
devnull=True)
if is_git != 0:
if self.debug:
click.echo('not git')
is_hg = self.call(['hg', '-q', 's... | python | def find_repo_type(self):
"""Check for git or hg repository"""
is_git = self.call(['git', 'rev-parse', '--is-inside-work-tree'],
devnull=True)
if is_git != 0:
if self.debug:
click.echo('not git')
is_hg = self.call(['hg', '-q', 's... | [
"def",
"find_repo_type",
"(",
"self",
")",
":",
"is_git",
"=",
"self",
".",
"call",
"(",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'--is-inside-work-tree'",
"]",
",",
"devnull",
"=",
"True",
")",
"if",
"is_git",
"!=",
"0",
":",
"if",
"self",
".",
"debug"... | Check for git or hg repository | [
"Check",
"for",
"git",
"or",
"hg",
"repository"
] | ca701ed72cd9f23a8e887f72f36c0fb0af42ef70 | https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L31-L44 | train | 57,286 |
Cecca/lydoc | lydoc/__init__.py | main | def main():
"""The main entry point of the program"""
# Parse command line arguments
argp = _cli_argument_parser()
args = argp.parse_args()
# setup logging
logging.basicConfig(
level=args.loglevel,
format="%(levelname)s %(message)s")
console.display("Collecting documentati... | python | def main():
"""The main entry point of the program"""
# Parse command line arguments
argp = _cli_argument_parser()
args = argp.parse_args()
# setup logging
logging.basicConfig(
level=args.loglevel,
format="%(levelname)s %(message)s")
console.display("Collecting documentati... | [
"def",
"main",
"(",
")",
":",
"# Parse command line arguments",
"argp",
"=",
"_cli_argument_parser",
"(",
")",
"args",
"=",
"argp",
".",
"parse_args",
"(",
")",
"# setup logging",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"args",
".",
"loglevel",
",",
... | The main entry point of the program | [
"The",
"main",
"entry",
"point",
"of",
"the",
"program"
] | cd01dd5ed902b2574fb412c55bdc684276a88505 | https://github.com/Cecca/lydoc/blob/cd01dd5ed902b2574fb412c55bdc684276a88505/lydoc/__init__.py#L45-L85 | train | 57,287 |
blockadeio/analyst_toolbench | blockade/cli/client.py | process_ioc | def process_ioc(args):
"""Process actions related to the IOC switch."""
client = IndicatorClient.from_config()
client.set_debug(True)
if args.get:
response = client.get_indicators()
elif args.single:
response = client.add_indicators(indicators=[args.single],
... | python | def process_ioc(args):
"""Process actions related to the IOC switch."""
client = IndicatorClient.from_config()
client.set_debug(True)
if args.get:
response = client.get_indicators()
elif args.single:
response = client.add_indicators(indicators=[args.single],
... | [
"def",
"process_ioc",
"(",
"args",
")",
":",
"client",
"=",
"IndicatorClient",
".",
"from_config",
"(",
")",
"client",
".",
"set_debug",
"(",
"True",
")",
"if",
"args",
".",
"get",
":",
"response",
"=",
"client",
".",
"get_indicators",
"(",
")",
"elif",
... | Process actions related to the IOC switch. | [
"Process",
"actions",
"related",
"to",
"the",
"IOC",
"switch",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/client.py#L10-L35 | train | 57,288 |
blockadeio/analyst_toolbench | blockade/cli/client.py | process_events | def process_events(args):
"""Process actions related to events switch."""
client = EventsClient.from_config()
client.set_debug(True)
if args.get:
response = client.get_events()
elif args.flush:
response = client.flush_events()
return response | python | def process_events(args):
"""Process actions related to events switch."""
client = EventsClient.from_config()
client.set_debug(True)
if args.get:
response = client.get_events()
elif args.flush:
response = client.flush_events()
return response | [
"def",
"process_events",
"(",
"args",
")",
":",
"client",
"=",
"EventsClient",
".",
"from_config",
"(",
")",
"client",
".",
"set_debug",
"(",
"True",
")",
"if",
"args",
".",
"get",
":",
"response",
"=",
"client",
".",
"get_events",
"(",
")",
"elif",
"a... | Process actions related to events switch. | [
"Process",
"actions",
"related",
"to",
"events",
"switch",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/client.py#L38-L46 | train | 57,289 |
blockadeio/analyst_toolbench | blockade/cli/client.py | main | def main():
"""Run the code."""
parser = ArgumentParser(description="Blockade Analyst Bench")
subs = parser.add_subparsers(dest='cmd')
ioc = subs.add_parser('ioc', help="Perform actions with IOCs")
ioc.add_argument('--single', '-s', help="Send a single IOC")
ioc.add_argument('--file', '-f', hel... | python | def main():
"""Run the code."""
parser = ArgumentParser(description="Blockade Analyst Bench")
subs = parser.add_subparsers(dest='cmd')
ioc = subs.add_parser('ioc', help="Perform actions with IOCs")
ioc.add_argument('--single', '-s', help="Send a single IOC")
ioc.add_argument('--file', '-f', hel... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Blockade Analyst Bench\"",
")",
"subs",
"=",
"parser",
".",
"add_subparsers",
"(",
"dest",
"=",
"'cmd'",
")",
"ioc",
"=",
"subs",
".",
"add_parser",
"(",
"'ioc'",
",... | Run the code. | [
"Run",
"the",
"code",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/client.py#L49-L95 | train | 57,290 |
CodyKochmann/generators | generators/window.py | window | def window(iterable, size=2):
''' yields wondows of a given size '''
iterable = iter(iterable)
d = deque(islice(iterable, size-1), maxlen=size)
for _ in map(d.append, iterable):
yield tuple(d) | python | def window(iterable, size=2):
''' yields wondows of a given size '''
iterable = iter(iterable)
d = deque(islice(iterable, size-1), maxlen=size)
for _ in map(d.append, iterable):
yield tuple(d) | [
"def",
"window",
"(",
"iterable",
",",
"size",
"=",
"2",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"d",
"=",
"deque",
"(",
"islice",
"(",
"iterable",
",",
"size",
"-",
"1",
")",
",",
"maxlen",
"=",
"size",
")",
"for",
"_",
"in",
... | yields wondows of a given size | [
"yields",
"wondows",
"of",
"a",
"given",
"size"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/window.py#L12-L17 | train | 57,291 |
tradenity/python-sdk | tradenity/resources/credit_card_payment.py | CreditCardPayment.payment_mode | def payment_mode(self, payment_mode):
"""Sets the payment_mode of this CreditCardPayment.
:param payment_mode: The payment_mode of this CreditCardPayment.
:type: str
"""
allowed_values = ["authorize", "capture"]
if payment_mode is not None and payment_mode not in allowe... | python | def payment_mode(self, payment_mode):
"""Sets the payment_mode of this CreditCardPayment.
:param payment_mode: The payment_mode of this CreditCardPayment.
:type: str
"""
allowed_values = ["authorize", "capture"]
if payment_mode is not None and payment_mode not in allowe... | [
"def",
"payment_mode",
"(",
"self",
",",
"payment_mode",
")",
":",
"allowed_values",
"=",
"[",
"\"authorize\"",
",",
"\"capture\"",
"]",
"if",
"payment_mode",
"is",
"not",
"None",
"and",
"payment_mode",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
... | Sets the payment_mode of this CreditCardPayment.
:param payment_mode: The payment_mode of this CreditCardPayment.
:type: str | [
"Sets",
"the",
"payment_mode",
"of",
"this",
"CreditCardPayment",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/credit_card_payment.py#L260-L274 | train | 57,292 |
ten10solutions/Geist | geist/matchers.py | match_via_correlation_coefficient | def match_via_correlation_coefficient(image, template, raw_tolerance=1, normed_tolerance=0.9):
""" Matching algorithm based on 2-dimensional version of Pearson product-moment correlation coefficient.
This is more robust in the case where the match might be scaled or slightly rotated.
From experime... | python | def match_via_correlation_coefficient(image, template, raw_tolerance=1, normed_tolerance=0.9):
""" Matching algorithm based on 2-dimensional version of Pearson product-moment correlation coefficient.
This is more robust in the case where the match might be scaled or slightly rotated.
From experime... | [
"def",
"match_via_correlation_coefficient",
"(",
"image",
",",
"template",
",",
"raw_tolerance",
"=",
"1",
",",
"normed_tolerance",
"=",
"0.9",
")",
":",
"h",
",",
"w",
"=",
"image",
".",
"shape",
"th",
",",
"tw",
"=",
"template",
".",
"shape",
"temp_mean"... | Matching algorithm based on 2-dimensional version of Pearson product-moment correlation coefficient.
This is more robust in the case where the match might be scaled or slightly rotated.
From experimentation, this method is less prone to false positives than the correlation method. | [
"Matching",
"algorithm",
"based",
"on",
"2",
"-",
"dimensional",
"version",
"of",
"Pearson",
"product",
"-",
"moment",
"correlation",
"coefficient",
"."
] | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/matchers.py#L43-L59 | train | 57,293 |
ten10solutions/Geist | geist/matchers.py | match_positions | def match_positions(shape, list_of_coords):
""" In cases where we have multiple matches, each highlighted by a region of coordinates,
we need to separate matches, and find mean of each to return as match position
"""
match_array = np.zeros(shape)
try:
# excpetion hit on this line if noth... | python | def match_positions(shape, list_of_coords):
""" In cases where we have multiple matches, each highlighted by a region of coordinates,
we need to separate matches, and find mean of each to return as match position
"""
match_array = np.zeros(shape)
try:
# excpetion hit on this line if noth... | [
"def",
"match_positions",
"(",
"shape",
",",
"list_of_coords",
")",
":",
"match_array",
"=",
"np",
".",
"zeros",
"(",
"shape",
")",
"try",
":",
"# excpetion hit on this line if nothing in list_of_coords- i.e. no matches",
"match_array",
"[",
"list_of_coords",
"[",
":",
... | In cases where we have multiple matches, each highlighted by a region of coordinates,
we need to separate matches, and find mean of each to return as match position | [
"In",
"cases",
"where",
"we",
"have",
"multiple",
"matches",
"each",
"highlighted",
"by",
"a",
"region",
"of",
"coordinates",
"we",
"need",
"to",
"separate",
"matches",
"and",
"find",
"mean",
"of",
"each",
"to",
"return",
"as",
"match",
"position"
] | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/matchers.py#L114-L130 | train | 57,294 |
freevoid/django-datafilters | datafilters/filterform.py | FilterFormBase.is_empty | def is_empty(self):
'''
Return `True` if form is valid and contains an empty lookup.
'''
return (self.is_valid() and
not self.simple_lookups and
not self.complex_conditions and
not self.extra_conditions) | python | def is_empty(self):
'''
Return `True` if form is valid and contains an empty lookup.
'''
return (self.is_valid() and
not self.simple_lookups and
not self.complex_conditions and
not self.extra_conditions) | [
"def",
"is_empty",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"is_valid",
"(",
")",
"and",
"not",
"self",
".",
"simple_lookups",
"and",
"not",
"self",
".",
"complex_conditions",
"and",
"not",
"self",
".",
"extra_conditions",
")"
] | Return `True` if form is valid and contains an empty lookup. | [
"Return",
"True",
"if",
"form",
"is",
"valid",
"and",
"contains",
"an",
"empty",
"lookup",
"."
] | 99051b3b3e97946981c0e9697576b0100093287c | https://github.com/freevoid/django-datafilters/blob/99051b3b3e97946981c0e9697576b0100093287c/datafilters/filterform.py#L118-L125 | train | 57,295 |
TissueMAPS/TmDeploy | tmdeploy/inventory.py | load_inventory | def load_inventory(hosts_file=HOSTS_FILE):
'''Loads Ansible inventory from file.
Parameters
----------
hosts_file: str, optional
path to Ansible hosts file
Returns
-------
ConfigParser.SafeConfigParser
content of `hosts_file`
'''
inventory = SafeConfigParser(allow_n... | python | def load_inventory(hosts_file=HOSTS_FILE):
'''Loads Ansible inventory from file.
Parameters
----------
hosts_file: str, optional
path to Ansible hosts file
Returns
-------
ConfigParser.SafeConfigParser
content of `hosts_file`
'''
inventory = SafeConfigParser(allow_n... | [
"def",
"load_inventory",
"(",
"hosts_file",
"=",
"HOSTS_FILE",
")",
":",
"inventory",
"=",
"SafeConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"hosts_file",
")",
":",
"inventory",
".",
"read",
"(",
"hos... | Loads Ansible inventory from file.
Parameters
----------
hosts_file: str, optional
path to Ansible hosts file
Returns
-------
ConfigParser.SafeConfigParser
content of `hosts_file` | [
"Loads",
"Ansible",
"inventory",
"from",
"file",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/tmdeploy/inventory.py#L147-L165 | train | 57,296 |
TissueMAPS/TmDeploy | tmdeploy/inventory.py | save_inventory | def save_inventory(inventory, hosts_file=HOSTS_FILE):
'''Saves Ansible inventory to file.
Parameters
----------
inventory: ConfigParser.SafeConfigParser
content of the `hosts_file`
hosts_file: str, optional
path to Ansible hosts file
'''
with open(hosts_file, 'w') as f:
... | python | def save_inventory(inventory, hosts_file=HOSTS_FILE):
'''Saves Ansible inventory to file.
Parameters
----------
inventory: ConfigParser.SafeConfigParser
content of the `hosts_file`
hosts_file: str, optional
path to Ansible hosts file
'''
with open(hosts_file, 'w') as f:
... | [
"def",
"save_inventory",
"(",
"inventory",
",",
"hosts_file",
"=",
"HOSTS_FILE",
")",
":",
"with",
"open",
"(",
"hosts_file",
",",
"'w'",
")",
"as",
"f",
":",
"inventory",
".",
"write",
"(",
"f",
")"
] | Saves Ansible inventory to file.
Parameters
----------
inventory: ConfigParser.SafeConfigParser
content of the `hosts_file`
hosts_file: str, optional
path to Ansible hosts file | [
"Saves",
"Ansible",
"inventory",
"to",
"file",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/tmdeploy/inventory.py#L168-L179 | train | 57,297 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Display/RPiDisplay.py | RPiDiaplay._init_config | def _init_config(self, width, height, spi=None, spiMosi= None, spiDC=None, spiCS=None, spiReset=None, spiClk=None):
"""!
SPI hardware and display width, height initialization.
"""
self._spi = spi
self._spi_mosi = spiMosi
self._spi_dc = spiDC
self._spi_cs = spiCS
... | python | def _init_config(self, width, height, spi=None, spiMosi= None, spiDC=None, spiCS=None, spiReset=None, spiClk=None):
"""!
SPI hardware and display width, height initialization.
"""
self._spi = spi
self._spi_mosi = spiMosi
self._spi_dc = spiDC
self._spi_cs = spiCS
... | [
"def",
"_init_config",
"(",
"self",
",",
"width",
",",
"height",
",",
"spi",
"=",
"None",
",",
"spiMosi",
"=",
"None",
",",
"spiDC",
"=",
"None",
",",
"spiCS",
"=",
"None",
",",
"spiReset",
"=",
"None",
",",
"spiClk",
"=",
"None",
")",
":",
"self",... | !
SPI hardware and display width, height initialization. | [
"!",
"SPI",
"hardware",
"and",
"display",
"width",
"height",
"initialization",
"."
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/RPiDisplay.py#L77-L89 | train | 57,298 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Display/RPiDisplay.py | RPiDiaplay._init_io | def _init_io(self):
"""!
GPIO initialization.
Set GPIO into BCM mode and init other IOs mode
"""
GPIO.setwarnings(False)
GPIO.setmode( GPIO.BCM )
pins = [ self._spi_dc ]
for pin in pins:
GPIO.setup( pin, GPIO.OUT ) | python | def _init_io(self):
"""!
GPIO initialization.
Set GPIO into BCM mode and init other IOs mode
"""
GPIO.setwarnings(False)
GPIO.setmode( GPIO.BCM )
pins = [ self._spi_dc ]
for pin in pins:
GPIO.setup( pin, GPIO.OUT ) | [
"def",
"_init_io",
"(",
"self",
")",
":",
"GPIO",
".",
"setwarnings",
"(",
"False",
")",
"GPIO",
".",
"setmode",
"(",
"GPIO",
".",
"BCM",
")",
"pins",
"=",
"[",
"self",
".",
"_spi_dc",
"]",
"for",
"pin",
"in",
"pins",
":",
"GPIO",
".",
"setup",
"... | !
GPIO initialization.
Set GPIO into BCM mode and init other IOs mode | [
"!",
"GPIO",
"initialization",
".",
"Set",
"GPIO",
"into",
"BCM",
"mode",
"and",
"init",
"other",
"IOs",
"mode"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/RPiDisplay.py#L91-L100 | train | 57,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.