repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
CZ-NIC/python-rt | rt.py | Rt.create_ticket | def create_ticket(self, Queue=None, files=[], **kwargs):
""" Create new ticket and set given parameters.
Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``::
content=id: ticket/new
Queue: General
Owner: Nobody
Requestors: somebody@example.com
Subject: Ticket created through REST API
Text: Lorem Ipsum
In case of success returned message has this form::
RT/3.8.7 200 Ok
# Ticket 123456 created.
# Ticket 123456 updated.
Otherwise::
RT/3.8.7 200 Ok
# Required: id, Queue
+ list of some key, value pairs, probably default values.
:keyword Queue: Queue where to create ticket
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ID of new ticket or ``-1``, if creating failed
"""
post_data = 'id: ticket/new\nQueue: {}\n'.format(Queue or self.default_queue, )
for key in kwargs:
if key[:4] == 'Text':
post_data += "{}: {}\n".format(key, re.sub(r'\n', r'\n ', kwargs[key]))
elif key[:3] == 'CF_':
post_data += "CF.{{{}}}: {}\n".format(key[3:], kwargs[key])
else:
post_data += "{}: {}\n".format(key, kwargs[key])
for file_info in files:
post_data += "\nAttachment: {}".format(file_info[0], )
msg = self.__request('ticket/new', post_data={'content': post_data}, files=files)
for line in msg.split('\n')[2:-1]:
res = self.RE_PATTERNS['ticket_created_pattern'].match(line)
if res is not None:
return int(res.group(1))
warnings.warn(line[2:])
return -1 | python | def create_ticket(self, Queue=None, files=[], **kwargs):
""" Create new ticket and set given parameters.
Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``::
content=id: ticket/new
Queue: General
Owner: Nobody
Requestors: somebody@example.com
Subject: Ticket created through REST API
Text: Lorem Ipsum
In case of success returned message has this form::
RT/3.8.7 200 Ok
# Ticket 123456 created.
# Ticket 123456 updated.
Otherwise::
RT/3.8.7 200 Ok
# Required: id, Queue
+ list of some key, value pairs, probably default values.
:keyword Queue: Queue where to create ticket
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ID of new ticket or ``-1``, if creating failed
"""
post_data = 'id: ticket/new\nQueue: {}\n'.format(Queue or self.default_queue, )
for key in kwargs:
if key[:4] == 'Text':
post_data += "{}: {}\n".format(key, re.sub(r'\n', r'\n ', kwargs[key]))
elif key[:3] == 'CF_':
post_data += "CF.{{{}}}: {}\n".format(key[3:], kwargs[key])
else:
post_data += "{}: {}\n".format(key, kwargs[key])
for file_info in files:
post_data += "\nAttachment: {}".format(file_info[0], )
msg = self.__request('ticket/new', post_data={'content': post_data}, files=files)
for line in msg.split('\n')[2:-1]:
res = self.RE_PATTERNS['ticket_created_pattern'].match(line)
if res is not None:
return int(res.group(1))
warnings.warn(line[2:])
return -1 | [
"def",
"create_ticket",
"(",
"self",
",",
"Queue",
"=",
"None",
",",
"files",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"post_data",
"=",
"'id: ticket/new\\nQueue: {}\\n'",
".",
"format",
"(",
"Queue",
"or",
"self",
".",
"default_queue",
",",
")",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"[",
":",
"4",
"]",
"==",
"'Text'",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"re",
".",
"sub",
"(",
"r'\\n'",
",",
"r'\\n '",
",",
"kwargs",
"[",
"key",
"]",
")",
")",
"elif",
"key",
"[",
":",
"3",
"]",
"==",
"'CF_'",
":",
"post_data",
"+=",
"\"CF.{{{}}}: {}\\n\"",
".",
"format",
"(",
"key",
"[",
"3",
":",
"]",
",",
"kwargs",
"[",
"key",
"]",
")",
"else",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"kwargs",
"[",
"key",
"]",
")",
"for",
"file_info",
"in",
"files",
":",
"post_data",
"+=",
"\"\\nAttachment: {}\"",
".",
"format",
"(",
"file_info",
"[",
"0",
"]",
",",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/new'",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
",",
"files",
"=",
"files",
")",
"for",
"line",
"in",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
":",
"-",
"1",
"]",
":",
"res",
"=",
"self",
".",
"RE_PATTERNS",
"[",
"'ticket_created_pattern'",
"]",
".",
"match",
"(",
"line",
")",
"if",
"res",
"is",
"not",
"None",
":",
"return",
"int",
"(",
"res",
".",
"group",
"(",
"1",
")",
")",
"warnings",
".",
"warn",
"(",
"line",
"[",
"2",
":",
"]",
")",
"return",
"-",
"1"
] | Create new ticket and set given parameters.
Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``::
content=id: ticket/new
Queue: General
Owner: Nobody
Requestors: somebody@example.com
Subject: Ticket created through REST API
Text: Lorem Ipsum
In case of success returned message has this form::
RT/3.8.7 200 Ok
# Ticket 123456 created.
# Ticket 123456 updated.
Otherwise::
RT/3.8.7 200 Ok
# Required: id, Queue
+ list of some key, value pairs, probably default values.
:keyword Queue: Queue where to create ticket
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ID of new ticket or ``-1``, if creating failed | [
"Create",
"new",
"ticket",
"and",
"set",
"given",
"parameters",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L642-L700 | train | 235,200 |
CZ-NIC/python-rt | rt.py | Rt.edit_ticket | def edit_ticket(self, ticket_id, **kwargs):
""" Edit ticket values.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)
"""
post_data = ''
for key, value in iteritems(kwargs):
if isinstance(value, (list, tuple)):
value = ", ".join(value)
if key[:3] != 'CF_':
post_data += "{}: {}\n".format(key, value)
else:
post_data += "CF.{{{}}}: {}\n".format(key[3:], value)
msg = self.__request('ticket/{}/edit'.format(str(ticket_id)), post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['update_pattern'].match(state) is not None | python | def edit_ticket(self, ticket_id, **kwargs):
""" Edit ticket values.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)
"""
post_data = ''
for key, value in iteritems(kwargs):
if isinstance(value, (list, tuple)):
value = ", ".join(value)
if key[:3] != 'CF_':
post_data += "{}: {}\n".format(key, value)
else:
post_data += "CF.{{{}}}: {}\n".format(key[3:], value)
msg = self.__request('ticket/{}/edit'.format(str(ticket_id)), post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['update_pattern'].match(state) is not None | [
"def",
"edit_ticket",
"(",
"self",
",",
"ticket_id",
",",
"*",
"*",
"kwargs",
")",
":",
"post_data",
"=",
"''",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"value",
"=",
"\", \"",
".",
"join",
"(",
"value",
")",
"if",
"key",
"[",
":",
"3",
"]",
"!=",
"'CF_'",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"value",
")",
"else",
":",
"post_data",
"+=",
"\"CF.{{{}}}: {}\\n\"",
".",
"format",
"(",
"key",
"[",
"3",
":",
"]",
",",
"value",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/edit'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
")",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
")",
"state",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'update_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None"
] | Edit ticket values.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed) | [
"Edit",
"ticket",
"values",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L702-L731 | train | 235,201 |
CZ-NIC/python-rt | rt.py | Rt.get_history | def get_history(self, ticket_id, transaction_id=None):
""" Get set of history items.
:param ticket_id: ID of ticket
:keyword transaction_id: If set to None, all history items are
returned, if set to ID of valid transaction
just one history item is returned
:returns: List of history items ordered increasingly by time of event.
Each history item is dictionary with following keys:
Description, Creator, Data, Created, TimeTaken, NewValue,
Content, Field, OldValue, Ticket, Type, id, Attachments
All these fields are strings, just 'Attachments' holds list
of pairs (attachment_id,filename_with_size).
Returns None if ticket or transaction does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
if transaction_id is None:
# We are using "long" format to get all history items at once.
# Each history item is then separated by double dash.
msgs = self.__request('ticket/{}/history?format=l'.format(str(ticket_id), ))
else:
msgs = self.__request('ticket/{}/history/id/{}'.format(str(ticket_id), str(transaction_id)))
lines = msgs.split('\n')
if (len(lines) > 2) and (
self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match(
lines[2])):
return None
msgs = msgs.split('\n--\n')
items = []
for msg in msgs:
pairs = {}
msg = msg.split('\n')
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_id:
raise UnexpectedMessageFormat('Unexpected history entry. \
Missing line starting with `Content:`.')
atta_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['attachments_pattern'].match(m)]
atta_id = atta_matching[0] if atta_matching else None
if not atta_id:
raise UnexpectedMessageFormat('Unexpected attachment part of history entry. \
Missing line starting with `Attachements:`.')
for i in range(cont_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
content = msg[cont_id][9:]
cont_id += 1
while (cont_id < len(msg)) and (msg[cont_id][:9] == ' ' * 9):
content += '\n' + msg[cont_id][9:]
cont_id += 1
pairs['Content'] = content
for i in range(cont_id, atta_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
attachments = []
for i in range(atta_id + 1, len(msg)):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
attachments.append((int(header),
content.strip()))
pairs['Attachments'] = attachments
items.append(pairs)
return items | python | def get_history(self, ticket_id, transaction_id=None):
""" Get set of history items.
:param ticket_id: ID of ticket
:keyword transaction_id: If set to None, all history items are
returned, if set to ID of valid transaction
just one history item is returned
:returns: List of history items ordered increasingly by time of event.
Each history item is dictionary with following keys:
Description, Creator, Data, Created, TimeTaken, NewValue,
Content, Field, OldValue, Ticket, Type, id, Attachments
All these fields are strings, just 'Attachments' holds list
of pairs (attachment_id,filename_with_size).
Returns None if ticket or transaction does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
if transaction_id is None:
# We are using "long" format to get all history items at once.
# Each history item is then separated by double dash.
msgs = self.__request('ticket/{}/history?format=l'.format(str(ticket_id), ))
else:
msgs = self.__request('ticket/{}/history/id/{}'.format(str(ticket_id), str(transaction_id)))
lines = msgs.split('\n')
if (len(lines) > 2) and (
self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match(
lines[2])):
return None
msgs = msgs.split('\n--\n')
items = []
for msg in msgs:
pairs = {}
msg = msg.split('\n')
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_id:
raise UnexpectedMessageFormat('Unexpected history entry. \
Missing line starting with `Content:`.')
atta_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['attachments_pattern'].match(m)]
atta_id = atta_matching[0] if atta_matching else None
if not atta_id:
raise UnexpectedMessageFormat('Unexpected attachment part of history entry. \
Missing line starting with `Attachements:`.')
for i in range(cont_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
content = msg[cont_id][9:]
cont_id += 1
while (cont_id < len(msg)) and (msg[cont_id][:9] == ' ' * 9):
content += '\n' + msg[cont_id][9:]
cont_id += 1
pairs['Content'] = content
for i in range(cont_id, atta_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
attachments = []
for i in range(atta_id + 1, len(msg)):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
attachments.append((int(header),
content.strip()))
pairs['Attachments'] = attachments
items.append(pairs)
return items | [
"def",
"get_history",
"(",
"self",
",",
"ticket_id",
",",
"transaction_id",
"=",
"None",
")",
":",
"if",
"transaction_id",
"is",
"None",
":",
"# We are using \"long\" format to get all history items at once.",
"# Each history item is then separated by double dash.",
"msgs",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/history?format=l'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"else",
":",
"msgs",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/history/id/{}'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"transaction_id",
")",
")",
")",
"lines",
"=",
"msgs",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"(",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
"or",
"self",
".",
"RE_PATTERNS",
"[",
"'not_related_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
")",
":",
"return",
"None",
"msgs",
"=",
"msgs",
".",
"split",
"(",
"'\\n--\\n'",
")",
"items",
"=",
"[",
"]",
"for",
"msg",
"in",
"msgs",
":",
"pairs",
"=",
"{",
"}",
"msg",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"cont_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'content_pattern'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"cont_id",
"=",
"cont_matching",
"[",
"0",
"]",
"if",
"cont_matching",
"else",
"None",
"if",
"not",
"cont_id",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected history entry. \\\n Missing line starting with `Content:`.'",
")",
"atta_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'attachments_pattern'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"atta_id",
"=",
"atta_matching",
"[",
"0",
"]",
"if",
"atta_matching",
"else",
"None",
"if",
"not",
"atta_id",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected attachment part of history entry. \\\n Missing line starting with `Attachements:`.'",
")",
"for",
"i",
"in",
"range",
"(",
"cont_id",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"content",
"=",
"msg",
"[",
"cont_id",
"]",
"[",
"9",
":",
"]",
"cont_id",
"+=",
"1",
"while",
"(",
"cont_id",
"<",
"len",
"(",
"msg",
")",
")",
"and",
"(",
"msg",
"[",
"cont_id",
"]",
"[",
":",
"9",
"]",
"==",
"' '",
"*",
"9",
")",
":",
"content",
"+=",
"'\\n'",
"+",
"msg",
"[",
"cont_id",
"]",
"[",
"9",
":",
"]",
"cont_id",
"+=",
"1",
"pairs",
"[",
"'Content'",
"]",
"=",
"content",
"for",
"i",
"in",
"range",
"(",
"cont_id",
",",
"atta_id",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"attachments",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"atta_id",
"+",
"1",
",",
"len",
"(",
"msg",
")",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"attachments",
".",
"append",
"(",
"(",
"int",
"(",
"header",
")",
",",
"content",
".",
"strip",
"(",
")",
")",
")",
"pairs",
"[",
"'Attachments'",
"]",
"=",
"attachments",
"items",
".",
"append",
"(",
"pairs",
")",
"return",
"items"
] | Get set of history items.
:param ticket_id: ID of ticket
:keyword transaction_id: If set to None, all history items are
returned, if set to ID of valid transaction
just one history item is returned
:returns: List of history items ordered increasingly by time of event.
Each history item is dictionary with following keys:
Description, Creator, Data, Created, TimeTaken, NewValue,
Content, Field, OldValue, Ticket, Type, id, Attachments
All these fields are strings, just 'Attachments' holds list
of pairs (attachment_id,filename_with_size).
Returns None if ticket or transaction does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message. | [
"Get",
"set",
"of",
"history",
"items",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L733-L801 | train | 235,202 |
CZ-NIC/python-rt | rt.py | Rt.get_short_history | def get_short_history(self, ticket_id):
""" Get set of short history items
:param ticket_id: ID of ticket
:returns: List of history items ordered increasingly by time of event.
Each history item is a tuple containing (id, Description).
Returns None if ticket does not exist.
"""
msg = self.__request('ticket/{}/history'.format(str(ticket_id), ))
items = []
lines = msg.split('\n')
multiline_buffer = ""
in_multiline = False
if self.__get_status_code(lines[0]) == 200:
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
if len(lines) >= 4:
for line in lines[4:]:
if line == "":
if not in_multiline:
# start of multiline block
in_multiline = True
else:
# end of multiline block
line = multiline_buffer
multiline_buffer = ""
in_multiline = False
else:
if in_multiline:
multiline_buffer += line
line = ""
if ': ' in line:
hist_id, desc = line.split(': ', 1)
items.append((int(hist_id), desc))
return items | python | def get_short_history(self, ticket_id):
""" Get set of short history items
:param ticket_id: ID of ticket
:returns: List of history items ordered increasingly by time of event.
Each history item is a tuple containing (id, Description).
Returns None if ticket does not exist.
"""
msg = self.__request('ticket/{}/history'.format(str(ticket_id), ))
items = []
lines = msg.split('\n')
multiline_buffer = ""
in_multiline = False
if self.__get_status_code(lines[0]) == 200:
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
if len(lines) >= 4:
for line in lines[4:]:
if line == "":
if not in_multiline:
# start of multiline block
in_multiline = True
else:
# end of multiline block
line = multiline_buffer
multiline_buffer = ""
in_multiline = False
else:
if in_multiline:
multiline_buffer += line
line = ""
if ': ' in line:
hist_id, desc = line.split(': ', 1)
items.append((int(hist_id), desc))
return items | [
"def",
"get_short_history",
"(",
"self",
",",
"ticket_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/history'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"items",
"=",
"[",
"]",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"multiline_buffer",
"=",
"\"\"",
"in_multiline",
"=",
"False",
"if",
"self",
".",
"__get_status_code",
"(",
"lines",
"[",
"0",
"]",
")",
"==",
"200",
":",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
":",
"return",
"None",
"if",
"len",
"(",
"lines",
")",
">=",
"4",
":",
"for",
"line",
"in",
"lines",
"[",
"4",
":",
"]",
":",
"if",
"line",
"==",
"\"\"",
":",
"if",
"not",
"in_multiline",
":",
"# start of multiline block",
"in_multiline",
"=",
"True",
"else",
":",
"# end of multiline block",
"line",
"=",
"multiline_buffer",
"multiline_buffer",
"=",
"\"\"",
"in_multiline",
"=",
"False",
"else",
":",
"if",
"in_multiline",
":",
"multiline_buffer",
"+=",
"line",
"line",
"=",
"\"\"",
"if",
"': '",
"in",
"line",
":",
"hist_id",
",",
"desc",
"=",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")",
"items",
".",
"append",
"(",
"(",
"int",
"(",
"hist_id",
")",
",",
"desc",
")",
")",
"return",
"items"
] | Get set of short history items
:param ticket_id: ID of ticket
:returns: List of history items ordered increasingly by time of event.
Each history item is a tuple containing (id, Description).
Returns None if ticket does not exist. | [
"Get",
"set",
"of",
"short",
"history",
"items"
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L803-L837 | train | 235,203 |
CZ-NIC/python-rt | rt.py | Rt.reply | def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]):
""" Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.
Form of message according to documentation::
id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with the same indentation as first
Cc: <...>
Bcc: <...>
TimeWorked: <...>
Attachment: an attachment filename/path
:param ticket_id: ID of ticket to which message belongs
:keyword text: Content of email message
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist
"""
return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files) | python | def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]):
""" Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.
Form of message according to documentation::
id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with the same indentation as first
Cc: <...>
Bcc: <...>
TimeWorked: <...>
Attachment: an attachment filename/path
:param ticket_id: ID of ticket to which message belongs
:keyword text: Content of email message
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist
"""
return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files) | [
"def",
"reply",
"(",
"self",
",",
"ticket_id",
",",
"text",
"=",
"''",
",",
"cc",
"=",
"''",
",",
"bcc",
"=",
"''",
",",
"content_type",
"=",
"'text/plain'",
",",
"files",
"=",
"[",
"]",
")",
":",
"return",
"self",
".",
"__correspond",
"(",
"ticket_id",
",",
"text",
",",
"'correspond'",
",",
"cc",
",",
"bcc",
",",
"content_type",
",",
"files",
")"
] | Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.
Form of message according to documentation::
id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with the same indentation as first
Cc: <...>
Bcc: <...>
TimeWorked: <...>
Attachment: an attachment filename/path
:param ticket_id: ID of ticket to which message belongs
:keyword text: Content of email message
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist | [
"Sends",
"email",
"message",
"to",
"the",
"contacts",
"in",
"Requestors",
"field",
"of",
"given",
"ticket",
"with",
"subject",
"as",
"is",
"set",
"in",
"Subject",
"field",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L868-L896 | train | 235,204 |
CZ-NIC/python-rt | rt.py | Rt.get_attachments | def get_attachments(self, ticket_id):
""" Get attachment list for a given ticket
:param ticket_id: ID of ticket
:returns: List of tuples for attachments belonging to given ticket.
Tuple format: (id, name, content_type, size)
Returns None if ticket does not exist.
"""
msg = self.__request('ticket/{}/attachments'.format(str(ticket_id), ))
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
attachment_infos = []
if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4):
for line in lines[4:]:
info = self.RE_PATTERNS['attachments_list_pattern'].match(line)
if info:
attachment_infos.append(info.groups())
return attachment_infos | python | def get_attachments(self, ticket_id):
""" Get attachment list for a given ticket
:param ticket_id: ID of ticket
:returns: List of tuples for attachments belonging to given ticket.
Tuple format: (id, name, content_type, size)
Returns None if ticket does not exist.
"""
msg = self.__request('ticket/{}/attachments'.format(str(ticket_id), ))
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
attachment_infos = []
if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4):
for line in lines[4:]:
info = self.RE_PATTERNS['attachments_list_pattern'].match(line)
if info:
attachment_infos.append(info.groups())
return attachment_infos | [
"def",
"get_attachments",
"(",
"self",
",",
"ticket_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
":",
"return",
"None",
"attachment_infos",
"=",
"[",
"]",
"if",
"(",
"self",
".",
"__get_status_code",
"(",
"lines",
"[",
"0",
"]",
")",
"==",
"200",
")",
"and",
"(",
"len",
"(",
"lines",
")",
">=",
"4",
")",
":",
"for",
"line",
"in",
"lines",
"[",
"4",
":",
"]",
":",
"info",
"=",
"self",
".",
"RE_PATTERNS",
"[",
"'attachments_list_pattern'",
"]",
".",
"match",
"(",
"line",
")",
"if",
"info",
":",
"attachment_infos",
".",
"append",
"(",
"info",
".",
"groups",
"(",
")",
")",
"return",
"attachment_infos"
] | Get attachment list for a given ticket
:param ticket_id: ID of ticket
:returns: List of tuples for attachments belonging to given ticket.
Tuple format: (id, name, content_type, size)
Returns None if ticket does not exist. | [
"Get",
"attachment",
"list",
"for",
"a",
"given",
"ticket"
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L933-L951 | train | 235,205 |
CZ-NIC/python-rt | rt.py | Rt.get_attachments_ids | def get_attachments_ids(self, ticket_id):
""" Get IDs of attachments for given ticket.
:param ticket_id: ID of ticket
:returns: List of IDs (type int) of attachments belonging to given
ticket. Returns None if ticket does not exist.
"""
attachments = self.get_attachments(ticket_id)
return [int(at[0]) for at in attachments] if attachments else attachments | python | def get_attachments_ids(self, ticket_id):
""" Get IDs of attachments for given ticket.
:param ticket_id: ID of ticket
:returns: List of IDs (type int) of attachments belonging to given
ticket. Returns None if ticket does not exist.
"""
attachments = self.get_attachments(ticket_id)
return [int(at[0]) for at in attachments] if attachments else attachments | [
"def",
"get_attachments_ids",
"(",
"self",
",",
"ticket_id",
")",
":",
"attachments",
"=",
"self",
".",
"get_attachments",
"(",
"ticket_id",
")",
"return",
"[",
"int",
"(",
"at",
"[",
"0",
"]",
")",
"for",
"at",
"in",
"attachments",
"]",
"if",
"attachments",
"else",
"attachments"
] | Get IDs of attachments for given ticket.
:param ticket_id: ID of ticket
:returns: List of IDs (type int) of attachments belonging to given
ticket. Returns None if ticket does not exist. | [
"Get",
"IDs",
"of",
"attachments",
"for",
"given",
"ticket",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L953-L961 | train | 235,206 |
CZ-NIC/python-rt | rt.py | Rt.get_attachment | def get_attachment(self, ticket_id, attachment_id):
""" Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
* Parent
* Creator
* Created
* Filename
* Content (bytes type)
* Headers
* MessageId
* ContentEncoding
* id
* Subject
All these fields are strings, just 'Headers' holds another
dictionary with attachment headers as strings e.g.:
* Delivered-To
* From
* Return-Path
* Content-Length
* To
* X-Seznam-User
* X-QM-Mark
* Domainkey-Signature
* RT-Message-ID
* X-RT-Incoming-Encryption
* X-Original-To
* Message-ID
* X-Spam-Status
* In-Reply-To
* Date
* Received
* X-Country
* X-Spam-Checker-Version
* X-Abuse
* MIME-Version
* Content-Type
* Subject
.. warning:: Content-Length parameter is set after opening
ticket in web interface!
Set of headers available depends on mailservers sending
emails not on Request Tracker!
Returns None if ticket or attachment does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
msg = self.__request('ticket/{}/attachments/{}'.format(str(ticket_id), str(attachment_id)),
text_response=False)
msg = msg.split(b'\n')
if (len(msg) > 2) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2])):
return None
msg = msg[2:]
head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)]
head_id = head_matching[0] if head_matching else None
if not head_id:
raise UnexpectedMessageFormat('Unexpected headers part of attachment entry. \
Missing line starting with `Headers:`.')
msg[head_id] = re.sub(b'^Headers: (.*)$', r'\1', msg[head_id])
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_matching:
raise UnexpectedMessageFormat('Unexpected content part of attachment entry. \
Missing line starting with `Content:`.')
pairs = {}
for i in range(head_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
headers = {}
for i in range(head_id, cont_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
pairs['Headers'] = headers
content = msg[cont_id][9:]
for i in range(cont_id + 1, len(msg)):
if msg[i][:9] == (b' ' * 9):
content += b'\n' + msg[i][9:]
pairs['Content'] = content
return pairs | python | def get_attachment(self, ticket_id, attachment_id):
""" Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
* Parent
* Creator
* Created
* Filename
* Content (bytes type)
* Headers
* MessageId
* ContentEncoding
* id
* Subject
All these fields are strings, just 'Headers' holds another
dictionary with attachment headers as strings e.g.:
* Delivered-To
* From
* Return-Path
* Content-Length
* To
* X-Seznam-User
* X-QM-Mark
* Domainkey-Signature
* RT-Message-ID
* X-RT-Incoming-Encryption
* X-Original-To
* Message-ID
* X-Spam-Status
* In-Reply-To
* Date
* Received
* X-Country
* X-Spam-Checker-Version
* X-Abuse
* MIME-Version
* Content-Type
* Subject
.. warning:: Content-Length parameter is set after opening
ticket in web interface!
Set of headers available depends on mailservers sending
emails not on Request Tracker!
Returns None if ticket or attachment does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
msg = self.__request('ticket/{}/attachments/{}'.format(str(ticket_id), str(attachment_id)),
text_response=False)
msg = msg.split(b'\n')
if (len(msg) > 2) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2])):
return None
msg = msg[2:]
head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)]
head_id = head_matching[0] if head_matching else None
if not head_id:
raise UnexpectedMessageFormat('Unexpected headers part of attachment entry. \
Missing line starting with `Headers:`.')
msg[head_id] = re.sub(b'^Headers: (.*)$', r'\1', msg[head_id])
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_matching:
raise UnexpectedMessageFormat('Unexpected content part of attachment entry. \
Missing line starting with `Content:`.')
pairs = {}
for i in range(head_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
headers = {}
for i in range(head_id, cont_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
pairs['Headers'] = headers
content = msg[cont_id][9:]
for i in range(cont_id + 1, len(msg)):
if msg[i][:9] == (b' ' * 9):
content += b'\n' + msg[i][9:]
pairs['Content'] = content
return pairs | [
"def",
"get_attachment",
"(",
"self",
",",
"ticket_id",
",",
"attachment_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments/{}'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"attachment_id",
")",
")",
",",
"text_response",
"=",
"False",
")",
"msg",
"=",
"msg",
".",
"split",
"(",
"b'\\n'",
")",
"if",
"(",
"len",
"(",
"msg",
")",
">",
"2",
")",
"and",
"(",
"self",
".",
"RE_PATTERNS",
"[",
"'invalid_attachment_pattern_bytes'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
"or",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern_bytes'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
")",
":",
"return",
"None",
"msg",
"=",
"msg",
"[",
"2",
":",
"]",
"head_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'headers_pattern_bytes'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"head_id",
"=",
"head_matching",
"[",
"0",
"]",
"if",
"head_matching",
"else",
"None",
"if",
"not",
"head_id",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected headers part of attachment entry. \\\n Missing line starting with `Headers:`.'",
")",
"msg",
"[",
"head_id",
"]",
"=",
"re",
".",
"sub",
"(",
"b'^Headers: (.*)$'",
",",
"r'\\1'",
",",
"msg",
"[",
"head_id",
"]",
")",
"cont_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'content_pattern_bytes'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"cont_id",
"=",
"cont_matching",
"[",
"0",
"]",
"if",
"cont_matching",
"else",
"None",
"if",
"not",
"cont_matching",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected content part of attachment entry. \\\n Missing line starting with `Content:`.'",
")",
"pairs",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"head_id",
")",
":",
"if",
"b': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"msg",
"[",
"i",
"]",
".",
"split",
"(",
"b': '",
",",
"1",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"headers",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"head_id",
",",
"cont_id",
")",
":",
"if",
"b': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"msg",
"[",
"i",
"]",
".",
"split",
"(",
"b': '",
",",
"1",
")",
"headers",
"[",
"header",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"pairs",
"[",
"'Headers'",
"]",
"=",
"headers",
"content",
"=",
"msg",
"[",
"cont_id",
"]",
"[",
"9",
":",
"]",
"for",
"i",
"in",
"range",
"(",
"cont_id",
"+",
"1",
",",
"len",
"(",
"msg",
")",
")",
":",
"if",
"msg",
"[",
"i",
"]",
"[",
":",
"9",
"]",
"==",
"(",
"b' '",
"*",
"9",
")",
":",
"content",
"+=",
"b'\\n'",
"+",
"msg",
"[",
"i",
"]",
"[",
"9",
":",
"]",
"pairs",
"[",
"'Content'",
"]",
"=",
"content",
"return",
"pairs"
] | Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
* Parent
* Creator
* Created
* Filename
* Content (bytes type)
* Headers
* MessageId
* ContentEncoding
* id
* Subject
All these fields are strings, just 'Headers' holds another
dictionary with attachment headers as strings e.g.:
* Delivered-To
* From
* Return-Path
* Content-Length
* To
* X-Seznam-User
* X-QM-Mark
* Domainkey-Signature
* RT-Message-ID
* X-RT-Incoming-Encryption
* X-Original-To
* Message-ID
* X-Spam-Status
* In-Reply-To
* Date
* Received
* X-Country
* X-Spam-Checker-Version
* X-Abuse
* MIME-Version
* Content-Type
* Subject
.. warning:: Content-Length parameter is set after opening
ticket in web interface!
Set of headers available depends on mailservers sending
emails not on Request Tracker!
Returns None if ticket or attachment does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message. | [
"Get",
"attachment",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L963-L1051 | train | 235,207 |
CZ-NIC/python-rt | rt.py | Rt.get_attachment_content | def get_attachment_content(self, ticket_id, attachment_id):
""" Get content of attachment without headers.
This function is necessary to use for binary attachment,
as it can contain ``\\n`` chars, which would disrupt parsing
of message if :py:meth:`~Rt.get_attachment` is used.
Format of message::
RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment
Returns: Bytes with content of attachment or None if ticket or
attachment does not exist.
"""
msg = self.__request('ticket/{}/attachments/{}/content'.format
(str(ticket_id), str(attachment_id)),
text_response=False)
lines = msg.split(b'\n', 3)
if (len(lines) == 4) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2])):
return None
return msg[msg.find(b'\n') + 2:-3] | python | def get_attachment_content(self, ticket_id, attachment_id):
""" Get content of attachment without headers.
This function is necessary to use for binary attachment,
as it can contain ``\\n`` chars, which would disrupt parsing
of message if :py:meth:`~Rt.get_attachment` is used.
Format of message::
RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment
Returns: Bytes with content of attachment or None if ticket or
attachment does not exist.
"""
msg = self.__request('ticket/{}/attachments/{}/content'.format
(str(ticket_id), str(attachment_id)),
text_response=False)
lines = msg.split(b'\n', 3)
if (len(lines) == 4) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2])):
return None
return msg[msg.find(b'\n') + 2:-3] | [
"def",
"get_attachment_content",
"(",
"self",
",",
"ticket_id",
",",
"attachment_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments/{}/content'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"attachment_id",
")",
")",
",",
"text_response",
"=",
"False",
")",
"lines",
"=",
"msg",
".",
"split",
"(",
"b'\\n'",
",",
"3",
")",
"if",
"(",
"len",
"(",
"lines",
")",
"==",
"4",
")",
"and",
"(",
"self",
".",
"RE_PATTERNS",
"[",
"'invalid_attachment_pattern_bytes'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
"or",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern_bytes'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
")",
":",
"return",
"None",
"return",
"msg",
"[",
"msg",
".",
"find",
"(",
"b'\\n'",
")",
"+",
"2",
":",
"-",
"3",
"]"
] | Get content of attachment without headers.
This function is necessary to use for binary attachment,
as it can contain ``\\n`` chars, which would disrupt parsing
of message if :py:meth:`~Rt.get_attachment` is used.
Format of message::
RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment
Returns: Bytes with content of attachment or None if ticket or
attachment does not exist. | [
"Get",
"content",
"of",
"attachment",
"without",
"headers",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1053-L1077 | train | 235,208 |
CZ-NIC/python-rt | rt.py | Rt.get_user | def get_user(self, user_id):
""" Get user details.
:param user_id: Identification of user by username (str) or user ID
(int)
:returns: User details as strings in dictionary with these keys for RT
users:
* Lang
* RealName
* Privileged
* Disabled
* Gecos
* EmailAddress
* Password
* id
* Name
Or these keys for external users (e.g. Requestors replying
to email from RT:
* RealName
* Disabled
* EmailAddress
* Password
* id
* Name
None is returned if user does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200
"""
msg = self.__request('user/{}'.format(str(user_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
for line in lines[2:]:
if ': ' in line:
header, content = line.split(': ', 1)
pairs[header.strip()] = content.strip()
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | python | def get_user(self, user_id):
""" Get user details.
:param user_id: Identification of user by username (str) or user ID
(int)
:returns: User details as strings in dictionary with these keys for RT
users:
* Lang
* RealName
* Privileged
* Disabled
* Gecos
* EmailAddress
* Password
* id
* Name
Or these keys for external users (e.g. Requestors replying
to email from RT:
* RealName
* Disabled
* EmailAddress
* Password
* id
* Name
None is returned if user does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200
"""
msg = self.__request('user/{}'.format(str(user_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
for line in lines[2:]:
if ': ' in line:
header, content = line.split(': ', 1)
pairs[header.strip()] = content.strip()
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | [
"def",
"get_user",
"(",
"self",
",",
"user_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'user/{}'",
".",
"format",
"(",
"str",
"(",
"user_id",
")",
",",
")",
")",
"status_code",
"=",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"if",
"(",
"status_code",
"==",
"200",
")",
":",
"pairs",
"=",
"{",
"}",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
":",
"return",
"None",
"for",
"line",
"in",
"lines",
"[",
"2",
":",
"]",
":",
"if",
"': '",
"in",
"line",
":",
"header",
",",
"content",
"=",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"return",
"pairs",
"else",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Received status code is {:d} instead of 200.'",
".",
"format",
"(",
"status_code",
")",
")"
] | Get user details.
:param user_id: Identification of user by username (str) or user ID
(int)
:returns: User details as strings in dictionary with these keys for RT
users:
* Lang
* RealName
* Privileged
* Disabled
* Gecos
* EmailAddress
* Password
* id
* Name
Or these keys for external users (e.g. Requestors replying
to email from RT:
* RealName
* Disabled
* EmailAddress
* Password
* id
* Name
None is returned if user does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200 | [
"Get",
"user",
"details",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1079-L1123 | train | 235,209 |
CZ-NIC/python-rt | rt.py | Rt.get_links | def get_links(self, ticket_id):
""" Gets the ticket links for a single ticket.
:param ticket_id: ticket ID
:returns: Links as lists of strings in dictionary with these keys
(just those which are defined):
* id
* Members
* MemberOf
* RefersTo
* ReferredToBy
* DependsOn
* DependedOnBy
None is returned if ticket does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200
"""
msg = self.__request('ticket/{}/links/show'.format(str(ticket_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
msg = msg.split('\n')
if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]):
return None
i = 2
while i < len(msg):
if ': ' in msg[i]:
key, link = self.split_header(msg[i])
links = [link.strip()]
j = i + 1
pad = len(key) + 2
# loop over next lines for the same key
while (j < len(msg)) and msg[j].startswith(' ' * pad):
links[-1] = links[-1][:-1] # remove trailing comma from previous item
links.append(msg[j][pad:].strip())
j += 1
pairs[key] = links
i = j - 1
i += 1
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | python | def get_links(self, ticket_id):
""" Gets the ticket links for a single ticket.
:param ticket_id: ticket ID
:returns: Links as lists of strings in dictionary with these keys
(just those which are defined):
* id
* Members
* MemberOf
* RefersTo
* ReferredToBy
* DependsOn
* DependedOnBy
None is returned if ticket does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200
"""
msg = self.__request('ticket/{}/links/show'.format(str(ticket_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
msg = msg.split('\n')
if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]):
return None
i = 2
while i < len(msg):
if ': ' in msg[i]:
key, link = self.split_header(msg[i])
links = [link.strip()]
j = i + 1
pad = len(key) + 2
# loop over next lines for the same key
while (j < len(msg)) and msg[j].startswith(' ' * pad):
links[-1] = links[-1][:-1] # remove trailing comma from previous item
links.append(msg[j][pad:].strip())
j += 1
pairs[key] = links
i = j - 1
i += 1
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | [
"def",
"get_links",
"(",
"self",
",",
"ticket_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/links/show'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"status_code",
"=",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"if",
"(",
"status_code",
"==",
"200",
")",
":",
"pairs",
"=",
"{",
"}",
"msg",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"msg",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
":",
"return",
"None",
"i",
"=",
"2",
"while",
"i",
"<",
"len",
"(",
"msg",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"key",
",",
"link",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"links",
"=",
"[",
"link",
".",
"strip",
"(",
")",
"]",
"j",
"=",
"i",
"+",
"1",
"pad",
"=",
"len",
"(",
"key",
")",
"+",
"2",
"# loop over next lines for the same key",
"while",
"(",
"j",
"<",
"len",
"(",
"msg",
")",
")",
"and",
"msg",
"[",
"j",
"]",
".",
"startswith",
"(",
"' '",
"*",
"pad",
")",
":",
"links",
"[",
"-",
"1",
"]",
"=",
"links",
"[",
"-",
"1",
"]",
"[",
":",
"-",
"1",
"]",
"# remove trailing comma from previous item",
"links",
".",
"append",
"(",
"msg",
"[",
"j",
"]",
"[",
"pad",
":",
"]",
".",
"strip",
"(",
")",
")",
"j",
"+=",
"1",
"pairs",
"[",
"key",
"]",
"=",
"links",
"i",
"=",
"j",
"-",
"1",
"i",
"+=",
"1",
"return",
"pairs",
"else",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Received status code is {:d} instead of 200.'",
".",
"format",
"(",
"status_code",
")",
")"
] | Gets the ticket links for a single ticket.
:param ticket_id: ticket ID
:returns: Links as lists of strings in dictionary with these keys
(just those which are defined):
* id
* Members
* MemberOf
* RefersTo
* ReferredToBy
* DependsOn
* DependedOnBy
None is returned if ticket does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200 | [
"Gets",
"the",
"ticket",
"links",
"for",
"a",
"single",
"ticket",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1286-L1329 | train | 235,210 |
CZ-NIC/python-rt | rt.py | Rt.edit_ticket_links | def edit_ticket_links(self, ticket_id, **kwargs):
""" Edit ticket links.
.. warning:: This method is deprecated in favour of edit_link method, because
there exists bug in RT 3.8 REST API causing mapping created links to
ticket/1. The only drawback is that edit_link cannot process multiple
links all at once.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set: DependsOn,
DependedOnBy, RefersTo, ReferredToBy, Members,
MemberOf. Each value should be either ticker ID or
external link. Int types are converted. Use empty
string as value to delete existing link.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)
"""
post_data = ''
for key in kwargs:
post_data += "{}: {}\n".format(key, str(kwargs[key]))
msg = self.__request('ticket/{}/links'.format(str(ticket_id), ),
post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None | python | def edit_ticket_links(self, ticket_id, **kwargs):
""" Edit ticket links.
.. warning:: This method is deprecated in favour of edit_link method, because
there exists bug in RT 3.8 REST API causing mapping created links to
ticket/1. The only drawback is that edit_link cannot process multiple
links all at once.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set: DependsOn,
DependedOnBy, RefersTo, ReferredToBy, Members,
MemberOf. Each value should be either ticker ID or
external link. Int types are converted. Use empty
string as value to delete existing link.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)
"""
post_data = ''
for key in kwargs:
post_data += "{}: {}\n".format(key, str(kwargs[key]))
msg = self.__request('ticket/{}/links'.format(str(ticket_id), ),
post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None | [
"def",
"edit_ticket_links",
"(",
"self",
",",
"ticket_id",
",",
"*",
"*",
"kwargs",
")",
":",
"post_data",
"=",
"''",
"for",
"key",
"in",
"kwargs",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"str",
"(",
"kwargs",
"[",
"key",
"]",
")",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/links'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
")",
"state",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'links_updated_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None"
] | Edit ticket links.
.. warning:: This method is deprecated in favour of edit_link method, because
there exists bug in RT 3.8 REST API causing mapping created links to
ticket/1. The only drawback is that edit_link cannot process multiple
links all at once.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set: DependsOn,
DependedOnBy, RefersTo, ReferredToBy, Members,
MemberOf. Each value should be either ticker ID or
external link. Int types are converted. Use empty
string as value to delete existing link.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed) | [
"Edit",
"ticket",
"links",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1331-L1357 | train | 235,211 |
CZ-NIC/python-rt | rt.py | Rt.split_header | def split_header(line):
""" Split a header line into field name and field value.
Note that custom fields may contain colons inside the curly braces,
so we need a special test for them.
:param line: A message line to be split.
:returns: (Field name, field value) tuple.
"""
match = re.match(r'^(CF\.\{.*?}): (.*)$', line)
if match:
return (match.group(1), match.group(2))
return line.split(': ', 1) | python | def split_header(line):
""" Split a header line into field name and field value.
Note that custom fields may contain colons inside the curly braces,
so we need a special test for them.
:param line: A message line to be split.
:returns: (Field name, field value) tuple.
"""
match = re.match(r'^(CF\.\{.*?}): (.*)$', line)
if match:
return (match.group(1), match.group(2))
return line.split(': ', 1) | [
"def",
"split_header",
"(",
"line",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(CF\\.\\{.*?}): (.*)$'",
",",
"line",
")",
"if",
"match",
":",
"return",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
"return",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")"
] | Split a header line into field name and field value.
Note that custom fields may contain colons inside the curly braces,
so we need a special test for them.
:param line: A message line to be split.
:returns: (Field name, field value) tuple. | [
"Split",
"a",
"header",
"line",
"into",
"field",
"name",
"and",
"field",
"value",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1450-L1463 | train | 235,212 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.PrivateKeyFromWIF | def PrivateKeyFromWIF(wif):
"""
Get the private key from a WIF key
Args:
wif (str): The wif key
Returns:
bytes: The private key
"""
if wif is None or len(wif) is not 52:
raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif)))
data = base58.b58decode(wif)
length = len(data)
if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01:
raise ValueError("Invalid format!")
checksum = Crypto.Hash256(data[0:34])[0:4]
if checksum != data[34:]:
raise ValueError("Invalid WIF Checksum!")
return data[1:33] | python | def PrivateKeyFromWIF(wif):
"""
Get the private key from a WIF key
Args:
wif (str): The wif key
Returns:
bytes: The private key
"""
if wif is None or len(wif) is not 52:
raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif)))
data = base58.b58decode(wif)
length = len(data)
if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01:
raise ValueError("Invalid format!")
checksum = Crypto.Hash256(data[0:34])[0:4]
if checksum != data[34:]:
raise ValueError("Invalid WIF Checksum!")
return data[1:33] | [
"def",
"PrivateKeyFromWIF",
"(",
"wif",
")",
":",
"if",
"wif",
"is",
"None",
"or",
"len",
"(",
"wif",
")",
"is",
"not",
"52",
":",
"raise",
"ValueError",
"(",
"'Please provide a wif with a length of 52 bytes (LEN: {0:d})'",
".",
"format",
"(",
"len",
"(",
"wif",
")",
")",
")",
"data",
"=",
"base58",
".",
"b58decode",
"(",
"wif",
")",
"length",
"=",
"len",
"(",
"data",
")",
"if",
"length",
"is",
"not",
"38",
"or",
"data",
"[",
"0",
"]",
"is",
"not",
"0x80",
"or",
"data",
"[",
"33",
"]",
"is",
"not",
"0x01",
":",
"raise",
"ValueError",
"(",
"\"Invalid format!\"",
")",
"checksum",
"=",
"Crypto",
".",
"Hash256",
"(",
"data",
"[",
"0",
":",
"34",
"]",
")",
"[",
"0",
":",
"4",
"]",
"if",
"checksum",
"!=",
"data",
"[",
"34",
":",
"]",
":",
"raise",
"ValueError",
"(",
"\"Invalid WIF Checksum!\"",
")",
"return",
"data",
"[",
"1",
":",
"33",
"]"
] | Get the private key from a WIF key
Args:
wif (str): The wif key
Returns:
bytes: The private key | [
"Get",
"the",
"private",
"key",
"from",
"a",
"WIF",
"key"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L81-L106 | train | 235,213 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.PrivateKeyFromNEP2 | def PrivateKeyFromNEP2(nep2_key, passphrase):
"""
Gets the private key from a NEP-2 encrypted private key
Args:
nep2_key (str): The nep-2 encrypted private key
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
bytes: The private key
"""
if not nep2_key or len(nep2_key) != 58:
raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key)))
ADDRESS_HASH_SIZE = 4
ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER)
try:
decoded_key = base58.b58decode_check(nep2_key)
except Exception as e:
raise ValueError("Invalid nep2_key")
address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE]
encrypted = decoded_key[-32:]
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
derived1 = derived[:32]
derived2 = derived[32:]
cipher = AES.new(derived2, AES.MODE_ECB)
decrypted = cipher.decrypt(encrypted)
private_key = xor_bytes(decrypted, derived1)
# Now check that the address hashes match. If they don't, the password was wrong.
kp_new = KeyPair(priv_key=private_key)
kp_new_address = kp_new.GetAddress()
kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest()
kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest()
kp_new_address_hash = kp_new_address_hash_tmp2[:4]
if (kp_new_address_hash != address_hash):
raise ValueError("Wrong passphrase")
return private_key | python | def PrivateKeyFromNEP2(nep2_key, passphrase):
"""
Gets the private key from a NEP-2 encrypted private key
Args:
nep2_key (str): The nep-2 encrypted private key
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
bytes: The private key
"""
if not nep2_key or len(nep2_key) != 58:
raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key)))
ADDRESS_HASH_SIZE = 4
ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER)
try:
decoded_key = base58.b58decode_check(nep2_key)
except Exception as e:
raise ValueError("Invalid nep2_key")
address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE]
encrypted = decoded_key[-32:]
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
derived1 = derived[:32]
derived2 = derived[32:]
cipher = AES.new(derived2, AES.MODE_ECB)
decrypted = cipher.decrypt(encrypted)
private_key = xor_bytes(decrypted, derived1)
# Now check that the address hashes match. If they don't, the password was wrong.
kp_new = KeyPair(priv_key=private_key)
kp_new_address = kp_new.GetAddress()
kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest()
kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest()
kp_new_address_hash = kp_new_address_hash_tmp2[:4]
if (kp_new_address_hash != address_hash):
raise ValueError("Wrong passphrase")
return private_key | [
"def",
"PrivateKeyFromNEP2",
"(",
"nep2_key",
",",
"passphrase",
")",
":",
"if",
"not",
"nep2_key",
"or",
"len",
"(",
"nep2_key",
")",
"!=",
"58",
":",
"raise",
"ValueError",
"(",
"'Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'",
".",
"format",
"(",
"len",
"(",
"nep2_key",
")",
")",
")",
"ADDRESS_HASH_SIZE",
"=",
"4",
"ADDRESS_HASH_OFFSET",
"=",
"len",
"(",
"NEP_FLAG",
")",
"+",
"len",
"(",
"NEP_HEADER",
")",
"try",
":",
"decoded_key",
"=",
"base58",
".",
"b58decode_check",
"(",
"nep2_key",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Invalid nep2_key\"",
")",
"address_hash",
"=",
"decoded_key",
"[",
"ADDRESS_HASH_OFFSET",
":",
"ADDRESS_HASH_OFFSET",
"+",
"ADDRESS_HASH_SIZE",
"]",
"encrypted",
"=",
"decoded_key",
"[",
"-",
"32",
":",
"]",
"pwd_normalized",
"=",
"bytes",
"(",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"passphrase",
")",
",",
"'utf-8'",
")",
"derived",
"=",
"scrypt",
".",
"hash",
"(",
"pwd_normalized",
",",
"address_hash",
",",
"N",
"=",
"SCRYPT_ITERATIONS",
",",
"r",
"=",
"SCRYPT_BLOCKSIZE",
",",
"p",
"=",
"SCRYPT_PARALLEL_FACTOR",
",",
"buflen",
"=",
"SCRYPT_KEY_LEN_BYTES",
")",
"derived1",
"=",
"derived",
"[",
":",
"32",
"]",
"derived2",
"=",
"derived",
"[",
"32",
":",
"]",
"cipher",
"=",
"AES",
".",
"new",
"(",
"derived2",
",",
"AES",
".",
"MODE_ECB",
")",
"decrypted",
"=",
"cipher",
".",
"decrypt",
"(",
"encrypted",
")",
"private_key",
"=",
"xor_bytes",
"(",
"decrypted",
",",
"derived1",
")",
"# Now check that the address hashes match. If they don't, the password was wrong.",
"kp_new",
"=",
"KeyPair",
"(",
"priv_key",
"=",
"private_key",
")",
"kp_new_address",
"=",
"kp_new",
".",
"GetAddress",
"(",
")",
"kp_new_address_hash_tmp",
"=",
"hashlib",
".",
"sha256",
"(",
"kp_new_address",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"digest",
"(",
")",
"kp_new_address_hash_tmp2",
"=",
"hashlib",
".",
"sha256",
"(",
"kp_new_address_hash_tmp",
")",
".",
"digest",
"(",
")",
"kp_new_address_hash",
"=",
"kp_new_address_hash_tmp2",
"[",
":",
"4",
"]",
"if",
"(",
"kp_new_address_hash",
"!=",
"address_hash",
")",
":",
"raise",
"ValueError",
"(",
"\"Wrong passphrase\"",
")",
"return",
"private_key"
] | Gets the private key from a NEP-2 encrypted private key
Args:
nep2_key (str): The nep-2 encrypted private key
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
bytes: The private key | [
"Gets",
"the",
"private",
"key",
"from",
"a",
"NEP",
"-",
"2",
"encrypted",
"private",
"key"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L109-L157 | train | 235,214 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.GetAddress | def GetAddress(self):
"""
Returns the public NEO address for this KeyPair
Returns:
str: The private key
"""
script = b'21' + self.PublicKey.encode_point(True) + b'ac'
script_hash = Crypto.ToScriptHash(script)
address = Crypto.ToAddress(script_hash)
return address | python | def GetAddress(self):
"""
Returns the public NEO address for this KeyPair
Returns:
str: The private key
"""
script = b'21' + self.PublicKey.encode_point(True) + b'ac'
script_hash = Crypto.ToScriptHash(script)
address = Crypto.ToAddress(script_hash)
return address | [
"def",
"GetAddress",
"(",
"self",
")",
":",
"script",
"=",
"b'21'",
"+",
"self",
".",
"PublicKey",
".",
"encode_point",
"(",
"True",
")",
"+",
"b'ac'",
"script_hash",
"=",
"Crypto",
".",
"ToScriptHash",
"(",
"script",
")",
"address",
"=",
"Crypto",
".",
"ToAddress",
"(",
"script_hash",
")",
"return",
"address"
] | Returns the public NEO address for this KeyPair
Returns:
str: The private key | [
"Returns",
"the",
"public",
"NEO",
"address",
"for",
"this",
"KeyPair"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L159-L169 | train | 235,215 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.Export | def Export(self):
"""
Export this KeyPair's private key in WIF format.
Returns:
str: The key in wif format
"""
data = bytearray(38)
data[0] = 0x80
data[1:33] = self.PrivateKey[0:32]
data[33] = 0x01
checksum = Crypto.Default().Hash256(data[0:34])
data[34:38] = checksum[0:4]
b58 = base58.b58encode(bytes(data))
return b58.decode("utf-8") | python | def Export(self):
"""
Export this KeyPair's private key in WIF format.
Returns:
str: The key in wif format
"""
data = bytearray(38)
data[0] = 0x80
data[1:33] = self.PrivateKey[0:32]
data[33] = 0x01
checksum = Crypto.Default().Hash256(data[0:34])
data[34:38] = checksum[0:4]
b58 = base58.b58encode(bytes(data))
return b58.decode("utf-8") | [
"def",
"Export",
"(",
"self",
")",
":",
"data",
"=",
"bytearray",
"(",
"38",
")",
"data",
"[",
"0",
"]",
"=",
"0x80",
"data",
"[",
"1",
":",
"33",
"]",
"=",
"self",
".",
"PrivateKey",
"[",
"0",
":",
"32",
"]",
"data",
"[",
"33",
"]",
"=",
"0x01",
"checksum",
"=",
"Crypto",
".",
"Default",
"(",
")",
".",
"Hash256",
"(",
"data",
"[",
"0",
":",
"34",
"]",
")",
"data",
"[",
"34",
":",
"38",
"]",
"=",
"checksum",
"[",
"0",
":",
"4",
"]",
"b58",
"=",
"base58",
".",
"b58encode",
"(",
"bytes",
"(",
"data",
")",
")",
"return",
"b58",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | Export this KeyPair's private key in WIF format.
Returns:
str: The key in wif format | [
"Export",
"this",
"KeyPair",
"s",
"private",
"key",
"in",
"WIF",
"format",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L171-L187 | train | 235,216 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.ExportNEP2 | def ExportNEP2(self, passphrase):
"""
Export the encrypted private key in NEP-2 format.
Args:
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
str: The NEP-2 encrypted private key
"""
if len(passphrase) < 2:
raise ValueError("Passphrase must have a minimum of 2 characters")
# Hash address twice, then only use the first 4 bytes
address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest()
address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
address_hash = address_hash_tmp2[:4]
# Normalize password and run scrypt over it with the address_hash
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
# Split the scrypt-result into two parts
derived1 = derived[:32]
derived2 = derived[32:]
# Run XOR and encrypt the derived parts with AES
xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
cipher = AES.new(derived2, AES.MODE_ECB)
encrypted = cipher.encrypt(xor_ed)
# Assemble the final result
assembled = bytearray()
assembled.extend(NEP_HEADER)
assembled.extend(NEP_FLAG)
assembled.extend(address_hash)
assembled.extend(encrypted)
# Finally, encode with Base58Check
encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
return encrypted_key_nep2.decode("utf-8") | python | def ExportNEP2(self, passphrase):
"""
Export the encrypted private key in NEP-2 format.
Args:
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
str: The NEP-2 encrypted private key
"""
if len(passphrase) < 2:
raise ValueError("Passphrase must have a minimum of 2 characters")
# Hash address twice, then only use the first 4 bytes
address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest()
address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
address_hash = address_hash_tmp2[:4]
# Normalize password and run scrypt over it with the address_hash
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
# Split the scrypt-result into two parts
derived1 = derived[:32]
derived2 = derived[32:]
# Run XOR and encrypt the derived parts with AES
xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
cipher = AES.new(derived2, AES.MODE_ECB)
encrypted = cipher.encrypt(xor_ed)
# Assemble the final result
assembled = bytearray()
assembled.extend(NEP_HEADER)
assembled.extend(NEP_FLAG)
assembled.extend(address_hash)
assembled.extend(encrypted)
# Finally, encode with Base58Check
encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
return encrypted_key_nep2.decode("utf-8") | [
"def",
"ExportNEP2",
"(",
"self",
",",
"passphrase",
")",
":",
"if",
"len",
"(",
"passphrase",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Passphrase must have a minimum of 2 characters\"",
")",
"# Hash address twice, then only use the first 4 bytes",
"address_hash_tmp",
"=",
"hashlib",
".",
"sha256",
"(",
"self",
".",
"GetAddress",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"digest",
"(",
")",
"address_hash_tmp2",
"=",
"hashlib",
".",
"sha256",
"(",
"address_hash_tmp",
")",
".",
"digest",
"(",
")",
"address_hash",
"=",
"address_hash_tmp2",
"[",
":",
"4",
"]",
"# Normalize password and run scrypt over it with the address_hash",
"pwd_normalized",
"=",
"bytes",
"(",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"passphrase",
")",
",",
"'utf-8'",
")",
"derived",
"=",
"scrypt",
".",
"hash",
"(",
"pwd_normalized",
",",
"address_hash",
",",
"N",
"=",
"SCRYPT_ITERATIONS",
",",
"r",
"=",
"SCRYPT_BLOCKSIZE",
",",
"p",
"=",
"SCRYPT_PARALLEL_FACTOR",
",",
"buflen",
"=",
"SCRYPT_KEY_LEN_BYTES",
")",
"# Split the scrypt-result into two parts",
"derived1",
"=",
"derived",
"[",
":",
"32",
"]",
"derived2",
"=",
"derived",
"[",
"32",
":",
"]",
"# Run XOR and encrypt the derived parts with AES",
"xor_ed",
"=",
"xor_bytes",
"(",
"bytes",
"(",
"self",
".",
"PrivateKey",
")",
",",
"derived1",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"derived2",
",",
"AES",
".",
"MODE_ECB",
")",
"encrypted",
"=",
"cipher",
".",
"encrypt",
"(",
"xor_ed",
")",
"# Assemble the final result",
"assembled",
"=",
"bytearray",
"(",
")",
"assembled",
".",
"extend",
"(",
"NEP_HEADER",
")",
"assembled",
".",
"extend",
"(",
"NEP_FLAG",
")",
"assembled",
".",
"extend",
"(",
"address_hash",
")",
"assembled",
".",
"extend",
"(",
"encrypted",
")",
"# Finally, encode with Base58Check",
"encrypted_key_nep2",
"=",
"base58",
".",
"b58encode_check",
"(",
"bytes",
"(",
"assembled",
")",
")",
"return",
"encrypted_key_nep2",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | Export the encrypted private key in NEP-2 format.
Args:
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
str: The NEP-2 encrypted private key | [
"Export",
"the",
"encrypted",
"private",
"key",
"in",
"NEP",
"-",
"2",
"format",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L189-L233 | train | 235,217 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadByte | def ReadByte(self, do_ord=True):
"""
Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred.
"""
try:
if do_ord:
return ord(self.stream.read(1))
return self.stream.read(1)
except Exception as e:
logger.error("ord expected character but got none")
return 0 | python | def ReadByte(self, do_ord=True):
"""
Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred.
"""
try:
if do_ord:
return ord(self.stream.read(1))
return self.stream.read(1)
except Exception as e:
logger.error("ord expected character but got none")
return 0 | [
"def",
"ReadByte",
"(",
"self",
",",
"do_ord",
"=",
"True",
")",
":",
"try",
":",
"if",
"do_ord",
":",
"return",
"ord",
"(",
"self",
".",
"stream",
".",
"read",
"(",
"1",
")",
")",
"return",
"self",
".",
"stream",
".",
"read",
"(",
"1",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"ord expected character but got none\"",
")",
"return",
"0"
] | Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred. | [
"Read",
"a",
"single",
"byte",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L46-L62 | train | 235,218 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.SafeReadBytes | def SafeReadBytes(self, length):
"""
Read exactly `length` number of bytes from the stream.
Raises:
ValueError is not enough data
Returns:
bytes: `length` number of bytes
"""
data = self.ReadBytes(length)
if len(data) < length:
raise ValueError("Not enough data available")
else:
return data | python | def SafeReadBytes(self, length):
"""
Read exactly `length` number of bytes from the stream.
Raises:
ValueError is not enough data
Returns:
bytes: `length` number of bytes
"""
data = self.ReadBytes(length)
if len(data) < length:
raise ValueError("Not enough data available")
else:
return data | [
"def",
"SafeReadBytes",
"(",
"self",
",",
"length",
")",
":",
"data",
"=",
"self",
".",
"ReadBytes",
"(",
"length",
")",
"if",
"len",
"(",
"data",
")",
"<",
"length",
":",
"raise",
"ValueError",
"(",
"\"Not enough data available\"",
")",
"else",
":",
"return",
"data"
] | Read exactly `length` number of bytes from the stream.
Raises:
ValueError is not enough data
Returns:
bytes: `length` number of bytes | [
"Read",
"exactly",
"length",
"number",
"of",
"bytes",
"from",
"the",
"stream",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L77-L91 | train | 235,219 |
CityOfZion/neo-python-core | neocore/Cryptography/Crypto.py | Crypto.ToScriptHash | def ToScriptHash(data, unhex=True):
"""
Get a script hash of the data.
Args:
data (bytes): data to hash.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
UInt160: script hash.
"""
if len(data) > 1 and unhex:
data = binascii.unhexlify(data)
return UInt160(data=binascii.unhexlify(bytes(Crypto.Hash160(data), encoding='utf-8'))) | python | def ToScriptHash(data, unhex=True):
"""
Get a script hash of the data.
Args:
data (bytes): data to hash.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
UInt160: script hash.
"""
if len(data) > 1 and unhex:
data = binascii.unhexlify(data)
return UInt160(data=binascii.unhexlify(bytes(Crypto.Hash160(data), encoding='utf-8'))) | [
"def",
"ToScriptHash",
"(",
"data",
",",
"unhex",
"=",
"True",
")",
":",
"if",
"len",
"(",
"data",
")",
">",
"1",
"and",
"unhex",
":",
"data",
"=",
"binascii",
".",
"unhexlify",
"(",
"data",
")",
"return",
"UInt160",
"(",
"data",
"=",
"binascii",
".",
"unhexlify",
"(",
"bytes",
"(",
"Crypto",
".",
"Hash160",
"(",
"data",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
")",
")"
] | Get a script hash of the data.
Args:
data (bytes): data to hash.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
UInt160: script hash. | [
"Get",
"a",
"script",
"hash",
"of",
"the",
"data",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L77-L90 | train | 235,220 |
CityOfZion/neo-python-core | neocore/Cryptography/Crypto.py | Crypto.Sign | def Sign(message, private_key):
"""
Sign the message with the given private key.
Args:
message (str): message to be signed
private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64)
Returns:
bytearray: the signature of the message.
"""
hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest()
v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key)
rb = bytearray(r.to_bytes(32, 'big'))
sb = bytearray(s.to_bytes(32, 'big'))
sig = rb + sb
return sig | python | def Sign(message, private_key):
"""
Sign the message with the given private key.
Args:
message (str): message to be signed
private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64)
Returns:
bytearray: the signature of the message.
"""
hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest()
v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key)
rb = bytearray(r.to_bytes(32, 'big'))
sb = bytearray(s.to_bytes(32, 'big'))
sig = rb + sb
return sig | [
"def",
"Sign",
"(",
"message",
",",
"private_key",
")",
":",
"hash",
"=",
"hashlib",
".",
"sha256",
"(",
"binascii",
".",
"unhexlify",
"(",
"message",
")",
")",
".",
"hexdigest",
"(",
")",
"v",
",",
"r",
",",
"s",
"=",
"bitcoin",
".",
"ecdsa_raw_sign",
"(",
"hash",
",",
"private_key",
")",
"rb",
"=",
"bytearray",
"(",
"r",
".",
"to_bytes",
"(",
"32",
",",
"'big'",
")",
")",
"sb",
"=",
"bytearray",
"(",
"s",
".",
"to_bytes",
"(",
"32",
",",
"'big'",
")",
")",
"sig",
"=",
"rb",
"+",
"sb",
"return",
"sig"
] | Sign the message with the given private key.
Args:
message (str): message to be signed
private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64)
Returns:
bytearray: the signature of the message. | [
"Sign",
"the",
"message",
"with",
"the",
"given",
"private",
"key",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L106-L126 | train | 235,221 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | FiniteField.sqrt | def sqrt(self, val, flag):
"""
calculate the square root modulus p
"""
if val.iszero():
return val
sw = self.p % 8
if sw == 3 or sw == 7:
res = val ** ((self.p + 1) / 4)
elif sw == 5:
x = val ** ((self.p + 1) / 4)
if x == 1:
res = val ** ((self.p + 3) / 8)
else:
res = (4 * val) ** ((self.p - 5) / 8) * 2 * val
else:
raise Exception("modsqrt non supported for (p%8)==1")
if res.value % 2 == flag:
return res
else:
return -res | python | def sqrt(self, val, flag):
"""
calculate the square root modulus p
"""
if val.iszero():
return val
sw = self.p % 8
if sw == 3 or sw == 7:
res = val ** ((self.p + 1) / 4)
elif sw == 5:
x = val ** ((self.p + 1) / 4)
if x == 1:
res = val ** ((self.p + 3) / 8)
else:
res = (4 * val) ** ((self.p - 5) / 8) * 2 * val
else:
raise Exception("modsqrt non supported for (p%8)==1")
if res.value % 2 == flag:
return res
else:
return -res | [
"def",
"sqrt",
"(",
"self",
",",
"val",
",",
"flag",
")",
":",
"if",
"val",
".",
"iszero",
"(",
")",
":",
"return",
"val",
"sw",
"=",
"self",
".",
"p",
"%",
"8",
"if",
"sw",
"==",
"3",
"or",
"sw",
"==",
"7",
":",
"res",
"=",
"val",
"**",
"(",
"(",
"self",
".",
"p",
"+",
"1",
")",
"/",
"4",
")",
"elif",
"sw",
"==",
"5",
":",
"x",
"=",
"val",
"**",
"(",
"(",
"self",
".",
"p",
"+",
"1",
")",
"/",
"4",
")",
"if",
"x",
"==",
"1",
":",
"res",
"=",
"val",
"**",
"(",
"(",
"self",
".",
"p",
"+",
"3",
")",
"/",
"8",
")",
"else",
":",
"res",
"=",
"(",
"4",
"*",
"val",
")",
"**",
"(",
"(",
"self",
".",
"p",
"-",
"5",
")",
"/",
"8",
")",
"*",
"2",
"*",
"val",
"else",
":",
"raise",
"Exception",
"(",
"\"modsqrt non supported for (p%8)==1\"",
")",
"if",
"res",
".",
"value",
"%",
"2",
"==",
"flag",
":",
"return",
"res",
"else",
":",
"return",
"-",
"res"
] | calculate the square root modulus p | [
"calculate",
"the",
"square",
"root",
"modulus",
"p"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L287-L308 | train | 235,222 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | FiniteField.value | def value(self, x):
"""
converts an integer or FinitField.Value to a value of this FiniteField.
"""
return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x) | python | def value(self, x):
"""
converts an integer or FinitField.Value to a value of this FiniteField.
"""
return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x) | [
"def",
"value",
"(",
"self",
",",
"x",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"FiniteField",
".",
"Value",
")",
"and",
"x",
".",
"field",
"==",
"self",
"else",
"FiniteField",
".",
"Value",
"(",
"self",
",",
"x",
")"
] | converts an integer or FinitField.Value to a value of this FiniteField. | [
"converts",
"an",
"integer",
"or",
"FinitField",
".",
"Value",
"to",
"a",
"value",
"of",
"this",
"FiniteField",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L316-L320 | train | 235,223 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | FiniteField.integer | def integer(self, x):
"""
returns a plain integer
"""
if type(x) is str:
hex = binascii.unhexlify(x)
return int.from_bytes(hex, 'big')
return x.value if isinstance(x, FiniteField.Value) else x | python | def integer(self, x):
"""
returns a plain integer
"""
if type(x) is str:
hex = binascii.unhexlify(x)
return int.from_bytes(hex, 'big')
return x.value if isinstance(x, FiniteField.Value) else x | [
"def",
"integer",
"(",
"self",
",",
"x",
")",
":",
"if",
"type",
"(",
"x",
")",
"is",
"str",
":",
"hex",
"=",
"binascii",
".",
"unhexlify",
"(",
"x",
")",
"return",
"int",
".",
"from_bytes",
"(",
"hex",
",",
"'big'",
")",
"return",
"x",
".",
"value",
"if",
"isinstance",
"(",
"x",
",",
"FiniteField",
".",
"Value",
")",
"else",
"x"
] | returns a plain integer | [
"returns",
"a",
"plain",
"integer"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L322-L330 | train | 235,224 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.add | def add(self, p, q):
"""
perform elliptic curve addition
"""
if p.iszero():
return q
if q.iszero():
return p
lft = 0
# calculate the slope of the intersection line
if p == q:
if p.y == 0:
return self.zero()
lft = (3 * p.x ** 2 + self.a) / (2 * p.y)
elif p.x == q.x:
return self.zero()
else:
lft = (p.y - q.y) / (p.x - q.x)
# calculate the intersection point
x = lft ** 2 - (p.x + q.x)
y = lft * (p.x - x) - p.y
return self.point(x, y) | python | def add(self, p, q):
"""
perform elliptic curve addition
"""
if p.iszero():
return q
if q.iszero():
return p
lft = 0
# calculate the slope of the intersection line
if p == q:
if p.y == 0:
return self.zero()
lft = (3 * p.x ** 2 + self.a) / (2 * p.y)
elif p.x == q.x:
return self.zero()
else:
lft = (p.y - q.y) / (p.x - q.x)
# calculate the intersection point
x = lft ** 2 - (p.x + q.x)
y = lft * (p.x - x) - p.y
return self.point(x, y) | [
"def",
"add",
"(",
"self",
",",
"p",
",",
"q",
")",
":",
"if",
"p",
".",
"iszero",
"(",
")",
":",
"return",
"q",
"if",
"q",
".",
"iszero",
"(",
")",
":",
"return",
"p",
"lft",
"=",
"0",
"# calculate the slope of the intersection line",
"if",
"p",
"==",
"q",
":",
"if",
"p",
".",
"y",
"==",
"0",
":",
"return",
"self",
".",
"zero",
"(",
")",
"lft",
"=",
"(",
"3",
"*",
"p",
".",
"x",
"**",
"2",
"+",
"self",
".",
"a",
")",
"/",
"(",
"2",
"*",
"p",
".",
"y",
")",
"elif",
"p",
".",
"x",
"==",
"q",
".",
"x",
":",
"return",
"self",
".",
"zero",
"(",
")",
"else",
":",
"lft",
"=",
"(",
"p",
".",
"y",
"-",
"q",
".",
"y",
")",
"/",
"(",
"p",
".",
"x",
"-",
"q",
".",
"x",
")",
"# calculate the intersection point",
"x",
"=",
"lft",
"**",
"2",
"-",
"(",
"p",
".",
"x",
"+",
"q",
".",
"x",
")",
"y",
"=",
"lft",
"*",
"(",
"p",
".",
"x",
"-",
"x",
")",
"-",
"p",
".",
"y",
"return",
"self",
".",
"point",
"(",
"x",
",",
"y",
")"
] | perform elliptic curve addition | [
"perform",
"elliptic",
"curve",
"addition"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L486-L509 | train | 235,225 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.point | def point(self, x, y):
"""
construct a point from 2 values
"""
return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y)) | python | def point(self, x, y):
"""
construct a point from 2 values
"""
return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y)) | [
"def",
"point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"EllipticCurve",
".",
"ECPoint",
"(",
"self",
",",
"self",
".",
"field",
".",
"value",
"(",
"x",
")",
",",
"self",
".",
"field",
".",
"value",
"(",
"y",
")",
")"
] | construct a point from 2 values | [
"construct",
"a",
"point",
"from",
"2",
"values"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L550-L554 | train | 235,226 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.isoncurve | def isoncurve(self, p):
"""
verifies if a point is on the curve
"""
return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b | python | def isoncurve(self, p):
"""
verifies if a point is on the curve
"""
return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b | [
"def",
"isoncurve",
"(",
"self",
",",
"p",
")",
":",
"return",
"p",
".",
"iszero",
"(",
")",
"or",
"p",
".",
"y",
"**",
"2",
"==",
"p",
".",
"x",
"**",
"3",
"+",
"self",
".",
"a",
"*",
"p",
".",
"x",
"+",
"self",
".",
"b"
] | verifies if a point is on the curve | [
"verifies",
"if",
"a",
"point",
"is",
"on",
"the",
"curve"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L556-L560 | train | 235,227 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.secp256r1 | def secp256r1():
"""
create the secp256r1 curve
"""
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291)
# return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
return ECDSA(ec,
ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),
GFp) | python | def secp256r1():
"""
create the secp256r1 curve
"""
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291)
# return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
return ECDSA(ec,
ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),
GFp) | [
"def",
"secp256r1",
"(",
")",
":",
"GFp",
"=",
"FiniteField",
"(",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF\"",
",",
"16",
")",
")",
"ec",
"=",
"EllipticCurve",
"(",
"GFp",
",",
"115792089210356248762697446949407573530086143415290314195533631308867097853948",
",",
"41058363725152142129326129780047268409114441015993725554835256314039467401291",
")",
"# return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int(\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\", 16))",
"return",
"ECDSA",
"(",
"ec",
",",
"ec",
".",
"point",
"(",
"0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
",",
"0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",
")",
",",
"GFp",
")"
] | create the secp256r1 curve | [
"create",
"the",
"secp256r1",
"curve"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L805-L814 | train | 235,228 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.decode_secp256r1 | def decode_secp256r1(str, unhex=True, check_on_curve=True):
"""
decode a public key on the secp256r1 curve
"""
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948,
41058363725152142129326129780047268409114441015993725554835256314039467401291)
point = ec.decode_from_hex(str, unhex=unhex)
if check_on_curve:
if point.isoncurve():
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
else:
raise Exception("Could not decode string")
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) | python | def decode_secp256r1(str, unhex=True, check_on_curve=True):
"""
decode a public key on the secp256r1 curve
"""
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948,
41058363725152142129326129780047268409114441015993725554835256314039467401291)
point = ec.decode_from_hex(str, unhex=unhex)
if check_on_curve:
if point.isoncurve():
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
else:
raise Exception("Could not decode string")
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) | [
"def",
"decode_secp256r1",
"(",
"str",
",",
"unhex",
"=",
"True",
",",
"check_on_curve",
"=",
"True",
")",
":",
"GFp",
"=",
"FiniteField",
"(",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF\"",
",",
"16",
")",
")",
"ec",
"=",
"EllipticCurve",
"(",
"GFp",
",",
"115792089210356248762697446949407573530086143415290314195533631308867097853948",
",",
"41058363725152142129326129780047268409114441015993725554835256314039467401291",
")",
"point",
"=",
"ec",
".",
"decode_from_hex",
"(",
"str",
",",
"unhex",
"=",
"unhex",
")",
"if",
"check_on_curve",
":",
"if",
"point",
".",
"isoncurve",
"(",
")",
":",
"return",
"ECDSA",
"(",
"GFp",
",",
"point",
",",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\"",
",",
"16",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Could not decode string\"",
")",
"return",
"ECDSA",
"(",
"GFp",
",",
"point",
",",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\"",
",",
"16",
")",
")"
] | decode a public key on the secp256r1 curve | [
"decode",
"a",
"public",
"key",
"on",
"the",
"secp256r1",
"curve"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L817-L834 | train | 235,229 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.secp256k1 | def secp256k1():
"""
create the secp256k1 curve
"""
GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
ec = EllipticCurve(GFp, 0, 7)
return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599) | python | def secp256k1():
"""
create the secp256k1 curve
"""
GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
ec = EllipticCurve(GFp, 0, 7)
return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599) | [
"def",
"secp256k1",
"(",
")",
":",
"GFp",
"=",
"FiniteField",
"(",
"2",
"**",
"256",
"-",
"2",
"**",
"32",
"-",
"977",
")",
"# This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F",
"ec",
"=",
"EllipticCurve",
"(",
"GFp",
",",
"0",
",",
"7",
")",
"return",
"ECDSA",
"(",
"ec",
",",
"ec",
".",
"point",
"(",
"0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798",
",",
"0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",
")",
",",
"2",
"**",
"256",
"-",
"432420386565659656852420866394968145599",
")"
] | create the secp256k1 curve | [
"create",
"the",
"secp256k1",
"curve"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L864-L870 | train | 235,230 |
CityOfZion/neo-python-core | neocore/Utils.py | isValidPublicAddress | def isValidPublicAddress(address: str) -> bool:
"""Check if address is a valid NEO address"""
valid = False
if len(address) == 34 and address[0] == 'A':
try:
base58.b58decode_check(address.encode())
valid = True
except ValueError:
# checksum mismatch
valid = False
return valid | python | def isValidPublicAddress(address: str) -> bool:
"""Check if address is a valid NEO address"""
valid = False
if len(address) == 34 and address[0] == 'A':
try:
base58.b58decode_check(address.encode())
valid = True
except ValueError:
# checksum mismatch
valid = False
return valid | [
"def",
"isValidPublicAddress",
"(",
"address",
":",
"str",
")",
"->",
"bool",
":",
"valid",
"=",
"False",
"if",
"len",
"(",
"address",
")",
"==",
"34",
"and",
"address",
"[",
"0",
"]",
"==",
"'A'",
":",
"try",
":",
"base58",
".",
"b58decode_check",
"(",
"address",
".",
"encode",
"(",
")",
")",
"valid",
"=",
"True",
"except",
"ValueError",
":",
"# checksum mismatch",
"valid",
"=",
"False",
"return",
"valid"
] | Check if address is a valid NEO address | [
"Check",
"if",
"address",
"is",
"a",
"valid",
"NEO",
"address"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Utils.py#L4-L16 | train | 235,231 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.__Build | def __Build(leaves):
"""
Build the merkle tree.
Args:
leaves (list): items are of type MerkleTreeNode.
Returns:
MerkleTreeNode: the root node.
"""
if len(leaves) < 1:
raise Exception('Leaves must have length')
if len(leaves) == 1:
return leaves[0]
num_parents = int((len(leaves) + 1) / 2)
parents = [MerkleTreeNode() for i in range(0, num_parents)]
for i in range(0, num_parents):
node = parents[i]
node.LeftChild = leaves[i * 2]
leaves[i * 2].Parent = node
if (i * 2 + 1 == len(leaves)):
node.RightChild = node.LeftChild
else:
node.RightChild = leaves[i * 2 + 1]
leaves[i * 2 + 1].Parent = node
hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray())
node.Hash = UInt256(data=Crypto.Hash256(hasharray))
return MerkleTree.__Build(parents) | python | def __Build(leaves):
"""
Build the merkle tree.
Args:
leaves (list): items are of type MerkleTreeNode.
Returns:
MerkleTreeNode: the root node.
"""
if len(leaves) < 1:
raise Exception('Leaves must have length')
if len(leaves) == 1:
return leaves[0]
num_parents = int((len(leaves) + 1) / 2)
parents = [MerkleTreeNode() for i in range(0, num_parents)]
for i in range(0, num_parents):
node = parents[i]
node.LeftChild = leaves[i * 2]
leaves[i * 2].Parent = node
if (i * 2 + 1 == len(leaves)):
node.RightChild = node.LeftChild
else:
node.RightChild = leaves[i * 2 + 1]
leaves[i * 2 + 1].Parent = node
hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray())
node.Hash = UInt256(data=Crypto.Hash256(hasharray))
return MerkleTree.__Build(parents) | [
"def",
"__Build",
"(",
"leaves",
")",
":",
"if",
"len",
"(",
"leaves",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"'Leaves must have length'",
")",
"if",
"len",
"(",
"leaves",
")",
"==",
"1",
":",
"return",
"leaves",
"[",
"0",
"]",
"num_parents",
"=",
"int",
"(",
"(",
"len",
"(",
"leaves",
")",
"+",
"1",
")",
"/",
"2",
")",
"parents",
"=",
"[",
"MerkleTreeNode",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_parents",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_parents",
")",
":",
"node",
"=",
"parents",
"[",
"i",
"]",
"node",
".",
"LeftChild",
"=",
"leaves",
"[",
"i",
"*",
"2",
"]",
"leaves",
"[",
"i",
"*",
"2",
"]",
".",
"Parent",
"=",
"node",
"if",
"(",
"i",
"*",
"2",
"+",
"1",
"==",
"len",
"(",
"leaves",
")",
")",
":",
"node",
".",
"RightChild",
"=",
"node",
".",
"LeftChild",
"else",
":",
"node",
".",
"RightChild",
"=",
"leaves",
"[",
"i",
"*",
"2",
"+",
"1",
"]",
"leaves",
"[",
"i",
"*",
"2",
"+",
"1",
"]",
".",
"Parent",
"=",
"node",
"hasharray",
"=",
"bytearray",
"(",
"node",
".",
"LeftChild",
".",
"Hash",
".",
"ToArray",
"(",
")",
"+",
"node",
".",
"RightChild",
".",
"Hash",
".",
"ToArray",
"(",
")",
")",
"node",
".",
"Hash",
"=",
"UInt256",
"(",
"data",
"=",
"Crypto",
".",
"Hash256",
"(",
"hasharray",
")",
")",
"return",
"MerkleTree",
".",
"__Build",
"(",
"parents",
")"
] | Build the merkle tree.
Args:
leaves (list): items are of type MerkleTreeNode.
Returns:
MerkleTreeNode: the root node. | [
"Build",
"the",
"merkle",
"tree",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L70-L101 | train | 235,232 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.ComputeRoot | def ComputeRoot(hashes):
"""
Compute the root hash.
Args:
hashes (list): the list of hashes to build the root from.
Returns:
bytes: the root hash.
"""
if not len(hashes):
raise Exception('Hashes must have length')
if len(hashes) == 1:
return hashes[0]
tree = MerkleTree(hashes)
return tree.Root.Hash | python | def ComputeRoot(hashes):
"""
Compute the root hash.
Args:
hashes (list): the list of hashes to build the root from.
Returns:
bytes: the root hash.
"""
if not len(hashes):
raise Exception('Hashes must have length')
if len(hashes) == 1:
return hashes[0]
tree = MerkleTree(hashes)
return tree.Root.Hash | [
"def",
"ComputeRoot",
"(",
"hashes",
")",
":",
"if",
"not",
"len",
"(",
"hashes",
")",
":",
"raise",
"Exception",
"(",
"'Hashes must have length'",
")",
"if",
"len",
"(",
"hashes",
")",
"==",
"1",
":",
"return",
"hashes",
"[",
"0",
"]",
"tree",
"=",
"MerkleTree",
"(",
"hashes",
")",
"return",
"tree",
".",
"Root",
".",
"Hash"
] | Compute the root hash.
Args:
hashes (list): the list of hashes to build the root from.
Returns:
bytes: the root hash. | [
"Compute",
"the",
"root",
"hash",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L109-L125 | train | 235,233 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.ToHashArray | def ToHashArray(self):
"""
Turn the tree into a list of hashes.
Returns:
list:
"""
hashes = set()
MerkleTree.__DepthFirstSearch(self.Root, hashes)
return list(hashes) | python | def ToHashArray(self):
"""
Turn the tree into a list of hashes.
Returns:
list:
"""
hashes = set()
MerkleTree.__DepthFirstSearch(self.Root, hashes)
return list(hashes) | [
"def",
"ToHashArray",
"(",
"self",
")",
":",
"hashes",
"=",
"set",
"(",
")",
"MerkleTree",
".",
"__DepthFirstSearch",
"(",
"self",
".",
"Root",
",",
"hashes",
")",
"return",
"list",
"(",
"hashes",
")"
] | Turn the tree into a list of hashes.
Returns:
list: | [
"Turn",
"the",
"tree",
"into",
"a",
"list",
"of",
"hashes",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L142-L151 | train | 235,234 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.Trim | def Trim(self, flags):
"""
Trim the nodes from the tree keeping only the root hash.
Args:
flags: "0000" for trimming, any other value for keeping the nodes.
"""
logger.info("Trimming!")
flags = bytearray(flags)
length = 1 << self.Depth - 1
while len(flags) < length:
flags.append(0)
MerkleTree._TrimNode(self.Root, 0, self.Depth, flags) | python | def Trim(self, flags):
"""
Trim the nodes from the tree keeping only the root hash.
Args:
flags: "0000" for trimming, any other value for keeping the nodes.
"""
logger.info("Trimming!")
flags = bytearray(flags)
length = 1 << self.Depth - 1
while len(flags) < length:
flags.append(0)
MerkleTree._TrimNode(self.Root, 0, self.Depth, flags) | [
"def",
"Trim",
"(",
"self",
",",
"flags",
")",
":",
"logger",
".",
"info",
"(",
"\"Trimming!\"",
")",
"flags",
"=",
"bytearray",
"(",
"flags",
")",
"length",
"=",
"1",
"<<",
"self",
".",
"Depth",
"-",
"1",
"while",
"len",
"(",
"flags",
")",
"<",
"length",
":",
"flags",
".",
"append",
"(",
"0",
")",
"MerkleTree",
".",
"_TrimNode",
"(",
"self",
".",
"Root",
",",
"0",
",",
"self",
".",
"Depth",
",",
"flags",
")"
] | Trim the nodes from the tree keeping only the root hash.
Args:
flags: "0000" for trimming, any other value for keeping the nodes. | [
"Trim",
"the",
"nodes",
"from",
"the",
"tree",
"keeping",
"only",
"the",
"root",
"hash",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L153-L166 | train | 235,235 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree._TrimNode | def _TrimNode(node, index, depth, flags):
"""
Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node.
00 to erase, 11 to keep. Will keep the node if either left or right is not-0
"""
if depth == 1 or node.LeftChild is None:
return
if depth == 2:
if not flags[index * 2] and not flags[index * 2 + 1]:
node.LeftChild = None
node.RightChild = None
else:
MerkleTree._TrimNode(node.LeftChild, index * 2, depth - 1, flags)
MerkleTree._TrimNode(node.RightChild, index * 2, depth - 1, flags)
if node.LeftChild.LeftChild is None and node.RightChild.RightChild is None:
node.LeftChild = None
node.RightChild = None | python | def _TrimNode(node, index, depth, flags):
"""
Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node.
00 to erase, 11 to keep. Will keep the node if either left or right is not-0
"""
if depth == 1 or node.LeftChild is None:
return
if depth == 2:
if not flags[index * 2] and not flags[index * 2 + 1]:
node.LeftChild = None
node.RightChild = None
else:
MerkleTree._TrimNode(node.LeftChild, index * 2, depth - 1, flags)
MerkleTree._TrimNode(node.RightChild, index * 2, depth - 1, flags)
if node.LeftChild.LeftChild is None and node.RightChild.RightChild is None:
node.LeftChild = None
node.RightChild = None | [
"def",
"_TrimNode",
"(",
"node",
",",
"index",
",",
"depth",
",",
"flags",
")",
":",
"if",
"depth",
"==",
"1",
"or",
"node",
".",
"LeftChild",
"is",
"None",
":",
"return",
"if",
"depth",
"==",
"2",
":",
"if",
"not",
"flags",
"[",
"index",
"*",
"2",
"]",
"and",
"not",
"flags",
"[",
"index",
"*",
"2",
"+",
"1",
"]",
":",
"node",
".",
"LeftChild",
"=",
"None",
"node",
".",
"RightChild",
"=",
"None",
"else",
":",
"MerkleTree",
".",
"_TrimNode",
"(",
"node",
".",
"LeftChild",
",",
"index",
"*",
"2",
",",
"depth",
"-",
"1",
",",
"flags",
")",
"MerkleTree",
".",
"_TrimNode",
"(",
"node",
".",
"RightChild",
",",
"index",
"*",
"2",
",",
"depth",
"-",
"1",
",",
"flags",
")",
"if",
"node",
".",
"LeftChild",
".",
"LeftChild",
"is",
"None",
"and",
"node",
".",
"RightChild",
".",
"RightChild",
"is",
"None",
":",
"node",
".",
"LeftChild",
"=",
"None",
"node",
".",
"RightChild",
"=",
"None"
] | Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node.
00 to erase, 11 to keep. Will keep the node if either left or right is not-0 | [
"Internal",
"helper",
"method",
"to",
"trim",
"a",
"node",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L169-L195 | train | 235,236 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | double_sha256 | def double_sha256(ba):
"""
Perform two SHA256 operations on the input.
Args:
ba (bytes): data to hash.
Returns:
str: hash as a double digit hex string.
"""
d1 = hashlib.sha256(ba)
d2 = hashlib.sha256()
d1.hexdigest()
d2.update(d1.digest())
return d2.hexdigest() | python | def double_sha256(ba):
"""
Perform two SHA256 operations on the input.
Args:
ba (bytes): data to hash.
Returns:
str: hash as a double digit hex string.
"""
d1 = hashlib.sha256(ba)
d2 = hashlib.sha256()
d1.hexdigest()
d2.update(d1.digest())
return d2.hexdigest() | [
"def",
"double_sha256",
"(",
"ba",
")",
":",
"d1",
"=",
"hashlib",
".",
"sha256",
"(",
"ba",
")",
"d2",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"d1",
".",
"hexdigest",
"(",
")",
"d2",
".",
"update",
"(",
"d1",
".",
"digest",
"(",
")",
")",
"return",
"d2",
".",
"hexdigest",
"(",
")"
] | Perform two SHA256 operations on the input.
Args:
ba (bytes): data to hash.
Returns:
str: hash as a double digit hex string. | [
"Perform",
"two",
"SHA256",
"operations",
"on",
"the",
"input",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L28-L42 | train | 235,237 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | scripthash_to_address | def scripthash_to_address(scripthash):
"""
Convert a script hash to a public address.
Args:
scripthash (bytes):
Returns:
str: base58 encoded string representing the wallet address.
"""
sb = bytearray([ADDRESS_VERSION]) + scripthash
c256 = bin_dbl_sha256(sb)[0:4]
outb = sb + bytearray(c256)
return base58.b58encode(bytes(outb)).decode("utf-8") | python | def scripthash_to_address(scripthash):
"""
Convert a script hash to a public address.
Args:
scripthash (bytes):
Returns:
str: base58 encoded string representing the wallet address.
"""
sb = bytearray([ADDRESS_VERSION]) + scripthash
c256 = bin_dbl_sha256(sb)[0:4]
outb = sb + bytearray(c256)
return base58.b58encode(bytes(outb)).decode("utf-8") | [
"def",
"scripthash_to_address",
"(",
"scripthash",
")",
":",
"sb",
"=",
"bytearray",
"(",
"[",
"ADDRESS_VERSION",
"]",
")",
"+",
"scripthash",
"c256",
"=",
"bin_dbl_sha256",
"(",
"sb",
")",
"[",
"0",
":",
"4",
"]",
"outb",
"=",
"sb",
"+",
"bytearray",
"(",
"c256",
")",
"return",
"base58",
".",
"b58encode",
"(",
"bytes",
"(",
"outb",
")",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | Convert a script hash to a public address.
Args:
scripthash (bytes):
Returns:
str: base58 encoded string representing the wallet address. | [
"Convert",
"a",
"script",
"hash",
"to",
"a",
"public",
"address",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L71-L84 | train | 235,238 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | base256_encode | def base256_encode(n, minwidth=0): # int/long to byte array
"""
Encode the input with base256.
Args:
n (int): input value.
minwidth: minimum return value length.
Raises:
ValueError: if a negative number is provided.
Returns:
bytearray:
"""
if n > 0:
arr = []
while n:
n, rem = divmod(n, 256)
arr.append(rem)
b = bytearray(reversed(arr))
elif n == 0:
b = bytearray(b'\x00')
else:
raise ValueError("Negative numbers not supported")
if minwidth > 0 and len(b) < minwidth: # zero padding needed?
padding = (minwidth - len(b)) * b'\x00'
b = bytearray(padding) + b
b.reverse()
return b | python | def base256_encode(n, minwidth=0): # int/long to byte array
"""
Encode the input with base256.
Args:
n (int): input value.
minwidth: minimum return value length.
Raises:
ValueError: if a negative number is provided.
Returns:
bytearray:
"""
if n > 0:
arr = []
while n:
n, rem = divmod(n, 256)
arr.append(rem)
b = bytearray(reversed(arr))
elif n == 0:
b = bytearray(b'\x00')
else:
raise ValueError("Negative numbers not supported")
if minwidth > 0 and len(b) < minwidth: # zero padding needed?
padding = (minwidth - len(b)) * b'\x00'
b = bytearray(padding) + b
b.reverse()
return b | [
"def",
"base256_encode",
"(",
"n",
",",
"minwidth",
"=",
"0",
")",
":",
"# int/long to byte array",
"if",
"n",
">",
"0",
":",
"arr",
"=",
"[",
"]",
"while",
"n",
":",
"n",
",",
"rem",
"=",
"divmod",
"(",
"n",
",",
"256",
")",
"arr",
".",
"append",
"(",
"rem",
")",
"b",
"=",
"bytearray",
"(",
"reversed",
"(",
"arr",
")",
")",
"elif",
"n",
"==",
"0",
":",
"b",
"=",
"bytearray",
"(",
"b'\\x00'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Negative numbers not supported\"",
")",
"if",
"minwidth",
">",
"0",
"and",
"len",
"(",
"b",
")",
"<",
"minwidth",
":",
"# zero padding needed?",
"padding",
"=",
"(",
"minwidth",
"-",
"len",
"(",
"b",
")",
")",
"*",
"b'\\x00'",
"b",
"=",
"bytearray",
"(",
"padding",
")",
"+",
"b",
"b",
".",
"reverse",
"(",
")",
"return",
"b"
] | Encode the input with base256.
Args:
n (int): input value.
minwidth: minimum return value length.
Raises:
ValueError: if a negative number is provided.
Returns:
bytearray: | [
"Encode",
"the",
"input",
"with",
"base256",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L141-L171 | train | 235,239 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | xor_bytes | def xor_bytes(a, b):
"""
XOR on two bytes objects
Args:
a (bytes): object 1
b (bytes): object 2
Returns:
bytes: The XOR result
"""
assert isinstance(a, bytes)
assert isinstance(b, bytes)
assert len(a) == len(b)
res = bytearray()
for i in range(len(a)):
res.append(a[i] ^ b[i])
return bytes(res) | python | def xor_bytes(a, b):
"""
XOR on two bytes objects
Args:
a (bytes): object 1
b (bytes): object 2
Returns:
bytes: The XOR result
"""
assert isinstance(a, bytes)
assert isinstance(b, bytes)
assert len(a) == len(b)
res = bytearray()
for i in range(len(a)):
res.append(a[i] ^ b[i])
return bytes(res) | [
"def",
"xor_bytes",
"(",
"a",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"bytes",
")",
"assert",
"isinstance",
"(",
"b",
",",
"bytes",
")",
"assert",
"len",
"(",
"a",
")",
"==",
"len",
"(",
"b",
")",
"res",
"=",
"bytearray",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
":",
"res",
".",
"append",
"(",
"a",
"[",
"i",
"]",
"^",
"b",
"[",
"i",
"]",
")",
"return",
"bytes",
"(",
"res",
")"
] | XOR on two bytes objects
Args:
a (bytes): object 1
b (bytes): object 2
Returns:
bytes: The XOR result | [
"XOR",
"on",
"two",
"bytes",
"objects"
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L174-L191 | train | 235,240 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteBytes | def WriteBytes(self, value, unhex=True):
"""
Write a `bytes` type to the stream.
Args:
value (bytes): array of bytes to write to the stream.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
int: the number of bytes written.
"""
if unhex:
try:
value = binascii.unhexlify(value)
except binascii.Error:
pass
return self.stream.write(value) | python | def WriteBytes(self, value, unhex=True):
"""
Write a `bytes` type to the stream.
Args:
value (bytes): array of bytes to write to the stream.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
int: the number of bytes written.
"""
if unhex:
try:
value = binascii.unhexlify(value)
except binascii.Error:
pass
return self.stream.write(value) | [
"def",
"WriteBytes",
"(",
"self",
",",
"value",
",",
"unhex",
"=",
"True",
")",
":",
"if",
"unhex",
":",
"try",
":",
"value",
"=",
"binascii",
".",
"unhexlify",
"(",
"value",
")",
"except",
"binascii",
".",
"Error",
":",
"pass",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"value",
")"
] | Write a `bytes` type to the stream.
Args:
value (bytes): array of bytes to write to the stream.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
int: the number of bytes written. | [
"Write",
"a",
"bytes",
"type",
"to",
"the",
"stream",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L88-L104 | train | 235,241 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteUInt160 | def WriteUInt160(self, value):
"""
Write a UInt160 type to the stream.
Args:
value (UInt160):
Raises:
Exception: when `value` is not of neocore.UInt160 type.
"""
if type(value) is UInt160:
value.Serialize(self)
else:
raise Exception("value must be UInt160 instance ") | python | def WriteUInt160(self, value):
"""
Write a UInt160 type to the stream.
Args:
value (UInt160):
Raises:
Exception: when `value` is not of neocore.UInt160 type.
"""
if type(value) is UInt160:
value.Serialize(self)
else:
raise Exception("value must be UInt160 instance ") | [
"def",
"WriteUInt160",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"UInt160",
":",
"value",
".",
"Serialize",
"(",
"self",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"value must be UInt160 instance \"",
")"
] | Write a UInt160 type to the stream.
Args:
value (UInt160):
Raises:
Exception: when `value` is not of neocore.UInt160 type. | [
"Write",
"a",
"UInt160",
"type",
"to",
"the",
"stream",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L274-L287 | train | 235,242 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteUInt256 | def WriteUInt256(self, value):
"""
Write a UInt256 type to the stream.
Args:
value (UInt256):
Raises:
Exception: when `value` is not of neocore.UInt256 type.
"""
if type(value) is UInt256:
value.Serialize(self)
else:
raise Exception("Cannot write value that is not UInt256") | python | def WriteUInt256(self, value):
"""
Write a UInt256 type to the stream.
Args:
value (UInt256):
Raises:
Exception: when `value` is not of neocore.UInt256 type.
"""
if type(value) is UInt256:
value.Serialize(self)
else:
raise Exception("Cannot write value that is not UInt256") | [
"def",
"WriteUInt256",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"UInt256",
":",
"value",
".",
"Serialize",
"(",
"self",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Cannot write value that is not UInt256\"",
")"
] | Write a UInt256 type to the stream.
Args:
value (UInt256):
Raises:
Exception: when `value` is not of neocore.UInt256 type. | [
"Write",
"a",
"UInt256",
"type",
"to",
"the",
"stream",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L289-L302 | train | 235,243 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.Write2000256List | def Write2000256List(self, arr):
"""
Write an array of 64 byte items to the stream.
Args:
arr (list): a list of 2000 items of 64 bytes in size.
"""
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.reverse()
self.WriteBytes(ba) | python | def Write2000256List(self, arr):
"""
Write an array of 64 byte items to the stream.
Args:
arr (list): a list of 2000 items of 64 bytes in size.
"""
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.reverse()
self.WriteBytes(ba) | [
"def",
"Write2000256List",
"(",
"self",
",",
"arr",
")",
":",
"for",
"item",
"in",
"arr",
":",
"ba",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"item",
")",
")",
"ba",
".",
"reverse",
"(",
")",
"self",
".",
"WriteBytes",
"(",
"ba",
")"
] | Write an array of 64 byte items to the stream.
Args:
arr (list): a list of 2000 items of 64 bytes in size. | [
"Write",
"an",
"array",
"of",
"64",
"byte",
"items",
"to",
"the",
"stream",
"."
] | 786c02cc2f41712d70b1f064ae3d67f86167107f | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L410-L420 | train | 235,244 |
OTA-Insight/djangosaml2idp | djangosaml2idp/processors.py | BaseProcessor.get_user_id | def get_user_id(self, user):
""" Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set
use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field.
"""
user_field = getattr(settings, 'SAML_IDP_DJANGO_USERNAME_FIELD', None) or \
getattr(user, 'USERNAME_FIELD', 'username')
return str(getattr(user, user_field)) | python | def get_user_id(self, user):
""" Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set
use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field.
"""
user_field = getattr(settings, 'SAML_IDP_DJANGO_USERNAME_FIELD', None) or \
getattr(user, 'USERNAME_FIELD', 'username')
return str(getattr(user, user_field)) | [
"def",
"get_user_id",
"(",
"self",
",",
"user",
")",
":",
"user_field",
"=",
"getattr",
"(",
"settings",
",",
"'SAML_IDP_DJANGO_USERNAME_FIELD'",
",",
"None",
")",
"or",
"getattr",
"(",
"user",
",",
"'USERNAME_FIELD'",
",",
"'username'",
")",
"return",
"str",
"(",
"getattr",
"(",
"user",
",",
"user_field",
")",
")"
] | Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set
use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field. | [
"Get",
"identifier",
"for",
"a",
"user",
".",
"Take",
"the",
"one",
"defined",
"in",
"settings",
".",
"SAML_IDP_DJANGO_USERNAME_FIELD",
"first",
"if",
"not",
"set",
"use",
"the",
"USERNAME_FIELD",
"property",
"which",
"is",
"set",
"on",
"the",
"user",
"Model",
".",
"This",
"defaults",
"to",
"the",
"user",
".",
"username",
"field",
"."
] | 8a238063da55bf4823bdc2192168171767c4e056 | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/processors.py#L22-L28 | train | 235,245 |
OTA-Insight/djangosaml2idp | djangosaml2idp/processors.py | BaseProcessor.create_identity | def create_identity(self, user, sp_mapping, **extra_config):
""" Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP
"""
return {
out_attr: getattr(user, user_attr)
for user_attr, out_attr in sp_mapping.items()
if hasattr(user, user_attr)
} | python | def create_identity(self, user, sp_mapping, **extra_config):
""" Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP
"""
return {
out_attr: getattr(user, user_attr)
for user_attr, out_attr in sp_mapping.items()
if hasattr(user, user_attr)
} | [
"def",
"create_identity",
"(",
"self",
",",
"user",
",",
"sp_mapping",
",",
"*",
"*",
"extra_config",
")",
":",
"return",
"{",
"out_attr",
":",
"getattr",
"(",
"user",
",",
"user_attr",
")",
"for",
"user_attr",
",",
"out_attr",
"in",
"sp_mapping",
".",
"items",
"(",
")",
"if",
"hasattr",
"(",
"user",
",",
"user_attr",
")",
"}"
] | Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP | [
"Generate",
"an",
"identity",
"dictionary",
"of",
"the",
"user",
"based",
"on",
"the",
"given",
"mapping",
"of",
"desired",
"user",
"attributes",
"by",
"the",
"SP"
] | 8a238063da55bf4823bdc2192168171767c4e056 | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/processors.py#L30-L38 | train | 235,246 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | sso_entry | def sso_entry(request):
""" Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session
and redirects the requester to the login_process view.
"""
if request.method == 'POST':
passed_data = request.POST
binding = BINDING_HTTP_POST
else:
passed_data = request.GET
binding = BINDING_HTTP_REDIRECT
request.session['Binding'] = binding
try:
request.session['SAMLRequest'] = passed_data['SAMLRequest']
except (KeyError, MultiValueDictKeyError) as e:
return HttpResponseBadRequest(e)
request.session['RelayState'] = passed_data.get('RelayState', '')
# TODO check how the redirect saml way works. Taken from example idp in pysaml2.
if "SigAlg" in passed_data and "Signature" in passed_data:
request.session['SigAlg'] = passed_data['SigAlg']
request.session['Signature'] = passed_data['Signature']
return HttpResponseRedirect(reverse('djangosaml2idp:saml_login_process')) | python | def sso_entry(request):
""" Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session
and redirects the requester to the login_process view.
"""
if request.method == 'POST':
passed_data = request.POST
binding = BINDING_HTTP_POST
else:
passed_data = request.GET
binding = BINDING_HTTP_REDIRECT
request.session['Binding'] = binding
try:
request.session['SAMLRequest'] = passed_data['SAMLRequest']
except (KeyError, MultiValueDictKeyError) as e:
return HttpResponseBadRequest(e)
request.session['RelayState'] = passed_data.get('RelayState', '')
# TODO check how the redirect saml way works. Taken from example idp in pysaml2.
if "SigAlg" in passed_data and "Signature" in passed_data:
request.session['SigAlg'] = passed_data['SigAlg']
request.session['Signature'] = passed_data['Signature']
return HttpResponseRedirect(reverse('djangosaml2idp:saml_login_process')) | [
"def",
"sso_entry",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"passed_data",
"=",
"request",
".",
"POST",
"binding",
"=",
"BINDING_HTTP_POST",
"else",
":",
"passed_data",
"=",
"request",
".",
"GET",
"binding",
"=",
"BINDING_HTTP_REDIRECT",
"request",
".",
"session",
"[",
"'Binding'",
"]",
"=",
"binding",
"try",
":",
"request",
".",
"session",
"[",
"'SAMLRequest'",
"]",
"=",
"passed_data",
"[",
"'SAMLRequest'",
"]",
"except",
"(",
"KeyError",
",",
"MultiValueDictKeyError",
")",
"as",
"e",
":",
"return",
"HttpResponseBadRequest",
"(",
"e",
")",
"request",
".",
"session",
"[",
"'RelayState'",
"]",
"=",
"passed_data",
".",
"get",
"(",
"'RelayState'",
",",
"''",
")",
"# TODO check how the redirect saml way works. Taken from example idp in pysaml2.",
"if",
"\"SigAlg\"",
"in",
"passed_data",
"and",
"\"Signature\"",
"in",
"passed_data",
":",
"request",
".",
"session",
"[",
"'SigAlg'",
"]",
"=",
"passed_data",
"[",
"'SigAlg'",
"]",
"request",
".",
"session",
"[",
"'Signature'",
"]",
"=",
"passed_data",
"[",
"'Signature'",
"]",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'djangosaml2idp:saml_login_process'",
")",
")"
] | Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session
and redirects the requester to the login_process view. | [
"Entrypoint",
"view",
"for",
"SSO",
".",
"Gathers",
"the",
"parameters",
"from",
"the",
"HTTP",
"request",
"stores",
"them",
"in",
"the",
"session",
"and",
"redirects",
"the",
"requester",
"to",
"the",
"login_process",
"view",
"."
] | 8a238063da55bf4823bdc2192168171767c4e056 | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L41-L63 | train | 235,247 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | metadata | def metadata(request):
""" Returns an XML with the SAML 2.0 metadata for this Idp.
The metadata is constructed on-the-fly based on the config dict in the django settings.
"""
conf = IdPConfig()
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
metadata = entity_descriptor(conf)
return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8") | python | def metadata(request):
""" Returns an XML with the SAML 2.0 metadata for this Idp.
The metadata is constructed on-the-fly based on the config dict in the django settings.
"""
conf = IdPConfig()
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
metadata = entity_descriptor(conf)
return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8") | [
"def",
"metadata",
"(",
"request",
")",
":",
"conf",
"=",
"IdPConfig",
"(",
")",
"conf",
".",
"load",
"(",
"copy",
".",
"deepcopy",
"(",
"settings",
".",
"SAML_IDP_CONFIG",
")",
")",
"metadata",
"=",
"entity_descriptor",
"(",
"conf",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"text_type",
"(",
"metadata",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"content_type",
"=",
"\"text/xml; charset=utf8\"",
")"
] | Returns an XML with the SAML 2.0 metadata for this Idp.
The metadata is constructed on-the-fly based on the config dict in the django settings. | [
"Returns",
"an",
"XML",
"with",
"the",
"SAML",
"2",
".",
"0",
"metadata",
"for",
"this",
"Idp",
".",
"The",
"metadata",
"is",
"constructed",
"on",
"-",
"the",
"-",
"fly",
"based",
"on",
"the",
"config",
"dict",
"in",
"the",
"django",
"settings",
"."
] | 8a238063da55bf4823bdc2192168171767c4e056 | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L284-L291 | train | 235,248 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | IdPHandlerViewMixin.dispatch | def dispatch(self, request, *args, **kwargs):
""" Construct IDP server with config from settings dict
"""
conf = IdPConfig()
try:
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
self.IDP = Server(config=conf)
except Exception as e:
return self.handle_error(request, exception=e)
return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs) | python | def dispatch(self, request, *args, **kwargs):
""" Construct IDP server with config from settings dict
"""
conf = IdPConfig()
try:
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
self.IDP = Server(config=conf)
except Exception as e:
return self.handle_error(request, exception=e)
return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"conf",
"=",
"IdPConfig",
"(",
")",
"try",
":",
"conf",
".",
"load",
"(",
"copy",
".",
"deepcopy",
"(",
"settings",
".",
"SAML_IDP_CONFIG",
")",
")",
"self",
".",
"IDP",
"=",
"Server",
"(",
"config",
"=",
"conf",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"self",
".",
"handle_error",
"(",
"request",
",",
"exception",
"=",
"e",
")",
"return",
"super",
"(",
"IdPHandlerViewMixin",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Construct IDP server with config from settings dict | [
"Construct",
"IDP",
"server",
"with",
"config",
"from",
"settings",
"dict"
] | 8a238063da55bf4823bdc2192168171767c4e056 | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L74-L83 | train | 235,249 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | IdPHandlerViewMixin.get_processor | def get_processor(self, entity_id, sp_config):
""" Instantiate user-specified processor or default to an all-access base processor.
Raises an exception if the configured processor class can not be found or initialized.
"""
processor_string = sp_config.get('processor', None)
if processor_string:
try:
return import_string(processor_string)(entity_id)
except Exception as e:
logger.error("Failed to instantiate processor: {} - {}".format(processor_string, e), exc_info=True)
raise
return BaseProcessor(entity_id) | python | def get_processor(self, entity_id, sp_config):
""" Instantiate user-specified processor or default to an all-access base processor.
Raises an exception if the configured processor class can not be found or initialized.
"""
processor_string = sp_config.get('processor', None)
if processor_string:
try:
return import_string(processor_string)(entity_id)
except Exception as e:
logger.error("Failed to instantiate processor: {} - {}".format(processor_string, e), exc_info=True)
raise
return BaseProcessor(entity_id) | [
"def",
"get_processor",
"(",
"self",
",",
"entity_id",
",",
"sp_config",
")",
":",
"processor_string",
"=",
"sp_config",
".",
"get",
"(",
"'processor'",
",",
"None",
")",
"if",
"processor_string",
":",
"try",
":",
"return",
"import_string",
"(",
"processor_string",
")",
"(",
"entity_id",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Failed to instantiate processor: {} - {}\"",
".",
"format",
"(",
"processor_string",
",",
"e",
")",
",",
"exc_info",
"=",
"True",
")",
"raise",
"return",
"BaseProcessor",
"(",
"entity_id",
")"
] | Instantiate user-specified processor or default to an all-access base processor.
Raises an exception if the configured processor class can not be found or initialized. | [
"Instantiate",
"user",
"-",
"specified",
"processor",
"or",
"default",
"to",
"an",
"all",
"-",
"access",
"base",
"processor",
".",
"Raises",
"an",
"exception",
"if",
"the",
"configured",
"processor",
"class",
"can",
"not",
"be",
"found",
"or",
"initialized",
"."
] | 8a238063da55bf4823bdc2192168171767c4e056 | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L85-L96 | train | 235,250 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | IscDhcpLeases.get | def get(self, include_backups=False):
"""
Parse the lease file and return a list of Lease instances.
"""
leases = []
with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file:
lease_data = lease_file.read()
if self.gzip:
lease_data = lease_data.decode('utf-8')
for match in self.regex_leaseblock.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
if 'hardware' not in properties and not include_backups:
# E.g. rows like {'binding': 'state abandoned', ...}
continue
lease = Lease(block['ip'], properties=properties, options=options, sets=sets)
leases.append(lease)
for match in self.regex_leaseblock6.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
host_identifier = block['id']
block_type = block['type']
last_client_communication = parse_time(properties['cltt'])
for address_block in self.regex_iaaddr.finditer(block['config']):
block = address_block.groupdict()
properties, options, sets = _extract_properties(block['config'])
lease = Lease6(block['ip'], properties, last_client_communication, host_identifier, block_type,
options=options, sets=sets)
leases.append(lease)
return leases | python | def get(self, include_backups=False):
"""
Parse the lease file and return a list of Lease instances.
"""
leases = []
with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file:
lease_data = lease_file.read()
if self.gzip:
lease_data = lease_data.decode('utf-8')
for match in self.regex_leaseblock.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
if 'hardware' not in properties and not include_backups:
# E.g. rows like {'binding': 'state abandoned', ...}
continue
lease = Lease(block['ip'], properties=properties, options=options, sets=sets)
leases.append(lease)
for match in self.regex_leaseblock6.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
host_identifier = block['id']
block_type = block['type']
last_client_communication = parse_time(properties['cltt'])
for address_block in self.regex_iaaddr.finditer(block['config']):
block = address_block.groupdict()
properties, options, sets = _extract_properties(block['config'])
lease = Lease6(block['ip'], properties, last_client_communication, host_identifier, block_type,
options=options, sets=sets)
leases.append(lease)
return leases | [
"def",
"get",
"(",
"self",
",",
"include_backups",
"=",
"False",
")",
":",
"leases",
"=",
"[",
"]",
"with",
"open",
"(",
"self",
".",
"filename",
")",
"if",
"not",
"self",
".",
"gzip",
"else",
"gzip",
".",
"open",
"(",
"self",
".",
"filename",
")",
"as",
"lease_file",
":",
"lease_data",
"=",
"lease_file",
".",
"read",
"(",
")",
"if",
"self",
".",
"gzip",
":",
"lease_data",
"=",
"lease_data",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"match",
"in",
"self",
".",
"regex_leaseblock",
".",
"finditer",
"(",
"lease_data",
")",
":",
"block",
"=",
"match",
".",
"groupdict",
"(",
")",
"properties",
",",
"options",
",",
"sets",
"=",
"_extract_properties",
"(",
"block",
"[",
"'config'",
"]",
")",
"if",
"'hardware'",
"not",
"in",
"properties",
"and",
"not",
"include_backups",
":",
"# E.g. rows like {'binding': 'state abandoned', ...}",
"continue",
"lease",
"=",
"Lease",
"(",
"block",
"[",
"'ip'",
"]",
",",
"properties",
"=",
"properties",
",",
"options",
"=",
"options",
",",
"sets",
"=",
"sets",
")",
"leases",
".",
"append",
"(",
"lease",
")",
"for",
"match",
"in",
"self",
".",
"regex_leaseblock6",
".",
"finditer",
"(",
"lease_data",
")",
":",
"block",
"=",
"match",
".",
"groupdict",
"(",
")",
"properties",
",",
"options",
",",
"sets",
"=",
"_extract_properties",
"(",
"block",
"[",
"'config'",
"]",
")",
"host_identifier",
"=",
"block",
"[",
"'id'",
"]",
"block_type",
"=",
"block",
"[",
"'type'",
"]",
"last_client_communication",
"=",
"parse_time",
"(",
"properties",
"[",
"'cltt'",
"]",
")",
"for",
"address_block",
"in",
"self",
".",
"regex_iaaddr",
".",
"finditer",
"(",
"block",
"[",
"'config'",
"]",
")",
":",
"block",
"=",
"address_block",
".",
"groupdict",
"(",
")",
"properties",
",",
"options",
",",
"sets",
"=",
"_extract_properties",
"(",
"block",
"[",
"'config'",
"]",
")",
"lease",
"=",
"Lease6",
"(",
"block",
"[",
"'ip'",
"]",
",",
"properties",
",",
"last_client_communication",
",",
"host_identifier",
",",
"block_type",
",",
"options",
"=",
"options",
",",
"sets",
"=",
"sets",
")",
"leases",
".",
"append",
"(",
"lease",
")",
"return",
"leases"
] | Parse the lease file and return a list of Lease instances. | [
"Parse",
"the",
"lease",
"file",
"and",
"return",
"a",
"list",
"of",
"Lease",
"instances",
"."
] | e96c00e31f3a52c01ef98193577d614d08a93285 | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L115-L151 | train | 235,251 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | IscDhcpLeases.get_current | def get_current(self):
"""
Parse the lease file and return a dict of active and valid Lease instances.
The key for this dict is the ethernet address of the lease.
"""
all_leases = self.get()
leases = {}
for lease in all_leases:
if lease.valid and lease.active:
if type(lease) is Lease:
leases[lease.ethernet] = lease
elif type(lease) is Lease6:
leases['%s-%s' % (lease.type, lease.host_identifier_string)] = lease
return leases | python | def get_current(self):
"""
Parse the lease file and return a dict of active and valid Lease instances.
The key for this dict is the ethernet address of the lease.
"""
all_leases = self.get()
leases = {}
for lease in all_leases:
if lease.valid and lease.active:
if type(lease) is Lease:
leases[lease.ethernet] = lease
elif type(lease) is Lease6:
leases['%s-%s' % (lease.type, lease.host_identifier_string)] = lease
return leases | [
"def",
"get_current",
"(",
"self",
")",
":",
"all_leases",
"=",
"self",
".",
"get",
"(",
")",
"leases",
"=",
"{",
"}",
"for",
"lease",
"in",
"all_leases",
":",
"if",
"lease",
".",
"valid",
"and",
"lease",
".",
"active",
":",
"if",
"type",
"(",
"lease",
")",
"is",
"Lease",
":",
"leases",
"[",
"lease",
".",
"ethernet",
"]",
"=",
"lease",
"elif",
"type",
"(",
"lease",
")",
"is",
"Lease6",
":",
"leases",
"[",
"'%s-%s'",
"%",
"(",
"lease",
".",
"type",
",",
"lease",
".",
"host_identifier_string",
")",
"]",
"=",
"lease",
"return",
"leases"
] | Parse the lease file and return a dict of active and valid Lease instances.
The key for this dict is the ethernet address of the lease. | [
"Parse",
"the",
"lease",
"file",
"and",
"return",
"a",
"dict",
"of",
"active",
"and",
"valid",
"Lease",
"instances",
".",
"The",
"key",
"for",
"this",
"dict",
"is",
"the",
"ethernet",
"address",
"of",
"the",
"lease",
"."
] | e96c00e31f3a52c01ef98193577d614d08a93285 | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L153-L166 | train | 235,252 |
crate/crash | src/crate/crash/layout.py | create_layout | def create_layout(lexer=None,
reserve_space_for_menu=8,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
extra_input_processors=None, multiline=False,
wrap_lines=True):
"""
Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar container
* a bottom right-aligned side-bar container
+-------------------------------------------+
| cr> select 1; |
| |
| |
+-------------------------------------------+
| bottom_toolbar_tokens sidebar_tokens |
+-------------------------------------------+
"""
# Create processors list.
input_processors = [
ConditionalProcessor(
# Highlight the reverse-i-search buffer
HighlightSearchProcessor(preview_search=True),
HasFocus(SEARCH_BUFFER)),
]
if extra_input_processors:
input_processors.extend(extra_input_processors)
lexer = PygmentsLexer(lexer, sync_from_start=True)
multiline = to_cli_filter(multiline)
sidebar_token = [
(Token.Toolbar.Status.Key, "[ctrl+d]"),
(Token.Toolbar.Status, " Exit")
]
sidebar_width = token_list_width(sidebar_token)
get_sidebar_tokens = lambda _: sidebar_token
def get_height(cli):
# If there is an autocompletion menu to be shown, make sure that our
# layout has at least a minimal height in order to display it.
if reserve_space_for_menu and not cli.is_done:
buff = cli.current_buffer
# Reserve the space, either when there are completions, or when
# `complete_while_typing` is true and we expect completions very
# soon.
if buff.complete_while_typing() or buff.complete_state is not None:
return LayoutDimension(min=reserve_space_for_menu)
return LayoutDimension()
# Create and return Container instance.
return HSplit([
VSplit([
HSplit([
# The main input, with completion menus floating on top of it.
FloatContainer(
HSplit([
Window(
BufferControl(
input_processors=input_processors,
lexer=lexer,
# enable preview search for reverse-i-search
preview_search=True),
get_height=get_height,
wrap_lines=wrap_lines,
left_margins=[
# In multiline mode, use the window margin to display
# the prompt and continuation tokens.
ConditionalMargin(
PromptMargin(get_prompt_tokens),
filter=multiline
)
],
),
]),
[
# Completion menu
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=16,
scroll_offset=1,
extra_filter=HasFocus(DEFAULT_BUFFER))
),
]
),
# reverse-i-search toolbar (ctrl+r)
ConditionalContainer(SearchToolbar(), multiline),
])
]),
] + [
VSplit([
# Left-Aligned Session Toolbar
ConditionalContainer(
Window(
TokenListControl(get_bottom_toolbar_tokens),
height=LayoutDimension.exact(1)
),
filter=~IsDone() & RendererHeightIsKnown()),
# Right-Aligned Container
ConditionalContainer(
Window(
TokenListControl(get_sidebar_tokens),
height=LayoutDimension.exact(1),
width=LayoutDimension.exact(sidebar_width)
),
filter=~IsDone() & RendererHeightIsKnown())
])
]) | python | def create_layout(lexer=None,
reserve_space_for_menu=8,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
extra_input_processors=None, multiline=False,
wrap_lines=True):
"""
Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar container
* a bottom right-aligned side-bar container
+-------------------------------------------+
| cr> select 1; |
| |
| |
+-------------------------------------------+
| bottom_toolbar_tokens sidebar_tokens |
+-------------------------------------------+
"""
# Create processors list.
input_processors = [
ConditionalProcessor(
# Highlight the reverse-i-search buffer
HighlightSearchProcessor(preview_search=True),
HasFocus(SEARCH_BUFFER)),
]
if extra_input_processors:
input_processors.extend(extra_input_processors)
lexer = PygmentsLexer(lexer, sync_from_start=True)
multiline = to_cli_filter(multiline)
sidebar_token = [
(Token.Toolbar.Status.Key, "[ctrl+d]"),
(Token.Toolbar.Status, " Exit")
]
sidebar_width = token_list_width(sidebar_token)
get_sidebar_tokens = lambda _: sidebar_token
def get_height(cli):
# If there is an autocompletion menu to be shown, make sure that our
# layout has at least a minimal height in order to display it.
if reserve_space_for_menu and not cli.is_done:
buff = cli.current_buffer
# Reserve the space, either when there are completions, or when
# `complete_while_typing` is true and we expect completions very
# soon.
if buff.complete_while_typing() or buff.complete_state is not None:
return LayoutDimension(min=reserve_space_for_menu)
return LayoutDimension()
# Create and return Container instance.
return HSplit([
VSplit([
HSplit([
# The main input, with completion menus floating on top of it.
FloatContainer(
HSplit([
Window(
BufferControl(
input_processors=input_processors,
lexer=lexer,
# enable preview search for reverse-i-search
preview_search=True),
get_height=get_height,
wrap_lines=wrap_lines,
left_margins=[
# In multiline mode, use the window margin to display
# the prompt and continuation tokens.
ConditionalMargin(
PromptMargin(get_prompt_tokens),
filter=multiline
)
],
),
]),
[
# Completion menu
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=16,
scroll_offset=1,
extra_filter=HasFocus(DEFAULT_BUFFER))
),
]
),
# reverse-i-search toolbar (ctrl+r)
ConditionalContainer(SearchToolbar(), multiline),
])
]),
] + [
VSplit([
# Left-Aligned Session Toolbar
ConditionalContainer(
Window(
TokenListControl(get_bottom_toolbar_tokens),
height=LayoutDimension.exact(1)
),
filter=~IsDone() & RendererHeightIsKnown()),
# Right-Aligned Container
ConditionalContainer(
Window(
TokenListControl(get_sidebar_tokens),
height=LayoutDimension.exact(1),
width=LayoutDimension.exact(sidebar_width)
),
filter=~IsDone() & RendererHeightIsKnown())
])
]) | [
"def",
"create_layout",
"(",
"lexer",
"=",
"None",
",",
"reserve_space_for_menu",
"=",
"8",
",",
"get_prompt_tokens",
"=",
"None",
",",
"get_bottom_toolbar_tokens",
"=",
"None",
",",
"extra_input_processors",
"=",
"None",
",",
"multiline",
"=",
"False",
",",
"wrap_lines",
"=",
"True",
")",
":",
"# Create processors list.",
"input_processors",
"=",
"[",
"ConditionalProcessor",
"(",
"# Highlight the reverse-i-search buffer",
"HighlightSearchProcessor",
"(",
"preview_search",
"=",
"True",
")",
",",
"HasFocus",
"(",
"SEARCH_BUFFER",
")",
")",
",",
"]",
"if",
"extra_input_processors",
":",
"input_processors",
".",
"extend",
"(",
"extra_input_processors",
")",
"lexer",
"=",
"PygmentsLexer",
"(",
"lexer",
",",
"sync_from_start",
"=",
"True",
")",
"multiline",
"=",
"to_cli_filter",
"(",
"multiline",
")",
"sidebar_token",
"=",
"[",
"(",
"Token",
".",
"Toolbar",
".",
"Status",
".",
"Key",
",",
"\"[ctrl+d]\"",
")",
",",
"(",
"Token",
".",
"Toolbar",
".",
"Status",
",",
"\" Exit\"",
")",
"]",
"sidebar_width",
"=",
"token_list_width",
"(",
"sidebar_token",
")",
"get_sidebar_tokens",
"=",
"lambda",
"_",
":",
"sidebar_token",
"def",
"get_height",
"(",
"cli",
")",
":",
"# If there is an autocompletion menu to be shown, make sure that our",
"# layout has at least a minimal height in order to display it.",
"if",
"reserve_space_for_menu",
"and",
"not",
"cli",
".",
"is_done",
":",
"buff",
"=",
"cli",
".",
"current_buffer",
"# Reserve the space, either when there are completions, or when",
"# `complete_while_typing` is true and we expect completions very",
"# soon.",
"if",
"buff",
".",
"complete_while_typing",
"(",
")",
"or",
"buff",
".",
"complete_state",
"is",
"not",
"None",
":",
"return",
"LayoutDimension",
"(",
"min",
"=",
"reserve_space_for_menu",
")",
"return",
"LayoutDimension",
"(",
")",
"# Create and return Container instance.",
"return",
"HSplit",
"(",
"[",
"VSplit",
"(",
"[",
"HSplit",
"(",
"[",
"# The main input, with completion menus floating on top of it.",
"FloatContainer",
"(",
"HSplit",
"(",
"[",
"Window",
"(",
"BufferControl",
"(",
"input_processors",
"=",
"input_processors",
",",
"lexer",
"=",
"lexer",
",",
"# enable preview search for reverse-i-search",
"preview_search",
"=",
"True",
")",
",",
"get_height",
"=",
"get_height",
",",
"wrap_lines",
"=",
"wrap_lines",
",",
"left_margins",
"=",
"[",
"# In multiline mode, use the window margin to display",
"# the prompt and continuation tokens.",
"ConditionalMargin",
"(",
"PromptMargin",
"(",
"get_prompt_tokens",
")",
",",
"filter",
"=",
"multiline",
")",
"]",
",",
")",
",",
"]",
")",
",",
"[",
"# Completion menu",
"Float",
"(",
"xcursor",
"=",
"True",
",",
"ycursor",
"=",
"True",
",",
"content",
"=",
"CompletionsMenu",
"(",
"max_height",
"=",
"16",
",",
"scroll_offset",
"=",
"1",
",",
"extra_filter",
"=",
"HasFocus",
"(",
"DEFAULT_BUFFER",
")",
")",
")",
",",
"]",
")",
",",
"# reverse-i-search toolbar (ctrl+r)",
"ConditionalContainer",
"(",
"SearchToolbar",
"(",
")",
",",
"multiline",
")",
",",
"]",
")",
"]",
")",
",",
"]",
"+",
"[",
"VSplit",
"(",
"[",
"# Left-Aligned Session Toolbar",
"ConditionalContainer",
"(",
"Window",
"(",
"TokenListControl",
"(",
"get_bottom_toolbar_tokens",
")",
",",
"height",
"=",
"LayoutDimension",
".",
"exact",
"(",
"1",
")",
")",
",",
"filter",
"=",
"~",
"IsDone",
"(",
")",
"&",
"RendererHeightIsKnown",
"(",
")",
")",
",",
"# Right-Aligned Container",
"ConditionalContainer",
"(",
"Window",
"(",
"TokenListControl",
"(",
"get_sidebar_tokens",
")",
",",
"height",
"=",
"LayoutDimension",
".",
"exact",
"(",
"1",
")",
",",
"width",
"=",
"LayoutDimension",
".",
"exact",
"(",
"sidebar_width",
")",
")",
",",
"filter",
"=",
"~",
"IsDone",
"(",
")",
"&",
"RendererHeightIsKnown",
"(",
")",
")",
"]",
")",
"]",
")"
] | Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar container
* a bottom right-aligned side-bar container
+-------------------------------------------+
| cr> select 1; |
| |
| |
+-------------------------------------------+
| bottom_toolbar_tokens sidebar_tokens |
+-------------------------------------------+ | [
"Creates",
"a",
"custom",
"Layout",
"for",
"the",
"Crash",
"input",
"REPL"
] | 32d3ddc78fd2f7848ed2b99d9cd8889e322528d9 | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/layout.py#L39-L157 | train | 235,253 |
crate/crash | src/crate/crash/command.py | _parse_statements | def _parse_statements(lines):
"""Return a generator of statements
Args: A list of strings that can contain one or more statements.
Statements are separated using ';' at the end of a line
Everything after the last ';' will be treated as the last statement.
>>> list(_parse_statements(['select * from ', 't1;', 'select name']))
['select * from\\nt1', 'select name']
>>> list(_parse_statements(['select * from t1;', ' ']))
['select * from t1']
"""
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield '\n'.join(parts)
parts[:] = []
if parts:
yield '\n'.join(parts) | python | def _parse_statements(lines):
"""Return a generator of statements
Args: A list of strings that can contain one or more statements.
Statements are separated using ';' at the end of a line
Everything after the last ';' will be treated as the last statement.
>>> list(_parse_statements(['select * from ', 't1;', 'select name']))
['select * from\\nt1', 'select name']
>>> list(_parse_statements(['select * from t1;', ' ']))
['select * from t1']
"""
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield '\n'.join(parts)
parts[:] = []
if parts:
yield '\n'.join(parts) | [
"def",
"_parse_statements",
"(",
"lines",
")",
":",
"lines",
"=",
"(",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"if",
"l",
")",
"lines",
"=",
"(",
"l",
"for",
"l",
"in",
"lines",
"if",
"l",
"and",
"not",
"l",
".",
"startswith",
"(",
"'--'",
")",
")",
"parts",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"parts",
".",
"append",
"(",
"line",
".",
"rstrip",
"(",
"';'",
")",
")",
"if",
"line",
".",
"endswith",
"(",
"';'",
")",
":",
"yield",
"'\\n'",
".",
"join",
"(",
"parts",
")",
"parts",
"[",
":",
"]",
"=",
"[",
"]",
"if",
"parts",
":",
"yield",
"'\\n'",
".",
"join",
"(",
"parts",
")"
] | Return a generator of statements
Args: A list of strings that can contain one or more statements.
Statements are separated using ';' at the end of a line
Everything after the last ';' will be treated as the last statement.
>>> list(_parse_statements(['select * from ', 't1;', 'select name']))
['select * from\\nt1', 'select name']
>>> list(_parse_statements(['select * from t1;', ' ']))
['select * from t1'] | [
"Return",
"a",
"generator",
"of",
"statements"
] | 32d3ddc78fd2f7848ed2b99d9cd8889e322528d9 | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L191-L213 | train | 235,254 |
crate/crash | src/crate/crash/command.py | CrateShell._show_tables | def _show_tables(self, *args):
""" print the existing tables within the 'doc' schema """
v = self.connection.lowest_server_version
schema_name = \
"table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name"
table_filter = \
" AND table_type = 'BASE TABLE'" if v >= TABLE_TYPE_MIN_VERSION else ""
self._exec("SELECT format('%s.%s', {schema}, table_name) AS name "
"FROM information_schema.tables "
"WHERE {schema} NOT IN ('sys','information_schema', 'pg_catalog')"
"{table_filter}"
.format(schema=schema_name, table_filter=table_filter)) | python | def _show_tables(self, *args):
""" print the existing tables within the 'doc' schema """
v = self.connection.lowest_server_version
schema_name = \
"table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name"
table_filter = \
" AND table_type = 'BASE TABLE'" if v >= TABLE_TYPE_MIN_VERSION else ""
self._exec("SELECT format('%s.%s', {schema}, table_name) AS name "
"FROM information_schema.tables "
"WHERE {schema} NOT IN ('sys','information_schema', 'pg_catalog')"
"{table_filter}"
.format(schema=schema_name, table_filter=table_filter)) | [
"def",
"_show_tables",
"(",
"self",
",",
"*",
"args",
")",
":",
"v",
"=",
"self",
".",
"connection",
".",
"lowest_server_version",
"schema_name",
"=",
"\"table_schema\"",
"if",
"v",
">=",
"TABLE_SCHEMA_MIN_VERSION",
"else",
"\"schema_name\"",
"table_filter",
"=",
"\" AND table_type = 'BASE TABLE'\"",
"if",
"v",
">=",
"TABLE_TYPE_MIN_VERSION",
"else",
"\"\"",
"self",
".",
"_exec",
"(",
"\"SELECT format('%s.%s', {schema}, table_name) AS name \"",
"\"FROM information_schema.tables \"",
"\"WHERE {schema} NOT IN ('sys','information_schema', 'pg_catalog')\"",
"\"{table_filter}\"",
".",
"format",
"(",
"schema",
"=",
"schema_name",
",",
"table_filter",
"=",
"table_filter",
")",
")"
] | print the existing tables within the 'doc' schema | [
"print",
"the",
"existing",
"tables",
"within",
"the",
"doc",
"schema"
] | 32d3ddc78fd2f7848ed2b99d9cd8889e322528d9 | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L321-L333 | train | 235,255 |
crate/crash | src/crate/crash/sysinfo.py | SysInfoCommand.execute | def execute(self):
""" print system and cluster info """
if not self.cmd.is_conn_available():
return
if self.cmd.connection.lowest_server_version >= SYSINFO_MIN_VERSION:
success, rows = self._sys_info()
self.cmd.exit_code = self.cmd.exit_code or int(not success)
if success:
for result in rows:
self.cmd.pprint(result.rows, result.cols)
self.cmd.logger.info(
"For debugging purposes you can send above listed information to support@crate.io")
else:
tmpl = 'Crate {version} does not support the cluster "sysinfo" command'
self.cmd.logger.warn(tmpl
.format(version=self.cmd.connection.lowest_server_version)) | python | def execute(self):
""" print system and cluster info """
if not self.cmd.is_conn_available():
return
if self.cmd.connection.lowest_server_version >= SYSINFO_MIN_VERSION:
success, rows = self._sys_info()
self.cmd.exit_code = self.cmd.exit_code or int(not success)
if success:
for result in rows:
self.cmd.pprint(result.rows, result.cols)
self.cmd.logger.info(
"For debugging purposes you can send above listed information to support@crate.io")
else:
tmpl = 'Crate {version} does not support the cluster "sysinfo" command'
self.cmd.logger.warn(tmpl
.format(version=self.cmd.connection.lowest_server_version)) | [
"def",
"execute",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cmd",
".",
"is_conn_available",
"(",
")",
":",
"return",
"if",
"self",
".",
"cmd",
".",
"connection",
".",
"lowest_server_version",
">=",
"SYSINFO_MIN_VERSION",
":",
"success",
",",
"rows",
"=",
"self",
".",
"_sys_info",
"(",
")",
"self",
".",
"cmd",
".",
"exit_code",
"=",
"self",
".",
"cmd",
".",
"exit_code",
"or",
"int",
"(",
"not",
"success",
")",
"if",
"success",
":",
"for",
"result",
"in",
"rows",
":",
"self",
".",
"cmd",
".",
"pprint",
"(",
"result",
".",
"rows",
",",
"result",
".",
"cols",
")",
"self",
".",
"cmd",
".",
"logger",
".",
"info",
"(",
"\"For debugging purposes you can send above listed information to support@crate.io\"",
")",
"else",
":",
"tmpl",
"=",
"'Crate {version} does not support the cluster \"sysinfo\" command'",
"self",
".",
"cmd",
".",
"logger",
".",
"warn",
"(",
"tmpl",
".",
"format",
"(",
"version",
"=",
"self",
".",
"cmd",
".",
"connection",
".",
"lowest_server_version",
")",
")"
] | print system and cluster info | [
"print",
"system",
"and",
"cluster",
"info"
] | 32d3ddc78fd2f7848ed2b99d9cd8889e322528d9 | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/sysinfo.py#L72-L87 | train | 235,256 |
crate/crash | src/crate/crash/config.py | Configuration.bwc_bool_transform_from | def bwc_bool_transform_from(cls, x):
"""
Read boolean values from old config files correctly
and interpret 'True' and 'False' as correct booleans.
"""
if x.lower() == 'true':
return True
elif x.lower() == 'false':
return False
return bool(int(x)) | python | def bwc_bool_transform_from(cls, x):
"""
Read boolean values from old config files correctly
and interpret 'True' and 'False' as correct booleans.
"""
if x.lower() == 'true':
return True
elif x.lower() == 'false':
return False
return bool(int(x)) | [
"def",
"bwc_bool_transform_from",
"(",
"cls",
",",
"x",
")",
":",
"if",
"x",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"return",
"True",
"elif",
"x",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"return",
"False",
"return",
"bool",
"(",
"int",
"(",
"x",
")",
")"
] | Read boolean values from old config files correctly
and interpret 'True' and 'False' as correct booleans. | [
"Read",
"boolean",
"values",
"from",
"old",
"config",
"files",
"correctly",
"and",
"interpret",
"True",
"and",
"False",
"as",
"correct",
"booleans",
"."
] | 32d3ddc78fd2f7848ed2b99d9cd8889e322528d9 | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/config.py#L44-L53 | train | 235,257 |
crate/crash | src/crate/crash/outputs.py | _transform_field | def _transform_field(field):
"""transform field for displaying"""
if isinstance(field, bool):
return TRUE if field else FALSE
elif isinstance(field, (list, dict)):
return json.dumps(field, sort_keys=True, ensure_ascii=False)
else:
return field | python | def _transform_field(field):
"""transform field for displaying"""
if isinstance(field, bool):
return TRUE if field else FALSE
elif isinstance(field, (list, dict)):
return json.dumps(field, sort_keys=True, ensure_ascii=False)
else:
return field | [
"def",
"_transform_field",
"(",
"field",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"bool",
")",
":",
"return",
"TRUE",
"if",
"field",
"else",
"FALSE",
"elif",
"isinstance",
"(",
"field",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"field",
",",
"sort_keys",
"=",
"True",
",",
"ensure_ascii",
"=",
"False",
")",
"else",
":",
"return",
"field"
] | transform field for displaying | [
"transform",
"field",
"for",
"displaying"
] | 32d3ddc78fd2f7848ed2b99d9cd8889e322528d9 | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/outputs.py#L42-L49 | train | 235,258 |
supermihi/pytaglib | src/pyprinttags.py | script | def script():
"""Run the command-line script."""
parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.")
parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true")
parser.add_argument("file", nargs="+", help="file(s) to print tags of")
args = parser.parse_args()
for filename in args.file:
if isinstance(filename, bytes):
filename = filename.decode(sys.getfilesystemencoding())
line = "TAGS OF '{0}'".format(os.path.basename(filename))
print("*" * len(line))
print(line)
print("*" * len(line))
audioFile = taglib.File(filename)
tags = audioFile.tags
if len(tags) > 0:
maxKeyLen = max(len(key) for key in tags.keys())
for key, values in tags.items():
for value in values:
print(('{0:' + str(maxKeyLen) + '} = {1}').format(key, value))
if len(audioFile.unsupported) > 0:
print('Unsupported tag elements: ' + "; ".join(audioFile.unsupported))
if sys.version_info[0] == 2:
inputFunction = raw_input
else:
inputFunction = input
if not args.batch and inputFunction("remove unsupported properties? [yN] ").lower() in ["y", "yes"]:
audioFile.removeUnsupportedProperties(audioFile.unsupported)
audioFile.save() | python | def script():
"""Run the command-line script."""
parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.")
parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true")
parser.add_argument("file", nargs="+", help="file(s) to print tags of")
args = parser.parse_args()
for filename in args.file:
if isinstance(filename, bytes):
filename = filename.decode(sys.getfilesystemencoding())
line = "TAGS OF '{0}'".format(os.path.basename(filename))
print("*" * len(line))
print(line)
print("*" * len(line))
audioFile = taglib.File(filename)
tags = audioFile.tags
if len(tags) > 0:
maxKeyLen = max(len(key) for key in tags.keys())
for key, values in tags.items():
for value in values:
print(('{0:' + str(maxKeyLen) + '} = {1}').format(key, value))
if len(audioFile.unsupported) > 0:
print('Unsupported tag elements: ' + "; ".join(audioFile.unsupported))
if sys.version_info[0] == 2:
inputFunction = raw_input
else:
inputFunction = input
if not args.batch and inputFunction("remove unsupported properties? [yN] ").lower() in ["y", "yes"]:
audioFile.removeUnsupportedProperties(audioFile.unsupported)
audioFile.save() | [
"def",
"script",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Print all textual tags of one or more audio files.\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-b\"",
",",
"\"--batch\"",
",",
"help",
"=",
"\"disable user interaction\"",
",",
"action",
"=",
"\"store_true\"",
")",
"parser",
".",
"add_argument",
"(",
"\"file\"",
",",
"nargs",
"=",
"\"+\"",
",",
"help",
"=",
"\"file(s) to print tags of\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"for",
"filename",
"in",
"args",
".",
"file",
":",
"if",
"isinstance",
"(",
"filename",
",",
"bytes",
")",
":",
"filename",
"=",
"filename",
".",
"decode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
"line",
"=",
"\"TAGS OF '{0}'\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
")",
"print",
"(",
"\"*\"",
"*",
"len",
"(",
"line",
")",
")",
"print",
"(",
"line",
")",
"print",
"(",
"\"*\"",
"*",
"len",
"(",
"line",
")",
")",
"audioFile",
"=",
"taglib",
".",
"File",
"(",
"filename",
")",
"tags",
"=",
"audioFile",
".",
"tags",
"if",
"len",
"(",
"tags",
")",
">",
"0",
":",
"maxKeyLen",
"=",
"max",
"(",
"len",
"(",
"key",
")",
"for",
"key",
"in",
"tags",
".",
"keys",
"(",
")",
")",
"for",
"key",
",",
"values",
"in",
"tags",
".",
"items",
"(",
")",
":",
"for",
"value",
"in",
"values",
":",
"print",
"(",
"(",
"'{0:'",
"+",
"str",
"(",
"maxKeyLen",
")",
"+",
"'} = {1}'",
")",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"if",
"len",
"(",
"audioFile",
".",
"unsupported",
")",
">",
"0",
":",
"print",
"(",
"'Unsupported tag elements: '",
"+",
"\"; \"",
".",
"join",
"(",
"audioFile",
".",
"unsupported",
")",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"inputFunction",
"=",
"raw_input",
"else",
":",
"inputFunction",
"=",
"input",
"if",
"not",
"args",
".",
"batch",
"and",
"inputFunction",
"(",
"\"remove unsupported properties? [yN] \"",
")",
".",
"lower",
"(",
")",
"in",
"[",
"\"y\"",
",",
"\"yes\"",
"]",
":",
"audioFile",
".",
"removeUnsupportedProperties",
"(",
"audioFile",
".",
"unsupported",
")",
"audioFile",
".",
"save",
"(",
")"
] | Run the command-line script. | [
"Run",
"the",
"command",
"-",
"line",
"script",
"."
] | 719224d4fdfee09925b865335f2af510ccdcad58 | https://github.com/supermihi/pytaglib/blob/719224d4fdfee09925b865335f2af510ccdcad58/src/pyprinttags.py#L23-L51 | train | 235,259 |
adafruit/Adafruit_CircuitPython_seesaw | adafruit_seesaw/seesaw.py | Seesaw.sw_reset | def sw_reset(self):
"""Trigger a software reset of the SeeSaw chip"""
self.write8(_STATUS_BASE, _STATUS_SWRST, 0xFF)
time.sleep(.500)
chip_id = self.read8(_STATUS_BASE, _STATUS_HW_ID)
if chip_id != _HW_ID_CODE:
raise RuntimeError("Seesaw hardware ID returned (0x{:x}) is not "
"correct! Expected 0x{:x}. Please check your wiring."
.format(chip_id, _HW_ID_CODE))
pid = self.get_version() >> 16
if pid == _CRICKIT_PID:
from adafruit_seesaw.crickit import Crickit_Pinmap
self.pin_mapping = Crickit_Pinmap
elif pid == _ROBOHATMM1_PID:
from adafruit_seesaw.robohat import MM1_Pinmap
self.pin_mapping = MM1_Pinmap
else:
from adafruit_seesaw.samd09 import SAMD09_Pinmap
self.pin_mapping = SAMD09_Pinmap | python | def sw_reset(self):
"""Trigger a software reset of the SeeSaw chip"""
self.write8(_STATUS_BASE, _STATUS_SWRST, 0xFF)
time.sleep(.500)
chip_id = self.read8(_STATUS_BASE, _STATUS_HW_ID)
if chip_id != _HW_ID_CODE:
raise RuntimeError("Seesaw hardware ID returned (0x{:x}) is not "
"correct! Expected 0x{:x}. Please check your wiring."
.format(chip_id, _HW_ID_CODE))
pid = self.get_version() >> 16
if pid == _CRICKIT_PID:
from adafruit_seesaw.crickit import Crickit_Pinmap
self.pin_mapping = Crickit_Pinmap
elif pid == _ROBOHATMM1_PID:
from adafruit_seesaw.robohat import MM1_Pinmap
self.pin_mapping = MM1_Pinmap
else:
from adafruit_seesaw.samd09 import SAMD09_Pinmap
self.pin_mapping = SAMD09_Pinmap | [
"def",
"sw_reset",
"(",
"self",
")",
":",
"self",
".",
"write8",
"(",
"_STATUS_BASE",
",",
"_STATUS_SWRST",
",",
"0xFF",
")",
"time",
".",
"sleep",
"(",
".500",
")",
"chip_id",
"=",
"self",
".",
"read8",
"(",
"_STATUS_BASE",
",",
"_STATUS_HW_ID",
")",
"if",
"chip_id",
"!=",
"_HW_ID_CODE",
":",
"raise",
"RuntimeError",
"(",
"\"Seesaw hardware ID returned (0x{:x}) is not \"",
"\"correct! Expected 0x{:x}. Please check your wiring.\"",
".",
"format",
"(",
"chip_id",
",",
"_HW_ID_CODE",
")",
")",
"pid",
"=",
"self",
".",
"get_version",
"(",
")",
">>",
"16",
"if",
"pid",
"==",
"_CRICKIT_PID",
":",
"from",
"adafruit_seesaw",
".",
"crickit",
"import",
"Crickit_Pinmap",
"self",
".",
"pin_mapping",
"=",
"Crickit_Pinmap",
"elif",
"pid",
"==",
"_ROBOHATMM1_PID",
":",
"from",
"adafruit_seesaw",
".",
"robohat",
"import",
"MM1_Pinmap",
"self",
".",
"pin_mapping",
"=",
"MM1_Pinmap",
"else",
":",
"from",
"adafruit_seesaw",
".",
"samd09",
"import",
"SAMD09_Pinmap",
"self",
".",
"pin_mapping",
"=",
"SAMD09_Pinmap"
] | Trigger a software reset of the SeeSaw chip | [
"Trigger",
"a",
"software",
"reset",
"of",
"the",
"SeeSaw",
"chip"
] | 3f55058dbdfcfde8cb5ce8708c0a37aacde9b313 | https://github.com/adafruit/Adafruit_CircuitPython_seesaw/blob/3f55058dbdfcfde8cb5ce8708c0a37aacde9b313/adafruit_seesaw/seesaw.py#L144-L165 | train | 235,260 |
lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_default_cache_file_path | def _get_default_cache_file_path(self):
"""
Returns default cache file path
:return: default cache file path (to data directory)
:rtype: str
"""
default_list_path = os.path.join(
self._get_default_cache_dir(), self._CACHE_FILE_NAME)
if not os.access(default_list_path, os.F_OK):
raise CacheFileError(
"Default cache file does not exist "
"'{}'!".format(default_list_path)
)
return default_list_path | python | def _get_default_cache_file_path(self):
"""
Returns default cache file path
:return: default cache file path (to data directory)
:rtype: str
"""
default_list_path = os.path.join(
self._get_default_cache_dir(), self._CACHE_FILE_NAME)
if not os.access(default_list_path, os.F_OK):
raise CacheFileError(
"Default cache file does not exist "
"'{}'!".format(default_list_path)
)
return default_list_path | [
"def",
"_get_default_cache_file_path",
"(",
"self",
")",
":",
"default_list_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_get_default_cache_dir",
"(",
")",
",",
"self",
".",
"_CACHE_FILE_NAME",
")",
"if",
"not",
"os",
".",
"access",
"(",
"default_list_path",
",",
"os",
".",
"F_OK",
")",
":",
"raise",
"CacheFileError",
"(",
"\"Default cache file does not exist \"",
"\"'{}'!\"",
".",
"format",
"(",
"default_list_path",
")",
")",
"return",
"default_list_path"
] | Returns default cache file path
:return: default cache file path (to data directory)
:rtype: str | [
"Returns",
"default",
"cache",
"file",
"path"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L77-L94 | train | 235,261 |
lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_writable_cache_dir | def _get_writable_cache_dir(self):
"""
Get writable cache directory with fallback to user's cache directory
and global temp directory
:raises: CacheFileError when cached directory is not writable for user
:return: path to cache directory
:rtype: str
"""
dir_path_data = self._get_default_cache_dir()
if os.access(dir_path_data, os.W_OK):
self._default_cache_file = True
return dir_path_data
dir_path_user = user_cache_dir(self._URLEXTRACT_NAME)
if not os.path.exists(dir_path_user):
os.makedirs(dir_path_user, exist_ok=True)
if os.access(dir_path_user, os.W_OK):
return dir_path_user
dir_path_temp = tempfile.gettempdir()
if os.access(dir_path_temp, os.W_OK):
return dir_path_temp
raise CacheFileError("Cache directories are not writable.") | python | def _get_writable_cache_dir(self):
"""
Get writable cache directory with fallback to user's cache directory
and global temp directory
:raises: CacheFileError when cached directory is not writable for user
:return: path to cache directory
:rtype: str
"""
dir_path_data = self._get_default_cache_dir()
if os.access(dir_path_data, os.W_OK):
self._default_cache_file = True
return dir_path_data
dir_path_user = user_cache_dir(self._URLEXTRACT_NAME)
if not os.path.exists(dir_path_user):
os.makedirs(dir_path_user, exist_ok=True)
if os.access(dir_path_user, os.W_OK):
return dir_path_user
dir_path_temp = tempfile.gettempdir()
if os.access(dir_path_temp, os.W_OK):
return dir_path_temp
raise CacheFileError("Cache directories are not writable.") | [
"def",
"_get_writable_cache_dir",
"(",
"self",
")",
":",
"dir_path_data",
"=",
"self",
".",
"_get_default_cache_dir",
"(",
")",
"if",
"os",
".",
"access",
"(",
"dir_path_data",
",",
"os",
".",
"W_OK",
")",
":",
"self",
".",
"_default_cache_file",
"=",
"True",
"return",
"dir_path_data",
"dir_path_user",
"=",
"user_cache_dir",
"(",
"self",
".",
"_URLEXTRACT_NAME",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_path_user",
")",
":",
"os",
".",
"makedirs",
"(",
"dir_path_user",
",",
"exist_ok",
"=",
"True",
")",
"if",
"os",
".",
"access",
"(",
"dir_path_user",
",",
"os",
".",
"W_OK",
")",
":",
"return",
"dir_path_user",
"dir_path_temp",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"if",
"os",
".",
"access",
"(",
"dir_path_temp",
",",
"os",
".",
"W_OK",
")",
":",
"return",
"dir_path_temp",
"raise",
"CacheFileError",
"(",
"\"Cache directories are not writable.\"",
")"
] | Get writable cache directory with fallback to user's cache directory
and global temp directory
:raises: CacheFileError when cached directory is not writable for user
:return: path to cache directory
:rtype: str | [
"Get",
"writable",
"cache",
"directory",
"with",
"fallback",
"to",
"user",
"s",
"cache",
"directory",
"and",
"global",
"temp",
"directory"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L96-L122 | train | 235,262 |
lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_cache_file_path | def _get_cache_file_path(self, cache_dir=None):
"""
Get path for cache file
:param str cache_dir: base path for TLD cache, defaults to data dir
:raises: CacheFileError when cached directory is not writable for user
:return: Full path to cached file with TLDs
:rtype: str
"""
if cache_dir is None:
# Tries to get writable cache dir with fallback to users data dir
# and temp directory
cache_dir = self._get_writable_cache_dir()
else:
if not os.access(cache_dir, os.W_OK):
raise CacheFileError("None of cache directories is writable.")
# get directory for cached file
return os.path.join(cache_dir, self._CACHE_FILE_NAME) | python | def _get_cache_file_path(self, cache_dir=None):
"""
Get path for cache file
:param str cache_dir: base path for TLD cache, defaults to data dir
:raises: CacheFileError when cached directory is not writable for user
:return: Full path to cached file with TLDs
:rtype: str
"""
if cache_dir is None:
# Tries to get writable cache dir with fallback to users data dir
# and temp directory
cache_dir = self._get_writable_cache_dir()
else:
if not os.access(cache_dir, os.W_OK):
raise CacheFileError("None of cache directories is writable.")
# get directory for cached file
return os.path.join(cache_dir, self._CACHE_FILE_NAME) | [
"def",
"_get_cache_file_path",
"(",
"self",
",",
"cache_dir",
"=",
"None",
")",
":",
"if",
"cache_dir",
"is",
"None",
":",
"# Tries to get writable cache dir with fallback to users data dir",
"# and temp directory",
"cache_dir",
"=",
"self",
".",
"_get_writable_cache_dir",
"(",
")",
"else",
":",
"if",
"not",
"os",
".",
"access",
"(",
"cache_dir",
",",
"os",
".",
"W_OK",
")",
":",
"raise",
"CacheFileError",
"(",
"\"None of cache directories is writable.\"",
")",
"# get directory for cached file",
"return",
"os",
".",
"path",
".",
"join",
"(",
"cache_dir",
",",
"self",
".",
"_CACHE_FILE_NAME",
")"
] | Get path for cache file
:param str cache_dir: base path for TLD cache, defaults to data dir
:raises: CacheFileError when cached directory is not writable for user
:return: Full path to cached file with TLDs
:rtype: str | [
"Get",
"path",
"for",
"cache",
"file"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L124-L142 | train | 235,263 |
lipoja/URLExtract | urlextract/cachefile.py | CacheFile._load_cached_tlds | def _load_cached_tlds(self):
"""
Loads TLDs from cached file to set.
:return: Set of current TLDs
:rtype: set
"""
# check if cached file is readable
if not os.access(self._tld_list_path, os.R_OK):
self._logger.error("Cached file is not readable for current "
"user. ({})".format(self._tld_list_path))
raise CacheFileError(
"Cached file is not readable for current user."
)
set_of_tlds = set()
with open(self._tld_list_path, 'r') as f_cache_tld:
for line in f_cache_tld:
tld = line.strip().lower()
# skip empty lines
if not tld:
continue
# skip comments
if tld[0] == '#':
continue
set_of_tlds.add("." + tld)
set_of_tlds.add("." + idna.decode(tld))
return set_of_tlds | python | def _load_cached_tlds(self):
"""
Loads TLDs from cached file to set.
:return: Set of current TLDs
:rtype: set
"""
# check if cached file is readable
if not os.access(self._tld_list_path, os.R_OK):
self._logger.error("Cached file is not readable for current "
"user. ({})".format(self._tld_list_path))
raise CacheFileError(
"Cached file is not readable for current user."
)
set_of_tlds = set()
with open(self._tld_list_path, 'r') as f_cache_tld:
for line in f_cache_tld:
tld = line.strip().lower()
# skip empty lines
if not tld:
continue
# skip comments
if tld[0] == '#':
continue
set_of_tlds.add("." + tld)
set_of_tlds.add("." + idna.decode(tld))
return set_of_tlds | [
"def",
"_load_cached_tlds",
"(",
"self",
")",
":",
"# check if cached file is readable",
"if",
"not",
"os",
".",
"access",
"(",
"self",
".",
"_tld_list_path",
",",
"os",
".",
"R_OK",
")",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"\"Cached file is not readable for current \"",
"\"user. ({})\"",
".",
"format",
"(",
"self",
".",
"_tld_list_path",
")",
")",
"raise",
"CacheFileError",
"(",
"\"Cached file is not readable for current user.\"",
")",
"set_of_tlds",
"=",
"set",
"(",
")",
"with",
"open",
"(",
"self",
".",
"_tld_list_path",
",",
"'r'",
")",
"as",
"f_cache_tld",
":",
"for",
"line",
"in",
"f_cache_tld",
":",
"tld",
"=",
"line",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"# skip empty lines",
"if",
"not",
"tld",
":",
"continue",
"# skip comments",
"if",
"tld",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"set_of_tlds",
".",
"add",
"(",
"\".\"",
"+",
"tld",
")",
"set_of_tlds",
".",
"add",
"(",
"\".\"",
"+",
"idna",
".",
"decode",
"(",
"tld",
")",
")",
"return",
"set_of_tlds"
] | Loads TLDs from cached file to set.
:return: Set of current TLDs
:rtype: set | [
"Loads",
"TLDs",
"from",
"cached",
"file",
"to",
"set",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L190-L220 | train | 235,264 |
lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_last_cachefile_modification | def _get_last_cachefile_modification(self):
"""
Get last modification of cache file with TLDs.
:return: Date and time of last modification or
None when file does not exist
:rtype: datetime|None
"""
try:
mtime = os.path.getmtime(self._tld_list_path)
except OSError:
return None
return datetime.fromtimestamp(mtime) | python | def _get_last_cachefile_modification(self):
"""
Get last modification of cache file with TLDs.
:return: Date and time of last modification or
None when file does not exist
:rtype: datetime|None
"""
try:
mtime = os.path.getmtime(self._tld_list_path)
except OSError:
return None
return datetime.fromtimestamp(mtime) | [
"def",
"_get_last_cachefile_modification",
"(",
"self",
")",
":",
"try",
":",
"mtime",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"_tld_list_path",
")",
"except",
"OSError",
":",
"return",
"None",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"mtime",
")"
] | Get last modification of cache file with TLDs.
:return: Date and time of last modification or
None when file does not exist
:rtype: datetime|None | [
"Get",
"last",
"modification",
"of",
"cache",
"file",
"with",
"TLDs",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L222-L236 | train | 235,265 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._get_after_tld_chars | def _get_after_tld_chars(self):
"""
Initialize after tld characters
"""
after_tld_chars = set(string.whitespace)
after_tld_chars |= {'/', '\"', '\'', '<', '>', '?', ':', '.', ','}
# get left enclosure characters
_, right_enclosure = zip(*self._enclosure)
# add right enclosure characters to be valid after TLD
# for correct parsing of URL e.g. (example.com)
after_tld_chars |= set(right_enclosure)
return after_tld_chars | python | def _get_after_tld_chars(self):
"""
Initialize after tld characters
"""
after_tld_chars = set(string.whitespace)
after_tld_chars |= {'/', '\"', '\'', '<', '>', '?', ':', '.', ','}
# get left enclosure characters
_, right_enclosure = zip(*self._enclosure)
# add right enclosure characters to be valid after TLD
# for correct parsing of URL e.g. (example.com)
after_tld_chars |= set(right_enclosure)
return after_tld_chars | [
"def",
"_get_after_tld_chars",
"(",
"self",
")",
":",
"after_tld_chars",
"=",
"set",
"(",
"string",
".",
"whitespace",
")",
"after_tld_chars",
"|=",
"{",
"'/'",
",",
"'\\\"'",
",",
"'\\''",
",",
"'<'",
",",
"'>'",
",",
"'?'",
",",
"':'",
",",
"'.'",
",",
"','",
"}",
"# get left enclosure characters",
"_",
",",
"right_enclosure",
"=",
"zip",
"(",
"*",
"self",
".",
"_enclosure",
")",
"# add right enclosure characters to be valid after TLD",
"# for correct parsing of URL e.g. (example.com)",
"after_tld_chars",
"|=",
"set",
"(",
"right_enclosure",
")",
"return",
"after_tld_chars"
] | Initialize after tld characters | [
"Initialize",
"after",
"tld",
"characters"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L91-L103 | train | 235,266 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.update_when_older | def update_when_older(self, days):
"""
Update TLD list cache file if the list is older than
number of days given in parameter `days` or if does not exist.
:param int days: number of days from last change
:return: True if update was successful, False otherwise
:rtype: bool
"""
last_cache = self._get_last_cachefile_modification()
if last_cache is None:
return self.update()
time_to_update = last_cache + timedelta(days=days)
if datetime.now() >= time_to_update:
return self.update()
return True | python | def update_when_older(self, days):
"""
Update TLD list cache file if the list is older than
number of days given in parameter `days` or if does not exist.
:param int days: number of days from last change
:return: True if update was successful, False otherwise
:rtype: bool
"""
last_cache = self._get_last_cachefile_modification()
if last_cache is None:
return self.update()
time_to_update = last_cache + timedelta(days=days)
if datetime.now() >= time_to_update:
return self.update()
return True | [
"def",
"update_when_older",
"(",
"self",
",",
"days",
")",
":",
"last_cache",
"=",
"self",
".",
"_get_last_cachefile_modification",
"(",
")",
"if",
"last_cache",
"is",
"None",
":",
"return",
"self",
".",
"update",
"(",
")",
"time_to_update",
"=",
"last_cache",
"+",
"timedelta",
"(",
"days",
"=",
"days",
")",
"if",
"datetime",
".",
"now",
"(",
")",
">=",
"time_to_update",
":",
"return",
"self",
".",
"update",
"(",
")",
"return",
"True"
] | Update TLD list cache file if the list is older than
number of days given in parameter `days` or if does not exist.
:param int days: number of days from last change
:return: True if update was successful, False otherwise
:rtype: bool | [
"Update",
"TLD",
"list",
"cache",
"file",
"if",
"the",
"list",
"is",
"older",
"than",
"number",
"of",
"days",
"given",
"in",
"parameter",
"days",
"or",
"if",
"does",
"not",
"exist",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L129-L148 | train | 235,267 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.set_stop_chars | def set_stop_chars(self, stop_chars):
"""
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
"""
warnings.warn("Method set_stop_chars is deprecated, "
"use `set_stop_chars_left` or "
"`set_stop_chars_right` instead", DeprecationWarning)
self._stop_chars = set(stop_chars)
self._stop_chars_left = self._stop_chars
self._stop_chars_right = self._stop_chars | python | def set_stop_chars(self, stop_chars):
"""
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
"""
warnings.warn("Method set_stop_chars is deprecated, "
"use `set_stop_chars_left` or "
"`set_stop_chars_right` instead", DeprecationWarning)
self._stop_chars = set(stop_chars)
self._stop_chars_left = self._stop_chars
self._stop_chars_right = self._stop_chars | [
"def",
"set_stop_chars",
"(",
"self",
",",
"stop_chars",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Method set_stop_chars is deprecated, \"",
"\"use `set_stop_chars_left` or \"",
"\"`set_stop_chars_right` instead\"",
",",
"DeprecationWarning",
")",
"self",
".",
"_stop_chars",
"=",
"set",
"(",
"stop_chars",
")",
"self",
".",
"_stop_chars_left",
"=",
"self",
".",
"_stop_chars",
"self",
".",
"_stop_chars_right",
"=",
"self",
".",
"_stop_chars"
] | Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters | [
"Set",
"stop",
"characters",
"used",
"when",
"determining",
"end",
"of",
"URL",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L196-L212 | train | 235,268 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.set_stop_chars_left | def set_stop_chars_left(self, stop_chars):
"""
Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError
"""
if not isinstance(stop_chars, set):
raise TypeError("stop_chars should be type set "
"but {} was given".format(type(stop_chars)))
self._stop_chars_left = stop_chars
self._stop_chars = self._stop_chars_left | self._stop_chars_right | python | def set_stop_chars_left(self, stop_chars):
"""
Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError
"""
if not isinstance(stop_chars, set):
raise TypeError("stop_chars should be type set "
"but {} was given".format(type(stop_chars)))
self._stop_chars_left = stop_chars
self._stop_chars = self._stop_chars_left | self._stop_chars_right | [
"def",
"set_stop_chars_left",
"(",
"self",
",",
"stop_chars",
")",
":",
"if",
"not",
"isinstance",
"(",
"stop_chars",
",",
"set",
")",
":",
"raise",
"TypeError",
"(",
"\"stop_chars should be type set \"",
"\"but {} was given\"",
".",
"format",
"(",
"type",
"(",
"stop_chars",
")",
")",
")",
"self",
".",
"_stop_chars_left",
"=",
"stop_chars",
"self",
".",
"_stop_chars",
"=",
"self",
".",
"_stop_chars_left",
"|",
"self",
".",
"_stop_chars_right"
] | Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError | [
"Set",
"stop",
"characters",
"for",
"text",
"on",
"left",
"from",
"TLD",
".",
"Stop",
"characters",
"are",
"used",
"when",
"determining",
"end",
"of",
"URL",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L223-L236 | train | 235,269 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.add_enclosure | def add_enclosure(self, left_char, right_char):
"""
Add new enclosure pair of characters. That and should be removed
when their presence is detected at beginning and end of found URL
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
self._enclosure.add((left_char, right_char))
self._after_tld_chars = self._get_after_tld_chars() | python | def add_enclosure(self, left_char, right_char):
"""
Add new enclosure pair of characters. That and should be removed
when their presence is detected at beginning and end of found URL
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
self._enclosure.add((left_char, right_char))
self._after_tld_chars = self._get_after_tld_chars() | [
"def",
"add_enclosure",
"(",
"self",
",",
"left_char",
",",
"right_char",
")",
":",
"assert",
"len",
"(",
"left_char",
")",
"==",
"1",
",",
"\"Parameter left_char must be character not string\"",
"assert",
"len",
"(",
"right_char",
")",
"==",
"1",
",",
"\"Parameter right_char must be character not string\"",
"self",
".",
"_enclosure",
".",
"add",
"(",
"(",
"left_char",
",",
"right_char",
")",
")",
"self",
".",
"_after_tld_chars",
"=",
"self",
".",
"_get_after_tld_chars",
"(",
")"
] | Add new enclosure pair of characters. That and should be removed
when their presence is detected at beginning and end of found URL
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")" | [
"Add",
"new",
"enclosure",
"pair",
"of",
"characters",
".",
"That",
"and",
"should",
"be",
"removed",
"when",
"their",
"presence",
"is",
"detected",
"at",
"beginning",
"and",
"end",
"of",
"found",
"URL"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L272-L286 | train | 235,270 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.remove_enclosure | def remove_enclosure(self, left_char, right_char):
"""
Remove enclosure pair from set of enclosures.
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
rm_enclosure = (left_char, right_char)
if rm_enclosure in self._enclosure:
self._enclosure.remove(rm_enclosure)
self._after_tld_chars = self._get_after_tld_chars() | python | def remove_enclosure(self, left_char, right_char):
"""
Remove enclosure pair from set of enclosures.
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
rm_enclosure = (left_char, right_char)
if rm_enclosure in self._enclosure:
self._enclosure.remove(rm_enclosure)
self._after_tld_chars = self._get_after_tld_chars() | [
"def",
"remove_enclosure",
"(",
"self",
",",
"left_char",
",",
"right_char",
")",
":",
"assert",
"len",
"(",
"left_char",
")",
"==",
"1",
",",
"\"Parameter left_char must be character not string\"",
"assert",
"len",
"(",
"right_char",
")",
"==",
"1",
",",
"\"Parameter right_char must be character not string\"",
"rm_enclosure",
"=",
"(",
"left_char",
",",
"right_char",
")",
"if",
"rm_enclosure",
"in",
"self",
".",
"_enclosure",
":",
"self",
".",
"_enclosure",
".",
"remove",
"(",
"rm_enclosure",
")",
"self",
".",
"_after_tld_chars",
"=",
"self",
".",
"_get_after_tld_chars",
"(",
")"
] | Remove enclosure pair from set of enclosures.
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")" | [
"Remove",
"enclosure",
"pair",
"from",
"set",
"of",
"enclosures",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L288-L303 | train | 235,271 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._complete_url | def _complete_url(self, text, tld_pos, tld):
"""
Expand string in both sides to match whole URL.
:param str text: text where we want to find URL
:param int tld_pos: position of TLD
:param str tld: matched TLD which should be in text
:return: returns URL
:rtype: str
"""
left_ok = True
right_ok = True
max_len = len(text) - 1
end_pos = tld_pos
start_pos = tld_pos
while left_ok or right_ok:
if left_ok:
if start_pos <= 0:
left_ok = False
else:
if text[start_pos - 1] not in self._stop_chars_left:
start_pos -= 1
else:
left_ok = False
if right_ok:
if end_pos >= max_len:
right_ok = False
else:
if text[end_pos + 1] not in self._stop_chars_right:
end_pos += 1
else:
right_ok = False
complete_url = text[start_pos:end_pos + 1].lstrip('/')
# remove last character from url
# when it is allowed character right after TLD (e.g. dot, comma)
temp_tlds = {tld + c for c in self._after_tld_chars}
# get only dot+tld+one_char and compare
if complete_url[len(complete_url)-len(tld)-1:] in temp_tlds:
complete_url = complete_url[:-1]
complete_url = self._split_markdown(complete_url, tld_pos-start_pos)
complete_url = self._remove_enclosure_from_url(
complete_url, tld_pos-start_pos, tld)
if not self._is_domain_valid(complete_url, tld):
return ""
return complete_url | python | def _complete_url(self, text, tld_pos, tld):
"""
Expand string in both sides to match whole URL.
:param str text: text where we want to find URL
:param int tld_pos: position of TLD
:param str tld: matched TLD which should be in text
:return: returns URL
:rtype: str
"""
left_ok = True
right_ok = True
max_len = len(text) - 1
end_pos = tld_pos
start_pos = tld_pos
while left_ok or right_ok:
if left_ok:
if start_pos <= 0:
left_ok = False
else:
if text[start_pos - 1] not in self._stop_chars_left:
start_pos -= 1
else:
left_ok = False
if right_ok:
if end_pos >= max_len:
right_ok = False
else:
if text[end_pos + 1] not in self._stop_chars_right:
end_pos += 1
else:
right_ok = False
complete_url = text[start_pos:end_pos + 1].lstrip('/')
# remove last character from url
# when it is allowed character right after TLD (e.g. dot, comma)
temp_tlds = {tld + c for c in self._after_tld_chars}
# get only dot+tld+one_char and compare
if complete_url[len(complete_url)-len(tld)-1:] in temp_tlds:
complete_url = complete_url[:-1]
complete_url = self._split_markdown(complete_url, tld_pos-start_pos)
complete_url = self._remove_enclosure_from_url(
complete_url, tld_pos-start_pos, tld)
if not self._is_domain_valid(complete_url, tld):
return ""
return complete_url | [
"def",
"_complete_url",
"(",
"self",
",",
"text",
",",
"tld_pos",
",",
"tld",
")",
":",
"left_ok",
"=",
"True",
"right_ok",
"=",
"True",
"max_len",
"=",
"len",
"(",
"text",
")",
"-",
"1",
"end_pos",
"=",
"tld_pos",
"start_pos",
"=",
"tld_pos",
"while",
"left_ok",
"or",
"right_ok",
":",
"if",
"left_ok",
":",
"if",
"start_pos",
"<=",
"0",
":",
"left_ok",
"=",
"False",
"else",
":",
"if",
"text",
"[",
"start_pos",
"-",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_left",
":",
"start_pos",
"-=",
"1",
"else",
":",
"left_ok",
"=",
"False",
"if",
"right_ok",
":",
"if",
"end_pos",
">=",
"max_len",
":",
"right_ok",
"=",
"False",
"else",
":",
"if",
"text",
"[",
"end_pos",
"+",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_right",
":",
"end_pos",
"+=",
"1",
"else",
":",
"right_ok",
"=",
"False",
"complete_url",
"=",
"text",
"[",
"start_pos",
":",
"end_pos",
"+",
"1",
"]",
".",
"lstrip",
"(",
"'/'",
")",
"# remove last character from url",
"# when it is allowed character right after TLD (e.g. dot, comma)",
"temp_tlds",
"=",
"{",
"tld",
"+",
"c",
"for",
"c",
"in",
"self",
".",
"_after_tld_chars",
"}",
"# get only dot+tld+one_char and compare",
"if",
"complete_url",
"[",
"len",
"(",
"complete_url",
")",
"-",
"len",
"(",
"tld",
")",
"-",
"1",
":",
"]",
"in",
"temp_tlds",
":",
"complete_url",
"=",
"complete_url",
"[",
":",
"-",
"1",
"]",
"complete_url",
"=",
"self",
".",
"_split_markdown",
"(",
"complete_url",
",",
"tld_pos",
"-",
"start_pos",
")",
"complete_url",
"=",
"self",
".",
"_remove_enclosure_from_url",
"(",
"complete_url",
",",
"tld_pos",
"-",
"start_pos",
",",
"tld",
")",
"if",
"not",
"self",
".",
"_is_domain_valid",
"(",
"complete_url",
",",
"tld",
")",
":",
"return",
"\"\"",
"return",
"complete_url"
] | Expand string in both sides to match whole URL.
:param str text: text where we want to find URL
:param int tld_pos: position of TLD
:param str tld: matched TLD which should be in text
:return: returns URL
:rtype: str | [
"Expand",
"string",
"in",
"both",
"sides",
"to",
"match",
"whole",
"URL",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L305-L354 | train | 235,272 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._validate_tld_match | def _validate_tld_match(self, text, matched_tld, tld_pos):
"""
Validate TLD match - tells if at found position is really TLD.
:param str text: text where we want to find URLs
:param str matched_tld: matched TLD
:param int tld_pos: position of matched TLD
:return: True if match is valid, False otherwise
:rtype: bool
"""
if tld_pos > len(text):
return False
right_tld_pos = tld_pos + len(matched_tld)
if len(text) > right_tld_pos:
if text[right_tld_pos] in self._after_tld_chars:
if tld_pos > 0 and text[tld_pos - 1] \
not in self._stop_chars_left:
return True
else:
if tld_pos > 0 and text[tld_pos - 1] not in self._stop_chars_left:
return True
return False | python | def _validate_tld_match(self, text, matched_tld, tld_pos):
"""
Validate TLD match - tells if at found position is really TLD.
:param str text: text where we want to find URLs
:param str matched_tld: matched TLD
:param int tld_pos: position of matched TLD
:return: True if match is valid, False otherwise
:rtype: bool
"""
if tld_pos > len(text):
return False
right_tld_pos = tld_pos + len(matched_tld)
if len(text) > right_tld_pos:
if text[right_tld_pos] in self._after_tld_chars:
if tld_pos > 0 and text[tld_pos - 1] \
not in self._stop_chars_left:
return True
else:
if tld_pos > 0 and text[tld_pos - 1] not in self._stop_chars_left:
return True
return False | [
"def",
"_validate_tld_match",
"(",
"self",
",",
"text",
",",
"matched_tld",
",",
"tld_pos",
")",
":",
"if",
"tld_pos",
">",
"len",
"(",
"text",
")",
":",
"return",
"False",
"right_tld_pos",
"=",
"tld_pos",
"+",
"len",
"(",
"matched_tld",
")",
"if",
"len",
"(",
"text",
")",
">",
"right_tld_pos",
":",
"if",
"text",
"[",
"right_tld_pos",
"]",
"in",
"self",
".",
"_after_tld_chars",
":",
"if",
"tld_pos",
">",
"0",
"and",
"text",
"[",
"tld_pos",
"-",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_left",
":",
"return",
"True",
"else",
":",
"if",
"tld_pos",
">",
"0",
"and",
"text",
"[",
"tld_pos",
"-",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_left",
":",
"return",
"True",
"return",
"False"
] | Validate TLD match - tells if at found position is really TLD.
:param str text: text where we want to find URLs
:param str matched_tld: matched TLD
:param int tld_pos: position of matched TLD
:return: True if match is valid, False otherwise
:rtype: bool | [
"Validate",
"TLD",
"match",
"-",
"tells",
"if",
"at",
"found",
"position",
"is",
"really",
"TLD",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L356-L379 | train | 235,273 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._split_markdown | def _split_markdown(text_url, tld_pos):
"""
Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has removed enclosure
:rtype: str
"""
# Markdown url can looks like:
# [http://example.com/](http://example.com/status/210)
left_bracket_pos = text_url.find('[')
# subtract 3 because URL is never shorter than 3 characters
if left_bracket_pos > tld_pos-3:
return text_url
right_bracket_pos = text_url.find(')')
if right_bracket_pos < tld_pos:
return text_url
middle_pos = text_url.rfind("](")
if middle_pos > tld_pos:
return text_url[left_bracket_pos+1:middle_pos]
return text_url | python | def _split_markdown(text_url, tld_pos):
"""
Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has removed enclosure
:rtype: str
"""
# Markdown url can looks like:
# [http://example.com/](http://example.com/status/210)
left_bracket_pos = text_url.find('[')
# subtract 3 because URL is never shorter than 3 characters
if left_bracket_pos > tld_pos-3:
return text_url
right_bracket_pos = text_url.find(')')
if right_bracket_pos < tld_pos:
return text_url
middle_pos = text_url.rfind("](")
if middle_pos > tld_pos:
return text_url[left_bracket_pos+1:middle_pos]
return text_url | [
"def",
"_split_markdown",
"(",
"text_url",
",",
"tld_pos",
")",
":",
"# Markdown url can looks like:",
"# [http://example.com/](http://example.com/status/210)",
"left_bracket_pos",
"=",
"text_url",
".",
"find",
"(",
"'['",
")",
"# subtract 3 because URL is never shorter than 3 characters",
"if",
"left_bracket_pos",
">",
"tld_pos",
"-",
"3",
":",
"return",
"text_url",
"right_bracket_pos",
"=",
"text_url",
".",
"find",
"(",
"')'",
")",
"if",
"right_bracket_pos",
"<",
"tld_pos",
":",
"return",
"text_url",
"middle_pos",
"=",
"text_url",
".",
"rfind",
"(",
"\"](\"",
")",
"if",
"middle_pos",
">",
"tld_pos",
":",
"return",
"text_url",
"[",
"left_bracket_pos",
"+",
"1",
":",
"middle_pos",
"]",
"return",
"text_url"
] | Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has removed enclosure
:rtype: str | [
"Split",
"markdown",
"URL",
".",
"There",
"is",
"an",
"issue",
"wen",
"Markdown",
"URL",
"is",
"found",
".",
"Parsing",
"of",
"the",
"URL",
"does",
"not",
"stop",
"on",
"right",
"place",
"so",
"wrongly",
"found",
"URL",
"has",
"to",
"be",
"split",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L497-L523 | train | 235,274 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.gen_urls | def gen_urls(self, text):
"""
Creates generator over found URLs in given text.
:param str text: text where we want to find URLs
:yields: URL found in text or empty string if no found
:rtype: str
"""
tld_pos = 0
matched_tlds = self._tlds_re.findall(text)
for tld in matched_tlds:
tmp_text = text[tld_pos:]
offset = tld_pos
tld_pos = tmp_text.find(tld)
validated = self._validate_tld_match(text, tld, offset + tld_pos)
if tld_pos != -1 and validated:
tmp_url = self._complete_url(text, offset + tld_pos, tld)
if tmp_url:
yield tmp_url
# do not search for TLD in already extracted URL
tld_pos_url = tmp_url.find(tld)
# move cursor right after found TLD
tld_pos += len(tld) + offset
# move cursor after end of found URL
tld_pos += len(tmp_url[tld_pos_url+len(tld):])
continue
# move cursor right after found TLD
tld_pos += len(tld) + offset | python | def gen_urls(self, text):
"""
Creates generator over found URLs in given text.
:param str text: text where we want to find URLs
:yields: URL found in text or empty string if no found
:rtype: str
"""
tld_pos = 0
matched_tlds = self._tlds_re.findall(text)
for tld in matched_tlds:
tmp_text = text[tld_pos:]
offset = tld_pos
tld_pos = tmp_text.find(tld)
validated = self._validate_tld_match(text, tld, offset + tld_pos)
if tld_pos != -1 and validated:
tmp_url = self._complete_url(text, offset + tld_pos, tld)
if tmp_url:
yield tmp_url
# do not search for TLD in already extracted URL
tld_pos_url = tmp_url.find(tld)
# move cursor right after found TLD
tld_pos += len(tld) + offset
# move cursor after end of found URL
tld_pos += len(tmp_url[tld_pos_url+len(tld):])
continue
# move cursor right after found TLD
tld_pos += len(tld) + offset | [
"def",
"gen_urls",
"(",
"self",
",",
"text",
")",
":",
"tld_pos",
"=",
"0",
"matched_tlds",
"=",
"self",
".",
"_tlds_re",
".",
"findall",
"(",
"text",
")",
"for",
"tld",
"in",
"matched_tlds",
":",
"tmp_text",
"=",
"text",
"[",
"tld_pos",
":",
"]",
"offset",
"=",
"tld_pos",
"tld_pos",
"=",
"tmp_text",
".",
"find",
"(",
"tld",
")",
"validated",
"=",
"self",
".",
"_validate_tld_match",
"(",
"text",
",",
"tld",
",",
"offset",
"+",
"tld_pos",
")",
"if",
"tld_pos",
"!=",
"-",
"1",
"and",
"validated",
":",
"tmp_url",
"=",
"self",
".",
"_complete_url",
"(",
"text",
",",
"offset",
"+",
"tld_pos",
",",
"tld",
")",
"if",
"tmp_url",
":",
"yield",
"tmp_url",
"# do not search for TLD in already extracted URL",
"tld_pos_url",
"=",
"tmp_url",
".",
"find",
"(",
"tld",
")",
"# move cursor right after found TLD",
"tld_pos",
"+=",
"len",
"(",
"tld",
")",
"+",
"offset",
"# move cursor after end of found URL",
"tld_pos",
"+=",
"len",
"(",
"tmp_url",
"[",
"tld_pos_url",
"+",
"len",
"(",
"tld",
")",
":",
"]",
")",
"continue",
"# move cursor right after found TLD",
"tld_pos",
"+=",
"len",
"(",
"tld",
")",
"+",
"offset"
] | Creates generator over found URLs in given text.
:param str text: text where we want to find URLs
:yields: URL found in text or empty string if no found
:rtype: str | [
"Creates",
"generator",
"over",
"found",
"URLs",
"in",
"given",
"text",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L525-L555 | train | 235,275 |
lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.find_urls | def find_urls(self, text, only_unique=False):
"""
Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list
"""
urls = self.gen_urls(text)
urls = OrderedDict.fromkeys(urls) if only_unique else urls
return list(urls) | python | def find_urls(self, text, only_unique=False):
"""
Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list
"""
urls = self.gen_urls(text)
urls = OrderedDict.fromkeys(urls) if only_unique else urls
return list(urls) | [
"def",
"find_urls",
"(",
"self",
",",
"text",
",",
"only_unique",
"=",
"False",
")",
":",
"urls",
"=",
"self",
".",
"gen_urls",
"(",
"text",
")",
"urls",
"=",
"OrderedDict",
".",
"fromkeys",
"(",
"urls",
")",
"if",
"only_unique",
"else",
"urls",
"return",
"list",
"(",
"urls",
")"
] | Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list | [
"Find",
"all",
"URLs",
"in",
"given",
"text",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L557-L568 | train | 235,276 |
pinax/pinax-badges | pinax/badges/base.py | Badge.possibly_award | def possibly_award(self, **state):
"""
Will see if the user should be awarded a badge. If this badge is
asynchronous it just queues up the badge awarding.
"""
assert "user" in state
if self.async:
from .tasks import AsyncBadgeAward
state = self.freeze(**state)
AsyncBadgeAward.delay(self, state)
return
self.actually_possibly_award(**state) | python | def possibly_award(self, **state):
"""
Will see if the user should be awarded a badge. If this badge is
asynchronous it just queues up the badge awarding.
"""
assert "user" in state
if self.async:
from .tasks import AsyncBadgeAward
state = self.freeze(**state)
AsyncBadgeAward.delay(self, state)
return
self.actually_possibly_award(**state) | [
"def",
"possibly_award",
"(",
"self",
",",
"*",
"*",
"state",
")",
":",
"assert",
"\"user\"",
"in",
"state",
"if",
"self",
".",
"async",
":",
"from",
".",
"tasks",
"import",
"AsyncBadgeAward",
"state",
"=",
"self",
".",
"freeze",
"(",
"*",
"*",
"state",
")",
"AsyncBadgeAward",
".",
"delay",
"(",
"self",
",",
"state",
")",
"return",
"self",
".",
"actually_possibly_award",
"(",
"*",
"*",
"state",
")"
] | Will see if the user should be awarded a badge. If this badge is
asynchronous it just queues up the badge awarding. | [
"Will",
"see",
"if",
"the",
"user",
"should",
"be",
"awarded",
"a",
"badge",
".",
"If",
"this",
"badge",
"is",
"asynchronous",
"it",
"just",
"queues",
"up",
"the",
"badge",
"awarding",
"."
] | 0921c388088e7c7a77098dc7d0eea393b4707ce5 | https://github.com/pinax/pinax-badges/blob/0921c388088e7c7a77098dc7d0eea393b4707ce5/pinax/badges/base.py#L26-L37 | train | 235,277 |
pinax/pinax-badges | pinax/badges/base.py | Badge.actually_possibly_award | def actually_possibly_award(self, **state):
"""
Does the actual work of possibly awarding a badge.
"""
user = state["user"]
force_timestamp = state.pop("force_timestamp", None)
awarded = self.award(**state)
if awarded is None:
return
if awarded.level is None:
assert len(self.levels) == 1
awarded.level = 1
# awarded levels are 1 indexed, for conveineince
awarded = awarded.level - 1
assert awarded < len(self.levels)
if (
not self.multiple and
BadgeAward.objects.filter(user=user, slug=self.slug, level=awarded)
):
return
extra_kwargs = {}
if force_timestamp is not None:
extra_kwargs["awarded_at"] = force_timestamp
badge = BadgeAward.objects.create(
user=user,
slug=self.slug,
level=awarded,
**extra_kwargs
)
self.send_badge_messages(badge)
badge_awarded.send(sender=self, badge_award=badge) | python | def actually_possibly_award(self, **state):
"""
Does the actual work of possibly awarding a badge.
"""
user = state["user"]
force_timestamp = state.pop("force_timestamp", None)
awarded = self.award(**state)
if awarded is None:
return
if awarded.level is None:
assert len(self.levels) == 1
awarded.level = 1
# awarded levels are 1 indexed, for conveineince
awarded = awarded.level - 1
assert awarded < len(self.levels)
if (
not self.multiple and
BadgeAward.objects.filter(user=user, slug=self.slug, level=awarded)
):
return
extra_kwargs = {}
if force_timestamp is not None:
extra_kwargs["awarded_at"] = force_timestamp
badge = BadgeAward.objects.create(
user=user,
slug=self.slug,
level=awarded,
**extra_kwargs
)
self.send_badge_messages(badge)
badge_awarded.send(sender=self, badge_award=badge) | [
"def",
"actually_possibly_award",
"(",
"self",
",",
"*",
"*",
"state",
")",
":",
"user",
"=",
"state",
"[",
"\"user\"",
"]",
"force_timestamp",
"=",
"state",
".",
"pop",
"(",
"\"force_timestamp\"",
",",
"None",
")",
"awarded",
"=",
"self",
".",
"award",
"(",
"*",
"*",
"state",
")",
"if",
"awarded",
"is",
"None",
":",
"return",
"if",
"awarded",
".",
"level",
"is",
"None",
":",
"assert",
"len",
"(",
"self",
".",
"levels",
")",
"==",
"1",
"awarded",
".",
"level",
"=",
"1",
"# awarded levels are 1 indexed, for conveineince",
"awarded",
"=",
"awarded",
".",
"level",
"-",
"1",
"assert",
"awarded",
"<",
"len",
"(",
"self",
".",
"levels",
")",
"if",
"(",
"not",
"self",
".",
"multiple",
"and",
"BadgeAward",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
",",
"slug",
"=",
"self",
".",
"slug",
",",
"level",
"=",
"awarded",
")",
")",
":",
"return",
"extra_kwargs",
"=",
"{",
"}",
"if",
"force_timestamp",
"is",
"not",
"None",
":",
"extra_kwargs",
"[",
"\"awarded_at\"",
"]",
"=",
"force_timestamp",
"badge",
"=",
"BadgeAward",
".",
"objects",
".",
"create",
"(",
"user",
"=",
"user",
",",
"slug",
"=",
"self",
".",
"slug",
",",
"level",
"=",
"awarded",
",",
"*",
"*",
"extra_kwargs",
")",
"self",
".",
"send_badge_messages",
"(",
"badge",
")",
"badge_awarded",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"badge_award",
"=",
"badge",
")"
] | Does the actual work of possibly awarding a badge. | [
"Does",
"the",
"actual",
"work",
"of",
"possibly",
"awarding",
"a",
"badge",
"."
] | 0921c388088e7c7a77098dc7d0eea393b4707ce5 | https://github.com/pinax/pinax-badges/blob/0921c388088e7c7a77098dc7d0eea393b4707ce5/pinax/badges/base.py#L39-L69 | train | 235,278 |
pinax/pinax-badges | pinax/badges/base.py | Badge.send_badge_messages | def send_badge_messages(self, badge_award):
"""
If the Badge class defines a message, send it to the user who was just
awarded the badge.
"""
user_message = getattr(badge_award.badge, "user_message", None)
if callable(user_message):
message = user_message(badge_award)
else:
message = user_message
if message is not None:
badge_award.user.message_set.create(message=message) | python | def send_badge_messages(self, badge_award):
"""
If the Badge class defines a message, send it to the user who was just
awarded the badge.
"""
user_message = getattr(badge_award.badge, "user_message", None)
if callable(user_message):
message = user_message(badge_award)
else:
message = user_message
if message is not None:
badge_award.user.message_set.create(message=message) | [
"def",
"send_badge_messages",
"(",
"self",
",",
"badge_award",
")",
":",
"user_message",
"=",
"getattr",
"(",
"badge_award",
".",
"badge",
",",
"\"user_message\"",
",",
"None",
")",
"if",
"callable",
"(",
"user_message",
")",
":",
"message",
"=",
"user_message",
"(",
"badge_award",
")",
"else",
":",
"message",
"=",
"user_message",
"if",
"message",
"is",
"not",
"None",
":",
"badge_award",
".",
"user",
".",
"message_set",
".",
"create",
"(",
"message",
"=",
"message",
")"
] | If the Badge class defines a message, send it to the user who was just
awarded the badge. | [
"If",
"the",
"Badge",
"class",
"defines",
"a",
"message",
"send",
"it",
"to",
"the",
"user",
"who",
"was",
"just",
"awarded",
"the",
"badge",
"."
] | 0921c388088e7c7a77098dc7d0eea393b4707ce5 | https://github.com/pinax/pinax-badges/blob/0921c388088e7c7a77098dc7d0eea393b4707ce5/pinax/badges/base.py#L71-L82 | train | 235,279 |
JBKahn/flake8-print | flake8_print.py | PrintFinder.visit_Print | def visit_Print(self, node):
"""Only exists in python 2."""
self.prints_used[(node.lineno, node.col_offset)] = VIOLATIONS["found"][PRINT_FUNCTION_NAME] | python | def visit_Print(self, node):
"""Only exists in python 2."""
self.prints_used[(node.lineno, node.col_offset)] = VIOLATIONS["found"][PRINT_FUNCTION_NAME] | [
"def",
"visit_Print",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"prints_used",
"[",
"(",
"node",
".",
"lineno",
",",
"node",
".",
"col_offset",
")",
"]",
"=",
"VIOLATIONS",
"[",
"\"found\"",
"]",
"[",
"PRINT_FUNCTION_NAME",
"]"
] | Only exists in python 2. | [
"Only",
"exists",
"in",
"python",
"2",
"."
] | e5d3812c4c93628ed804e9ecf74c2d31780627e5 | https://github.com/JBKahn/flake8-print/blob/e5d3812c4c93628ed804e9ecf74c2d31780627e5/flake8_print.py#L30-L32 | train | 235,280 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.create_lockfile | def create_lockfile(self):
"""
Write recursive dependencies list to outfile
with hard-pinned versions.
Then fix it.
"""
process = subprocess.Popen(
self.pin_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
if process.returncode == 0:
self.fix_lockfile()
else:
logger.critical("ERROR executing %s", ' '.join(self.pin_command))
logger.critical("Exit code: %s", process.returncode)
logger.critical(stdout.decode('utf-8'))
logger.critical(stderr.decode('utf-8'))
raise RuntimeError("Failed to pip-compile {0}".format(self.infile)) | python | def create_lockfile(self):
"""
Write recursive dependencies list to outfile
with hard-pinned versions.
Then fix it.
"""
process = subprocess.Popen(
self.pin_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
if process.returncode == 0:
self.fix_lockfile()
else:
logger.critical("ERROR executing %s", ' '.join(self.pin_command))
logger.critical("Exit code: %s", process.returncode)
logger.critical(stdout.decode('utf-8'))
logger.critical(stderr.decode('utf-8'))
raise RuntimeError("Failed to pip-compile {0}".format(self.infile)) | [
"def",
"create_lockfile",
"(",
"self",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"pin_command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate",
"(",
")",
"if",
"process",
".",
"returncode",
"==",
"0",
":",
"self",
".",
"fix_lockfile",
"(",
")",
"else",
":",
"logger",
".",
"critical",
"(",
"\"ERROR executing %s\"",
",",
"' '",
".",
"join",
"(",
"self",
".",
"pin_command",
")",
")",
"logger",
".",
"critical",
"(",
"\"Exit code: %s\"",
",",
"process",
".",
"returncode",
")",
"logger",
".",
"critical",
"(",
"stdout",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"logger",
".",
"critical",
"(",
"stderr",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"raise",
"RuntimeError",
"(",
"\"Failed to pip-compile {0}\"",
".",
"format",
"(",
"self",
".",
"infile",
")",
")"
] | Write recursive dependencies list to outfile
with hard-pinned versions.
Then fix it. | [
"Write",
"recursive",
"dependencies",
"list",
"to",
"outfile",
"with",
"hard",
"-",
"pinned",
"versions",
".",
"Then",
"fix",
"it",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L31-L50 | train | 235,281 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.infile | def infile(self):
"""Path of the input file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['in_ext'])) | python | def infile(self):
"""Path of the input file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['in_ext'])) | [
"def",
"infile",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'{0}.{1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"OPTIONS",
"[",
"'in_ext'",
"]",
")",
")"
] | Path of the input file | [
"Path",
"of",
"the",
"input",
"file"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L74-L77 | train | 235,282 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.outfile | def outfile(self):
"""Path of the output file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['out_ext'])) | python | def outfile(self):
"""Path of the output file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['out_ext'])) | [
"def",
"outfile",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'{0}.{1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"OPTIONS",
"[",
"'out_ext'",
"]",
")",
")"
] | Path of the output file | [
"Path",
"of",
"the",
"output",
"file"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L80-L83 | train | 235,283 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.pin_command | def pin_command(self):
"""Compose pip-compile shell command"""
parts = [
'pip-compile',
'--no-header',
'--verbose',
'--rebuild',
'--no-index',
'--output-file', self.outfile,
self.infile,
]
if OPTIONS['upgrade']:
parts.insert(3, '--upgrade')
if self.add_hashes:
parts.insert(1, '--generate-hashes')
return parts | python | def pin_command(self):
"""Compose pip-compile shell command"""
parts = [
'pip-compile',
'--no-header',
'--verbose',
'--rebuild',
'--no-index',
'--output-file', self.outfile,
self.infile,
]
if OPTIONS['upgrade']:
parts.insert(3, '--upgrade')
if self.add_hashes:
parts.insert(1, '--generate-hashes')
return parts | [
"def",
"pin_command",
"(",
"self",
")",
":",
"parts",
"=",
"[",
"'pip-compile'",
",",
"'--no-header'",
",",
"'--verbose'",
",",
"'--rebuild'",
",",
"'--no-index'",
",",
"'--output-file'",
",",
"self",
".",
"outfile",
",",
"self",
".",
"infile",
",",
"]",
"if",
"OPTIONS",
"[",
"'upgrade'",
"]",
":",
"parts",
".",
"insert",
"(",
"3",
",",
"'--upgrade'",
")",
"if",
"self",
".",
"add_hashes",
":",
"parts",
".",
"insert",
"(",
"1",
",",
"'--generate-hashes'",
")",
"return",
"parts"
] | Compose pip-compile shell command | [
"Compose",
"pip",
"-",
"compile",
"shell",
"command"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L86-L101 | train | 235,284 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.fix_lockfile | def fix_lockfile(self):
"""Run each line of outfile through fix_pin"""
with open(self.outfile, 'rt') as fp:
lines = [
self.fix_pin(line)
for line in self.concatenated(fp)
]
with open(self.outfile, 'wt') as fp:
fp.writelines([
line + '\n'
for line in lines
if line is not None
]) | python | def fix_lockfile(self):
"""Run each line of outfile through fix_pin"""
with open(self.outfile, 'rt') as fp:
lines = [
self.fix_pin(line)
for line in self.concatenated(fp)
]
with open(self.outfile, 'wt') as fp:
fp.writelines([
line + '\n'
for line in lines
if line is not None
]) | [
"def",
"fix_lockfile",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'rt'",
")",
"as",
"fp",
":",
"lines",
"=",
"[",
"self",
".",
"fix_pin",
"(",
"line",
")",
"for",
"line",
"in",
"self",
".",
"concatenated",
"(",
"fp",
")",
"]",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'wt'",
")",
"as",
"fp",
":",
"fp",
".",
"writelines",
"(",
"[",
"line",
"+",
"'\\n'",
"for",
"line",
"in",
"lines",
"if",
"line",
"is",
"not",
"None",
"]",
")"
] | Run each line of outfile through fix_pin | [
"Run",
"each",
"line",
"of",
"outfile",
"through",
"fix_pin"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L103-L115 | train | 235,285 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.fix_pin | def fix_pin(self, line):
"""
Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set
"""
dep = Dependency(line)
if dep.valid:
if dep.package in self.ignore:
ignored_version = self.ignore[dep.package]
if ignored_version is not None:
# ignored_version can be None to disable conflict detection
if dep.version and dep.version != ignored_version:
logger.error(
"Package %s was resolved to different "
"versions in different environments: %s and %s",
dep.package, dep.version, ignored_version,
)
raise RuntimeError(
"Please add constraints for the package "
"version listed above"
)
return None
self.packages[dep.package] = dep.version
if self.forbid_post or dep.is_compatible:
# Always drop post for internal packages
dep.drop_post()
return dep.serialize()
return line.strip() | python | def fix_pin(self, line):
"""
Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set
"""
dep = Dependency(line)
if dep.valid:
if dep.package in self.ignore:
ignored_version = self.ignore[dep.package]
if ignored_version is not None:
# ignored_version can be None to disable conflict detection
if dep.version and dep.version != ignored_version:
logger.error(
"Package %s was resolved to different "
"versions in different environments: %s and %s",
dep.package, dep.version, ignored_version,
)
raise RuntimeError(
"Please add constraints for the package "
"version listed above"
)
return None
self.packages[dep.package] = dep.version
if self.forbid_post or dep.is_compatible:
# Always drop post for internal packages
dep.drop_post()
return dep.serialize()
return line.strip() | [
"def",
"fix_pin",
"(",
"self",
",",
"line",
")",
":",
"dep",
"=",
"Dependency",
"(",
"line",
")",
"if",
"dep",
".",
"valid",
":",
"if",
"dep",
".",
"package",
"in",
"self",
".",
"ignore",
":",
"ignored_version",
"=",
"self",
".",
"ignore",
"[",
"dep",
".",
"package",
"]",
"if",
"ignored_version",
"is",
"not",
"None",
":",
"# ignored_version can be None to disable conflict detection",
"if",
"dep",
".",
"version",
"and",
"dep",
".",
"version",
"!=",
"ignored_version",
":",
"logger",
".",
"error",
"(",
"\"Package %s was resolved to different \"",
"\"versions in different environments: %s and %s\"",
",",
"dep",
".",
"package",
",",
"dep",
".",
"version",
",",
"ignored_version",
",",
")",
"raise",
"RuntimeError",
"(",
"\"Please add constraints for the package \"",
"\"version listed above\"",
")",
"return",
"None",
"self",
".",
"packages",
"[",
"dep",
".",
"package",
"]",
"=",
"dep",
".",
"version",
"if",
"self",
".",
"forbid_post",
"or",
"dep",
".",
"is_compatible",
":",
"# Always drop post for internal packages",
"dep",
".",
"drop_post",
"(",
")",
"return",
"dep",
".",
"serialize",
"(",
")",
"return",
"line",
".",
"strip",
"(",
")"
] | Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set | [
"Fix",
"dependency",
"by",
"removing",
"post",
"-",
"releases",
"from",
"versions",
"and",
"loosing",
"constraints",
"on",
"internal",
"packages",
".",
"Drop",
"packages",
"from",
"ignore",
"set"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L133-L163 | train | 235,286 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.add_references | def add_references(self, other_names):
"""Add references to other_names in outfile"""
if not other_names:
# Skip on empty list
return
with open(self.outfile, 'rt') as fp:
header, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.writelines(header)
fp.writelines(
'-r {0}.{1}\n'.format(other_name, OPTIONS['out_ext'])
for other_name in sorted(other_names)
)
fp.writelines(body) | python | def add_references(self, other_names):
"""Add references to other_names in outfile"""
if not other_names:
# Skip on empty list
return
with open(self.outfile, 'rt') as fp:
header, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.writelines(header)
fp.writelines(
'-r {0}.{1}\n'.format(other_name, OPTIONS['out_ext'])
for other_name in sorted(other_names)
)
fp.writelines(body) | [
"def",
"add_references",
"(",
"self",
",",
"other_names",
")",
":",
"if",
"not",
"other_names",
":",
"# Skip on empty list",
"return",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'rt'",
")",
"as",
"fp",
":",
"header",
",",
"body",
"=",
"self",
".",
"split_header",
"(",
"fp",
")",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'wt'",
")",
"as",
"fp",
":",
"fp",
".",
"writelines",
"(",
"header",
")",
"fp",
".",
"writelines",
"(",
"'-r {0}.{1}\\n'",
".",
"format",
"(",
"other_name",
",",
"OPTIONS",
"[",
"'out_ext'",
"]",
")",
"for",
"other_name",
"in",
"sorted",
"(",
"other_names",
")",
")",
"fp",
".",
"writelines",
"(",
"body",
")"
] | Add references to other_names in outfile | [
"Add",
"references",
"to",
"other_names",
"in",
"outfile"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L165-L178 | train | 235,287 |
peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.replace_header | def replace_header(self, header_text):
"""Replace pip-compile header with custom text"""
with open(self.outfile, 'rt') as fp:
_, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.write(header_text)
fp.writelines(body) | python | def replace_header(self, header_text):
"""Replace pip-compile header with custom text"""
with open(self.outfile, 'rt') as fp:
_, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.write(header_text)
fp.writelines(body) | [
"def",
"replace_header",
"(",
"self",
",",
"header_text",
")",
":",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'rt'",
")",
"as",
"fp",
":",
"_",
",",
"body",
"=",
"self",
".",
"split_header",
"(",
"fp",
")",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'wt'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"header_text",
")",
"fp",
".",
"writelines",
"(",
"body",
")"
] | Replace pip-compile header with custom text | [
"Replace",
"pip",
"-",
"compile",
"header",
"with",
"custom",
"text"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L197-L203 | train | 235,288 |
peterdemin/pip-compile-multi | pipcompilemulti/discover.py | order_by_refs | def order_by_refs(envs):
"""
Return topologicaly sorted list of environments.
I.e. all referenced environments are placed before their references.
"""
topology = {
env['name']: set(env['refs'])
for env in envs
}
by_name = {
env['name']: env
for env in envs
}
return [
by_name[name]
for name in toposort_flatten(topology)
] | python | def order_by_refs(envs):
"""
Return topologicaly sorted list of environments.
I.e. all referenced environments are placed before their references.
"""
topology = {
env['name']: set(env['refs'])
for env in envs
}
by_name = {
env['name']: env
for env in envs
}
return [
by_name[name]
for name in toposort_flatten(topology)
] | [
"def",
"order_by_refs",
"(",
"envs",
")",
":",
"topology",
"=",
"{",
"env",
"[",
"'name'",
"]",
":",
"set",
"(",
"env",
"[",
"'refs'",
"]",
")",
"for",
"env",
"in",
"envs",
"}",
"by_name",
"=",
"{",
"env",
"[",
"'name'",
"]",
":",
"env",
"for",
"env",
"in",
"envs",
"}",
"return",
"[",
"by_name",
"[",
"name",
"]",
"for",
"name",
"in",
"toposort_flatten",
"(",
"topology",
")",
"]"
] | Return topologicaly sorted list of environments.
I.e. all referenced environments are placed before their references. | [
"Return",
"topologicaly",
"sorted",
"list",
"of",
"environments",
".",
"I",
".",
"e",
".",
"all",
"referenced",
"environments",
"are",
"placed",
"before",
"their",
"references",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/discover.py#L46-L62 | train | 235,289 |
peterdemin/pip-compile-multi | pipcompilemulti/dependency.py | Dependency.is_compatible | def is_compatible(self):
"""Check if package name is matched by compatible_patterns"""
for pattern in OPTIONS['compatible_patterns']:
if fnmatch(self.package.lower(), pattern):
return True
return False | python | def is_compatible(self):
"""Check if package name is matched by compatible_patterns"""
for pattern in OPTIONS['compatible_patterns']:
if fnmatch(self.package.lower(), pattern):
return True
return False | [
"def",
"is_compatible",
"(",
"self",
")",
":",
"for",
"pattern",
"in",
"OPTIONS",
"[",
"'compatible_patterns'",
"]",
":",
"if",
"fnmatch",
"(",
"self",
".",
"package",
".",
"lower",
"(",
")",
",",
"pattern",
")",
":",
"return",
"True",
"return",
"False"
] | Check if package name is matched by compatible_patterns | [
"Check",
"if",
"package",
"name",
"is",
"matched",
"by",
"compatible_patterns"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/dependency.py#L104-L109 | train | 235,290 |
peterdemin/pip-compile-multi | pipcompilemulti/dependency.py | Dependency.drop_post | def drop_post(self):
"""Remove .postXXXX postfix from version"""
post_index = self.version.find('.post')
if post_index >= 0:
self.version = self.version[:post_index] | python | def drop_post(self):
"""Remove .postXXXX postfix from version"""
post_index = self.version.find('.post')
if post_index >= 0:
self.version = self.version[:post_index] | [
"def",
"drop_post",
"(",
"self",
")",
":",
"post_index",
"=",
"self",
".",
"version",
".",
"find",
"(",
"'.post'",
")",
"if",
"post_index",
">=",
"0",
":",
"self",
".",
"version",
"=",
"self",
".",
"version",
"[",
":",
"post_index",
"]"
] | Remove .postXXXX postfix from version | [
"Remove",
".",
"postXXXX",
"postfix",
"from",
"version"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/dependency.py#L111-L115 | train | 235,291 |
peterdemin/pip-compile-multi | pipcompilemulti/verify.py | verify_environments | def verify_environments():
"""
For each environment verify hash comments and report failures.
If any failure occured, exit with code 1.
"""
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
)
)
success = True
for conf in env_confs:
env = Environment(name=conf['name'])
current_comment = generate_hash_comment(env.infile)
existing_comment = parse_hash_comment(env.outfile)
if current_comment == existing_comment:
logger.info("OK - %s was generated from %s.",
env.outfile, env.infile)
else:
logger.error("ERROR! %s was not regenerated after changes in %s.",
env.outfile, env.infile)
logger.error("Expecting: %s", current_comment.strip())
logger.error("Found: %s", existing_comment.strip())
success = False
return success | python | def verify_environments():
"""
For each environment verify hash comments and report failures.
If any failure occured, exit with code 1.
"""
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
)
)
success = True
for conf in env_confs:
env = Environment(name=conf['name'])
current_comment = generate_hash_comment(env.infile)
existing_comment = parse_hash_comment(env.outfile)
if current_comment == existing_comment:
logger.info("OK - %s was generated from %s.",
env.outfile, env.infile)
else:
logger.error("ERROR! %s was not regenerated after changes in %s.",
env.outfile, env.infile)
logger.error("Expecting: %s", current_comment.strip())
logger.error("Found: %s", existing_comment.strip())
success = False
return success | [
"def",
"verify_environments",
"(",
")",
":",
"env_confs",
"=",
"discover",
"(",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'*.'",
"+",
"OPTIONS",
"[",
"'in_ext'",
"]",
",",
")",
")",
"success",
"=",
"True",
"for",
"conf",
"in",
"env_confs",
":",
"env",
"=",
"Environment",
"(",
"name",
"=",
"conf",
"[",
"'name'",
"]",
")",
"current_comment",
"=",
"generate_hash_comment",
"(",
"env",
".",
"infile",
")",
"existing_comment",
"=",
"parse_hash_comment",
"(",
"env",
".",
"outfile",
")",
"if",
"current_comment",
"==",
"existing_comment",
":",
"logger",
".",
"info",
"(",
"\"OK - %s was generated from %s.\"",
",",
"env",
".",
"outfile",
",",
"env",
".",
"infile",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"ERROR! %s was not regenerated after changes in %s.\"",
",",
"env",
".",
"outfile",
",",
"env",
".",
"infile",
")",
"logger",
".",
"error",
"(",
"\"Expecting: %s\"",
",",
"current_comment",
".",
"strip",
"(",
")",
")",
"logger",
".",
"error",
"(",
"\"Found: %s\"",
",",
"existing_comment",
".",
"strip",
"(",
")",
")",
"success",
"=",
"False",
"return",
"success"
] | For each environment verify hash comments and report failures.
If any failure occured, exit with code 1. | [
"For",
"each",
"environment",
"verify",
"hash",
"comments",
"and",
"report",
"failures",
".",
"If",
"any",
"failure",
"occured",
"exit",
"with",
"code",
"1",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/verify.py#L15-L40 | train | 235,292 |
peterdemin/pip-compile-multi | pipcompilemulti/verify.py | generate_hash_comment | def generate_hash_comment(file_path):
"""
Read file with given file_path and return string of format
# SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709
which is hex representation of SHA1 file content hash
"""
with open(file_path, 'rb') as fp:
hexdigest = hashlib.sha1(fp.read().strip()).hexdigest()
return "# SHA1:{0}\n".format(hexdigest) | python | def generate_hash_comment(file_path):
"""
Read file with given file_path and return string of format
# SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709
which is hex representation of SHA1 file content hash
"""
with open(file_path, 'rb') as fp:
hexdigest = hashlib.sha1(fp.read().strip()).hexdigest()
return "# SHA1:{0}\n".format(hexdigest) | [
"def",
"generate_hash_comment",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"fp",
":",
"hexdigest",
"=",
"hashlib",
".",
"sha1",
"(",
"fp",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"return",
"\"# SHA1:{0}\\n\"",
".",
"format",
"(",
"hexdigest",
")"
] | Read file with given file_path and return string of format
# SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709
which is hex representation of SHA1 file content hash | [
"Read",
"file",
"with",
"given",
"file_path",
"and",
"return",
"string",
"of",
"format"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/verify.py#L43-L53 | train | 235,293 |
peterdemin/pip-compile-multi | pipcompilemulti/config.py | parse_value | def parse_value(key, value):
"""Parse value as comma-delimited list if default value for it is list"""
default = OPTIONS.get(key)
if isinstance(default, collections.Iterable):
if not isinstance(default, six.string_types):
return [item.strip()
for item in value.split(',')]
return value | python | def parse_value(key, value):
"""Parse value as comma-delimited list if default value for it is list"""
default = OPTIONS.get(key)
if isinstance(default, collections.Iterable):
if not isinstance(default, six.string_types):
return [item.strip()
for item in value.split(',')]
return value | [
"def",
"parse_value",
"(",
"key",
",",
"value",
")",
":",
"default",
"=",
"OPTIONS",
".",
"get",
"(",
"key",
")",
"if",
"isinstance",
"(",
"default",
",",
"collections",
".",
"Iterable",
")",
":",
"if",
"not",
"isinstance",
"(",
"default",
",",
"six",
".",
"string_types",
")",
":",
"return",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"return",
"value"
] | Parse value as comma-delimited list if default value for it is list | [
"Parse",
"value",
"as",
"comma",
"-",
"delimited",
"list",
"if",
"default",
"value",
"for",
"it",
"is",
"list"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/config.py#L53-L60 | train | 235,294 |
peterdemin/pip-compile-multi | pipcompilemulti/config.py | python_version_matchers | def python_version_matchers():
"""Return set of string representations of current python version"""
version = sys.version_info
patterns = [
"{0}",
"{0}{1}",
"{0}.{1}",
]
matchers = [
pattern.format(*version)
for pattern in patterns
] + [None]
return set(matchers) | python | def python_version_matchers():
"""Return set of string representations of current python version"""
version = sys.version_info
patterns = [
"{0}",
"{0}{1}",
"{0}.{1}",
]
matchers = [
pattern.format(*version)
for pattern in patterns
] + [None]
return set(matchers) | [
"def",
"python_version_matchers",
"(",
")",
":",
"version",
"=",
"sys",
".",
"version_info",
"patterns",
"=",
"[",
"\"{0}\"",
",",
"\"{0}{1}\"",
",",
"\"{0}.{1}\"",
",",
"]",
"matchers",
"=",
"[",
"pattern",
".",
"format",
"(",
"*",
"version",
")",
"for",
"pattern",
"in",
"patterns",
"]",
"+",
"[",
"None",
"]",
"return",
"set",
"(",
"matchers",
")"
] | Return set of string representations of current python version | [
"Return",
"set",
"of",
"string",
"representations",
"of",
"current",
"python",
"version"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/config.py#L63-L75 | train | 235,295 |
peterdemin/pip-compile-multi | pipcompilemulti/cli_v2.py | verify | def verify(ctx):
"""Upgrade locked dependency versions"""
oks = run_configurations(
skipper(verify_environments),
read_sections,
)
ctx.exit(0
if False not in oks
else 1) | python | def verify(ctx):
"""Upgrade locked dependency versions"""
oks = run_configurations(
skipper(verify_environments),
read_sections,
)
ctx.exit(0
if False not in oks
else 1) | [
"def",
"verify",
"(",
"ctx",
")",
":",
"oks",
"=",
"run_configurations",
"(",
"skipper",
"(",
"verify_environments",
")",
",",
"read_sections",
",",
")",
"ctx",
".",
"exit",
"(",
"0",
"if",
"False",
"not",
"in",
"oks",
"else",
"1",
")"
] | Upgrade locked dependency versions | [
"Upgrade",
"locked",
"dependency",
"versions"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/cli_v2.py#L38-L46 | train | 235,296 |
peterdemin/pip-compile-multi | pipcompilemulti/cli_v2.py | skipper | def skipper(func):
"""Decorator that memorizes base_dir, in_ext and out_ext from OPTIONS
and skips execution for duplicates."""
@functools.wraps(func)
def wrapped():
"""Dummy docstring to make pylint happy."""
key = (OPTIONS['base_dir'], OPTIONS['in_ext'], OPTIONS['out_ext'])
if key not in seen:
seen[key] = func()
return seen[key]
seen = {}
return wrapped | python | def skipper(func):
"""Decorator that memorizes base_dir, in_ext and out_ext from OPTIONS
and skips execution for duplicates."""
@functools.wraps(func)
def wrapped():
"""Dummy docstring to make pylint happy."""
key = (OPTIONS['base_dir'], OPTIONS['in_ext'], OPTIONS['out_ext'])
if key not in seen:
seen[key] = func()
return seen[key]
seen = {}
return wrapped | [
"def",
"skipper",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
")",
":",
"\"\"\"Dummy docstring to make pylint happy.\"\"\"",
"key",
"=",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"OPTIONS",
"[",
"'in_ext'",
"]",
",",
"OPTIONS",
"[",
"'out_ext'",
"]",
")",
"if",
"key",
"not",
"in",
"seen",
":",
"seen",
"[",
"key",
"]",
"=",
"func",
"(",
")",
"return",
"seen",
"[",
"key",
"]",
"seen",
"=",
"{",
"}",
"return",
"wrapped"
] | Decorator that memorizes base_dir, in_ext and out_ext from OPTIONS
and skips execution for duplicates. | [
"Decorator",
"that",
"memorizes",
"base_dir",
"in_ext",
"and",
"out_ext",
"from",
"OPTIONS",
"and",
"skips",
"execution",
"for",
"duplicates",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/cli_v2.py#L49-L60 | train | 235,297 |
peterdemin/pip-compile-multi | pipcompilemulti/cli_v2.py | run_configurations | def run_configurations(callback, sections_reader):
"""Parse configurations and execute callback for matching."""
base = dict(OPTIONS)
sections = sections_reader()
if sections is None:
logger.info("Configuration not found in .ini files. "
"Running with default settings")
recompile()
elif sections == []:
logger.info("Configuration does not match current runtime. "
"Exiting")
results = []
for section, options in sections:
OPTIONS.clear()
OPTIONS.update(base)
OPTIONS.update(options)
logger.debug("Running configuration from section \"%s\". OPTIONS: %r",
section, OPTIONS)
results.append(callback())
return results | python | def run_configurations(callback, sections_reader):
"""Parse configurations and execute callback for matching."""
base = dict(OPTIONS)
sections = sections_reader()
if sections is None:
logger.info("Configuration not found in .ini files. "
"Running with default settings")
recompile()
elif sections == []:
logger.info("Configuration does not match current runtime. "
"Exiting")
results = []
for section, options in sections:
OPTIONS.clear()
OPTIONS.update(base)
OPTIONS.update(options)
logger.debug("Running configuration from section \"%s\". OPTIONS: %r",
section, OPTIONS)
results.append(callback())
return results | [
"def",
"run_configurations",
"(",
"callback",
",",
"sections_reader",
")",
":",
"base",
"=",
"dict",
"(",
"OPTIONS",
")",
"sections",
"=",
"sections_reader",
"(",
")",
"if",
"sections",
"is",
"None",
":",
"logger",
".",
"info",
"(",
"\"Configuration not found in .ini files. \"",
"\"Running with default settings\"",
")",
"recompile",
"(",
")",
"elif",
"sections",
"==",
"[",
"]",
":",
"logger",
".",
"info",
"(",
"\"Configuration does not match current runtime. \"",
"\"Exiting\"",
")",
"results",
"=",
"[",
"]",
"for",
"section",
",",
"options",
"in",
"sections",
":",
"OPTIONS",
".",
"clear",
"(",
")",
"OPTIONS",
".",
"update",
"(",
"base",
")",
"OPTIONS",
".",
"update",
"(",
"options",
")",
"logger",
".",
"debug",
"(",
"\"Running configuration from section \\\"%s\\\". OPTIONS: %r\"",
",",
"section",
",",
"OPTIONS",
")",
"results",
".",
"append",
"(",
"callback",
"(",
")",
")",
"return",
"results"
] | Parse configurations and execute callback for matching. | [
"Parse",
"configurations",
"and",
"execute",
"callback",
"for",
"matching",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/cli_v2.py#L63-L82 | train | 235,298 |
peterdemin/pip-compile-multi | pipcompilemulti/actions.py | recompile | def recompile():
"""
Compile requirements files for all environments.
"""
pinned_packages = {}
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
),
)
if OPTIONS['header_file']:
with open(OPTIONS['header_file']) as fp:
base_header_text = fp.read()
else:
base_header_text = DEFAULT_HEADER
hashed_by_reference = set()
for name in OPTIONS['add_hashes']:
hashed_by_reference.update(
reference_cluster(env_confs, name)
)
included_and_refs = set(OPTIONS['include_names'])
for name in set(included_and_refs):
included_and_refs.update(
recursive_refs(env_confs, name)
)
for conf in env_confs:
if included_and_refs:
if conf['name'] not in included_and_refs:
# Skip envs that are not included or referenced by included:
continue
rrefs = recursive_refs(env_confs, conf['name'])
add_hashes = conf['name'] in hashed_by_reference
env = Environment(
name=conf['name'],
ignore=merged_packages(pinned_packages, rrefs),
forbid_post=conf['name'] in OPTIONS['forbid_post'],
add_hashes=add_hashes,
)
logger.info("Locking %s to %s. References: %r",
env.infile, env.outfile, sorted(rrefs))
env.create_lockfile()
header_text = generate_hash_comment(env.infile) + base_header_text
env.replace_header(header_text)
env.add_references(conf['refs'])
pinned_packages[conf['name']] = env.packages | python | def recompile():
"""
Compile requirements files for all environments.
"""
pinned_packages = {}
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
),
)
if OPTIONS['header_file']:
with open(OPTIONS['header_file']) as fp:
base_header_text = fp.read()
else:
base_header_text = DEFAULT_HEADER
hashed_by_reference = set()
for name in OPTIONS['add_hashes']:
hashed_by_reference.update(
reference_cluster(env_confs, name)
)
included_and_refs = set(OPTIONS['include_names'])
for name in set(included_and_refs):
included_and_refs.update(
recursive_refs(env_confs, name)
)
for conf in env_confs:
if included_and_refs:
if conf['name'] not in included_and_refs:
# Skip envs that are not included or referenced by included:
continue
rrefs = recursive_refs(env_confs, conf['name'])
add_hashes = conf['name'] in hashed_by_reference
env = Environment(
name=conf['name'],
ignore=merged_packages(pinned_packages, rrefs),
forbid_post=conf['name'] in OPTIONS['forbid_post'],
add_hashes=add_hashes,
)
logger.info("Locking %s to %s. References: %r",
env.infile, env.outfile, sorted(rrefs))
env.create_lockfile()
header_text = generate_hash_comment(env.infile) + base_header_text
env.replace_header(header_text)
env.add_references(conf['refs'])
pinned_packages[conf['name']] = env.packages | [
"def",
"recompile",
"(",
")",
":",
"pinned_packages",
"=",
"{",
"}",
"env_confs",
"=",
"discover",
"(",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'*.'",
"+",
"OPTIONS",
"[",
"'in_ext'",
"]",
",",
")",
",",
")",
"if",
"OPTIONS",
"[",
"'header_file'",
"]",
":",
"with",
"open",
"(",
"OPTIONS",
"[",
"'header_file'",
"]",
")",
"as",
"fp",
":",
"base_header_text",
"=",
"fp",
".",
"read",
"(",
")",
"else",
":",
"base_header_text",
"=",
"DEFAULT_HEADER",
"hashed_by_reference",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"OPTIONS",
"[",
"'add_hashes'",
"]",
":",
"hashed_by_reference",
".",
"update",
"(",
"reference_cluster",
"(",
"env_confs",
",",
"name",
")",
")",
"included_and_refs",
"=",
"set",
"(",
"OPTIONS",
"[",
"'include_names'",
"]",
")",
"for",
"name",
"in",
"set",
"(",
"included_and_refs",
")",
":",
"included_and_refs",
".",
"update",
"(",
"recursive_refs",
"(",
"env_confs",
",",
"name",
")",
")",
"for",
"conf",
"in",
"env_confs",
":",
"if",
"included_and_refs",
":",
"if",
"conf",
"[",
"'name'",
"]",
"not",
"in",
"included_and_refs",
":",
"# Skip envs that are not included or referenced by included:",
"continue",
"rrefs",
"=",
"recursive_refs",
"(",
"env_confs",
",",
"conf",
"[",
"'name'",
"]",
")",
"add_hashes",
"=",
"conf",
"[",
"'name'",
"]",
"in",
"hashed_by_reference",
"env",
"=",
"Environment",
"(",
"name",
"=",
"conf",
"[",
"'name'",
"]",
",",
"ignore",
"=",
"merged_packages",
"(",
"pinned_packages",
",",
"rrefs",
")",
",",
"forbid_post",
"=",
"conf",
"[",
"'name'",
"]",
"in",
"OPTIONS",
"[",
"'forbid_post'",
"]",
",",
"add_hashes",
"=",
"add_hashes",
",",
")",
"logger",
".",
"info",
"(",
"\"Locking %s to %s. References: %r\"",
",",
"env",
".",
"infile",
",",
"env",
".",
"outfile",
",",
"sorted",
"(",
"rrefs",
")",
")",
"env",
".",
"create_lockfile",
"(",
")",
"header_text",
"=",
"generate_hash_comment",
"(",
"env",
".",
"infile",
")",
"+",
"base_header_text",
"env",
".",
"replace_header",
"(",
"header_text",
")",
"env",
".",
"add_references",
"(",
"conf",
"[",
"'refs'",
"]",
")",
"pinned_packages",
"[",
"conf",
"[",
"'name'",
"]",
"]",
"=",
"env",
".",
"packages"
] | Compile requirements files for all environments. | [
"Compile",
"requirements",
"files",
"for",
"all",
"environments",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/actions.py#L17-L62 | train | 235,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.