repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
marccarre/py_sak
py_sak/functions.py
log_debug
def log_debug(func, *args, **kwargs): ''' Wrap call of provided function with debug log statements. ''' logging.debug('Starting "%s" in thread %s...', func.__name__, current_thread()) results = func(*args, **kwargs) logging.debug('Successfully finished "%s" in thread %s.', func.__name__, current_thread(...
python
def log_debug(func, *args, **kwargs): ''' Wrap call of provided function with debug log statements. ''' logging.debug('Starting "%s" in thread %s...', func.__name__, current_thread()) results = func(*args, **kwargs) logging.debug('Successfully finished "%s" in thread %s.', func.__name__, current_thread(...
[ "def", "log_debug", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "'Starting \"%s\" in thread %s...'", ",", "func", ".", "__name__", ",", "current_thread", "(", ")", ")", "results", "=", "func", "(", "*",...
Wrap call of provided function with debug log statements.
[ "Wrap", "call", "of", "provided", "function", "with", "debug", "log", "statements", "." ]
train
https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/functions.py#L11-L16
marccarre/py_sak
py_sak/functions.py
try_catch
def try_catch(func, *args, **kwargs): ''' Wrap call of provided function with try/except block and debug log statements. If an instance of 'Exception' (or one of its subclasses) is thrown by 'func', it is caught, and the exception object itself is return as a result. ''' try: return log_...
python
def try_catch(func, *args, **kwargs): ''' Wrap call of provided function with try/except block and debug log statements. If an instance of 'Exception' (or one of its subclasses) is thrown by 'func', it is caught, and the exception object itself is return as a result. ''' try: return log_...
[ "def", "try_catch", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "log_debug", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "exc", ":", "logging", ".", "debug", ...
Wrap call of provided function with try/except block and debug log statements. If an instance of 'Exception' (or one of its subclasses) is thrown by 'func', it is caught, and the exception object itself is return as a result.
[ "Wrap", "call", "of", "provided", "function", "with", "try", "/", "except", "block", "and", "debug", "log", "statements", ".", "If", "an", "instance", "of", "Exception", "(", "or", "one", "of", "its", "subclasses", ")", "is", "thrown", "by", "func", "it"...
train
https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/functions.py#L19-L29
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.reformat
def reformat(self, dtstring, before, after): """Edit the time string format. See https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior for all format string options. **中文文档** 将datetime string从一种格式转换成另一种格式。 """ a_...
python
def reformat(self, dtstring, before, after): """Edit the time string format. See https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior for all format string options. **中文文档** 将datetime string从一种格式转换成另一种格式。 """ a_...
[ "def", "reformat", "(", "self", ",", "dtstring", ",", "before", ",", "after", ")", ":", "a_datetime", "=", "datetime", ".", "strptime", "(", "dtstring", ",", "before", ")", "return", "datetime", ".", "strftime", "(", "a_datetime", ",", "after", ")" ]
Edit the time string format. See https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior for all format string options. **中文文档** 将datetime string从一种格式转换成另一种格式。
[ "Edit", "the", "time", "string", "format", ".", "See", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "2", "/", "library", "/", "datetime", ".", "html#strftime", "-", "and", "-", "strptime", "-", "behavior", "for", "all", "format", "string...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L177-L188
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.str2date
def str2date(self, datestr): """Try parse date from string. If None template matching this datestr, raise Error. :param datestr: a string represent a date :type datestr: str :return: a datetime.date object Usage:: >>> from weatherl...
python
def str2date(self, datestr): """Try parse date from string. If None template matching this datestr, raise Error. :param datestr: a string represent a date :type datestr: str :return: a datetime.date object Usage:: >>> from weatherl...
[ "def", "str2date", "(", "self", ",", "datestr", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "datestr", ",", "self", ".", "default_date_template", ")", ".", "date", "(", ")", "except", ":", "# 如果默认的模板不匹配, 则重新尝试所有的模板", "pass", "# try all ...
Try parse date from string. If None template matching this datestr, raise Error. :param datestr: a string represent a date :type datestr: str :return: a datetime.date object Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewr...
[ "Try", "parse", "date", "from", "string", ".", "If", "None", "template", "matching", "this", "datestr", "raise", "Error", ".", ":", "param", "datestr", ":", "a", "string", "represent", "a", "date", ":", "type", "datestr", ":", "str", ":", "return", ":", ...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L190-L225
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.str2datetime
def str2datetime(self, datetimestr): """Try parse datetime from string. If None template matching this datestr, raise Error. :param datetimestr: a string represent a datetime :type datetimestr: str :return: a datetime.datetime object Usage:: ...
python
def str2datetime(self, datetimestr): """Try parse datetime from string. If None template matching this datestr, raise Error. :param datetimestr: a string represent a datetime :type datetimestr: str :return: a datetime.datetime object Usage:: ...
[ "def", "str2datetime", "(", "self", ",", "datetimestr", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "datetimestr", ",", "self", ".", "default_datetime_templates", ")", "except", ":", "# 如果默认的模板不匹配, 则重新尝试所有的模板", "pass", "# try all datetime_templ...
Try parse datetime from string. If None template matching this datestr, raise Error. :param datetimestr: a string represent a datetime :type datetimestr: str :return: a datetime.datetime object Usage:: >>> from weatherlab.lib.timelib.timew...
[ "Try", "parse", "datetime", "from", "string", ".", "If", "None", "template", "matching", "this", "datestr", "raise", "Error", ".", ":", "param", "datetimestr", ":", "a", "string", "represent", "a", "datetime", ":", "type", "datetimestr", ":", "str", ":", "...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L227-L263
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.std_datetimestr
def std_datetimestr(self, datetimestr): """Reformat a datetime string to standard format. """ return datetime.strftime( self.str2datetime(datetimestr), self.std_datetimeformat)
python
def std_datetimestr(self, datetimestr): """Reformat a datetime string to standard format. """ return datetime.strftime( self.str2datetime(datetimestr), self.std_datetimeformat)
[ "def", "std_datetimestr", "(", "self", ",", "datetimestr", ")", ":", "return", "datetime", ".", "strftime", "(", "self", ".", "str2datetime", "(", "datetimestr", ")", ",", "self", ".", "std_datetimeformat", ")" ]
Reformat a datetime string to standard format.
[ "Reformat", "a", "datetime", "string", "to", "standard", "format", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L271-L275
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.parse_date
def parse_date(self, value): """A lazy method to parse anything to date. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import datetime >>> timewrapper.parse_date("12/25/1985") datetime.date(1985,...
python
def parse_date(self, value): """A lazy method to parse anything to date. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import datetime >>> timewrapper.parse_date("12/25/1985") datetime.date(1985,...
[ "def", "parse_date", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "date", ")", "and", "not", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "str", ")", ...
A lazy method to parse anything to date. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import datetime >>> timewrapper.parse_date("12/25/1985") datetime.date(1985, 12, 25) >>> timewrapper.par...
[ "A", "lazy", "method", "to", "parse", "anything", "to", "date", ".", "Usage", "::", ">>>", "from", "weatherlab", ".", "lib", ".", "timelib", ".", "timewrapper", "import", "timewrapper", ">>>", "from", "datetime", "import", "datetime", ">>>", "timewrapper", "...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L311-L335
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.parse_datetime
def parse_datetime(self, value): """A lazy method to parse anything to datetime. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import date >>> timewrapper.parse_datetime("2001-09-11 10:07:00 AM") ...
python
def parse_datetime(self, value): """A lazy method to parse anything to datetime. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import date >>> timewrapper.parse_datetime("2001-09-11 10:07:00 AM") ...
[ "def", "parse_datetime", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "return", "self", ".", "str2datetime", "(", "value", ...
A lazy method to parse anything to datetime. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import date >>> timewrapper.parse_datetime("2001-09-11 10:07:00 AM") datetime.datetime(2001, 9, 11, 10, 7) ...
[ "A", "lazy", "method", "to", "parse", "anything", "to", "datetime", ".", "Usage", "::", ">>>", "from", "weatherlab", ".", "lib", ".", "timelib", ".", "timewrapper", "import", "timewrapper", ">>>", "from", "datetime", "import", "date", ">>>", "timewrapper", "...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L337-L363
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper._freq_parser
def _freq_parser(self, freq): """ day, hour, min, sec, """ freq = freq.lower().strip() try: if "day" in freq: freq = freq.replace("day", "") return timedelta(days=int(freq)) elif "hour" in freq: freq = freq.r...
python
def _freq_parser(self, freq): """ day, hour, min, sec, """ freq = freq.lower().strip() try: if "day" in freq: freq = freq.replace("day", "") return timedelta(days=int(freq)) elif "hour" in freq: freq = freq.r...
[ "def", "_freq_parser", "(", "self", ",", "freq", ")", ":", "freq", "=", "freq", ".", "lower", "(", ")", ".", "strip", "(", ")", "try", ":", "if", "\"day\"", "in", "freq", ":", "freq", "=", "freq", ".", "replace", "(", "\"day\"", ",", "\"\"", ")",...
day, hour, min, sec,
[ "day", "hour", "min", "sec" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L368-L389
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.dtime_range
def dtime_range(self, start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: ...
python
def dtime_range(self, start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: ...
[ "def", "dtime_range", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "periods", "=", "None", ",", "freq", "=", "\"1day\"", ",", "normalize", "=", "False", ",", "return_date", "=", "False", ")", ":", "def", "normalize_datetime_to_mi...
A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for ge...
[ "A", "pure", "Python", "implementation", "of", "pandas", ".", "date_range", "()", ".", "Given", "2", "of", "start", "end", "periods", "and", "freq", "generate", "a", "series", "of", "datetime", "object", ".", ":", "param", "start", ":", "Left", "bound", ...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L391-L501
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.weekday_series
def weekday_series(self, start, end, weekday): """Generate a datetime series with same weekday number. ISO weekday number: Mon = 1, Sun = 7 Usage:: >>> timewrapper.weekday_series( # All Tuesday >>> "2014-01-01 06:30:25", "2014-02-01 06:30:25...
python
def weekday_series(self, start, end, weekday): """Generate a datetime series with same weekday number. ISO weekday number: Mon = 1, Sun = 7 Usage:: >>> timewrapper.weekday_series( # All Tuesday >>> "2014-01-01 06:30:25", "2014-02-01 06:30:25...
[ "def", "weekday_series", "(", "self", ",", "start", ",", "end", ",", "weekday", ")", ":", "startdatetime", "=", "self", ".", "parse_datetime", "(", "start", ")", "enddatetime", "=", "self", ".", "parse_datetime", "(", "end", ")", "series", "=", "list", "...
Generate a datetime series with same weekday number. ISO weekday number: Mon = 1, Sun = 7 Usage:: >>> timewrapper.weekday_series( # All Tuesday >>> "2014-01-01 06:30:25", "2014-02-01 06:30:25", weekday=2), [ datetime(2014...
[ "Generate", "a", "datetime", "series", "with", "same", "weekday", "number", ".", "ISO", "weekday", "number", ":", "Mon", "=", "1", "Sun", "=", "7", "Usage", "::", ">>>", "timewrapper", ".", "weekday_series", "(", "#", "All", "Tuesday", ">>>", "2014", "-"...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L503-L531
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.day_interval
def day_interval(year, month, day, return_str=False): """ Usage Example:: >>> timewrapper.day_interval(2014, 3, 1) (datetime(2014, 3, 1, 0, 0, 0), datetime(2014, 3, 1, 23, 59, 59)) """ start, end = datetime(year, month, day), datetime(year, month...
python
def day_interval(year, month, day, return_str=False): """ Usage Example:: >>> timewrapper.day_interval(2014, 3, 1) (datetime(2014, 3, 1, 0, 0, 0), datetime(2014, 3, 1, 23, 59, 59)) """ start, end = datetime(year, month, day), datetime(year, month...
[ "def", "day_interval", "(", "year", ",", "month", ",", "day", ",", "return_str", "=", "False", ")", ":", "start", ",", "end", "=", "datetime", "(", "year", ",", "month", ",", "day", ")", ",", "datetime", "(", "year", ",", "month", ",", "day", ")", ...
Usage Example:: >>> timewrapper.day_interval(2014, 3, 1) (datetime(2014, 3, 1, 0, 0, 0), datetime(2014, 3, 1, 23, 59, 59))
[ "Usage", "Example", "::", ">>>", "timewrapper", ".", "day_interval", "(", "2014", "3", "1", ")", "(", "datetime", "(", "2014", "3", "1", "0", "0", "0", ")", "datetime", "(", "2014", "3", "1", "23", "59", "59", "))" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L543-L555
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.month_interval
def month_interval(year, month, return_str=False): """ Usage Example:: >>> timewrapper.day_interval(2014, 12) (datetime(2014, 12, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59)) """ if month == 12: start, end = datetime(year, month, ...
python
def month_interval(year, month, return_str=False): """ Usage Example:: >>> timewrapper.day_interval(2014, 12) (datetime(2014, 12, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59)) """ if month == 12: start, end = datetime(year, month, ...
[ "def", "month_interval", "(", "year", ",", "month", ",", "return_str", "=", "False", ")", ":", "if", "month", "==", "12", ":", "start", ",", "end", "=", "datetime", "(", "year", ",", "month", ",", "1", ")", ",", "datetime", "(", "year", "+", "1", ...
Usage Example:: >>> timewrapper.day_interval(2014, 12) (datetime(2014, 12, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59))
[ "Usage", "Example", "::", ">>>", "timewrapper", ".", "day_interval", "(", "2014", "12", ")", "(", "datetime", "(", "2014", "12", "1", "0", "0", "0", ")", "datetime", "(", "2014", "12", "31", "23", "59", "59", "))" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L558-L574
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.randdate
def randdate(self, start=date(1970, 1, 1), end=date.today()): """Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default da...
python
def randdate(self, start=date(1970, 1, 1), end=date.today()): """Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default da...
[ "def", "randdate", "(", "self", ",", "start", "=", "date", "(", "1970", ",", "1", ",", "1", ")", ",", "end", "=", "date", ".", "today", "(", ")", ")", ":", "if", "isinstance", "(", "start", ",", "str", ")", ":", "start", "=", "self", ".", "st...
Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文...
[ "Generate", "a", "random", "date", "between", "start", "to", "end", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L595-L615
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.randdatetime
def randdatetime(self, start=datetime(1970,1,1), end=datetime.now()): """Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or dateti...
python
def randdatetime(self, start=datetime(1970,1,1), end=datetime.now()): """Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or dateti...
[ "def", "randdatetime", "(", "self", ",", "start", "=", "datetime", "(", "1970", ",", "1", ",", "1", ")", ",", "end", "=", "datetime", ".", "now", "(", ")", ")", ":", "if", "isinstance", "(", "start", ",", "str", ")", ":", "start", "=", "self", ...
Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object...
[ "Generate", "a", "random", "datetime", "between", "start", "to", "end", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L617-L636
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.add_months
def add_months(self, datetimestr, n, return_date=False): """Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :para...
python
def add_months(self, datetimestr, n, return_date=False): """Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :para...
[ "def", "add_months", "(", "self", ",", "datetimestr", ",", "n", ",", "return_date", "=", "False", ")", ":", "a_datetime", "=", "self", ".", "parse_datetime", "(", "datetimestr", ")", "month_from_ordinary", "=", "a_datetime", ".", "year", "*", "12", "+", "a...
Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n:...
[ "Returns", "a", "time", "that", "n", "months", "after", "a", "time", ".", "Notice", ":", "for", "example", "the", "date", "that", "one", "month", "after", "2015", "-", "01", "-", "31", "supposed", "to", "be", "2015", "-", "02", "-", "31", ".", "But...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L713-L746
MacHu-GWU/angora-project
angora/timelib/timewrapper.py
TimeWrapper.round_to_specified_time
def round_to_specified_time(self, a_datetime, hour, minute, second, mode="lower"): """Round the given datetime to specified hour, minute and second. :param mode: if 'lower', floor to. if 'upper', ceiling to. **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ ...
python
def round_to_specified_time(self, a_datetime, hour, minute, second, mode="lower"): """Round the given datetime to specified hour, minute and second. :param mode: if 'lower', floor to. if 'upper', ceiling to. **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ ...
[ "def", "round_to_specified_time", "(", "self", ",", "a_datetime", ",", "hour", ",", "minute", ",", "second", ",", "mode", "=", "\"lower\"", ")", ":", "mode", "=", "mode", ".", "lower", "(", ")", "new_datetime", "=", "datetime", "(", "a_datetime", ".", "y...
Round the given datetime to specified hour, minute and second. :param mode: if 'lower', floor to. if 'upper', ceiling to. **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
[ "Round", "the", "given", "datetime", "to", "specified", "hour", "minute", "and", "second", ".", ":", "param", "mode", ":", "if", "lower", "floor", "to", ".", "if", "upper", "ceiling", "to", ".", "**", "中文文档", "**", "将给定时间对齐到最近的一个指定了小时", "分钟", "秒的时间上。" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L777-L801
the01/python-paps
paps/si/app/sensorClient.py
SensorClient.join
def join(self, people): """ Join the local audience (a config message should be received on success) Validates that there are people to join and that each of them has a valid unique id :param people: Which people does this sensor have :type people: list[paps.pers...
python
def join(self, people): """ Join the local audience (a config message should be received on success) Validates that there are people to join and that each of them has a valid unique id :param people: Which people does this sensor have :type people: list[paps.pers...
[ "def", "join", "(", "self", ",", "people", ")", ":", "tries", "=", "0", "if", "not", "people", ":", "raise", "SensorJoinException", "(", "\"No people given\"", ")", "ids", "=", "set", "(", ")", "for", "person", "in", "people", ":", "if", "not", "person...
Join the local audience (a config message should be received on success) Validates that there are people to join and that each of them has a valid unique id :param people: Which people does this sensor have :type people: list[paps.person.Person] :rtype: None :rai...
[ "Join", "the", "local", "audience", "(", "a", "config", "message", "should", "be", "received", "on", "success", ")", "Validates", "that", "there", "are", "people", "to", "join", "and", "that", "each", "of", "them", "has", "a", "valid", "unique", "id" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L53-L102
the01/python-paps
paps/si/app/sensorClient.py
SensorClient.unjoin
def unjoin(self): """ Leave the local audience :rtype: None :raises SensorJoinException: Failed to leave """ self.debug("()") if self._joined.is_set(): packet = APPUnjoinMessage(device_id=Id.NOT_SET) self._send_packet(self._server_ip, self...
python
def unjoin(self): """ Leave the local audience :rtype: None :raises SensorJoinException: Failed to leave """ self.debug("()") if self._joined.is_set(): packet = APPUnjoinMessage(device_id=Id.NOT_SET) self._send_packet(self._server_ip, self...
[ "def", "unjoin", "(", "self", ")", ":", "self", ".", "debug", "(", "\"()\"", ")", "if", "self", ".", "_joined", ".", "is_set", "(", ")", ":", "packet", "=", "APPUnjoinMessage", "(", "device_id", "=", "Id", ".", "NOT_SET", ")", "self", ".", "_send_pac...
Leave the local audience :rtype: None :raises SensorJoinException: Failed to leave
[ "Leave", "the", "local", "audience" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L104-L116
the01/python-paps
paps/si/app/sensorClient.py
SensorClient.config
def config(self, settings): """ Configuration has changed - config this module and lower layers (calls on_config - if set) :param settings: New configuration :type settings: dict :rtype: None :raises SensorUpdateException: Failed to update """ sel...
python
def config(self, settings): """ Configuration has changed - config this module and lower layers (calls on_config - if set) :param settings: New configuration :type settings: dict :rtype: None :raises SensorUpdateException: Failed to update """ sel...
[ "def", "config", "(", "self", ",", "settings", ")", ":", "self", ".", "debug", "(", "\"()\"", ")", "# TODO synchronize access to vars", "try", ":", "self", ".", "_device_id", "=", "settings", "[", "'device_id'", "]", "self", ".", "_packet_timeout", "=", "set...
Configuration has changed - config this module and lower layers (calls on_config - if set) :param settings: New configuration :type settings: dict :rtype: None :raises SensorUpdateException: Failed to update
[ "Configuration", "has", "changed", "-", "config", "this", "module", "and", "lower", "layers", "(", "calls", "on_config", "-", "if", "set", ")" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L118-L147
the01/python-paps
paps/si/app/sensorClient.py
SensorClient.person_update
def person_update(self, people): """ Update the status of people :param people: All people of this sensor :type people: list[paps.person.Person] :rtype: None :raises SensorUpdateException: Failed to update """ packet = APPUpdateMessage(device_id=Id.NOT_S...
python
def person_update(self, people): """ Update the status of people :param people: All people of this sensor :type people: list[paps.person.Person] :rtype: None :raises SensorUpdateException: Failed to update """ packet = APPUpdateMessage(device_id=Id.NOT_S...
[ "def", "person_update", "(", "self", ",", "people", ")", ":", "packet", "=", "APPUpdateMessage", "(", "device_id", "=", "Id", ".", "NOT_SET", ",", "people", "=", "people", ")", "self", ".", "_send_packet", "(", "self", ".", "_server_ip", ",", "self", "."...
Update the status of people :param people: All people of this sensor :type people: list[paps.person.Person] :rtype: None :raises SensorUpdateException: Failed to update
[ "Update", "the", "status", "of", "people" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L149-L163
the01/python-paps
paps/si/app/sensorClient.py
SensorClient._do_config_packet
def _do_config_packet(self, packet, ip, port): """ Apply config to this instance :param packet: Packet with config :type packet: paps.si.app.message.APPMessage :param ip: Ip of server :type ip: str :param port: Port of server :type port: int :rtyp...
python
def _do_config_packet(self, packet, ip, port): """ Apply config to this instance :param packet: Packet with config :type packet: paps.si.app.message.APPMessage :param ip: Ip of server :type ip: str :param port: Port of server :type port: int :rtyp...
[ "def", "_do_config_packet", "(", "self", ",", "packet", ",", "ip", ",", "port", ")", ":", "self", ".", "debug", "(", "\"()\"", ")", "if", "packet", ".", "header", ".", "device_id", "!=", "Id", ".", "SERVER", ":", "# Only allow config packets from server", ...
Apply config to this instance :param packet: Packet with config :type packet: paps.si.app.message.APPMessage :param ip: Ip of server :type ip: str :param port: Port of server :type port: int :rtype: None
[ "Apply", "config", "to", "this", "instance" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L184-L216
the01/python-paps
paps/si/app/sensorClient.py
SensorClient.start
def start(self, blocking=False): """ Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None :raises SensorStartException: Failed to start """ self.debug("()") ...
python
def start(self, blocking=False): """ Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None :raises SensorStartException: Failed to start """ self.debug("()") ...
[ "def", "start", "(", "self", ",", "blocking", "=", "False", ")", ":", "self", ".", "debug", "(", "\"()\"", ")", "super", "(", "SensorClient", ",", "self", ")", ".", "start", "(", "blocking", "=", "False", ")", "try", ":", "a_thread", "=", "threading"...
Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None :raises SensorStartException: Failed to start
[ "Start", "the", "interface" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L218-L242
the01/python-paps
paps/si/app/sensorClient.py
SensorClient.stop
def stop(self): """ Stop the interface :rtype: None """ self.debug("()") try: self.unjoin() time.sleep(2) except: self.exception("Failed to leave audience") super(SensorClient, self).stop()
python
def stop(self): """ Stop the interface :rtype: None """ self.debug("()") try: self.unjoin() time.sleep(2) except: self.exception("Failed to leave audience") super(SensorClient, self).stop()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "debug", "(", "\"()\"", ")", "try", ":", "self", ".", "unjoin", "(", ")", "time", ".", "sleep", "(", "2", ")", "except", ":", "self", ".", "exception", "(", "\"Failed to leave audience\"", ")", "supe...
Stop the interface :rtype: None
[ "Stop", "the", "interface" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorClient.py#L244-L256
ArtoLabs/SimpleSteem
simplesteem/util.py
Util.goodnode
def goodnode(self, nodelist): ''' Goes through the provided list and returns the first server node that does not return an error. ''' l = len(nodelist) for n in range(self.current_node(l), l): self.msg.message("Trying node " + str(n) + ": " + nodelist[n]) ...
python
def goodnode(self, nodelist): ''' Goes through the provided list and returns the first server node that does not return an error. ''' l = len(nodelist) for n in range(self.current_node(l), l): self.msg.message("Trying node " + str(n) + ": " + nodelist[n]) ...
[ "def", "goodnode", "(", "self", ",", "nodelist", ")", ":", "l", "=", "len", "(", "nodelist", ")", "for", "n", "in", "range", "(", "self", ".", "current_node", "(", "l", ")", ",", "l", ")", ":", "self", ".", "msg", ".", "message", "(", "\"Trying n...
Goes through the provided list and returns the first server node that does not return an error.
[ "Goes", "through", "the", "provided", "list", "and", "returns", "the", "first", "server", "node", "that", "does", "not", "return", "an", "error", "." ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L52-L68
ArtoLabs/SimpleSteem
simplesteem/util.py
Util.permlink
def permlink(self, identifier): ''' Deconstructs an identifier into an account name and permlink ''' temp = identifier.split("@") temp2 = temp[1].split("/") return [temp2[0], temp2[1]]
python
def permlink(self, identifier): ''' Deconstructs an identifier into an account name and permlink ''' temp = identifier.split("@") temp2 = temp[1].split("/") return [temp2[0], temp2[1]]
[ "def", "permlink", "(", "self", ",", "identifier", ")", ":", "temp", "=", "identifier", ".", "split", "(", "\"@\"", ")", "temp2", "=", "temp", "[", "1", "]", ".", "split", "(", "\"/\"", ")", "return", "[", "temp2", "[", "0", "]", ",", "temp2", "[...
Deconstructs an identifier into an account name and permlink
[ "Deconstructs", "an", "identifier", "into", "an", "account", "name", "and", "permlink" ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L78-L84
ArtoLabs/SimpleSteem
simplesteem/util.py
Util.minutes_back
def minutes_back(self, date): ''' Gives a number (integer) of days since a given date ''' elapsed = (datetime.utcnow() - datetime.strptime(date,'%Y-%m-%dT%H:%M:%S')) if elapsed.days > 0: secondsback = (elapsed.days * 24 * 60 * 60) + elapsed.seconds else: ...
python
def minutes_back(self, date): ''' Gives a number (integer) of days since a given date ''' elapsed = (datetime.utcnow() - datetime.strptime(date,'%Y-%m-%dT%H:%M:%S')) if elapsed.days > 0: secondsback = (elapsed.days * 24 * 60 * 60) + elapsed.seconds else: ...
[ "def", "minutes_back", "(", "self", ",", "date", ")", ":", "elapsed", "=", "(", "datetime", ".", "utcnow", "(", ")", "-", "datetime", ".", "strptime", "(", "date", ",", "'%Y-%m-%dT%H:%M:%S'", ")", ")", "if", "elapsed", ".", "days", ">", "0", ":", "se...
Gives a number (integer) of days since a given date
[ "Gives", "a", "number", "(", "integer", ")", "of", "days", "since", "a", "given", "date" ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L87-L97
ArtoLabs/SimpleSteem
simplesteem/util.py
Util.scale_vote
def scale_vote(self, value): ''' Scales a vote value between 1 and 100 to 150 to 10000 as required by Steem-Python for certain method calls ''' value = int(value) * 100 if value < 100: value = 100 if value > 10000: value = 10000 ret...
python
def scale_vote(self, value): ''' Scales a vote value between 1 and 100 to 150 to 10000 as required by Steem-Python for certain method calls ''' value = int(value) * 100 if value < 100: value = 100 if value > 10000: value = 10000 ret...
[ "def", "scale_vote", "(", "self", ",", "value", ")", ":", "value", "=", "int", "(", "value", ")", "*", "100", "if", "value", "<", "100", ":", "value", "=", "100", "if", "value", ">", "10000", ":", "value", "=", "10000", "return", "value" ]
Scales a vote value between 1 and 100 to 150 to 10000 as required by Steem-Python for certain method calls
[ "Scales", "a", "vote", "value", "between", "1", "and", "100", "to", "150", "to", "10000", "as", "required", "by", "Steem", "-", "Python", "for", "certain", "method", "calls" ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L100-L110
ArtoLabs/SimpleSteem
simplesteem/util.py
Util.calc_regenerated
def calc_regenerated(self, lastvotetime): ''' Uses math formula to calculate the amount of steem power that would have been regenerated given a certain datetime object ''' delta = datetime.utcnow() - datetime.strptime(lastvotetime,'%Y-%m-%dT%H:%M:%S') td = delta.days ...
python
def calc_regenerated(self, lastvotetime): ''' Uses math formula to calculate the amount of steem power that would have been regenerated given a certain datetime object ''' delta = datetime.utcnow() - datetime.strptime(lastvotetime,'%Y-%m-%dT%H:%M:%S') td = delta.days ...
[ "def", "calc_regenerated", "(", "self", ",", "lastvotetime", ")", ":", "delta", "=", "datetime", ".", "utcnow", "(", ")", "-", "datetime", ".", "strptime", "(", "lastvotetime", ",", "'%Y-%m-%dT%H:%M:%S'", ")", "td", "=", "delta", ".", "days", "ts", "=", ...
Uses math formula to calculate the amount of steem power that would have been regenerated given a certain datetime object
[ "Uses", "math", "formula", "to", "calculate", "the", "amount", "of", "steem", "power", "that", "would", "have", "been", "regenerated", "given", "a", "certain", "datetime", "object" ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L113-L122
ArtoLabs/SimpleSteem
simplesteem/util.py
Util.retry
def retry(self, msg, e, retry_num, waittime): ''' Creates the retry message and waits the given default time when a method call fails or a server does not respond appropriately. ''' self.msg.error_message(msg) self.msg.error_message(e) self.msg.error_message("Att...
python
def retry(self, msg, e, retry_num, waittime): ''' Creates the retry message and waits the given default time when a method call fails or a server does not respond appropriately. ''' self.msg.error_message(msg) self.msg.error_message(e) self.msg.error_message("Att...
[ "def", "retry", "(", "self", ",", "msg", ",", "e", ",", "retry_num", ",", "waittime", ")", ":", "self", ".", "msg", ".", "error_message", "(", "msg", ")", "self", ".", "msg", ".", "error_message", "(", "e", ")", "self", ".", "msg", ".", "error_mess...
Creates the retry message and waits the given default time when a method call fails or a server does not respond appropriately.
[ "Creates", "the", "retry", "message", "and", "waits", "the", "given", "default", "time", "when", "a", "method", "call", "fails", "or", "a", "server", "does", "not", "respond", "appropriately", "." ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L125-L133
ArtoLabs/SimpleSteem
simplesteem/util.py
Util.sp_to_rshares
def sp_to_rshares(self, sp, voting_power=10000, vote_pct=10000): """ Obtain the r-shares :param number sp: Steem Power :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting participation (100% = 10000) """ vesting_shares = int(self.s...
python
def sp_to_rshares(self, sp, voting_power=10000, vote_pct=10000): """ Obtain the r-shares :param number sp: Steem Power :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting participation (100% = 10000) """ vesting_shares = int(self.s...
[ "def", "sp_to_rshares", "(", "self", ",", "sp", ",", "voting_power", "=", "10000", ",", "vote_pct", "=", "10000", ")", ":", "vesting_shares", "=", "int", "(", "self", ".", "sp_to_vests", "(", "sp", ")", "*", "1e6", ")", "used_power", "=", "int", "(", ...
Obtain the r-shares :param number sp: Steem Power :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting participation (100% = 10000)
[ "Obtain", "the", "r", "-", "shares", ":", "param", "number", "sp", ":", "Steem", "Power", ":", "param", "int", "voting_power", ":", "voting", "power", "(", "100%", "=", "10000", ")", ":", "param", "int", "vote_pct", ":", "voting", "participation", "(", ...
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/util.py#L157-L168
wtsi-hgi/python-baton-wrapper
baton/_baton/baton_entity_mappers.py
_BatonIrodsEntityMapper._create_entity_query_arguments
def _create_entity_query_arguments(self, load_metadata: bool=True) -> List[str]: """ Create arguments to use with baton. :param load_metadata: whether baton should load metadata :return: the arguments to use with baton """ arguments = ["--acl", "--replicate", "--timestamp...
python
def _create_entity_query_arguments(self, load_metadata: bool=True) -> List[str]: """ Create arguments to use with baton. :param load_metadata: whether baton should load metadata :return: the arguments to use with baton """ arguments = ["--acl", "--replicate", "--timestamp...
[ "def", "_create_entity_query_arguments", "(", "self", ",", "load_metadata", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "arguments", "=", "[", "\"--acl\"", ",", "\"--replicate\"", ",", "\"--timestamp\"", "]", "if", "load_metadata", ":", ...
Create arguments to use with baton. :param load_metadata: whether baton should load metadata :return: the arguments to use with baton
[ "Create", "arguments", "to", "use", "with", "baton", ".", ":", "param", "load_metadata", ":", "whether", "baton", "should", "load", "metadata", ":", "return", ":", "the", "arguments", "to", "use", "with", "baton" ]
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/_baton/baton_entity_mappers.py#L124-L133
wtsi-hgi/python-baton-wrapper
baton/_baton/baton_entity_mappers.py
_BatonIrodsEntityMapper._baton_json_to_irods_entities
def _baton_json_to_irods_entities(self, entities_as_baton_json: List[Dict]) -> List[EntityType]: """ Converts the baton representation of multiple iRODS entities to a list of `EntityType` models. :param entities_as_baton_json: the baton serialization representation of the entities :retur...
python
def _baton_json_to_irods_entities(self, entities_as_baton_json: List[Dict]) -> List[EntityType]: """ Converts the baton representation of multiple iRODS entities to a list of `EntityType` models. :param entities_as_baton_json: the baton serialization representation of the entities :retur...
[ "def", "_baton_json_to_irods_entities", "(", "self", ",", "entities_as_baton_json", ":", "List", "[", "Dict", "]", ")", "->", "List", "[", "EntityType", "]", ":", "assert", "(", "isinstance", "(", "entities_as_baton_json", ",", "list", ")", ")", "entities", "=...
Converts the baton representation of multiple iRODS entities to a list of `EntityType` models. :param entities_as_baton_json: the baton serialization representation of the entities :return: the equivalent models
[ "Converts", "the", "baton", "representation", "of", "multiple", "iRODS", "entities", "to", "a", "list", "of", "EntityType", "models", ".", ":", "param", "entities_as_baton_json", ":", "the", "baton", "serialization", "representation", "of", "the", "entities", ":",...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/_baton/baton_entity_mappers.py#L135-L148
Bornazadeh/django-payline-dotir
payline_dotir/payment_gateway.py
send_url
def send_url(amount, redirect_url, url, api): ''' return payment gateway url to redirect user to it for payment. ''' values = {'api': api, 'amount': amount, 'redirect': redirect_url} send_request = requests.post(SEND_URL_FINAL, data=values) id_get = send_request.text print(id_get) if...
python
def send_url(amount, redirect_url, url, api): ''' return payment gateway url to redirect user to it for payment. ''' values = {'api': api, 'amount': amount, 'redirect': redirect_url} send_request = requests.post(SEND_URL_FINAL, data=values) id_get = send_request.text print(id_get) if...
[ "def", "send_url", "(", "amount", ",", "redirect_url", ",", "url", ",", "api", ")", ":", "values", "=", "{", "'api'", ":", "api", ",", "'amount'", ":", "amount", ",", "'redirect'", ":", "redirect_url", "}", "send_request", "=", "requests", ".", "post", ...
return payment gateway url to redirect user to it for payment.
[ "return", "payment", "gateway", "url", "to", "redirect", "user", "to", "it", "for", "payment", "." ]
train
https://github.com/Bornazadeh/django-payline-dotir/blob/b2ac0b689da0cb3920e92512109247ef0c218f6f/payline_dotir/payment_gateway.py#L11-L36
Bornazadeh/django-payline-dotir
payline_dotir/payment_gateway.py
get_result
def get_result(api, trans_id, id_get): ''' Check if the given id_get and trans_id is from a valid transaction. ''' check_values = {'api': api, 'id_get': id_get, 'trans_id': trans_id} check_transaction = requests.post(CHECK_URL_FINAL, data=check_values) result = check_transaction.text if res...
python
def get_result(api, trans_id, id_get): ''' Check if the given id_get and trans_id is from a valid transaction. ''' check_values = {'api': api, 'id_get': id_get, 'trans_id': trans_id} check_transaction = requests.post(CHECK_URL_FINAL, data=check_values) result = check_transaction.text if res...
[ "def", "get_result", "(", "api", ",", "trans_id", ",", "id_get", ")", ":", "check_values", "=", "{", "'api'", ":", "api", ",", "'id_get'", ":", "id_get", ",", "'trans_id'", ":", "trans_id", "}", "check_transaction", "=", "requests", ".", "post", "(", "CH...
Check if the given id_get and trans_id is from a valid transaction.
[ "Check", "if", "the", "given", "id_get", "and", "trans_id", "is", "from", "a", "valid", "transaction", "." ]
train
https://github.com/Bornazadeh/django-payline-dotir/blob/b2ac0b689da0cb3920e92512109247ef0c218f6f/payline_dotir/payment_gateway.py#L39-L60
ambition-trial/ambition-sites
ambition_sites/get_site_id.py
get_site_id
def get_site_id(name): """Expects sites list has elements of format (SITE_ID(int), site_name(char), site_long_name(char)). """ try: site_id = [site for site in ambition_sites if site[1] == name][0][0] except IndexError: try: site_id = [site for site in ambition_sites if s...
python
def get_site_id(name): """Expects sites list has elements of format (SITE_ID(int), site_name(char), site_long_name(char)). """ try: site_id = [site for site in ambition_sites if site[1] == name][0][0] except IndexError: try: site_id = [site for site in ambition_sites if s...
[ "def", "get_site_id", "(", "name", ")", ":", "try", ":", "site_id", "=", "[", "site", "for", "site", "in", "ambition_sites", "if", "site", "[", "1", "]", "==", "name", "]", "[", "0", "]", "[", "0", "]", "except", "IndexError", ":", "try", ":", "s...
Expects sites list has elements of format (SITE_ID(int), site_name(char), site_long_name(char)).
[ "Expects", "sites", "list", "has", "elements", "of", "format", "(", "SITE_ID", "(", "int", ")", "site_name", "(", "char", ")", "site_long_name", "(", "char", "))", "." ]
train
https://github.com/ambition-trial/ambition-sites/blob/35c0507af9294150a799aec85f328da686039fd5/ambition_sites/get_site_id.py#L8-L24
sunjinopensource/asynmsg
asynmsg.py
_run_once
def _run_once(runner_list, extra_tick, use_poll): """ :return True - success; False - extra_tick failure; runner object - the runner who tick failure """ if len(runner_list) > 0: asyncore.loop(0, use_poll, None, 1) for runner in runner_list: if not runner.tick(): ...
python
def _run_once(runner_list, extra_tick, use_poll): """ :return True - success; False - extra_tick failure; runner object - the runner who tick failure """ if len(runner_list) > 0: asyncore.loop(0, use_poll, None, 1) for runner in runner_list: if not runner.tick(): ...
[ "def", "_run_once", "(", "runner_list", ",", "extra_tick", ",", "use_poll", ")", ":", "if", "len", "(", "runner_list", ")", ">", "0", ":", "asyncore", ".", "loop", "(", "0", ",", "use_poll", ",", "None", ",", "1", ")", "for", "runner", "in", "runner_...
:return True - success; False - extra_tick failure; runner object - the runner who tick failure
[ ":", "return", "True", "-", "success", ";", "False", "-", "extra_tick", "failure", ";", "runner", "object", "-", "the", "runner", "who", "tick", "failure" ]
train
https://github.com/sunjinopensource/asynmsg/blob/9c1d14f859cc6702446c3bb30b9916280429bd1d/asynmsg.py#L98-L111
sunjinopensource/asynmsg
asynmsg.py
run_once
def run_once(runner_list=None, extra_tick=Sleep(0.001), use_poll=False, auto_stop=True): """ :param auto_stop when tick error occur, stop all runners, except: if error was from a runner tick and the runner has set 'only_stop_self_when_tick_error' to True, then only this runner stop """ i...
python
def run_once(runner_list=None, extra_tick=Sleep(0.001), use_poll=False, auto_stop=True): """ :param auto_stop when tick error occur, stop all runners, except: if error was from a runner tick and the runner has set 'only_stop_self_when_tick_error' to True, then only this runner stop """ i...
[ "def", "run_once", "(", "runner_list", "=", "None", ",", "extra_tick", "=", "Sleep", "(", "0.001", ")", ",", "use_poll", "=", "False", ",", "auto_stop", "=", "True", ")", ":", "if", "runner_list", "is", "None", ":", "runner_list", "=", "_runner_list", "c...
:param auto_stop when tick error occur, stop all runners, except: if error was from a runner tick and the runner has set 'only_stop_self_when_tick_error' to True, then only this runner stop
[ ":", "param", "auto_stop", "when", "tick", "error", "occur", "stop", "all", "runners", "except", ":", "if", "error", "was", "from", "a", "runner", "tick", "and", "the", "runner", "has", "set", "only_stop_self_when_tick_error", "to", "True", "then", "only", "...
train
https://github.com/sunjinopensource/asynmsg/blob/9c1d14f859cc6702446c3bb30b9916280429bd1d/asynmsg.py#L114-L141
sunjinopensource/asynmsg
asynmsg.py
_Session.send_message
def send_message(self, msg_id, msg_data): """msg_data can be None""" if self._error.has_error() or self._force_close_time > 0: return False byte_msg = self.message_packer.pack(msg_id, msg_data) length = struct.calcsize(self.__class__.message_packer.size_fmt) + len(byte_msg) ...
python
def send_message(self, msg_id, msg_data): """msg_data can be None""" if self._error.has_error() or self._force_close_time > 0: return False byte_msg = self.message_packer.pack(msg_id, msg_data) length = struct.calcsize(self.__class__.message_packer.size_fmt) + len(byte_msg) ...
[ "def", "send_message", "(", "self", ",", "msg_id", ",", "msg_data", ")", ":", "if", "self", ".", "_error", ".", "has_error", "(", ")", "or", "self", ".", "_force_close_time", ">", "0", ":", "return", "False", "byte_msg", "=", "self", ".", "message_packer...
msg_data can be None
[ "msg_data", "can", "be", "None" ]
train
https://github.com/sunjinopensource/asynmsg/blob/9c1d14f859cc6702446c3bb30b9916280429bd1d/asynmsg.py#L495-L508
sunjinopensource/asynmsg
asynmsg.py
ClientInfinite.do_connect
def do_connect(self): """发起连接""" assert self.socket is None self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(self._connect_address)
python
def do_connect(self): """发起连接""" assert self.socket is None self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(self._connect_address)
[ "def", "do_connect", "(", "self", ")", ":", "assert", "self", ".", "socket", "is", "None", "self", ".", "create_socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "connect", "(", "self", ".", "_connect_address", ...
发起连接
[ "发起连接" ]
train
https://github.com/sunjinopensource/asynmsg/blob/9c1d14f859cc6702446c3bb30b9916280429bd1d/asynmsg.py#L956-L960
jeffrimko/Auxly
lib/auxly/filesys.py
abspath
def abspath(relpath, root=None): """Returns an absolute path based on the given root and relative path.""" root = root or cwd() if op.isfile(root): root = op.dirname(root) return op.abspath(op.join(root, relpath))
python
def abspath(relpath, root=None): """Returns an absolute path based on the given root and relative path.""" root = root or cwd() if op.isfile(root): root = op.dirname(root) return op.abspath(op.join(root, relpath))
[ "def", "abspath", "(", "relpath", ",", "root", "=", "None", ")", ":", "root", "=", "root", "or", "cwd", "(", ")", "if", "op", ".", "isfile", "(", "root", ")", ":", "root", "=", "op", ".", "dirname", "(", "root", ")", "return", "op", ".", "abspa...
Returns an absolute path based on the given root and relative path.
[ "Returns", "an", "absolute", "path", "based", "on", "the", "given", "root", "and", "relative", "path", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L203-L208
jeffrimko/Auxly
lib/auxly/filesys.py
makedirs
def makedirs(path, ignore_extsep=False): """Makes all directories required for given path; returns true if successful and false otherwise. **Examples**: :: auxly.filesys.makedirs("bar/baz") """ if not ignore_extsep and op.basename(path).find(os.extsep) > -1: path = op.dirname(pa...
python
def makedirs(path, ignore_extsep=False): """Makes all directories required for given path; returns true if successful and false otherwise. **Examples**: :: auxly.filesys.makedirs("bar/baz") """ if not ignore_extsep and op.basename(path).find(os.extsep) > -1: path = op.dirname(pa...
[ "def", "makedirs", "(", "path", ",", "ignore_extsep", "=", "False", ")", ":", "if", "not", "ignore_extsep", "and", "op", ".", "basename", "(", "path", ")", ".", "find", "(", "os", ".", "extsep", ")", ">", "-", "1", ":", "path", "=", "op", ".", "d...
Makes all directories required for given path; returns true if successful and false otherwise. **Examples**: :: auxly.filesys.makedirs("bar/baz")
[ "Makes", "all", "directories", "required", "for", "given", "path", ";", "returns", "true", "if", "successful", "and", "false", "otherwise", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L223-L237
jeffrimko/Auxly
lib/auxly/filesys.py
delete
def delete(path, regex=None, recurse=False, test=False): """Deletes the file or directory at `path`. If `path` is a directory and `regex` is provided, matching files will be deleted; `recurse` controls whether subdirectories are recursed. A list of deleted items is returned. If `test` is true, nothing w...
python
def delete(path, regex=None, recurse=False, test=False): """Deletes the file or directory at `path`. If `path` is a directory and `regex` is provided, matching files will be deleted; `recurse` controls whether subdirectories are recursed. A list of deleted items is returned. If `test` is true, nothing w...
[ "def", "delete", "(", "path", ",", "regex", "=", "None", ",", "recurse", "=", "False", ",", "test", "=", "False", ")", ":", "deleted", "=", "[", "]", "if", "op", ".", "isfile", "(", "path", ")", ":", "if", "not", "test", ":", "os", ".", "remove...
Deletes the file or directory at `path`. If `path` is a directory and `regex` is provided, matching files will be deleted; `recurse` controls whether subdirectories are recursed. A list of deleted items is returned. If `test` is true, nothing will be deleted and a list of items that would have been dele...
[ "Deletes", "the", "file", "or", "directory", "at", "path", ".", "If", "path", "is", "a", "directory", "and", "regex", "is", "provided", "matching", "files", "will", "be", "deleted", ";", "recurse", "controls", "whether", "subdirectories", "are", "recursed", ...
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L239-L263
jeffrimko/Auxly
lib/auxly/filesys.py
walkfiles
def walkfiles(startdir, regex=None, recurse=True): """Yields the absolute paths of files found within the given start directory. Can optionally filter paths using a regex pattern.""" for r,_,fs in os.walk(startdir): if not recurse and startdir != r: return for f in fs: ...
python
def walkfiles(startdir, regex=None, recurse=True): """Yields the absolute paths of files found within the given start directory. Can optionally filter paths using a regex pattern.""" for r,_,fs in os.walk(startdir): if not recurse and startdir != r: return for f in fs: ...
[ "def", "walkfiles", "(", "startdir", ",", "regex", "=", "None", ",", "recurse", "=", "True", ")", ":", "for", "r", ",", "_", ",", "fs", "in", "os", ".", "walk", "(", "startdir", ")", ":", "if", "not", "recurse", "and", "startdir", "!=", "r", ":",...
Yields the absolute paths of files found within the given start directory. Can optionally filter paths using a regex pattern.
[ "Yields", "the", "absolute", "paths", "of", "files", "found", "within", "the", "given", "start", "directory", ".", "Can", "optionally", "filter", "paths", "using", "a", "regex", "pattern", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L265-L276
jeffrimko/Auxly
lib/auxly/filesys.py
countfiles
def countfiles(path, recurse=False): """Returns the number of files under the given directory path.""" if not op.isdir(path): return 0 count = 0 for r,ds,fs in os.walk(path): count += len(fs) if not recurse: break return count
python
def countfiles(path, recurse=False): """Returns the number of files under the given directory path.""" if not op.isdir(path): return 0 count = 0 for r,ds,fs in os.walk(path): count += len(fs) if not recurse: break return count
[ "def", "countfiles", "(", "path", ",", "recurse", "=", "False", ")", ":", "if", "not", "op", ".", "isdir", "(", "path", ")", ":", "return", "0", "count", "=", "0", "for", "r", ",", "ds", ",", "fs", "in", "os", ".", "walk", "(", "path", ")", "...
Returns the number of files under the given directory path.
[ "Returns", "the", "number", "of", "files", "under", "the", "given", "directory", "path", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L278-L287
jeffrimko/Auxly
lib/auxly/filesys.py
isempty
def isempty(path): """Returns True if the given file or directory path is empty. **Examples**: :: auxly.filesys.isempty("foo.txt") # Works on files... auxly.filesys.isempty("bar") # ...or directories! """ if op.isdir(path): return [] == os.listdir(path) elif op.isfile(...
python
def isempty(path): """Returns True if the given file or directory path is empty. **Examples**: :: auxly.filesys.isempty("foo.txt") # Works on files... auxly.filesys.isempty("bar") # ...or directories! """ if op.isdir(path): return [] == os.listdir(path) elif op.isfile(...
[ "def", "isempty", "(", "path", ")", ":", "if", "op", ".", "isdir", "(", "path", ")", ":", "return", "[", "]", "==", "os", ".", "listdir", "(", "path", ")", "elif", "op", ".", "isfile", "(", "path", ")", ":", "return", "0", "==", "os", ".", "s...
Returns True if the given file or directory path is empty. **Examples**: :: auxly.filesys.isempty("foo.txt") # Works on files... auxly.filesys.isempty("bar") # ...or directories!
[ "Returns", "True", "if", "the", "given", "file", "or", "directory", "path", "is", "empty", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L300-L312
jeffrimko/Auxly
lib/auxly/filesys.py
getsize
def getsize(path, recurse=False): """Returns the size of the file or directory in bytes.""" if not op.isdir(path): return op.getsize(path) size = 0 for r,_,fs in os.walk(path): for f in fs: size += getsize(op.join(r,f)) if not recurse: break return siz...
python
def getsize(path, recurse=False): """Returns the size of the file or directory in bytes.""" if not op.isdir(path): return op.getsize(path) size = 0 for r,_,fs in os.walk(path): for f in fs: size += getsize(op.join(r,f)) if not recurse: break return siz...
[ "def", "getsize", "(", "path", ",", "recurse", "=", "False", ")", ":", "if", "not", "op", ".", "isdir", "(", "path", ")", ":", "return", "op", ".", "getsize", "(", "path", ")", "size", "=", "0", "for", "r", ",", "_", ",", "fs", "in", "os", "....
Returns the size of the file or directory in bytes.
[ "Returns", "the", "size", "of", "the", "file", "or", "directory", "in", "bytes", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L314-L324
jeffrimko/Auxly
lib/auxly/filesys.py
copy
def copy(srcpath, dstpath, overwrite=True): """Copies the file or directory at `srcpath` to `dstpath`. Returns True if successful, False otherwise.""" # Handle bail conditions. if not op.exists(srcpath): return False if not overwrite: if op.isfile(dstpath): return False ...
python
def copy(srcpath, dstpath, overwrite=True): """Copies the file or directory at `srcpath` to `dstpath`. Returns True if successful, False otherwise.""" # Handle bail conditions. if not op.exists(srcpath): return False if not overwrite: if op.isfile(dstpath): return False ...
[ "def", "copy", "(", "srcpath", ",", "dstpath", ",", "overwrite", "=", "True", ")", ":", "# Handle bail conditions.", "if", "not", "op", ".", "exists", "(", "srcpath", ")", ":", "return", "False", "if", "not", "overwrite", ":", "if", "op", ".", "isfile", ...
Copies the file or directory at `srcpath` to `dstpath`. Returns True if successful, False otherwise.
[ "Copies", "the", "file", "or", "directory", "at", "srcpath", "to", "dstpath", ".", "Returns", "True", "if", "successful", "False", "otherwise", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L326-L362
jeffrimko/Auxly
lib/auxly/filesys.py
move
def move(srcpath, dstpath, overwrite=True): """Moves the file or directory at `srcpath` to `dstpath`. Returns True if successful, False otherwise.""" # TODO: (JRR@201612230924) Consider adding smarter checks to prevent files ending up with directory names; e.g. if dstpath directory does not exist. if no...
python
def move(srcpath, dstpath, overwrite=True): """Moves the file or directory at `srcpath` to `dstpath`. Returns True if successful, False otherwise.""" # TODO: (JRR@201612230924) Consider adding smarter checks to prevent files ending up with directory names; e.g. if dstpath directory does not exist. if no...
[ "def", "move", "(", "srcpath", ",", "dstpath", ",", "overwrite", "=", "True", ")", ":", "# TODO: (JRR@201612230924) Consider adding smarter checks to prevent files ending up with directory names; e.g. if dstpath directory does not exist.", "if", "not", "op", ".", "exists", "(", ...
Moves the file or directory at `srcpath` to `dstpath`. Returns True if successful, False otherwise.
[ "Moves", "the", "file", "or", "directory", "at", "srcpath", "to", "dstpath", ".", "Returns", "True", "if", "successful", "False", "otherwise", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L364-L401
jeffrimko/Auxly
lib/auxly/filesys.py
checksum
def checksum(fpath, hasher=None, asbytes=False): """Returns the checksum of the file at the given path as a hex string (default) or as a bytes literal. Uses MD5 by default. **Attribution**: Based on code from `Stack Overflow <https://stackoverflow.com/a/3431835/789078>`_.""" def blockiter(fpath...
python
def checksum(fpath, hasher=None, asbytes=False): """Returns the checksum of the file at the given path as a hex string (default) or as a bytes literal. Uses MD5 by default. **Attribution**: Based on code from `Stack Overflow <https://stackoverflow.com/a/3431835/789078>`_.""" def blockiter(fpath...
[ "def", "checksum", "(", "fpath", ",", "hasher", "=", "None", ",", "asbytes", "=", "False", ")", ":", "def", "blockiter", "(", "fpath", ",", "blocksize", "=", "0x1000", ")", ":", "with", "open", "(", "fpath", ",", "\"rb\"", ")", "as", "afile", ":", ...
Returns the checksum of the file at the given path as a hex string (default) or as a bytes literal. Uses MD5 by default. **Attribution**: Based on code from `Stack Overflow <https://stackoverflow.com/a/3431835/789078>`_.
[ "Returns", "the", "checksum", "of", "the", "file", "at", "the", "given", "path", "as", "a", "hex", "string", "(", "default", ")", "or", "as", "a", "bytes", "literal", ".", "Uses", "MD5", "by", "default", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L403-L419
jeffrimko/Auxly
lib/auxly/filesys.py
_FileSysObject.dirpath
def dirpath(self): """Returns a Path object for the directory associated with this object.""" if self.isfile(): return Path(op.dirname(self._fspath)) else: return Path(self)
python
def dirpath(self): """Returns a Path object for the directory associated with this object.""" if self.isfile(): return Path(op.dirname(self._fspath)) else: return Path(self)
[ "def", "dirpath", "(", "self", ")", ":", "if", "self", ".", "isfile", "(", ")", ":", "return", "Path", "(", "op", ".", "dirname", "(", "self", ".", "_fspath", ")", ")", "else", ":", "return", "Path", "(", "self", ")" ]
Returns a Path object for the directory associated with this object.
[ "Returns", "a", "Path", "object", "for", "the", "directory", "associated", "with", "this", "object", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L65-L70
jeffrimko/Auxly
lib/auxly/filesys.py
File.read
def read(self, encoding=None): """Reads from the file and returns result as a string.""" encoding = encoding or ENCODING try: with codecs.open(self.path, encoding=encoding) as fi: return fi.read() except: return None
python
def read(self, encoding=None): """Reads from the file and returns result as a string.""" encoding = encoding or ENCODING try: with codecs.open(self.path, encoding=encoding) as fi: return fi.read() except: return None
[ "def", "read", "(", "self", ",", "encoding", "=", "None", ")", ":", "encoding", "=", "encoding", "or", "ENCODING", "try", ":", "with", "codecs", ".", "open", "(", "self", ".", "path", ",", "encoding", "=", "encoding", ")", "as", "fi", ":", "return", ...
Reads from the file and returns result as a string.
[ "Reads", "from", "the", "file", "and", "returns", "result", "as", "a", "string", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L131-L138
jeffrimko/Auxly
lib/auxly/filesys.py
File.readlines
def readlines(self, encoding=None): """Reads from the file and returns result as a list of lines.""" try: encoding = encoding or ENCODING with codecs.open(self.path, encoding=None) as fi: return fi.readlines() except: return []
python
def readlines(self, encoding=None): """Reads from the file and returns result as a list of lines.""" try: encoding = encoding or ENCODING with codecs.open(self.path, encoding=None) as fi: return fi.readlines() except: return []
[ "def", "readlines", "(", "self", ",", "encoding", "=", "None", ")", ":", "try", ":", "encoding", "=", "encoding", "or", "ENCODING", "with", "codecs", ".", "open", "(", "self", ".", "path", ",", "encoding", "=", "None", ")", "as", "fi", ":", "return",...
Reads from the file and returns result as a list of lines.
[ "Reads", "from", "the", "file", "and", "returns", "result", "as", "a", "list", "of", "lines", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L139-L146
jeffrimko/Auxly
lib/auxly/filesys.py
File._write
def _write(self, content, mode, encoding=None, linesep=False): """Handles file writes.""" makedirs(self.path) try: encoding = encoding or ENCODING if "b" not in mode: try: content = str(content) except: ...
python
def _write(self, content, mode, encoding=None, linesep=False): """Handles file writes.""" makedirs(self.path) try: encoding = encoding or ENCODING if "b" not in mode: try: content = str(content) except: ...
[ "def", "_write", "(", "self", ",", "content", ",", "mode", ",", "encoding", "=", "None", ",", "linesep", "=", "False", ")", ":", "makedirs", "(", "self", ".", "path", ")", "try", ":", "encoding", "=", "encoding", "or", "ENCODING", "if", "\"b\"", "not...
Handles file writes.
[ "Handles", "file", "writes", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L147-L163
jeffrimko/Auxly
lib/auxly/filesys.py
File.append
def append(self, content, binary=False, encoding=None): """Appends the given content to the file. Existing content is preserved. Returns true if successful, false otherwise.""" mode = "ab" if binary else "a" return self._write(content, mode, encoding=encoding, linesep=False)
python
def append(self, content, binary=False, encoding=None): """Appends the given content to the file. Existing content is preserved. Returns true if successful, false otherwise.""" mode = "ab" if binary else "a" return self._write(content, mode, encoding=encoding, linesep=False)
[ "def", "append", "(", "self", ",", "content", ",", "binary", "=", "False", ",", "encoding", "=", "None", ")", ":", "mode", "=", "\"ab\"", "if", "binary", "else", "\"a\"", "return", "self", ".", "_write", "(", "content", ",", "mode", ",", "encoding", ...
Appends the given content to the file. Existing content is preserved. Returns true if successful, false otherwise.
[ "Appends", "the", "given", "content", "to", "the", "file", ".", "Existing", "content", "is", "preserved", ".", "Returns", "true", "if", "successful", "false", "otherwise", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L164-L168
jeffrimko/Auxly
lib/auxly/filesys.py
File.appendline
def appendline(self, content, binary=False, encoding=None): """Same as `append()` but adds a line break after the content.""" mode = "ab" if binary else "a" return self._write(content, mode, encoding=encoding, linesep=True)
python
def appendline(self, content, binary=False, encoding=None): """Same as `append()` but adds a line break after the content.""" mode = "ab" if binary else "a" return self._write(content, mode, encoding=encoding, linesep=True)
[ "def", "appendline", "(", "self", ",", "content", ",", "binary", "=", "False", ",", "encoding", "=", "None", ")", ":", "mode", "=", "\"ab\"", "if", "binary", "else", "\"a\"", "return", "self", ".", "_write", "(", "content", ",", "mode", ",", "encoding"...
Same as `append()` but adds a line break after the content.
[ "Same", "as", "append", "()", "but", "adds", "a", "line", "break", "after", "the", "content", "." ]
train
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L169-L172
pyvec/pyvodb
pyvodb/cli/cliutil.py
handle_raw_output
def handle_raw_output(ctx, data): """If a raw output format is set, dump data and exit""" if ctx.obj['format'] == 'json': print(json_dump(data)) exit(0) if ctx.obj['format'] == 'yaml': print(yaml_dump(data), end='') exit(0)
python
def handle_raw_output(ctx, data): """If a raw output format is set, dump data and exit""" if ctx.obj['format'] == 'json': print(json_dump(data)) exit(0) if ctx.obj['format'] == 'yaml': print(yaml_dump(data), end='') exit(0)
[ "def", "handle_raw_output", "(", "ctx", ",", "data", ")", ":", "if", "ctx", ".", "obj", "[", "'format'", "]", "==", "'json'", ":", "print", "(", "json_dump", "(", "data", ")", ")", "exit", "(", "0", ")", "if", "ctx", ".", "obj", "[", "'format'", ...
If a raw output format is set, dump data and exit
[ "If", "a", "raw", "output", "format", "is", "set", "dump", "data", "and", "exit" ]
train
https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/cli/cliutil.py#L10-L17
mrstephenneal/dirutility
dirutility/walk/multiprocess.py
Sprinter._get_root_files
def _get_root_files(self, directory): """Retrieve files within the root directory""" if len(self.filepaths) is 0: if self.filters: root_files = [(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) ...
python
def _get_root_files(self, directory): """Retrieve files within the root directory""" if len(self.filepaths) is 0: if self.filters: root_files = [(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) ...
[ "def", "_get_root_files", "(", "self", ",", "directory", ")", ":", "if", "len", "(", "self", ".", "filepaths", ")", "is", "0", ":", "if", "self", ".", "filters", ":", "root_files", "=", "[", "(", "directory", ",", "f", ")", "for", "f", "in", "os", ...
Retrieve files within the root directory
[ "Retrieve", "files", "within", "the", "root", "directory" ]
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/multiprocess.py#L45-L56
mrstephenneal/dirutility
dirutility/walk/multiprocess.py
Sprinter.explore_path_filter
def explore_path_filter(self, task_num, dirpath): """ Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to unsear...
python
def explore_path_filter(self, task_num, dirpath): """ Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to unsear...
[ "def", "explore_path_filter", "(", "self", ",", "task_num", ",", "dirpath", ")", ":", "base", ",", "path", "=", "dirpath", "directories", "=", "[", "]", "nondirectories", "=", "[", "]", "if", "self", ".", "filters", ".", "validate", "(", "path", ")", "...
Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to unsearched Queue
[ "Explore", "path", "to", "discover", "unsearched", "directories", "and", "save", "filepaths", ":", "param", "task_num", ":", "Processor", "ID", ":", "param", "dirpath", ":", "Tuple", "(", "base", "directory", "path", ")", "path", "information", "pulled", "from...
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/multiprocess.py#L58-L92
mrstephenneal/dirutility
dirutility/walk/multiprocess.py
Sprinter.explore_path_encompass
def explore_path_encompass(self, task_num, dirpath): """ Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to uns...
python
def explore_path_encompass(self, task_num, dirpath): """ Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to uns...
[ "def", "explore_path_encompass", "(", "self", ",", "task_num", ",", "dirpath", ")", ":", "base", ",", "path", "=", "dirpath", "directories", "=", "[", "]", "nondirectories", "=", "[", "]", "self", ".", "_printer", "(", "\"Task: \"", "+", "str", "(", "tas...
Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to unsearched Queue
[ "Explore", "path", "to", "discover", "unsearched", "directories", "and", "save", "filepaths", ":", "param", "task_num", ":", "Processor", "ID", ":", "param", "dirpath", ":", "Tuple", "(", "base", "directory", "path", ")", "path", "information", "pulled", "from...
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/multiprocess.py#L94-L115
mrstephenneal/dirutility
dirutility/walk/multiprocess.py
Sprinter.parallel_worker
def parallel_worker(self, task_num): """ Continuously pulls directories from the Queue until it is empty. Gets child directories from parent and adds them to Queue. Executes task_done() to remove directory from unsearched Queue :param task_num: Processor ID """ wh...
python
def parallel_worker(self, task_num): """ Continuously pulls directories from the Queue until it is empty. Gets child directories from parent and adds them to Queue. Executes task_done() to remove directory from unsearched Queue :param task_num: Processor ID """ wh...
[ "def", "parallel_worker", "(", "self", ",", "task_num", ")", ":", "while", "True", ":", "base", ",", "path", "=", "self", ".", "unsearched", ".", "get", "(", ")", "dirs", "=", "self", ".", "explore_path", "(", "task_num", ",", "(", "base", ",", "path...
Continuously pulls directories from the Queue until it is empty. Gets child directories from parent and adds them to Queue. Executes task_done() to remove directory from unsearched Queue :param task_num: Processor ID
[ "Continuously", "pulls", "directories", "from", "the", "Queue", "until", "it", "is", "empty", ".", "Gets", "child", "directories", "from", "parent", "and", "adds", "them", "to", "Queue", ".", "Executes", "task_done", "()", "to", "remove", "directory", "from", ...
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/multiprocess.py#L117-L129
mrstephenneal/dirutility
dirutility/walk/multiprocess.py
Sprinter.sprinter
def sprinter(self): """ Called when parallelize is True. This function will generate the file names in a directory tree by adding directories to a Queue and continuously exploring directories in the Queue until Queue is emptied. Significantly faster than crawler method for larger...
python
def sprinter(self): """ Called when parallelize is True. This function will generate the file names in a directory tree by adding directories to a Queue and continuously exploring directories in the Queue until Queue is emptied. Significantly faster than crawler method for larger...
[ "def", "sprinter", "(", "self", ")", ":", "self", ".", "_printer", "(", "'Multiprocess Walk'", ")", "# Loop through directories in case there is more than one (1)", "for", "directory", "in", "self", ".", "directory", ":", "self", ".", "_get_root_files", "(", "director...
Called when parallelize is True. This function will generate the file names in a directory tree by adding directories to a Queue and continuously exploring directories in the Queue until Queue is emptied. Significantly faster than crawler method for larger directory trees.
[ "Called", "when", "parallelize", "is", "True", ".", "This", "function", "will", "generate", "the", "file", "names", "in", "a", "directory", "tree", "by", "adding", "directories", "to", "a", "Queue", "and", "continuously", "exploring", "directories", "in", "the...
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/multiprocess.py#L131-L152
fr33jc/bang
bang/providers/__init__.py
get_provider
def get_provider(name, creds): """ Generates and memoizes a :class:`~bang.providers.provider.Provider` object for the given name. :param str name: The provider name, as given in the config stanza. This token is used to find the appropriate :class:`~bang.providers.provider.Provider`. ...
python
def get_provider(name, creds): """ Generates and memoizes a :class:`~bang.providers.provider.Provider` object for the given name. :param str name: The provider name, as given in the config stanza. This token is used to find the appropriate :class:`~bang.providers.provider.Provider`. ...
[ "def", "get_provider", "(", "name", ",", "creds", ")", ":", "p", "=", "_PROVIDERS", ".", "get", "(", "name", ")", "if", "not", "p", ":", "provider", "=", "PROVIDER_MAP", ".", "get", "(", "name", ")", "if", "not", "provider", ":", "if", "name", "=="...
Generates and memoizes a :class:`~bang.providers.provider.Provider` object for the given name. :param str name: The provider name, as given in the config stanza. This token is used to find the appropriate :class:`~bang.providers.provider.Provider`. :param dict creds: The credentials dic...
[ "Generates", "and", "memoizes", "a", ":", "class", ":", "~bang", ".", "providers", ".", "provider", ".", "Provider", "object", "for", "the", "given", "name", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/__init__.py#L42-L68
humilis/humilis-firehose
scripts/empty-bucket.py
empty_bucket
def empty_bucket(outputs_file): """Empty the bucket associated to the test deployment.""" with open(outputs_file, "r") as f: outputs = yaml.load(f) bucket = outputs["storage"]["BucketName"] print("Emptying bucket {} ...".format(bucket)) os.system("aws s3 rm s3://{} --recursive".format(buck...
python
def empty_bucket(outputs_file): """Empty the bucket associated to the test deployment.""" with open(outputs_file, "r") as f: outputs = yaml.load(f) bucket = outputs["storage"]["BucketName"] print("Emptying bucket {} ...".format(bucket)) os.system("aws s3 rm s3://{} --recursive".format(buck...
[ "def", "empty_bucket", "(", "outputs_file", ")", ":", "with", "open", "(", "outputs_file", ",", "\"r\"", ")", "as", "f", ":", "outputs", "=", "yaml", ".", "load", "(", "f", ")", "bucket", "=", "outputs", "[", "\"storage\"", "]", "[", "\"BucketName\"", ...
Empty the bucket associated to the test deployment.
[ "Empty", "the", "bucket", "associated", "to", "the", "test", "deployment", "." ]
train
https://github.com/humilis/humilis-firehose/blob/8611e4b18d534bbafb638597da1304fc87be62b5/scripts/empty-bucket.py#L9-L18
scivision/histutils
histutils/findnearest.py
findClosestAzel
def findClosestAzel(az, el, azpts, elpts): """ assumes that azpts, elpts are each list of 1-D arrays or 2-D arrays az: 2-D Numpy array of azimuths in the image el: 2-D Numpy array of elevations in the image azpts: 1-D or 2-D Numpy array of azimuth points to see where nearest neighbor index is el...
python
def findClosestAzel(az, el, azpts, elpts): """ assumes that azpts, elpts are each list of 1-D arrays or 2-D arrays az: 2-D Numpy array of azimuths in the image el: 2-D Numpy array of elevations in the image azpts: 1-D or 2-D Numpy array of azimuth points to see where nearest neighbor index is el...
[ "def", "findClosestAzel", "(", "az", ",", "el", ",", "azpts", ",", "elpts", ")", ":", "assert", "az", ".", "ndim", "==", "2", "assert", "az", ".", "shape", "==", "el", ".", "shape", "azpts", "=", "np", ".", "atleast_1d", "(", "azpts", ")", "elpts",...
assumes that azpts, elpts are each list of 1-D arrays or 2-D arrays az: 2-D Numpy array of azimuths in the image el: 2-D Numpy array of elevations in the image azpts: 1-D or 2-D Numpy array of azimuth points to see where nearest neighbor index is elpts: 1-D or 2-D Numpy array of azimuth points to see wh...
[ "assumes", "that", "azpts", "elpts", "are", "each", "list", "of", "1", "-", "D", "arrays", "or", "2", "-", "D", "arrays", "az", ":", "2", "-", "D", "Numpy", "array", "of", "azimuths", "in", "the", "image", "el", ":", "2", "-", "D", "Numpy", "arra...
train
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/findnearest.py#L6-L40
scivision/histutils
histutils/findnearest.py
_findindex
def _findindex(az0, el0, az, el): """ inputs: ------ az0, el0: N-D array of azimuth, elevation. May be masked arrays az, el: 1-D vectors of azimuth, elevation points from other camera to find closest angle for joint FOV. output: row, col: index of camera 0 closest to camera 1 FOV for each ...
python
def _findindex(az0, el0, az, el): """ inputs: ------ az0, el0: N-D array of azimuth, elevation. May be masked arrays az, el: 1-D vectors of azimuth, elevation points from other camera to find closest angle for joint FOV. output: row, col: index of camera 0 closest to camera 1 FOV for each ...
[ "def", "_findindex", "(", "az0", ",", "el0", ",", "az", ",", "el", ")", ":", "assert", "az0", ".", "size", "==", "el0", ".", "size", "# just for clarity", "assert", "az", ".", "ndim", "==", "el", ".", "ndim", "==", "1", ",", "'expect vector of test poi...
inputs: ------ az0, el0: N-D array of azimuth, elevation. May be masked arrays az, el: 1-D vectors of azimuth, elevation points from other camera to find closest angle for joint FOV. output: row, col: index of camera 0 closest to camera 1 FOV for each unmasked pixel I think with some minor tw...
[ "inputs", ":", "------", "az0", "el0", ":", "N", "-", "D", "array", "of", "azimuth", "elevation", ".", "May", "be", "masked", "arrays", "az", "el", ":", "1", "-", "D", "vectors", "of", "azimuth", "elevation", "points", "from", "other", "camera", "to", ...
train
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/findnearest.py#L43-L75
marccarre/py_sak
py_sak/concurrent.py
concurrent_class_factory
def concurrent_class_factory(concurrent_class_name, thread_unsafe_class): ''' Dynamically creates a thread-safe class which exposes the same API as the provided thread-unsafe class, but for which all public methods now: - accept an iterable of inputs, - parallelize processing of this iterable on a p...
python
def concurrent_class_factory(concurrent_class_name, thread_unsafe_class): ''' Dynamically creates a thread-safe class which exposes the same API as the provided thread-unsafe class, but for which all public methods now: - accept an iterable of inputs, - parallelize processing of this iterable on a p...
[ "def", "concurrent_class_factory", "(", "concurrent_class_name", ",", "thread_unsafe_class", ")", ":", "concurrent_class", "=", "_create_blank_concurrent_class", "(", "concurrent_class_name", ",", "thread_unsafe_class", ")", "for", "method_name", ",", "method", "in", "getme...
Dynamically creates a thread-safe class which exposes the same API as the provided thread-unsafe class, but for which all public methods now: - accept an iterable of inputs, - parallelize processing of this iterable on a pool of workers. The resulting class's __init__ method optionally accepts: %s
[ "Dynamically", "creates", "a", "thread", "-", "safe", "class", "which", "exposes", "the", "same", "API", "as", "the", "provided", "thread", "-", "unsafe", "class", "but", "for", "which", "all", "public", "methods", "now", ":", "-", "accept", "an", "iterabl...
train
https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/concurrent.py#L40-L53
zeromake/aiko
aiko/utils.py
decode_bytes
def decode_bytes(data: bytes, encoding: str = DEFAULT_CODING, errors: str = 'strict') -> str: """ 集中调用 decode """ return data.decode(encoding, errors)
python
def decode_bytes(data: bytes, encoding: str = DEFAULT_CODING, errors: str = 'strict') -> str: """ 集中调用 decode """ return data.decode(encoding, errors)
[ "def", "decode_bytes", "(", "data", ":", "bytes", ",", "encoding", ":", "str", "=", "DEFAULT_CODING", ",", "errors", ":", "str", "=", "'strict'", ")", "->", "str", ":", "return", "data", ".", "decode", "(", "encoding", ",", "errors", ")" ]
集中调用 decode
[ "集中调用", "decode" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L31-L35
zeromake/aiko
aiko/utils.py
encode_str
def encode_str(data: str, encoding: str = DEFAULT_CODING, errors: str = 'strict') -> bytes: """ 集中调用 encode """ return data.encode(encoding, errors)
python
def encode_str(data: str, encoding: str = DEFAULT_CODING, errors: str = 'strict') -> bytes: """ 集中调用 encode """ return data.encode(encoding, errors)
[ "def", "encode_str", "(", "data", ":", "str", ",", "encoding", ":", "str", "=", "DEFAULT_CODING", ",", "errors", ":", "str", "=", "'strict'", ")", "->", "bytes", ":", "return", "data", ".", "encode", "(", "encoding", ",", "errors", ")" ]
集中调用 encode
[ "集中调用", "encode" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L38-L42
zeromake/aiko
aiko/utils.py
handle_async_gen
def handle_async_gen(gen: Any, gen_obj: Any) -> Any: """ 处理异步生成器 """ if gen is None: return None if asyncio.iscoroutine(gen): try: temp = yield from gen gen_obj.send(temp) return except Exception as error: try: g...
python
def handle_async_gen(gen: Any, gen_obj: Any) -> Any: """ 处理异步生成器 """ if gen is None: return None if asyncio.iscoroutine(gen): try: temp = yield from gen gen_obj.send(temp) return except Exception as error: try: g...
[ "def", "handle_async_gen", "(", "gen", ":", "Any", ",", "gen_obj", ":", "Any", ")", "->", "Any", ":", "if", "gen", "is", "None", ":", "return", "None", "if", "asyncio", ".", "iscoroutine", "(", "gen", ")", ":", "try", ":", "temp", "=", "yield", "fr...
处理异步生成器
[ "处理异步生成器" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L46-L64
zeromake/aiko
aiko/utils.py
parse_http_date
def parse_http_date(date: str) -> int: """ 解析http时间到 timestamp """ try: return int( datetime.strptime( date, ISO_DATE_FORMAT, ).timestamp(), ) except ValueError: return 0
python
def parse_http_date(date: str) -> int: """ 解析http时间到 timestamp """ try: return int( datetime.strptime( date, ISO_DATE_FORMAT, ).timestamp(), ) except ValueError: return 0
[ "def", "parse_http_date", "(", "date", ":", "str", ")", "->", "int", ":", "try", ":", "return", "int", "(", "datetime", ".", "strptime", "(", "date", ",", "ISO_DATE_FORMAT", ",", ")", ".", "timestamp", "(", ")", ",", ")", "except", "ValueError", ":", ...
解析http时间到 timestamp
[ "解析http时间到", "timestamp" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L67-L79
zeromake/aiko
aiko/utils.py
fresh
def fresh(req_headers: HEADER_TYPE, res_headers: HEADER_TYPE) -> bool: """ 根据 req_headers, res_headers 判断改消息是否为 304 """ modified_since = cast( Optional[str], req_headers.get('if-modified-since'), ) none_match = cast( Optional[str], req_headers.get('if-none-match')...
python
def fresh(req_headers: HEADER_TYPE, res_headers: HEADER_TYPE) -> bool: """ 根据 req_headers, res_headers 判断改消息是否为 304 """ modified_since = cast( Optional[str], req_headers.get('if-modified-since'), ) none_match = cast( Optional[str], req_headers.get('if-none-match')...
[ "def", "fresh", "(", "req_headers", ":", "HEADER_TYPE", ",", "res_headers", ":", "HEADER_TYPE", ")", "->", "bool", ":", "modified_since", "=", "cast", "(", "Optional", "[", "str", "]", ",", "req_headers", ".", "get", "(", "'if-modified-since'", ")", ",", "...
根据 req_headers, res_headers 判断改消息是否为 304
[ "根据", "req_headers", "res_headers", "判断改消息是否为", "304" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L82-L137
zeromake/aiko
aiko/utils.py
ProxyAttr.reuse_handle
def reuse_handle( self, name: str, rename: str, pmap: Dict[str, Set[str]], ) -> bool: """ 判断是否复用之前的 """ if name in pmap: name_map = pmap[name] if rename not in name_map: name_map.add(rename) ...
python
def reuse_handle( self, name: str, rename: str, pmap: Dict[str, Set[str]], ) -> bool: """ 判断是否复用之前的 """ if name in pmap: name_map = pmap[name] if rename not in name_map: name_map.add(rename) ...
[ "def", "reuse_handle", "(", "self", ",", "name", ":", "str", ",", "rename", ":", "str", ",", "pmap", ":", "Dict", "[", "str", ",", "Set", "[", "str", "]", "]", ",", ")", "->", "bool", ":", "if", "name", "in", "pmap", ":", "name_map", "=", "pmap...
判断是否复用之前的
[ "判断是否复用之前的" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L173-L189
zeromake/aiko
aiko/utils.py
ProxyAttr.method
def method(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 method """ if rename is None: rename = name if self.reuse_handle(name, rename, self._method): return self def proxy_method(self2: Any, *args: Any, **kwargs: Any) ...
python
def method(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 method """ if rename is None: rename = name if self.reuse_handle(name, rename, self._method): return self def proxy_method(self2: Any, *args: Any, **kwargs: Any) ...
[ "def", "method", "(", "self", ",", "name", ":", "str", ",", "rename", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "'ProxyAttr'", ":", "if", "rename", "is", "None", ":", "rename", "=", "name", "if", "self", ".", "reuse_handle", "(", "n...
为类设置代理 method
[ "为类设置代理", "method" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L191-L208
zeromake/aiko
aiko/utils.py
ProxyAttr.getter
def getter(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 getattr """ if rename is None: rename = name if self.reuse_handle(name, rename, self._getter): return self def proxy_get(this: Any) -> None: """ ...
python
def getter(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 getattr """ if rename is None: rename = name if self.reuse_handle(name, rename, self._getter): return self def proxy_get(this: Any) -> None: """ ...
[ "def", "getter", "(", "self", ",", "name", ":", "str", ",", "rename", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "'ProxyAttr'", ":", "if", "rename", "is", "None", ":", "rename", "=", "name", "if", "self", ".", "reuse_handle", "(", "n...
为类设置代理 getattr
[ "为类设置代理", "getattr" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L210-L234
zeromake/aiko
aiko/utils.py
ProxyAttr.setter
def setter(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 setter """ if rename is None: rename = name if self.reuse_handle(name, rename, self._setter): return self def proxy_set(this: Any, val: Any) -> None: ...
python
def setter(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 setter """ if rename is None: rename = name if self.reuse_handle(name, rename, self._setter): return self def proxy_set(this: Any, val: Any) -> None: ...
[ "def", "setter", "(", "self", ",", "name", ":", "str", ",", "rename", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "'ProxyAttr'", ":", "if", "rename", "is", "None", ":", "rename", "=", "name", "if", "self", ".", "reuse_handle", "(", "n...
为类设置代理 setter
[ "为类设置代理", "setter" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L236-L259
zeromake/aiko
aiko/utils.py
ProxyAttr.access
def access(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 getter, setter """ self.getter(name, rename) self.setter(name, rename) return self
python
def access(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr': """ 为类设置代理 getter, setter """ self.getter(name, rename) self.setter(name, rename) return self
[ "def", "access", "(", "self", ",", "name", ":", "str", ",", "rename", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "'ProxyAttr'", ":", "self", ".", "getter", "(", "name", ",", "rename", ")", "self", ".", "setter", "(", "name", ",", "...
为类设置代理 getter, setter
[ "为类设置代理", "getter", "setter" ]
train
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L261-L267
MacHu-GWU/angora-project
angora/text/formatter.py
fmt_title
def fmt_title(text): """Article title formatter. Except functional words, first letter uppercase. Example: "Google Killing Annoying Browsing Feature" **中文文档** 文章标题的格式, 除了虚词, 每个英文单词的第一个字母大写。 """ text = text.strip() if len(text) == 0: # if empty string, return it return text ...
python
def fmt_title(text): """Article title formatter. Except functional words, first letter uppercase. Example: "Google Killing Annoying Browsing Feature" **中文文档** 文章标题的格式, 除了虚词, 每个英文单词的第一个字母大写。 """ text = text.strip() if len(text) == 0: # if empty string, return it return text ...
[ "def", "fmt_title", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "len", "(", "text", ")", "==", "0", ":", "# if empty string, return it", "return", "text", "else", ":", "text", "=", "text", ".", "lower", "(", ")", "# lowe...
Article title formatter. Except functional words, first letter uppercase. Example: "Google Killing Annoying Browsing Feature" **中文文档** 文章标题的格式, 除了虚词, 每个英文单词的第一个字母大写。
[ "Article", "title", "formatter", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/formatter.py#L36-L62
MacHu-GWU/angora-project
angora/text/formatter.py
fmt_sentence
def fmt_sentence(text): """English sentence formatter. First letter is always upper case. Example: "Do you want to build a snow man?" **中文文档** 句子格式。每句话的第一个单词第一个字母大写。 """ text = text.strip() if len(text) == 0: # if empty string, return it return text else: text = ...
python
def fmt_sentence(text): """English sentence formatter. First letter is always upper case. Example: "Do you want to build a snow man?" **中文文档** 句子格式。每句话的第一个单词第一个字母大写。 """ text = text.strip() if len(text) == 0: # if empty string, return it return text else: text = ...
[ "def", "fmt_sentence", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "len", "(", "text", ")", "==", "0", ":", "# if empty string, return it", "return", "text", "else", ":", "text", "=", "text", ".", "lower", "(", ")", "# l...
English sentence formatter. First letter is always upper case. Example: "Do you want to build a snow man?" **中文文档** 句子格式。每句话的第一个单词第一个字母大写。
[ "English", "sentence", "formatter", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/formatter.py#L65-L83
MacHu-GWU/angora-project
angora/text/formatter.py
fmt_filename
def fmt_filename(text): """File name formatter. Remove all file system forbidden char from text. **中文文档** 移除文件系统中不允许的字符。 """ forbidden_char = ["\\", "/", ":", "*", "?", "|", "<", ">", '"'] for char in forbidden_char: text = text.replace(char, "") return text
python
def fmt_filename(text): """File name formatter. Remove all file system forbidden char from text. **中文文档** 移除文件系统中不允许的字符。 """ forbidden_char = ["\\", "/", ":", "*", "?", "|", "<", ">", '"'] for char in forbidden_char: text = text.replace(char, "") return text
[ "def", "fmt_filename", "(", "text", ")", ":", "forbidden_char", "=", "[", "\"\\\\\"", ",", "\"/\"", ",", "\":\"", ",", "\"*\"", ",", "\"?\"", ",", "\"|\"", ",", "\"<\"", ",", "\">\"", ",", "'\"'", "]", "for", "char", "in", "forbidden_char", ":", "text"...
File name formatter. Remove all file system forbidden char from text. **中文文档** 移除文件系统中不允许的字符。
[ "File", "name", "formatter", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/formatter.py#L107-L119
rsalmaso/django-fluo
fluo/forms/fields.py
GroupedChoiceField.clean
def clean(self, value): """ Validates that the input is in self.choices. """ value = super().clean(value) if value in (None, ''): value = '' value = smart_text(value) if value == '': return value valid_values = [] for group_...
python
def clean(self, value): """ Validates that the input is in self.choices. """ value = super().clean(value) if value in (None, ''): value = '' value = smart_text(value) if value == '': return value valid_values = [] for group_...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", ")", ".", "clean", "(", "value", ")", "if", "value", "in", "(", "None", ",", "''", ")", ":", "value", "=", "''", "value", "=", "smart_text", "(", "value", ")", "if...
Validates that the input is in self.choices.
[ "Validates", "that", "the", "input", "is", "in", "self", ".", "choices", "." ]
train
https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/forms/fields.py#L70-L85
salimm/pylods
pylods/deserialize.py
DeserializationContext.copy_all
def copy_all(self, ctxt): ''' copies all values into the current context from given context :param ctxt: ''' for key, value in ctxt.iteritems: self.set_attribute(key, value)
python
def copy_all(self, ctxt): ''' copies all values into the current context from given context :param ctxt: ''' for key, value in ctxt.iteritems: self.set_attribute(key, value)
[ "def", "copy_all", "(", "self", ",", "ctxt", ")", ":", "for", "key", ",", "value", "in", "ctxt", ".", "iteritems", ":", "self", ".", "set_attribute", "(", "key", ",", "value", ")" ]
copies all values into the current context from given context :param ctxt:
[ "copies", "all", "values", "into", "the", "current", "context", "from", "given", "context", ":", "param", "ctxt", ":" ]
train
https://github.com/salimm/pylods/blob/d089e2a9afb1fa8cb6c754933fc574b512757c40/pylods/deserialize.py#L30-L36
salimm/pylods
pylods/deserialize.py
Typed.resolve
def resolve(cls, propname, objcls=None): ''' resolve type of the class property for the class. If objcls is not set then assume that cls argument (class that the function is called from) is the class we are trying to resolve the type for :param cls: :param ...
python
def resolve(cls, propname, objcls=None): ''' resolve type of the class property for the class. If objcls is not set then assume that cls argument (class that the function is called from) is the class we are trying to resolve the type for :param cls: :param ...
[ "def", "resolve", "(", "cls", ",", "propname", ",", "objcls", "=", "None", ")", ":", "# object class is not given", "if", "objcls", "is", "None", ":", "objcls", "=", "cls", "# get type", "typemap", "=", "cls", ".", "_types", ".", "get", "(", "objcls", ")...
resolve type of the class property for the class. If objcls is not set then assume that cls argument (class that the function is called from) is the class we are trying to resolve the type for :param cls: :param objcls: :param propname:
[ "resolve", "type", "of", "the", "class", "property", "for", "the", "class", ".", "If", "objcls", "is", "not", "set", "then", "assume", "that", "cls", "argument", "(", "class", "that", "the", "function", "is", "called", "from", ")", "is", "the", "class", ...
train
https://github.com/salimm/pylods/blob/d089e2a9afb1fa8cb6c754933fc574b512757c40/pylods/deserialize.py#L143-L161
salimm/pylods
pylods/deserialize.py
Typed.register_type
def register_type(cls, propname, valcls, objcls=None): ''' register type for class :param cls: :param propname: :param valcls: :param objcls: ''' # object class is not given if objcls is None: objcls = cls # g...
python
def register_type(cls, propname, valcls, objcls=None): ''' register type for class :param cls: :param propname: :param valcls: :param objcls: ''' # object class is not given if objcls is None: objcls = cls # g...
[ "def", "register_type", "(", "cls", ",", "propname", ",", "valcls", ",", "objcls", "=", "None", ")", ":", "# object class is not given", "if", "objcls", "is", "None", ":", "objcls", "=", "cls", "# get type map for objcls", "typemap", "=", "cls", ".", "_types",...
register type for class :param cls: :param propname: :param valcls: :param objcls:
[ "register", "type", "for", "class", ":", "param", "cls", ":", ":", "param", "propname", ":", ":", "param", "valcls", ":", ":", "param", "objcls", ":" ]
train
https://github.com/salimm/pylods/blob/d089e2a9afb1fa8cb6c754933fc574b512757c40/pylods/deserialize.py#L164-L183
saltonmassally/Eve-Statsd
eve_statsd/__init__.py
StatsD._init_request_hooks
def _init_request_hooks(self): """ initialize pre request hooks""" for method_type in ('pre', 'post'): for method in _METHODS: event = getattr(self.app, 'on_' + method_type + '_' + method) event_hook = getattr(hooks, method_type + '_' + method) ...
python
def _init_request_hooks(self): """ initialize pre request hooks""" for method_type in ('pre', 'post'): for method in _METHODS: event = getattr(self.app, 'on_' + method_type + '_' + method) event_hook = getattr(hooks, method_type + '_' + method) ...
[ "def", "_init_request_hooks", "(", "self", ")", ":", "for", "method_type", "in", "(", "'pre'", ",", "'post'", ")", ":", "for", "method", "in", "_METHODS", ":", "event", "=", "getattr", "(", "self", ".", "app", ",", "'on_'", "+", "method_type", "+", "'_...
initialize pre request hooks
[ "initialize", "pre", "request", "hooks" ]
train
https://github.com/saltonmassally/Eve-Statsd/blob/bd7cf83db4ca70da47e130ac7600739260179d79/eve_statsd/__init__.py#L50-L56
sbuss/pypercube
pypercube/metric.py
Metric.from_json
def from_json(cls, json_obj): """Build a MetricResponse from JSON. :param json_obj: JSON data representing a Cube Metric. :type json_obj: `String` or `json` :throws: `InvalidMetricError` when any of {type,time,data} fields are not present in json_obj. """ if isin...
python
def from_json(cls, json_obj): """Build a MetricResponse from JSON. :param json_obj: JSON data representing a Cube Metric. :type json_obj: `String` or `json` :throws: `InvalidMetricError` when any of {type,time,data} fields are not present in json_obj. """ if isin...
[ "def", "from_json", "(", "cls", ",", "json_obj", ")", ":", "if", "isinstance", "(", "json_obj", ",", "str", ")", ":", "json_obj", "=", "json", ".", "loads", "(", "json_obj", ")", "time", "=", "None", "value", "=", "None", "if", "cls", ".", "TIME_FIEL...
Build a MetricResponse from JSON. :param json_obj: JSON data representing a Cube Metric. :type json_obj: `String` or `json` :throws: `InvalidMetricError` when any of {type,time,data} fields are not present in json_obj.
[ "Build", "a", "MetricResponse", "from", "JSON", "." ]
train
https://github.com/sbuss/pypercube/blob/e9d2cca9c004b8bad6d1e0b68b080f887a186a22/pypercube/metric.py#L25-L48
mdeous/fatbotslim
fatbotslim/cli.py
make_parser
def make_parser(): """ Creates an argument parser configured with options to run a bot from the command line. :return: configured argument parser :rtype: :class:`argparse.ArgumentParser` """ parser = ArgumentParser( description='Start an IRC bot instance from the command line.', ...
python
def make_parser(): """ Creates an argument parser configured with options to run a bot from the command line. :return: configured argument parser :rtype: :class:`argparse.ArgumentParser` """ parser = ArgumentParser( description='Start an IRC bot instance from the command line.', ...
[ "def", "make_parser", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "'Start an IRC bot instance from the command line.'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ",", ")", "parser", ".", "add_argument", "(", "'-v'", ",", ...
Creates an argument parser configured with options to run a bot from the command line. :return: configured argument parser :rtype: :class:`argparse.ArgumentParser`
[ "Creates", "an", "argument", "parser", "configured", "with", "options", "to", "run", "a", "bot", "from", "the", "command", "line", "." ]
train
https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/cli.py#L37-L96
mdeous/fatbotslim
fatbotslim/cli.py
make_bot
def make_bot(): """ Creates a new bot instance ready to be launched. """ parser = make_parser() args = parser.parse_args() settings = { 'server': args.server, 'port': args.port, 'ssl': args.ssl, 'nick': args.nick, 'realname': args.name, 'channels':...
python
def make_bot(): """ Creates a new bot instance ready to be launched. """ parser = make_parser() args = parser.parse_args() settings = { 'server': args.server, 'port': args.port, 'ssl': args.ssl, 'nick': args.nick, 'realname': args.name, 'channels':...
[ "def", "make_bot", "(", ")", ":", "parser", "=", "make_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "settings", "=", "{", "'server'", ":", "args", ".", "server", ",", "'port'", ":", "args", ".", "port", ",", "'ssl'", ":", ...
Creates a new bot instance ready to be launched.
[ "Creates", "a", "new", "bot", "instance", "ready", "to", "be", "launched", "." ]
train
https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/cli.py#L99-L114
mdeous/fatbotslim
fatbotslim/cli.py
main
def main(bot): """ Entry point for the command line launcher. :param bot: the IRC bot to run :type bot: :class:`fatbotslim.irc.bot.IRC` """ greenlet = spawn(bot.run) try: greenlet.join() except KeyboardInterrupt: print '' # cosmetics matters log.info("Killed by ...
python
def main(bot): """ Entry point for the command line launcher. :param bot: the IRC bot to run :type bot: :class:`fatbotslim.irc.bot.IRC` """ greenlet = spawn(bot.run) try: greenlet.join() except KeyboardInterrupt: print '' # cosmetics matters log.info("Killed by ...
[ "def", "main", "(", "bot", ")", ":", "greenlet", "=", "spawn", "(", "bot", ".", "run", ")", "try", ":", "greenlet", ".", "join", "(", ")", "except", "KeyboardInterrupt", ":", "print", "''", "# cosmetics matters", "log", ".", "info", "(", "\"Killed by use...
Entry point for the command line launcher. :param bot: the IRC bot to run :type bot: :class:`fatbotslim.irc.bot.IRC`
[ "Entry", "point", "for", "the", "command", "line", "launcher", "." ]
train
https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/cli.py#L117-L132
fr33jc/bang
bang/stack.py
Stack.get_namespace
def get_namespace(self, key): """ Returns a :class:`~bang.util.SharedNamespace` for the given :attr:`key`. These are used by :class:`~bang.deployers.deployer.Deployer` objects of the same ``deployer_class`` to coordinate control over multiple deployed instances of like r...
python
def get_namespace(self, key): """ Returns a :class:`~bang.util.SharedNamespace` for the given :attr:`key`. These are used by :class:`~bang.deployers.deployer.Deployer` objects of the same ``deployer_class`` to coordinate control over multiple deployed instances of like r...
[ "def", "get_namespace", "(", "self", ",", "key", ")", ":", "namespace", "=", "self", ".", "shared_namespaces", ".", "get", "(", "key", ")", "if", "namespace", ":", "return", "namespace", "ns", "=", "SharedNamespace", "(", "self", ".", "manager", ")", "se...
Returns a :class:`~bang.util.SharedNamespace` for the given :attr:`key`. These are used by :class:`~bang.deployers.deployer.Deployer` objects of the same ``deployer_class`` to coordinate control over multiple deployed instances of like resources. E.g. With 5 clones of an application ...
[ "Returns", "a", ":", "class", ":", "~bang", ".", "util", ".", "SharedNamespace", "for", "the", "given", ":", "attr", ":", "key", ".", "These", "are", "used", "by", ":", "class", ":", "~bang", ".", "deployers", ".", "deployer", ".", "Deployer", "objects...
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L89-L111
fr33jc/bang
bang/stack.py
Stack.find_first
def find_first(self, attr_name, resources, extra_prefix=''): """ Returns the boto object for the first resource in ``resources`` that belongs to this stack. Uses the attribute specified by ``attr_name`` to match the stack name. E.g. An RDS instance for a stack named ``foo`` mi...
python
def find_first(self, attr_name, resources, extra_prefix=''): """ Returns the boto object for the first resource in ``resources`` that belongs to this stack. Uses the attribute specified by ``attr_name`` to match the stack name. E.g. An RDS instance for a stack named ``foo`` mi...
[ "def", "find_first", "(", "self", ",", "attr_name", ",", "resources", ",", "extra_prefix", "=", "''", ")", ":", "prefix", "=", "self", ".", "name", "+", "'-'", "+", "(", "extra_prefix", "+", "'-'", "if", "extra_prefix", "else", "''", ")", "for", "res",...
Returns the boto object for the first resource in ``resources`` that belongs to this stack. Uses the attribute specified by ``attr_name`` to match the stack name. E.g. An RDS instance for a stack named ``foo`` might be named ``foo-mydb-fis8932ifs``. This call:: find_firs...
[ "Returns", "the", "boto", "object", "for", "the", "first", "resource", "in", "resources", "that", "belongs", "to", "this", "stack", ".", "Uses", "the", "attribute", "specified", "by", "attr_name", "to", "match", "the", "stack", "name", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L113-L136
fr33jc/bang
bang/stack.py
Stack.add_lb_secgroup
def add_lb_secgroup(self, lb_name, hosts, port): """ Used by the load balancer deployer to register a hostname for a load balancer, in order that security group rules can be applied later. This is multiprocess-safe, but since keys are accessed only be a single load balancer deplo...
python
def add_lb_secgroup(self, lb_name, hosts, port): """ Used by the load balancer deployer to register a hostname for a load balancer, in order that security group rules can be applied later. This is multiprocess-safe, but since keys are accessed only be a single load balancer deplo...
[ "def", "add_lb_secgroup", "(", "self", ",", "lb_name", ",", "hosts", ",", "port", ")", ":", "self", ".", "lb_sec_groups", ".", "merge", "(", "lb_name", ",", "{", "'hosts'", ":", "hosts", ",", "'port'", ":", "port", "}", ")" ]
Used by the load balancer deployer to register a hostname for a load balancer, in order that security group rules can be applied later. This is multiprocess-safe, but since keys are accessed only be a single load balancer deployer there should be no conflicts. :param str lb_name...
[ "Used", "by", "the", "load", "balancer", "deployer", "to", "register", "a", "hostname", "for", "a", "load", "balancer", "in", "order", "that", "security", "group", "rules", "can", "be", "applied", "later", ".", "This", "is", "multiprocess", "-", "safe", "b...
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L138-L152
fr33jc/bang
bang/stack.py
Stack.add_host
def add_host(self, host, group_names=None, host_vars=None): """ Used by deployers to add hosts to the inventory. :param str host: The host identifier (e.g. hostname, IP address) to use in the inventory. :param list group_names: A list of group names to which the host ...
python
def add_host(self, host, group_names=None, host_vars=None): """ Used by deployers to add hosts to the inventory. :param str host: The host identifier (e.g. hostname, IP address) to use in the inventory. :param list group_names: A list of group names to which the host ...
[ "def", "add_host", "(", "self", ",", "host", ",", "group_names", "=", "None", ",", "host_vars", "=", "None", ")", ":", "gnames", "=", "group_names", "if", "group_names", "else", "[", "]", "hvars", "=", "host_vars", "if", "host_vars", "else", "{", "}", ...
Used by deployers to add hosts to the inventory. :param str host: The host identifier (e.g. hostname, IP address) to use in the inventory. :param list group_names: A list of group names to which the host belongs. **Note: This list will be sorted in-place.** :param ...
[ "Used", "by", "deployers", "to", "add", "hosts", "to", "the", "inventory", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L154-L186
fr33jc/bang
bang/stack.py
Stack.describe
def describe(self): """Iterates through the deployers but doesn't run anything""" for stage, corunners in self.get_deployers(): print self.name, "STAGE ", stage for d in corunners: print d.__class__.__name__, ",".join( [p[1].__name__ for p ...
python
def describe(self): """Iterates through the deployers but doesn't run anything""" for stage, corunners in self.get_deployers(): print self.name, "STAGE ", stage for d in corunners: print d.__class__.__name__, ",".join( [p[1].__name__ for p ...
[ "def", "describe", "(", "self", ")", ":", "for", "stage", ",", "corunners", "in", "self", ".", "get_deployers", "(", ")", ":", "print", "self", ".", "name", ",", "\"STAGE \"", ",", "stage", "for", "d", "in", "corunners", ":", "print", "d", ".", "__cl...
Iterates through the deployers but doesn't run anything
[ "Iterates", "through", "the", "deployers", "but", "doesn", "t", "run", "anything" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L188-L195
fr33jc/bang
bang/stack.py
Stack.configure
def configure(self): """ Executes the ansible playbooks that configure the servers in the stack. Assumes that the root playbook directory is ``./playbooks/`` relative to the stack configuration file. Also sets the ansible *module_path* to be ``./common_modules/`` relative to th...
python
def configure(self): """ Executes the ansible playbooks that configure the servers in the stack. Assumes that the root playbook directory is ``./playbooks/`` relative to the stack configuration file. Also sets the ansible *module_path* to be ``./common_modules/`` relative to th...
[ "def", "configure", "(", "self", ")", ":", "cfg", "=", "self", ".", "config", "bang_config_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "cfg", ".", "filepath", ")", ")", "playbook_dir", "=", "os", ".", ...
Executes the ansible playbooks that configure the servers in the stack. Assumes that the root playbook directory is ``./playbooks/`` relative to the stack configuration file. Also sets the ansible *module_path* to be ``./common_modules/`` relative to the stack configuration file. E.g....
[ "Executes", "the", "ansible", "playbooks", "that", "configure", "the", "servers", "in", "the", "stack", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L234-L336
fr33jc/bang
bang/stack.py
Stack.show_inventory
def show_inventory(self, pretty=False): """ Satisfies the ``--list`` portion of ansible's external inventory API. Allows ``bang`` to be used as an external inventory script, for example when running ad-hoc ops tasks. For more details, see: http://ansible.cc/docs/api.html#extern...
python
def show_inventory(self, pretty=False): """ Satisfies the ``--list`` portion of ansible's external inventory API. Allows ``bang`` to be used as an external inventory script, for example when running ad-hoc ops tasks. For more details, see: http://ansible.cc/docs/api.html#extern...
[ "def", "show_inventory", "(", "self", ",", "pretty", "=", "False", ")", ":", "inv_lists", "=", "copy", ".", "deepcopy", "(", "self", ".", "groups_and_vars", ".", "lists", ")", "# sort the host lists to help consumers of the inventory (e.g. ansible", "# playbooks)", "f...
Satisfies the ``--list`` portion of ansible's external inventory API. Allows ``bang`` to be used as an external inventory script, for example when running ad-hoc ops tasks. For more details, see: http://ansible.cc/docs/api.html#external-inventory-scripts
[ "Satisfies", "the", "--", "list", "portion", "of", "ansible", "s", "external", "inventory", "API", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L348-L376
krinj/k-util
k_util/core.py
interpolate_color
def interpolate_color(c1, c2, factor: float) -> list: """ Linear interpolate two 3-channel colors, using channel based interpolation. """ assert(len(c1) == len(c2)) new_color = [] for i in range(len(c1)): new_color.append(int(interpolate(c1[i], c2[i], factor))) return new_color
python
def interpolate_color(c1, c2, factor: float) -> list: """ Linear interpolate two 3-channel colors, using channel based interpolation. """ assert(len(c1) == len(c2)) new_color = [] for i in range(len(c1)): new_color.append(int(interpolate(c1[i], c2[i], factor))) return new_color
[ "def", "interpolate_color", "(", "c1", ",", "c2", ",", "factor", ":", "float", ")", "->", "list", ":", "assert", "(", "len", "(", "c1", ")", "==", "len", "(", "c2", ")", ")", "new_color", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(...
Linear interpolate two 3-channel colors, using channel based interpolation.
[ "Linear", "interpolate", "two", "3", "-", "channel", "colors", "using", "channel", "based", "interpolation", "." ]
train
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/core.py#L11-L18
krinj/k-util
k_util/core.py
interpolate
def interpolate(f1: float, f2: float, factor: float) -> float: """ Linearly interpolate between two float values. """ return f1 + (f2 - f1) * factor
python
def interpolate(f1: float, f2: float, factor: float) -> float: """ Linearly interpolate between two float values. """ return f1 + (f2 - f1) * factor
[ "def", "interpolate", "(", "f1", ":", "float", ",", "f2", ":", "float", ",", "factor", ":", "float", ")", "->", "float", ":", "return", "f1", "+", "(", "f2", "-", "f1", ")", "*", "factor" ]
Linearly interpolate between two float values.
[ "Linearly", "interpolate", "between", "two", "float", "values", "." ]
train
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/core.py#L21-L23
krinj/k-util
k_util/core.py
filter_value
def filter_value(old: float, new: float, factor: float) -> float: """ Linearly interpolate between two float values. """ r_factor: float = 1 - factor return old * r_factor + new * factor
python
def filter_value(old: float, new: float, factor: float) -> float: """ Linearly interpolate between two float values. """ r_factor: float = 1 - factor return old * r_factor + new * factor
[ "def", "filter_value", "(", "old", ":", "float", ",", "new", ":", "float", ",", "factor", ":", "float", ")", "->", "float", ":", "r_factor", ":", "float", "=", "1", "-", "factor", "return", "old", "*", "r_factor", "+", "new", "*", "factor" ]
Linearly interpolate between two float values.
[ "Linearly", "interpolate", "between", "two", "float", "values", "." ]
train
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/core.py#L26-L29
JNRowe/jnrbase
jnrbase/human_time.py
human_timestamp
def human_timestamp(__timestamp: datetime.datetime) -> str: """Format a relative time. Args: __timestamp: Event to generate relative timestamp against Returns: Human readable date and time offset """ numstr = '. a two three four five six seven eight nine ten'.split() matches = ...
python
def human_timestamp(__timestamp: datetime.datetime) -> str: """Format a relative time. Args: __timestamp: Event to generate relative timestamp against Returns: Human readable date and time offset """ numstr = '. a two three four five six seven eight nine ten'.split() matches = ...
[ "def", "human_timestamp", "(", "__timestamp", ":", "datetime", ".", "datetime", ")", "->", "str", ":", "numstr", "=", "'. a two three four five six seven eight nine ten'", ".", "split", "(", ")", "matches", "=", "[", "60", "*", "60", "*", "24", "*", "365", "...
Format a relative time. Args: __timestamp: Event to generate relative timestamp against Returns: Human readable date and time offset
[ "Format", "a", "relative", "time", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/human_time.py#L25-L71