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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
usc-isi-i2/etk
etk/knowledge_graph_schema.py
KGSchema.is_date
def is_date(v) -> (bool, date): """ Boolean function for checking if v is a date Args: v: Returns: bool """ if isinstance(v, date): return True, v try: reg = r'^([0-9]{4})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T' ...
python
def is_date(v) -> (bool, date): """ Boolean function for checking if v is a date Args: v: Returns: bool """ if isinstance(v, date): return True, v try: reg = r'^([0-9]{4})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T' ...
[ "def", "is_date", "(", "v", ")", "->", "(", "bool", ",", "date", ")", ":", "if", "isinstance", "(", "v", ",", "date", ")", ":", "return", "True", ",", "v", "try", ":", "reg", "=", "r'^([0-9]{4})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T'", "r'([0-...
Boolean function for checking if v is a date Args: v: Returns: bool
[ "Boolean", "function", "for", "checking", "if", "v", "is", "a", "date" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph_schema.py#L171-L194
train
usc-isi-i2/etk
etk/knowledge_graph_schema.py
KGSchema.is_location
def is_location(v) -> (bool, str): """ Boolean function for checking if v is a location format Args: v: Returns: bool """ def convert2float(value): try: float_num = float(value) return float_num except...
python
def is_location(v) -> (bool, str): """ Boolean function for checking if v is a location format Args: v: Returns: bool """ def convert2float(value): try: float_num = float(value) return float_num except...
[ "def", "is_location", "(", "v", ")", "->", "(", "bool", ",", "str", ")", ":", "def", "convert2float", "(", "value", ")", ":", "try", ":", "float_num", "=", "float", "(", "value", ")", "return", "float_num", "except", "ValueError", ":", "return", "False...
Boolean function for checking if v is a location format Args: v: Returns: bool
[ "Boolean", "function", "for", "checking", "if", "v", "is", "a", "location", "format" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph_schema.py#L197-L227
train
usc-isi-i2/etk
etk/document.py
Document.select_segments
def select_segments(self, jsonpath: str) -> List[Segment]: """ Dereferences the json_path inside the document and returns the selected elements. This method should compile and cache the compiled json_path in case the same path is reused by multiple extractors. Args: ...
python
def select_segments(self, jsonpath: str) -> List[Segment]: """ Dereferences the json_path inside the document and returns the selected elements. This method should compile and cache the compiled json_path in case the same path is reused by multiple extractors. Args: ...
[ "def", "select_segments", "(", "self", ",", "jsonpath", ":", "str", ")", "->", "List", "[", "Segment", "]", ":", "path", "=", "self", ".", "etk", ".", "parse_json_path", "(", "jsonpath", ")", "matches", "=", "path", ".", "find", "(", "self", ".", "cd...
Dereferences the json_path inside the document and returns the selected elements. This method should compile and cache the compiled json_path in case the same path is reused by multiple extractors. Args: jsonpath (str): a valid JSON path. Returns: A list of Segments object ...
[ "Dereferences", "the", "json_path", "inside", "the", "document", "and", "returns", "the", "selected", "elements", ".", "This", "method", "should", "compile", "and", "cache", "the", "compiled", "json_path", "in", "case", "the", "same", "path", "is", "reused", "...
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/document.py#L81-L100
train
usc-isi-i2/etk
examples/elicit_gdelt_mapping/elicit_gdelt_module.py
GdeltModule.attribute_value
def attribute_value(self, doc: Document, attribute_name: str): """ Access data using attribute name rather than the numeric indices Returns: the value for the attribute """ return doc.cdr_document.get(self.header_translation_table[attribute_name])
python
def attribute_value(self, doc: Document, attribute_name: str): """ Access data using attribute name rather than the numeric indices Returns: the value for the attribute """ return doc.cdr_document.get(self.header_translation_table[attribute_name])
[ "def", "attribute_value", "(", "self", ",", "doc", ":", "Document", ",", "attribute_name", ":", "str", ")", ":", "return", "doc", ".", "cdr_document", ".", "get", "(", "self", ".", "header_translation_table", "[", "attribute_name", "]", ")" ]
Access data using attribute name rather than the numeric indices Returns: the value for the attribute
[ "Access", "data", "using", "attribute", "name", "rather", "than", "the", "numeric", "indices" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/examples/elicit_gdelt_mapping/elicit_gdelt_module.py#L120-L127
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
all_cities
def all_cities(): """ Get a list of all Backpage city names. Returns: list of city names as Strings """ cities = [] fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(csvfile, delimiter = ',') for row in reader: ...
python
def all_cities(): """ Get a list of all Backpage city names. Returns: list of city names as Strings """ cities = [] fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(csvfile, delimiter = ',') for row in reader: ...
[ "def", "all_cities", "(", ")", ":", "cities", "=", "[", "]", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/CityPops.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")", "as", "csvfile", ":", "reader", "="...
Get a list of all Backpage city names. Returns: list of city names as Strings
[ "Get", "a", "list", "of", "all", "Backpage", "city", "names", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L16-L30
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
city_nums
def city_nums(): """ Get a dictionary of Backpage city names mapped to their 'legend' value. Returns: dictionary of Backpage city names mapped to their numeric value """ city_nums = {} first_row = 1 num = 0 fname = pkg_resources.resource_filename(__name__, 'resources/Distance_Matrix.csv') with op...
python
def city_nums(): """ Get a dictionary of Backpage city names mapped to their 'legend' value. Returns: dictionary of Backpage city names mapped to their numeric value """ city_nums = {} first_row = 1 num = 0 fname = pkg_resources.resource_filename(__name__, 'resources/Distance_Matrix.csv') with op...
[ "def", "city_nums", "(", ")", ":", "city_nums", "=", "{", "}", "first_row", "=", "1", "num", "=", "0", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/Distance_Matrix.csv'", ")", "with", "open", "(", "fname", ",", ...
Get a dictionary of Backpage city names mapped to their 'legend' value. Returns: dictionary of Backpage city names mapped to their numeric value
[ "Get", "a", "dictionary", "of", "Backpage", "city", "names", "mapped", "to", "their", "legend", "value", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L86-L106
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
date_clean
def date_clean(date, dashboard_style=False): """ Clean the numerical date value in order to present it. Args: boo: numerical date (20160205) Returns: Stringified version of the input date ("2016-02-05") """ if dashboard_style: dt = str(date) out = dt[4:6] + '/' + dt[6:] + '/' + dt[:4] els...
python
def date_clean(date, dashboard_style=False): """ Clean the numerical date value in order to present it. Args: boo: numerical date (20160205) Returns: Stringified version of the input date ("2016-02-05") """ if dashboard_style: dt = str(date) out = dt[4:6] + '/' + dt[6:] + '/' + dt[:4] els...
[ "def", "date_clean", "(", "date", ",", "dashboard_style", "=", "False", ")", ":", "if", "dashboard_style", ":", "dt", "=", "str", "(", "date", ")", "out", "=", "dt", "[", "4", ":", "6", "]", "+", "'/'", "+", "dt", "[", "6", ":", "]", "+", "'/'"...
Clean the numerical date value in order to present it. Args: boo: numerical date (20160205) Returns: Stringified version of the input date ("2016-02-05")
[ "Clean", "the", "numerical", "date", "value", "in", "order", "to", "present", "it", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L118-L133
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
date_range
def date_range(start, end, boo): """ Return list of dates within a specified range, inclusive. Args: start: earliest date to include, String ("2015-11-25") end: latest date to include, String ("2015-12-01") boo: if true, output list contains Numbers (20151230); if false, list contains Strings ("2015-...
python
def date_range(start, end, boo): """ Return list of dates within a specified range, inclusive. Args: start: earliest date to include, String ("2015-11-25") end: latest date to include, String ("2015-12-01") boo: if true, output list contains Numbers (20151230); if false, list contains Strings ("2015-...
[ "def", "date_range", "(", "start", ",", "end", ",", "boo", ")", ":", "earliest", "=", "datetime", ".", "strptime", "(", "start", ".", "replace", "(", "'-'", ",", "' '", ")", ",", "'%Y %m %d'", ")", "latest", "=", "datetime", ".", "strptime", "(", "en...
Return list of dates within a specified range, inclusive. Args: start: earliest date to include, String ("2015-11-25") end: latest date to include, String ("2015-12-01") boo: if true, output list contains Numbers (20151230); if false, list contains Strings ("2015-12-30") Returns: list of either Num...
[ "Return", "list", "of", "dates", "within", "a", "specified", "range", "inclusive", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L145-L172
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
ethnicities_clean
def ethnicities_clean(): """ Get dictionary of unformatted ethnicity types mapped to clean corresponding ethnicity strings """ eths_clean = {} fname = pkg_resources.resource_filename(__name__, 'resources/Ethnicity_Groups.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(csvfile, delimiter = ',')...
python
def ethnicities_clean(): """ Get dictionary of unformatted ethnicity types mapped to clean corresponding ethnicity strings """ eths_clean = {} fname = pkg_resources.resource_filename(__name__, 'resources/Ethnicity_Groups.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(csvfile, delimiter = ',')...
[ "def", "ethnicities_clean", "(", ")", ":", "eths_clean", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/Ethnicity_Groups.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")", "as", "csvfile", ":"...
Get dictionary of unformatted ethnicity types mapped to clean corresponding ethnicity strings
[ "Get", "dictionary", "of", "unformatted", "ethnicity", "types", "mapped", "to", "clean", "corresponding", "ethnicity", "strings" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L264-L280
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
formal_cities
def formal_cities(reverse=False): """ Get a dictionary that maps all Backpage city names to their presentable, formal names. Returns: dictionary of Backpage city names mapped to formal city names """ output = {} fname = pkg_resources.resource_filename(__name__, 'resources/Formal_City_Name_Pairs.csv') ...
python
def formal_cities(reverse=False): """ Get a dictionary that maps all Backpage city names to their presentable, formal names. Returns: dictionary of Backpage city names mapped to formal city names """ output = {} fname = pkg_resources.resource_filename(__name__, 'resources/Formal_City_Name_Pairs.csv') ...
[ "def", "formal_cities", "(", "reverse", "=", "False", ")", ":", "output", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/Formal_City_Name_Pairs.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")...
Get a dictionary that maps all Backpage city names to their presentable, formal names. Returns: dictionary of Backpage city names mapped to formal city names
[ "Get", "a", "dictionary", "that", "maps", "all", "Backpage", "city", "names", "to", "their", "presentable", "formal", "names", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L295-L313
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
get_lats
def get_lats(): """ Get a dictionary that maps Backpage city names to their respective latitudes. Returns: dictionary that maps city names (Strings) to latitudes (Floats) """ lats = {} fname = pkg_resources.resource_filename(__name__, 'resources/Latitudes-Longitudes.csv') with open(fname, 'rb') as cs...
python
def get_lats(): """ Get a dictionary that maps Backpage city names to their respective latitudes. Returns: dictionary that maps city names (Strings) to latitudes (Floats) """ lats = {} fname = pkg_resources.resource_filename(__name__, 'resources/Latitudes-Longitudes.csv') with open(fname, 'rb') as cs...
[ "def", "get_lats", "(", ")", ":", "lats", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/Latitudes-Longitudes.csv'", ")", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "csvfile", ":", "reader...
Get a dictionary that maps Backpage city names to their respective latitudes. Returns: dictionary that maps city names (Strings) to latitudes (Floats)
[ "Get", "a", "dictionary", "that", "maps", "Backpage", "city", "names", "to", "their", "respective", "latitudes", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L376-L393
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
get_longs
def get_longs(): """ Get a dictionary that maps Backpage city names to their respective longitudes. Returns: dictionary that maps city names (Strings) to longitudes (Floats) """ longs = {} fname = pkg_resources.resource_filename(__name__, 'resources/Latitudes-Longitudes.csv') with open(fname, 'rb') a...
python
def get_longs(): """ Get a dictionary that maps Backpage city names to their respective longitudes. Returns: dictionary that maps city names (Strings) to longitudes (Floats) """ longs = {} fname = pkg_resources.resource_filename(__name__, 'resources/Latitudes-Longitudes.csv') with open(fname, 'rb') a...
[ "def", "get_longs", "(", ")", ":", "longs", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/Latitudes-Longitudes.csv'", ")", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "csvfile", ":", "read...
Get a dictionary that maps Backpage city names to their respective longitudes. Returns: dictionary that maps city names (Strings) to longitudes (Floats)
[ "Get", "a", "dictionary", "that", "maps", "Backpage", "city", "names", "to", "their", "respective", "longitudes", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L396-L412
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
get_regions
def get_regions(): """ Get a dictionary of state names mapped to their respective region numeric values. New England -> 0 Mid Atlantic -> 1 Midwest East -> 2 Midwest West -> 3 Southeast -> 4 Southwest -> 5 Mountain West -> 6 Pacific -> 7 Alaska -> 8 Hawaii -> 9 Returns: dictionary of sta...
python
def get_regions(): """ Get a dictionary of state names mapped to their respective region numeric values. New England -> 0 Mid Atlantic -> 1 Midwest East -> 2 Midwest West -> 3 Southeast -> 4 Southwest -> 5 Mountain West -> 6 Pacific -> 7 Alaska -> 8 Hawaii -> 9 Returns: dictionary of sta...
[ "def", "get_regions", "(", ")", ":", "new_england", "=", "[", "'Connecticut'", ",", "'Maine'", ",", "'Massachusetts'", ",", "'New Hampshire'", ",", "'Rhode Island'", ",", "'Vermont'", "]", "mid_atlantic", "=", "[", "'New Jersey'", ",", "'New York'", ",", "'Penns...
Get a dictionary of state names mapped to their respective region numeric values. New England -> 0 Mid Atlantic -> 1 Midwest East -> 2 Midwest West -> 3 Southeast -> 4 Southwest -> 5 Mountain West -> 6 Pacific -> 7 Alaska -> 8 Hawaii -> 9 Returns: dictionary of state names mapped to region n...
[ "Get", "a", "dictionary", "of", "state", "names", "mapped", "to", "their", "respective", "region", "numeric", "values", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L445-L492
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
populations
def populations(): """ Get a dictionary of Backpage city names mapped to their citizen populations. Returns: dictionary of Backpage city names mapped to their populations (integers) """ city_pops = {} fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv') with open(fname, 'rU') a...
python
def populations(): """ Get a dictionary of Backpage city names mapped to their citizen populations. Returns: dictionary of Backpage city names mapped to their populations (integers) """ city_pops = {} fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv') with open(fname, 'rU') a...
[ "def", "populations", "(", ")", ":", "city_pops", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/CityPops.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")", "as", "csvfile", ":", "reader", ...
Get a dictionary of Backpage city names mapped to their citizen populations. Returns: dictionary of Backpage city names mapped to their populations (integers)
[ "Get", "a", "dictionary", "of", "Backpage", "city", "names", "mapped", "to", "their", "citizen", "populations", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L495-L508
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
state_names
def state_names(): """ Get the set of all US state names """ names = set() fname = pkg_resources.resource_filename(__name__, 'resources/States.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(csvfile, delimiter = ',') for row in reader: names.add(row[0]) return names
python
def state_names(): """ Get the set of all US state names """ names = set() fname = pkg_resources.resource_filename(__name__, 'resources/States.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(csvfile, delimiter = ',') for row in reader: names.add(row[0]) return names
[ "def", "state_names", "(", ")", ":", "names", "=", "set", "(", ")", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/States.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")", "as", "csvfile", ":", "reader"...
Get the set of all US state names
[ "Get", "the", "set", "of", "all", "US", "state", "names" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L540-L549
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
state_nums
def state_nums(): """ Get a dictionary of state names mapped to their 'legend' value. Returns: dictionary of state names mapped to their numeric value """ st_nums = {} fname = pkg_resources.resource_filename(__name__, 'resources/States.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(...
python
def state_nums(): """ Get a dictionary of state names mapped to their 'legend' value. Returns: dictionary of state names mapped to their numeric value """ st_nums = {} fname = pkg_resources.resource_filename(__name__, 'resources/States.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(...
[ "def", "state_nums", "(", ")", ":", "st_nums", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/States.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")", "as", "csvfile", ":", "reader", "=",...
Get a dictionary of state names mapped to their 'legend' value. Returns: dictionary of state names mapped to their numeric value
[ "Get", "a", "dictionary", "of", "state", "names", "mapped", "to", "their", "legend", "value", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L552-L567
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
states
def states(): """ Get a dictionary of Backpage city names mapped to their respective states. Returns: dictionary of Backpage city names mapped to their states """ states = {} fname = pkg_resources.resource_filename(__name__, 'resources/City_State_Pairs.csv') with open(fname, 'rU') as csvfile: rea...
python
def states(): """ Get a dictionary of Backpage city names mapped to their respective states. Returns: dictionary of Backpage city names mapped to their states """ states = {} fname = pkg_resources.resource_filename(__name__, 'resources/City_State_Pairs.csv') with open(fname, 'rU') as csvfile: rea...
[ "def", "states", "(", ")", ":", "states", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/City_State_Pairs.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")", "as", "csvfile", ":", "reader", ...
Get a dictionary of Backpage city names mapped to their respective states. Returns: dictionary of Backpage city names mapped to their states
[ "Get", "a", "dictionary", "of", "Backpage", "city", "names", "mapped", "to", "their", "respective", "states", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L583-L597
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/utils.py
today
def today(boo): """ Return today's date as either a String or a Number, as specified by the User. Args: boo: if true, function returns Number (20151230); if false, returns String ("2015-12-30") Returns: either a Number or a string, dependent upon the user's input """ tod = datetime.strptime(datetim...
python
def today(boo): """ Return today's date as either a String or a Number, as specified by the User. Args: boo: if true, function returns Number (20151230); if false, returns String ("2015-12-30") Returns: either a Number or a string, dependent upon the user's input """ tod = datetime.strptime(datetim...
[ "def", "today", "(", "boo", ")", ":", "tod", "=", "datetime", ".", "strptime", "(", "datetime", ".", "today", "(", ")", ".", "date", "(", ")", ".", "isoformat", "(", ")", ".", "replace", "(", "'-'", ",", "' '", ")", ",", "'%Y %m %d'", ")", "if", ...
Return today's date as either a String or a Number, as specified by the User. Args: boo: if true, function returns Number (20151230); if false, returns String ("2015-12-30") Returns: either a Number or a string, dependent upon the user's input
[ "Return", "today", "s", "date", "as", "either", "a", "String", "or", "a", "Number", "as", "specified", "by", "the", "User", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/utils.py#L615-L628
train
usc-isi-i2/etk
etk/extractors/glossary_extractor.py
GlossaryExtractor._generate_ngrams_with_context
def _generate_ngrams_with_context(self, tokens: List[Token]) -> chain: """Generates the 1-gram to n-grams tuples of the list of tokens""" chained_ngrams_iter = self._generate_ngrams_with_context_helper(iter(tokens), 1) for n in range(2, self._ngrams + 1): ngrams_iter = tee(tokens, n)...
python
def _generate_ngrams_with_context(self, tokens: List[Token]) -> chain: """Generates the 1-gram to n-grams tuples of the list of tokens""" chained_ngrams_iter = self._generate_ngrams_with_context_helper(iter(tokens), 1) for n in range(2, self._ngrams + 1): ngrams_iter = tee(tokens, n)...
[ "def", "_generate_ngrams_with_context", "(", "self", ",", "tokens", ":", "List", "[", "Token", "]", ")", "->", "chain", ":", "chained_ngrams_iter", "=", "self", ".", "_generate_ngrams_with_context_helper", "(", "iter", "(", "tokens", ")", ",", "1", ")", "for",...
Generates the 1-gram to n-grams tuples of the list of tokens
[ "Generates", "the", "1", "-", "gram", "to", "n", "-", "grams", "tuples", "of", "the", "list", "of", "tokens" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/glossary_extractor.py#L86-L96
train
usc-isi-i2/etk
etk/extractors/glossary_extractor.py
GlossaryExtractor._populate_trie
def _populate_trie(self, values: List[str]) -> CharTrie: """Takes a list and inserts its elements into a new trie and returns it""" if self._default_tokenizer: return reduce(self._populate_trie_reducer, iter(values), CharTrie()) return reduce(self._populate_trie_reducer_regex, iter(v...
python
def _populate_trie(self, values: List[str]) -> CharTrie: """Takes a list and inserts its elements into a new trie and returns it""" if self._default_tokenizer: return reduce(self._populate_trie_reducer, iter(values), CharTrie()) return reduce(self._populate_trie_reducer_regex, iter(v...
[ "def", "_populate_trie", "(", "self", ",", "values", ":", "List", "[", "str", "]", ")", "->", "CharTrie", ":", "if", "self", ".", "_default_tokenizer", ":", "return", "reduce", "(", "self", ".", "_populate_trie_reducer", ",", "iter", "(", "values", ")", ...
Takes a list and inserts its elements into a new trie and returns it
[ "Takes", "a", "list", "and", "inserts", "its", "elements", "into", "a", "new", "trie", "and", "returns", "it" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/glossary_extractor.py#L98-L102
train
usc-isi-i2/etk
etk/extractors/glossary_extractor.py
GlossaryExtractor._generate_ngrams_with_context_helper
def _generate_ngrams_with_context_helper(ngrams_iter: iter, ngrams_len: int) -> map: """Updates the end index""" return map(lambda term: (term[1], term[0], term[0] + ngrams_len), enumerate(ngrams_iter))
python
def _generate_ngrams_with_context_helper(ngrams_iter: iter, ngrams_len: int) -> map: """Updates the end index""" return map(lambda term: (term[1], term[0], term[0] + ngrams_len), enumerate(ngrams_iter))
[ "def", "_generate_ngrams_with_context_helper", "(", "ngrams_iter", ":", "iter", ",", "ngrams_len", ":", "int", ")", "->", "map", ":", "return", "map", "(", "lambda", "term", ":", "(", "term", "[", "1", "]", ",", "term", "[", "0", "]", ",", "term", "[",...
Updates the end index
[ "Updates", "the", "end", "index" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/glossary_extractor.py#L137-L139
train
usc-isi-i2/etk
etk/extractors/glossary_extractor.py
GlossaryExtractor._combine_ngrams
def _combine_ngrams(ngrams, joiner) -> str: """Construct keys for checking in trie""" if isinstance(ngrams, str): return ngrams else: combined = joiner.join(ngrams) return combined
python
def _combine_ngrams(ngrams, joiner) -> str: """Construct keys for checking in trie""" if isinstance(ngrams, str): return ngrams else: combined = joiner.join(ngrams) return combined
[ "def", "_combine_ngrams", "(", "ngrams", ",", "joiner", ")", "->", "str", ":", "if", "isinstance", "(", "ngrams", ",", "str", ")", ":", "return", "ngrams", "else", ":", "combined", "=", "joiner", ".", "join", "(", "ngrams", ")", "return", "combined" ]
Construct keys for checking in trie
[ "Construct", "keys", "for", "checking", "in", "trie" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/glossary_extractor.py#L142-L148
train
usc-isi-i2/etk
etk/extractors/spacy_rule_extractor.py
SpacyRuleExtractor.extract
def extract(self, text: str) -> List[Extraction]: """ Extract from text Args: text (str): input str to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches. """ doc = self._tokenizer.tokenize_...
python
def extract(self, text: str) -> List[Extraction]: """ Extract from text Args: text (str): input str to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches. """ doc = self._tokenizer.tokenize_...
[ "def", "extract", "(", "self", ",", "text", ":", "str", ")", "->", "List", "[", "Extraction", "]", ":", "doc", "=", "self", ".", "_tokenizer", ".", "tokenize_to_spacy_doc", "(", "text", ")", "self", ".", "_load_matcher", "(", ")", "matches", "=", "[", ...
Extract from text Args: text (str): input str to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches.
[ "Extract", "from", "text" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/spacy_rule_extractor.py#L134-L185
train
usc-isi-i2/etk
etk/extractors/spacy_rule_extractor.py
SpacyRuleExtractor._load_matcher
def _load_matcher(self) -> None: """ Add constructed spacy rule to Matcher """ for id_key in self._rule_lst: if self._rule_lst[id_key].active: pattern_lst = [a_pattern.spacy_token_lst for a_pattern in self._rule_lst[id_key].patterns] for spacy...
python
def _load_matcher(self) -> None: """ Add constructed spacy rule to Matcher """ for id_key in self._rule_lst: if self._rule_lst[id_key].active: pattern_lst = [a_pattern.spacy_token_lst for a_pattern in self._rule_lst[id_key].patterns] for spacy...
[ "def", "_load_matcher", "(", "self", ")", "->", "None", ":", "for", "id_key", "in", "self", ".", "_rule_lst", ":", "if", "self", ".", "_rule_lst", "[", "id_key", "]", ".", "active", ":", "pattern_lst", "=", "[", "a_pattern", ".", "spacy_token_lst", "for"...
Add constructed spacy rule to Matcher
[ "Add", "constructed", "spacy", "rule", "to", "Matcher" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/spacy_rule_extractor.py#L187-L196
train
usc-isi-i2/etk
etk/utilities.py
Utility.make_json_serializable
def make_json_serializable(doc: Dict): """ Make the document JSON serializable. This is a poor man's implementation that handles dates and nothing else. This method modifies the given document in place. Args: doc: A Python Dictionary, typically a CDR object. Returns...
python
def make_json_serializable(doc: Dict): """ Make the document JSON serializable. This is a poor man's implementation that handles dates and nothing else. This method modifies the given document in place. Args: doc: A Python Dictionary, typically a CDR object. Returns...
[ "def", "make_json_serializable", "(", "doc", ":", "Dict", ")", ":", "for", "k", ",", "v", "in", "doc", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "datetime", ".", "date", ")", ":", "doc", "[", "k", "]", "=", "v", ".", "strf...
Make the document JSON serializable. This is a poor man's implementation that handles dates and nothing else. This method modifies the given document in place. Args: doc: A Python Dictionary, typically a CDR object. Returns: None
[ "Make", "the", "document", "JSON", "serializable", ".", "This", "is", "a", "poor", "man", "s", "implementation", "that", "handles", "dates", "and", "nothing", "else", ".", "This", "method", "modifies", "the", "given", "document", "in", "place", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/utilities.py#L11-L26
train
usc-isi-i2/etk
etk/black_list_filter.py
BlackListFilter.filter
def filter(self, extractions, case_sensitive=False) -> List[Extraction]: """filters out the extraction if extracted value is in the blacklist""" filtered_extractions = [] if not isinstance(extractions, list): extractions = [extractions] for extraction in extractions: ...
python
def filter(self, extractions, case_sensitive=False) -> List[Extraction]: """filters out the extraction if extracted value is in the blacklist""" filtered_extractions = [] if not isinstance(extractions, list): extractions = [extractions] for extraction in extractions: ...
[ "def", "filter", "(", "self", ",", "extractions", ",", "case_sensitive", "=", "False", ")", "->", "List", "[", "Extraction", "]", ":", "filtered_extractions", "=", "[", "]", "if", "not", "isinstance", "(", "extractions", ",", "list", ")", ":", "extractions...
filters out the extraction if extracted value is in the blacklist
[ "filters", "out", "the", "extraction", "if", "extracted", "value", "is", "in", "the", "blacklist" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/black_list_filter.py#L9-L27
train
usc-isi-i2/etk
etk/ontology_api.py
rdf_generation
def rdf_generation(kg_object) -> str: """ Convert input knowledge graph object into n-triples RDF :param kg_object: str, dict, or json object :return: n-triples RDF in str """ import json if isinstance(kg_object, dict): kg_object = json.dumps(kg_object) g = Graph() g.parse(...
python
def rdf_generation(kg_object) -> str: """ Convert input knowledge graph object into n-triples RDF :param kg_object: str, dict, or json object :return: n-triples RDF in str """ import json if isinstance(kg_object, dict): kg_object = json.dumps(kg_object) g = Graph() g.parse(...
[ "def", "rdf_generation", "(", "kg_object", ")", "->", "str", ":", "import", "json", "if", "isinstance", "(", "kg_object", ",", "dict", ")", ":", "kg_object", "=", "json", ".", "dumps", "(", "kg_object", ")", "g", "=", "Graph", "(", ")", "g", ".", "pa...
Convert input knowledge graph object into n-triples RDF :param kg_object: str, dict, or json object :return: n-triples RDF in str
[ "Convert", "input", "knowledge", "graph", "object", "into", "n", "-", "triples", "RDF" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/ontology_api.py#L829-L842
train
usc-isi-i2/etk
etk/ontology_api.py
OntologyDatatypeProperty.is_legal_object
def is_legal_object(self, data_type: str) -> bool: """ Do data_type validation according to the rules of the XML xsd schema. Args: data_type: Returns: """ data_type = str(data_type) ranges = self.included_ranges() return not ranges or data_t...
python
def is_legal_object(self, data_type: str) -> bool: """ Do data_type validation according to the rules of the XML xsd schema. Args: data_type: Returns: """ data_type = str(data_type) ranges = self.included_ranges() return not ranges or data_t...
[ "def", "is_legal_object", "(", "self", ",", "data_type", ":", "str", ")", "->", "bool", ":", "data_type", "=", "str", "(", "data_type", ")", "ranges", "=", "self", ".", "included_ranges", "(", ")", "return", "not", "ranges", "or", "data_type", "in", "ran...
Do data_type validation according to the rules of the XML xsd schema. Args: data_type: Returns:
[ "Do", "data_type", "validation", "according", "to", "the", "rules", "of", "the", "XML", "xsd", "schema", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/ontology_api.py#L242-L255
train
usc-isi-i2/etk
etk/ontology_api.py
Ontology.get_entity
def get_entity(self, uri: str) -> OntologyClass: """ Find an ontology entity based on URI :param uri: URIRef or str :return: the OntologyEntity having the specified uri, or None """ return self.entities.get(str(uri), None)
python
def get_entity(self, uri: str) -> OntologyClass: """ Find an ontology entity based on URI :param uri: URIRef or str :return: the OntologyEntity having the specified uri, or None """ return self.entities.get(str(uri), None)
[ "def", "get_entity", "(", "self", ",", "uri", ":", "str", ")", "->", "OntologyClass", ":", "return", "self", ".", "entities", ".", "get", "(", "str", "(", "uri", ")", ",", "None", ")" ]
Find an ontology entity based on URI :param uri: URIRef or str :return: the OntologyEntity having the specified uri, or None
[ "Find", "an", "ontology", "entity", "based", "on", "URI" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/ontology_api.py#L599-L606
train
usc-isi-i2/etk
etk/ontology_api.py
Ontology.merge_with_master_config
def merge_with_master_config(self, config, defaults={}, delete_orphan_fields=False) -> dict: """ Merge current ontology with input master config. :param config: master config, should be str or dict :param defaults: a dict that sets default color and icon :param delete_orphan_fie...
python
def merge_with_master_config(self, config, defaults={}, delete_orphan_fields=False) -> dict: """ Merge current ontology with input master config. :param config: master config, should be str or dict :param defaults: a dict that sets default color and icon :param delete_orphan_fie...
[ "def", "merge_with_master_config", "(", "self", ",", "config", ",", "defaults", "=", "{", "}", ",", "delete_orphan_fields", "=", "False", ")", "->", "dict", ":", "if", "isinstance", "(", "config", ",", "str", ")", ":", "import", "json", "config", "=", "j...
Merge current ontology with input master config. :param config: master config, should be str or dict :param defaults: a dict that sets default color and icon :param delete_orphan_fields: if a property doesn't exist in the ontology then delete it :return: merged master config in dict
[ "Merge", "current", "ontology", "with", "input", "master", "config", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/ontology_api.py#L618-L680
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/misc.py
phone_text_subs
def phone_text_subs(): """ Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual Number value. Returns: dictionary of dictionaries containing Strings mapped to Numbers """ Small = { 'zero': 0, 'zer0': 0, 'one': 1, 'two': 2, 'th...
python
def phone_text_subs(): """ Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual Number value. Returns: dictionary of dictionaries containing Strings mapped to Numbers """ Small = { 'zero': 0, 'zer0': 0, 'one': 1, 'two': 2, 'th...
[ "def", "phone_text_subs", "(", ")", ":", "Small", "=", "{", "'zero'", ":", "0", ",", "'zer0'", ":", "0", ",", "'one'", ":", "1", ",", "'two'", ":", "2", ",", "'three'", ":", "3", ",", "'four'", ":", "4", ",", "'fuor'", ":", "4", ",", "'five'", ...
Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual Number value. Returns: dictionary of dictionaries containing Strings mapped to Numbers
[ "Gets", "a", "dictionary", "of", "dictionaries", "that", "each", "contain", "alphabetic", "number", "manifestations", "mapped", "to", "their", "actual", "Number", "value", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/misc.py#L26-L89
train
usc-isi-i2/etk
etk/extractors/sentence_extractor.py
SentenceExtractor.extract
def extract(self, text: str) -> List[Extraction]: """ Splits text by sentences. Args: text (str): Input text to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches. """ doc = self._parser(tex...
python
def extract(self, text: str) -> List[Extraction]: """ Splits text by sentences. Args: text (str): Input text to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches. """ doc = self._parser(tex...
[ "def", "extract", "(", "self", ",", "text", ":", "str", ")", "->", "List", "[", "Extraction", "]", ":", "doc", "=", "self", ".", "_parser", "(", "text", ")", "extractions", "=", "list", "(", ")", "for", "sent", "in", "doc", ".", "sents", ":", "th...
Splits text by sentences. Args: text (str): Input text to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches.
[ "Splits", "text", "by", "sentences", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/sentence_extractor.py#L57-L80
train
usc-isi-i2/etk
etk/extractors/table_extractor.py
TableExtraction.gen_html
def gen_html(row_list): """ Return html table string from a list of data rows """ table = "<table>" for row in row_list: table += "<tr>" cells = row["cells"] for c in cells: t = c['cell'] if c else '' table += t tabl...
python
def gen_html(row_list): """ Return html table string from a list of data rows """ table = "<table>" for row in row_list: table += "<tr>" cells = row["cells"] for c in cells: t = c['cell'] if c else '' table += t tabl...
[ "def", "gen_html", "(", "row_list", ")", ":", "table", "=", "\"<table>\"", "for", "row", "in", "row_list", ":", "table", "+=", "\"<tr>\"", "cells", "=", "row", "[", "\"cells\"", "]", "for", "c", "in", "cells", ":", "t", "=", "c", "[", "'cell'", "]", ...
Return html table string from a list of data rows
[ "Return", "html", "table", "string", "from", "a", "list", "of", "data", "rows" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/table_extractor.py#L463-L474
train
usc-isi-i2/etk
etk/extractors/html_content_extractor.py
HTMLContentExtractor.extract
def extract(self, html_text: str, strategy: Strategy=Strategy.ALL_TEXT) \ -> List[Extraction]: """ Extracts text from an HTML page using a variety of strategies Args: html_text (str): html page in string strategy (enum[Strategy.ALL_TEXT, Strategy.MAIN_CONTENT...
python
def extract(self, html_text: str, strategy: Strategy=Strategy.ALL_TEXT) \ -> List[Extraction]: """ Extracts text from an HTML page using a variety of strategies Args: html_text (str): html page in string strategy (enum[Strategy.ALL_TEXT, Strategy.MAIN_CONTENT...
[ "def", "extract", "(", "self", ",", "html_text", ":", "str", ",", "strategy", ":", "Strategy", "=", "Strategy", ".", "ALL_TEXT", ")", "->", "List", "[", "Extraction", "]", ":", "if", "html_text", ":", "if", "strategy", "==", "Strategy", ".", "ALL_TEXT", ...
Extracts text from an HTML page using a variety of strategies Args: html_text (str): html page in string strategy (enum[Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_RELAXED, Strategy.MAIN_CONTENT_STRICT]): one of Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_STRICT and Strategy.MAIN_...
[ "Extracts", "text", "from", "an", "HTML", "page", "using", "a", "variety", "of", "strategies" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/html_content_extractor.py#L41-L69
train
usc-isi-i2/etk
etk/data_extractors/htiExtractors/parser_helpers.py
clean_part_ethn
def clean_part_ethn(body): """ Prepare a string to be parsed for ethnicities. Returns a "translated" string (e.g. all instances of "china" converted to "chinese") """ # patterns that can create false positive situations patterns_to_remove = [r'black ?or ?african', r'african ?or ?black', r'no ?black', ...
python
def clean_part_ethn(body): """ Prepare a string to be parsed for ethnicities. Returns a "translated" string (e.g. all instances of "china" converted to "chinese") """ # patterns that can create false positive situations patterns_to_remove = [r'black ?or ?african', r'african ?or ?black', r'no ?black', ...
[ "def", "clean_part_ethn", "(", "body", ")", ":", "patterns_to_remove", "=", "[", "r'black ?or ?african'", ",", "r'african ?or ?black'", ",", "r'no ?black'", ",", "r'no ?african'", ",", "r'no ?aa'", ",", "r'white ?men'", ",", "r'white ?gentlemen'", ",", "r'no ?spanish'",...
Prepare a string to be parsed for ethnicities. Returns a "translated" string (e.g. all instances of "china" converted to "chinese")
[ "Prepare", "a", "string", "to", "be", "parsed", "for", "ethnicities", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/data_extractors/htiExtractors/parser_helpers.py#L70-L103
train
usc-isi-i2/etk
etk/knowledge_graph.py
KnowledgeGraph._add_doc_value
def _add_doc_value(self, field_name: str, jsonpath: str) -> None: """ Add a value to knowledge graph by giving a jsonpath Args: field_name: str jsonpath: str Returns: """ path = self.origin_doc.etk.parse_json_path(jsonpath) matches = path...
python
def _add_doc_value(self, field_name: str, jsonpath: str) -> None: """ Add a value to knowledge graph by giving a jsonpath Args: field_name: str jsonpath: str Returns: """ path = self.origin_doc.etk.parse_json_path(jsonpath) matches = path...
[ "def", "_add_doc_value", "(", "self", ",", "field_name", ":", "str", ",", "jsonpath", ":", "str", ")", "->", "None", ":", "path", "=", "self", ".", "origin_doc", ".", "etk", ".", "parse_json_path", "(", "jsonpath", ")", "matches", "=", "path", ".", "fi...
Add a value to knowledge graph by giving a jsonpath Args: field_name: str jsonpath: str Returns:
[ "Add", "a", "value", "to", "knowledge", "graph", "by", "giving", "a", "jsonpath" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph.py#L109-L132
train
usc-isi-i2/etk
etk/knowledge_graph.py
KnowledgeGraph.add_value
def add_value(self, field_name: str, value: object = None, json_path: str = None, json_path_extraction: str = None, keep_empty: bool = False) -> None: """ Add a value to knowledge graph. Input can either be a value or a json_path. If the input is json_path, the helper function ...
python
def add_value(self, field_name: str, value: object = None, json_path: str = None, json_path_extraction: str = None, keep_empty: bool = False) -> None: """ Add a value to knowledge graph. Input can either be a value or a json_path. If the input is json_path, the helper function ...
[ "def", "add_value", "(", "self", ",", "field_name", ":", "str", ",", "value", ":", "object", "=", "None", ",", "json_path", ":", "str", "=", "None", ",", "json_path_extraction", ":", "str", "=", "None", ",", "keep_empty", ":", "bool", "=", "False", ")"...
Add a value to knowledge graph. Input can either be a value or a json_path. If the input is json_path, the helper function _add_doc_value is called. If the input is a value, then it is handled Args: field_name: str, the field name in the knowledge graph value: th...
[ "Add", "a", "value", "to", "knowledge", "graph", ".", "Input", "can", "either", "be", "a", "value", "or", "a", "json_path", ".", "If", "the", "input", "is", "json_path", "the", "helper", "function", "_add_doc_value", "is", "called", ".", "If", "the", "in...
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph.py#L134-L194
train
usc-isi-i2/etk
etk/knowledge_graph.py
KnowledgeGraph.get_values
def get_values(self, field_name: str) -> List[object]: """ Get a list of all the values of a field. Args: field_name: Returns: the list of values (not the keys) """ result = list() if self.validate_field(field_name): for value_key in sel...
python
def get_values(self, field_name: str) -> List[object]: """ Get a list of all the values of a field. Args: field_name: Returns: the list of values (not the keys) """ result = list() if self.validate_field(field_name): for value_key in sel...
[ "def", "get_values", "(", "self", ",", "field_name", ":", "str", ")", "->", "List", "[", "object", "]", ":", "result", "=", "list", "(", ")", "if", "self", ".", "validate_field", "(", "field_name", ")", ":", "for", "value_key", "in", "self", ".", "_k...
Get a list of all the values of a field. Args: field_name: Returns: the list of values (not the keys)
[ "Get", "a", "list", "of", "all", "the", "values", "of", "a", "field", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph.py#L207-L221
train
usc-isi-i2/etk
etk/knowledge_graph.py
KnowledgeGraph.context_resolve
def context_resolve(self, field_uri: str) -> str: """ According to field_uri to add corresponding context and return a resolvable field_name :param field_uri: :return: a field_name that can be resolved with kg's @context """ from rdflib.namespace import split_uri ...
python
def context_resolve(self, field_uri: str) -> str: """ According to field_uri to add corresponding context and return a resolvable field_name :param field_uri: :return: a field_name that can be resolved with kg's @context """ from rdflib.namespace import split_uri ...
[ "def", "context_resolve", "(", "self", ",", "field_uri", ":", "str", ")", "->", "str", ":", "from", "rdflib", ".", "namespace", "import", "split_uri", "context", "=", "self", ".", "_kg", "[", "\"@context\"", "]", "=", "self", ".", "_kg", ".", "get", "(...
According to field_uri to add corresponding context and return a resolvable field_name :param field_uri: :return: a field_name that can be resolved with kg's @context
[ "According", "to", "field_uri", "to", "add", "corresponding", "context", "and", "return", "a", "resolvable", "field_name" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph.py#L274-L303
train
usc-isi-i2/etk
etk/tokenizer.py
Tokenizer.tokenize_to_spacy_doc
def tokenize_to_spacy_doc(self, text: str) -> Doc: """ Tokenize the given text, returning a spacy doc. Used for spacy rule extractor Args: text (string): Returns: Doc """ if not self.keep_multi_space: text = re.sub(' +', ' ', text) doc =...
python
def tokenize_to_spacy_doc(self, text: str) -> Doc: """ Tokenize the given text, returning a spacy doc. Used for spacy rule extractor Args: text (string): Returns: Doc """ if not self.keep_multi_space: text = re.sub(' +', ' ', text) doc =...
[ "def", "tokenize_to_spacy_doc", "(", "self", ",", "text", ":", "str", ")", "->", "Doc", ":", "if", "not", "self", ".", "keep_multi_space", ":", "text", "=", "re", ".", "sub", "(", "' +'", ",", "' '", ",", "text", ")", "doc", "=", "self", ".", "nlp"...
Tokenize the given text, returning a spacy doc. Used for spacy rule extractor Args: text (string): Returns: Doc
[ "Tokenize", "the", "given", "text", "returning", "a", "spacy", "doc", ".", "Used", "for", "spacy", "rule", "extractor" ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/tokenizer.py#L62-L78
train
usc-isi-i2/etk
etk/tokenizer.py
Tokenizer.reconstruct_text
def reconstruct_text(tokens: List[Token]) -> str: """ Given a list of tokens, reconstruct the original text with as much fidelity as possible. Args: [tokens]: Returns: a string. """ return "".join([x.text_with_ws for x in tokens])
python
def reconstruct_text(tokens: List[Token]) -> str: """ Given a list of tokens, reconstruct the original text with as much fidelity as possible. Args: [tokens]: Returns: a string. """ return "".join([x.text_with_ws for x in tokens])
[ "def", "reconstruct_text", "(", "tokens", ":", "List", "[", "Token", "]", ")", "->", "str", ":", "return", "\"\"", ".", "join", "(", "[", "x", ".", "text_with_ws", "for", "x", "in", "tokens", "]", ")" ]
Given a list of tokens, reconstruct the original text with as much fidelity as possible. Args: [tokens]: Returns: a string.
[ "Given", "a", "list", "of", "tokens", "reconstruct", "the", "original", "text", "with", "as", "much", "fidelity", "as", "possible", "." ]
aab077c984ea20f5e8ae33af622fe11d3c4df866
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/tokenizer.py#L160-L170
train
phodge/homely
homely/_engine2.py
Engine._removecleaner
def _removecleaner(self, cleaner): """ Remove the cleaner from the list if it already exists. Returns True if the cleaner was removed. """ oldlen = len(self._old_cleaners) self._old_cleaners = [ oldc for oldc in self._old_cleaners if not oldc.issam...
python
def _removecleaner(self, cleaner): """ Remove the cleaner from the list if it already exists. Returns True if the cleaner was removed. """ oldlen = len(self._old_cleaners) self._old_cleaners = [ oldc for oldc in self._old_cleaners if not oldc.issam...
[ "def", "_removecleaner", "(", "self", ",", "cleaner", ")", ":", "oldlen", "=", "len", "(", "self", ".", "_old_cleaners", ")", "self", ".", "_old_cleaners", "=", "[", "oldc", "for", "oldc", "in", "self", ".", "_old_cleaners", "if", "not", "oldc", ".", "...
Remove the cleaner from the list if it already exists. Returns True if the cleaner was removed.
[ "Remove", "the", "cleaner", "from", "the", "list", "if", "it", "already", "exists", ".", "Returns", "True", "if", "the", "cleaner", "was", "removed", "." ]
98ddcf3e4f29b0749645817b4866baaea8376085
https://github.com/phodge/homely/blob/98ddcf3e4f29b0749645817b4866baaea8376085/homely/_engine2.py#L254-L264
train
phodge/homely
homely/_cli.py
add
def add(repo_path, dest_path): ''' Registers a git repository with homely so that it will run its `HOMELY.py` script on each invocation of `homely update`. `homely add` also immediately executes a `homely update` so that the dotfiles are installed straight away. If the git repository is hosted onlin...
python
def add(repo_path, dest_path): ''' Registers a git repository with homely so that it will run its `HOMELY.py` script on each invocation of `homely update`. `homely add` also immediately executes a `homely update` so that the dotfiles are installed straight away. If the git repository is hosted onlin...
[ "def", "add", "(", "repo_path", ",", "dest_path", ")", ":", "mkcfgdir", "(", ")", "try", ":", "repo", "=", "getrepohandler", "(", "repo_path", ")", "except", "NotARepo", "as", "err", ":", "echo", "(", "\"ERROR: {}: {}\"", ".", "format", "(", "ERR_NOT_A_REP...
Registers a git repository with homely so that it will run its `HOMELY.py` script on each invocation of `homely update`. `homely add` also immediately executes a `homely update` so that the dotfiles are installed straight away. If the git repository is hosted online, a local clone will be created first....
[ "Registers", "a", "git", "repository", "with", "homely", "so", "that", "it", "will", "run", "its", "HOMELY", ".", "py", "script", "on", "each", "invocation", "of", "homely", "update", ".", "homely", "add", "also", "immediately", "executes", "a", "homely", ...
98ddcf3e4f29b0749645817b4866baaea8376085
https://github.com/phodge/homely/blob/98ddcf3e4f29b0749645817b4866baaea8376085/homely/_cli.py#L72-L120
train
phodge/homely
homely/_cli.py
forget
def forget(identifier): ''' Tells homely to forget about a dotfiles repository that was previously added. You can then run `homely update` to have homely perform automatic cleanup of anything that was installed by that dotfiles repo. REPO This should be the path to a local dotfiles reposito...
python
def forget(identifier): ''' Tells homely to forget about a dotfiles repository that was previously added. You can then run `homely update` to have homely perform automatic cleanup of anything that was installed by that dotfiles repo. REPO This should be the path to a local dotfiles reposito...
[ "def", "forget", "(", "identifier", ")", ":", "errors", "=", "False", "for", "one", "in", "identifier", ":", "cfg", "=", "RepoListConfig", "(", ")", "info", "=", "cfg", ".", "find_by_any", "(", "one", ",", "\"ilc\"", ")", "if", "not", "info", ":", "w...
Tells homely to forget about a dotfiles repository that was previously added. You can then run `homely update` to have homely perform automatic cleanup of anything that was installed by that dotfiles repo. REPO This should be the path to a local dotfiles repository that has already been reg...
[ "Tells", "homely", "to", "forget", "about", "a", "dotfiles", "repository", "that", "was", "previously", "added", ".", "You", "can", "then", "run", "homely", "update", "to", "have", "homely", "perform", "automatic", "cleanup", "of", "anything", "that", "was", ...
98ddcf3e4f29b0749645817b4866baaea8376085
https://github.com/phodge/homely/blob/98ddcf3e4f29b0749645817b4866baaea8376085/homely/_cli.py#L146-L174
train
phodge/homely
homely/_cli.py
update
def update(identifiers, nopull, only): ''' Performs a `git pull` in each of the repositories registered with `homely add`, runs all of their HOMELY.py scripts, and then performs automatic cleanup as necessary. REPO This should be the path to a local dotfiles repository that has already ...
python
def update(identifiers, nopull, only): ''' Performs a `git pull` in each of the repositories registered with `homely add`, runs all of their HOMELY.py scripts, and then performs automatic cleanup as necessary. REPO This should be the path to a local dotfiles repository that has already ...
[ "def", "update", "(", "identifiers", ",", "nopull", ",", "only", ")", ":", "mkcfgdir", "(", ")", "setallowpull", "(", "not", "nopull", ")", "cfg", "=", "RepoListConfig", "(", ")", "if", "len", "(", "identifiers", ")", ":", "updatedict", "=", "{", "}", ...
Performs a `git pull` in each of the repositories registered with `homely add`, runs all of their HOMELY.py scripts, and then performs automatic cleanup as necessary. REPO This should be the path to a local dotfiles repository that has already been registered using `homely add`. If you spec...
[ "Performs", "a", "git", "pull", "in", "each", "of", "the", "repositories", "registered", "with", "homely", "add", "runs", "all", "of", "their", "HOMELY", ".", "py", "scripts", "and", "then", "performs", "automatic", "cleanup", "as", "necessary", "." ]
98ddcf3e4f29b0749645817b4866baaea8376085
https://github.com/phodge/homely/blob/98ddcf3e4f29b0749645817b4866baaea8376085/homely/_cli.py#L185-L227
train
phodge/homely
homely/pipinstall.py
pipinstall
def pipinstall(packagename, pips=None, trypips=[], scripts=None): """ Install packages from pip. The primary advantage of using this function is that homely can automatically remove the package for you when you no longer want it. package: The name of the pip package to install pips: ...
python
def pipinstall(packagename, pips=None, trypips=[], scripts=None): """ Install packages from pip. The primary advantage of using this function is that homely can automatically remove the package for you when you no longer want it. package: The name of the pip package to install pips: ...
[ "def", "pipinstall", "(", "packagename", ",", "pips", "=", "None", ",", "trypips", "=", "[", "]", ",", "scripts", "=", "None", ")", ":", "if", "scripts", "is", "None", ":", "scripts", "=", "{", "}", "if", "pips", "is", "None", ":", "pips", "=", "...
Install packages from pip. The primary advantage of using this function is that homely can automatically remove the package for you when you no longer want it. package: The name of the pip package to install pips: A list of `pip` executables to install the package with. `['pip2.7',...
[ "Install", "packages", "from", "pip", "." ]
98ddcf3e4f29b0749645817b4866baaea8376085
https://github.com/phodge/homely/blob/98ddcf3e4f29b0749645817b4866baaea8376085/homely/pipinstall.py#L12-L60
train
phodge/homely
homely/_utils.py
getstatus
def getstatus(): """Get the status of the previous 'homely update', or any 'homely update' that may be running in another process. """ if exists(RUNFILE): mtime = os.stat(RUNFILE).st_mtime with open(SECTIONFILE) as f: section = f.read().strip() # what section? ...
python
def getstatus(): """Get the status of the previous 'homely update', or any 'homely update' that may be running in another process. """ if exists(RUNFILE): mtime = os.stat(RUNFILE).st_mtime with open(SECTIONFILE) as f: section = f.read().strip() # what section? ...
[ "def", "getstatus", "(", ")", ":", "if", "exists", "(", "RUNFILE", ")", ":", "mtime", "=", "os", ".", "stat", "(", "RUNFILE", ")", ".", "st_mtime", "with", "open", "(", "SECTIONFILE", ")", "as", "f", ":", "section", "=", "f", ".", "read", "(", ")...
Get the status of the previous 'homely update', or any 'homely update' that may be running in another process.
[ "Get", "the", "status", "of", "the", "previous", "homely", "update", "or", "any", "homely", "update", "that", "may", "be", "running", "in", "another", "process", "." ]
98ddcf3e4f29b0749645817b4866baaea8376085
https://github.com/phodge/homely/blob/98ddcf3e4f29b0749645817b4866baaea8376085/homely/_utils.py#L615-L648
train
phodge/homely
homely/_utils.py
RepoListConfig.find_by_any
def find_by_any(self, identifier, how): """ how should be a string with any or all of the characters "ilc" """ if "i" in how: match = self.find_by_id(identifier) if match: return match if "l" in how: match = self.find_by_localpa...
python
def find_by_any(self, identifier, how): """ how should be a string with any or all of the characters "ilc" """ if "i" in how: match = self.find_by_id(identifier) if match: return match if "l" in how: match = self.find_by_localpa...
[ "def", "find_by_any", "(", "self", ",", "identifier", ",", "how", ")", ":", "if", "\"i\"", "in", "how", ":", "match", "=", "self", ".", "find_by_id", "(", "identifier", ")", "if", "match", ":", "return", "match", "if", "\"l\"", "in", "how", ":", "mat...
how should be a string with any or all of the characters "ilc"
[ "how", "should", "be", "a", "string", "with", "any", "or", "all", "of", "the", "characters", "ilc" ]
98ddcf3e4f29b0749645817b4866baaea8376085
https://github.com/phodge/homely/blob/98ddcf3e4f29b0749645817b4866baaea8376085/homely/_utils.py#L339-L354
train
glyph/automat
automat/_discover.py
isOriginalLocation
def isOriginalLocation(attr): """ Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined. """ sourceModule = inspect.getmodule(attr.load()) if sourceModule is None: return False currentModule = attr ...
python
def isOriginalLocation(attr): """ Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined. """ sourceModule = inspect.getmodule(attr.load()) if sourceModule is None: return False currentModule = attr ...
[ "def", "isOriginalLocation", "(", "attr", ")", ":", "sourceModule", "=", "inspect", ".", "getmodule", "(", "attr", ".", "load", "(", ")", ")", "if", "sourceModule", "is", "None", ":", "return", "False", "currentModule", "=", "attr", "while", "not", "isinst...
Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined.
[ "Attempt", "to", "discover", "if", "this", "appearance", "of", "a", "PythonAttribute", "representing", "a", "class", "refers", "to", "the", "module", "where", "that", "class", "was", "defined", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_discover.py#L7-L21
train
glyph/automat
automat/_core.py
Automaton.initialState
def initialState(self, state): """ Set this automaton's initial state. Raises a ValueError if this automaton already has an initial state. """ if self._initialState is not _NO_STATE: raise ValueError( "initial state already set to {}".format(self._in...
python
def initialState(self, state): """ Set this automaton's initial state. Raises a ValueError if this automaton already has an initial state. """ if self._initialState is not _NO_STATE: raise ValueError( "initial state already set to {}".format(self._in...
[ "def", "initialState", "(", "self", ",", "state", ")", ":", "if", "self", ".", "_initialState", "is", "not", "_NO_STATE", ":", "raise", "ValueError", "(", "\"initial state already set to {}\"", ".", "format", "(", "self", ".", "_initialState", ")", ")", "self"...
Set this automaton's initial state. Raises a ValueError if this automaton already has an initial state.
[ "Set", "this", "automaton", "s", "initial", "state", ".", "Raises", "a", "ValueError", "if", "this", "automaton", "already", "has", "an", "initial", "state", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_core.py#L56-L66
train
glyph/automat
automat/_core.py
Automaton.addTransition
def addTransition(self, inState, inputSymbol, outState, outputSymbols): """ Add the given transition to the outputSymbol. Raise ValueError if there is already a transition with the same inState and inputSymbol. """ # keeping self._transitions in a flat list makes addTransition ...
python
def addTransition(self, inState, inputSymbol, outState, outputSymbols): """ Add the given transition to the outputSymbol. Raise ValueError if there is already a transition with the same inState and inputSymbol. """ # keeping self._transitions in a flat list makes addTransition ...
[ "def", "addTransition", "(", "self", ",", "inState", ",", "inputSymbol", ",", "outState", ",", "outputSymbols", ")", ":", "for", "(", "anInState", ",", "anInputSymbol", ",", "anOutState", ",", "_", ")", "in", "self", ".", "_transitions", ":", "if", "(", ...
Add the given transition to the outputSymbol. Raise ValueError if there is already a transition with the same inState and inputSymbol.
[ "Add", "the", "given", "transition", "to", "the", "outputSymbol", ".", "Raise", "ValueError", "if", "there", "is", "already", "a", "transition", "with", "the", "same", "inState", "and", "inputSymbol", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_core.py#L69-L83
train
glyph/automat
automat/_core.py
Automaton.outputAlphabet
def outputAlphabet(self): """ The full set of symbols which can be produced by this automaton. """ return set( chain.from_iterable( outputSymbols for (inState, inputSymbol, outState, outputSymbols) in self._transitions ...
python
def outputAlphabet(self): """ The full set of symbols which can be produced by this automaton. """ return set( chain.from_iterable( outputSymbols for (inState, inputSymbol, outState, outputSymbols) in self._transitions ...
[ "def", "outputAlphabet", "(", "self", ")", ":", "return", "set", "(", "chain", ".", "from_iterable", "(", "outputSymbols", "for", "(", "inState", ",", "inputSymbol", ",", "outState", ",", "outputSymbols", ")", "in", "self", ".", "_transitions", ")", ")" ]
The full set of symbols which can be produced by this automaton.
[ "The", "full", "set", "of", "symbols", "which", "can", "be", "produced", "by", "this", "automaton", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_core.py#L101-L111
train
glyph/automat
automat/_core.py
Automaton.states
def states(self): """ All valid states; "Q" in the mathematical description of a state machine. """ return frozenset( chain.from_iterable( (inState, outState) for (inState, inputSymbol, outState, outputSymbol) ...
python
def states(self): """ All valid states; "Q" in the mathematical description of a state machine. """ return frozenset( chain.from_iterable( (inState, outState) for (inState, inputSymbol, outState, outputSymbol) ...
[ "def", "states", "(", "self", ")", ":", "return", "frozenset", "(", "chain", ".", "from_iterable", "(", "(", "inState", ",", "outState", ")", "for", "(", "inState", ",", "inputSymbol", ",", "outState", ",", "outputSymbol", ")", "in", "self", ".", "_trans...
All valid states; "Q" in the mathematical description of a state machine.
[ "All", "valid", "states", ";", "Q", "in", "the", "mathematical", "description", "of", "a", "state", "machine", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_core.py#L114-L126
train
glyph/automat
automat/_core.py
Transitioner.transition
def transition(self, inputSymbol): """ Transition between states, returning any outputs. """ outState, outputSymbols = self._automaton.outputForInput(self._state, inputSymbol) outTracer = None if self._trace...
python
def transition(self, inputSymbol): """ Transition between states, returning any outputs. """ outState, outputSymbols = self._automaton.outputForInput(self._state, inputSymbol) outTracer = None if self._trace...
[ "def", "transition", "(", "self", ",", "inputSymbol", ")", ":", "outState", ",", "outputSymbols", "=", "self", ".", "_automaton", ".", "outputForInput", "(", "self", ".", "_state", ",", "inputSymbol", ")", "outTracer", "=", "None", "if", "self", ".", "_tra...
Transition between states, returning any outputs.
[ "Transition", "between", "states", "returning", "any", "outputs", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_core.py#L153-L165
train
glyph/automat
automat/_methodical.py
_getArgSpec
def _getArgSpec(func): """ Normalize inspect.ArgSpec across python versions and convert mutable attributes to immutable types. :param Callable func: A function. :return: The function's ArgSpec. :rtype: ArgSpec """ spec = getArgsSpec(func) return ArgSpec( args=tuple(spec.args...
python
def _getArgSpec(func): """ Normalize inspect.ArgSpec across python versions and convert mutable attributes to immutable types. :param Callable func: A function. :return: The function's ArgSpec. :rtype: ArgSpec """ spec = getArgsSpec(func) return ArgSpec( args=tuple(spec.args...
[ "def", "_getArgSpec", "(", "func", ")", ":", "spec", "=", "getArgsSpec", "(", "func", ")", "return", "ArgSpec", "(", "args", "=", "tuple", "(", "spec", ".", "args", ")", ",", "varargs", "=", "spec", ".", "varargs", ",", "varkw", "=", "spec", ".", "...
Normalize inspect.ArgSpec across python versions and convert mutable attributes to immutable types. :param Callable func: A function. :return: The function's ArgSpec. :rtype: ArgSpec
[ "Normalize", "inspect", ".", "ArgSpec", "across", "python", "versions", "and", "convert", "mutable", "attributes", "to", "immutable", "types", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_methodical.py#L26-L47
train
glyph/automat
automat/_methodical.py
_getArgNames
def _getArgNames(spec): """ Get the name of all arguments defined in a function signature. The name of * and ** arguments is normalized to "*args" and "**kwargs". :param ArgSpec spec: A function to interrogate for a signature. :return: The set of all argument names in `func`s signature. :rtype...
python
def _getArgNames(spec): """ Get the name of all arguments defined in a function signature. The name of * and ** arguments is normalized to "*args" and "**kwargs". :param ArgSpec spec: A function to interrogate for a signature. :return: The set of all argument names in `func`s signature. :rtype...
[ "def", "_getArgNames", "(", "spec", ")", ":", "return", "set", "(", "spec", ".", "args", "+", "spec", ".", "kwonlyargs", "+", "(", "(", "'*args'", ",", ")", "if", "spec", ".", "varargs", "else", "(", ")", ")", "+", "(", "(", "'**kwargs'", ",", ")...
Get the name of all arguments defined in a function signature. The name of * and ** arguments is normalized to "*args" and "**kwargs". :param ArgSpec spec: A function to interrogate for a signature. :return: The set of all argument names in `func`s signature. :rtype: Set[str]
[ "Get", "the", "name", "of", "all", "arguments", "defined", "in", "a", "function", "signature", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_methodical.py#L50-L66
train
glyph/automat
automat/_methodical.py
_keywords_only
def _keywords_only(f): """ Decorate a function so all its arguments must be passed by keyword. A useful utility for decorators that take arguments so that they don't accidentally get passed the thing they're decorating as their first argument. Only works for methods right now. """ @wra...
python
def _keywords_only(f): """ Decorate a function so all its arguments must be passed by keyword. A useful utility for decorators that take arguments so that they don't accidentally get passed the thing they're decorating as their first argument. Only works for methods right now. """ @wra...
[ "def", "_keywords_only", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "g", "(", "self", ",", "**", "kw", ")", ":", "return", "f", "(", "self", ",", "**", "kw", ")", "return", "g" ]
Decorate a function so all its arguments must be passed by keyword. A useful utility for decorators that take arguments so that they don't accidentally get passed the thing they're decorating as their first argument. Only works for methods right now.
[ "Decorate", "a", "function", "so", "all", "its", "arguments", "must", "be", "passed", "by", "keyword", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_methodical.py#L69-L82
train
glyph/automat
automat/_methodical.py
_filterArgs
def _filterArgs(args, kwargs, inputSpec, outputSpec): """ Filter out arguments that were passed to input that output won't accept. :param tuple args: The *args that input received. :param dict kwargs: The **kwargs that input received. :param ArgSpec inputSpec: The input's arg spec. :param ArgSp...
python
def _filterArgs(args, kwargs, inputSpec, outputSpec): """ Filter out arguments that were passed to input that output won't accept. :param tuple args: The *args that input received. :param dict kwargs: The **kwargs that input received. :param ArgSpec inputSpec: The input's arg spec. :param ArgSp...
[ "def", "_filterArgs", "(", "args", ",", "kwargs", ",", "inputSpec", ",", "outputSpec", ")", ":", "named_args", "=", "tuple", "(", "zip", "(", "inputSpec", ".", "args", "[", "1", ":", "]", ",", "args", ")", ")", "if", "outputSpec", ".", "varargs", ":"...
Filter out arguments that were passed to input that output won't accept. :param tuple args: The *args that input received. :param dict kwargs: The **kwargs that input received. :param ArgSpec inputSpec: The input's arg spec. :param ArgSpec outputSpec: The output's arg spec. :return: The args and kw...
[ "Filter", "out", "arguments", "that", "were", "passed", "to", "input", "that", "output", "won", "t", "accept", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_methodical.py#L169-L206
train
glyph/automat
automat/_methodical.py
MethodicalMachine.state
def state(self, initial=False, terminal=False, serialized=None): """ Declare a state, possibly an initial state or a terminal state. This is a decorator for methods, but it will modify the method so as not to be callable any more. :param bool initial: is this stat...
python
def state(self, initial=False, terminal=False, serialized=None): """ Declare a state, possibly an initial state or a terminal state. This is a decorator for methods, but it will modify the method so as not to be callable any more. :param bool initial: is this stat...
[ "def", "state", "(", "self", ",", "initial", "=", "False", ",", "terminal", "=", "False", ",", "serialized", "=", "None", ")", ":", "def", "decorator", "(", "stateMethod", ")", ":", "state", "=", "MethodicalState", "(", "machine", "=", "self", ",", "me...
Declare a state, possibly an initial state or a terminal state. This is a decorator for methods, but it will modify the method so as not to be callable any more. :param bool initial: is this state the initial state? Only one state on this :class:`automat.MethodicalMachine` ...
[ "Declare", "a", "state", "possibly", "an", "initial", "state", "or", "a", "terminal", "state", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_methodical.py#L337-L365
train
glyph/automat
automat/_methodical.py
MethodicalMachine.input
def input(self): """ Declare an input. This is a decorator for methods. """ def decorator(inputMethod): return MethodicalInput(automaton=self._automaton, method=inputMethod, symbol=self._symbol) ...
python
def input(self): """ Declare an input. This is a decorator for methods. """ def decorator(inputMethod): return MethodicalInput(automaton=self._automaton, method=inputMethod, symbol=self._symbol) ...
[ "def", "input", "(", "self", ")", ":", "def", "decorator", "(", "inputMethod", ")", ":", "return", "MethodicalInput", "(", "automaton", "=", "self", ".", "_automaton", ",", "method", "=", "inputMethod", ",", "symbol", "=", "self", ".", "_symbol", ")", "r...
Declare an input. This is a decorator for methods.
[ "Declare", "an", "input", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_methodical.py#L369-L379
train
glyph/automat
automat/_methodical.py
MethodicalMachine.output
def output(self): """ Declare an output. This is a decorator for methods. This method will be called when the state machine transitions to this state as specified in the decorated `output` method. """ def decorator(outputMethod): return MethodicalOut...
python
def output(self): """ Declare an output. This is a decorator for methods. This method will be called when the state machine transitions to this state as specified in the decorated `output` method. """ def decorator(outputMethod): return MethodicalOut...
[ "def", "output", "(", "self", ")", ":", "def", "decorator", "(", "outputMethod", ")", ":", "return", "MethodicalOutput", "(", "machine", "=", "self", ",", "method", "=", "outputMethod", ")", "return", "decorator" ]
Declare an output. This is a decorator for methods. This method will be called when the state machine transitions to this state as specified in the decorated `output` method.
[ "Declare", "an", "output", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_methodical.py#L383-L394
train
glyph/automat
automat/_visualize.py
elementMaker
def elementMaker(name, *children, **attrs): """ Construct a string from the HTML element description. """ formattedAttrs = ' '.join('{}={}'.format(key, _gvquote(str(value))) for key, value in sorted(attrs.items())) formattedChildren = ''.join(children) return u'<{na...
python
def elementMaker(name, *children, **attrs): """ Construct a string from the HTML element description. """ formattedAttrs = ' '.join('{}={}'.format(key, _gvquote(str(value))) for key, value in sorted(attrs.items())) formattedChildren = ''.join(children) return u'<{na...
[ "def", "elementMaker", "(", "name", ",", "*", "children", ",", "**", "attrs", ")", ":", "formattedAttrs", "=", "' '", ".", "join", "(", "'{}={}'", ".", "format", "(", "key", ",", "_gvquote", "(", "str", "(", "value", ")", ")", ")", "for", "key", ",...
Construct a string from the HTML element description.
[ "Construct", "a", "string", "from", "the", "HTML", "element", "description", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_visualize.py#L18-L28
train
glyph/automat
automat/_visualize.py
tableMaker
def tableMaker(inputLabel, outputLabels, port, _E=elementMaker): """ Construct an HTML table to label a state transition. """ colspan = {} if outputLabels: colspan['colspan'] = str(len(outputLabels)) inputLabelCell = _E("td", _E("font", ...
python
def tableMaker(inputLabel, outputLabels, port, _E=elementMaker): """ Construct an HTML table to label a state transition. """ colspan = {} if outputLabels: colspan['colspan'] = str(len(outputLabels)) inputLabelCell = _E("td", _E("font", ...
[ "def", "tableMaker", "(", "inputLabel", ",", "outputLabels", ",", "port", ",", "_E", "=", "elementMaker", ")", ":", "colspan", "=", "{", "}", "if", "outputLabels", ":", "colspan", "[", "'colspan'", "]", "=", "str", "(", "len", "(", "outputLabels", ")", ...
Construct an HTML table to label a state transition.
[ "Construct", "an", "HTML", "table", "to", "label", "a", "state", "transition", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_visualize.py#L31-L60
train
glyph/automat
automat/_introspection.py
preserveName
def preserveName(f): """ Preserve the name of the given function on the decorated function. """ def decorator(decorated): return copyfunction(decorated, dict(name=f.__name__), dict(name=f.__name__)) return decorator
python
def preserveName(f): """ Preserve the name of the given function on the decorated function. """ def decorator(decorated): return copyfunction(decorated, dict(name=f.__name__), dict(name=f.__name__)) return decorator
[ "def", "preserveName", "(", "f", ")", ":", "def", "decorator", "(", "decorated", ")", ":", "return", "copyfunction", "(", "decorated", ",", "dict", "(", "name", "=", "f", ".", "__name__", ")", ",", "dict", "(", "name", "=", "f", ".", "__name__", ")",...
Preserve the name of the given function on the decorated function.
[ "Preserve", "the", "name", "of", "the", "given", "function", "on", "the", "decorated", "function", "." ]
80c6eb925eeef120443f4f9c81398bea629884b8
https://github.com/glyph/automat/blob/80c6eb925eeef120443f4f9c81398bea629884b8/automat/_introspection.py#L35-L42
train
heroku/kafka-helper
kafka_helper.py
get_kafka_ssl_context
def get_kafka_ssl_context(): """ Returns an SSL context based on the certificate information in the Kafka config vars. """ # NOTE: We assume that Kafka environment variables are present. If using # Apache Kafka on Heroku, they will be available in your app configuration. # # 1. Write the PEM...
python
def get_kafka_ssl_context(): """ Returns an SSL context based on the certificate information in the Kafka config vars. """ # NOTE: We assume that Kafka environment variables are present. If using # Apache Kafka on Heroku, they will be available in your app configuration. # # 1. Write the PEM...
[ "def", "get_kafka_ssl_context", "(", ")", ":", "with", "NamedTemporaryFile", "(", "suffix", "=", "'.crt'", ")", "as", "cert_file", ",", "NamedTemporaryFile", "(", "suffix", "=", "'.key'", ")", "as", "key_file", ",", "NamedTemporaryFile", "(", "suffix", "=", "'...
Returns an SSL context based on the certificate information in the Kafka config vars.
[ "Returns", "an", "SSL", "context", "based", "on", "the", "certificate", "information", "in", "the", "Kafka", "config", "vars", "." ]
33d809ac4d6e7294ff44f18635d4ea71c882906a
https://github.com/heroku/kafka-helper/blob/33d809ac4d6e7294ff44f18635d4ea71c882906a/kafka_helper.py#L22-L81
train
heroku/kafka-helper
kafka_helper.py
get_kafka_producer
def get_kafka_producer(acks='all', value_serializer=lambda v: json.dumps(v).encode('utf-8')): """ Return a KafkaProducer that uses the SSLContext created with create_ssl_context. """ producer = KafkaProducer( bootstrap_servers=get_kafka_brokers(), security_protoco...
python
def get_kafka_producer(acks='all', value_serializer=lambda v: json.dumps(v).encode('utf-8')): """ Return a KafkaProducer that uses the SSLContext created with create_ssl_context. """ producer = KafkaProducer( bootstrap_servers=get_kafka_brokers(), security_protoco...
[ "def", "get_kafka_producer", "(", "acks", "=", "'all'", ",", "value_serializer", "=", "lambda", "v", ":", "json", ".", "dumps", "(", "v", ")", ".", "encode", "(", "'utf-8'", ")", ")", ":", "producer", "=", "KafkaProducer", "(", "bootstrap_servers", "=", ...
Return a KafkaProducer that uses the SSLContext created with create_ssl_context.
[ "Return", "a", "KafkaProducer", "that", "uses", "the", "SSLContext", "created", "with", "create_ssl_context", "." ]
33d809ac4d6e7294ff44f18635d4ea71c882906a
https://github.com/heroku/kafka-helper/blob/33d809ac4d6e7294ff44f18635d4ea71c882906a/kafka_helper.py#L98-L112
train
heroku/kafka-helper
kafka_helper.py
get_kafka_consumer
def get_kafka_consumer(topic=None, value_deserializer=lambda v: json.loads(v.decode('utf-8'))): """ Return a KafkaConsumer that uses the SSLContext created with create_ssl_context. """ # Create the KafkaConsumer connected to the specified brokers. Use the # SSLContext that is...
python
def get_kafka_consumer(topic=None, value_deserializer=lambda v: json.loads(v.decode('utf-8'))): """ Return a KafkaConsumer that uses the SSLContext created with create_ssl_context. """ # Create the KafkaConsumer connected to the specified brokers. Use the # SSLContext that is...
[ "def", "get_kafka_consumer", "(", "topic", "=", "None", ",", "value_deserializer", "=", "lambda", "v", ":", "json", ".", "loads", "(", "v", ".", "decode", "(", "'utf-8'", ")", ")", ")", ":", "consumer", "=", "KafkaConsumer", "(", "topic", ",", "bootstrap...
Return a KafkaConsumer that uses the SSLContext created with create_ssl_context.
[ "Return", "a", "KafkaConsumer", "that", "uses", "the", "SSLContext", "created", "with", "create_ssl_context", "." ]
33d809ac4d6e7294ff44f18635d4ea71c882906a
https://github.com/heroku/kafka-helper/blob/33d809ac4d6e7294ff44f18635d4ea71c882906a/kafka_helper.py#L115-L131
train
goerz/clusterjob
clusterjob/backends/sge.py
SgeBackend.replace_body_vars
def replace_body_vars(self, body): """Given a multiline string that is the body of the job script, replace the placeholders for environment variables with backend-specific realizations, and return the modified body. See the `job_vars` attribute for the mappings that are performed. ...
python
def replace_body_vars(self, body): """Given a multiline string that is the body of the job script, replace the placeholders for environment variables with backend-specific realizations, and return the modified body. See the `job_vars` attribute for the mappings that are performed. ...
[ "def", "replace_body_vars", "(", "self", ",", "body", ")", ":", "for", "key", ",", "val", "in", "self", ".", "job_vars", ".", "items", "(", ")", ":", "body", "=", "body", ".", "replace", "(", "key", ",", "val", ")", "return", "body" ]
Given a multiline string that is the body of the job script, replace the placeholders for environment variables with backend-specific realizations, and return the modified body. See the `job_vars` attribute for the mappings that are performed.
[ "Given", "a", "multiline", "string", "that", "is", "the", "body", "of", "the", "job", "script", "replace", "the", "placeholders", "for", "environment", "variables", "with", "backend", "-", "specific", "realizations", "and", "return", "the", "modified", "body", ...
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/backends/sge.py#L157-L165
train
goerz/clusterjob
clusterjob/utils.py
set_executable
def set_executable(filename): """Set the exectuable bit on the given filename""" st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC)
python
def set_executable(filename): """Set the exectuable bit on the given filename""" st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC)
[ "def", "set_executable", "(", "filename", ")", ":", "st", "=", "os", ".", "stat", "(", "filename", ")", "os", ".", "chmod", "(", "filename", ",", "st", ".", "st_mode", "|", "stat", ".", "S_IEXEC", ")" ]
Set the exectuable bit on the given filename
[ "Set", "the", "exectuable", "bit", "on", "the", "given", "filename" ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/utils.py#L19-L22
train
goerz/clusterjob
clusterjob/utils.py
split_seq
def split_seq(seq, n_chunks): """Split the given sequence into `n_chunks`. Suitable for distributing an array of jobs over a fixed number of workers. >>> split_seq([1,2,3,4,5,6], 3) [[1, 2], [3, 4], [5, 6]] >>> split_seq([1,2,3,4,5,6], 2) [[1, 2, 3], [4, 5, 6]] >>> split_seq([1,2,3,4,5,6,7]...
python
def split_seq(seq, n_chunks): """Split the given sequence into `n_chunks`. Suitable for distributing an array of jobs over a fixed number of workers. >>> split_seq([1,2,3,4,5,6], 3) [[1, 2], [3, 4], [5, 6]] >>> split_seq([1,2,3,4,5,6], 2) [[1, 2, 3], [4, 5, 6]] >>> split_seq([1,2,3,4,5,6,7]...
[ "def", "split_seq", "(", "seq", ",", "n_chunks", ")", ":", "newseq", "=", "[", "]", "splitsize", "=", "1.0", "/", "n_chunks", "*", "len", "(", "seq", ")", "for", "i", "in", "range", "(", "n_chunks", ")", ":", "newseq", ".", "append", "(", "seq", ...
Split the given sequence into `n_chunks`. Suitable for distributing an array of jobs over a fixed number of workers. >>> split_seq([1,2,3,4,5,6], 3) [[1, 2], [3, 4], [5, 6]] >>> split_seq([1,2,3,4,5,6], 2) [[1, 2, 3], [4, 5, 6]] >>> split_seq([1,2,3,4,5,6,7], 3) [[1, 2], [3, 4, 5], [6, 7]]
[ "Split", "the", "given", "sequence", "into", "n_chunks", ".", "Suitable", "for", "distributing", "an", "array", "of", "jobs", "over", "a", "fixed", "number", "of", "workers", "." ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/utils.py#L31-L46
train
goerz/clusterjob
clusterjob/__init__.py
AsyncResult.status
def status(self): """Return the job status as one of the codes defined in the `clusterjob.status` module. finished, communicate with the cluster to determine the job's status. """ if self._status >= COMPLETED: return self._status else: cmd = self.b...
python
def status(self): """Return the job status as one of the codes defined in the `clusterjob.status` module. finished, communicate with the cluster to determine the job's status. """ if self._status >= COMPLETED: return self._status else: cmd = self.b...
[ "def", "status", "(", "self", ")", ":", "if", "self", ".", "_status", ">=", "COMPLETED", ":", "return", "self", ".", "_status", "else", ":", "cmd", "=", "self", ".", "backend", ".", "cmd_status", "(", "self", ",", "finished", "=", "False", ")", "resp...
Return the job status as one of the codes defined in the `clusterjob.status` module. finished, communicate with the cluster to determine the job's status.
[ "Return", "the", "job", "status", "as", "one", "of", "the", "codes", "defined", "in", "the", "clusterjob", ".", "status", "module", ".", "finished", "communicate", "with", "the", "cluster", "to", "determine", "the", "job", "s", "status", "." ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L927-L952
train
goerz/clusterjob
clusterjob/__init__.py
AsyncResult.dump
def dump(self, cache_file=None): """Write dump out to file `cache_file`, defaulting to ``self.cache_file``""" if cache_file is None: cache_file = self.cache_file if cache_file is not None: self.cache_file = cache_file with open(cache_file, 'wb') as pic...
python
def dump(self, cache_file=None): """Write dump out to file `cache_file`, defaulting to ``self.cache_file``""" if cache_file is None: cache_file = self.cache_file if cache_file is not None: self.cache_file = cache_file with open(cache_file, 'wb') as pic...
[ "def", "dump", "(", "self", ",", "cache_file", "=", "None", ")", ":", "if", "cache_file", "is", "None", ":", "cache_file", "=", "self", ".", "cache_file", "if", "cache_file", "is", "not", "None", ":", "self", ".", "cache_file", "=", "cache_file", "with",...
Write dump out to file `cache_file`, defaulting to ``self.cache_file``
[ "Write", "dump", "out", "to", "file", "cache_file", "defaulting", "to", "self", ".", "cache_file" ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L963-L975
train
goerz/clusterjob
clusterjob/__init__.py
AsyncResult.load
def load(cls, cache_file, backend=None): """Instantiate AsyncResult from dumped `cache_file`. This is the inverse of :meth:`dump`. Parameters ---------- cache_file: str Name of file from which the run should be read. backend: clusterjob.backen...
python
def load(cls, cache_file, backend=None): """Instantiate AsyncResult from dumped `cache_file`. This is the inverse of :meth:`dump`. Parameters ---------- cache_file: str Name of file from which the run should be read. backend: clusterjob.backen...
[ "def", "load", "(", "cls", ",", "cache_file", ",", "backend", "=", "None", ")", ":", "with", "open", "(", "cache_file", ",", "'rb'", ")", "as", "pickle_fh", ":", "(", "remote", ",", "backend_name", ",", "max_sleep_interval", ",", "job_id", ",", "status",...
Instantiate AsyncResult from dumped `cache_file`. This is the inverse of :meth:`dump`. Parameters ---------- cache_file: str Name of file from which the run should be read. backend: clusterjob.backends.ClusterjobBackend or None The bac...
[ "Instantiate", "AsyncResult", "from", "dumped", "cache_file", "." ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L978-L1003
train
goerz/clusterjob
clusterjob/__init__.py
AsyncResult.wait
def wait(self, timeout=None): """Wait until the result is available or until roughly timeout seconds pass.""" logger = logging.getLogger(__name__) if int(self.max_sleep_interval) < int(self._min_sleep_interval): self.max_sleep_interval = int(self._min_sleep_interval) ...
python
def wait(self, timeout=None): """Wait until the result is available or until roughly timeout seconds pass.""" logger = logging.getLogger(__name__) if int(self.max_sleep_interval) < int(self._min_sleep_interval): self.max_sleep_interval = int(self._min_sleep_interval) ...
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "int", "(", "self", ".", "max_sleep_interval", ")", "<", "int", "(", "self", ".", "_min_sleep_interval", ")", ":"...
Wait until the result is available or until roughly timeout seconds pass.
[ "Wait", "until", "the", "result", "is", "available", "or", "until", "roughly", "timeout", "seconds", "pass", "." ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L1005-L1026
train
goerz/clusterjob
clusterjob/__init__.py
AsyncResult.successful
def successful(self): """Return True if the job finished with a COMPLETED status, False if it finished with a CANCELLED or FAILED status. Raise an `AssertionError` if the job has not completed""" status = self.status assert status >= COMPLETED, "status is %s" % status ret...
python
def successful(self): """Return True if the job finished with a COMPLETED status, False if it finished with a CANCELLED or FAILED status. Raise an `AssertionError` if the job has not completed""" status = self.status assert status >= COMPLETED, "status is %s" % status ret...
[ "def", "successful", "(", "self", ")", ":", "status", "=", "self", ".", "status", "assert", "status", ">=", "COMPLETED", ",", "\"status is %s\"", "%", "status", "return", "(", "self", ".", "status", "==", "COMPLETED", ")" ]
Return True if the job finished with a COMPLETED status, False if it finished with a CANCELLED or FAILED status. Raise an `AssertionError` if the job has not completed
[ "Return", "True", "if", "the", "job", "finished", "with", "a", "COMPLETED", "status", "False", "if", "it", "finished", "with", "a", "CANCELLED", "or", "FAILED", "status", ".", "Raise", "an", "AssertionError", "if", "the", "job", "has", "not", "completed" ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L1032-L1038
train
goerz/clusterjob
clusterjob/__init__.py
AsyncResult.cancel
def cancel(self): """Instruct the cluster to cancel the running job. Has no effect if job is not running""" if self.status > COMPLETED: return cmd = self.backend.cmd_cancel(self) self._run_cmd(cmd, self.remote, ignore_exit_code=True, ssh=self.ssh) self._status...
python
def cancel(self): """Instruct the cluster to cancel the running job. Has no effect if job is not running""" if self.status > COMPLETED: return cmd = self.backend.cmd_cancel(self) self._run_cmd(cmd, self.remote, ignore_exit_code=True, ssh=self.ssh) self._status...
[ "def", "cancel", "(", "self", ")", ":", "if", "self", ".", "status", ">", "COMPLETED", ":", "return", "cmd", "=", "self", ".", "backend", ".", "cmd_cancel", "(", "self", ")", "self", ".", "_run_cmd", "(", "cmd", ",", "self", ".", "remote", ",", "ig...
Instruct the cluster to cancel the running job. Has no effect if job is not running
[ "Instruct", "the", "cluster", "to", "cancel", "the", "running", "job", ".", "Has", "no", "effect", "if", "job", "is", "not", "running" ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L1040-L1048
train
goerz/clusterjob
clusterjob/__init__.py
AsyncResult.run_epilogue
def run_epilogue(self): """Run the epilogue script in the current working directory. raises: subprocess.CalledProcessError: if the script does not finish with exit code zero. """ logger = logging.getLogger(__name__) if self.epilogue is not None: ...
python
def run_epilogue(self): """Run the epilogue script in the current working directory. raises: subprocess.CalledProcessError: if the script does not finish with exit code zero. """ logger = logging.getLogger(__name__) if self.epilogue is not None: ...
[ "def", "run_epilogue", "(", "self", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "self", ".", "epilogue", "is", "not", "None", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "'w'", ",", "delete", "=", "False...
Run the epilogue script in the current working directory. raises: subprocess.CalledProcessError: if the script does not finish with exit code zero.
[ "Run", "the", "epilogue", "script", "in", "the", "current", "working", "directory", "." ]
361760d1a6dd3cbde49c5c2158a3acd0c314a749
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L1050-L1079
train
kennknowles/python-jsonpath-rw
jsonpath_rw/lexer.py
JsonPathLexer.t_ID
def t_ID(self, t): r'[a-zA-Z_@][a-zA-Z0-9_@\-]*' t.type = self.reserved_words.get(t.value, 'ID') return t
python
def t_ID(self, t): r'[a-zA-Z_@][a-zA-Z0-9_@\-]*' t.type = self.reserved_words.get(t.value, 'ID') return t
[ "def", "t_ID", "(", "self", ",", "t", ")", ":", "r'[a-zA-Z_@][a-zA-Z0-9_@\\-]*'", "t", ".", "type", "=", "self", ".", "reserved_words", ".", "get", "(", "t", ".", "value", ",", "'ID'", ")", "return", "t" ]
r'[a-zA-Z_@][a-zA-Z0-9_@\-]*
[ "r", "[", "a", "-", "zA", "-", "Z_" ]
f615451d7b405e23e0f80b15cad03b1427b0256d
https://github.com/kennknowles/python-jsonpath-rw/blob/f615451d7b405e23e0f80b15cad03b1427b0256d/jsonpath_rw/lexer.py#L63-L66
train
kennknowles/python-jsonpath-rw
jsonpath_rw/lexer.py
JsonPathLexer.t_newline
def t_newline(self, t): r'\n' t.lexer.lineno += 1 t.lexer.latest_newline = t.lexpos
python
def t_newline(self, t): r'\n' t.lexer.lineno += 1 t.lexer.latest_newline = t.lexpos
[ "def", "t_newline", "(", "self", ",", "t", ")", ":", "r'\\n'", "t", ".", "lexer", ".", "lineno", "+=", "1", "t", ".", "lexer", ".", "latest_newline", "=", "t", ".", "lexpos" ]
r'\n
[ "r", "\\", "n" ]
f615451d7b405e23e0f80b15cad03b1427b0256d
https://github.com/kennknowles/python-jsonpath-rw/blob/f615451d7b405e23e0f80b15cad03b1427b0256d/jsonpath_rw/lexer.py#L159-L162
train
kennknowles/python-jsonpath-rw
jsonpath_rw/jsonpath.py
DatumInContext.id_pseudopath
def id_pseudopath(self): """ Looks like a path, but with ids stuck in when available """ try: pseudopath = Fields(str(self.value[auto_id_field])) except (TypeError, AttributeError, KeyError): # This may not be all the interesting exceptions pseudopath = se...
python
def id_pseudopath(self): """ Looks like a path, but with ids stuck in when available """ try: pseudopath = Fields(str(self.value[auto_id_field])) except (TypeError, AttributeError, KeyError): # This may not be all the interesting exceptions pseudopath = se...
[ "def", "id_pseudopath", "(", "self", ")", ":", "try", ":", "pseudopath", "=", "Fields", "(", "str", "(", "self", ".", "value", "[", "auto_id_field", "]", ")", ")", "except", "(", "TypeError", ",", "AttributeError", ",", "KeyError", ")", ":", "pseudopath"...
Looks like a path, but with ids stuck in when available
[ "Looks", "like", "a", "path", "but", "with", "ids", "stuck", "in", "when", "available" ]
f615451d7b405e23e0f80b15cad03b1427b0256d
https://github.com/kennknowles/python-jsonpath-rw/blob/f615451d7b405e23e0f80b15cad03b1427b0256d/jsonpath_rw/jsonpath.py#L97-L109
train
hashedin/jinjasql
jinjasql/core.py
bind
def bind(value, name): """A filter that prints %s, and stores the value in an array, so that it can be bound using a prepared statement This filter is automatically applied to every {{variable}} during the lexing stage, so developers can't forget to bind """ if isinstance(value, Markup): ...
python
def bind(value, name): """A filter that prints %s, and stores the value in an array, so that it can be bound using a prepared statement This filter is automatically applied to every {{variable}} during the lexing stage, so developers can't forget to bind """ if isinstance(value, Markup): ...
[ "def", "bind", "(", "value", ",", "name", ")", ":", "if", "isinstance", "(", "value", ",", "Markup", ")", ":", "return", "value", "elif", "requires_in_clause", "(", "value", ")", ":", "raise", "MissingInClauseException", "(", ")", "else", ":", "return", ...
A filter that prints %s, and stores the value in an array, so that it can be bound using a prepared statement This filter is automatically applied to every {{variable}} during the lexing stage, so developers can't forget to bind
[ "A", "filter", "that", "prints", "%s", "and", "stores", "the", "value", "in", "an", "array", "so", "that", "it", "can", "be", "bound", "using", "a", "prepared", "statement" ]
c81795b9280f3815f08b3b19df61868c6265bf1b
https://github.com/hashedin/jinjasql/blob/c81795b9280f3815f08b3b19df61868c6265bf1b/jinjasql/core.py#L92-L105
train
alecthomas/injector
injector/__init__.py
inject
def inject(function): """Decorator declaring parameters to be injected. eg. >>> Sizes = Key('sizes') >>> Names = Key('names') >>> >>> class A: ... @inject ... def __init__(self, number: int, name: str, sizes: Sizes): ... print([number, name, sizes]) ... >>> ...
python
def inject(function): """Decorator declaring parameters to be injected. eg. >>> Sizes = Key('sizes') >>> Names = Key('names') >>> >>> class A: ... @inject ... def __init__(self, number: int, name: str, sizes: Sizes): ... print([number, name, sizes]) ... >>> ...
[ "def", "inject", "(", "function", ")", ":", "try", ":", "bindings", "=", "_infer_injected_bindings", "(", "function", ")", "except", "_BindingNotYetAvailable", ":", "bindings", "=", "'deferred'", "return", "method_wrapper", "(", "function", ",", "bindings", ")" ]
Decorator declaring parameters to be injected. eg. >>> Sizes = Key('sizes') >>> Names = Key('names') >>> >>> class A: ... @inject ... def __init__(self, number: int, name: str, sizes: Sizes): ... print([number, name, sizes]) ... >>> def configure(binder): .....
[ "Decorator", "declaring", "parameters", "to", "be", "injected", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L904-L941
train
alecthomas/injector
injector/__init__.py
noninjectable
def noninjectable(*args): """Mark some parameters as not injectable. This serves as documentation for people reading the code and will prevent Injector from ever attempting to provide the parameters. For example: >>> class Service: ... pass ... >>> class SomeClass: ... @inj...
python
def noninjectable(*args): """Mark some parameters as not injectable. This serves as documentation for people reading the code and will prevent Injector from ever attempting to provide the parameters. For example: >>> class Service: ... pass ... >>> class SomeClass: ... @inj...
[ "def", "noninjectable", "(", "*", "args", ")", ":", "def", "decorator", "(", "function", ")", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "inspect", ".", "unwrap", "(", "function", ")", ")", "for", "arg", "in", "args", ":", "if", "arg",...
Mark some parameters as not injectable. This serves as documentation for people reading the code and will prevent Injector from ever attempting to provide the parameters. For example: >>> class Service: ... pass ... >>> class SomeClass: ... @inject ... @noninjectable('u...
[ "Mark", "some", "parameters", "as", "not", "injectable", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L944-L979
train
alecthomas/injector
injector/__init__.py
Binder.bind
def bind(self, interface, to=None, scope=None): """Bind an interface to an implementation. :param interface: Interface or :func:`Key` to bind. :param to: Instance or class to bind to, or an explicit :class:`Provider` subclass. :param scope: Optional :class:`Scope` in which ...
python
def bind(self, interface, to=None, scope=None): """Bind an interface to an implementation. :param interface: Interface or :func:`Key` to bind. :param to: Instance or class to bind to, or an explicit :class:`Provider` subclass. :param scope: Optional :class:`Scope` in which ...
[ "def", "bind", "(", "self", ",", "interface", ",", "to", "=", "None", ",", "scope", "=", "None", ")", ":", "if", "type", "(", "interface", ")", "is", "type", "and", "issubclass", "(", "interface", ",", "(", "BaseMappingKey", ",", "BaseSequenceKey", ")"...
Bind an interface to an implementation. :param interface: Interface or :func:`Key` to bind. :param to: Instance or class to bind to, or an explicit :class:`Provider` subclass. :param scope: Optional :class:`Scope` in which to bind.
[ "Bind", "an", "interface", "to", "an", "implementation", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L293-L304
train
alecthomas/injector
injector/__init__.py
Binder.multibind
def multibind(self, interface, to, scope=None): """Creates or extends a multi-binding. A multi-binding maps from a key to a sequence, where each element in the sequence is provided separately. :param interface: :func:`MappingKey` or :func:`SequenceKey` to bind to. :param to: In...
python
def multibind(self, interface, to, scope=None): """Creates or extends a multi-binding. A multi-binding maps from a key to a sequence, where each element in the sequence is provided separately. :param interface: :func:`MappingKey` or :func:`SequenceKey` to bind to. :param to: In...
[ "def", "multibind", "(", "self", ",", "interface", ",", "to", ",", "scope", "=", "None", ")", ":", "key", "=", "BindingKey", ".", "create", "(", "interface", ")", "if", "key", "not", "in", "self", ".", "_bindings", ":", "if", "isinstance", "(", "inte...
Creates or extends a multi-binding. A multi-binding maps from a key to a sequence, where each element in the sequence is provided separately. :param interface: :func:`MappingKey` or :func:`SequenceKey` to bind to. :param to: Instance, class to bind to, or an explicit :class:`Provider` ...
[ "Creates", "or", "extends", "a", "multi", "-", "binding", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L306-L329
train
alecthomas/injector
injector/__init__.py
Binder.install
def install(self, module): """Install a module into this binder. In this context the module is one of the following: * function taking the :class:`Binder` as it's only parameter :: def configure(binder): bind(str, to='s') binder.install(conf...
python
def install(self, module): """Install a module into this binder. In this context the module is one of the following: * function taking the :class:`Binder` as it's only parameter :: def configure(binder): bind(str, to='s') binder.install(conf...
[ "def", "install", "(", "self", ",", "module", ")", ":", "if", "type", "(", "module", ")", "is", "type", "and", "issubclass", "(", "module", ",", "Module", ")", ":", "instance", "=", "module", "(", ")", "else", ":", "instance", "=", "module", "instanc...
Install a module into this binder. In this context the module is one of the following: * function taking the :class:`Binder` as it's only parameter :: def configure(binder): bind(str, to='s') binder.install(configure) * instance of :class:`...
[ "Install", "a", "module", "into", "this", "binder", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L331-L366
train
alecthomas/injector
injector/__init__.py
Injector.get
def get(self, interface: Type[T], scope=None) -> T: """Get an instance of the given interface. .. note:: Although this method is part of :class:`Injector`'s public interface it's meant to be used in limited set of circumstances. For example, to create some kind of ...
python
def get(self, interface: Type[T], scope=None) -> T: """Get an instance of the given interface. .. note:: Although this method is part of :class:`Injector`'s public interface it's meant to be used in limited set of circumstances. For example, to create some kind of ...
[ "def", "get", "(", "self", ",", "interface", ":", "Type", "[", "T", "]", ",", "scope", "=", "None", ")", "->", "T", ":", "key", "=", "BindingKey", ".", "create", "(", "interface", ")", "binding", ",", "binder", "=", "self", ".", "binder", ".", "g...
Get an instance of the given interface. .. note:: Although this method is part of :class:`Injector`'s public interface it's meant to be used in limited set of circumstances. For example, to create some kind of root object (application object) of your applicatio...
[ "Get", "an", "instance", "of", "the", "given", "interface", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L655-L703
train
alecthomas/injector
injector/__init__.py
Injector.create_object
def create_object(self, cls: Type[T], additional_kwargs=None) -> T: """Create a new instance, satisfying any dependencies on cls.""" additional_kwargs = additional_kwargs or {} log.debug('%sCreating %r object with %r', self._log_prefix, cls, additional_kwargs) try: instance ...
python
def create_object(self, cls: Type[T], additional_kwargs=None) -> T: """Create a new instance, satisfying any dependencies on cls.""" additional_kwargs = additional_kwargs or {} log.debug('%sCreating %r object with %r', self._log_prefix, cls, additional_kwargs) try: instance ...
[ "def", "create_object", "(", "self", ",", "cls", ":", "Type", "[", "T", "]", ",", "additional_kwargs", "=", "None", ")", "->", "T", ":", "additional_kwargs", "=", "additional_kwargs", "or", "{", "}", "log", ".", "debug", "(", "'%sCreating %r object with %r'"...
Create a new instance, satisfying any dependencies on cls.
[ "Create", "a", "new", "instance", "satisfying", "any", "dependencies", "on", "cls", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L708-L738
train
alecthomas/injector
injector/__init__.py
Injector.call_with_injection
def call_with_injection(self, callable, self_=None, args=(), kwargs={}): """Call a callable and provide it's dependencies if needed. :param self_: Instance of a class callable belongs to if it's a method, None otherwise. :param args: Arguments to pass to callable. :param kwa...
python
def call_with_injection(self, callable, self_=None, args=(), kwargs={}): """Call a callable and provide it's dependencies if needed. :param self_: Instance of a class callable belongs to if it's a method, None otherwise. :param args: Arguments to pass to callable. :param kwa...
[ "def", "call_with_injection", "(", "self", ",", "callable", ",", "self_", "=", "None", ",", "args", "=", "(", ")", ",", "kwargs", "=", "{", "}", ")", ":", "def", "_get_callable_bindings", "(", "callable", ")", ":", "if", "not", "hasattr", "(", "callabl...
Call a callable and provide it's dependencies if needed. :param self_: Instance of a class callable belongs to if it's a method, None otherwise. :param args: Arguments to pass to callable. :param kwargs: Keyword arguments to pass to callable. :type callable: callable ...
[ "Call", "a", "callable", "and", "provide", "it", "s", "dependencies", "if", "needed", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L740-L786
train
alecthomas/injector
injector/__init__.py
Injector.args_to_inject
def args_to_inject(self, function, bindings, owner_key): """Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a metho...
python
def args_to_inject(self, function, bindings, owner_key): """Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a metho...
[ "def", "args_to_inject", "(", "self", ",", "function", ",", "bindings", ",", "owner_key", ")", ":", "dependencies", "=", "{", "}", "key", "=", "(", "owner_key", ",", "function", ",", "tuple", "(", "sorted", "(", "bindings", ".", "items", "(", ")", ")",...
Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a method this will be the owning class. :returns: Dictionary of res...
[ "Inject", "arguments", "into", "a", "function", "." ]
07c7200166dcf5abc3bd425607f6c20206b8fe65
https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L790-L828
train
timkpaine/lantern
lantern/extensions/savehooks/remove_output.py
scrub_output_pre_save
def scrub_output_pre_save(model, **kwargs): """scrub output before saving notebooks""" # only run on notebooks if model['type'] != 'notebook': return # only run on nbformat v4 if model['content']['nbformat'] != 4: return for cell in model['content']['cells']: if cell['ce...
python
def scrub_output_pre_save(model, **kwargs): """scrub output before saving notebooks""" # only run on notebooks if model['type'] != 'notebook': return # only run on nbformat v4 if model['content']['nbformat'] != 4: return for cell in model['content']['cells']: if cell['ce...
[ "def", "scrub_output_pre_save", "(", "model", ",", "**", "kwargs", ")", ":", "if", "model", "[", "'type'", "]", "!=", "'notebook'", ":", "return", "if", "model", "[", "'content'", "]", "[", "'nbformat'", "]", "!=", "4", ":", "return", "for", "cell", "i...
scrub output before saving notebooks
[ "scrub", "output", "before", "saving", "notebooks" ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/lantern/extensions/savehooks/remove_output.py#L1-L14
train
timkpaine/lantern
lantern/widgets/variable_inspector.py
VariableInspector.close
def close(self): """Close and remove hooks.""" if not self.closed: self._ipython.events.unregister('post_run_cell', self._fill) self._box.close() self.closed = True
python
def close(self): """Close and remove hooks.""" if not self.closed: self._ipython.events.unregister('post_run_cell', self._fill) self._box.close() self.closed = True
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "self", ".", "_ipython", ".", "events", ".", "unregister", "(", "'post_run_cell'", ",", "self", ".", "_fill", ")", "self", ".", "_box", ".", "close", "(", ")", "self", ...
Close and remove hooks.
[ "Close", "and", "remove", "hooks", "." ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/lantern/widgets/variable_inspector.py#L42-L47
train
timkpaine/lantern
lantern/widgets/variable_inspector.py
VariableInspector._fill
def _fill(self): """Fill self with variable information.""" types_to_exclude = ['module', 'function', 'builtin_function_or_method', 'instance', '_Feature', 'type', 'ufunc'] values = self.namespace.who_ls() def eval(expr): return self.namespace.she...
python
def _fill(self): """Fill self with variable information.""" types_to_exclude = ['module', 'function', 'builtin_function_or_method', 'instance', '_Feature', 'type', 'ufunc'] values = self.namespace.who_ls() def eval(expr): return self.namespace.she...
[ "def", "_fill", "(", "self", ")", ":", "types_to_exclude", "=", "[", "'module'", ",", "'function'", ",", "'builtin_function_or_method'", ",", "'instance'", ",", "'_Feature'", ",", "'type'", ",", "'ufunc'", "]", "values", "=", "self", ".", "namespace", ".", "...
Fill self with variable information.
[ "Fill", "self", "with", "variable", "information", "." ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/lantern/widgets/variable_inspector.py#L49-L67
train
timkpaine/lantern
lantern/extensions/headless/__init__.py
set_var
def set_var(var, set_='""'): '''set var outside notebook''' if isinstance(set_, str): to_set = json.dumps(set_) elif isinstance(set_, dict) or isinstance(set_, list): try: to_set = json.dumps(set_) except ValueError: raise Exception('var not jsonable') els...
python
def set_var(var, set_='""'): '''set var outside notebook''' if isinstance(set_, str): to_set = json.dumps(set_) elif isinstance(set_, dict) or isinstance(set_, list): try: to_set = json.dumps(set_) except ValueError: raise Exception('var not jsonable') els...
[ "def", "set_var", "(", "var", ",", "set_", "=", "'\"\"'", ")", ":", "if", "isinstance", "(", "set_", ",", "str", ")", ":", "to_set", "=", "json", ".", "dumps", "(", "set_", ")", "elif", "isinstance", "(", "set_", ",", "dict", ")", "or", "isinstance...
set var outside notebook
[ "set", "var", "outside", "notebook" ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/lantern/extensions/headless/__init__.py#L23-L35
train
timkpaine/lantern
lantern/extensions/headless/__init__.py
get_var
def get_var(var, default='""'): '''get var inside notebook''' ret = os.environ.get('NBCONVERT_' + var) if ret is None: return default return json.loads(ret)
python
def get_var(var, default='""'): '''get var inside notebook''' ret = os.environ.get('NBCONVERT_' + var) if ret is None: return default return json.loads(ret)
[ "def", "get_var", "(", "var", ",", "default", "=", "'\"\"'", ")", ":", "ret", "=", "os", ".", "environ", ".", "get", "(", "'NBCONVERT_'", "+", "var", ")", "if", "ret", "is", "None", ":", "return", "default", "return", "json", ".", "loads", "(", "re...
get var inside notebook
[ "get", "var", "inside", "notebook" ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/lantern/extensions/headless/__init__.py#L38-L43
train
timkpaine/lantern
lantern/plotting/plotutils.py
align_yaxis_np
def align_yaxis_np(axes): """Align zeros of the two axes, zooming them out by same ratio""" axes = np.array(axes) extrema = np.array([ax.get_ylim() for ax in axes]) # reset for divide by zero issues for i in range(len(extrema)): if np.isclose(extrema[i, 0], 0.0): extrema[i, 0] =...
python
def align_yaxis_np(axes): """Align zeros of the two axes, zooming them out by same ratio""" axes = np.array(axes) extrema = np.array([ax.get_ylim() for ax in axes]) # reset for divide by zero issues for i in range(len(extrema)): if np.isclose(extrema[i, 0], 0.0): extrema[i, 0] =...
[ "def", "align_yaxis_np", "(", "axes", ")", ":", "axes", "=", "np", ".", "array", "(", "axes", ")", "extrema", "=", "np", ".", "array", "(", "[", "ax", ".", "get_ylim", "(", ")", "for", "ax", "in", "axes", "]", ")", "for", "i", "in", "range", "(...
Align zeros of the two axes, zooming them out by same ratio
[ "Align", "zeros", "of", "the", "two", "axes", "zooming", "them", "out", "by", "same", "ratio" ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/lantern/plotting/plotutils.py#L93-L145
train
timkpaine/lantern
experimental/dash/dash-vanguard-report-master/app.py
make_dash_table
def make_dash_table(df): ''' Return a dash definitio of an HTML table for a Pandas dataframe ''' table = [] for index, row in df.iterrows(): html_row = [] for i in range(len(row)): html_row.append(html.Td([row[i]])) table.append(html.Tr(html_row)) return table
python
def make_dash_table(df): ''' Return a dash definitio of an HTML table for a Pandas dataframe ''' table = [] for index, row in df.iterrows(): html_row = [] for i in range(len(row)): html_row.append(html.Td([row[i]])) table.append(html.Tr(html_row)) return table
[ "def", "make_dash_table", "(", "df", ")", ":", "table", "=", "[", "]", "for", "index", ",", "row", "in", "df", ".", "iterrows", "(", ")", ":", "html_row", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "row", ")", ")", ":", "html_ro...
Return a dash definitio of an HTML table for a Pandas dataframe
[ "Return", "a", "dash", "definitio", "of", "an", "HTML", "table", "for", "a", "Pandas", "dataframe" ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/experimental/dash/dash-vanguard-report-master/app.py#L33-L41
train
timkpaine/lantern
lantern/extensions/savehooks/convert_to_script.py
script_post_save
def script_post_save(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return global _script_export...
python
def script_post_save(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return global _script_export...
[ "def", "script_post_save", "(", "model", ",", "os_path", ",", "contents_manager", ",", "**", "kwargs", ")", ":", "from", "nbconvert", ".", "exporters", ".", "script", "import", "ScriptExporter", "if", "model", "[", "'type'", "]", "!=", "'notebook'", ":", "re...
convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script`
[ "convert", "notebooks", "to", "Python", "script", "after", "save", "with", "nbconvert" ]
40a3aad630ab40735a5221a1d96118697317a414
https://github.com/timkpaine/lantern/blob/40a3aad630ab40735a5221a1d96118697317a414/lantern/extensions/savehooks/convert_to_script.py#L8-L32
train
kennethreitz/xerox
xerox/x11.py
copy
def copy(string, xsel=False): """Copy given string into system clipboard. If 'xsel' is True, this will also copy into the primary x selection for middle click.""" try: _cmd = ["xclip", "-selection", "clipboard"] subprocess.Popen(_cmd, stdin=subprocess.PIPE).communicate( strin...
python
def copy(string, xsel=False): """Copy given string into system clipboard. If 'xsel' is True, this will also copy into the primary x selection for middle click.""" try: _cmd = ["xclip", "-selection", "clipboard"] subprocess.Popen(_cmd, stdin=subprocess.PIPE).communicate( strin...
[ "def", "copy", "(", "string", ",", "xsel", "=", "False", ")", ":", "try", ":", "_cmd", "=", "[", "\"xclip\"", ",", "\"-selection\"", ",", "\"clipboard\"", "]", "subprocess", ".", "Popen", "(", "_cmd", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", ...
Copy given string into system clipboard. If 'xsel' is True, this will also copy into the primary x selection for middle click.
[ "Copy", "given", "string", "into", "system", "clipboard", ".", "If", "xsel", "is", "True", "this", "will", "also", "copy", "into", "the", "primary", "x", "selection", "for", "middle", "click", "." ]
c34d2fb03ff892b31016173c520e784e86cc2d70
https://github.com/kennethreitz/xerox/blob/c34d2fb03ff892b31016173c520e784e86cc2d70/xerox/x11.py#L10-L22
train
kennethreitz/xerox
xerox/__init__.py
main
def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip('\n')) else: # paste output print(paste())
python
def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip('\n')) else: # paste output print(paste())
[ "def", "main", "(", ")", ":", "if", "sys", ".", "argv", "[", "1", ":", "]", ":", "copy", "(", "' '", ".", "join", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", ")", "elif", "not", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "co...
Entry point for cli.
[ "Entry", "point", "for", "cli", "." ]
c34d2fb03ff892b31016173c520e784e86cc2d70
https://github.com/kennethreitz/xerox/blob/c34d2fb03ff892b31016173c520e784e86cc2d70/xerox/__init__.py#L6-L13
train