repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.rnd_date | def rnd_date(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 date.today())
:return: a datetime.date object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的日期。
"""
if isinstance(start, string_types):
start = self.str2date(start)
if isinstance(end, string_types):
end = self.str2date(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return date.fromordinal(
random.randint(start.toordinal(), end.toordinal())) | python | def rnd_date(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 date.today())
:return: a datetime.date object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的日期。
"""
if isinstance(start, string_types):
start = self.str2date(start)
if isinstance(end, string_types):
end = self.str2date(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return date.fromordinal(
random.randint(start.toordinal(), end.toordinal())) | [
"def",
"rnd_date",
"(",
"self",
",",
"start",
"=",
"date",
"(",
"1970",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"date",
".",
"today",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"start",
",",
"string_types",
")",
":",
"start",
"=",
"self",
"... | 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
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 | [
"Generate",
"a",
"random",
"date",
"between",
"start",
"to",
"end",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L529-L549 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.rnd_date_array | def rnd_date_array(self, size, start=date(1970, 1, 1), end=date.today()):
"""Array or Matrix of random date generator.
"""
if isinstance(start, string_types):
start = self.str2date(start)
if isinstance(end, string_types):
end = self.str2date(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.randn(size, self._rnd_date, start, end) | python | def rnd_date_array(self, size, start=date(1970, 1, 1), end=date.today()):
"""Array or Matrix of random date generator.
"""
if isinstance(start, string_types):
start = self.str2date(start)
if isinstance(end, string_types):
end = self.str2date(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.randn(size, self._rnd_date, start, end) | [
"def",
"rnd_date_array",
"(",
"self",
",",
"size",
",",
"start",
"=",
"date",
"(",
"1970",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"date",
".",
"today",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"start",
",",
"string_types",
")",
":",
"start... | Array or Matrix of random date generator. | [
"Array",
"or",
"Matrix",
"of",
"random",
"date",
"generator",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L551-L561 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex._rnd_datetime | def _rnd_datetime(self, start, end):
"""Internal random datetime generator.
"""
return self.from_utctimestamp(
random.randint(
int(self.to_utctimestamp(start)),
int(self.to_utctimestamp(end)),
)
) | python | def _rnd_datetime(self, start, end):
"""Internal random datetime generator.
"""
return self.from_utctimestamp(
random.randint(
int(self.to_utctimestamp(start)),
int(self.to_utctimestamp(end)),
)
) | [
"def",
"_rnd_datetime",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"return",
"self",
".",
"from_utctimestamp",
"(",
"random",
".",
"randint",
"(",
"int",
"(",
"self",
".",
"to_utctimestamp",
"(",
"start",
")",
")",
",",
"int",
"(",
"self",
".",
... | Internal random datetime generator. | [
"Internal",
"random",
"datetime",
"generator",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L563-L571 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.rnd_datetime | def rnd_datetime(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 datetime.datetime, (default datetime.now())
:return: a datetime.datetime object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的时间。
"""
if isinstance(start, string_types):
start = self.str2datetime(start)
if isinstance(end, str):
end = self.str2datetime(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.from_utctimestamp(
random.randint(
int(self.to_utctimestamp(start)),
int(self.to_utctimestamp(end)),
)
) | python | def rnd_datetime(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 datetime.datetime, (default datetime.now())
:return: a datetime.datetime object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的时间。
"""
if isinstance(start, string_types):
start = self.str2datetime(start)
if isinstance(end, str):
end = self.str2datetime(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.from_utctimestamp(
random.randint(
int(self.to_utctimestamp(start)),
int(self.to_utctimestamp(end)),
)
) | [
"def",
"rnd_datetime",
"(",
"self",
",",
"start",
"=",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"datetime",
".",
"now",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"start",
",",
"string_types",
")",
":",
"start",
"=",
"... | 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
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 | [
"Generate",
"a",
"random",
"datetime",
"between",
"start",
"to",
"end",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L573-L597 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.rnd_datetime_array | def rnd_datetime_array(self,
size, start=datetime(1970, 1, 1), end=datetime.now()):
"""Array or Matrix of random datetime generator.
"""
if isinstance(start, string_types):
start = self.str2datetime(start)
if isinstance(end, str):
end = self.str2datetime(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.randn(size, self._rnd_datetime, start, end) | python | def rnd_datetime_array(self,
size, start=datetime(1970, 1, 1), end=datetime.now()):
"""Array or Matrix of random datetime generator.
"""
if isinstance(start, string_types):
start = self.str2datetime(start)
if isinstance(end, str):
end = self.str2datetime(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.randn(size, self._rnd_datetime, start, end) | [
"def",
"rnd_datetime_array",
"(",
"self",
",",
"size",
",",
"start",
"=",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"datetime",
".",
"now",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"start",
",",
"string_types",
")",
":"... | Array or Matrix of random datetime generator. | [
"Array",
"or",
"Matrix",
"of",
"random",
"datetime",
"generator",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L599-L610 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.add_seconds | def add_seconds(self, datetimestr, n):
"""Returns a time that n seconds after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of seconds, value can be negative
**中文文档**
返回给定日期N秒之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=n) | python | def add_seconds(self, datetimestr, n):
"""Returns a time that n seconds after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of seconds, value can be negative
**中文文档**
返回给定日期N秒之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=n) | [
"def",
"add_seconds",
"(",
"self",
",",
"datetimestr",
",",
"n",
")",
":",
"a_datetime",
"=",
"self",
".",
"parse_datetime",
"(",
"datetimestr",
")",
"return",
"a_datetime",
"+",
"timedelta",
"(",
"seconds",
"=",
"n",
")"
] | Returns a time that n seconds after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of seconds, value can be negative
**中文文档**
返回给定日期N秒之后的时间。 | [
"Returns",
"a",
"time",
"that",
"n",
"seconds",
"after",
"a",
"time",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L613-L624 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.add_minutes | def add_minutes(self, datetimestr, n):
"""Returns a time that n minutes after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of minutes, value can be negative
**中文文档**
返回给定日期N分钟之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=60 * n) | python | def add_minutes(self, datetimestr, n):
"""Returns a time that n minutes after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of minutes, value can be negative
**中文文档**
返回给定日期N分钟之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=60 * n) | [
"def",
"add_minutes",
"(",
"self",
",",
"datetimestr",
",",
"n",
")",
":",
"a_datetime",
"=",
"self",
".",
"parse_datetime",
"(",
"datetimestr",
")",
"return",
"a_datetime",
"+",
"timedelta",
"(",
"seconds",
"=",
"60",
"*",
"n",
")"
] | Returns a time that n minutes after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of minutes, value can be negative
**中文文档**
返回给定日期N分钟之后的时间。 | [
"Returns",
"a",
"time",
"that",
"n",
"minutes",
"after",
"a",
"time",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L626-L637 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.add_hours | def add_hours(self, datetimestr, n):
"""Returns a time that n hours after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of hours, value can be negative
**中文文档**
返回给定日期N小时之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=3600 * n) | python | def add_hours(self, datetimestr, n):
"""Returns a time that n hours after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of hours, value can be negative
**中文文档**
返回给定日期N小时之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=3600 * n) | [
"def",
"add_hours",
"(",
"self",
",",
"datetimestr",
",",
"n",
")",
":",
"a_datetime",
"=",
"self",
".",
"parse_datetime",
"(",
"datetimestr",
")",
"return",
"a_datetime",
"+",
"timedelta",
"(",
"seconds",
"=",
"3600",
"*",
"n",
")"
] | Returns a time that n hours after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of hours, value can be negative
**中文文档**
返回给定日期N小时之后的时间。 | [
"Returns",
"a",
"time",
"that",
"n",
"hours",
"after",
"a",
"time",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L639-L650 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.add_weeks | def add_weeks(self, datetimestr, n, return_date=False):
"""Returns a time that n weeks after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of weeks, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N周之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
a_datetime += timedelta(days=7 * n)
if return_date:
return a_datetime.date()
else:
return a_datetime | python | def add_weeks(self, datetimestr, n, return_date=False):
"""Returns a time that n weeks after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of weeks, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N周之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
a_datetime += timedelta(days=7 * n)
if return_date:
return a_datetime.date()
else:
return a_datetime | [
"def",
"add_weeks",
"(",
"self",
",",
"datetimestr",
",",
"n",
",",
"return_date",
"=",
"False",
")",
":",
"a_datetime",
"=",
"self",
".",
"parse_datetime",
"(",
"datetimestr",
")",
"a_datetime",
"+=",
"timedelta",
"(",
"days",
"=",
"7",
"*",
"n",
")",
... | Returns a time that n weeks after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of weeks, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N周之后的时间。 | [
"Returns",
"a",
"time",
"that",
"n",
"weeks",
"after",
"a",
"time",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L670-L686 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.add_years | def add_years(self, datetimestr, n, return_date=False):
"""Returns a time that n years after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of years, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N年之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
try:
a_datetime = datetime(
a_datetime.year + n, a_datetime.month, a_datetime.day,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
except:
a_datetime = datetime(
a_datetime.year + n, 2, 28,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
if return_date:
return a_datetime.date()
else:
return a_datetime | python | def add_years(self, datetimestr, n, return_date=False):
"""Returns a time that n years after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of years, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N年之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
try:
a_datetime = datetime(
a_datetime.year + n, a_datetime.month, a_datetime.day,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
except:
a_datetime = datetime(
a_datetime.year + n, 2, 28,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
if return_date:
return a_datetime.date()
else:
return a_datetime | [
"def",
"add_years",
"(",
"self",
",",
"datetimestr",
",",
"n",
",",
"return_date",
"=",
"False",
")",
":",
"a_datetime",
"=",
"self",
".",
"parse_datetime",
"(",
"datetimestr",
")",
"try",
":",
"a_datetime",
"=",
"datetime",
"(",
"a_datetime",
".",
"year",... | Returns a time that n years after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of years, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N年之后的时间。 | [
"Returns",
"a",
"time",
"that",
"n",
"years",
"after",
"a",
"time",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L725-L752 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.round_to | def round_to(self, dt, hour, minute, second, mode="floor"):
"""Round the given datetime to specified hour, minute and second.
:param mode: 'floor' or 'ceiling'
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
"""
mode = mode.lower()
new_dt = datetime(dt.year, dt.month, dt.day, hour, minute, second)
if mode == "floor":
if new_dt <= dt:
return new_dt
else:
return rolex.add_days(new_dt, -1)
elif mode == "ceiling":
if new_dt >= dt:
return new_dt
else:
return rolex.add_days(new_dt, 1)
else:
raise ValueError("'mode' has to be 'floor' or 'ceiling'!") | python | def round_to(self, dt, hour, minute, second, mode="floor"):
"""Round the given datetime to specified hour, minute and second.
:param mode: 'floor' or 'ceiling'
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
"""
mode = mode.lower()
new_dt = datetime(dt.year, dt.month, dt.day, hour, minute, second)
if mode == "floor":
if new_dt <= dt:
return new_dt
else:
return rolex.add_days(new_dt, -1)
elif mode == "ceiling":
if new_dt >= dt:
return new_dt
else:
return rolex.add_days(new_dt, 1)
else:
raise ValueError("'mode' has to be 'floor' or 'ceiling'!") | [
"def",
"round_to",
"(",
"self",
",",
"dt",
",",
"hour",
",",
"minute",
",",
"second",
",",
"mode",
"=",
"\"floor\"",
")",
":",
"mode",
"=",
"mode",
".",
"lower",
"(",
")",
"new_dt",
"=",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month"... | Round the given datetime to specified hour, minute and second.
:param mode: 'floor' or 'ceiling'
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 | [
"Round",
"the",
"given",
"datetime",
"to",
"specified",
"hour",
"minute",
"and",
"second",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L754-L777 |
etcher-be/epab | epab/linters/_lint.py | lint | def lint(ctx: click.Context, amend: bool = False, stage: bool = False):
"""
Runs all linters
Args:
ctx: click context
amend: whether or not to commit results
stage: whether or not to stage changes
"""
_lint(ctx, amend, stage) | python | def lint(ctx: click.Context, amend: bool = False, stage: bool = False):
"""
Runs all linters
Args:
ctx: click context
amend: whether or not to commit results
stage: whether or not to stage changes
"""
_lint(ctx, amend, stage) | [
"def",
"lint",
"(",
"ctx",
":",
"click",
".",
"Context",
",",
"amend",
":",
"bool",
"=",
"False",
",",
"stage",
":",
"bool",
"=",
"False",
")",
":",
"_lint",
"(",
"ctx",
",",
"amend",
",",
"stage",
")"
] | Runs all linters
Args:
ctx: click context
amend: whether or not to commit results
stage: whether or not to stage changes | [
"Runs",
"all",
"linters"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/linters/_lint.py#L44-L53 |
cohorte/cohorte-herald | python/herald/core.py | _WaitingPost.callback | def callback(self, herald_svc, message):
"""
Tries to call the callback of the post message.
Avoids errors to go outside this method.
:param herald_svc: Herald service instance
:param message: Received answer message
"""
if self.__callback is not None:
try:
# pylint: disable=W0703
self.__callback(herald_svc, message)
except Exception as ex:
_logger.exception("Error calling callback: %s", ex) | python | def callback(self, herald_svc, message):
"""
Tries to call the callback of the post message.
Avoids errors to go outside this method.
:param herald_svc: Herald service instance
:param message: Received answer message
"""
if self.__callback is not None:
try:
# pylint: disable=W0703
self.__callback(herald_svc, message)
except Exception as ex:
_logger.exception("Error calling callback: %s", ex) | [
"def",
"callback",
"(",
"self",
",",
"herald_svc",
",",
"message",
")",
":",
"if",
"self",
".",
"__callback",
"is",
"not",
"None",
":",
"try",
":",
"# pylint: disable=W0703",
"self",
".",
"__callback",
"(",
"herald_svc",
",",
"message",
")",
"except",
"Exc... | Tries to call the callback of the post message.
Avoids errors to go outside this method.
:param herald_svc: Herald service instance
:param message: Received answer message | [
"Tries",
"to",
"call",
"the",
"callback",
"of",
"the",
"post",
"message",
".",
"Avoids",
"errors",
"to",
"go",
"outside",
"this",
"method",
"."
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/core.py#L153-L166 |
cohorte/cohorte-herald | python/herald/core.py | _WaitingPost.errback | def errback(self, herald_svc, exception):
"""
Tries to call the error callback of the post message.
Avoids errors to go outside this method.
:param herald_svc: Herald service instance
:param exception: An exception describing/caused by the error
"""
if self.__errback is not None:
try:
# pylint: disable=W0703
self.__errback(herald_svc, exception)
except Exception as ex:
_logger.exception("Error calling errback: %s", ex) | python | def errback(self, herald_svc, exception):
"""
Tries to call the error callback of the post message.
Avoids errors to go outside this method.
:param herald_svc: Herald service instance
:param exception: An exception describing/caused by the error
"""
if self.__errback is not None:
try:
# pylint: disable=W0703
self.__errback(herald_svc, exception)
except Exception as ex:
_logger.exception("Error calling errback: %s", ex) | [
"def",
"errback",
"(",
"self",
",",
"herald_svc",
",",
"exception",
")",
":",
"if",
"self",
".",
"__errback",
"is",
"not",
"None",
":",
"try",
":",
"# pylint: disable=W0703",
"self",
".",
"__errback",
"(",
"herald_svc",
",",
"exception",
")",
"except",
"Ex... | Tries to call the error callback of the post message.
Avoids errors to go outside this method.
:param herald_svc: Herald service instance
:param exception: An exception describing/caused by the error | [
"Tries",
"to",
"call",
"the",
"error",
"callback",
"of",
"the",
"post",
"message",
".",
"Avoids",
"errors",
"to",
"go",
"outside",
"this",
"method",
"."
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/core.py#L168-L181 |
GustavePate/distarkcli | distarkcli/utils/zhelpers.py | socket_set_hwm | def socket_set_hwm(socket, hwm=-1):
"""libzmq 2/3 compatible sethwm"""
try:
socket.sndhwm = socket.rcvhwm = hwm
except AttributeError:
socket.hwm = hwm | python | def socket_set_hwm(socket, hwm=-1):
"""libzmq 2/3 compatible sethwm"""
try:
socket.sndhwm = socket.rcvhwm = hwm
except AttributeError:
socket.hwm = hwm | [
"def",
"socket_set_hwm",
"(",
"socket",
",",
"hwm",
"=",
"-",
"1",
")",
":",
"try",
":",
"socket",
".",
"sndhwm",
"=",
"socket",
".",
"rcvhwm",
"=",
"hwm",
"except",
"AttributeError",
":",
"socket",
".",
"hwm",
"=",
"hwm"
] | libzmq 2/3 compatible sethwm | [
"libzmq",
"2",
"/",
"3",
"compatible",
"sethwm"
] | train | https://github.com/GustavePate/distarkcli/blob/44b0e637e94ebb2687a1b7e2f6c5d0658d775238/distarkcli/utils/zhelpers.py#L48-L53 |
GustavePate/distarkcli | distarkcli/utils/zhelpers.py | zpipe | def zpipe(ctx):
"""build inproc pipe for talking to threads
mimic pipe used in czmq zthread_fork.
Returns a pair of PAIRs connected via inproc
"""
a = ctx.socket(zmq.PAIR)
a.linger = 0
b = ctx.socket(zmq.PAIR)
b.linger = 0
socket_set_hwm(a, 1)
socket_set_hwm(b, 1)
iface = "inproc://%s" % binascii.hexlify(os.urandom(8))
a.bind(iface)
b.connect(iface)
return a, b | python | def zpipe(ctx):
"""build inproc pipe for talking to threads
mimic pipe used in czmq zthread_fork.
Returns a pair of PAIRs connected via inproc
"""
a = ctx.socket(zmq.PAIR)
a.linger = 0
b = ctx.socket(zmq.PAIR)
b.linger = 0
socket_set_hwm(a, 1)
socket_set_hwm(b, 1)
iface = "inproc://%s" % binascii.hexlify(os.urandom(8))
a.bind(iface)
b.connect(iface)
return a, b | [
"def",
"zpipe",
"(",
"ctx",
")",
":",
"a",
"=",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PAIR",
")",
"a",
".",
"linger",
"=",
"0",
"b",
"=",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PAIR",
")",
"b",
".",
"linger",
"=",
"0",
"socket_set_hwm",
"(... | build inproc pipe for talking to threads
mimic pipe used in czmq zthread_fork.
Returns a pair of PAIRs connected via inproc | [
"build",
"inproc",
"pipe",
"for",
"talking",
"to",
"threads"
] | train | https://github.com/GustavePate/distarkcli/blob/44b0e637e94ebb2687a1b7e2f6c5d0658d775238/distarkcli/utils/zhelpers.py#L56-L72 |
Datary/scrapbag | scrapbag/geo/__init__.py | get_country | def get_country(similar=False, **kwargs):
"""
Get a country for pycountry
"""
result_country = None
try:
if similar:
for country in countries:
if kwargs.get('name', '') in country.name:
result_country = country
break
else:
result_country = countries.get(**kwargs)
except Exception as ex:
msg = ('Country not found in pycountry with params introduced'
' - {}'.format(ex))
logger.error(msg, params=kwargs)
return result_country | python | def get_country(similar=False, **kwargs):
"""
Get a country for pycountry
"""
result_country = None
try:
if similar:
for country in countries:
if kwargs.get('name', '') in country.name:
result_country = country
break
else:
result_country = countries.get(**kwargs)
except Exception as ex:
msg = ('Country not found in pycountry with params introduced'
' - {}'.format(ex))
logger.error(msg, params=kwargs)
return result_country | [
"def",
"get_country",
"(",
"similar",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"result_country",
"=",
"None",
"try",
":",
"if",
"similar",
":",
"for",
"country",
"in",
"countries",
":",
"if",
"kwargs",
".",
"get",
"(",
"'name'",
",",
"''",
")... | Get a country for pycountry | [
"Get",
"a",
"country",
"for",
"pycountry"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/__init__.py#L14-L32 |
Datary/scrapbag | scrapbag/geo/__init__.py | get_location | def get_location(address=""):
"""
Retrieve location coordinates from an address introduced.
"""
coordinates = None
try:
geolocator = Nominatim()
location = geolocator.geocode(address)
coordinates = (location.latitude, location.longitude)
except Exception as ex:
logger.error('Fail get location - {}'.format(ex))
return coordinates | python | def get_location(address=""):
"""
Retrieve location coordinates from an address introduced.
"""
coordinates = None
try:
geolocator = Nominatim()
location = geolocator.geocode(address)
coordinates = (location.latitude, location.longitude)
except Exception as ex:
logger.error('Fail get location - {}'.format(ex))
return coordinates | [
"def",
"get_location",
"(",
"address",
"=",
"\"\"",
")",
":",
"coordinates",
"=",
"None",
"try",
":",
"geolocator",
"=",
"Nominatim",
"(",
")",
"location",
"=",
"geolocator",
".",
"geocode",
"(",
"address",
")",
"coordinates",
"=",
"(",
"location",
".",
... | Retrieve location coordinates from an address introduced. | [
"Retrieve",
"location",
"coordinates",
"from",
"an",
"address",
"introduced",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/__init__.py#L35-L46 |
Datary/scrapbag | scrapbag/geo/__init__.py | get_address | def get_address(coords=None, **kwargs):
"""
Retrieve addres from a location in coords format introduced.
"""
address = None
try:
if (not coords) and \
('latitude' in kwargs and 'longitude' in kwargs) or \
('location' in kwargs):
coords = kwargs.get(
'location', (kwargs.get('latitude'), kwargs.get('longitude')))
# transform coords
if isinstance(coords, (list, tuple)) and len(coords) == 2:
coords = "{}, {}".join(map(str, coords))
geolocator = Nominatim()
location = geolocator.reverse(coords)
address = location.address
except Exception as ex:
logger.error('Fail get reverse address - {}'.format(ex))
return address | python | def get_address(coords=None, **kwargs):
"""
Retrieve addres from a location in coords format introduced.
"""
address = None
try:
if (not coords) and \
('latitude' in kwargs and 'longitude' in kwargs) or \
('location' in kwargs):
coords = kwargs.get(
'location', (kwargs.get('latitude'), kwargs.get('longitude')))
# transform coords
if isinstance(coords, (list, tuple)) and len(coords) == 2:
coords = "{}, {}".join(map(str, coords))
geolocator = Nominatim()
location = geolocator.reverse(coords)
address = location.address
except Exception as ex:
logger.error('Fail get reverse address - {}'.format(ex))
return address | [
"def",
"get_address",
"(",
"coords",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"address",
"=",
"None",
"try",
":",
"if",
"(",
"not",
"coords",
")",
"and",
"(",
"'latitude'",
"in",
"kwargs",
"and",
"'longitude'",
"in",
"kwargs",
")",
"or",
"(",
... | Retrieve addres from a location in coords format introduced. | [
"Retrieve",
"addres",
"from",
"a",
"location",
"in",
"coords",
"format",
"introduced",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/__init__.py#L49-L71 |
clusterpoint/python-client-api | pycps/request.py | Request.set_documents | def set_documents(self, documents, fully_formed=False):
""" Wrap documents in the correct root tags, add id fields and convert them to xml strings.
Args:
documents -- If fully_formed is False (default), accepts dict where keys are document ids and values can be ether
xml string, etree.ElementTree or dict representation of an xml document (see dict_to_etree()).
If fully_formed is True, accepts list or single document where ids are integrated in document or
not needed and document has the right root tag.
Keyword args:
fully_formed -- If documents are fully formed (contains the right root tags and id fields) set to True
to avoid the owerhead of documets beeing parsed at all. If set to True only list of documents or
a single document can be pased as 'documents', not a dict of documents. Default is False.
"""
def add_id(document, id):
def make_id_tag(root, rel_path, max_depth):
if max_depth < 0:
raise ParameterError("document_id_xpath too deep!")
if not rel_path:
return root
else:
child = root.find(rel_path[0])
if child is None:
child = ET.Element(rel_path[0])
root.append(child)
return make_id_tag(child, rel_path[1:], max_depth - 1)
make_id_tag(document, doc_id_xpath, 10).text = str(id)
if fully_formed: # documents is a list or single document that contians root tags and id fields.
if not isinstance(documents, list):
documents = [documents]
else: # documents is dict with ids as keys and documents as values.
doc_root_tag = self.connection.document_root_xpath # Local scope is faster.
doc_id_xpath = self.connection.document_id_xpath.split('/')
# Convert to etrees.
documents = dict([(id, to_etree((document if document is not None else
query.term('', doc_root_tag)), doc_root_tag))
for id, document in documents.items()]) # TODO: possibly ineficient
# If root not the same as given xpath, make new root and append to it.
for id, document in documents.items():
if document.tag != doc_root_tag:
documents[id] = ET.Element(doc_root_tag)
documents[id].append(document) # documents is still the old reference
# Insert ids in documents and collapse to a list of documents.
for id, document in documents.items():
add_id(document, id)
documents = documents.values()
self._documents = map(to_raw_xml, documents) | python | def set_documents(self, documents, fully_formed=False):
""" Wrap documents in the correct root tags, add id fields and convert them to xml strings.
Args:
documents -- If fully_formed is False (default), accepts dict where keys are document ids and values can be ether
xml string, etree.ElementTree or dict representation of an xml document (see dict_to_etree()).
If fully_formed is True, accepts list or single document where ids are integrated in document or
not needed and document has the right root tag.
Keyword args:
fully_formed -- If documents are fully formed (contains the right root tags and id fields) set to True
to avoid the owerhead of documets beeing parsed at all. If set to True only list of documents or
a single document can be pased as 'documents', not a dict of documents. Default is False.
"""
def add_id(document, id):
def make_id_tag(root, rel_path, max_depth):
if max_depth < 0:
raise ParameterError("document_id_xpath too deep!")
if not rel_path:
return root
else:
child = root.find(rel_path[0])
if child is None:
child = ET.Element(rel_path[0])
root.append(child)
return make_id_tag(child, rel_path[1:], max_depth - 1)
make_id_tag(document, doc_id_xpath, 10).text = str(id)
if fully_formed: # documents is a list or single document that contians root tags and id fields.
if not isinstance(documents, list):
documents = [documents]
else: # documents is dict with ids as keys and documents as values.
doc_root_tag = self.connection.document_root_xpath # Local scope is faster.
doc_id_xpath = self.connection.document_id_xpath.split('/')
# Convert to etrees.
documents = dict([(id, to_etree((document if document is not None else
query.term('', doc_root_tag)), doc_root_tag))
for id, document in documents.items()]) # TODO: possibly ineficient
# If root not the same as given xpath, make new root and append to it.
for id, document in documents.items():
if document.tag != doc_root_tag:
documents[id] = ET.Element(doc_root_tag)
documents[id].append(document) # documents is still the old reference
# Insert ids in documents and collapse to a list of documents.
for id, document in documents.items():
add_id(document, id)
documents = documents.values()
self._documents = map(to_raw_xml, documents) | [
"def",
"set_documents",
"(",
"self",
",",
"documents",
",",
"fully_formed",
"=",
"False",
")",
":",
"def",
"add_id",
"(",
"document",
",",
"id",
")",
":",
"def",
"make_id_tag",
"(",
"root",
",",
"rel_path",
",",
"max_depth",
")",
":",
"if",
"max_depth",
... | Wrap documents in the correct root tags, add id fields and convert them to xml strings.
Args:
documents -- If fully_formed is False (default), accepts dict where keys are document ids and values can be ether
xml string, etree.ElementTree or dict representation of an xml document (see dict_to_etree()).
If fully_formed is True, accepts list or single document where ids are integrated in document or
not needed and document has the right root tag.
Keyword args:
fully_formed -- If documents are fully formed (contains the right root tags and id fields) set to True
to avoid the owerhead of documets beeing parsed at all. If set to True only list of documents or
a single document can be pased as 'documents', not a dict of documents. Default is False. | [
"Wrap",
"documents",
"in",
"the",
"correct",
"root",
"tags",
"add",
"id",
"fields",
"and",
"convert",
"them",
"to",
"xml",
"strings",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/request.py#L69-L116 |
clusterpoint/python-client-api | pycps/request.py | Request.set_doc_ids | def set_doc_ids(self, doc_ids):
""" Build xml documents from a list of document ids.
Args:
doc_ids -- A document id or a lost of those.
"""
if isinstance(doc_ids, list):
self.set_documents(dict.fromkeys(doc_ids))
else:
self.set_documents({doc_ids: None}) | python | def set_doc_ids(self, doc_ids):
""" Build xml documents from a list of document ids.
Args:
doc_ids -- A document id or a lost of those.
"""
if isinstance(doc_ids, list):
self.set_documents(dict.fromkeys(doc_ids))
else:
self.set_documents({doc_ids: None}) | [
"def",
"set_doc_ids",
"(",
"self",
",",
"doc_ids",
")",
":",
"if",
"isinstance",
"(",
"doc_ids",
",",
"list",
")",
":",
"self",
".",
"set_documents",
"(",
"dict",
".",
"fromkeys",
"(",
"doc_ids",
")",
")",
"else",
":",
"self",
".",
"set_documents",
"("... | Build xml documents from a list of document ids.
Args:
doc_ids -- A document id or a lost of those. | [
"Build",
"xml",
"documents",
"from",
"a",
"list",
"of",
"document",
"ids",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/request.py#L118-L127 |
clusterpoint/python-client-api | pycps/request.py | Request.add_property | def add_property(self, set_property, name, starting_value, tag_name=None):
""" Set properies of atributes stored in content using stored common fdel and fget and given fset.
Args:
set_property -- Function that sets given property.
name -- Name of the atribute this property must simulate. Used as key in content dict by default.
starting_value -- Starting value of given property.
Keyword args:
tag_name -- The tag name stored in conted dict as a key if different to name.
"""
def del_property(self, tag_name):
try:
del self._content[tag_name]
except KeyError:
pass
def get_property(self, tag_name):
try:
return self._content[tag_name]
except KeyError:
return None
tag_name = (name if tag_name is None else tag_name)
fget = lambda self: get_property(self, tag_name)
fdel = lambda self: del_property(self, tag_name)
fset = lambda self, value: set_property(value)
setattr(self.__class__, name, property(fget, fset, fdel))
set_property(starting_value) | python | def add_property(self, set_property, name, starting_value, tag_name=None):
""" Set properies of atributes stored in content using stored common fdel and fget and given fset.
Args:
set_property -- Function that sets given property.
name -- Name of the atribute this property must simulate. Used as key in content dict by default.
starting_value -- Starting value of given property.
Keyword args:
tag_name -- The tag name stored in conted dict as a key if different to name.
"""
def del_property(self, tag_name):
try:
del self._content[tag_name]
except KeyError:
pass
def get_property(self, tag_name):
try:
return self._content[tag_name]
except KeyError:
return None
tag_name = (name if tag_name is None else tag_name)
fget = lambda self: get_property(self, tag_name)
fdel = lambda self: del_property(self, tag_name)
fset = lambda self, value: set_property(value)
setattr(self.__class__, name, property(fget, fset, fdel))
set_property(starting_value) | [
"def",
"add_property",
"(",
"self",
",",
"set_property",
",",
"name",
",",
"starting_value",
",",
"tag_name",
"=",
"None",
")",
":",
"def",
"del_property",
"(",
"self",
",",
"tag_name",
")",
":",
"try",
":",
"del",
"self",
".",
"_content",
"[",
"tag_name... | Set properies of atributes stored in content using stored common fdel and fget and given fset.
Args:
set_property -- Function that sets given property.
name -- Name of the atribute this property must simulate. Used as key in content dict by default.
starting_value -- Starting value of given property.
Keyword args:
tag_name -- The tag name stored in conted dict as a key if different to name. | [
"Set",
"properies",
"of",
"atributes",
"stored",
"in",
"content",
"using",
"stored",
"common",
"fdel",
"and",
"fget",
"and",
"given",
"fset",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/request.py#L129-L157 |
clusterpoint/python-client-api | pycps/request.py | Request.set_query | def set_query(self, value):
""" Convert a dict form of query in a string of needed and store the query string.
Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values.
"""
if isinstance(value, basestring) or value is None:
self._content['query'] = value
elif hasattr(value, 'keys'):
self._content['query'] = query.terms_from_dict(value)
else:
raise TypeError("Query must be a string or dict. Got: " + type(value) + " insted!") | python | def set_query(self, value):
""" Convert a dict form of query in a string of needed and store the query string.
Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values.
"""
if isinstance(value, basestring) or value is None:
self._content['query'] = value
elif hasattr(value, 'keys'):
self._content['query'] = query.terms_from_dict(value)
else:
raise TypeError("Query must be a string or dict. Got: " + type(value) + " insted!") | [
"def",
"set_query",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"or",
"value",
"is",
"None",
":",
"self",
".",
"_content",
"[",
"'query'",
"]",
"=",
"value",
"elif",
"hasattr",
"(",
"value",
",",
"'k... | Convert a dict form of query in a string of needed and store the query string.
Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values. | [
"Convert",
"a",
"dict",
"form",
"of",
"query",
"in",
"a",
"string",
"of",
"needed",
"and",
"store",
"the",
"query",
"string",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/request.py#L176-L188 |
clusterpoint/python-client-api | pycps/request.py | Request.get_xml_request | def get_xml_request(self):
""" Make xml request string from stored request information.
Returns:
A properly formated XMl request string containing all set request fields and
wraped in connections envelope.
"""
def wrap_xml_content(xml_content):
""" Wrap XML content string in the correct CPS request envelope."""
fields = ['<?xml version="1.0" encoding="utf-8"?>\n',
'<cps:request xmlns:cps="www.clusterpoint.com">\n',
'<cps:storage>', self.connection._storage, '</cps:storage>\n']
if self.timestamp:
fields += [] # TODO: implement
if self.request_id:
fields += ['<cps:request_id>', str(self.request_id), '</cps:request_id>\n']
if self.connection.reply_charset:
fields += [] # TODO: implement
if self.connection.application:
fields += ['<cps:application>', self.connection.application, '</cps:application>\n']
fields += ['<cps:command>', self._command, '</cps:command>\n',
'<cps:user>', self.connection._user, '</cps:user>\n',
'<cps:password>', self.connection._password, '</cps:password>\n',
'<cps:account>', self.connection._account, '</cps:account>\n']
if self.timeout:
fields += ['<cps:timeout>', str(self.timeout), '</cps:timeout>\n']
if self.type:
fields += ['<cps:type>', self.type, '</cps:type>\n']
if xml_content:
fields += ['<cps:content>\n', xml_content, '\n</cps:content>\n']
else:
fields += '<cps:content/>\n'
fields += '</cps:request>\n'
# String concat from list faster than incremental concat.
xml_request = ''.join(fields)
return xml_request
xml_content = []
if self._documents:
xml_content += self._documents
for key, value in self._nested_content.items():
if value:
xml_content += ['<{0}>'.format(key)] +\
['<{0}>{1}</{0}>'.format(sub_key, sub_value) for sub_key, sub_value in value if sub_value] +\
['</{0}>'.format(key)]
for key, value in self._content.items():
if not isinstance(value, list):
value = [value]
xml_content += ['<{0}>{1}</{0}>'.format(key, item) for item in value if item]
xml_content = '\n'.join(xml_content)
return wrap_xml_content(xml_content) | python | def get_xml_request(self):
""" Make xml request string from stored request information.
Returns:
A properly formated XMl request string containing all set request fields and
wraped in connections envelope.
"""
def wrap_xml_content(xml_content):
""" Wrap XML content string in the correct CPS request envelope."""
fields = ['<?xml version="1.0" encoding="utf-8"?>\n',
'<cps:request xmlns:cps="www.clusterpoint.com">\n',
'<cps:storage>', self.connection._storage, '</cps:storage>\n']
if self.timestamp:
fields += [] # TODO: implement
if self.request_id:
fields += ['<cps:request_id>', str(self.request_id), '</cps:request_id>\n']
if self.connection.reply_charset:
fields += [] # TODO: implement
if self.connection.application:
fields += ['<cps:application>', self.connection.application, '</cps:application>\n']
fields += ['<cps:command>', self._command, '</cps:command>\n',
'<cps:user>', self.connection._user, '</cps:user>\n',
'<cps:password>', self.connection._password, '</cps:password>\n',
'<cps:account>', self.connection._account, '</cps:account>\n']
if self.timeout:
fields += ['<cps:timeout>', str(self.timeout), '</cps:timeout>\n']
if self.type:
fields += ['<cps:type>', self.type, '</cps:type>\n']
if xml_content:
fields += ['<cps:content>\n', xml_content, '\n</cps:content>\n']
else:
fields += '<cps:content/>\n'
fields += '</cps:request>\n'
# String concat from list faster than incremental concat.
xml_request = ''.join(fields)
return xml_request
xml_content = []
if self._documents:
xml_content += self._documents
for key, value in self._nested_content.items():
if value:
xml_content += ['<{0}>'.format(key)] +\
['<{0}>{1}</{0}>'.format(sub_key, sub_value) for sub_key, sub_value in value if sub_value] +\
['</{0}>'.format(key)]
for key, value in self._content.items():
if not isinstance(value, list):
value = [value]
xml_content += ['<{0}>{1}</{0}>'.format(key, item) for item in value if item]
xml_content = '\n'.join(xml_content)
return wrap_xml_content(xml_content) | [
"def",
"get_xml_request",
"(",
"self",
")",
":",
"def",
"wrap_xml_content",
"(",
"xml_content",
")",
":",
"\"\"\" Wrap XML content string in the correct CPS request envelope.\"\"\"",
"fields",
"=",
"[",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n'",
",",
"'<cps:request xmlns:... | Make xml request string from stored request information.
Returns:
A properly formated XMl request string containing all set request fields and
wraped in connections envelope. | [
"Make",
"xml",
"request",
"string",
"from",
"stored",
"request",
"information",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/request.py#L269-L319 |
clusterpoint/python-client-api | pycps/request.py | Request.send | def send(self):
""" Send an XML string version of content through the connection.
Returns:
Response object.
"""
xml_request = self.get_xml_request()
if(self.connection._debug == 1):
print(xml_request)
Debug.warn('-' * 25)
Debug.warn(self._command)
Debug.dump("doc: \n", self._documents)
Debug.dump("cont: \n", self._content)
Debug.dump("nest cont \n", self._nested_content)
Debug.dump("Request: \n", xml_request)
response = _handle_response(self.connection._send_request(xml_request),
self._command, self.connection.document_id_xpath)
# TODO: jāpabeidz debugs
# if(self.connection._debug == 1):
# # print(response)
# print(format(ET.tostring(response)))
return response | python | def send(self):
""" Send an XML string version of content through the connection.
Returns:
Response object.
"""
xml_request = self.get_xml_request()
if(self.connection._debug == 1):
print(xml_request)
Debug.warn('-' * 25)
Debug.warn(self._command)
Debug.dump("doc: \n", self._documents)
Debug.dump("cont: \n", self._content)
Debug.dump("nest cont \n", self._nested_content)
Debug.dump("Request: \n", xml_request)
response = _handle_response(self.connection._send_request(xml_request),
self._command, self.connection.document_id_xpath)
# TODO: jāpabeidz debugs
# if(self.connection._debug == 1):
# # print(response)
# print(format(ET.tostring(response)))
return response | [
"def",
"send",
"(",
"self",
")",
":",
"xml_request",
"=",
"self",
".",
"get_xml_request",
"(",
")",
"if",
"(",
"self",
".",
"connection",
".",
"_debug",
"==",
"1",
")",
":",
"print",
"(",
"xml_request",
")",
"Debug",
".",
"warn",
"(",
"'-'",
"*",
"... | Send an XML string version of content through the connection.
Returns:
Response object. | [
"Send",
"an",
"XML",
"string",
"version",
"of",
"content",
"through",
"the",
"connection",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/request.py#L321-L344 |
nakagami/minitds | minitds/minitds.py | _min_timezone_offset | def _min_timezone_offset():
"time zone offset (minutes)"
now = time.time()
return (datetime.datetime.fromtimestamp(now) - datetime.datetime.utcfromtimestamp(now)).seconds // 60 | python | def _min_timezone_offset():
"time zone offset (minutes)"
now = time.time()
return (datetime.datetime.fromtimestamp(now) - datetime.datetime.utcfromtimestamp(now)).seconds // 60 | [
"def",
"_min_timezone_offset",
"(",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"return",
"(",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"now",
")",
"-",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"now",
")",
")",
... | time zone offset (minutes) | [
"time",
"zone",
"offset",
"(",
"minutes",
")"
] | train | https://github.com/nakagami/minitds/blob/d885888207a22b1a77bedfb76c070539568b2847/minitds/minitds.py#L233-L236 |
nakagami/minitds | minitds/minitds.py | Connection.parse_transaction_id | def parse_transaction_id(self, data):
"return transaction_id"
if data[0] == TDS_ERROR_TOKEN:
raise self.parse_error('begin()', data)
t, data = _parse_byte(data)
assert t == TDS_ENVCHANGE_TOKEN
_, data = _parse_int(data, 2) # packet length
e, data = _parse_byte(data)
assert e == TDS_ENV_BEGINTRANS
ln, data = _parse_byte(data)
assert ln == 8 # transaction id length
return data[:ln], data[ln:] | python | def parse_transaction_id(self, data):
"return transaction_id"
if data[0] == TDS_ERROR_TOKEN:
raise self.parse_error('begin()', data)
t, data = _parse_byte(data)
assert t == TDS_ENVCHANGE_TOKEN
_, data = _parse_int(data, 2) # packet length
e, data = _parse_byte(data)
assert e == TDS_ENV_BEGINTRANS
ln, data = _parse_byte(data)
assert ln == 8 # transaction id length
return data[:ln], data[ln:] | [
"def",
"parse_transaction_id",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"[",
"0",
"]",
"==",
"TDS_ERROR_TOKEN",
":",
"raise",
"self",
".",
"parse_error",
"(",
"'begin()'",
",",
"data",
")",
"t",
",",
"data",
"=",
"_parse_byte",
"(",
"data",
")... | return transaction_id | [
"return",
"transaction_id"
] | train | https://github.com/nakagami/minitds/blob/d885888207a22b1a77bedfb76c070539568b2847/minitds/minitds.py#L1142-L1153 |
onyxfish/clan | clan/utils.py | format_duration | def format_duration(secs):
"""
Format a duration in seconds as minutes and seconds.
"""
secs = int(secs)
if abs(secs) > 60:
mins = abs(secs) / 60
secs = abs(secs) - (mins * 60)
return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs)
return '%is' % secs | python | def format_duration(secs):
"""
Format a duration in seconds as minutes and seconds.
"""
secs = int(secs)
if abs(secs) > 60:
mins = abs(secs) / 60
secs = abs(secs) - (mins * 60)
return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs)
return '%is' % secs | [
"def",
"format_duration",
"(",
"secs",
")",
":",
"secs",
"=",
"int",
"(",
"secs",
")",
"if",
"abs",
"(",
"secs",
")",
">",
"60",
":",
"mins",
"=",
"abs",
"(",
"secs",
")",
"/",
"60",
"secs",
"=",
"abs",
"(",
"secs",
")",
"-",
"(",
"mins",
"*"... | Format a duration in seconds as minutes and seconds. | [
"Format",
"a",
"duration",
"in",
"seconds",
"as",
"minutes",
"and",
"seconds",
"."
] | train | https://github.com/onyxfish/clan/blob/415ddd027ea81013f2d62d75aec6da70703df49c/clan/utils.py#L53-L65 |
ekatek/char-classify | chClassifier/base_classifier.py | ClassificationTrainer.learn | def learn(self, numEpochs, batchsize):
"""Train the classifier for a given number of epochs, with a given batchsize"""
for epoch in range(numEpochs):
print('epoch %d' % epoch)
indexes = np.random.permutation(self.trainsize)
for i in range(0, self.trainsize, batchsize):
x = Variable(self.x_train[indexes[i: i + batchsize]])
t = Variable(self.y_train[indexes[i: i + batchsize]])
self.optimizer.update(self.model, x, t) | python | def learn(self, numEpochs, batchsize):
"""Train the classifier for a given number of epochs, with a given batchsize"""
for epoch in range(numEpochs):
print('epoch %d' % epoch)
indexes = np.random.permutation(self.trainsize)
for i in range(0, self.trainsize, batchsize):
x = Variable(self.x_train[indexes[i: i + batchsize]])
t = Variable(self.y_train[indexes[i: i + batchsize]])
self.optimizer.update(self.model, x, t) | [
"def",
"learn",
"(",
"self",
",",
"numEpochs",
",",
"batchsize",
")",
":",
"for",
"epoch",
"in",
"range",
"(",
"numEpochs",
")",
":",
"print",
"(",
"'epoch %d'",
"%",
"epoch",
")",
"indexes",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"self",
... | Train the classifier for a given number of epochs, with a given batchsize | [
"Train",
"the",
"classifier",
"for",
"a",
"given",
"number",
"of",
"epochs",
"with",
"a",
"given",
"batchsize"
] | train | https://github.com/ekatek/char-classify/blob/35fcfeac32d7e939e98efb528fab4ca2a45c20c5/chClassifier/base_classifier.py#L62-L70 |
ekatek/char-classify | chClassifier/base_classifier.py | ClassificationTrainer.evaluate | def evaluate(self, batchsize):
"""Evaluate how well the classifier is doing. Return mean loss and mean accuracy"""
sum_loss, sum_accuracy = 0, 0
for i in range(0, self.testsize, batchsize):
x = Variable(self.x_test[i: i + batchsize])
y = Variable(self.y_test[i: i + batchsize])
loss = self.model(x, y)
sum_loss += loss.data * batchsize
sum_accuracy += self.model.accuracy.data * batchsize
return sum_loss / self.testsize, sum_accuracy / self.testsize | python | def evaluate(self, batchsize):
"""Evaluate how well the classifier is doing. Return mean loss and mean accuracy"""
sum_loss, sum_accuracy = 0, 0
for i in range(0, self.testsize, batchsize):
x = Variable(self.x_test[i: i + batchsize])
y = Variable(self.y_test[i: i + batchsize])
loss = self.model(x, y)
sum_loss += loss.data * batchsize
sum_accuracy += self.model.accuracy.data * batchsize
return sum_loss / self.testsize, sum_accuracy / self.testsize | [
"def",
"evaluate",
"(",
"self",
",",
"batchsize",
")",
":",
"sum_loss",
",",
"sum_accuracy",
"=",
"0",
",",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"testsize",
",",
"batchsize",
")",
":",
"x",
"=",
"Variable",
"(",
"self",
".",
... | Evaluate how well the classifier is doing. Return mean loss and mean accuracy | [
"Evaluate",
"how",
"well",
"the",
"classifier",
"is",
"doing",
".",
"Return",
"mean",
"loss",
"and",
"mean",
"accuracy"
] | train | https://github.com/ekatek/char-classify/blob/35fcfeac32d7e939e98efb528fab4ca2a45c20c5/chClassifier/base_classifier.py#L72-L81 |
ekatek/char-classify | chClassifier/base_classifier.py | ClassificationTrainer.save | def save(self, model_filename, optimizer_filename):
""" Save the state of the model & optimizer to disk """
serializers.save_hdf5(model_filename, self.model)
serializers.save_hdf5(optimizer_filename, self.optimizer) | python | def save(self, model_filename, optimizer_filename):
""" Save the state of the model & optimizer to disk """
serializers.save_hdf5(model_filename, self.model)
serializers.save_hdf5(optimizer_filename, self.optimizer) | [
"def",
"save",
"(",
"self",
",",
"model_filename",
",",
"optimizer_filename",
")",
":",
"serializers",
".",
"save_hdf5",
"(",
"model_filename",
",",
"self",
".",
"model",
")",
"serializers",
".",
"save_hdf5",
"(",
"optimizer_filename",
",",
"self",
".",
"optim... | Save the state of the model & optimizer to disk | [
"Save",
"the",
"state",
"of",
"the",
"model",
"&",
"optimizer",
"to",
"disk"
] | train | https://github.com/ekatek/char-classify/blob/35fcfeac32d7e939e98efb528fab4ca2a45c20c5/chClassifier/base_classifier.py#L84-L87 |
ekatek/char-classify | chClassifier/base_classifier.py | Classifier.classify | def classify(self, phrase_vector):
""" Run this over an input vector and see the result """
x = Variable(np.asarray([phrase_vector]))
return self.model.predictor(x).data[0] | python | def classify(self, phrase_vector):
""" Run this over an input vector and see the result """
x = Variable(np.asarray([phrase_vector]))
return self.model.predictor(x).data[0] | [
"def",
"classify",
"(",
"self",
",",
"phrase_vector",
")",
":",
"x",
"=",
"Variable",
"(",
"np",
".",
"asarray",
"(",
"[",
"phrase_vector",
"]",
")",
")",
"return",
"self",
".",
"model",
".",
"predictor",
"(",
"x",
")",
".",
"data",
"[",
"0",
"]"
] | Run this over an input vector and see the result | [
"Run",
"this",
"over",
"an",
"input",
"vector",
"and",
"see",
"the",
"result"
] | train | https://github.com/ekatek/char-classify/blob/35fcfeac32d7e939e98efb528fab4ca2a45c20c5/chClassifier/base_classifier.py#L104-L107 |
django-fluent/fluentcms-emailtemplates | fluentcms_emailtemplates/managers.py | EmailTemplateQuerySet.parent_site | def parent_site(self, site):
"""
Filter to the given site, only give content relevant for that site.
"""
# Avoid auto filter if site is already set.
self._parent_site = site
if settings.FLUENTCMS_EMAILTEMPLATES_ENABLE_CROSS_SITE:
# Allow content to be shared between all sites:
return self.filter(Q(parent_site=site) | Q(is_cross_site=True))
else:
return self.filter(parent_site=site) | python | def parent_site(self, site):
"""
Filter to the given site, only give content relevant for that site.
"""
# Avoid auto filter if site is already set.
self._parent_site = site
if settings.FLUENTCMS_EMAILTEMPLATES_ENABLE_CROSS_SITE:
# Allow content to be shared between all sites:
return self.filter(Q(parent_site=site) | Q(is_cross_site=True))
else:
return self.filter(parent_site=site) | [
"def",
"parent_site",
"(",
"self",
",",
"site",
")",
":",
"# Avoid auto filter if site is already set.",
"self",
".",
"_parent_site",
"=",
"site",
"if",
"settings",
".",
"FLUENTCMS_EMAILTEMPLATES_ENABLE_CROSS_SITE",
":",
"# Allow content to be shared between all sites:",
"ret... | Filter to the given site, only give content relevant for that site. | [
"Filter",
"to",
"the",
"given",
"site",
"only",
"give",
"content",
"relevant",
"for",
"that",
"site",
"."
] | train | https://github.com/django-fluent/fluentcms-emailtemplates/blob/29f032dab9f60d05db852d2a1adcbd16e18017d1/fluentcms_emailtemplates/managers.py#L21-L32 |
django-fluent/fluentcms-emailtemplates | fluentcms_emailtemplates/managers.py | EmailTemplateQuerySet._single_site | def _single_site(self):
"""
Make sure the queryset is filtered on a parent site, if that didn't happen already.
"""
if settings.FLUENTCMS_EMAILTEMPLATES_FILTER_SITE_ID and self._parent_site is None:
return self.parent_site(settings.SITE_ID)
else:
return self | python | def _single_site(self):
"""
Make sure the queryset is filtered on a parent site, if that didn't happen already.
"""
if settings.FLUENTCMS_EMAILTEMPLATES_FILTER_SITE_ID and self._parent_site is None:
return self.parent_site(settings.SITE_ID)
else:
return self | [
"def",
"_single_site",
"(",
"self",
")",
":",
"if",
"settings",
".",
"FLUENTCMS_EMAILTEMPLATES_FILTER_SITE_ID",
"and",
"self",
".",
"_parent_site",
"is",
"None",
":",
"return",
"self",
".",
"parent_site",
"(",
"settings",
".",
"SITE_ID",
")",
"else",
":",
"ret... | Make sure the queryset is filtered on a parent site, if that didn't happen already. | [
"Make",
"sure",
"the",
"queryset",
"is",
"filtered",
"on",
"a",
"parent",
"site",
"if",
"that",
"didn",
"t",
"happen",
"already",
"."
] | train | https://github.com/django-fluent/fluentcms-emailtemplates/blob/29f032dab9f60d05db852d2a1adcbd16e18017d1/fluentcms_emailtemplates/managers.py#L35-L42 |
Laufire/ec | ec/modules/helper_tasks.py | help | def help(route):
r"""Displays help for the given route.
Args:
route (str): A route that resolves a member.
"""
help_text = getRouteHelp(route.split('/') if route else [])
if help_text is None:
err('Can\'t help :(')
else:
print '\n%s' % help_text | python | def help(route):
r"""Displays help for the given route.
Args:
route (str): A route that resolves a member.
"""
help_text = getRouteHelp(route.split('/') if route else [])
if help_text is None:
err('Can\'t help :(')
else:
print '\n%s' % help_text | [
"def",
"help",
"(",
"route",
")",
":",
"help_text",
"=",
"getRouteHelp",
"(",
"route",
".",
"split",
"(",
"'/'",
")",
"if",
"route",
"else",
"[",
"]",
")",
"if",
"help_text",
"is",
"None",
":",
"err",
"(",
"'Can\\'t help :('",
")",
"else",
":",
"prin... | r"""Displays help for the given route.
Args:
route (str): A route that resolves a member. | [
"r",
"Displays",
"help",
"for",
"the",
"given",
"route",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/helper_tasks.py#L23-L35 |
duniter/duniter-python-api | duniterpy/key/base58.py | Base58Encoder.encode | def encode(data: Union[str, bytes]) -> str:
"""
Return Base58 string from data
:param data: Bytes or string data
"""
return ensure_str(base58.b58encode(ensure_bytes(data))) | python | def encode(data: Union[str, bytes]) -> str:
"""
Return Base58 string from data
:param data: Bytes or string data
"""
return ensure_str(base58.b58encode(ensure_bytes(data))) | [
"def",
"encode",
"(",
"data",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"str",
":",
"return",
"ensure_str",
"(",
"base58",
".",
"b58encode",
"(",
"ensure_bytes",
"(",
"data",
")",
")",
")"
] | Return Base58 string from data
:param data: Bytes or string data | [
"Return",
"Base58",
"string",
"from",
"data"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/base58.py#L10-L16 |
scivision/gridaurora | gridaurora/plots.py | plotOptMod | def plotOptMod(verNObg3gray, VERgray):
""" called from either readTranscar.py or hist-feasibility/plotsnew.py """
if VERgray is None and verNObg3gray is None:
return
fg = figure()
ax2 = fg.gca() # summed (as camera would see)
if VERgray is not None:
z = VERgray.alt_km
Ek = VERgray.energy_ev.values
# ax1.semilogx(VERgray, z, marker='',label='filt', color='b')
props = {'boxstyle': 'round', 'facecolor': 'wheat', 'alpha': 0.5}
fgs, axs = fg.subplots(6, 6, sharex=True, sharey='row')
axs = axs.ravel() # for convenient iteration
fgs.subplots_adjust(hspace=0, wspace=0)
fgs.suptitle('filtered VER/flux')
fgs.text(0.04, 0.5, 'Altitude [km]', va='center', rotation='vertical')
fgs.text(0.5, 0.04, 'Beam energy [eV]', ha='center')
for i, e in enumerate(Ek):
axs[i].semilogx(VERgray.loc[:, e], z)
axs[i].set_xlim((1e-3, 1e4))
# place a text box in upper left in axes coords
axs[i].text(0.95, 0.95, '{:0.0f}'.format(e)+'eV',
transform=axs[i].transAxes, fontsize=12,
va='top', ha='right', bbox=props)
for i in range(33, 36):
axs[i].axis('off')
ax2.semilogx(VERgray.sum(axis=1), z, label='filt', color='b')
# specific to energies
ax = figure().gca()
for e in Ek:
ax.semilogx(VERgray.loc[:, e], z, marker='', label='{:.0f} eV'.format(e))
ax.set_title('filtered VER/flux')
ax.set_xlabel('VER/flux')
ax.set_ylabel('altitude [km]')
ax.legend(loc='best', fontsize=8)
ax.set_xlim((1e-5, 1e5))
ax.grid(True)
if verNObg3gray is not None:
ax1 = figure().gca() # overview
z = verNObg3gray.alt_km
Ek = verNObg3gray.energy_ev.values
ax1.semilogx(verNObg3gray, z, marker='', label='unfilt', color='r')
ax2.semilogx(verNObg3gray.sum(axis=1), z, label='unfilt', color='r')
ax = figure().gca()
for e in Ek:
ax.semilogx(verNObg3gray.loc[:, e], z, marker='', label='{:.0f} eV'.format(e))
ax.set_title('UNfiltered VER/flux')
ax.set_xlabel('VER/flux')
ax.set_ylabel('altitude [km]')
ax.legend(loc='best', fontsize=8)
ax.set_xlim((1e-5, 1e5))
ax.grid(True)
ax1.set_title('VER/flux, one profile per beam')
ax1.set_xlabel('VER/flux')
ax1.set_ylabel('altitude [km]')
ax1.grid(True)
ax2.set_xlabel('VER/flux')
ax2.set_ylabel('altitude [km]')
ax2.set_title('VER/flux summed over all energy beams \n (as the camera would see)')
ax2.legend(loc='best')
ax2.grid(True) | python | def plotOptMod(verNObg3gray, VERgray):
""" called from either readTranscar.py or hist-feasibility/plotsnew.py """
if VERgray is None and verNObg3gray is None:
return
fg = figure()
ax2 = fg.gca() # summed (as camera would see)
if VERgray is not None:
z = VERgray.alt_km
Ek = VERgray.energy_ev.values
# ax1.semilogx(VERgray, z, marker='',label='filt', color='b')
props = {'boxstyle': 'round', 'facecolor': 'wheat', 'alpha': 0.5}
fgs, axs = fg.subplots(6, 6, sharex=True, sharey='row')
axs = axs.ravel() # for convenient iteration
fgs.subplots_adjust(hspace=0, wspace=0)
fgs.suptitle('filtered VER/flux')
fgs.text(0.04, 0.5, 'Altitude [km]', va='center', rotation='vertical')
fgs.text(0.5, 0.04, 'Beam energy [eV]', ha='center')
for i, e in enumerate(Ek):
axs[i].semilogx(VERgray.loc[:, e], z)
axs[i].set_xlim((1e-3, 1e4))
# place a text box in upper left in axes coords
axs[i].text(0.95, 0.95, '{:0.0f}'.format(e)+'eV',
transform=axs[i].transAxes, fontsize=12,
va='top', ha='right', bbox=props)
for i in range(33, 36):
axs[i].axis('off')
ax2.semilogx(VERgray.sum(axis=1), z, label='filt', color='b')
# specific to energies
ax = figure().gca()
for e in Ek:
ax.semilogx(VERgray.loc[:, e], z, marker='', label='{:.0f} eV'.format(e))
ax.set_title('filtered VER/flux')
ax.set_xlabel('VER/flux')
ax.set_ylabel('altitude [km]')
ax.legend(loc='best', fontsize=8)
ax.set_xlim((1e-5, 1e5))
ax.grid(True)
if verNObg3gray is not None:
ax1 = figure().gca() # overview
z = verNObg3gray.alt_km
Ek = verNObg3gray.energy_ev.values
ax1.semilogx(verNObg3gray, z, marker='', label='unfilt', color='r')
ax2.semilogx(verNObg3gray.sum(axis=1), z, label='unfilt', color='r')
ax = figure().gca()
for e in Ek:
ax.semilogx(verNObg3gray.loc[:, e], z, marker='', label='{:.0f} eV'.format(e))
ax.set_title('UNfiltered VER/flux')
ax.set_xlabel('VER/flux')
ax.set_ylabel('altitude [km]')
ax.legend(loc='best', fontsize=8)
ax.set_xlim((1e-5, 1e5))
ax.grid(True)
ax1.set_title('VER/flux, one profile per beam')
ax1.set_xlabel('VER/flux')
ax1.set_ylabel('altitude [km]')
ax1.grid(True)
ax2.set_xlabel('VER/flux')
ax2.set_ylabel('altitude [km]')
ax2.set_title('VER/flux summed over all energy beams \n (as the camera would see)')
ax2.legend(loc='best')
ax2.grid(True) | [
"def",
"plotOptMod",
"(",
"verNObg3gray",
",",
"VERgray",
")",
":",
"if",
"VERgray",
"is",
"None",
"and",
"verNObg3gray",
"is",
"None",
":",
"return",
"fg",
"=",
"figure",
"(",
")",
"ax2",
"=",
"fg",
".",
"gca",
"(",
")",
"# summed (as camera would see)",
... | called from either readTranscar.py or hist-feasibility/plotsnew.py | [
"called",
"from",
"either",
"readTranscar",
".",
"py",
"or",
"hist",
"-",
"feasibility",
"/",
"plotsnew",
".",
"py"
] | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/plots.py#L260-L331 |
timothydmorton/simpledist | simpledist/kde.py | deriv | def deriv(f,c,dx=0.0001):
"""
deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient.
"""
return (f(c+dx)-f(c-dx))/(2*dx) | python | def deriv(f,c,dx=0.0001):
"""
deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient.
"""
return (f(c+dx)-f(c-dx))/(2*dx) | [
"def",
"deriv",
"(",
"f",
",",
"c",
",",
"dx",
"=",
"0.0001",
")",
":",
"return",
"(",
"f",
"(",
"c",
"+",
"dx",
")",
"-",
"f",
"(",
"c",
"-",
"dx",
")",
")",
"/",
"(",
"2",
"*",
"dx",
")"
] | deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient. | [
"deriv",
"(",
"f",
"c",
"dx",
")",
"--",
">",
"float",
"Returns",
"f",
"(",
"x",
")",
"computed",
"as",
"a",
"symmetric",
"difference",
"quotient",
"."
] | train | https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/kde.py#L224-L230 |
timothydmorton/simpledist | simpledist/kde.py | newton | def newton(f,c,tol=0.0001,restrict=None):
"""
newton(f,c) --> float
Returns the x closest to c such that f(x) = 0
"""
#print(c)
if restrict:
lo,hi = restrict
if c < lo or c > hi:
print(c)
c = random*(hi-lo)+lo
if fuzzyequals(f(c),0,tol):
return c
else:
try:
return newton(f,c-f(c)/deriv(f,c,tol),tol,restrict)
except:
return None | python | def newton(f,c,tol=0.0001,restrict=None):
"""
newton(f,c) --> float
Returns the x closest to c such that f(x) = 0
"""
#print(c)
if restrict:
lo,hi = restrict
if c < lo or c > hi:
print(c)
c = random*(hi-lo)+lo
if fuzzyequals(f(c),0,tol):
return c
else:
try:
return newton(f,c-f(c)/deriv(f,c,tol),tol,restrict)
except:
return None | [
"def",
"newton",
"(",
"f",
",",
"c",
",",
"tol",
"=",
"0.0001",
",",
"restrict",
"=",
"None",
")",
":",
"#print(c)",
"if",
"restrict",
":",
"lo",
",",
"hi",
"=",
"restrict",
"if",
"c",
"<",
"lo",
"or",
"c",
">",
"hi",
":",
"print",
"(",
"c",
... | newton(f,c) --> float
Returns the x closest to c such that f(x) = 0 | [
"newton",
"(",
"f",
"c",
")",
"--",
">",
"float",
"Returns",
"the",
"x",
"closest",
"to",
"c",
"such",
"that",
"f",
"(",
"x",
")",
"=",
"0"
] | train | https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/kde.py#L235-L254 |
timothydmorton/simpledist | simpledist/kde.py | KDE.integrate_box | def integrate_box(self,low,high,forcequad=False,**kwargs):
"""Integrates over a box. Optionally force quad integration, even for non-adaptive.
If adaptive mode is not being used, this will just call the
`scipy.stats.gaussian_kde` method `integrate_box_1d`. Else,
by default, it will call `scipy.integrate.quad`. If the
`forcequad` flag is turned on, then that integration will be
used even if adaptive mode is off.
Parameters
----------
low : float
Lower limit of integration
high : float
Upper limit of integration
forcequad : bool
If `True`, then use the quad integration even if adaptive mode is off.
kwargs
Keyword arguments passed to `scipy.integrate.quad`.
"""
if not self.adaptive and not forcequad:
return self.gauss_kde.integrate_box_1d(low,high)*self.norm
return quad(self.evaluate,low,high,**kwargs)[0] | python | def integrate_box(self,low,high,forcequad=False,**kwargs):
"""Integrates over a box. Optionally force quad integration, even for non-adaptive.
If adaptive mode is not being used, this will just call the
`scipy.stats.gaussian_kde` method `integrate_box_1d`. Else,
by default, it will call `scipy.integrate.quad`. If the
`forcequad` flag is turned on, then that integration will be
used even if adaptive mode is off.
Parameters
----------
low : float
Lower limit of integration
high : float
Upper limit of integration
forcequad : bool
If `True`, then use the quad integration even if adaptive mode is off.
kwargs
Keyword arguments passed to `scipy.integrate.quad`.
"""
if not self.adaptive and not forcequad:
return self.gauss_kde.integrate_box_1d(low,high)*self.norm
return quad(self.evaluate,low,high,**kwargs)[0] | [
"def",
"integrate_box",
"(",
"self",
",",
"low",
",",
"high",
",",
"forcequad",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"adaptive",
"and",
"not",
"forcequad",
":",
"return",
"self",
".",
"gauss_kde",
".",
"integrate_b... | Integrates over a box. Optionally force quad integration, even for non-adaptive.
If adaptive mode is not being used, this will just call the
`scipy.stats.gaussian_kde` method `integrate_box_1d`. Else,
by default, it will call `scipy.integrate.quad`. If the
`forcequad` flag is turned on, then that integration will be
used even if adaptive mode is off.
Parameters
----------
low : float
Lower limit of integration
high : float
Upper limit of integration
forcequad : bool
If `True`, then use the quad integration even if adaptive mode is off.
kwargs
Keyword arguments passed to `scipy.integrate.quad`. | [
"Integrates",
"over",
"a",
"box",
".",
"Optionally",
"force",
"quad",
"integration",
"even",
"for",
"non",
"-",
"adaptive",
"."
] | train | https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/kde.py#L131-L156 |
solocompt/plugs-mail | plugs_mail/mail.py | PlugsMail.validate_context | def validate_context(self):
"""
Make sure there are no duplicate context objects
or we might end up with switched data
Converting the tuple to a set gets rid of the
eventual duplicate objects, comparing the length
of the original tuple and set tells us if we
have duplicates in the tuple or not
"""
if self.context and len(self.context) != len(set(self.context)):
LOGGER.error('Cannot have duplicated context objects')
raise Exception('Cannot have duplicated context objects.') | python | def validate_context(self):
"""
Make sure there are no duplicate context objects
or we might end up with switched data
Converting the tuple to a set gets rid of the
eventual duplicate objects, comparing the length
of the original tuple and set tells us if we
have duplicates in the tuple or not
"""
if self.context and len(self.context) != len(set(self.context)):
LOGGER.error('Cannot have duplicated context objects')
raise Exception('Cannot have duplicated context objects.') | [
"def",
"validate_context",
"(",
"self",
")",
":",
"if",
"self",
".",
"context",
"and",
"len",
"(",
"self",
".",
"context",
")",
"!=",
"len",
"(",
"set",
"(",
"self",
".",
"context",
")",
")",
":",
"LOGGER",
".",
"error",
"(",
"'Cannot have duplicated c... | Make sure there are no duplicate context objects
or we might end up with switched data
Converting the tuple to a set gets rid of the
eventual duplicate objects, comparing the length
of the original tuple and set tells us if we
have duplicates in the tuple or not | [
"Make",
"sure",
"there",
"are",
"no",
"duplicate",
"context",
"objects",
"or",
"we",
"might",
"end",
"up",
"with",
"switched",
"data"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L33-L45 |
solocompt/plugs-mail | plugs_mail/mail.py | PlugsMail.get_instance_of | def get_instance_of(self, model_cls):
"""
Search the data to find a instance
of a model specified in the template
"""
for obj in self.data.values():
if isinstance(obj, model_cls):
return obj
LOGGER.error('Context Not Found')
raise Exception('Context Not Found') | python | def get_instance_of(self, model_cls):
"""
Search the data to find a instance
of a model specified in the template
"""
for obj in self.data.values():
if isinstance(obj, model_cls):
return obj
LOGGER.error('Context Not Found')
raise Exception('Context Not Found') | [
"def",
"get_instance_of",
"(",
"self",
",",
"model_cls",
")",
":",
"for",
"obj",
"in",
"self",
".",
"data",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"model_cls",
")",
":",
"return",
"obj",
"LOGGER",
".",
"error",
"(",
"'Cont... | Search the data to find a instance
of a model specified in the template | [
"Search",
"the",
"data",
"to",
"find",
"a",
"instance",
"of",
"a",
"model",
"specified",
"in",
"the",
"template"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L47-L56 |
solocompt/plugs-mail | plugs_mail/mail.py | PlugsMail.get_context | def get_context(self):
"""
Create a dict with the context data
context is not required, but if it
is defined it should be a tuple
"""
if not self.context:
return
else:
assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.format(type(self.context))
for model in self.context:
model_cls = utils.get_model_class(model)
key = utils.camel_to_snake(model_cls.__name__)
self.context_data[key] = self.get_instance_of(model_cls) | python | def get_context(self):
"""
Create a dict with the context data
context is not required, but if it
is defined it should be a tuple
"""
if not self.context:
return
else:
assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.format(type(self.context))
for model in self.context:
model_cls = utils.get_model_class(model)
key = utils.camel_to_snake(model_cls.__name__)
self.context_data[key] = self.get_instance_of(model_cls) | [
"def",
"get_context",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"context",
":",
"return",
"else",
":",
"assert",
"isinstance",
"(",
"self",
".",
"context",
",",
"tuple",
")",
",",
"'Expected a Tuple not {0}'",
".",
"format",
"(",
"type",
"(",
"sel... | Create a dict with the context data
context is not required, but if it
is defined it should be a tuple | [
"Create",
"a",
"dict",
"with",
"the",
"context",
"data",
"context",
"is",
"not",
"required",
"but",
"if",
"it",
"is",
"defined",
"it",
"should",
"be",
"a",
"tuple"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L58-L71 |
solocompt/plugs-mail | plugs_mail/mail.py | PlugsMail.get_context_data | def get_context_data(self):
"""
Context Data is equal to context + extra_context
Merge the dicts context_data and extra_context and
update state
"""
self.get_context()
self.context_data.update(self.get_extra_context())
return self.context_data | python | def get_context_data(self):
"""
Context Data is equal to context + extra_context
Merge the dicts context_data and extra_context and
update state
"""
self.get_context()
self.context_data.update(self.get_extra_context())
return self.context_data | [
"def",
"get_context_data",
"(",
"self",
")",
":",
"self",
".",
"get_context",
"(",
")",
"self",
".",
"context_data",
".",
"update",
"(",
"self",
".",
"get_extra_context",
"(",
")",
")",
"return",
"self",
".",
"context_data"
] | Context Data is equal to context + extra_context
Merge the dicts context_data and extra_context and
update state | [
"Context",
"Data",
"is",
"equal",
"to",
"context",
"+",
"extra_context",
"Merge",
"the",
"dicts",
"context_data",
"and",
"extra_context",
"and",
"update",
"state"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L82-L90 |
solocompt/plugs-mail | plugs_mail/mail.py | PlugsMail.send | def send(self, to, language=None, **data):
"""
This is the method to be called
"""
self.data = data
self.get_context_data()
if app_settings['SEND_EMAILS']:
try:
if language:
mail.send(to, template=self.template, context=self.context_data, language=language)
else:
mail.send(to, template=self.template, context=self.context_data)
except EmailTemplate.DoesNotExist:
msg = 'Trying to use a non existent email template {0}'.format(self.template)
LOGGER.error('Trying to use a non existent email template {0}'.format(self.template)) | python | def send(self, to, language=None, **data):
"""
This is the method to be called
"""
self.data = data
self.get_context_data()
if app_settings['SEND_EMAILS']:
try:
if language:
mail.send(to, template=self.template, context=self.context_data, language=language)
else:
mail.send(to, template=self.template, context=self.context_data)
except EmailTemplate.DoesNotExist:
msg = 'Trying to use a non existent email template {0}'.format(self.template)
LOGGER.error('Trying to use a non existent email template {0}'.format(self.template)) | [
"def",
"send",
"(",
"self",
",",
"to",
",",
"language",
"=",
"None",
",",
"*",
"*",
"data",
")",
":",
"self",
".",
"data",
"=",
"data",
"self",
".",
"get_context_data",
"(",
")",
"if",
"app_settings",
"[",
"'SEND_EMAILS'",
"]",
":",
"try",
":",
"if... | This is the method to be called | [
"This",
"is",
"the",
"method",
"to",
"be",
"called"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L92-L106 |
mazi76erX2/mention-python | mention/mention/base.py | CreateAnAlertAPI.params | def params(self):
"""Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict
"""
params = {}
params["access_token"] = self.access_token
params["account_id"] = self.account_id
return params | python | def params(self):
"""Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict
"""
params = {}
params["access_token"] = self.access_token
params["account_id"] = self.account_id
return params | [
"def",
"params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"\"access_token\"",
"]",
"=",
"self",
".",
"access_token",
"params",
"[",
"\"account_id\"",
"]",
"=",
"self",
".",
"account_id",
"return",
"params"
] | Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict | [
"Parameters",
"used",
"in",
"the",
"url",
"of",
"the",
"API",
"call",
"and",
"for",
"authentication",
"."
] | train | https://github.com/mazi76erX2/mention-python/blob/5133f463faa4ef053365fbf15db0a75dbb00a4e5/mention/mention/base.py#L236-L245 |
mazi76erX2/mention-python | mention/mention/base.py | CreateAnAlertAPI.data | def data(self):
"""Parameters passed to the API containing the details to create a new
alert.
:return: parameters to create new alert.
:rtype: dict
"""
data = {}
data["name"] = self.name
data["query"] = self.queryd
data["languages"] = self.languages
data["countries"] = self.countries if self.countries else ""
data["sources"] = self.sources if self.sources else ""
data["blocked_sites"] = self.blocked_sites if self.blocked_sites else ""
data["noise_detection"] = self.noise_detection if self.noise_detection else ""
data["reviews_pages"] = self.reviews_pages if self.reviews_pages else ""
# Deletes parameter if it does not have a value
for key, value in list(data.items()):
if value == '':
del data[key]
data = json.dumps(data)
return data | python | def data(self):
"""Parameters passed to the API containing the details to create a new
alert.
:return: parameters to create new alert.
:rtype: dict
"""
data = {}
data["name"] = self.name
data["query"] = self.queryd
data["languages"] = self.languages
data["countries"] = self.countries if self.countries else ""
data["sources"] = self.sources if self.sources else ""
data["blocked_sites"] = self.blocked_sites if self.blocked_sites else ""
data["noise_detection"] = self.noise_detection if self.noise_detection else ""
data["reviews_pages"] = self.reviews_pages if self.reviews_pages else ""
# Deletes parameter if it does not have a value
for key, value in list(data.items()):
if value == '':
del data[key]
data = json.dumps(data)
return data | [
"def",
"data",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"\"name\"",
"]",
"=",
"self",
".",
"name",
"data",
"[",
"\"query\"",
"]",
"=",
"self",
".",
"queryd",
"data",
"[",
"\"languages\"",
"]",
"=",
"self",
".",
"languages",
"data"... | Parameters passed to the API containing the details to create a new
alert.
:return: parameters to create new alert.
:rtype: dict | [
"Parameters",
"passed",
"to",
"the",
"API",
"containing",
"the",
"details",
"to",
"create",
"a",
"new",
"alert",
"."
] | train | https://github.com/mazi76erX2/mention-python/blob/5133f463faa4ef053365fbf15db0a75dbb00a4e5/mention/mention/base.py#L248-L271 |
mazi76erX2/mention-python | mention/mention/base.py | FetchAllMentionsAPI.params | def params(self):
"""Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict
"""
params = {}
params["access_token"] = self.access_token
params["account_id"] = self.account_id
params["alert_id"] = self.alert_id
if self.since_id:
params["since_id"] = self.since_id
else:
params["before_date"] = self.before_date if self.before_date else ""
params["not_before_date"] = self.not_before_date if self.before_date else ""
params["cursor"] = self.cursor if self.cursor else ""
if self.unread:
params["unread"] = self.unread
else:
if (self.favorite) and (
(self.folder == "inbox") or (self.folder == "archive")):
params["favorite"] = self.favorite
params["folder"] = self.folder
else:
params["folder"] = self.folder if self.folder else ""
params["q"] = self.q if self.q else ""
params["tone"] = self.tone if self.tone else ""
if int(self.limit) > 1000:
params["limit"] = "1000"
elif int(self.limit) < 1:
params["limit"] = ""
else:
params["limit"] = self.limit
params["source"] = self.source if self.source else ""
params["countries"] = self.countries if self.countries else ""
params["include_children"] = self.include_children if self.include_children else ""
params["sort"] = self.sort if self.sort else ""
params["languages"] = self.languages if self.languages else ""
params["timezone"] = self.timezone if self.timezone else ""
# Deletes parameter if it does not have a value
for key, value in list(params.items()):
if value == '':
del params[key]
return params | python | def params(self):
"""Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict
"""
params = {}
params["access_token"] = self.access_token
params["account_id"] = self.account_id
params["alert_id"] = self.alert_id
if self.since_id:
params["since_id"] = self.since_id
else:
params["before_date"] = self.before_date if self.before_date else ""
params["not_before_date"] = self.not_before_date if self.before_date else ""
params["cursor"] = self.cursor if self.cursor else ""
if self.unread:
params["unread"] = self.unread
else:
if (self.favorite) and (
(self.folder == "inbox") or (self.folder == "archive")):
params["favorite"] = self.favorite
params["folder"] = self.folder
else:
params["folder"] = self.folder if self.folder else ""
params["q"] = self.q if self.q else ""
params["tone"] = self.tone if self.tone else ""
if int(self.limit) > 1000:
params["limit"] = "1000"
elif int(self.limit) < 1:
params["limit"] = ""
else:
params["limit"] = self.limit
params["source"] = self.source if self.source else ""
params["countries"] = self.countries if self.countries else ""
params["include_children"] = self.include_children if self.include_children else ""
params["sort"] = self.sort if self.sort else ""
params["languages"] = self.languages if self.languages else ""
params["timezone"] = self.timezone if self.timezone else ""
# Deletes parameter if it does not have a value
for key, value in list(params.items()):
if value == '':
del params[key]
return params | [
"def",
"params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"\"access_token\"",
"]",
"=",
"self",
".",
"access_token",
"params",
"[",
"\"account_id\"",
"]",
"=",
"self",
".",
"account_id",
"params",
"[",
"\"alert_id\"",
"]",
"=",
"sel... | Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict | [
"Parameters",
"used",
"in",
"the",
"url",
"of",
"the",
"API",
"call",
"and",
"for",
"authentication",
"."
] | train | https://github.com/mazi76erX2/mention-python/blob/5133f463faa4ef053365fbf15db0a75dbb00a4e5/mention/mention/base.py#L710-L760 |
mazi76erX2/mention-python | mention/mention/base.py | FetchMentionChildrenAPI.params | def params(self):
"""Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict
"""
params = {}
params["access_token"] = self.access_token
params["account_id"] = self.account_id
params["alert_id"] = self.alert_id
params["mention_id"] = self.mention_id
params["before_date"] = self.before_date if self.before_date else ""
if self.limit:
if int(self.limit) > 1000:
params["limit"] = "1000"
elif int(self.limit) < 1:
params["limit"] = ""
else:
params["limit"] = self.limit
return params | python | def params(self):
"""Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict
"""
params = {}
params["access_token"] = self.access_token
params["account_id"] = self.account_id
params["alert_id"] = self.alert_id
params["mention_id"] = self.mention_id
params["before_date"] = self.before_date if self.before_date else ""
if self.limit:
if int(self.limit) > 1000:
params["limit"] = "1000"
elif int(self.limit) < 1:
params["limit"] = ""
else:
params["limit"] = self.limit
return params | [
"def",
"params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"\"access_token\"",
"]",
"=",
"self",
".",
"access_token",
"params",
"[",
"\"account_id\"",
"]",
"=",
"self",
".",
"account_id",
"params",
"[",
"\"alert_id\"",
"]",
"=",
"sel... | Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict | [
"Parameters",
"used",
"in",
"the",
"url",
"of",
"the",
"API",
"call",
"and",
"for",
"authentication",
"."
] | train | https://github.com/mazi76erX2/mention-python/blob/5133f463faa4ef053365fbf15db0a75dbb00a4e5/mention/mention/base.py#L839-L860 |
mazi76erX2/mention-python | mention/mention/base.py | FetchMentionChildrenAPI.url | def url(self):
"""The concatenation of the `base_url` and `end_url` that make up the
resultant url.
:return: the `base_url` and the `end_url`.
:rtype: str
"""
end_url = ("/accounts/{account_id}/alerts/{alert_id}/mentions/"
"{mention_id}/children?")
def without_keys(d, keys):
return {x: d[x] for x in d if x not in keys}
keys = {"access_token", "account_id", "alert_id"}
parameters = without_keys(self.params, keys)
for key, value in list(parameters.items()):
if value != '':
end_url += '&' + key + '={' + key + '}'
end_url = end_url.format(**self.params)
return self._base_url + end_url | python | def url(self):
"""The concatenation of the `base_url` and `end_url` that make up the
resultant url.
:return: the `base_url` and the `end_url`.
:rtype: str
"""
end_url = ("/accounts/{account_id}/alerts/{alert_id}/mentions/"
"{mention_id}/children?")
def without_keys(d, keys):
return {x: d[x] for x in d if x not in keys}
keys = {"access_token", "account_id", "alert_id"}
parameters = without_keys(self.params, keys)
for key, value in list(parameters.items()):
if value != '':
end_url += '&' + key + '={' + key + '}'
end_url = end_url.format(**self.params)
return self._base_url + end_url | [
"def",
"url",
"(",
"self",
")",
":",
"end_url",
"=",
"(",
"\"/accounts/{account_id}/alerts/{alert_id}/mentions/\"",
"\"{mention_id}/children?\"",
")",
"def",
"without_keys",
"(",
"d",
",",
"keys",
")",
":",
"return",
"{",
"x",
":",
"d",
"[",
"x",
"]",
"for",
... | The concatenation of the `base_url` and `end_url` that make up the
resultant url.
:return: the `base_url` and the `end_url`.
:rtype: str | [
"The",
"concatenation",
"of",
"the",
"base_url",
"and",
"end_url",
"that",
"make",
"up",
"the",
"resultant",
"url",
"."
] | train | https://github.com/mazi76erX2/mention-python/blob/5133f463faa4ef053365fbf15db0a75dbb00a4e5/mention/mention/base.py#L863-L884 |
mazi76erX2/mention-python | mention/mention/base.py | CurateAMentionAPI.data | def data(self):
"""Parameters passed to the API containing the details to update a
alert.
:return: parameters to create new alert.
:rtype: dict
"""
data = {}
data["favorite"] = self.favorite if self.favorite else ""
data["trashed"] = self.trashed if self.trashed else ""
data["read"] = self.read if self.read else ""
data["tags"] = self.tags if self.tags else ""
data["folder"] = self.folder if self.folder else ""
data["tone"] = self.tone if self.tone else ""
# Deletes parameter if it does not have a value
for key, value in list(data.items()):
if value == '':
del data[key]
data = json.dumps(data)
return data | python | def data(self):
"""Parameters passed to the API containing the details to update a
alert.
:return: parameters to create new alert.
:rtype: dict
"""
data = {}
data["favorite"] = self.favorite if self.favorite else ""
data["trashed"] = self.trashed if self.trashed else ""
data["read"] = self.read if self.read else ""
data["tags"] = self.tags if self.tags else ""
data["folder"] = self.folder if self.folder else ""
data["tone"] = self.tone if self.tone else ""
# Deletes parameter if it does not have a value
for key, value in list(data.items()):
if value == '':
del data[key]
data = json.dumps(data)
return data | [
"def",
"data",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"\"favorite\"",
"]",
"=",
"self",
".",
"favorite",
"if",
"self",
".",
"favorite",
"else",
"\"\"",
"data",
"[",
"\"trashed\"",
"]",
"=",
"self",
".",
"trashed",
"if",
"self",
... | Parameters passed to the API containing the details to update a
alert.
:return: parameters to create new alert.
:rtype: dict | [
"Parameters",
"passed",
"to",
"the",
"API",
"containing",
"the",
"details",
"to",
"update",
"a",
"alert",
"."
] | train | https://github.com/mazi76erX2/mention-python/blob/5133f463faa4ef053365fbf15db0a75dbb00a4e5/mention/mention/base.py#L1075-L1096 |
Laufire/ec | ec/interface.py | call | def call(command, collect_missing=False, silent=True):
r"""Calls a task, as if it were called from the command line.
Args:
command (str): A route followed by params (as if it were entered in the shell).
collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False.
Returns:
The return value of the called command.
"""
return (_execCommand if silent else execCommand)(shlex.split(command), collect_missing) | python | def call(command, collect_missing=False, silent=True):
r"""Calls a task, as if it were called from the command line.
Args:
command (str): A route followed by params (as if it were entered in the shell).
collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False.
Returns:
The return value of the called command.
"""
return (_execCommand if silent else execCommand)(shlex.split(command), collect_missing) | [
"def",
"call",
"(",
"command",
",",
"collect_missing",
"=",
"False",
",",
"silent",
"=",
"True",
")",
":",
"return",
"(",
"_execCommand",
"if",
"silent",
"else",
"execCommand",
")",
"(",
"shlex",
".",
"split",
"(",
"command",
")",
",",
"collect_missing",
... | r"""Calls a task, as if it were called from the command line.
Args:
command (str): A route followed by params (as if it were entered in the shell).
collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False.
Returns:
The return value of the called command. | [
"r",
"Calls",
"a",
"task",
"as",
"if",
"it",
"were",
"called",
"from",
"the",
"command",
"line",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/interface.py#L38-L48 |
Laufire/ec | ec/interface.py | add | def add(TargetGroup, NewMember, Config=None, Args=None):
r"""Adds members to an existing group.
Args:
TargetGroup (Group): The target group for the addition.
NewMember (Group / Task): The member to be added.
Config (dict): The config for the member.
Args (OrderedDict): ArgConfig for the NewMember, if it's a task (optional).
"""
Member = Task(NewMember, Args or {}, Config or {}) if isfunction(NewMember) else Group(NewMember, Config or {})
ParentMembers = TargetGroup.__ec_member__.Members
ParentMembers[Member.Config['name']] = Member
alias = Member.Config.get('alias')
if alias:
ParentMembers[alias] = Member | python | def add(TargetGroup, NewMember, Config=None, Args=None):
r"""Adds members to an existing group.
Args:
TargetGroup (Group): The target group for the addition.
NewMember (Group / Task): The member to be added.
Config (dict): The config for the member.
Args (OrderedDict): ArgConfig for the NewMember, if it's a task (optional).
"""
Member = Task(NewMember, Args or {}, Config or {}) if isfunction(NewMember) else Group(NewMember, Config or {})
ParentMembers = TargetGroup.__ec_member__.Members
ParentMembers[Member.Config['name']] = Member
alias = Member.Config.get('alias')
if alias:
ParentMembers[alias] = Member | [
"def",
"add",
"(",
"TargetGroup",
",",
"NewMember",
",",
"Config",
"=",
"None",
",",
"Args",
"=",
"None",
")",
":",
"Member",
"=",
"Task",
"(",
"NewMember",
",",
"Args",
"or",
"{",
"}",
",",
"Config",
"or",
"{",
"}",
")",
"if",
"isfunction",
"(",
... | r"""Adds members to an existing group.
Args:
TargetGroup (Group): The target group for the addition.
NewMember (Group / Task): The member to be added.
Config (dict): The config for the member.
Args (OrderedDict): ArgConfig for the NewMember, if it's a task (optional). | [
"r",
"Adds",
"members",
"to",
"an",
"existing",
"group",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/interface.py#L60-L77 |
sqrvrtx/plaid | plaid/plaid.py | do_check_pep8 | def do_check_pep8(files, status):
"""
Run the python pep8 tool against the filst of supplied files.
Append any linting errors to the returned status list
Args:
files (str): list of files to run pep8 against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list.
"""
for file_name in files:
args = ['flake8', '--max-line-length=120', '{0}'.format(file_name)]
output = run(*args)
if output:
status.append("Python PEP8/Flake8: {0}: {1}".format(file_name,
output))
return status | python | def do_check_pep8(files, status):
"""
Run the python pep8 tool against the filst of supplied files.
Append any linting errors to the returned status list
Args:
files (str): list of files to run pep8 against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list.
"""
for file_name in files:
args = ['flake8', '--max-line-length=120', '{0}'.format(file_name)]
output = run(*args)
if output:
status.append("Python PEP8/Flake8: {0}: {1}".format(file_name,
output))
return status | [
"def",
"do_check_pep8",
"(",
"files",
",",
"status",
")",
":",
"for",
"file_name",
"in",
"files",
":",
"args",
"=",
"[",
"'flake8'",
",",
"'--max-line-length=120'",
",",
"'{0}'",
".",
"format",
"(",
"file_name",
")",
"]",
"output",
"=",
"run",
"(",
"*",
... | Run the python pep8 tool against the filst of supplied files.
Append any linting errors to the returned status list
Args:
files (str): list of files to run pep8 against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list. | [
"Run",
"the",
"python",
"pep8",
"tool",
"against",
"the",
"filst",
"of",
"supplied",
"files",
".",
"Append",
"any",
"linting",
"errors",
"to",
"the",
"returned",
"status",
"list"
] | train | https://github.com/sqrvrtx/plaid/blob/2b6162f896e40e7c490e767839de143e042c2a18/plaid/plaid.py#L31-L54 |
sqrvrtx/plaid | plaid/plaid.py | do_check | def do_check(func, files, status):
"""
Generic do_check helper method
Args:
func (function): Specific function to call
files (list): list of files to run against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list.
"""
for file_name in files:
with open(file_name, 'r') as f:
output = func.parse(f.read(), file_name)
if output:
status.append("{0}: {1}".format(file_name, output))
return status | python | def do_check(func, files, status):
"""
Generic do_check helper method
Args:
func (function): Specific function to call
files (list): list of files to run against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list.
"""
for file_name in files:
with open(file_name, 'r') as f:
output = func.parse(f.read(), file_name)
if output:
status.append("{0}: {1}".format(file_name, output))
return status | [
"def",
"do_check",
"(",
"func",
",",
"files",
",",
"status",
")",
":",
"for",
"file_name",
"in",
"files",
":",
"with",
"open",
"(",
"file_name",
",",
"'r'",
")",
"as",
"f",
":",
"output",
"=",
"func",
".",
"parse",
"(",
"f",
".",
"read",
"(",
")"... | Generic do_check helper method
Args:
func (function): Specific function to call
files (list): list of files to run against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list. | [
"Generic",
"do_check",
"helper",
"method"
] | train | https://github.com/sqrvrtx/plaid/blob/2b6162f896e40e7c490e767839de143e042c2a18/plaid/plaid.py#L57-L79 |
sqrvrtx/plaid | plaid/plaid.py | check_for_empty_defaults | def check_for_empty_defaults(status):
"""
Method to check for empty roles structure.
When a role is created using ansible-galaxy it creates a default
scaffolding structure. Best practice dictates that if any of these are not
used then they should be removed. For example a bare main.yml with the
following string is created for a 'defaults' for a role called 'myrole':
---
defaults file for myrole
This should be removed.
Args:
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list.
"""
dirs_to_check = ('./vars', './handlers', './defaults', './tasks')
for dirpath, dirname, filename in os.walk('.'):
if dirpath == './files' or dirpath == "./templates":
if not any([dirname, filename]):
status.append("There are no files in the {0} directory. please"
" remove directory".format(dirpath))
if dirpath in dirs_to_check:
try:
joined_filename = os.path.join(dirpath, 'main.yml')
with open(joined_filename, 'r') as f:
# try to match:
# ---
# (tasks|vars|defaults) file for myrole
#
if re.match(r'^---\n# \S+ file for \S+\n$', f.read()):
status.append("Empty file, please remove file and "
"directory: {0}".format(joined_filename))
except IOError:
# Can't find a main.yml - but this could be legitimate
pass
return status | python | def check_for_empty_defaults(status):
"""
Method to check for empty roles structure.
When a role is created using ansible-galaxy it creates a default
scaffolding structure. Best practice dictates that if any of these are not
used then they should be removed. For example a bare main.yml with the
following string is created for a 'defaults' for a role called 'myrole':
---
defaults file for myrole
This should be removed.
Args:
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list.
"""
dirs_to_check = ('./vars', './handlers', './defaults', './tasks')
for dirpath, dirname, filename in os.walk('.'):
if dirpath == './files' or dirpath == "./templates":
if not any([dirname, filename]):
status.append("There are no files in the {0} directory. please"
" remove directory".format(dirpath))
if dirpath in dirs_to_check:
try:
joined_filename = os.path.join(dirpath, 'main.yml')
with open(joined_filename, 'r') as f:
# try to match:
# ---
# (tasks|vars|defaults) file for myrole
#
if re.match(r'^---\n# \S+ file for \S+\n$', f.read()):
status.append("Empty file, please remove file and "
"directory: {0}".format(joined_filename))
except IOError:
# Can't find a main.yml - but this could be legitimate
pass
return status | [
"def",
"check_for_empty_defaults",
"(",
"status",
")",
":",
"dirs_to_check",
"=",
"(",
"'./vars'",
",",
"'./handlers'",
",",
"'./defaults'",
",",
"'./tasks'",
")",
"for",
"dirpath",
",",
"dirname",
",",
"filename",
"in",
"os",
".",
"walk",
"(",
"'.'",
")",
... | Method to check for empty roles structure.
When a role is created using ansible-galaxy it creates a default
scaffolding structure. Best practice dictates that if any of these are not
used then they should be removed. For example a bare main.yml with the
following string is created for a 'defaults' for a role called 'myrole':
---
defaults file for myrole
This should be removed.
Args:
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
status list of current pre-redeive check failures. Might be an empty
list. | [
"Method",
"to",
"check",
"for",
"empty",
"roles",
"structure",
"."
] | train | https://github.com/sqrvrtx/plaid/blob/2b6162f896e40e7c490e767839de143e042c2a18/plaid/plaid.py#L88-L134 |
duniter/duniter-python-api | duniterpy/documents/revocation.py | Revocation.from_inline | def from_inline(cls: Type[RevocationType], version: int, currency: str, inline: str) -> RevocationType:
"""
Return Revocation document instance from inline string
Only self.pubkey is populated.
You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods
:param version: Version number
:param currency: Name of the currency
:param inline: Inline document
:return:
"""
cert_data = Revocation.re_inline.match(inline)
if cert_data is None:
raise MalformedDocumentError("Revokation")
pubkey = cert_data.group(1)
signature = cert_data.group(2)
return cls(version, currency, pubkey, signature) | python | def from_inline(cls: Type[RevocationType], version: int, currency: str, inline: str) -> RevocationType:
"""
Return Revocation document instance from inline string
Only self.pubkey is populated.
You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods
:param version: Version number
:param currency: Name of the currency
:param inline: Inline document
:return:
"""
cert_data = Revocation.re_inline.match(inline)
if cert_data is None:
raise MalformedDocumentError("Revokation")
pubkey = cert_data.group(1)
signature = cert_data.group(2)
return cls(version, currency, pubkey, signature) | [
"def",
"from_inline",
"(",
"cls",
":",
"Type",
"[",
"RevocationType",
"]",
",",
"version",
":",
"int",
",",
"currency",
":",
"str",
",",
"inline",
":",
"str",
")",
"->",
"RevocationType",
":",
"cert_data",
"=",
"Revocation",
".",
"re_inline",
".",
"match... | Return Revocation document instance from inline string
Only self.pubkey is populated.
You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods
:param version: Version number
:param currency: Name of the currency
:param inline: Inline document
:return: | [
"Return",
"Revocation",
"document",
"instance",
"from",
"inline",
"string"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/revocation.py#L51-L69 |
duniter/duniter-python-api | duniterpy/documents/revocation.py | Revocation.from_signed_raw | def from_signed_raw(cls: Type[RevocationType], signed_raw: str) -> RevocationType:
"""
Return Revocation document instance from a signed raw string
:param signed_raw: raw document file in duniter format
:return:
"""
lines = signed_raw.splitlines(True)
n = 0
version = int(Revocation.parse_field("Version", lines[n]))
n += 1
Revocation.parse_field("Type", lines[n])
n += 1
currency = Revocation.parse_field("Currency", lines[n])
n += 1
issuer = Revocation.parse_field("Issuer", lines[n])
n += 1
identity_uid = Revocation.parse_field("IdtyUniqueID", lines[n])
n += 1
identity_timestamp = Revocation.parse_field("IdtyTimestamp", lines[n])
n += 1
identity_signature = Revocation.parse_field("IdtySignature", lines[n])
n += 1
signature = Revocation.parse_field("Signature", lines[n])
n += 1
identity = Identity(version, currency, issuer, identity_uid, identity_timestamp, identity_signature)
return cls(version, currency, identity, signature) | python | def from_signed_raw(cls: Type[RevocationType], signed_raw: str) -> RevocationType:
"""
Return Revocation document instance from a signed raw string
:param signed_raw: raw document file in duniter format
:return:
"""
lines = signed_raw.splitlines(True)
n = 0
version = int(Revocation.parse_field("Version", lines[n]))
n += 1
Revocation.parse_field("Type", lines[n])
n += 1
currency = Revocation.parse_field("Currency", lines[n])
n += 1
issuer = Revocation.parse_field("Issuer", lines[n])
n += 1
identity_uid = Revocation.parse_field("IdtyUniqueID", lines[n])
n += 1
identity_timestamp = Revocation.parse_field("IdtyTimestamp", lines[n])
n += 1
identity_signature = Revocation.parse_field("IdtySignature", lines[n])
n += 1
signature = Revocation.parse_field("Signature", lines[n])
n += 1
identity = Identity(version, currency, issuer, identity_uid, identity_timestamp, identity_signature)
return cls(version, currency, identity, signature) | [
"def",
"from_signed_raw",
"(",
"cls",
":",
"Type",
"[",
"RevocationType",
"]",
",",
"signed_raw",
":",
"str",
")",
"->",
"RevocationType",
":",
"lines",
"=",
"signed_raw",
".",
"splitlines",
"(",
"True",
")",
"n",
"=",
"0",
"version",
"=",
"int",
"(",
... | Return Revocation document instance from a signed raw string
:param signed_raw: raw document file in duniter format
:return: | [
"Return",
"Revocation",
"document",
"instance",
"from",
"a",
"signed",
"raw",
"string"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/revocation.py#L72-L108 |
duniter/duniter-python-api | duniterpy/documents/revocation.py | Revocation.extract_self_cert | def extract_self_cert(signed_raw: str) -> Identity:
"""
Return self-certified Identity instance from the signed raw Revocation document
:param signed_raw: Signed raw document string
:return:
"""
lines = signed_raw.splitlines(True)
n = 0
version = int(Revocation.parse_field("Version", lines[n]))
n += 1
Revocation.parse_field("Type", lines[n])
n += 1
currency = Revocation.parse_field("Currency", lines[n])
n += 1
issuer = Revocation.parse_field("Issuer", lines[n])
n += 1
unique_id = Revocation.parse_field("IdtyUniqueID", lines[n])
n += 1
timestamp = Revocation.parse_field("IdtyTimestamp", lines[n])
n += 1
signature = Revocation.parse_field("IdtySignature", lines[n])
n += 1
return Identity(version, currency, issuer, unique_id, timestamp, signature) | python | def extract_self_cert(signed_raw: str) -> Identity:
"""
Return self-certified Identity instance from the signed raw Revocation document
:param signed_raw: Signed raw document string
:return:
"""
lines = signed_raw.splitlines(True)
n = 0
version = int(Revocation.parse_field("Version", lines[n]))
n += 1
Revocation.parse_field("Type", lines[n])
n += 1
currency = Revocation.parse_field("Currency", lines[n])
n += 1
issuer = Revocation.parse_field("Issuer", lines[n])
n += 1
unique_id = Revocation.parse_field("IdtyUniqueID", lines[n])
n += 1
timestamp = Revocation.parse_field("IdtyTimestamp", lines[n])
n += 1
signature = Revocation.parse_field("IdtySignature", lines[n])
n += 1
return Identity(version, currency, issuer, unique_id, timestamp, signature) | [
"def",
"extract_self_cert",
"(",
"signed_raw",
":",
"str",
")",
"->",
"Identity",
":",
"lines",
"=",
"signed_raw",
".",
"splitlines",
"(",
"True",
")",
"n",
"=",
"0",
"version",
"=",
"int",
"(",
"Revocation",
".",
"parse_field",
"(",
"\"Version\"",
",",
... | Return self-certified Identity instance from the signed raw Revocation document
:param signed_raw: Signed raw document string
:return: | [
"Return",
"self",
"-",
"certified",
"Identity",
"instance",
"from",
"the",
"signed",
"raw",
"Revocation",
"document"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/revocation.py#L111-L142 |
duniter/duniter-python-api | duniterpy/documents/revocation.py | Revocation.raw | def raw(self) -> str:
"""
Return Revocation raw document string
:return:
"""
if not isinstance(self.identity, Identity):
raise MalformedDocumentError("Can not return full revocation document created from inline")
return """Version: {version}
Type: Revocation
Currency: {currency}
Issuer: {pubkey}
IdtyUniqueID: {uid}
IdtyTimestamp: {timestamp}
IdtySignature: {signature}
""".format(version=self.version,
currency=self.currency,
pubkey=self.identity.pubkey,
uid=self.identity.uid,
timestamp=self.identity.timestamp,
signature=self.identity.signatures[0]) | python | def raw(self) -> str:
"""
Return Revocation raw document string
:return:
"""
if not isinstance(self.identity, Identity):
raise MalformedDocumentError("Can not return full revocation document created from inline")
return """Version: {version}
Type: Revocation
Currency: {currency}
Issuer: {pubkey}
IdtyUniqueID: {uid}
IdtyTimestamp: {timestamp}
IdtySignature: {signature}
""".format(version=self.version,
currency=self.currency,
pubkey=self.identity.pubkey,
uid=self.identity.uid,
timestamp=self.identity.timestamp,
signature=self.identity.signatures[0]) | [
"def",
"raw",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"identity",
",",
"Identity",
")",
":",
"raise",
"MalformedDocumentError",
"(",
"\"Can not return full revocation document created from inline\"",
")",
"return",
"\"\"\"Ver... | Return Revocation raw document string
:return: | [
"Return",
"Revocation",
"raw",
"document",
"string"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/revocation.py#L152-L173 |
duniter/duniter-python-api | duniterpy/documents/revocation.py | Revocation.sign | def sign(self, keys: list) -> None:
"""
Sign the current document.
Warning : current signatures will be replaced with the new ones.
:param keys: List of libnacl key instances
:return:
"""
if not isinstance(self.identity, Identity):
raise MalformedDocumentError("Can not return full revocation document created from inline")
self.signatures = []
for key in keys:
signing = base64.b64encode(key.signature(bytes(self.raw(), 'ascii')))
self.signatures.append(signing.decode("ascii")) | python | def sign(self, keys: list) -> None:
"""
Sign the current document.
Warning : current signatures will be replaced with the new ones.
:param keys: List of libnacl key instances
:return:
"""
if not isinstance(self.identity, Identity):
raise MalformedDocumentError("Can not return full revocation document created from inline")
self.signatures = []
for key in keys:
signing = base64.b64encode(key.signature(bytes(self.raw(), 'ascii')))
self.signatures.append(signing.decode("ascii")) | [
"def",
"sign",
"(",
"self",
",",
"keys",
":",
"list",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"identity",
",",
"Identity",
")",
":",
"raise",
"MalformedDocumentError",
"(",
"\"Can not return full revocation document created from inline... | Sign the current document.
Warning : current signatures will be replaced with the new ones.
:param keys: List of libnacl key instances
:return: | [
"Sign",
"the",
"current",
"document",
".",
"Warning",
":",
"current",
"signatures",
"will",
"be",
"replaced",
"with",
"the",
"new",
"ones",
"."
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/revocation.py#L175-L189 |
duniter/duniter-python-api | duniterpy/documents/revocation.py | Revocation.signed_raw | def signed_raw(self) -> str:
"""
Return Revocation signed raw document string
:return:
"""
if not isinstance(self.identity, Identity):
raise MalformedDocumentError("Can not return full revocation document created from inline")
raw = self.raw()
signed = "\n".join(self.signatures)
signed_raw = raw + signed + "\n"
return signed_raw | python | def signed_raw(self) -> str:
"""
Return Revocation signed raw document string
:return:
"""
if not isinstance(self.identity, Identity):
raise MalformedDocumentError("Can not return full revocation document created from inline")
raw = self.raw()
signed = "\n".join(self.signatures)
signed_raw = raw + signed + "\n"
return signed_raw | [
"def",
"signed_raw",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"identity",
",",
"Identity",
")",
":",
"raise",
"MalformedDocumentError",
"(",
"\"Can not return full revocation document created from inline\"",
")",
"raw",
"=",
... | Return Revocation signed raw document string
:return: | [
"Return",
"Revocation",
"signed",
"raw",
"document",
"string"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/revocation.py#L191-L203 |
Datary/scrapbag | scrapbag/strings.py | clean_text | def clean_text(text):
"""
Retrieve clean text without markdown sintax or other things.
"""
if text:
text = html2text.html2text(clean_markdown(text))
return re.sub(r'\s+', ' ', text).strip() | python | def clean_text(text):
"""
Retrieve clean text without markdown sintax or other things.
"""
if text:
text = html2text.html2text(clean_markdown(text))
return re.sub(r'\s+', ' ', text).strip() | [
"def",
"clean_text",
"(",
"text",
")",
":",
"if",
"text",
":",
"text",
"=",
"html2text",
".",
"html2text",
"(",
"clean_markdown",
"(",
"text",
")",
")",
"return",
"re",
".",
"sub",
"(",
"r'\\s+'",
",",
"' '",
",",
"text",
")",
".",
"strip",
"(",
")... | Retrieve clean text without markdown sintax or other things. | [
"Retrieve",
"clean",
"text",
"without",
"markdown",
"sintax",
"or",
"other",
"things",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/strings.py#L15-L21 |
Datary/scrapbag | scrapbag/strings.py | clean_markdown | def clean_markdown(text):
"""
Parse markdown sintaxt to html.
"""
result = text
if isinstance(text, str):
result = ''.join(
BeautifulSoup(markdown(text), 'lxml').findAll(text=True))
return result | python | def clean_markdown(text):
"""
Parse markdown sintaxt to html.
"""
result = text
if isinstance(text, str):
result = ''.join(
BeautifulSoup(markdown(text), 'lxml').findAll(text=True))
return result | [
"def",
"clean_markdown",
"(",
"text",
")",
":",
"result",
"=",
"text",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"result",
"=",
"''",
".",
"join",
"(",
"BeautifulSoup",
"(",
"markdown",
"(",
"text",
")",
",",
"'lxml'",
")",
".",
"findAll... | Parse markdown sintaxt to html. | [
"Parse",
"markdown",
"sintaxt",
"to",
"html",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/strings.py#L24-L34 |
Datary/scrapbag | scrapbag/strings.py | select_regexp_char | def select_regexp_char(char):
"""
Select correct regex depending the char
"""
regexp = '{}'.format(char)
if not isinstance(char, str) and not isinstance(char, int):
regexp = ''
if isinstance(char, str) and not char.isalpha() and not char.isdigit():
regexp = r"\{}".format(char)
return regexp | python | def select_regexp_char(char):
"""
Select correct regex depending the char
"""
regexp = '{}'.format(char)
if not isinstance(char, str) and not isinstance(char, int):
regexp = ''
if isinstance(char, str) and not char.isalpha() and not char.isdigit():
regexp = r"\{}".format(char)
return regexp | [
"def",
"select_regexp_char",
"(",
"char",
")",
":",
"regexp",
"=",
"'{}'",
".",
"format",
"(",
"char",
")",
"if",
"not",
"isinstance",
"(",
"char",
",",
"str",
")",
"and",
"not",
"isinstance",
"(",
"char",
",",
"int",
")",
":",
"regexp",
"=",
"''",
... | Select correct regex depending the char | [
"Select",
"correct",
"regex",
"depending",
"the",
"char"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/strings.py#L51-L63 |
Datary/scrapbag | scrapbag/strings.py | exclude_chars | def exclude_chars(text, exclusion=None):
"""
Clean text string of simbols in exclusion list.
"""
exclusion = [] if exclusion is None else exclusion
regexp = r"|".join([select_regexp_char(x) for x in exclusion]) or r''
return re.sub(regexp, '', text) | python | def exclude_chars(text, exclusion=None):
"""
Clean text string of simbols in exclusion list.
"""
exclusion = [] if exclusion is None else exclusion
regexp = r"|".join([select_regexp_char(x) for x in exclusion]) or r''
return re.sub(regexp, '', text) | [
"def",
"exclude_chars",
"(",
"text",
",",
"exclusion",
"=",
"None",
")",
":",
"exclusion",
"=",
"[",
"]",
"if",
"exclusion",
"is",
"None",
"else",
"exclusion",
"regexp",
"=",
"r\"|\"",
".",
"join",
"(",
"[",
"select_regexp_char",
"(",
"x",
")",
"for",
... | Clean text string of simbols in exclusion list. | [
"Clean",
"text",
"string",
"of",
"simbols",
"in",
"exclusion",
"list",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/strings.py#L66-L72 |
Datary/scrapbag | scrapbag/strings.py | strip_accents | def strip_accents(text):
"""
Strip agents from a string.
"""
normalized_str = unicodedata.normalize('NFD', text)
return ''.join([
c for c in normalized_str if unicodedata.category(c) != 'Mn']) | python | def strip_accents(text):
"""
Strip agents from a string.
"""
normalized_str = unicodedata.normalize('NFD', text)
return ''.join([
c for c in normalized_str if unicodedata.category(c) != 'Mn']) | [
"def",
"strip_accents",
"(",
"text",
")",
":",
"normalized_str",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
",",
"text",
")",
"return",
"''",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"normalized_str",
"if",
"unicodedata",
".",
"category",
"... | Strip agents from a string. | [
"Strip",
"agents",
"from",
"a",
"string",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/strings.py#L75-L83 |
Datary/scrapbag | scrapbag/strings.py | normalizer | def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs):
"""
Clean text string of simbols only alphanumeric chars.
"""
clean_str = re.sub(r'[^\w{}]'.format(
"".join(exclusion)), separate_char, text.strip()) or ''
clean_lowerbar = clean_str_without_accents = strip_accents(clean_str)
if '_' not in exclusion:
clean_lowerbar = re.sub(r'\_', separate_char, clean_str_without_accents.strip())
limit_guion = re.sub(r'\-+', separate_char, clean_lowerbar.strip())
# TODO: refactor with a regexp
if limit_guion and separate_char and separate_char in limit_guion[0]:
limit_guion = limit_guion[1:]
if limit_guion and separate_char and separate_char in limit_guion[-1]:
limit_guion = limit_guion[:-1]
if lower:
limit_guion = limit_guion.lower()
return limit_guion | python | def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs):
"""
Clean text string of simbols only alphanumeric chars.
"""
clean_str = re.sub(r'[^\w{}]'.format(
"".join(exclusion)), separate_char, text.strip()) or ''
clean_lowerbar = clean_str_without_accents = strip_accents(clean_str)
if '_' not in exclusion:
clean_lowerbar = re.sub(r'\_', separate_char, clean_str_without_accents.strip())
limit_guion = re.sub(r'\-+', separate_char, clean_lowerbar.strip())
# TODO: refactor with a regexp
if limit_guion and separate_char and separate_char in limit_guion[0]:
limit_guion = limit_guion[1:]
if limit_guion and separate_char and separate_char in limit_guion[-1]:
limit_guion = limit_guion[:-1]
if lower:
limit_guion = limit_guion.lower()
return limit_guion | [
"def",
"normalizer",
"(",
"text",
",",
"exclusion",
"=",
"OPERATIONS_EXCLUSION",
",",
"lower",
"=",
"True",
",",
"separate_char",
"=",
"'-'",
",",
"*",
"*",
"kwargs",
")",
":",
"clean_str",
"=",
"re",
".",
"sub",
"(",
"r'[^\\w{}]'",
".",
"format",
"(",
... | Clean text string of simbols only alphanumeric chars. | [
"Clean",
"text",
"string",
"of",
"simbols",
"only",
"alphanumeric",
"chars",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/strings.py#L89-L112 |
Datary/scrapbag | scrapbag/strings.py | normalize_dict | def normalize_dict(dictionary, **kwargs):
"""
Given an dict, normalize all of their keys using normalize function.
"""
result = {}
if isinstance(dictionary, dict):
keys = list(dictionary.keys())
for key in keys:
result[normalizer(key, **kwargs)] = normalize_dict(dictionary.get(key), **kwargs)
else:
result = dictionary
return result | python | def normalize_dict(dictionary, **kwargs):
"""
Given an dict, normalize all of their keys using normalize function.
"""
result = {}
if isinstance(dictionary, dict):
keys = list(dictionary.keys())
for key in keys:
result[normalizer(key, **kwargs)] = normalize_dict(dictionary.get(key), **kwargs)
else:
result = dictionary
return result | [
"def",
"normalize_dict",
"(",
"dictionary",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"dictionary",
",",
"dict",
")",
":",
"keys",
"=",
"list",
"(",
"dictionary",
".",
"keys",
"(",
")",
")",
"for",
"key",
... | Given an dict, normalize all of their keys using normalize function. | [
"Given",
"an",
"dict",
"normalize",
"all",
"of",
"their",
"keys",
"using",
"normalize",
"function",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/strings.py#L115-L126 |
salesking/salesking_python_sdk | salesking/utils/helpers.py | pluralize | def pluralize(data_type):
"""
adds s to the data type or the correct english plural form
"""
known = {
u"address": u"addresses",
u"company": u"companies"
}
if data_type in known.keys():
return known[data_type]
else:
return u"%ss" % data_type | python | def pluralize(data_type):
"""
adds s to the data type or the correct english plural form
"""
known = {
u"address": u"addresses",
u"company": u"companies"
}
if data_type in known.keys():
return known[data_type]
else:
return u"%ss" % data_type | [
"def",
"pluralize",
"(",
"data_type",
")",
":",
"known",
"=",
"{",
"u\"address\"",
":",
"u\"addresses\"",
",",
"u\"company\"",
":",
"u\"companies\"",
"}",
"if",
"data_type",
"in",
"known",
".",
"keys",
"(",
")",
":",
"return",
"known",
"[",
"data_type",
"]... | adds s to the data type or the correct english plural form | [
"adds",
"s",
"to",
"the",
"data",
"type",
"or",
"the",
"correct",
"english",
"plural",
"form"
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/helpers.py#L13-L24 |
salesking/salesking_python_sdk | salesking/utils/helpers.py | remove_properties_containing_None | def remove_properties_containing_None(properties_dict):
"""
removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match
"""
# remove empty properties - as validations may fail
new_dict = dict()
for key in properties_dict.keys():
value = properties_dict[key]
if value is not None:
new_dict[key] = value
return new_dict | python | def remove_properties_containing_None(properties_dict):
"""
removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match
"""
# remove empty properties - as validations may fail
new_dict = dict()
for key in properties_dict.keys():
value = properties_dict[key]
if value is not None:
new_dict[key] = value
return new_dict | [
"def",
"remove_properties_containing_None",
"(",
"properties_dict",
")",
":",
"# remove empty properties - as validations may fail",
"new_dict",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"properties_dict",
".",
"keys",
"(",
")",
":",
"value",
"=",
"properties_dict",
... | removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match | [
"removes",
"keys",
"from",
"a",
"dict",
"those",
"values",
"==",
"None",
"json",
"schema",
"validation",
"might",
"fail",
"if",
"they",
"are",
"set",
"and",
"the",
"type",
"or",
"format",
"of",
"the",
"property",
"does",
"not",
"match"
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/helpers.py#L26-L38 |
salesking/salesking_python_sdk | salesking/utils/helpers.py | dict_to_object | def dict_to_object(d):
"""Recursively converts a dict to an object"""
top = type('CreateSendModel', (object,), d)
seqs = tuple, list, set, frozenset
for i, j in d.items():
if isinstance(j, dict):
setattr(top, i, dict_to_object(j))
elif isinstance(j, seqs):
setattr(top, i, type(j)(dict_to_object(sj) if isinstance(sj, dict) else sj for sj in j))
else:
setattr(top, i, j)
return top | python | def dict_to_object(d):
"""Recursively converts a dict to an object"""
top = type('CreateSendModel', (object,), d)
seqs = tuple, list, set, frozenset
for i, j in d.items():
if isinstance(j, dict):
setattr(top, i, dict_to_object(j))
elif isinstance(j, seqs):
setattr(top, i, type(j)(dict_to_object(sj) if isinstance(sj, dict) else sj for sj in j))
else:
setattr(top, i, j)
return top | [
"def",
"dict_to_object",
"(",
"d",
")",
":",
"top",
"=",
"type",
"(",
"'CreateSendModel'",
",",
"(",
"object",
",",
")",
",",
"d",
")",
"seqs",
"=",
"tuple",
",",
"list",
",",
"set",
",",
"frozenset",
"for",
"i",
",",
"j",
"in",
"d",
".",
"items"... | Recursively converts a dict to an object | [
"Recursively",
"converts",
"a",
"dict",
"to",
"an",
"object"
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/helpers.py#L47-L58 |
timothydmorton/obliquity | obliquity/distributions.py | veq_samples | def veq_samples(R_dist,Prot_dist,N=1e4,alpha=0.23,l0=20,sigl=20):
"""Source for diff rot
"""
ls = stats.norm(l0,sigl).rvs(N)
Prots = Prot_dist.rvs(N)
Prots *= diff_Prot_factor(ls,alpha)
return R_dist.rvs(N)*2*np.pi*RSUN/(Prots*DAY)/1e5 | python | def veq_samples(R_dist,Prot_dist,N=1e4,alpha=0.23,l0=20,sigl=20):
"""Source for diff rot
"""
ls = stats.norm(l0,sigl).rvs(N)
Prots = Prot_dist.rvs(N)
Prots *= diff_Prot_factor(ls,alpha)
return R_dist.rvs(N)*2*np.pi*RSUN/(Prots*DAY)/1e5 | [
"def",
"veq_samples",
"(",
"R_dist",
",",
"Prot_dist",
",",
"N",
"=",
"1e4",
",",
"alpha",
"=",
"0.23",
",",
"l0",
"=",
"20",
",",
"sigl",
"=",
"20",
")",
":",
"ls",
"=",
"stats",
".",
"norm",
"(",
"l0",
",",
"sigl",
")",
".",
"rvs",
"(",
"N"... | Source for diff rot | [
"Source",
"for",
"diff",
"rot"
] | train | https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/distributions.py#L132-L138 |
timothydmorton/obliquity | obliquity/distributions.py | fveq | def fveq(z,R,dR,P,dP):
"""z=veq in km/s.
"""
R *= 2*pi*RSUN
dR *= 2*pi*RSUN
P *= DAY
dP *= DAY
exp1 = -P**2/(2*dP**2) - R**2/(2*dR**2)
exp2 = (dR**2*P + dP**2*R*(z*1e5))**2/(2*dP**2*dR**2*(dR**2 + dP**2*(z*1e5)**2))
nonexp_term = 2*dP*dR*np.sqrt(dR**2 + dP**2*(z*1e5)**2)
return 1e5/(4*pi*(dR**2 + dP**2*(z*1e5)**2)**(3/2))*np.exp(exp1 + exp2) *\
(dR**2 * P*np.sqrt(2*pi) +
dP**2 * np.sqrt(2*pi)*R*(z*1e5) +
nonexp_term * np.exp(-exp2) +
np.sqrt(2*pi)*(dR**2*P + dP**2*R*(z*1e5))*erf((dR**2*P + dP**2*R*(z*1e5)) *
(np.sqrt(2)*dP*dR*
np.sqrt(dR**2 + dP**2*(z*1e5)**2)))) | python | def fveq(z,R,dR,P,dP):
"""z=veq in km/s.
"""
R *= 2*pi*RSUN
dR *= 2*pi*RSUN
P *= DAY
dP *= DAY
exp1 = -P**2/(2*dP**2) - R**2/(2*dR**2)
exp2 = (dR**2*P + dP**2*R*(z*1e5))**2/(2*dP**2*dR**2*(dR**2 + dP**2*(z*1e5)**2))
nonexp_term = 2*dP*dR*np.sqrt(dR**2 + dP**2*(z*1e5)**2)
return 1e5/(4*pi*(dR**2 + dP**2*(z*1e5)**2)**(3/2))*np.exp(exp1 + exp2) *\
(dR**2 * P*np.sqrt(2*pi) +
dP**2 * np.sqrt(2*pi)*R*(z*1e5) +
nonexp_term * np.exp(-exp2) +
np.sqrt(2*pi)*(dR**2*P + dP**2*R*(z*1e5))*erf((dR**2*P + dP**2*R*(z*1e5)) *
(np.sqrt(2)*dP*dR*
np.sqrt(dR**2 + dP**2*(z*1e5)**2)))) | [
"def",
"fveq",
"(",
"z",
",",
"R",
",",
"dR",
",",
"P",
",",
"dP",
")",
":",
"R",
"*=",
"2",
"*",
"pi",
"*",
"RSUN",
"dR",
"*=",
"2",
"*",
"pi",
"*",
"RSUN",
"P",
"*=",
"DAY",
"dP",
"*=",
"DAY",
"exp1",
"=",
"-",
"P",
"**",
"2",
"/",
... | z=veq in km/s. | [
"z",
"=",
"veq",
"in",
"km",
"/",
"s",
"."
] | train | https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/distributions.py#L170-L190 |
henzk/ape | ape/installtools/__init__.py | cleanup | def cleanup():
"""Clean up the installation directory."""
lib_dir = os.path.join(os.environ['CONTAINER_DIR'], '_lib')
if os.path.exists(lib_dir):
shutil.rmtree(lib_dir)
os.mkdir(lib_dir) | python | def cleanup():
"""Clean up the installation directory."""
lib_dir = os.path.join(os.environ['CONTAINER_DIR'], '_lib')
if os.path.exists(lib_dir):
shutil.rmtree(lib_dir)
os.mkdir(lib_dir) | [
"def",
"cleanup",
"(",
")",
":",
"lib_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'CONTAINER_DIR'",
"]",
",",
"'_lib'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"lib_dir",
")",
":",
"shutil",
".",
"rmtree",
... | Clean up the installation directory. | [
"Clean",
"up",
"the",
"installation",
"directory",
"."
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/installtools/__init__.py#L17-L22 |
henzk/ape | ape/installtools/__init__.py | get_or_create_project_venv | def get_or_create_project_venv():
"""
Create a project-level virtualenv (if it does not already exist).
:return: ``VirtualEnv`` object
"""
venv_dir = get_project_venv_dir()
if os.path.exists(venv_dir):
return VirtualEnv(venv_dir)
else:
return create_project_venv() | python | def get_or_create_project_venv():
"""
Create a project-level virtualenv (if it does not already exist).
:return: ``VirtualEnv`` object
"""
venv_dir = get_project_venv_dir()
if os.path.exists(venv_dir):
return VirtualEnv(venv_dir)
else:
return create_project_venv() | [
"def",
"get_or_create_project_venv",
"(",
")",
":",
"venv_dir",
"=",
"get_project_venv_dir",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"venv_dir",
")",
":",
"return",
"VirtualEnv",
"(",
"venv_dir",
")",
"else",
":",
"return",
"create_project_venv"... | Create a project-level virtualenv (if it does not already exist).
:return: ``VirtualEnv`` object | [
"Create",
"a",
"project",
"-",
"level",
"virtualenv",
"(",
"if",
"it",
"does",
"not",
"already",
"exist",
")",
"."
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/installtools/__init__.py#L30-L41 |
henzk/ape | ape/installtools/__init__.py | create_project_venv | def create_project_venv():
"""
Create a project-level virtualenv.
:raises: if virtualenv exists already
:return: ``VirtualEnv`` object
"""
print('... creating project-level virtualenv')
venv_dir = get_project_venv_dir()
if os.path.exists(venv_dir):
raise Exception('ERROR: virtualenv already exists!')
use_venv_module = sys.version_info >= (3, 0) and 'APE_USE_VIRTUALENV' not in os.environ
VirtualEnv.create_virtualenv(venv_dir, use_venv_module=use_venv_module)
print('... virtualenv successfully created')
return VirtualEnv(venv_dir) | python | def create_project_venv():
"""
Create a project-level virtualenv.
:raises: if virtualenv exists already
:return: ``VirtualEnv`` object
"""
print('... creating project-level virtualenv')
venv_dir = get_project_venv_dir()
if os.path.exists(venv_dir):
raise Exception('ERROR: virtualenv already exists!')
use_venv_module = sys.version_info >= (3, 0) and 'APE_USE_VIRTUALENV' not in os.environ
VirtualEnv.create_virtualenv(venv_dir, use_venv_module=use_venv_module)
print('... virtualenv successfully created')
return VirtualEnv(venv_dir) | [
"def",
"create_project_venv",
"(",
")",
":",
"print",
"(",
"'... creating project-level virtualenv'",
")",
"venv_dir",
"=",
"get_project_venv_dir",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"venv_dir",
")",
":",
"raise",
"Exception",
"(",
"'ERROR: v... | Create a project-level virtualenv.
:raises: if virtualenv exists already
:return: ``VirtualEnv`` object | [
"Create",
"a",
"project",
"-",
"level",
"virtualenv",
"."
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/installtools/__init__.py#L44-L62 |
henzk/ape | ape/installtools/__init__.py | fetch_pool | def fetch_pool(repo_url, branch='master', reuse_existing=False):
"""Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object."""
repo_name = get_repo_name(repo_url)
lib_dir = get_lib_dir()
pool_dir = get_pool_dir(repo_name)
print('... fetching %s ' % repo_name)
if os.path.exists(pool_dir):
if not reuse_existing:
raise Exception('ERROR: repository already exists')
else:
try:
a = call(['git', 'clone', repo_url], cwd=lib_dir)
except OSError:
raise Exception('ERROR: You probably dont have git installed: sudo apt-get install git')
if a != 0:
raise Exception('ERROR: check your repository url and credentials!')
try:
call(['git', 'checkout', branch], cwd=pool_dir)
except OSError:
raise Exception('ERROR: cannot switch branches')
print('... repository successfully cloned')
return FeaturePool(pool_dir) | python | def fetch_pool(repo_url, branch='master', reuse_existing=False):
"""Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object."""
repo_name = get_repo_name(repo_url)
lib_dir = get_lib_dir()
pool_dir = get_pool_dir(repo_name)
print('... fetching %s ' % repo_name)
if os.path.exists(pool_dir):
if not reuse_existing:
raise Exception('ERROR: repository already exists')
else:
try:
a = call(['git', 'clone', repo_url], cwd=lib_dir)
except OSError:
raise Exception('ERROR: You probably dont have git installed: sudo apt-get install git')
if a != 0:
raise Exception('ERROR: check your repository url and credentials!')
try:
call(['git', 'checkout', branch], cwd=pool_dir)
except OSError:
raise Exception('ERROR: cannot switch branches')
print('... repository successfully cloned')
return FeaturePool(pool_dir) | [
"def",
"fetch_pool",
"(",
"repo_url",
",",
"branch",
"=",
"'master'",
",",
"reuse_existing",
"=",
"False",
")",
":",
"repo_name",
"=",
"get_repo_name",
"(",
"repo_url",
")",
"lib_dir",
"=",
"get_lib_dir",
"(",
")",
"pool_dir",
"=",
"get_pool_dir",
"(",
"repo... | Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object. | [
"Fetch",
"a",
"git",
"repository",
"from",
"repo_url",
"and",
"returns",
"a",
"FeaturePool",
"object",
"."
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/installtools/__init__.py#L77-L102 |
CodyKochmann/strict_functions | strict_functions/noglobals.py | noglobals | def noglobals(fn):
""" decorator for functions that dont get access to globals """
return type(fn)(
getattr(fn, 'func_code', getattr(fn, '__code__')),
{'__builtins__': builtins},
getattr(fn, 'func_name', getattr(fn, '__name__')),
getattr(fn, 'func_defaults', getattr(fn, '__defaults__')),
getattr(fn, 'func_closure', getattr(fn, '__closure__'))
) | python | def noglobals(fn):
""" decorator for functions that dont get access to globals """
return type(fn)(
getattr(fn, 'func_code', getattr(fn, '__code__')),
{'__builtins__': builtins},
getattr(fn, 'func_name', getattr(fn, '__name__')),
getattr(fn, 'func_defaults', getattr(fn, '__defaults__')),
getattr(fn, 'func_closure', getattr(fn, '__closure__'))
) | [
"def",
"noglobals",
"(",
"fn",
")",
":",
"return",
"type",
"(",
"fn",
")",
"(",
"getattr",
"(",
"fn",
",",
"'func_code'",
",",
"getattr",
"(",
"fn",
",",
"'__code__'",
")",
")",
",",
"{",
"'__builtins__'",
":",
"builtins",
"}",
",",
"getattr",
"(",
... | decorator for functions that dont get access to globals | [
"decorator",
"for",
"functions",
"that",
"dont",
"get",
"access",
"to",
"globals"
] | train | https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/noglobals.py#L9-L17 |
Datary/scrapbag | scrapbag/collections.py | exclude_values | def exclude_values(values, args):
"""
Exclude data with specific value.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
values list values where exclude elements
args list or dict elements to exclude
============= ============= =======================================
Returns: vakues without excluded elements
"""
if isinstance(args, dict):
return {
key: value
for key, value in (
(k, exclude_values(values, v)) for (k, v) in args.items())
if value not in values
}
elif isinstance(args, list):
return [
item
for item in [exclude_values(values, i) for i in args]
if item not in values
]
return args | python | def exclude_values(values, args):
"""
Exclude data with specific value.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
values list values where exclude elements
args list or dict elements to exclude
============= ============= =======================================
Returns: vakues without excluded elements
"""
if isinstance(args, dict):
return {
key: value
for key, value in (
(k, exclude_values(values, v)) for (k, v) in args.items())
if value not in values
}
elif isinstance(args, list):
return [
item
for item in [exclude_values(values, i) for i in args]
if item not in values
]
return args | [
"def",
"exclude_values",
"(",
"values",
",",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"dict",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"(",
"(",
"k",
",",
"exclude_values",
"(",
"values",
",",
"... | Exclude data with specific value.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
values list values where exclude elements
args list or dict elements to exclude
============= ============= =======================================
Returns: vakues without excluded elements | [
"Exclude",
"data",
"with",
"specific",
"value",
".",
"=============",
"=============",
"=======================================",
"Parameter",
"Type",
"Description",
"=============",
"=============",
"=======================================",
"values",
"list",
"values",
"where",
... | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L15-L41 |
Datary/scrapbag | scrapbag/collections.py | get_element | def get_element(source, path, separator=r'[/.]'):
"""
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (string): '/' or '.' string with attribute names
"""
return _get_element_by_names(source, re.split(separator, path)) | python | def get_element(source, path, separator=r'[/.]'):
"""
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (string): '/' or '.' string with attribute names
"""
return _get_element_by_names(source, re.split(separator, path)) | [
"def",
"get_element",
"(",
"source",
",",
"path",
",",
"separator",
"=",
"r'[/.]'",
")",
":",
"return",
"_get_element_by_names",
"(",
"source",
",",
"re",
".",
"split",
"(",
"separator",
",",
"path",
")",
")"
] | Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (string): '/' or '.' string with attribute names | [
"Given",
"a",
"dict",
"and",
"path",
"/",
"or",
".",
"separated",
".",
"Digs",
"into",
"de",
"dict",
"to",
"retrieve",
"the",
"specified",
"element",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L72-L81 |
Datary/scrapbag | scrapbag/collections.py | _get_element_by_names | def _get_element_by_names(source, names):
"""
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (list): list of attribute names
"""
if source is None:
return source
else:
if names:
head, *rest = names
if isinstance(source, dict) and head in source:
return _get_element_by_names(source[head], rest)
elif isinstance(source, list) and head.isdigit():
return _get_element_by_names(source[int(head)], rest)
elif not names[0]:
pass
else:
source = None
return source | python | def _get_element_by_names(source, names):
"""
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (list): list of attribute names
"""
if source is None:
return source
else:
if names:
head, *rest = names
if isinstance(source, dict) and head in source:
return _get_element_by_names(source[head], rest)
elif isinstance(source, list) and head.isdigit():
return _get_element_by_names(source[int(head)], rest)
elif not names[0]:
pass
else:
source = None
return source | [
"def",
"_get_element_by_names",
"(",
"source",
",",
"names",
")",
":",
"if",
"source",
"is",
"None",
":",
"return",
"source",
"else",
":",
"if",
"names",
":",
"head",
",",
"",
"*",
"rest",
"=",
"names",
"if",
"isinstance",
"(",
"source",
",",
"dict",
... | Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (list): list of attribute names | [
"Given",
"a",
"dict",
"and",
"path",
"/",
"or",
".",
"separated",
".",
"Digs",
"into",
"de",
"dict",
"to",
"retrieve",
"the",
"specified",
"element",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L84-L108 |
Datary/scrapbag | scrapbag/collections.py | add_element | def add_element(source, path, value, separator=r'[/.]', **kwargs):
"""
Add element into a list or dict easily using a path.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
source list or dict element where add the value.
path string path to add the value in element.
value ¿all? value to add in source.
separator regex string Regexp to divide the path.
============= ============= =======================================
Returns: source with added value
"""
return _add_element_by_names(
source,
exclude_empty_values(re.split(separator, path)),
value,
**kwargs) | python | def add_element(source, path, value, separator=r'[/.]', **kwargs):
"""
Add element into a list or dict easily using a path.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
source list or dict element where add the value.
path string path to add the value in element.
value ¿all? value to add in source.
separator regex string Regexp to divide the path.
============= ============= =======================================
Returns: source with added value
"""
return _add_element_by_names(
source,
exclude_empty_values(re.split(separator, path)),
value,
**kwargs) | [
"def",
"add_element",
"(",
"source",
",",
"path",
",",
"value",
",",
"separator",
"=",
"r'[/.]'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_add_element_by_names",
"(",
"source",
",",
"exclude_empty_values",
"(",
"re",
".",
"split",
"(",
"separator",
"... | Add element into a list or dict easily using a path.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
source list or dict element where add the value.
path string path to add the value in element.
value ¿all? value to add in source.
separator regex string Regexp to divide the path.
============= ============= =======================================
Returns: source with added value | [
"Add",
"element",
"into",
"a",
"list",
"or",
"dict",
"easily",
"using",
"a",
"path",
".",
"=============",
"=============",
"=======================================",
"Parameter",
"Type",
"Description",
"=============",
"=============",
"======================================... | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L111-L129 |
Datary/scrapbag | scrapbag/collections.py | _add_element_by_names | def _add_element_by_names(src, names, value, override=False, digit=True):
"""
Internal method recursive to Add element into a list or dict easily using
a path.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
src list or dict element where add the value.
names list list with names to navigate in src.
value ¿all? value to add in src.
override boolean Override the value in path src.
============= ============= =======================================
Returns: src with added value
"""
if src is None:
return False
else:
if names and names[0]:
head, *rest = names
# list and digit head
if isinstance(src, list):
if force_list(digit)[0] and head.isdigit():
head = int(head)
# if src is a list and lenght <= head
if len(src) <= head:
src.extend([""] * (head + 1 - len(src)))
# head not in src :(
elif isinstance(src, dict):
if head not in src:
src[head] = [""] * (int(rest[0]) + 1) if rest and force_list(digit)[0] and rest[0].isdigit() else {}
# more heads in rest
if rest:
# Head find but isn't a dict or list to navigate for it.
if not isinstance(src[head], (dict, list)):
# only could be str for dict or int for list
src[head] = [""] * (int(rest[0]) + 1) if force_list(digit)[0] and rest[0].isdigit() else {}
digit = digit if not digit or not isinstance(digit, list) else digit[1:]
if not force_list(digit)[0] and rest and str(rest[0]).isdigit() and isinstance(src[head], list) and override:
src[head] = {}
_add_element_by_names(src[head], rest, value, override=override, digit=digit)
else:
digit = digit if not digit or not isinstance(digit, list) else digit[1:]
if not force_list(digit)[0] and rest and str(rest[0]).isdigit() and isinstance(src[head], list) and override:
src[head] = {}
_add_element_by_names(src[head], rest, value, override=override, digit=digit)
# it's final head
else:
if not override:
if isinstance(src, list) and isinstance(head, int):
if src[head] == '':
src[head] = value
else:
src.append(value)
elif isinstance(src[head], list):
src[head].append(value)
elif isinstance(src[head], dict) and isinstance(value, dict):
src[head].update(value)
else:
src[head] = value
else:
src[head] = value
return src | python | def _add_element_by_names(src, names, value, override=False, digit=True):
"""
Internal method recursive to Add element into a list or dict easily using
a path.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
src list or dict element where add the value.
names list list with names to navigate in src.
value ¿all? value to add in src.
override boolean Override the value in path src.
============= ============= =======================================
Returns: src with added value
"""
if src is None:
return False
else:
if names and names[0]:
head, *rest = names
# list and digit head
if isinstance(src, list):
if force_list(digit)[0] and head.isdigit():
head = int(head)
# if src is a list and lenght <= head
if len(src) <= head:
src.extend([""] * (head + 1 - len(src)))
# head not in src :(
elif isinstance(src, dict):
if head not in src:
src[head] = [""] * (int(rest[0]) + 1) if rest and force_list(digit)[0] and rest[0].isdigit() else {}
# more heads in rest
if rest:
# Head find but isn't a dict or list to navigate for it.
if not isinstance(src[head], (dict, list)):
# only could be str for dict or int for list
src[head] = [""] * (int(rest[0]) + 1) if force_list(digit)[0] and rest[0].isdigit() else {}
digit = digit if not digit or not isinstance(digit, list) else digit[1:]
if not force_list(digit)[0] and rest and str(rest[0]).isdigit() and isinstance(src[head], list) and override:
src[head] = {}
_add_element_by_names(src[head], rest, value, override=override, digit=digit)
else:
digit = digit if not digit or not isinstance(digit, list) else digit[1:]
if not force_list(digit)[0] and rest and str(rest[0]).isdigit() and isinstance(src[head], list) and override:
src[head] = {}
_add_element_by_names(src[head], rest, value, override=override, digit=digit)
# it's final head
else:
if not override:
if isinstance(src, list) and isinstance(head, int):
if src[head] == '':
src[head] = value
else:
src.append(value)
elif isinstance(src[head], list):
src[head].append(value)
elif isinstance(src[head], dict) and isinstance(value, dict):
src[head].update(value)
else:
src[head] = value
else:
src[head] = value
return src | [
"def",
"_add_element_by_names",
"(",
"src",
",",
"names",
",",
"value",
",",
"override",
"=",
"False",
",",
"digit",
"=",
"True",
")",
":",
"if",
"src",
"is",
"None",
":",
"return",
"False",
"else",
":",
"if",
"names",
"and",
"names",
"[",
"0",
"]",
... | Internal method recursive to Add element into a list or dict easily using
a path.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
src list or dict element where add the value.
names list list with names to navigate in src.
value ¿all? value to add in src.
override boolean Override the value in path src.
============= ============= =======================================
Returns: src with added value | [
"Internal",
"method",
"recursive",
"to",
"Add",
"element",
"into",
"a",
"list",
"or",
"dict",
"easily",
"using",
"a",
"path",
".",
"=============",
"=============",
"=======================================",
"Parameter",
"Type",
"Description",
"=============",
"========... | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L132-L218 |
Datary/scrapbag | scrapbag/collections.py | format_dict | def format_dict(dic, format_list, separator=',', default_value=str):
"""
Format dict to string passing a list of keys as order
Args:
lista: List with elements to clean duplicates.
"""
dic = collections.defaultdict(default_value, dic)
str_format = separator.join(["{" + "{}".format(head) + "}" for head in format_list])
return str_format.format(**dic) | python | def format_dict(dic, format_list, separator=',', default_value=str):
"""
Format dict to string passing a list of keys as order
Args:
lista: List with elements to clean duplicates.
"""
dic = collections.defaultdict(default_value, dic)
str_format = separator.join(["{" + "{}".format(head) + "}" for head in format_list])
return str_format.format(**dic) | [
"def",
"format_dict",
"(",
"dic",
",",
"format_list",
",",
"separator",
"=",
"','",
",",
"default_value",
"=",
"str",
")",
":",
"dic",
"=",
"collections",
".",
"defaultdict",
"(",
"default_value",
",",
"dic",
")",
"str_format",
"=",
"separator",
".",
"join... | Format dict to string passing a list of keys as order
Args:
lista: List with elements to clean duplicates. | [
"Format",
"dict",
"to",
"string",
"passing",
"a",
"list",
"of",
"keys",
"as",
"order",
"Args",
":",
"lista",
":",
"List",
"with",
"elements",
"to",
"clean",
"duplicates",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L221-L232 |
Datary/scrapbag | scrapbag/collections.py | force_list | def force_list(element):
"""
Given an element or a list, concatenates every element and clean it to
create a full text
"""
if element is None:
return []
if isinstance(element, (collections.Iterator, list)):
return element
return [element] | python | def force_list(element):
"""
Given an element or a list, concatenates every element and clean it to
create a full text
"""
if element is None:
return []
if isinstance(element, (collections.Iterator, list)):
return element
return [element] | [
"def",
"force_list",
"(",
"element",
")",
":",
"if",
"element",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"element",
",",
"(",
"collections",
".",
"Iterator",
",",
"list",
")",
")",
":",
"return",
"element",
"return",
"[",
"elemen... | Given an element or a list, concatenates every element and clean it to
create a full text | [
"Given",
"an",
"element",
"or",
"a",
"list",
"concatenates",
"every",
"element",
"and",
"clean",
"it",
"to",
"create",
"a",
"full",
"text"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L235-L246 |
Datary/scrapbag | scrapbag/collections.py | chunks | def chunks(lista, size):
"""Yield successive n-sized chunks from l."""
if not isinstance(lista, list):
logger.error('Erron in chunks, arg introduced is not a list.', lista=lista)
return lista
for i in range(0, len(lista), size):
yield lista[i:i + size] | python | def chunks(lista, size):
"""Yield successive n-sized chunks from l."""
if not isinstance(lista, list):
logger.error('Erron in chunks, arg introduced is not a list.', lista=lista)
return lista
for i in range(0, len(lista), size):
yield lista[i:i + size] | [
"def",
"chunks",
"(",
"lista",
",",
"size",
")",
":",
"if",
"not",
"isinstance",
"(",
"lista",
",",
"list",
")",
":",
"logger",
".",
"error",
"(",
"'Erron in chunks, arg introduced is not a list.'",
",",
"lista",
"=",
"lista",
")",
"return",
"lista",
"for",
... | Yield successive n-sized chunks from l. | [
"Yield",
"successive",
"n",
"-",
"sized",
"chunks",
"from",
"l",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L282-L289 |
Datary/scrapbag | scrapbag/collections.py | flatten | def flatten(data, parent_key='', sep='_'):
"""
Transform dictionary multilevel values to one level dict, concatenating
the keys with sep between them.
"""
items = []
if isinstance(data, list):
logger.debug('Flattening list {}'.format(data))
list_keys = [str(i) for i in range(0, len(data))]
items.extend(
flatten(dict(zip(list_keys, data)), parent_key, sep=sep).items())
elif isinstance(data, dict):
logger.debug('Flattening dict {}'.format(data))
for key, value in data.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(value, collections.MutableMapping):
items.extend(flatten(value, new_key, sep=sep).items())
else:
if isinstance(value, list):
list_keys = [str(i) for i in range(0, len(value))]
items.extend(
flatten(
dict(zip(list_keys, value)), new_key, sep=sep).items())
else:
items.append((new_key, value))
else:
logger.debug('Nothing to flatten with {}'.format(data))
return data
return collections.OrderedDict(items) | python | def flatten(data, parent_key='', sep='_'):
"""
Transform dictionary multilevel values to one level dict, concatenating
the keys with sep between them.
"""
items = []
if isinstance(data, list):
logger.debug('Flattening list {}'.format(data))
list_keys = [str(i) for i in range(0, len(data))]
items.extend(
flatten(dict(zip(list_keys, data)), parent_key, sep=sep).items())
elif isinstance(data, dict):
logger.debug('Flattening dict {}'.format(data))
for key, value in data.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(value, collections.MutableMapping):
items.extend(flatten(value, new_key, sep=sep).items())
else:
if isinstance(value, list):
list_keys = [str(i) for i in range(0, len(value))]
items.extend(
flatten(
dict(zip(list_keys, value)), new_key, sep=sep).items())
else:
items.append((new_key, value))
else:
logger.debug('Nothing to flatten with {}'.format(data))
return data
return collections.OrderedDict(items) | [
"def",
"flatten",
"(",
"data",
",",
"parent_key",
"=",
"''",
",",
"sep",
"=",
"'_'",
")",
":",
"items",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"logger",
".",
"debug",
"(",
"'Flattening list {}'",
".",
"format",
"(",
... | Transform dictionary multilevel values to one level dict, concatenating
the keys with sep between them. | [
"Transform",
"dictionary",
"multilevel",
"values",
"to",
"one",
"level",
"dict",
"concatenating",
"the",
"keys",
"with",
"sep",
"between",
"them",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L292-L324 |
Datary/scrapbag | scrapbag/collections.py | nested_dict_to_list | def nested_dict_to_list(path, dic, exclusion=None):
"""
Transform nested dict to list
"""
result = []
exclusion = ['__self'] if exclusion is None else exclusion
for key, value in dic.items():
if not any([exclude in key for exclude in exclusion]):
if isinstance(value, dict):
aux = path + key + "/"
result.extend(nested_dict_to_list(aux, value))
else:
if path.endswith("/"):
path = path[:-1]
result.append([path, key, value])
return result | python | def nested_dict_to_list(path, dic, exclusion=None):
"""
Transform nested dict to list
"""
result = []
exclusion = ['__self'] if exclusion is None else exclusion
for key, value in dic.items():
if not any([exclude in key for exclude in exclusion]):
if isinstance(value, dict):
aux = path + key + "/"
result.extend(nested_dict_to_list(aux, value))
else:
if path.endswith("/"):
path = path[:-1]
result.append([path, key, value])
return result | [
"def",
"nested_dict_to_list",
"(",
"path",
",",
"dic",
",",
"exclusion",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"exclusion",
"=",
"[",
"'__self'",
"]",
"if",
"exclusion",
"is",
"None",
"else",
"exclusion",
"for",
"key",
",",
"value",
"in",
"di... | Transform nested dict to list | [
"Transform",
"nested",
"dict",
"to",
"list"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L345-L364 |
Datary/scrapbag | scrapbag/collections.py | find_value_in_object | def find_value_in_object(attr, obj):
"""Return values for any key coincidence with attr in obj or any other
nested dict.
"""
# Carry on inspecting inside the list or tuple
if isinstance(obj, (collections.Iterator, list)):
for item in obj:
yield from find_value_in_object(attr, item)
# Final object (dict or entity) inspect inside
elif isinstance(obj, collections.Mapping):
# If result is found, inspect inside and return inner results
if attr in obj:
# If it is iterable, just return the inner elements (avoid nested
# lists)
if isinstance(obj[attr], (collections.Iterator, list)):
for item in obj[attr]:
yield item
# If not, return just the objects
else:
yield obj[attr]
# Carry on inspecting inside the object
for item in obj.values():
if item:
yield from find_value_in_object(attr, item) | python | def find_value_in_object(attr, obj):
"""Return values for any key coincidence with attr in obj or any other
nested dict.
"""
# Carry on inspecting inside the list or tuple
if isinstance(obj, (collections.Iterator, list)):
for item in obj:
yield from find_value_in_object(attr, item)
# Final object (dict or entity) inspect inside
elif isinstance(obj, collections.Mapping):
# If result is found, inspect inside and return inner results
if attr in obj:
# If it is iterable, just return the inner elements (avoid nested
# lists)
if isinstance(obj[attr], (collections.Iterator, list)):
for item in obj[attr]:
yield item
# If not, return just the objects
else:
yield obj[attr]
# Carry on inspecting inside the object
for item in obj.values():
if item:
yield from find_value_in_object(attr, item) | [
"def",
"find_value_in_object",
"(",
"attr",
",",
"obj",
")",
":",
"# Carry on inspecting inside the list or tuple",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"collections",
".",
"Iterator",
",",
"list",
")",
")",
":",
"for",
"item",
"in",
"obj",
":",
"yield",
... | Return values for any key coincidence with attr in obj or any other
nested dict. | [
"Return",
"values",
"for",
"any",
"key",
"coincidence",
"with",
"attr",
"in",
"obj",
"or",
"any",
"other",
"nested",
"dict",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L367-L396 |
Datary/scrapbag | scrapbag/collections.py | remove_list_duplicates | def remove_list_duplicates(lista, unique=False):
"""
Remove duplicated elements in a list.
Args:
lista: List with elements to clean duplicates.
"""
result = []
allready = []
for elem in lista:
if elem not in result:
result.append(elem)
else:
allready.append(elem)
if unique:
for elem in allready:
result = list(filter((elem).__ne__, result))
return result | python | def remove_list_duplicates(lista, unique=False):
"""
Remove duplicated elements in a list.
Args:
lista: List with elements to clean duplicates.
"""
result = []
allready = []
for elem in lista:
if elem not in result:
result.append(elem)
else:
allready.append(elem)
if unique:
for elem in allready:
result = list(filter((elem).__ne__, result))
return result | [
"def",
"remove_list_duplicates",
"(",
"lista",
",",
"unique",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"allready",
"=",
"[",
"]",
"for",
"elem",
"in",
"lista",
":",
"if",
"elem",
"not",
"in",
"result",
":",
"result",
".",
"append",
"(",
"elem... | Remove duplicated elements in a list.
Args:
lista: List with elements to clean duplicates. | [
"Remove",
"duplicated",
"elements",
"in",
"a",
"list",
".",
"Args",
":",
"lista",
":",
"List",
"with",
"elements",
"to",
"clean",
"duplicates",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L399-L418 |
Datary/scrapbag | scrapbag/collections.py | dict2orderedlist | def dict2orderedlist(dic, order_list, default='', **kwargs):
"""
Return a list with dict values ordered by a list of key passed in args.
"""
result = []
for key_order in order_list:
value = get_element(dic, key_order, **kwargs)
result.append(value if value is not None else default)
return result | python | def dict2orderedlist(dic, order_list, default='', **kwargs):
"""
Return a list with dict values ordered by a list of key passed in args.
"""
result = []
for key_order in order_list:
value = get_element(dic, key_order, **kwargs)
result.append(value if value is not None else default)
return result | [
"def",
"dict2orderedlist",
"(",
"dic",
",",
"order_list",
",",
"default",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"key_order",
"in",
"order_list",
":",
"value",
"=",
"get_element",
"(",
"dic",
",",
"key_order",
","... | Return a list with dict values ordered by a list of key passed in args. | [
"Return",
"a",
"list",
"with",
"dict",
"values",
"ordered",
"by",
"a",
"list",
"of",
"key",
"passed",
"in",
"args",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L421-L429 |
Datary/scrapbag | scrapbag/collections.py | get_dimension | def get_dimension(data):
"""
Get dimension of the data passed by argument independently if it's an
arrays or dictionaries
"""
result = [0, 0]
if isinstance(data, list):
result = get_dimension_array(data)
elif isinstance(data, dict):
result = get_dimension_dict(data)
return result | python | def get_dimension(data):
"""
Get dimension of the data passed by argument independently if it's an
arrays or dictionaries
"""
result = [0, 0]
if isinstance(data, list):
result = get_dimension_array(data)
elif isinstance(data, dict):
result = get_dimension_dict(data)
return result | [
"def",
"get_dimension",
"(",
"data",
")",
":",
"result",
"=",
"[",
"0",
",",
"0",
"]",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"result",
"=",
"get_dimension_array",
"(",
"data",
")",
"elif",
"isinstance",
"(",
"data",
",",
"dict",
")"... | Get dimension of the data passed by argument independently if it's an
arrays or dictionaries | [
"Get",
"dimension",
"of",
"the",
"data",
"passed",
"by",
"argument",
"independently",
"if",
"it",
"s",
"an",
"arrays",
"or",
"dictionaries"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L432-L445 |
Datary/scrapbag | scrapbag/collections.py | get_dimension_array | def get_dimension_array(array):
"""
Get dimension of an array getting the number of rows and the max num of
columns.
"""
if all(isinstance(el, list) for el in array):
result = [len(array), len(max([x for x in array], key=len,))]
# elif array and isinstance(array, list):
else:
result = [len(array), 1]
return result | python | def get_dimension_array(array):
"""
Get dimension of an array getting the number of rows and the max num of
columns.
"""
if all(isinstance(el, list) for el in array):
result = [len(array), len(max([x for x in array], key=len,))]
# elif array and isinstance(array, list):
else:
result = [len(array), 1]
return result | [
"def",
"get_dimension_array",
"(",
"array",
")",
":",
"if",
"all",
"(",
"isinstance",
"(",
"el",
",",
"list",
")",
"for",
"el",
"in",
"array",
")",
":",
"result",
"=",
"[",
"len",
"(",
"array",
")",
",",
"len",
"(",
"max",
"(",
"[",
"x",
"for",
... | Get dimension of an array getting the number of rows and the max num of
columns. | [
"Get",
"dimension",
"of",
"an",
"array",
"getting",
"the",
"number",
"of",
"rows",
"and",
"the",
"max",
"num",
"of",
"columns",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L462-L474 |
Datary/scrapbag | scrapbag/collections.py | get_ldict_keys | def get_ldict_keys(ldict, flatten_keys=False, **kwargs):
"""
Get first level keys from a list of dicts
"""
result = []
for ddict in ldict:
if isinstance(ddict, dict):
if flatten_keys:
ddict = flatten(ddict, **kwargs)
result.extend(ddict.keys())
return list(set(result)) | python | def get_ldict_keys(ldict, flatten_keys=False, **kwargs):
"""
Get first level keys from a list of dicts
"""
result = []
for ddict in ldict:
if isinstance(ddict, dict):
if flatten_keys:
ddict = flatten(ddict, **kwargs)
result.extend(ddict.keys())
return list(set(result)) | [
"def",
"get_ldict_keys",
"(",
"ldict",
",",
"flatten_keys",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"ddict",
"in",
"ldict",
":",
"if",
"isinstance",
"(",
"ddict",
",",
"dict",
")",
":",
"if",
"flatten_keys",
"... | Get first level keys from a list of dicts | [
"Get",
"first",
"level",
"keys",
"from",
"a",
"list",
"of",
"dicts"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L477-L489 |
Datary/scrapbag | scrapbag/collections.py | get_alldictkeys | def get_alldictkeys(ddict, parent=None):
"""
Get all keys in a dict
"""
parent = [] if parent is None else parent
if not isinstance(ddict, dict):
return [tuple(parent)]
return reduce(
list.__add__,
[get_alldictkeys(v, parent + [k]) for k, v in ddict.items()],
[]) | python | def get_alldictkeys(ddict, parent=None):
"""
Get all keys in a dict
"""
parent = [] if parent is None else parent
if not isinstance(ddict, dict):
return [tuple(parent)]
return reduce(
list.__add__,
[get_alldictkeys(v, parent + [k]) for k, v in ddict.items()],
[]) | [
"def",
"get_alldictkeys",
"(",
"ddict",
",",
"parent",
"=",
"None",
")",
":",
"parent",
"=",
"[",
"]",
"if",
"parent",
"is",
"None",
"else",
"parent",
"if",
"not",
"isinstance",
"(",
"ddict",
",",
"dict",
")",
":",
"return",
"[",
"tuple",
"(",
"paren... | Get all keys in a dict | [
"Get",
"all",
"keys",
"in",
"a",
"dict"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L492-L503 |
Datary/scrapbag | scrapbag/collections.py | clean_dictkeys | def clean_dictkeys(ddict, exclusions=None):
"""
Exclude chars in dict keys and return a clean dictionary.
"""
exclusions = [] if exclusions is None else exclusions
if not isinstance(ddict, dict):
return {}
for key in list(ddict.keys()):
if [incl for incl in exclusions if incl in key]:
data = ddict.pop(key)
clean_key = exclude_chars(key, exclusions)
if clean_key:
if clean_key in ddict:
ddict[clean_key] = force_list(ddict[clean_key])
add_element(ddict, clean_key, data)
else:
ddict[clean_key] = data
# dict case
if isinstance(ddict.get(key), dict):
ddict[key] = clean_dictkeys(ddict[key], exclusions)
# list case
elif isinstance(ddict.get(key), list):
for row in ddict[key]:
if isinstance(row, dict):
row = clean_dictkeys(row, exclusions)
return ddict | python | def clean_dictkeys(ddict, exclusions=None):
"""
Exclude chars in dict keys and return a clean dictionary.
"""
exclusions = [] if exclusions is None else exclusions
if not isinstance(ddict, dict):
return {}
for key in list(ddict.keys()):
if [incl for incl in exclusions if incl in key]:
data = ddict.pop(key)
clean_key = exclude_chars(key, exclusions)
if clean_key:
if clean_key in ddict:
ddict[clean_key] = force_list(ddict[clean_key])
add_element(ddict, clean_key, data)
else:
ddict[clean_key] = data
# dict case
if isinstance(ddict.get(key), dict):
ddict[key] = clean_dictkeys(ddict[key], exclusions)
# list case
elif isinstance(ddict.get(key), list):
for row in ddict[key]:
if isinstance(row, dict):
row = clean_dictkeys(row, exclusions)
return ddict | [
"def",
"clean_dictkeys",
"(",
"ddict",
",",
"exclusions",
"=",
"None",
")",
":",
"exclusions",
"=",
"[",
"]",
"if",
"exclusions",
"is",
"None",
"else",
"exclusions",
"if",
"not",
"isinstance",
"(",
"ddict",
",",
"dict",
")",
":",
"return",
"{",
"}",
"f... | Exclude chars in dict keys and return a clean dictionary. | [
"Exclude",
"chars",
"in",
"dict",
"keys",
"and",
"return",
"a",
"clean",
"dictionary",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/collections.py#L506-L537 |
robehickman/simple-http-file-sync | shttpfs/client.py | authenticate | def authenticate(previous_token = None):
""" Authenticate the client to the server """
# if we already have a session token, try to authenticate with it
if previous_token != None:
headers = server_connection.request("authenticate", {
'session_token' : previous_token,
'repository' : config['repository']})[1] # Only care about headers
if headers['status'] == 'ok':
return previous_token
# If the session token has expired, or if we don't have one, re-authenticate
headers = server_connection.request("begin_auth", {'repository' : config['repository']})[1] # Only care about headers
if headers['status'] == 'ok':
signature = base64.b64encode(pysodium.crypto_sign_detached(headers['auth_token'].decode('utf-8'), config['private_key']))
headers = server_connection.request("authenticate", {
'auth_token' : headers['auth_token'],
'signature' : signature,
'user' : config['user'],
'repository' : config['repository']})[1] # Only care about headers
if headers['status'] == 'ok': return headers['session_token']
raise SystemExit('Authentication failed') | python | def authenticate(previous_token = None):
""" Authenticate the client to the server """
# if we already have a session token, try to authenticate with it
if previous_token != None:
headers = server_connection.request("authenticate", {
'session_token' : previous_token,
'repository' : config['repository']})[1] # Only care about headers
if headers['status'] == 'ok':
return previous_token
# If the session token has expired, or if we don't have one, re-authenticate
headers = server_connection.request("begin_auth", {'repository' : config['repository']})[1] # Only care about headers
if headers['status'] == 'ok':
signature = base64.b64encode(pysodium.crypto_sign_detached(headers['auth_token'].decode('utf-8'), config['private_key']))
headers = server_connection.request("authenticate", {
'auth_token' : headers['auth_token'],
'signature' : signature,
'user' : config['user'],
'repository' : config['repository']})[1] # Only care about headers
if headers['status'] == 'ok': return headers['session_token']
raise SystemExit('Authentication failed') | [
"def",
"authenticate",
"(",
"previous_token",
"=",
"None",
")",
":",
"# if we already have a session token, try to authenticate with it",
"if",
"previous_token",
"!=",
"None",
":",
"headers",
"=",
"server_connection",
".",
"request",
"(",
"\"authenticate\"",
",",
"{",
"... | Authenticate the client to the server | [
"Authenticate",
"the",
"client",
"to",
"the",
"server"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/client.py#L43-L68 |
robehickman/simple-http-file-sync | shttpfs/client.py | find_local_changes | def find_local_changes():
""" Find things that have changed since the last run, applying ignore filters """
manifest = data_store.read_local_manifest()
old_state = manifest['files']
current_state = get_file_list(config['data_dir'])
current_state = [fle for fle in current_state if not
next((True for flter in config['ignore_filters']
if fnmatch.fnmatch(fle['path'], flter)), False)]
return manifest, find_manifest_changes(current_state, old_state) | python | def find_local_changes():
""" Find things that have changed since the last run, applying ignore filters """
manifest = data_store.read_local_manifest()
old_state = manifest['files']
current_state = get_file_list(config['data_dir'])
current_state = [fle for fle in current_state if not
next((True for flter in config['ignore_filters']
if fnmatch.fnmatch(fle['path'], flter)), False)]
return manifest, find_manifest_changes(current_state, old_state) | [
"def",
"find_local_changes",
"(",
")",
":",
"manifest",
"=",
"data_store",
".",
"read_local_manifest",
"(",
")",
"old_state",
"=",
"manifest",
"[",
"'files'",
"]",
"current_state",
"=",
"get_file_list",
"(",
"config",
"[",
"'data_dir'",
"]",
")",
"current_state"... | Find things that have changed since the last run, applying ignore filters | [
"Find",
"things",
"that",
"have",
"changed",
"since",
"the",
"last",
"run",
"applying",
"ignore",
"filters"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/client.py#L72-L81 |
robehickman/simple-http-file-sync | shttpfs/client.py | update | def update(session_token, testing = False):
""" Compare changes on the client to changes on the server and update local files
which have changed on the server. """
conflict_comparison_file_dest = cpjoin(config['data_dir'], '.shttpfs', 'conflict_files')
conflict_resolution_path = cpjoin(config['data_dir'], '.shttpfs', 'conflict_resolution.json')
conflict_resolutions = file_or_default(conflict_resolution_path, [], json.loads)
# Make sure that all conflicts have been resolved, reject if not
if not all(len(c['4_resolution']) == 1 for c in conflict_resolutions): conflict_resolutions = []
# Send the changes and the revision of the most recent update to the server to find changes
manifest, client_changes = find_local_changes()
req_result, headers = server_connection.request("find_changed", {
"session_token" : session_token,
'repository' : config['repository'],
"previous_revision" : manifest['have_revision'],
}, {
"client_changes" : json.dumps(client_changes),
"conflict_resolutions" : json.dumps(conflict_resolutions)})
if headers['status'] != 'ok':
if headers['msg'] == 'Please resolve conflicts':
raise SystemExit('Server error: Please resolve conflicts in .shttpfs/conflict_resolution.json')
else:
raise SystemExit('Server error')
result = json.loads(req_result)
changes = result['sorted_changes']
# Are there any changes?
if all(v == [] for k,v in changes.iteritems()):
print 'Nothing to update'
return
# Pull and delete from remote to local
if changes['client_pull_files'] != []:
# Filter out pull ignore files
filtered_pull_files = []
for fle in changes['client_pull_files']:
if not next((True for flter in config['pull_ignore_filters'] if fnmatch.fnmatch(fle['path'], flter)), False):
filtered_pull_files.append(fle)
else: # log ignored items to give the opportunity to pull them in the future
with open(cpjoin(working_copy_base_path, '.shttpfs', 'pull_ignored_items'), 'a') as pull_ignore_log:
pull_ignore_log.write(json.dumps((result['head'], fle)))
pull_ignore_log.flush()
if filtered_pull_files != []:
print 'Pulling files from server...'
#----------
for fle in filtered_pull_files:
print 'Pulling file: ' + fle['path']
req_result, headers = server_connection.request("pull_file", {
'session_token' : session_token,
'repository' : config['repository'],
'path' : fle['path']}, gen = True)
if headers['status'] != 'ok':
raise SystemExit('Failed to pull file')
else:
make_dirs_if_dont_exist(data_store.get_full_file_path(cpjoin(*fle['path'].split('/')[:-1]) + '/'))
data_store.fs_put(fle['path'], req_result)
# Files which have been deleted on server and need deleting on client
if changes['to_delete_on_client'] != []:
print 'Removing files deleted on the server...'
for fle in changes['to_delete_on_client']:
print 'Deleting file: ' + fle['path']
try: data_store.fs_delete(fle['path'])
except OSError: print 'Warning: remote deleted file does not exist locally.'
# Delete the folder if it is now empty
try: os.removedirs(os.path.dirname(data_store.get_full_file_path(fle['path'])))
except OSError as e:
if e.errno not in [errno.ENOTEMPTY, errno.ENOENT]: raise
# Files which are in conflict
if changes['conflict_files'] != []:
print "There are conflicts!\n"
out = []; server_versions = []
for fle in changes['conflict_files']:
fle['resolution'] = ['local', 'remote']
print 'Path: ' + fle['file_info']['path']
print 'Client status: ' + fle['client_status']
print 'Server status: ' + fle['server_status']
print
out.append({'1_path' : fle['file_info']['path'],
'2_client_status' : fle['client_status'],
'3_server_status' : fle['server_status'],
'4_resolution' : ['client', 'server']})
if fle['server_status'] == 'Changed': server_versions.append(fle['file_info'])
#===============
if server_versions != []:
choice = None
if not testing:
while True:
print 'Download server versions for comparison? (Y/N)'
choice = raw_input()
if choice.lower() in ['y', 'n']: break
else: choice = 'y'
errors = []
if choice == 'y':
for fle in server_versions:
print 'Pulling file: ' + fle['path']
result, headers = server_connection.request("pull_file", {
'session_token' : session_token,
'repository' : config['repository'],
'path' : fle['path']}, gen = True)
if headers['status'] != 'ok':
errors.append(fle['path'])
else:
make_dirs_if_dont_exist(cpjoin(conflict_comparison_file_dest, *fle['path'].split('/')[:-1]) + '/')
result(cpjoin(conflict_comparison_file_dest, fle['path']))
print 'Server versions of conflicting files written to .shttpfs/conflict_files\n'
pprint(errors)
# ====================
file_put_contents(conflict_resolution_path, json.dumps(out, indent=4, sort_keys=True))
raise SystemExit("Conflict resolution file written to .shttpfs/conflict_resolution.json\n" +
"Please edit this file removing 'client', or 'server' to choose which version to retain.")
# Update the latest revision in the manifest only if there are no conflicts
else:
data_store.begin()
manifest = data_store.read_local_manifest()
manifest['have_revision'] = result['head']
data_store.write_local_manifest(manifest)
data_store.commit()
#delete the conflicts resolution file and recursively delete any conflict files downloaded for comparison
ignore(os.remove, conflict_resolution_path)
ignore(shutil.rmtree, conflict_comparison_file_dest)
if changes['to_delete_on_server'] != [] or changes['client_push_files'] != []:
print 'There are local changes to commit'
else:
print 'Update OK' | python | def update(session_token, testing = False):
""" Compare changes on the client to changes on the server and update local files
which have changed on the server. """
conflict_comparison_file_dest = cpjoin(config['data_dir'], '.shttpfs', 'conflict_files')
conflict_resolution_path = cpjoin(config['data_dir'], '.shttpfs', 'conflict_resolution.json')
conflict_resolutions = file_or_default(conflict_resolution_path, [], json.loads)
# Make sure that all conflicts have been resolved, reject if not
if not all(len(c['4_resolution']) == 1 for c in conflict_resolutions): conflict_resolutions = []
# Send the changes and the revision of the most recent update to the server to find changes
manifest, client_changes = find_local_changes()
req_result, headers = server_connection.request("find_changed", {
"session_token" : session_token,
'repository' : config['repository'],
"previous_revision" : manifest['have_revision'],
}, {
"client_changes" : json.dumps(client_changes),
"conflict_resolutions" : json.dumps(conflict_resolutions)})
if headers['status'] != 'ok':
if headers['msg'] == 'Please resolve conflicts':
raise SystemExit('Server error: Please resolve conflicts in .shttpfs/conflict_resolution.json')
else:
raise SystemExit('Server error')
result = json.loads(req_result)
changes = result['sorted_changes']
# Are there any changes?
if all(v == [] for k,v in changes.iteritems()):
print 'Nothing to update'
return
# Pull and delete from remote to local
if changes['client_pull_files'] != []:
# Filter out pull ignore files
filtered_pull_files = []
for fle in changes['client_pull_files']:
if not next((True for flter in config['pull_ignore_filters'] if fnmatch.fnmatch(fle['path'], flter)), False):
filtered_pull_files.append(fle)
else: # log ignored items to give the opportunity to pull them in the future
with open(cpjoin(working_copy_base_path, '.shttpfs', 'pull_ignored_items'), 'a') as pull_ignore_log:
pull_ignore_log.write(json.dumps((result['head'], fle)))
pull_ignore_log.flush()
if filtered_pull_files != []:
print 'Pulling files from server...'
#----------
for fle in filtered_pull_files:
print 'Pulling file: ' + fle['path']
req_result, headers = server_connection.request("pull_file", {
'session_token' : session_token,
'repository' : config['repository'],
'path' : fle['path']}, gen = True)
if headers['status'] != 'ok':
raise SystemExit('Failed to pull file')
else:
make_dirs_if_dont_exist(data_store.get_full_file_path(cpjoin(*fle['path'].split('/')[:-1]) + '/'))
data_store.fs_put(fle['path'], req_result)
# Files which have been deleted on server and need deleting on client
if changes['to_delete_on_client'] != []:
print 'Removing files deleted on the server...'
for fle in changes['to_delete_on_client']:
print 'Deleting file: ' + fle['path']
try: data_store.fs_delete(fle['path'])
except OSError: print 'Warning: remote deleted file does not exist locally.'
# Delete the folder if it is now empty
try: os.removedirs(os.path.dirname(data_store.get_full_file_path(fle['path'])))
except OSError as e:
if e.errno not in [errno.ENOTEMPTY, errno.ENOENT]: raise
# Files which are in conflict
if changes['conflict_files'] != []:
print "There are conflicts!\n"
out = []; server_versions = []
for fle in changes['conflict_files']:
fle['resolution'] = ['local', 'remote']
print 'Path: ' + fle['file_info']['path']
print 'Client status: ' + fle['client_status']
print 'Server status: ' + fle['server_status']
print
out.append({'1_path' : fle['file_info']['path'],
'2_client_status' : fle['client_status'],
'3_server_status' : fle['server_status'],
'4_resolution' : ['client', 'server']})
if fle['server_status'] == 'Changed': server_versions.append(fle['file_info'])
#===============
if server_versions != []:
choice = None
if not testing:
while True:
print 'Download server versions for comparison? (Y/N)'
choice = raw_input()
if choice.lower() in ['y', 'n']: break
else: choice = 'y'
errors = []
if choice == 'y':
for fle in server_versions:
print 'Pulling file: ' + fle['path']
result, headers = server_connection.request("pull_file", {
'session_token' : session_token,
'repository' : config['repository'],
'path' : fle['path']}, gen = True)
if headers['status'] != 'ok':
errors.append(fle['path'])
else:
make_dirs_if_dont_exist(cpjoin(conflict_comparison_file_dest, *fle['path'].split('/')[:-1]) + '/')
result(cpjoin(conflict_comparison_file_dest, fle['path']))
print 'Server versions of conflicting files written to .shttpfs/conflict_files\n'
pprint(errors)
# ====================
file_put_contents(conflict_resolution_path, json.dumps(out, indent=4, sort_keys=True))
raise SystemExit("Conflict resolution file written to .shttpfs/conflict_resolution.json\n" +
"Please edit this file removing 'client', or 'server' to choose which version to retain.")
# Update the latest revision in the manifest only if there are no conflicts
else:
data_store.begin()
manifest = data_store.read_local_manifest()
manifest['have_revision'] = result['head']
data_store.write_local_manifest(manifest)
data_store.commit()
#delete the conflicts resolution file and recursively delete any conflict files downloaded for comparison
ignore(os.remove, conflict_resolution_path)
ignore(shutil.rmtree, conflict_comparison_file_dest)
if changes['to_delete_on_server'] != [] or changes['client_push_files'] != []:
print 'There are local changes to commit'
else:
print 'Update OK' | [
"def",
"update",
"(",
"session_token",
",",
"testing",
"=",
"False",
")",
":",
"conflict_comparison_file_dest",
"=",
"cpjoin",
"(",
"config",
"[",
"'data_dir'",
"]",
",",
"'.shttpfs'",
",",
"'conflict_files'",
")",
"conflict_resolution_path",
"=",
"cpjoin",
"(",
... | Compare changes on the client to changes on the server and update local files
which have changed on the server. | [
"Compare",
"changes",
"on",
"the",
"client",
"to",
"changes",
"on",
"the",
"server",
"and",
"update",
"local",
"files",
"which",
"have",
"changed",
"on",
"the",
"server",
"."
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/client.py#L85-L235 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.