repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
bitlabstudio/django-libs
django_libs/utils/text.py
create_random_string
def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789', repetitions=False): """ Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided. ...
python
def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789', repetitions=False): """ Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided. ...
[ "def", "create_random_string", "(", "length", "=", "7", ",", "chars", "=", "'ABCDEFGHJKMNPQRSTUVWXYZ23456789'", ",", "repetitions", "=", "False", ")", ":", "if", "repetitions", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")"...
Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided.
[ "Returns", "a", "random", "string", "based", "on", "the", "provided", "arguments", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/text.py#L5-L16
train
Returns a random string based on the provided arguments.
bitlabstudio/django-libs
django_libs/loaders.py
load_member
def load_member(fqn): """Loads and returns a class for a given fully qualified name.""" modulename, member_name = split_fqn(fqn) module = __import__(modulename, globals(), locals(), member_name) return getattr(module, member_name)
python
def load_member(fqn): """Loads and returns a class for a given fully qualified name.""" modulename, member_name = split_fqn(fqn) module = __import__(modulename, globals(), locals(), member_name) return getattr(module, member_name)
[ "def", "load_member", "(", "fqn", ")", ":", "modulename", ",", "member_name", "=", "split_fqn", "(", "fqn", ")", "module", "=", "__import__", "(", "modulename", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "member_name", ")", "return", "getatt...
Loads and returns a class for a given fully qualified name.
[ "Loads", "and", "returns", "a", "class", "for", "a", "given", "fully", "qualified", "name", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/loaders.py#L5-L9
train
Loads and returns a class for a given fully qualified name.
bitlabstudio/django-libs
django_libs/loaders.py
split_fqn
def split_fqn(fqn): """ Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string. """ if hasattr(fqn, '__call__'): fqn_string = fqn() else: fqn_string = fqn return...
python
def split_fqn(fqn): """ Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string. """ if hasattr(fqn, '__call__'): fqn_string = fqn() else: fqn_string = fqn return...
[ "def", "split_fqn", "(", "fqn", ")", ":", "if", "hasattr", "(", "fqn", ",", "'__call__'", ")", ":", "fqn_string", "=", "fqn", "(", ")", "else", ":", "fqn_string", "=", "fqn", "return", "fqn_string", ".", "rsplit", "(", "'.'", ",", "1", ")" ]
Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string.
[ "Returns", "the", "left", "and", "right", "part", "of", "the", "import", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/loaders.py#L18-L30
train
Returns the left and right part of the import.
mozillazg/python-shanbay
shanbay/team.py
Team.info
def info(self): """小组信息 :return: 小组信息 :rtype: dict 返回值示例 :: { 'title': u'title', # 标题 'leader': u'leader', # 组长 'date_created': datetime.datetime(2013, 10, 6, 0, 0), # 创建日期 'rank': 1000, # 排名 'number':...
python
def info(self): """小组信息 :return: 小组信息 :rtype: dict 返回值示例 :: { 'title': u'title', # 标题 'leader': u'leader', # 组长 'date_created': datetime.datetime(2013, 10, 6, 0, 0), # 创建日期 'rank': 1000, # 排名 'number':...
[ "def", "info", "(", "self", ")", ":", "html", "=", "self", ".", "request", "(", "self", ".", "team_url", ")", ".", "text", "soup", "=", "BeautifulSoup", "(", "html", ")", "team_header", "=", "soup", ".", "find_all", "(", "class_", "=", "'team-header'",...
小组信息 :return: 小组信息 :rtype: dict 返回值示例 :: { 'title': u'title', # 标题 'leader': u'leader', # 组长 'date_created': datetime.datetime(2013, 10, 6, 0, 0), # 创建日期 'rank': 1000, # 排名 'number': 10, # 当前成员数 ...
[ "小组信息" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L44-L98
train
Get info about the current nation.
mozillazg/python-shanbay
shanbay/team.py
Team.update_limit
def update_limit(self, days, kind=2, condition='>='): """更新成员加入条件 :rtype: bool """ url = 'http://www.shanbay.com/team/setqualification/%s' % self.team_id data = { 'kind': kind, 'condition': condition, 'value': days, 'team': self.te...
python
def update_limit(self, days, kind=2, condition='>='): """更新成员加入条件 :rtype: bool """ url = 'http://www.shanbay.com/team/setqualification/%s' % self.team_id data = { 'kind': kind, 'condition': condition, 'value': days, 'team': self.te...
[ "def", "update_limit", "(", "self", ",", "days", ",", "kind", "=", "2", ",", "condition", "=", "'>='", ")", ":", "url", "=", "'http://www.shanbay.com/team/setqualification/%s'", "%", "self", ".", "team_id", "data", "=", "{", "'kind'", ":", "kind", ",", "'c...
更新成员加入条件 :rtype: bool
[ "更新成员加入条件" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L100-L114
train
Update the limit of the current referral.
mozillazg/python-shanbay
shanbay/team.py
Team.members
def members(self): """获取小组所有成员的信息列表""" all_members = [] for page in range(1, self.max_page() + 1): all_members.extend(self.single_page_members(page)) return all_members
python
def members(self): """获取小组所有成员的信息列表""" all_members = [] for page in range(1, self.max_page() + 1): all_members.extend(self.single_page_members(page)) return all_members
[ "def", "members", "(", "self", ")", ":", "all_members", "=", "[", "]", "for", "page", "in", "range", "(", "1", ",", "self", ".", "max_page", "(", ")", "+", "1", ")", ":", "all_members", ".", "extend", "(", "self", ".", "single_page_members", "(", "...
获取小组所有成员的信息列表
[ "获取小组所有成员的信息列表" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L116-L121
train
get all members of the page
mozillazg/python-shanbay
shanbay/team.py
Team.max_page
def max_page(self): """获取小组成员管理页面的最大页数""" html = self.request(self.dismiss_url).text soup = BeautifulSoup(html) # 分页所在 div try: pagination = soup.find_all(class_='pagination')[0] except IndexError as e: logger.exception(e) return 1 ...
python
def max_page(self): """获取小组成员管理页面的最大页数""" html = self.request(self.dismiss_url).text soup = BeautifulSoup(html) # 分页所在 div try: pagination = soup.find_all(class_='pagination')[0] except IndexError as e: logger.exception(e) return 1 ...
[ "def", "max_page", "(", "self", ")", ":", "html", "=", "self", ".", "request", "(", "self", ".", "dismiss_url", ")", ".", "text", "soup", "=", "BeautifulSoup", "(", "html", ")", "# 分页所在 div", "try", ":", "pagination", "=", "soup", ".", "find_all", "(",...
获取小组成员管理页面的最大页数
[ "获取小组成员管理页面的最大页数" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L123-L134
train
get max page
mozillazg/python-shanbay
shanbay/team.py
Team.single_page_members
def single_page_members(self, page_number=1): """获取单个页面内的小组成员信息 :param page_number: 页码 :return: 包含小组成员信息的列表 返回值示例: :: [{ 'id': 123, # member_id 'username': 'jim', # username 'nickname': 'Jim', ...
python
def single_page_members(self, page_number=1): """获取单个页面内的小组成员信息 :param page_number: 页码 :return: 包含小组成员信息的列表 返回值示例: :: [{ 'id': 123, # member_id 'username': 'jim', # username 'nickname': 'Jim', ...
[ "def", "single_page_members", "(", "self", ",", "page_number", "=", "1", ")", ":", "url", "=", "'%s?page=%s'", "%", "(", "self", ".", "dismiss_url", ",", "page_number", ")", "html", "=", "self", ".", "request", "(", "url", ")", ".", "text", "soup", "="...
获取单个页面内的小组成员信息 :param page_number: 页码 :return: 包含小组成员信息的列表 返回值示例: :: [{ 'id': 123, # member_id 'username': 'jim', # username 'nickname': 'Jim', # 昵称 'role': u'小组长', # 身份 ...
[ "获取单个页面内的小组成员信息" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L136-L220
train
Get a list of members from a single page.
mozillazg/python-shanbay
shanbay/team.py
Team.dismiss
def dismiss(self, member_ids): """踢人. 注意别把自己给踢了. :param member_ids: 组员 ids :return: bool """ url = 'http://www.shanbay.com/api/v1/team/member/' data = { 'action': 'dispel', } if isinstance(member_ids, (list, tuple)): data['ids'] = ...
python
def dismiss(self, member_ids): """踢人. 注意别把自己给踢了. :param member_ids: 组员 ids :return: bool """ url = 'http://www.shanbay.com/api/v1/team/member/' data = { 'action': 'dispel', } if isinstance(member_ids, (list, tuple)): data['ids'] = ...
[ "def", "dismiss", "(", "self", ",", "member_ids", ")", ":", "url", "=", "'http://www.shanbay.com/api/v1/team/member/'", "data", "=", "{", "'action'", ":", "'dispel'", ",", "}", "if", "isinstance", "(", "member_ids", ",", "(", "list", ",", "tuple", ")", ")", ...
踢人. 注意别把自己给踢了. :param member_ids: 组员 ids :return: bool
[ "踢人", ".", "注意别把自己给踢了", "." ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L228-L247
train
Dismiss a set of members from the shanbay.
mozillazg/python-shanbay
shanbay/team.py
Team.forum_id
def forum_id(self): """小组发帖要用的 forum_id""" html = self.request(self.team_url).text soup = BeautifulSoup(html) return soup.find(id='forum_id').attrs['value']
python
def forum_id(self): """小组发帖要用的 forum_id""" html = self.request(self.team_url).text soup = BeautifulSoup(html) return soup.find(id='forum_id').attrs['value']
[ "def", "forum_id", "(", "self", ")", ":", "html", "=", "self", ".", "request", "(", "self", ".", "team_url", ")", ".", "text", "soup", "=", "BeautifulSoup", "(", "html", ")", "return", "soup", ".", "find", "(", "id", "=", "'forum_id'", ")", ".", "a...
小组发帖要用的 forum_id
[ "小组发帖要用的", "forum_id" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L249-L253
train
get forum_id
mozillazg/python-shanbay
shanbay/team.py
Team.new_topic
def new_topic(self, title, content): """小组发贴 :return: 帖子 id 或 ``None`` """ data = { 'title': title, 'body': content, 'csrfmiddlewaretoken': self._request.cookies.get('csrftoken') } url = 'http://www.shanbay.com/api/v1/forum/%s/thread/'...
python
def new_topic(self, title, content): """小组发贴 :return: 帖子 id 或 ``None`` """ data = { 'title': title, 'body': content, 'csrfmiddlewaretoken': self._request.cookies.get('csrftoken') } url = 'http://www.shanbay.com/api/v1/forum/%s/thread/'...
[ "def", "new_topic", "(", "self", ",", "title", ",", "content", ")", ":", "data", "=", "{", "'title'", ":", "title", ",", "'body'", ":", "content", ",", "'csrfmiddlewaretoken'", ":", "self", ".", "_request", ".", "cookies", ".", "get", "(", "'csrftoken'",...
小组发贴 :return: 帖子 id 或 ``None``
[ "小组发贴" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L255-L269
train
create a new topic
mozillazg/python-shanbay
shanbay/team.py
Team.reply_topic
def reply_topic(self, topic_id, content): """小组回帖 :return: 帖子 id 或 ``None`` """ data = { 'body': content, 'csrfmiddlewaretoken': self._request.cookies.get('csrftoken') } url = 'http://www.shanbay.com/api/v1/forum/thread/%s/post/' % topic_id ...
python
def reply_topic(self, topic_id, content): """小组回帖 :return: 帖子 id 或 ``None`` """ data = { 'body': content, 'csrfmiddlewaretoken': self._request.cookies.get('csrftoken') } url = 'http://www.shanbay.com/api/v1/forum/thread/%s/post/' % topic_id ...
[ "def", "reply_topic", "(", "self", ",", "topic_id", ",", "content", ")", ":", "data", "=", "{", "'body'", ":", "content", ",", "'csrfmiddlewaretoken'", ":", "self", ".", "_request", ".", "cookies", ".", "get", "(", "'csrftoken'", ")", "}", "url", "=", ...
小组回帖 :return: 帖子 id 或 ``None``
[ "小组回帖" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/team.py#L271-L284
train
reply to a topic
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.connect
def connect(self, origin=None): """ Connects to the server. :param origin: (Optional) The origin. """ self.logger.debug('Establish connection...') if self.connected: self.logger.warning('Connection already established. Return...') return ...
python
def connect(self, origin=None): """ Connects to the server. :param origin: (Optional) The origin. """ self.logger.debug('Establish connection...') if self.connected: self.logger.warning('Connection already established. Return...') return ...
[ "def", "connect", "(", "self", ",", "origin", "=", "None", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Establish connection...'", ")", "if", "self", ".", "connected", ":", "self", ".", "logger", ".", "warning", "(", "'Connection already established...
Connects to the server. :param origin: (Optional) The origin.
[ "Connects", "to", "the", "server", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L45-L66
train
Connects to the server.
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.disconnect
def disconnect(self): """ Closes the connection. """ self.logger.debug('Close connection...') self.auto_reconnect = False if self.websocket is not None: self.websocket.close()
python
def disconnect(self): """ Closes the connection. """ self.logger.debug('Close connection...') self.auto_reconnect = False if self.websocket is not None: self.websocket.close()
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Close connection...'", ")", "self", ".", "auto_reconnect", "=", "False", "if", "self", ".", "websocket", "is", "not", "None", ":", "self", ".", "websocket", ".", "clo...
Closes the connection.
[ "Closes", "the", "connection", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L68-L77
train
Closes the connection to the server.
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.send
def send(self, data): """ Sends data to the server. """ self.logger.debug('Send data: {}'.format(data)) if not self.connected: self.logger.warning('Connection not established. Return...') return self.websocket.send(json.dumps(data))
python
def send(self, data): """ Sends data to the server. """ self.logger.debug('Send data: {}'.format(data)) if not self.connected: self.logger.warning('Connection not established. Return...') return self.websocket.send(json.dumps(data))
[ "def", "send", "(", "self", ",", "data", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Send data: {}'", ".", "format", "(", "data", ")", ")", "if", "not", "self", ".", "connected", ":", "self", ".", "logger", ".", "warning", "(", "'Connection...
Sends data to the server.
[ "Sends", "data", "to", "the", "server", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L97-L107
train
Sends data to the server.
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection._on_message
def _on_message(self, socket, message): """ Called aways when a message arrives. """ data = json.loads(message) message_type = None identifier = None subscription = None if 'type' in data: message_type = data['type'] if 'identifier' i...
python
def _on_message(self, socket, message): """ Called aways when a message arrives. """ data = json.loads(message) message_type = None identifier = None subscription = None if 'type' in data: message_type = data['type'] if 'identifier' i...
[ "def", "_on_message", "(", "self", ",", "socket", ",", "message", ")", ":", "data", "=", "json", ".", "loads", "(", "message", ")", "message_type", "=", "None", "identifier", "=", "None", "subscription", "=", "None", "if", "'type'", "in", "data", ":", ...
Called aways when a message arrives.
[ "Called", "aways", "when", "a", "message", "arrives", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L116-L147
train
Called aways when a message arrives.
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection._on_close
def _on_close(self, socket): """ Called when the connection was closed. """ self.logger.debug('Connection closed.') for subscription in self.subscriptions.values(): if subscription.state == 'subscribed': subscription.state = 'connection_pending'
python
def _on_close(self, socket): """ Called when the connection was closed. """ self.logger.debug('Connection closed.') for subscription in self.subscriptions.values(): if subscription.state == 'subscribed': subscription.state = 'connection_pending'
[ "def", "_on_close", "(", "self", ",", "socket", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Connection closed.'", ")", "for", "subscription", "in", "self", ".", "subscriptions", ".", "values", "(", ")", ":", "if", "subscription", ".", "state", ...
Called when the connection was closed.
[ "Called", "when", "the", "connection", "was", "closed", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L149-L157
train
Called when the socket is closed.
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.connected
def connected(self): """ If connected to server. """ return self.websocket is not None and \ self.websocket.sock is not None and \ self.websocket.sock.connected
python
def connected(self): """ If connected to server. """ return self.websocket is not None and \ self.websocket.sock is not None and \ self.websocket.sock.connected
[ "def", "connected", "(", "self", ")", ":", "return", "self", ".", "websocket", "is", "not", "None", "and", "self", ".", "websocket", ".", "sock", "is", "not", "None", "and", "self", ".", "websocket", ".", "sock", ".", "connected" ]
If connected to server.
[ "If", "connected", "to", "server", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L167-L173
train
Returns True if the websocket is connected to the server.
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.find_subscription
def find_subscription(self, identifier): """ Finds a subscription by it's identifier. """ for subscription in self.subscriptions.values(): if subscription.identifier == identifier: return subscription
python
def find_subscription(self, identifier): """ Finds a subscription by it's identifier. """ for subscription in self.subscriptions.values(): if subscription.identifier == identifier: return subscription
[ "def", "find_subscription", "(", "self", ",", "identifier", ")", ":", "for", "subscription", "in", "self", ".", "subscriptions", ".", "values", "(", ")", ":", "if", "subscription", ".", "identifier", "==", "identifier", ":", "return", "subscription" ]
Finds a subscription by it's identifier.
[ "Finds", "a", "subscription", "by", "it", "s", "identifier", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L175-L182
train
Finds a subscription by it s identifier.
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.create
def create(self): """ Subscribes at the server. """ self.logger.debug('Create subscription on server...') if not self.connection.connected: self.state = 'connection_pending' return data = { 'command': 'subscribe', 'identif...
python
def create(self): """ Subscribes at the server. """ self.logger.debug('Create subscription on server...') if not self.connection.connected: self.state = 'connection_pending' return data = { 'command': 'subscribe', 'identif...
[ "def", "create", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Create subscription on server...'", ")", "if", "not", "self", ".", "connection", ".", "connected", ":", "self", ".", "state", "=", "'connection_pending'", "return", "data", "...
Subscribes at the server.
[ "Subscribes", "at", "the", "server", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L33-L49
train
Create a new subscription on the server.
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.remove
def remove(self): """ Removes the subscription. """ self.logger.debug('Remove subscription from server...') data = { 'command': 'unsubscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'unsu...
python
def remove(self): """ Removes the subscription. """ self.logger.debug('Remove subscription from server...') data = { 'command': 'unsubscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'unsu...
[ "def", "remove", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Remove subscription from server...'", ")", "data", "=", "{", "'command'", ":", "'unsubscribe'", ",", "'identifier'", ":", "self", ".", "_identifier_string", "(", ")", "}", "s...
Removes the subscription.
[ "Removes", "the", "subscription", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L51-L63
train
Removes the subscription from the server.
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.send
def send(self, message): """ Sends data to the server on the subscription channel. :param data: The JSON data to send. """ self.logger.debug('Send message: {}'.format(message)) if self.state == 'pending' or self.state == 'connection_pending': self.lo...
python
def send(self, message): """ Sends data to the server on the subscription channel. :param data: The JSON data to send. """ self.logger.debug('Send message: {}'.format(message)) if self.state == 'pending' or self.state == 'connection_pending': self.lo...
[ "def", "send", "(", "self", ",", "message", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Send message: {}'", ".", "format", "(", "message", ")", ")", "if", "self", ".", "state", "==", "'pending'", "or", "self", ".", "state", "==", "'connection...
Sends data to the server on the subscription channel. :param data: The JSON data to send.
[ "Sends", "data", "to", "the", "server", "on", "the", "subscription", "channel", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L65-L88
train
Sends a message to the server on the current channel.
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.received
def received(self, data): """ API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message """ self.logger.debug('Data received: {}'.format(data)) message_type = None ...
python
def received(self, data): """ API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message """ self.logger.debug('Data received: {}'.format(data)) message_type = None ...
[ "def", "received", "(", "self", ",", "data", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Data received: {}'", ".", "format", "(", "data", ")", ")", "message_type", "=", "None", "if", "'type'", "in", "data", ":", "message_type", "=", "data", "...
API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message
[ "API", "for", "the", "connection", "to", "forward", "information", "to", "this", "subscription", "instance", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L101-L123
train
Handle incoming data from the broker.
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription._subscribed
def _subscribed(self): """ Called when the subscription was accepted successfully. """ self.logger.debug('Subscription confirmed.') self.state = 'subscribed' for message in self.message_queue: self.send(message)
python
def _subscribed(self): """ Called when the subscription was accepted successfully. """ self.logger.debug('Subscription confirmed.') self.state = 'subscribed' for message in self.message_queue: self.send(message)
[ "def", "_subscribed", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Subscription confirmed.'", ")", "self", ".", "state", "=", "'subscribed'", "for", "message", "in", "self", ".", "message_queue", ":", "self", ".", "send", "(", "messag...
Called when the subscription was accepted successfully.
[ "Called", "when", "the", "subscription", "was", "accepted", "successfully", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L125-L133
train
Called when the subscription was accepted.
flavio/scsgate
scsgate/monitor/__init__.py
cli_opts
def cli_opts(): """ Handle the command line options """ parser = argparse.ArgumentParser() parser.add_argument( "--homeassistant-config", type=str, required=False, dest="config", help="Create configuration section for home assistant",) parser.add_argument( ...
python
def cli_opts(): """ Handle the command line options """ parser = argparse.ArgumentParser() parser.add_argument( "--homeassistant-config", type=str, required=False, dest="config", help="Create configuration section for home assistant",) parser.add_argument( ...
[ "def", "cli_opts", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--homeassistant-config\"", ",", "type", "=", "str", ",", "required", "=", "False", ",", "dest", "=", "\"config\"", ",", "he...
Handle the command line options
[ "Handle", "the", "command", "line", "options" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L13-L44
train
Handle the command line options
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._setup_signal_handler
def _setup_signal_handler(self): """ Register signal handlers """ signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGQUIT, self._signal_handler)
python
def _setup_signal_handler(self): """ Register signal handlers """ signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGQUIT, self._signal_handler)
[ "def", "_setup_signal_handler", "(", "self", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "self", ".", "_signal_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "self", ".", "_signal_handler", ")", "signa...
Register signal handlers
[ "Register", "signal", "handlers" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L83-L87
train
Register signal handlers
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._signal_handler
def _signal_handler(self, signum, frame): """ Method called when handling signals """ if self._options.config: with open(self._options.config, "w") as cfg: yaml.dump(self._home_assistant_config(), cfg) print( "Dumped home assistant configur...
python
def _signal_handler(self, signum, frame): """ Method called when handling signals """ if self._options.config: with open(self._options.config, "w") as cfg: yaml.dump(self._home_assistant_config(), cfg) print( "Dumped home assistant configur...
[ "def", "_signal_handler", "(", "self", ",", "signum", ",", "frame", ")", ":", "if", "self", ".", "_options", ".", "config", ":", "with", "open", "(", "self", ".", "_options", ".", "config", ",", "\"w\"", ")", "as", "cfg", ":", "yaml", ".", "dump", ...
Method called when handling signals
[ "Method", "called", "when", "handling", "signals" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L89-L98
train
Method called when handling signals
flavio/scsgate
scsgate/monitor/__init__.py
Monitor.start
def start(self): """ Monitor the bus for events and handle them """ print("Entering monitoring mode, press CTRL-C to quit") serial = self._connection.serial while True: serial.write(b"@R") length = int(serial.read(), 16) data = serial.read(length * 2)...
python
def start(self): """ Monitor the bus for events and handle them """ print("Entering monitoring mode, press CTRL-C to quit") serial = self._connection.serial while True: serial.write(b"@R") length = int(serial.read(), 16) data = serial.read(length * 2)...
[ "def", "start", "(", "self", ")", ":", "print", "(", "\"Entering monitoring mode, press CTRL-C to quit\"", ")", "serial", "=", "self", ".", "_connection", ".", "serial", "while", "True", ":", "serial", ".", "write", "(", "b\"@R\"", ")", "length", "=", "int", ...
Monitor the bus for events and handle them
[ "Monitor", "the", "bus", "for", "events", "and", "handle", "them" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L100-L122
train
Monitor the bus for events and handle them
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._add_device
def _add_device(self, scs_id, ha_id, name): """ Add device to the list of known ones """ if scs_id in self._devices: return self._devices[scs_id] = { 'name': name, 'ha_id': ha_id }
python
def _add_device(self, scs_id, ha_id, name): """ Add device to the list of known ones """ if scs_id in self._devices: return self._devices[scs_id] = { 'name': name, 'ha_id': ha_id }
[ "def", "_add_device", "(", "self", ",", "scs_id", ",", "ha_id", ",", "name", ")", ":", "if", "scs_id", "in", "self", ".", "_devices", ":", "return", "self", ".", "_devices", "[", "scs_id", "]", "=", "{", "'name'", ":", "name", ",", "'ha_id'", ":", ...
Add device to the list of known ones
[ "Add", "device", "to", "the", "list", "of", "known", "ones" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L124-L132
train
Add a device to the list of known ones
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._home_assistant_config
def _home_assistant_config(self): """ Creates home assistant configuration for the known devices """ devices = {} for scs_id, dev in self._devices.items(): devices[dev['ha_id']] = { 'name': dev['name'], 'scs_id': scs_id} return {'devices': dev...
python
def _home_assistant_config(self): """ Creates home assistant configuration for the known devices """ devices = {} for scs_id, dev in self._devices.items(): devices[dev['ha_id']] = { 'name': dev['name'], 'scs_id': scs_id} return {'devices': dev...
[ "def", "_home_assistant_config", "(", "self", ")", ":", "devices", "=", "{", "}", "for", "scs_id", ",", "dev", "in", "self", ".", "_devices", ".", "items", "(", ")", ":", "devices", "[", "dev", "[", "'ha_id'", "]", "]", "=", "{", "'name'", ":", "de...
Creates home assistant configuration for the known devices
[ "Creates", "home", "assistant", "configuration", "for", "the", "known", "devices" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L134-L142
train
Creates home assistant configuration for the known devices
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._load_filter
def _load_filter(self, config): """ Load the filter file and populates self._devices accordingly """ path = pathlib.Path(config) if not path.is_file(): return with open(config, 'r') as conf: devices = yaml.load(conf)['devices'] for ha_id, dev in devic...
python
def _load_filter(self, config): """ Load the filter file and populates self._devices accordingly """ path = pathlib.Path(config) if not path.is_file(): return with open(config, 'r') as conf: devices = yaml.load(conf)['devices'] for ha_id, dev in devic...
[ "def", "_load_filter", "(", "self", ",", "config", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "config", ")", "if", "not", "path", ".", "is_file", "(", ")", ":", "return", "with", "open", "(", "config", ",", "'r'", ")", "as", "conf", ":", ...
Load the filter file and populates self._devices accordingly
[ "Load", "the", "filter", "file", "and", "populates", "self", ".", "_devices", "accordingly" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L144-L155
train
Load the filter file and populate self. _devices accordingly
flavio/scsgate
scsgate/connection.py
Connection.close
def close(self): """ Closes the connection to the serial port and ensure no pending operatoin are left """ self._serial.write(b"@c") self._serial.read() self._serial.close()
python
def close(self): """ Closes the connection to the serial port and ensure no pending operatoin are left """ self._serial.write(b"@c") self._serial.read() self._serial.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "_serial", ".", "write", "(", "b\"@c\"", ")", "self", ".", "_serial", ".", "read", "(", ")", "self", ".", "_serial", ".", "close", "(", ")" ]
Closes the connection to the serial port and ensure no pending operatoin are left
[ "Closes", "the", "connection", "to", "the", "serial", "port", "and", "ensure", "no", "pending", "operatoin", "are", "left" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/connection.py#L48-L53
train
Closes the connection to the serial port and ensure no pending items are left.
kensho-technologies/grift
grift/config.py
ConfigProperty.load
def load(self, value): """Load a value, converting it to the proper type if validation_type exists.""" if self.property_type is None: return value elif not isinstance(self.property_type, BaseType): raise TypeError('property_type must be schematics BaseType') else:...
python
def load(self, value): """Load a value, converting it to the proper type if validation_type exists.""" if self.property_type is None: return value elif not isinstance(self.property_type, BaseType): raise TypeError('property_type must be schematics BaseType') else:...
[ "def", "load", "(", "self", ",", "value", ")", ":", "if", "self", ".", "property_type", "is", "None", ":", "return", "value", "elif", "not", "isinstance", "(", "self", ".", "property_type", ",", "BaseType", ")", ":", "raise", "TypeError", "(", "'property...
Load a value, converting it to the proper type if validation_type exists.
[ "Load", "a", "value", "converting", "it", "to", "the", "proper", "type", "if", "validation_type", "exists", "." ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L35-L44
train
Load a value converting it to the proper type if validation_type exists.
kensho-technologies/grift
grift/config.py
BaseConfig._iter_config_props
def _iter_config_props(cls): """Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """ props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty)) for attr_name, config_prop in props: yield attr_name, config_prop
python
def _iter_config_props(cls): """Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """ props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty)) for attr_name, config_prop in props: yield attr_name, config_prop
[ "def", "_iter_config_props", "(", "cls", ")", ":", "props", "=", "inspect", ".", "getmembers", "(", "cls", ",", "lambda", "a", ":", "isinstance", "(", "a", ",", "ConfigProperty", ")", ")", "for", "attr_name", ",", "config_prop", "in", "props", ":", "yiel...
Iterate over all ConfigProperty attributes, yielding (attr_name, config_property)
[ "Iterate", "over", "all", "ConfigProperty", "attributes", "yielding", "(", "attr_name", "config_property", ")" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L70-L74
train
Iterate over all ConfigProperty attributes and yield them as a tuple.
kensho-technologies/grift
grift/config.py
BaseConfig._update_property_keys
def _update_property_keys(cls): """Set unspecified property_keys for each ConfigProperty to the name of the class attr""" for attr_name, config_prop in cls._iter_config_props(): if config_prop.property_key is None: config_prop.property_key = attr_name
python
def _update_property_keys(cls): """Set unspecified property_keys for each ConfigProperty to the name of the class attr""" for attr_name, config_prop in cls._iter_config_props(): if config_prop.property_key is None: config_prop.property_key = attr_name
[ "def", "_update_property_keys", "(", "cls", ")", ":", "for", "attr_name", ",", "config_prop", "in", "cls", ".", "_iter_config_props", "(", ")", ":", "if", "config_prop", ".", "property_key", "is", "None", ":", "config_prop", ".", "property_key", "=", "attr_nam...
Set unspecified property_keys for each ConfigProperty to the name of the class attr
[ "Set", "unspecified", "property_keys", "for", "each", "ConfigProperty", "to", "the", "name", "of", "the", "class", "attr" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L77-L81
train
Update the unspecified property_keys for each ConfigProperty in the class attr
kensho-technologies/grift
grift/config.py
BaseConfig._set_instance_prop
def _set_instance_prop(self, attr_name, config_prop, value): """Set instance property to a value and add it varz if needed""" setattr(self, attr_name, value) # add to varz if it is not private if not config_prop.exclude_from_varz: self.varz[attr_name] = value
python
def _set_instance_prop(self, attr_name, config_prop, value): """Set instance property to a value and add it varz if needed""" setattr(self, attr_name, value) # add to varz if it is not private if not config_prop.exclude_from_varz: self.varz[attr_name] = value
[ "def", "_set_instance_prop", "(", "self", ",", "attr_name", ",", "config_prop", ",", "value", ")", ":", "setattr", "(", "self", ",", "attr_name", ",", "value", ")", "# add to varz if it is not private", "if", "not", "config_prop", ".", "exclude_from_varz", ":", ...
Set instance property to a value and add it varz if needed
[ "Set", "instance", "property", "to", "a", "value", "and", "add", "it", "varz", "if", "needed" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L83-L89
train
Set instance property to a value and add it varz if needed
kensho-technologies/grift
grift/config.py
BaseConfig._load
def _load(self): """Load values for all ConfigProperty attributes""" for attr_name, config_prop in self._iter_config_props(): found = False for loader in self._loaders: if loader.exists(config_prop.property_key): raw_value = loader.get(config_p...
python
def _load(self): """Load values for all ConfigProperty attributes""" for attr_name, config_prop in self._iter_config_props(): found = False for loader in self._loaders: if loader.exists(config_prop.property_key): raw_value = loader.get(config_p...
[ "def", "_load", "(", "self", ")", ":", "for", "attr_name", ",", "config_prop", "in", "self", ".", "_iter_config_props", "(", ")", ":", "found", "=", "False", "for", "loader", "in", "self", ".", "_loaders", ":", "if", "loader", ".", "exists", "(", "conf...
Load values for all ConfigProperty attributes
[ "Load", "values", "for", "all", "ConfigProperty", "attributes" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L91-L108
train
Load values for all ConfigProperty attributes
kensho-technologies/grift
grift/config.py
BaseConfig.reload
def reload(self): """Reload all ConfigProperty values (reading from loader sources again, if applicable)""" for loader in self._loaders: loader.reload() self.varz = {} # reset varz self._load()
python
def reload(self): """Reload all ConfigProperty values (reading from loader sources again, if applicable)""" for loader in self._loaders: loader.reload() self.varz = {} # reset varz self._load()
[ "def", "reload", "(", "self", ")", ":", "for", "loader", "in", "self", ".", "_loaders", ":", "loader", ".", "reload", "(", ")", "self", ".", "varz", "=", "{", "}", "# reset varz", "self", ".", "_load", "(", ")" ]
Reload all ConfigProperty values (reading from loader sources again, if applicable)
[ "Reload", "all", "ConfigProperty", "values", "(", "reading", "from", "loader", "sources", "again", "if", "applicable", ")" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L110-L116
train
Reload all ConfigProperty values from all loaded loaders.
kensho-technologies/grift
grift/config.py
BaseConfig.as_dict
def as_dict(self): """Return all properties and values in a dictionary (includes private properties)""" return {config_name: getattr(self, config_name) for config_name, _ in self._iter_config_props()}
python
def as_dict(self): """Return all properties and values in a dictionary (includes private properties)""" return {config_name: getattr(self, config_name) for config_name, _ in self._iter_config_props()}
[ "def", "as_dict", "(", "self", ")", ":", "return", "{", "config_name", ":", "getattr", "(", "self", ",", "config_name", ")", "for", "config_name", ",", "_", "in", "self", ".", "_iter_config_props", "(", ")", "}" ]
Return all properties and values in a dictionary (includes private properties)
[ "Return", "all", "properties", "and", "values", "in", "a", "dictionary", "(", "includes", "private", "properties", ")" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L118-L121
train
Return all properties and values in a dictionary
kensho-technologies/grift
grift/utils.py
in_same_dir
def in_same_dir(as_file, target_file): """Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file """ return os.path.abspa...
python
def in_same_dir(as_file, target_file): """Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file """ return os.path.abspa...
[ "def", "in_same_dir", "(", "as_file", ",", "target_file", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "as_file", ")", ",", "target_file", ")", ")" ]
Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file
[ "Return", "an", "absolute", "path", "to", "a", "target", "file", "that", "is", "located", "in", "the", "same", "directory", "as", "as_file" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/utils.py#L5-L13
train
Return an absolute path to a target file that is located in the same directory as as_file
pr-omethe-us/PyKED
pyked/validation.py
compare_name
def compare_name(given_name, family_name, question_name): """Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer"...
python
def compare_name(given_name, family_name, question_name): """Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer"...
[ "def", "compare_name", "(", "given_name", ",", "family_name", ",", "question_name", ")", ":", "# lowercase everything", "given_name", "=", "given_name", ".", "lower", "(", ")", "family_name", "=", "family_name", ".", "lower", "(", ")", "question_name", "=", "que...
Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer". Other possibilities include names with hyphens such as "Chi...
[ "Compares", "a", "name", "in", "question", "to", "a", "specified", "name", "separated", "into", "given", "and", "family", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L91-L166
train
Compares a name in question separated into given and family.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_t_range
def _validate_isvalid_t_range(self, isvalid_t_range, field, values): """Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List...
python
def _validate_isvalid_t_range(self, isvalid_t_range, field, values): """Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List...
[ "def", "_validate_isvalid_t_range", "(", "self", ",", "isvalid_t_range", ",", "field", ",", "values", ")", ":", "if", "all", "(", "[", "isinstance", "(", "v", ",", "(", "float", ",", "int", ")", ")", "for", "v", "in", "values", "]", ")", ":", "# If n...
Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List of temperature values indicating low, middle, and high ranges The rule...
[ "Checks", "that", "the", "temperature", "ranges", "given", "for", "thermo", "data", "are", "valid", "Args", ":", "isvalid_t_range", "(", "bool", ")", ":", "flag", "from", "schema", "indicating", "T", "range", "is", "to", "be", "checked", "field", "(", "str...
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L172-L200
train
Checks that the temperature ranges given for thermo data are valid.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_unit
def _validate_isvalid_unit(self, isvalid_unit, field, value): """Checks for appropriate units using Pint unit registry. Args: isvalid_unit (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with units in question. value (`dic...
python
def _validate_isvalid_unit(self, isvalid_unit, field, value): """Checks for appropriate units using Pint unit registry. Args: isvalid_unit (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with units in question. value (`dic...
[ "def", "_validate_isvalid_unit", "(", "self", ",", "isvalid_unit", ",", "field", ",", "value", ")", ":", "quantity", "=", "1.0", "*", "units", "(", "value", "[", "'units'", "]", ")", "try", ":", "quantity", ".", "to", "(", "property_units", "[", "field",...
Checks for appropriate units using Pint unit registry. Args: isvalid_unit (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with units in question. value (`dict`): dictionary of values from file associated with this property. ...
[ "Checks", "for", "appropriate", "units", "using", "Pint", "unit", "registry", ".", "Args", ":", "isvalid_unit", "(", "bool", ")", ":", "flag", "from", "schema", "indicating", "units", "to", "be", "checked", ".", "field", "(", "str", ")", ":", "property", ...
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L202-L219
train
Checks if the units of the file associated with this property are compatible with the Pint unit registry.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_history
def _validate_isvalid_history(self, isvalid_history, field, value): """Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. ...
python
def _validate_isvalid_history(self, isvalid_history, field, value): """Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. ...
[ "def", "_validate_isvalid_history", "(", "self", ",", "isvalid_history", ",", "field", ",", "value", ")", ":", "# Check the type has appropriate units", "history_type", "=", "value", "[", "'type'", "]", "if", "history_type", ".", "endswith", "(", "'emission'", ")", ...
Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. value (`dict`): dictionary of values from file associated with this propert...
[ "Checks", "that", "the", "given", "time", "history", "is", "properly", "formatted", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L221-L262
train
Checks that the given time history is properly formatted.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_quantity
def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. ...
python
def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. ...
[ "def", "_validate_isvalid_quantity", "(", "self", ",", "isvalid_quantity", ",", "field", ",", "value", ")", ":", "quantity", "=", "Q_", "(", "value", "[", "0", "]", ")", "low_lim", "=", "0.0", "*", "units", "(", "property_units", "[", "field", "]", ")", ...
Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. value (`list`): list whose first element is a string representing a value wi...
[ "Checks", "for", "valid", "given", "value", "and", "appropriate", "units", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L264-L287
train
Checks for valid given value and appropriate units.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_uncertainty
def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value): """Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with t...
python
def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value): """Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with t...
[ "def", "_validate_isvalid_uncertainty", "(", "self", ",", "isvalid_uncertainty", ",", "field", ",", "value", ")", ":", "self", ".", "_validate_isvalid_quantity", "(", "True", ",", "field", ",", "value", ")", "# This len check is necessary for reasons that aren't quite cle...
Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with the quantity in question. value (`list`): list with the string of the value ...
[ "Checks", "for", "valid", "given", "value", "and", "appropriate", "units", "with", "uncertainty", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L289-L315
train
Checks for valid given value and appropriate units with uncertainty.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_reference
def _validate_isvalid_reference(self, isvalid_reference, field, value): """Checks valid reference metadata using DOI (if present). Args: isvalid_reference (`bool`): flag from schema indicating reference to be checked. field (`str`): 'reference' value (`dict`): dictio...
python
def _validate_isvalid_reference(self, isvalid_reference, field, value): """Checks valid reference metadata using DOI (if present). Args: isvalid_reference (`bool`): flag from schema indicating reference to be checked. field (`str`): 'reference' value (`dict`): dictio...
[ "def", "_validate_isvalid_reference", "(", "self", ",", "isvalid_reference", ",", "field", ",", "value", ")", ":", "if", "'doi'", "in", "value", ":", "try", ":", "ref", "=", "crossref_api", ".", "works", "(", "ids", "=", "value", "[", "'doi'", "]", ")", ...
Checks valid reference metadata using DOI (if present). Args: isvalid_reference (`bool`): flag from schema indicating reference to be checked. field (`str`): 'reference' value (`dict`): dictionary of reference metadata. The rule's arguments are validated against thi...
[ "Checks", "valid", "reference", "metadata", "using", "DOI", "(", "if", "present", ")", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L317-L418
train
Checks that the DOI is in the correct format.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_orcid
def _validate_isvalid_orcid(self, isvalid_orcid, field, value): """Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule...
python
def _validate_isvalid_orcid(self, isvalid_orcid, field, value): """Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule...
[ "def", "_validate_isvalid_orcid", "(", "self", ",", "isvalid_orcid", ",", "field", ",", "value", ")", ":", "if", "isvalid_orcid", "and", "'ORCID'", "in", "value", ":", "try", ":", "res", "=", "search_orcid", "(", "value", "[", "'ORCID'", "]", ")", "except"...
Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule's arguments are validated against this schema: {'isvalid_orcid...
[ "Checks", "for", "valid", "ORCID", "if", "given", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L420-L451
train
Checks for valid ORCID and checks if it matches the given ORCID.
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_composition
def _validate_isvalid_composition(self, isvalid_composition, field, value): """Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (di...
python
def _validate_isvalid_composition(self, isvalid_composition, field, value): """Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (di...
[ "def", "_validate_isvalid_composition", "(", "self", ",", "isvalid_composition", ",", "field", ",", "value", ")", ":", "sum_amount", "=", "0.0", "if", "value", "[", "'kind'", "]", "in", "[", "'mass fraction'", ",", "'mole fraction'", "]", ":", "low_lim", "=", ...
Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (dict): dictionary of composition The rule's arguments are validated against this...
[ "Checks", "for", "valid", "specification", "of", "composition", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L453-L499
train
Checks if the composition of the current object is valid.
gsi-upm/soil
soil/analysis.py
read_csv
def read_csv(filename, keys=None, convert_types=False, **kwargs): ''' Read a CSV in canonical form: :: <agent_id, t_step, key, value, value_type> ''' df = pd.read_csv(filename) if convert_types: df = convert_types_slow(df) if keys: df = df[df['key'].isin(keys)] df =...
python
def read_csv(filename, keys=None, convert_types=False, **kwargs): ''' Read a CSV in canonical form: :: <agent_id, t_step, key, value, value_type> ''' df = pd.read_csv(filename) if convert_types: df = convert_types_slow(df) if keys: df = df[df['key'].isin(keys)] df =...
[ "def", "read_csv", "(", "filename", ",", "keys", "=", "None", ",", "convert_types", "=", "False", ",", "*", "*", "kwargs", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "filename", ")", "if", "convert_types", ":", "df", "=", "convert_types_slow", "(...
Read a CSV in canonical form: :: <agent_id, t_step, key, value, value_type>
[ "Read", "a", "CSV", "in", "canonical", "form", ":", "::" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L42-L55
train
Read a CSV file in canonical form.
gsi-upm/soil
soil/analysis.py
convert_types_slow
def convert_types_slow(df): '''This is a slow operation.''' dtypes = get_types(df) for k, v in dtypes.items(): t = df[df['key']==k] t['value'] = t['value'].astype(v) df = df.apply(convert_row, axis=1) return df
python
def convert_types_slow(df): '''This is a slow operation.''' dtypes = get_types(df) for k, v in dtypes.items(): t = df[df['key']==k] t['value'] = t['value'].astype(v) df = df.apply(convert_row, axis=1) return df
[ "def", "convert_types_slow", "(", "df", ")", ":", "dtypes", "=", "get_types", "(", "df", ")", "for", "k", ",", "v", "in", "dtypes", ".", "items", "(", ")", ":", "t", "=", "df", "[", "df", "[", "'key'", "]", "==", "k", "]", "t", "[", "'value'", ...
This is a slow operation.
[ "This", "is", "a", "slow", "operation", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L63-L70
train
This is a slow operation.
gsi-upm/soil
soil/analysis.py
split_df
def split_df(df): ''' Split a dataframe in two dataframes: one with the history of agents, and one with the environment history ''' envmask = (df['agent_id'] == 'env') n_env = envmask.sum() if n_env == len(df): return df, None elif n_env == 0: return None, df agents, ...
python
def split_df(df): ''' Split a dataframe in two dataframes: one with the history of agents, and one with the environment history ''' envmask = (df['agent_id'] == 'env') n_env = envmask.sum() if n_env == len(df): return df, None elif n_env == 0: return None, df agents, ...
[ "def", "split_df", "(", "df", ")", ":", "envmask", "=", "(", "df", "[", "'agent_id'", "]", "==", "'env'", ")", "n_env", "=", "envmask", ".", "sum", "(", ")", "if", "n_env", "==", "len", "(", "df", ")", ":", "return", "df", ",", "None", "elif", ...
Split a dataframe in two dataframes: one with the history of agents, and one with the environment history
[ "Split", "a", "dataframe", "in", "two", "dataframes", ":", "one", "with", "the", "history", "of", "agents", "and", "one", "with", "the", "environment", "history" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L72-L84
train
Split a dataframe in two dataframes one with the history of agents and the environment history and one with the agents and the environment history .
gsi-upm/soil
soil/analysis.py
process
def process(df, **kwargs): ''' Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into two dataframes with a column per key: one with the history of the agents, and one for the history of the environment. ''' env, agents = split_df(df) return process_one(env...
python
def process(df, **kwargs): ''' Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into two dataframes with a column per key: one with the history of the agents, and one for the history of the environment. ''' env, agents = split_df(df) return process_one(env...
[ "def", "process", "(", "df", ",", "*", "*", "kwargs", ")", ":", "env", ",", "agents", "=", "split_df", "(", "df", ")", "return", "process_one", "(", "env", ",", "*", "*", "kwargs", ")", ",", "process_one", "(", "agents", ",", "*", "*", "kwargs", ...
Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into two dataframes with a column per key: one with the history of the agents, and one for the history of the environment.
[ "Process", "a", "dataframe", "in", "canonical", "form", "(", "t_step", "agent_id", "key", "value", "value_type", ")", "into", "two", "dataframes", "with", "a", "column", "per", "key", ":", "one", "with", "the", "history", "of", "the", "agents", "and", "one...
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L87-L94
train
Process a dataframe in canonical form into a sequence of two dataframes with a column per key.
gsi-upm/soil
soil/analysis.py
process_one
def process_one(df, *keys, columns=['key', 'agent_id'], values='value', fill=True, index=['t_step',], aggfunc='first', **kwargs): ''' Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into a dataframe with a column per key ''' if df ...
python
def process_one(df, *keys, columns=['key', 'agent_id'], values='value', fill=True, index=['t_step',], aggfunc='first', **kwargs): ''' Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into a dataframe with a column per key ''' if df ...
[ "def", "process_one", "(", "df", ",", "*", "keys", ",", "columns", "=", "[", "'key'", ",", "'agent_id'", "]", ",", "values", "=", "'value'", ",", "fill", "=", "True", ",", "index", "=", "[", "'t_step'", ",", "]", ",", "aggfunc", "=", "'first'", ","...
Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into a dataframe with a column per key
[ "Process", "a", "dataframe", "in", "canonical", "form", "(", "t_step", "agent_id", "key", "value", "value_type", ")", "into", "a", "dataframe", "with", "a", "column", "per", "key" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L102-L118
train
Process a dataframe in canonical form with a column per key.
gsi-upm/soil
soil/analysis.py
plot_all
def plot_all(*args, **kwargs): ''' Read all the trial data and plot the result of applying a function on them. ''' dfs = do_all(*args, **kwargs) ps = [] for line in dfs: f, df, config = line df.plot(title=config['name']) ps.append(df) return ps
python
def plot_all(*args, **kwargs): ''' Read all the trial data and plot the result of applying a function on them. ''' dfs = do_all(*args, **kwargs) ps = [] for line in dfs: f, df, config = line df.plot(title=config['name']) ps.append(df) return ps
[ "def", "plot_all", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "dfs", "=", "do_all", "(", "*", "args", ",", "*", "*", "kwargs", ")", "ps", "=", "[", "]", "for", "line", "in", "dfs", ":", "f", ",", "df", ",", "config", "=", "line", ...
Read all the trial data and plot the result of applying a function on them.
[ "Read", "all", "the", "trial", "data", "and", "plot", "the", "result", "of", "applying", "a", "function", "on", "them", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L139-L149
train
Read all the trial data and plot the result of applying a function on them.
gsi-upm/soil
soil/utils.py
name
def name(value, known_modules=[]): '''Return a name that can be imported, to serialize/deserialize an object''' if value is None: return 'None' if not isinstance(value, type): # Get the class name first value = type(value) tname = value.__name__ if hasattr(builtins, tname): ...
python
def name(value, known_modules=[]): '''Return a name that can be imported, to serialize/deserialize an object''' if value is None: return 'None' if not isinstance(value, type): # Get the class name first value = type(value) tname = value.__name__ if hasattr(builtins, tname): ...
[ "def", "name", "(", "value", ",", "known_modules", "=", "[", "]", ")", ":", "if", "value", "is", "None", ":", "return", "'None'", "if", "not", "isinstance", "(", "value", ",", "type", ")", ":", "# Get the class name first", "value", "=", "type", "(", "...
Return a name that can be imported, to serialize/deserialize an object
[ "Return", "a", "name", "that", "can", "be", "imported", "to", "serialize", "/", "deserialize", "an", "object" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/utils.py#L87-L107
train
Return a name that can be imported to serialize or deserialize an object
gsi-upm/soil
soil/utils.py
serialize
def serialize(v, known_modules=[]): '''Get a text representation of an object.''' tname = name(v, known_modules=known_modules) func = serializer(tname) return func(v), tname
python
def serialize(v, known_modules=[]): '''Get a text representation of an object.''' tname = name(v, known_modules=known_modules) func = serializer(tname) return func(v), tname
[ "def", "serialize", "(", "v", ",", "known_modules", "=", "[", "]", ")", ":", "tname", "=", "name", "(", "v", ",", "known_modules", "=", "known_modules", ")", "func", "=", "serializer", "(", "tname", ")", "return", "func", "(", "v", ")", ",", "tname" ...
Get a text representation of an object.
[ "Get", "a", "text", "representation", "of", "an", "object", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/utils.py#L116-L120
train
Get a text representation of an object.
gsi-upm/soil
soil/utils.py
deserialize
def deserialize(type_, value=None, **kwargs): '''Get an object from a text representation''' if not isinstance(type_, str): return type_ des = deserializer(type_, **kwargs) if value is None: return des return des(value)
python
def deserialize(type_, value=None, **kwargs): '''Get an object from a text representation''' if not isinstance(type_, str): return type_ des = deserializer(type_, **kwargs) if value is None: return des return des(value)
[ "def", "deserialize", "(", "type_", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "type_", ",", "str", ")", ":", "return", "type_", "des", "=", "deserializer", "(", "type_", ",", "*", "*", "kwargs", "...
Get an object from a text representation
[ "Get", "an", "object", "from", "a", "text", "representation" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/utils.py#L155-L162
train
Get an object from a text representation
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.content
def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content
python
def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content
[ "def", "content", "(", "self", ")", ":", "if", "self", ".", "_content", "is", "None", ":", "self", ".", "_content", "=", "self", ".", "parse_files", "(", ")", "return", "self", ".", "_content" ]
Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line).
[ "Return", "parsed", "data", ".", "Parse", "it", "if", "not", "already", "parsed", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L48-L57
train
Return parsed data. Parse it.
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.matching_files
def matching_files(self): """ Find files. Returns: list: the list of matching files. """ matching = [] matcher = self.file_path_regex pieces = self.file_path_regex.pattern.split(sep) partial_matchers = list(map(re.compile, ( sep.jo...
python
def matching_files(self): """ Find files. Returns: list: the list of matching files. """ matching = [] matcher = self.file_path_regex pieces = self.file_path_regex.pattern.split(sep) partial_matchers = list(map(re.compile, ( sep.jo...
[ "def", "matching_files", "(", "self", ")", ":", "matching", "=", "[", "]", "matcher", "=", "self", ".", "file_path_regex", "pieces", "=", "self", ".", "file_path_regex", ".", "pattern", ".", "split", "(", "sep", ")", "partial_matchers", "=", "list", "(", ...
Find files. Returns: list: the list of matching files.
[ "Find", "files", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L60-L84
train
Find files. returns the list of matching files.
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.parse_files
def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: ...
python
def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: ...
[ "def", "parse_files", "(", "self", ")", ":", "log_re", "=", "self", ".", "log_format_regex", "log_lines", "=", "[", "]", "for", "log_file", "in", "self", ".", "matching_files", "(", ")", ":", "with", "open", "(", "log_file", ")", "as", "f", ":", "match...
Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line).
[ "Find", "the", "files", "and", "parse", "them", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L86-L100
train
Find the files and parse them.
gsi-upm/soil
soil/agents/__init__.py
calculate_distribution
def calculate_distribution(network_agents=None, agent_type=None): ''' Calculate the threshold values (thresholds for a uniform distribution) of an agent distribution given the weights of each agent type. The input has this form: :: [ {'agent_type': 'a...
python
def calculate_distribution(network_agents=None, agent_type=None): ''' Calculate the threshold values (thresholds for a uniform distribution) of an agent distribution given the weights of each agent type. The input has this form: :: [ {'agent_type': 'a...
[ "def", "calculate_distribution", "(", "network_agents", "=", "None", ",", "agent_type", "=", "None", ")", ":", "if", "network_agents", ":", "network_agents", "=", "deepcopy", "(", "network_agents", ")", "elif", "agent_type", ":", "network_agents", "=", "[", "{",...
Calculate the threshold values (thresholds for a uniform distribution) of an agent distribution given the weights of each agent type. The input has this form: :: [ {'agent_type': 'agent_type_1', 'weight': 0.2, 'state': { 'id': 0 ...
[ "Calculate", "the", "threshold", "values", "(", "thresholds", "for", "a", "uniform", "distribution", ")", "of", "an", "agent", "distribution", "given", "the", "weights", "of", "each", "agent", "type", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L341-L384
train
Calculates the threshold values for a uniform distribution of the network agents.
gsi-upm/soil
soil/agents/__init__.py
serialize_distribution
def serialize_distribution(network_agents, known_modules=[]): ''' When serializing an agent distribution, remove the thresholds, in order to avoid cluttering the YAML definition file. ''' d = deepcopy(list(network_agents)) for v in d: if 'threshold' in v: del v['threshold'] ...
python
def serialize_distribution(network_agents, known_modules=[]): ''' When serializing an agent distribution, remove the thresholds, in order to avoid cluttering the YAML definition file. ''' d = deepcopy(list(network_agents)) for v in d: if 'threshold' in v: del v['threshold'] ...
[ "def", "serialize_distribution", "(", "network_agents", ",", "known_modules", "=", "[", "]", ")", ":", "d", "=", "deepcopy", "(", "list", "(", "network_agents", ")", ")", "for", "v", "in", "d", ":", "if", "'threshold'", "in", "v", ":", "del", "v", "[",...
When serializing an agent distribution, remove the thresholds, in order to avoid cluttering the YAML definition file.
[ "When", "serializing", "an", "agent", "distribution", "remove", "the", "thresholds", "in", "order", "to", "avoid", "cluttering", "the", "YAML", "definition", "file", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L394-L405
train
Serializes a network agent distribution into a YAML document.
gsi-upm/soil
soil/agents/__init__.py
_validate_states
def _validate_states(states, topology): '''Validate states to avoid ignoring states during initialization''' states = states or [] if isinstance(states, dict): for x in states: assert x in topology.node else: assert len(states) <= len(topology) return states
python
def _validate_states(states, topology): '''Validate states to avoid ignoring states during initialization''' states = states or [] if isinstance(states, dict): for x in states: assert x in topology.node else: assert len(states) <= len(topology) return states
[ "def", "_validate_states", "(", "states", ",", "topology", ")", ":", "states", "=", "states", "or", "[", "]", "if", "isinstance", "(", "states", ",", "dict", ")", ":", "for", "x", "in", "states", ":", "assert", "x", "in", "topology", ".", "node", "el...
Validate states to avoid ignoring states during initialization
[ "Validate", "states", "to", "avoid", "ignoring", "states", "during", "initialization" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L423-L431
train
Validate states to avoid ignoring states during initialization
gsi-upm/soil
soil/agents/__init__.py
_convert_agent_types
def _convert_agent_types(ind, to_string=False, **kwargs): '''Convenience method to allow specifying agents by class or class name.''' if to_string: return serialize_distribution(ind, **kwargs) return deserialize_distribution(ind, **kwargs)
python
def _convert_agent_types(ind, to_string=False, **kwargs): '''Convenience method to allow specifying agents by class or class name.''' if to_string: return serialize_distribution(ind, **kwargs) return deserialize_distribution(ind, **kwargs)
[ "def", "_convert_agent_types", "(", "ind", ",", "to_string", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "to_string", ":", "return", "serialize_distribution", "(", "ind", ",", "*", "*", "kwargs", ")", "return", "deserialize_distribution", "(", "in...
Convenience method to allow specifying agents by class or class name.
[ "Convenience", "method", "to", "allow", "specifying", "agents", "by", "class", "or", "class", "name", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L434-L438
train
Convenience method to allow specifying agents by class or class name.
gsi-upm/soil
soil/agents/__init__.py
_agent_from_distribution
def _agent_from_distribution(distribution, value=-1, agent_id=None): """Used in the initialization of agents given an agent distribution.""" if value < 0: value = random.random() for d in sorted(distribution, key=lambda x: x['threshold']): threshold = d['threshold'] # Check if the de...
python
def _agent_from_distribution(distribution, value=-1, agent_id=None): """Used in the initialization of agents given an agent distribution.""" if value < 0: value = random.random() for d in sorted(distribution, key=lambda x: x['threshold']): threshold = d['threshold'] # Check if the de...
[ "def", "_agent_from_distribution", "(", "distribution", ",", "value", "=", "-", "1", ",", "agent_id", "=", "None", ")", ":", "if", "value", "<", "0", ":", "value", "=", "random", ".", "random", "(", ")", "for", "d", "in", "sorted", "(", "distribution",...
Used in the initialization of agents given an agent distribution.
[ "Used", "in", "the", "initialization", "of", "agents", "given", "an", "agent", "distribution", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L441-L456
train
Used in the initialization of agents given an agent distribution.
gsi-upm/soil
soil/agents/__init__.py
NetworkAgent.ego_search
def ego_search(self, steps=1, center=False, node=None, **kwargs): '''Get a list of nodes in the ego network of *node* of radius *steps*''' node = as_node(node if node is not None else self) G = self.subgraph(**kwargs) return nx.ego_graph(G, node, center=center, radius=steps).nodes()
python
def ego_search(self, steps=1, center=False, node=None, **kwargs): '''Get a list of nodes in the ego network of *node* of radius *steps*''' node = as_node(node if node is not None else self) G = self.subgraph(**kwargs) return nx.ego_graph(G, node, center=center, radius=steps).nodes()
[ "def", "ego_search", "(", "self", ",", "steps", "=", "1", ",", "center", "=", "False", ",", "node", "=", "None", ",", "*", "*", "kwargs", ")", ":", "node", "=", "as_node", "(", "node", "if", "node", "is", "not", "None", "else", "self", ")", "G", ...
Get a list of nodes in the ego network of *node* of radius *steps*
[ "Get", "a", "list", "of", "nodes", "in", "the", "ego", "network", "of", "*", "node", "*", "of", "radius", "*", "steps", "*" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L214-L218
train
Get a list of nodes in the ego network of radius * steps*
gsi-upm/soil
soil/agents/__init__.py
Geo.geo_search
def geo_search(self, radius, node=None, center=False, **kwargs): '''Get a list of nodes whose coordinates are closer than *radius* to *node*.''' node = as_node(node if node is not None else self) G = self.subgraph(**kwargs) pos = nx.get_node_attributes(G, 'pos') if not pos: ...
python
def geo_search(self, radius, node=None, center=False, **kwargs): '''Get a list of nodes whose coordinates are closer than *radius* to *node*.''' node = as_node(node if node is not None else self) G = self.subgraph(**kwargs) pos = nx.get_node_attributes(G, 'pos') if not pos: ...
[ "def", "geo_search", "(", "self", ",", "radius", ",", "node", "=", "None", ",", "center", "=", "False", ",", "*", "*", "kwargs", ")", ":", "node", "=", "as_node", "(", "node", "if", "node", "is", "not", "None", "else", "self", ")", "G", "=", "sel...
Get a list of nodes whose coordinates are closer than *radius* to *node*.
[ "Get", "a", "list", "of", "nodes", "whose", "coordinates", "are", "closer", "than", "*", "radius", "*", "to", "*", "node", "*", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L462-L474
train
Get a list of nodes whose coordinates are closer than radius to node.
gsi-upm/soil
soil/web/__init__.py
SocketHandler.on_message
def on_message(self, message): """ Receiving a message from the websocket, parse, and act accordingly. """ msg = tornado.escape.json_decode(message) if msg['type'] == 'config_file': if self.application.verbose: print(msg['data']) self.config = list(yam...
python
def on_message(self, message): """ Receiving a message from the websocket, parse, and act accordingly. """ msg = tornado.escape.json_decode(message) if msg['type'] == 'config_file': if self.application.verbose: print(msg['data']) self.config = list(yam...
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "msg", "=", "tornado", ".", "escape", ".", "json_decode", "(", "message", ")", "if", "msg", "[", "'type'", "]", "==", "'config_file'", ":", "if", "self", ".", "application", ".", "verbose", ":...
Receiving a message from the websocket, parse, and act accordingly.
[ "Receiving", "a", "message", "from", "the", "websocket", "parse", "and", "act", "accordingly", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/web/__init__.py#L53-L142
train
Receives a message from the websocket parse and act accordingly.
gsi-upm/soil
soil/web/__init__.py
ModularServer.launch
def launch(self, port=None): """ Run the app. """ if port is not None: self.port = port url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port) print('Interface starting at {url}'.format(url=url)) self.listen(self.port) # webbrowser.open(url) t...
python
def launch(self, port=None): """ Run the app. """ if port is not None: self.port = port url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port) print('Interface starting at {url}'.format(url=url)) self.listen(self.port) # webbrowser.open(url) t...
[ "def", "launch", "(", "self", ",", "port", "=", "None", ")", ":", "if", "port", "is", "not", "None", ":", "self", ".", "port", "=", "port", "url", "=", "'http://127.0.0.1:{PORT}'", ".", "format", "(", "PORT", "=", "self", ".", "port", ")", "print", ...
Run the app.
[ "Run", "the", "app", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/web/__init__.py#L245-L254
train
Launch the application.
Genida/django-meerkat
src/meerkat/logs/stats.py
status_codes_by_date_stats
def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( ...
python
def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( ...
[ "def", "status_codes_by_date_stats", "(", ")", ":", "def", "date_counter", "(", "queryset", ")", ":", "return", "dict", "(", "Counter", "(", "map", "(", "lambda", "dt", ":", "ms_since_epoch", "(", "datetime", ".", "combine", "(", "make_naive", "(", "dt", "...
Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
[ "Get", "stats", "for", "status", "codes", "by", "date", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/stats.py#L38-L67
train
Get stats for status codes by date.
Genida/django-meerkat
src/meerkat/logs/stats.py
most_visited_pages_stats
def most_visited_pages_stats(): """ Get stats for most visited pages. Args: logs (list): logs data to use. Returns: dict: more_than_10 and less_than_10: list of dict (bound + url list). """ stats = {'more_than_10': [], 'less_than_10': {}} counter = Counter(list(RequestLog....
python
def most_visited_pages_stats(): """ Get stats for most visited pages. Args: logs (list): logs data to use. Returns: dict: more_than_10 and less_than_10: list of dict (bound + url list). """ stats = {'more_than_10': [], 'less_than_10': {}} counter = Counter(list(RequestLog....
[ "def", "most_visited_pages_stats", "(", ")", ":", "stats", "=", "{", "'more_than_10'", ":", "[", "]", ",", "'less_than_10'", ":", "{", "}", "}", "counter", "=", "Counter", "(", "list", "(", "RequestLog", ".", "objects", ".", "values_list", "(", "'url'", ...
Get stats for most visited pages. Args: logs (list): logs data to use. Returns: dict: more_than_10 and less_than_10: list of dict (bound + url list).
[ "Get", "stats", "for", "most", "visited", "pages", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/stats.py#L70-L153
train
Get stats for the most visited pages.
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
CityPubs.enter
def enter(self, pub_id, *nodes): '''Agents will try to enter. The pub checks if it is possible''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) if not pub['open'] or (pub['capacity'] < (len(nodes) + pub...
python
def enter(self, pub_id, *nodes): '''Agents will try to enter. The pub checks if it is possible''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) if not pub['open'] or (pub['capacity'] < (len(nodes) + pub...
[ "def", "enter", "(", "self", ",", "pub_id", ",", "*", "nodes", ")", ":", "try", ":", "pub", "=", "self", "[", "'pubs'", "]", "[", "pub_id", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Pub {} is not available'", ".", "format", "(", "pu...
Agents will try to enter. The pub checks if it is possible
[ "Agents", "will", "try", "to", "enter", ".", "The", "pub", "checks", "if", "it", "is", "possible" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L25-L36
train
Attempts to enter a node in the agent.
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
CityPubs.exit
def exit(self, pub_id, *node_ids): '''Agents will notify the pub they want to leave''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) for node_id in node_ids: node = self.get_agent(node_id) ...
python
def exit(self, pub_id, *node_ids): '''Agents will notify the pub they want to leave''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) for node_id in node_ids: node = self.get_agent(node_id) ...
[ "def", "exit", "(", "self", ",", "pub_id", ",", "*", "node_ids", ")", ":", "try", ":", "pub", "=", "self", "[", "'pubs'", "]", "[", "pub_id", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Pub {} is not available'", ".", "format", "(", "...
Agents will notify the pub they want to leave
[ "Agents", "will", "notify", "the", "pub", "they", "want", "to", "leave" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L43-L53
train
Agents will notify the pub they want to leave
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.looking_for_friends
def looking_for_friends(self): '''Look for friends to drink with''' self.info('I am looking for friends') available_friends = list(self.get_agents(drunk=False, pub=None, state_id=self.looking_for_fr...
python
def looking_for_friends(self): '''Look for friends to drink with''' self.info('I am looking for friends') available_friends = list(self.get_agents(drunk=False, pub=None, state_id=self.looking_for_fr...
[ "def", "looking_for_friends", "(", "self", ")", ":", "self", ".", "info", "(", "'I am looking for friends'", ")", "available_friends", "=", "list", "(", "self", ".", "get_agents", "(", "drunk", "=", "False", ",", "pub", "=", "None", ",", "state_id", "=", "...
Look for friends to drink with
[ "Look", "for", "friends", "to", "drink", "with" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L73-L84
train
Look for friends to drink with
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.looking_for_pub
def looking_for_pub(self): '''Look for a pub that accepts me and my friends''' if self['pub'] != None: return self.sober_in_pub self.debug('I am looking for a pub') group = list(self.get_neighboring_agents()) for pub in self.env.available_pubs(): self.debu...
python
def looking_for_pub(self): '''Look for a pub that accepts me and my friends''' if self['pub'] != None: return self.sober_in_pub self.debug('I am looking for a pub') group = list(self.get_neighboring_agents()) for pub in self.env.available_pubs(): self.debu...
[ "def", "looking_for_pub", "(", "self", ")", ":", "if", "self", "[", "'pub'", "]", "!=", "None", ":", "return", "self", ".", "sober_in_pub", "self", ".", "debug", "(", "'I am looking for a pub'", ")", "group", "=", "list", "(", "self", ".", "get_neighboring...
Look for a pub that accepts me and my friends
[ "Look", "for", "a", "pub", "that", "accepts", "me", "and", "my", "friends" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L87-L97
train
Look for a pub that accepts me and my friends
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.befriend
def befriend(self, other_agent, force=False): ''' Try to become friends with another agent. The chances of success depend on both agents' openness. ''' if force or self['openness'] > random(): self.env.add_edge(self, other_agent) self.info('Made some frien...
python
def befriend(self, other_agent, force=False): ''' Try to become friends with another agent. The chances of success depend on both agents' openness. ''' if force or self['openness'] > random(): self.env.add_edge(self, other_agent) self.info('Made some frien...
[ "def", "befriend", "(", "self", ",", "other_agent", ",", "force", "=", "False", ")", ":", "if", "force", "or", "self", "[", "'openness'", "]", ">", "random", "(", ")", ":", "self", ".", "env", ".", "add_edge", "(", "self", ",", "other_agent", ")", ...
Try to become friends with another agent. The chances of success depend on both agents' openness.
[ "Try", "to", "become", "friends", "with", "another", "agent", ".", "The", "chances", "of", "success", "depend", "on", "both", "agents", "openness", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L125-L134
train
Try to become friends with another agent.
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.try_friends
def try_friends(self, others): ''' Look for random agents around me and try to befriend them''' befriended = False k = int(10*self['openness']) shuffle(others) for friend in islice(others, k): # random.choice >= 3.7 if friend == self: continue ...
python
def try_friends(self, others): ''' Look for random agents around me and try to befriend them''' befriended = False k = int(10*self['openness']) shuffle(others) for friend in islice(others, k): # random.choice >= 3.7 if friend == self: continue ...
[ "def", "try_friends", "(", "self", ",", "others", ")", ":", "befriended", "=", "False", "k", "=", "int", "(", "10", "*", "self", "[", "'openness'", "]", ")", "shuffle", "(", "others", ")", "for", "friend", "in", "islice", "(", "others", ",", "k", "...
Look for random agents around me and try to befriend them
[ "Look", "for", "random", "agents", "around", "me", "and", "try", "to", "befriend", "them" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L136-L150
train
Look for random agents around me and try to befriend them
byu-dml/metalearn
metalearn/metafeatures/common_operations.py
profile_distribution
def profile_distribution(data): """ Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector Parameters ---------- data: array of real values Returns ------- features = dictionary containing the min, max, mean, and standard deviation """ i...
python
def profile_distribution(data): """ Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector Parameters ---------- data: array of real values Returns ------- features = dictionary containing the min, max, mean, and standard deviation """ i...
[ "def", "profile_distribution", "(", "data", ")", ":", "if", "len", "(", "data", ")", "==", "0", ":", "return", "(", "data", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ","...
Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector Parameters ---------- data: array of real values Returns ------- features = dictionary containing the min, max, mean, and standard deviation
[ "Compute", "the", "mean", "standard", "deviation", "min", "quartile1", "quartile2", "quartile3", "and", "max", "of", "a", "vector" ]
0a3b7cb339250144f6d2f70977f74fe457cecee3
https://github.com/byu-dml/metalearn/blob/0a3b7cb339250144f6d2f70977f74fe457cecee3/metalearn/metafeatures/common_operations.py#L6-L27
train
Compute the mean standard deviation min max quartile1 quartile2 quartile3 and max of a vector
kensho-technologies/grift
grift/property_types.py
DictType.to_native
def to_native(self, value): """Return the value as a dict, raising error if conversion to dict is not possible""" if isinstance(value, dict): return value elif isinstance(value, six.string_types): native_value = json.loads(value) if isinstance(native_value, di...
python
def to_native(self, value): """Return the value as a dict, raising error if conversion to dict is not possible""" if isinstance(value, dict): return value elif isinstance(value, six.string_types): native_value = json.loads(value) if isinstance(native_value, di...
[ "def", "to_native", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "native_value", "=", "json", ".", "loads...
Return the value as a dict, raising error if conversion to dict is not possible
[ "Return", "the", "value", "as", "a", "dict", "raising", "error", "if", "conversion", "to", "dict", "is", "not", "possible" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L14-L23
train
Return the value as a dict raising error if conversion is not possible
kensho-technologies/grift
grift/property_types.py
ListType.to_native
def to_native(self, value): """Load a value as a list, converting items if necessary""" if isinstance(value, six.string_types): value_list = value.split(self.string_delim) else: value_list = value to_native = self.member_type.to_native if self.member_type is not ...
python
def to_native(self, value): """Load a value as a list, converting items if necessary""" if isinstance(value, six.string_types): value_list = value.split(self.string_delim) else: value_list = value to_native = self.member_type.to_native if self.member_type is not ...
[ "def", "to_native", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value_list", "=", "value", ".", "split", "(", "self", ".", "string_delim", ")", "else", ":", "value_list", "=", "valu...
Load a value as a list, converting items if necessary
[ "Load", "a", "value", "as", "a", "list", "converting", "items", "if", "necessary" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L47-L55
train
Load a value as a list converting items if necessary
kensho-technologies/grift
grift/property_types.py
ListType.validate_member_type
def validate_member_type(self, value): """Validate each member of the list, if member_type exists""" if self.member_type: for item in value: self.member_type.validate(item)
python
def validate_member_type(self, value): """Validate each member of the list, if member_type exists""" if self.member_type: for item in value: self.member_type.validate(item)
[ "def", "validate_member_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "member_type", ":", "for", "item", "in", "value", ":", "self", ".", "member_type", ".", "validate", "(", "item", ")" ]
Validate each member of the list, if member_type exists
[ "Validate", "each", "member", "of", "the", "list", "if", "member_type", "exists" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L57-L61
train
Validate each member of the list
kensho-technologies/grift
grift/property_types.py
ListType.validate_length
def validate_length(self, value): """Validate the length of value, if min_length or max_length was specified""" list_len = len(value) if value else 0 if self.max_length is not None and list_len > self.max_length: raise ValidationError( u'List has {} values; max lengt...
python
def validate_length(self, value): """Validate the length of value, if min_length or max_length was specified""" list_len = len(value) if value else 0 if self.max_length is not None and list_len > self.max_length: raise ValidationError( u'List has {} values; max lengt...
[ "def", "validate_length", "(", "self", ",", "value", ")", ":", "list_len", "=", "len", "(", "value", ")", "if", "value", "else", "0", "if", "self", ".", "max_length", "is", "not", "None", "and", "list_len", ">", "self", ".", "max_length", ":", "raise",...
Validate the length of value, if min_length or max_length was specified
[ "Validate", "the", "length", "of", "value", "if", "min_length", "or", "max_length", "was", "specified" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L63-L73
train
Validate the length of value if min_length or max_length was specified
kensho-technologies/grift
grift/property_types.py
NetworkType.validate_resource
def validate_resource(self, value): """Validate the network resource with exponential backoff""" def do_backoff(*args, **kwargs): """Call self._test_connection with exponential backoff, for self._max_tries attempts""" attempts = 0 while True: try: ...
python
def validate_resource(self, value): """Validate the network resource with exponential backoff""" def do_backoff(*args, **kwargs): """Call self._test_connection with exponential backoff, for self._max_tries attempts""" attempts = 0 while True: try: ...
[ "def", "validate_resource", "(", "self", ",", "value", ")", ":", "def", "do_backoff", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Call self._test_connection with exponential backoff, for self._max_tries attempts\"\"\"", "attempts", "=", "0", "while", "...
Validate the network resource with exponential backoff
[ "Validate", "the", "network", "resource", "with", "exponential", "backoff" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L101-L119
train
Validate the network resource with exponential backoff.
mozillazg/python-shanbay
shanbay/__init__.py
Shanbay.login
def login(self, **kwargs): """登录""" payload = { 'username': self.username, 'password': self.password, } headers = kwargs.setdefault('headers', {}) headers.setdefault( 'Referer', 'https://www.shanbay.com/web/account/login' ) ...
python
def login(self, **kwargs): """登录""" payload = { 'username': self.username, 'password': self.password, } headers = kwargs.setdefault('headers', {}) headers.setdefault( 'Referer', 'https://www.shanbay.com/web/account/login' ) ...
[ "def", "login", "(", "self", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "'username'", ":", "self", ".", "username", ",", "'password'", ":", "self", ".", "password", ",", "}", "headers", "=", "kwargs", ".", "setdefault", "(", "'headers'", ...
登录
[ "登录" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/__init__.py#L68-L82
train
Login to Shanbay.
mozillazg/python-shanbay
shanbay/__init__.py
Shanbay.server_date_utc
def server_date_utc(self): """获取扇贝网服务器时间(UTC 时间)""" date_str = self.request('http://www.shanbay.com', 'head' ).headers['date'] date_utc = datetime.datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S GMT') return...
python
def server_date_utc(self): """获取扇贝网服务器时间(UTC 时间)""" date_str = self.request('http://www.shanbay.com', 'head' ).headers['date'] date_utc = datetime.datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S GMT') return...
[ "def", "server_date_utc", "(", "self", ")", ":", "date_str", "=", "self", ".", "request", "(", "'http://www.shanbay.com'", ",", "'head'", ")", ".", "headers", "[", "'date'", "]", "date_utc", "=", "datetime", ".", "datetime", ".", "strptime", "(", "date_str",...
获取扇贝网服务器时间(UTC 时间)
[ "获取扇贝网服务器时间(UTC", "时间)" ]
d505ba614dc13a36afce46969d13fc64e10dde0d
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/__init__.py#L84-L90
train
Get server s date in UTC
byu-dml/metalearn
metalearn/metafeatures/metafeatures.py
Metafeatures.list_metafeatures
def list_metafeatures(cls, group="all"): """ Returns a list of metafeatures computable by the Metafeatures class. """ # todo make group for intractable metafeatures for wide datasets or # datasets with high cardinality categorical columns: # PredPCA1, PredPCA2, PredPCA3, ...
python
def list_metafeatures(cls, group="all"): """ Returns a list of metafeatures computable by the Metafeatures class. """ # todo make group for intractable metafeatures for wide datasets or # datasets with high cardinality categorical columns: # PredPCA1, PredPCA2, PredPCA3, ...
[ "def", "list_metafeatures", "(", "cls", ",", "group", "=", "\"all\"", ")", ":", "# todo make group for intractable metafeatures for wide datasets or", "# datasets with high cardinality categorical columns:", "# PredPCA1, PredPCA2, PredPCA3, PredEigen1, PredEigen2, PredEigen3,", "# PredDet,...
Returns a list of metafeatures computable by the Metafeatures class.
[ "Returns", "a", "list", "of", "metafeatures", "computable", "by", "the", "Metafeatures", "class", "." ]
0a3b7cb339250144f6d2f70977f74fe457cecee3
https://github.com/byu-dml/metalearn/blob/0a3b7cb339250144f6d2f70977f74fe457cecee3/metalearn/metafeatures/metafeatures.py#L49-L69
train
Returns a list of metafeatures computable by the Metafeatures class.
byu-dml/metalearn
metalearn/metafeatures/metafeatures.py
Metafeatures.compute
def compute( self, X: DataFrame, Y: Series=None, column_types: Dict[str, str]=None, metafeature_ids: List=None, exclude: List=None, sample_shape=None, seed=None, n_folds=2, verbose=False, timeout=None ) -> dict: """ Parameters ---------- X: pandas.Data...
python
def compute( self, X: DataFrame, Y: Series=None, column_types: Dict[str, str]=None, metafeature_ids: List=None, exclude: List=None, sample_shape=None, seed=None, n_folds=2, verbose=False, timeout=None ) -> dict: """ Parameters ---------- X: pandas.Data...
[ "def", "compute", "(", "self", ",", "X", ":", "DataFrame", ",", "Y", ":", "Series", "=", "None", ",", "column_types", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "metafeature_ids", ":", "List", "=", "None", ",", "exclude", ":", "Lis...
Parameters ---------- X: pandas.DataFrame, the dataset features Y: pandas.Series, the dataset targets column_types: Dict[str, str], dict from column name to column type as "NUMERIC" or "CATEGORICAL" or "TEXT", must include Y column metafeature_ids: list, the metafeatu...
[ "Parameters", "----------", "X", ":", "pandas", ".", "DataFrame", "the", "dataset", "features", "Y", ":", "pandas", ".", "Series", "the", "dataset", "targets", "column_types", ":", "Dict", "[", "str", "str", "]", "dict", "from", "column", "name", "to", "co...
0a3b7cb339250144f6d2f70977f74fe457cecee3
https://github.com/byu-dml/metalearn/blob/0a3b7cb339250144f6d2f70977f74fe457cecee3/metalearn/metafeatures/metafeatures.py#L71-L167
train
Compute the metafeatures of the referenced base class for the given metafeatures.
byu-dml/metalearn
metalearn/metafeatures/metafeatures.py
Metafeatures._sample_rows
def _sample_rows(self, X, Y, sample_shape, seed): """ Stratified uniform sampling of rows, according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation. """ if sample_shape[0] is None or X.shape[0] <= sample_shape[0]: ...
python
def _sample_rows(self, X, Y, sample_shape, seed): """ Stratified uniform sampling of rows, according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation. """ if sample_shape[0] is None or X.shape[0] <= sample_shape[0]: ...
[ "def", "_sample_rows", "(", "self", ",", "X", ",", "Y", ",", "sample_shape", ",", "seed", ")", ":", "if", "sample_shape", "[", "0", "]", "is", "None", "or", "X", ".", "shape", "[", "0", "]", "<=", "sample_shape", "[", "0", "]", ":", "X_sample", "...
Stratified uniform sampling of rows, according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation.
[ "Stratified", "uniform", "sampling", "of", "rows", "according", "to", "the", "classes", "in", "Y", ".", "Ensures", "there", "are", "enough", "samples", "from", "each", "class", "in", "Y", "for", "cross", "validation", "." ]
0a3b7cb339250144f6d2f70977f74fe457cecee3
https://github.com/byu-dml/metalearn/blob/0a3b7cb339250144f6d2f70977f74fe457cecee3/metalearn/metafeatures/metafeatures.py#L466-L488
train
Stratified uniform sampling of rows according to the classes in Y.
kensho-technologies/grift
grift/loaders.py
VaultLoader.from_token
def from_token(cls, url, path, token): """Constructor: use token authentication to read secrets from a Vault path See https://www.vaultproject.io/docs/auth/token.html Args: url: Vault url path: Vault path where secrets are stored vault_token: token (must hav...
python
def from_token(cls, url, path, token): """Constructor: use token authentication to read secrets from a Vault path See https://www.vaultproject.io/docs/auth/token.html Args: url: Vault url path: Vault path where secrets are stored vault_token: token (must hav...
[ "def", "from_token", "(", "cls", ",", "url", ",", "path", ",", "token", ")", ":", "source_dict", "=", "cls", ".", "_fetch_secrets", "(", "url", ",", "path", ",", "token", ")", "return", "cls", "(", "source_dict", ",", "url", ",", "path", ",", "token"...
Constructor: use token authentication to read secrets from a Vault path See https://www.vaultproject.io/docs/auth/token.html Args: url: Vault url path: Vault path where secrets are stored vault_token: token (must have access to vault path)
[ "Constructor", ":", "use", "token", "authentication", "to", "read", "secrets", "from", "a", "Vault", "path" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L100-L111
train
Create a new instance of a new key - value store using a token
kensho-technologies/grift
grift/loaders.py
VaultLoader.from_app_role
def from_app_role(cls, url, path, role_id, secret_id): """Constructor: use AppRole authentication to read secrets from a Vault path See https://www.vaultproject.io/docs/auth/approle.html Args: url: Vault url path: Vault path where secrets are stored role_id:...
python
def from_app_role(cls, url, path, role_id, secret_id): """Constructor: use AppRole authentication to read secrets from a Vault path See https://www.vaultproject.io/docs/auth/approle.html Args: url: Vault url path: Vault path where secrets are stored role_id:...
[ "def", "from_app_role", "(", "cls", ",", "url", ",", "path", ",", "role_id", ",", "secret_id", ")", ":", "token", "=", "cls", ".", "_fetch_app_role_token", "(", "url", ",", "role_id", ",", "secret_id", ")", "source_dict", "=", "cls", ".", "_fetch_secrets",...
Constructor: use AppRole authentication to read secrets from a Vault path See https://www.vaultproject.io/docs/auth/approle.html Args: url: Vault url path: Vault path where secrets are stored role_id: Vault RoleID secret_id: Vault SecretID
[ "Constructor", ":", "use", "AppRole", "authentication", "to", "read", "secrets", "from", "a", "Vault", "path" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L114-L127
train
Create a new object from a Vault AppRole
kensho-technologies/grift
grift/loaders.py
VaultLoader._fetch_secrets
def _fetch_secrets(vault_url, path, token): """Read data from the vault path""" url = _url_joiner(vault_url, 'v1', path) resp = requests.get(url, headers=VaultLoader._get_headers(token)) resp.raise_for_status() data = resp.json() if data.get('errors'): raise V...
python
def _fetch_secrets(vault_url, path, token): """Read data from the vault path""" url = _url_joiner(vault_url, 'v1', path) resp = requests.get(url, headers=VaultLoader._get_headers(token)) resp.raise_for_status() data = resp.json() if data.get('errors'): raise V...
[ "def", "_fetch_secrets", "(", "vault_url", ",", "path", ",", "token", ")", ":", "url", "=", "_url_joiner", "(", "vault_url", ",", "'v1'", ",", "path", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "VaultLoader", ".", "_get_...
Read data from the vault path
[ "Read", "data", "from", "the", "vault", "path" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L140-L149
train
Fetch data from the vault path
kensho-technologies/grift
grift/loaders.py
VaultLoader._fetch_app_role_token
def _fetch_app_role_token(vault_url, role_id, secret_id): """Get a Vault token, using the RoleID and SecretID""" url = _url_joiner(vault_url, 'v1/auth/approle/login') resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id}) resp.raise_for_status() data = resp....
python
def _fetch_app_role_token(vault_url, role_id, secret_id): """Get a Vault token, using the RoleID and SecretID""" url = _url_joiner(vault_url, 'v1/auth/approle/login') resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id}) resp.raise_for_status() data = resp....
[ "def", "_fetch_app_role_token", "(", "vault_url", ",", "role_id", ",", "secret_id", ")", ":", "url", "=", "_url_joiner", "(", "vault_url", ",", "'v1/auth/approle/login'", ")", "resp", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "{", "'role_id...
Get a Vault token, using the RoleID and SecretID
[ "Get", "a", "Vault", "token", "using", "the", "RoleID", "and", "SecretID" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L152-L160
train
Fetch a Vault token using the RoleID and SecretID
kensho-technologies/grift
grift/loaders.py
VaultLoader.reload
def reload(self): """Reread secrets from the vault path""" self._source = self._fetch_secrets(self._vault_url, self._path, self._token)
python
def reload(self): """Reread secrets from the vault path""" self._source = self._fetch_secrets(self._vault_url, self._path, self._token)
[ "def", "reload", "(", "self", ")", ":", "self", ".", "_source", "=", "self", ".", "_fetch_secrets", "(", "self", ".", "_vault_url", ",", "self", ".", "_path", ",", "self", ".", "_token", ")" ]
Reread secrets from the vault path
[ "Reread", "secrets", "from", "the", "vault", "path" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L162-L164
train
Reload the secrets from the vault path
kensho-technologies/grift
grift/loaders.py
VaultLoader.lookup_token
def lookup_token(self): """Convenience method: look up the vault token""" url = _url_joiner(self._vault_url, 'v1/auth/token/lookup-self') resp = requests.get(url, headers=self._headers) resp.raise_for_status() data = resp.json() if data.get('errors'): raise Va...
python
def lookup_token(self): """Convenience method: look up the vault token""" url = _url_joiner(self._vault_url, 'v1/auth/token/lookup-self') resp = requests.get(url, headers=self._headers) resp.raise_for_status() data = resp.json() if data.get('errors'): raise Va...
[ "def", "lookup_token", "(", "self", ")", ":", "url", "=", "_url_joiner", "(", "self", ".", "_vault_url", ",", "'v1/auth/token/lookup-self'", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", ")", "resp", ...
Convenience method: look up the vault token
[ "Convenience", "method", ":", "look", "up", "the", "vault", "token" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L166-L174
train
Convenience method to look up the vault token
kensho-technologies/grift
grift/loaders.py
VaultLoader.renew_token
def renew_token(self): """Convenience method: renew Vault token""" url = _url_joiner(self._vault_url, 'v1/auth/token/renew-self') resp = requests.get(url, headers=self._headers) resp.raise_for_status() data = resp.json() if data.get('errors'): raise VaultExcep...
python
def renew_token(self): """Convenience method: renew Vault token""" url = _url_joiner(self._vault_url, 'v1/auth/token/renew-self') resp = requests.get(url, headers=self._headers) resp.raise_for_status() data = resp.json() if data.get('errors'): raise VaultExcep...
[ "def", "renew_token", "(", "self", ")", ":", "url", "=", "_url_joiner", "(", "self", ".", "_vault_url", ",", "'v1/auth/token/renew-self'", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", ")", "resp", "....
Convenience method: renew Vault token
[ "Convenience", "method", ":", "renew", "Vault", "token" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L176-L184
train
Convenience method to renew Vault token
inveniosoftware/invenio-search-ui
invenio_search_ui/views.py
sorted_options
def sorted_options(sort_options): """Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS. """ return [ { 'title': v['title'], ...
python
def sorted_options(sort_options): """Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS. """ return [ { 'title': v['title'], ...
[ "def", "sorted_options", "(", "sort_options", ")", ":", "return", "[", "{", "'title'", ":", "v", "[", "'title'", "]", ",", "'value'", ":", "(", "'-{0}'", ".", "format", "(", "k", ")", "if", "v", ".", "get", "(", "'default_order'", ",", "'asc'", ")", ...
Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS.
[ "Sort", "sort", "options", "for", "display", "." ]
4b61737f938cbfdc1aad6602a73f3a24d53b3312
https://github.com/inveniosoftware/invenio-search-ui/blob/4b61737f938cbfdc1aad6602a73f3a24d53b3312/invenio_search_ui/views.py#L29-L44
train
Sort options for Invenio - Search - JS.
bitlabstudio/django-libs
django_libs/utils/converter.py
html_to_plain_text
def html_to_plain_text(html): """Converts html code into formatted plain text.""" # Use BeautifulSoup to normalize the html soup = BeautifulSoup(html, "html.parser") # Init the parser parser = HTML2PlainParser() parser.feed(str(soup.encode('utf-8'))) # Strip the end of the plain text res...
python
def html_to_plain_text(html): """Converts html code into formatted plain text.""" # Use BeautifulSoup to normalize the html soup = BeautifulSoup(html, "html.parser") # Init the parser parser = HTML2PlainParser() parser.feed(str(soup.encode('utf-8'))) # Strip the end of the plain text res...
[ "def", "html_to_plain_text", "(", "html", ")", ":", "# Use BeautifulSoup to normalize the html", "soup", "=", "BeautifulSoup", "(", "html", ",", "\"html.parser\"", ")", "# Init the parser", "parser", "=", "HTML2PlainParser", "(", ")", "parser", ".", "feed", "(", "st...
Converts html code into formatted plain text.
[ "Converts", "html", "code", "into", "formatted", "plain", "text", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/converter.py#L112-L126
train
Converts html code into formatted plain text.
bitlabstudio/django-libs
django_libs/utils/converter.py
HTML2PlainParser.handle_starttag
def handle_starttag(self, tag, attrs): """Handles every start tag like e.g. <p>.""" if (tag in self.newline_before_elements): self.text += '\n' if (tag in self.stroke_before_elements and not self.text.endswith(self.stroke_text)): # Put a stroke in front of...
python
def handle_starttag(self, tag, attrs): """Handles every start tag like e.g. <p>.""" if (tag in self.newline_before_elements): self.text += '\n' if (tag in self.stroke_before_elements and not self.text.endswith(self.stroke_text)): # Put a stroke in front of...
[ "def", "handle_starttag", "(", "self", ",", "tag", ",", "attrs", ")", ":", "if", "(", "tag", "in", "self", ".", "newline_before_elements", ")", ":", "self", ".", "text", "+=", "'\\n'", "if", "(", "tag", "in", "self", ".", "stroke_before_elements", "and",...
Handles every start tag like e.g. <p>.
[ "Handles", "every", "start", "tag", "like", "e", ".", "g", ".", "<p", ">", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/converter.py#L55-L68
train
Handles every start tag like e. g. <p >.
bitlabstudio/django-libs
django_libs/utils/converter.py
HTML2PlainParser.handle_data
def handle_data(self, data): """Handles data between tags.""" # Only proceed with unignored elements if self.lasttag not in self.ignored_elements: # Remove any predefined linebreaks text = data.replace('\n', '') # If there's some text left, proceed! ...
python
def handle_data(self, data): """Handles data between tags.""" # Only proceed with unignored elements if self.lasttag not in self.ignored_elements: # Remove any predefined linebreaks text = data.replace('\n', '') # If there's some text left, proceed! ...
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "# Only proceed with unignored elements", "if", "self", ".", "lasttag", "not", "in", "self", ".", "ignored_elements", ":", "# Remove any predefined linebreaks", "text", "=", "data", ".", "replace", "(", "'\...
Handles data between tags.
[ "Handles", "data", "between", "tags", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/converter.py#L70-L84
train
Handles data between tags.