id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
232,200 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/views/roles.py | RoleList.post | def post(self):
"""Create a new role"""
self.reqparse.add_argument('name', type=str, required=True)
self.reqparse.add_argument('color', type=str, required=True)
args = self.reqparse.parse_args()
role = Role()
role.name = args['name']
role.color = args['color']
db.session.add(role)
db.session.commit()
auditlog(event='role.create', actor=session['user'].username, data=args)
return self.make_response('Role {} has been created'.format(role.role_id), HTTP.CREATED) | python | def post(self):
self.reqparse.add_argument('name', type=str, required=True)
self.reqparse.add_argument('color', type=str, required=True)
args = self.reqparse.parse_args()
role = Role()
role.name = args['name']
role.color = args['color']
db.session.add(role)
db.session.commit()
auditlog(event='role.create', actor=session['user'].username, data=args)
return self.make_response('Role {} has been created'.format(role.role_id), HTTP.CREATED) | [
"def",
"post",
"(",
"self",
")",
":",
"self",
".",
"reqparse",
".",
"add_argument",
"(",
"'name'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"True",
")",
"self",
".",
"reqparse",
".",
"add_argument",
"(",
"'color'",
",",
"type",
"=",
"str",
",",... | Create a new role | [
"Create",
"a",
"new",
"role"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/roles.py#L40-L54 |
232,201 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/views/roles.py | RoleGet.get | def get(self, roleId):
"""Get a specific role information"""
role = db.Role.find_one(Role.role_id == roleId)
if not role:
return self.make_response('No such role found', HTTP.NOT_FOUND)
return self.make_response({'role': role}) | python | def get(self, roleId):
role = db.Role.find_one(Role.role_id == roleId)
if not role:
return self.make_response('No such role found', HTTP.NOT_FOUND)
return self.make_response({'role': role}) | [
"def",
"get",
"(",
"self",
",",
"roleId",
")",
":",
"role",
"=",
"db",
".",
"Role",
".",
"find_one",
"(",
"Role",
".",
"role_id",
"==",
"roleId",
")",
"if",
"not",
"role",
":",
"return",
"self",
".",
"make_response",
"(",
"'No such role found'",
",",
... | Get a specific role information | [
"Get",
"a",
"specific",
"role",
"information"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/roles.py#L62-L69 |
232,202 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/views/roles.py | RoleGet.delete | def delete(self, roleId):
"""Delete a user role"""
role = db.Role.find_one(Role.role_id == roleId)
if not role:
return self.make_response('No such role found', HTTP.NOT_FOUND)
if role.name in ('User', 'Admin'):
return self.make_response('Cannot delete the built-in roles', HTTP.BAD_REQUEST)
db.session.delete(role)
db.session.commit()
auditlog(event='role.delete', actor=session['user'].username, data={'roleId': roleId})
return self.make_response({
'message': 'Role has been deleted',
'roleId': roleId
}) | python | def delete(self, roleId):
role = db.Role.find_one(Role.role_id == roleId)
if not role:
return self.make_response('No such role found', HTTP.NOT_FOUND)
if role.name in ('User', 'Admin'):
return self.make_response('Cannot delete the built-in roles', HTTP.BAD_REQUEST)
db.session.delete(role)
db.session.commit()
auditlog(event='role.delete', actor=session['user'].username, data={'roleId': roleId})
return self.make_response({
'message': 'Role has been deleted',
'roleId': roleId
}) | [
"def",
"delete",
"(",
"self",
",",
"roleId",
")",
":",
"role",
"=",
"db",
".",
"Role",
".",
"find_one",
"(",
"Role",
".",
"role_id",
"==",
"roleId",
")",
"if",
"not",
"role",
":",
"return",
"self",
".",
"make_response",
"(",
"'No such role found'",
","... | Delete a user role | [
"Delete",
"a",
"user",
"role"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/roles.py#L94-L110 |
232,203 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/notifiers/email.py | EmailNotifier.__send_ses_email | def __send_ses_email(self, recipients, subject, body_html, body_text):
"""Send an email using SES
Args:
recipients (`1ist` of `str`): List of recipient email addresses
subject (str): Subject of the email
body_html (str): HTML body of the email
body_text (str): Text body of the email
Returns:
`None`
"""
source_arn = dbconfig.get('source_arn', NS_EMAIL)
return_arn = dbconfig.get('return_path_arn', NS_EMAIL)
session = get_local_aws_session()
ses = session.client('ses', region_name=dbconfig.get('ses_region', NS_EMAIL, 'us-west-2'))
body = {}
if body_html:
body['Html'] = {
'Data': body_html
}
if body_text:
body['Text'] = {
'Data': body_text
}
ses_options = {
'Source': self.sender,
'Destination': {
'ToAddresses': recipients
},
'Message': {
'Subject': {
'Data': subject
},
'Body': body
}
}
# Set SES options if needed
if source_arn and return_arn:
ses_options.update({
'SourceArn': source_arn,
'ReturnPathArn': return_arn
})
ses.send_email(**ses_options) | python | def __send_ses_email(self, recipients, subject, body_html, body_text):
source_arn = dbconfig.get('source_arn', NS_EMAIL)
return_arn = dbconfig.get('return_path_arn', NS_EMAIL)
session = get_local_aws_session()
ses = session.client('ses', region_name=dbconfig.get('ses_region', NS_EMAIL, 'us-west-2'))
body = {}
if body_html:
body['Html'] = {
'Data': body_html
}
if body_text:
body['Text'] = {
'Data': body_text
}
ses_options = {
'Source': self.sender,
'Destination': {
'ToAddresses': recipients
},
'Message': {
'Subject': {
'Data': subject
},
'Body': body
}
}
# Set SES options if needed
if source_arn and return_arn:
ses_options.update({
'SourceArn': source_arn,
'ReturnPathArn': return_arn
})
ses.send_email(**ses_options) | [
"def",
"__send_ses_email",
"(",
"self",
",",
"recipients",
",",
"subject",
",",
"body_html",
",",
"body_text",
")",
":",
"source_arn",
"=",
"dbconfig",
".",
"get",
"(",
"'source_arn'",
",",
"NS_EMAIL",
")",
"return_arn",
"=",
"dbconfig",
".",
"get",
"(",
"... | Send an email using SES
Args:
recipients (`1ist` of `str`): List of recipient email addresses
subject (str): Subject of the email
body_html (str): HTML body of the email
body_text (str): Text body of the email
Returns:
`None` | [
"Send",
"an",
"email",
"using",
"SES"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/notifiers/email.py#L100-L148 |
232,204 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/notifiers/email.py | EmailNotifier.__send_smtp_email | def __send_smtp_email(self, recipients, subject, html_body, text_body):
"""Send an email using SMTP
Args:
recipients (`list` of `str`): List of recipient email addresses
subject (str): Subject of the email
html_body (str): HTML body of the email
text_body (str): Text body of the email
Returns:
`None`
"""
smtp = smtplib.SMTP(
dbconfig.get('smtp_server', NS_EMAIL, 'localhost'),
dbconfig.get('smtp_port', NS_EMAIL, 25)
)
source_arn = dbconfig.get('source_arn', NS_EMAIL)
return_arn = dbconfig.get('return_path_arn', NS_EMAIL)
from_arn = dbconfig.get('from_arn', NS_EMAIL)
msg = MIMEMultipart('alternative')
# Set SES options if needed
if source_arn and from_arn and return_arn:
msg['X-SES-SOURCE-ARN'] = source_arn
msg['X-SES-FROM-ARN'] = from_arn
msg['X-SES-RETURN-PATH-ARN'] = return_arn
msg['Subject'] = subject
msg['To'] = ','.join(recipients)
msg['From'] = self.sender
# Check body types to avoid exceptions
if html_body:
html_part = MIMEText(html_body, 'html')
msg.attach(html_part)
if text_body:
text_part = MIMEText(text_body, 'plain')
msg.attach(text_part)
# TLS if needed
if dbconfig.get('smtp_tls', NS_EMAIL, False):
smtp.starttls()
# Login if needed
username = dbconfig.get('smtp_username', NS_EMAIL)
password = dbconfig.get('smtp_password', NS_EMAIL)
if username and password:
smtp.login(username, password)
smtp.sendmail(self.sender, recipients, msg.as_string())
smtp.quit() | python | def __send_smtp_email(self, recipients, subject, html_body, text_body):
smtp = smtplib.SMTP(
dbconfig.get('smtp_server', NS_EMAIL, 'localhost'),
dbconfig.get('smtp_port', NS_EMAIL, 25)
)
source_arn = dbconfig.get('source_arn', NS_EMAIL)
return_arn = dbconfig.get('return_path_arn', NS_EMAIL)
from_arn = dbconfig.get('from_arn', NS_EMAIL)
msg = MIMEMultipart('alternative')
# Set SES options if needed
if source_arn and from_arn and return_arn:
msg['X-SES-SOURCE-ARN'] = source_arn
msg['X-SES-FROM-ARN'] = from_arn
msg['X-SES-RETURN-PATH-ARN'] = return_arn
msg['Subject'] = subject
msg['To'] = ','.join(recipients)
msg['From'] = self.sender
# Check body types to avoid exceptions
if html_body:
html_part = MIMEText(html_body, 'html')
msg.attach(html_part)
if text_body:
text_part = MIMEText(text_body, 'plain')
msg.attach(text_part)
# TLS if needed
if dbconfig.get('smtp_tls', NS_EMAIL, False):
smtp.starttls()
# Login if needed
username = dbconfig.get('smtp_username', NS_EMAIL)
password = dbconfig.get('smtp_password', NS_EMAIL)
if username and password:
smtp.login(username, password)
smtp.sendmail(self.sender, recipients, msg.as_string())
smtp.quit() | [
"def",
"__send_smtp_email",
"(",
"self",
",",
"recipients",
",",
"subject",
",",
"html_body",
",",
"text_body",
")",
":",
"smtp",
"=",
"smtplib",
".",
"SMTP",
"(",
"dbconfig",
".",
"get",
"(",
"'smtp_server'",
",",
"NS_EMAIL",
",",
"'localhost'",
")",
",",... | Send an email using SMTP
Args:
recipients (`list` of `str`): List of recipient email addresses
subject (str): Subject of the email
html_body (str): HTML body of the email
text_body (str): Text body of the email
Returns:
`None` | [
"Send",
"an",
"email",
"using",
"SMTP"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/notifiers/email.py#L150-L200 |
232,205 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/json_utils.py | InquisitorJSONEncoder.default | def default(self, obj):
"""Default object encoder function
Args:
obj (:obj:`Any`): Object to be serialized
Returns:
JSON string
"""
if isinstance(obj, datetime):
return obj.isoformat()
if issubclass(obj.__class__, Enum.__class__):
return obj.value
to_json = getattr(obj, 'to_json', None)
if to_json:
out = obj.to_json()
if issubclass(obj.__class__, Model):
out.update({'__type': obj.__class__.__name__})
return out
return JSONEncoder.default(self, obj) | python | def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if issubclass(obj.__class__, Enum.__class__):
return obj.value
to_json = getattr(obj, 'to_json', None)
if to_json:
out = obj.to_json()
if issubclass(obj.__class__, Model):
out.update({'__type': obj.__class__.__name__})
return out
return JSONEncoder.default(self, obj) | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
")",
":",
"return",
"obj",
".",
"isoformat",
"(",
")",
"if",
"issubclass",
"(",
"obj",
".",
"__class__",
",",
"Enum",
".",
"__class__",
")",
":",
... | Default object encoder function
Args:
obj (:obj:`Any`): Object to be serialized
Returns:
JSON string | [
"Default",
"object",
"encoder",
"function"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/json_utils.py#L24-L47 |
232,206 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | is_truthy | def is_truthy(value, default=False):
"""Evaluate a value for truthiness
>>> is_truthy('Yes')
True
>>> is_truthy('False')
False
>>> is_truthy(1)
True
Args:
value (Any): Value to evaluate
default (bool): Optional default value, if the input does not match the true or false values
Returns:
True if a truthy value is passed, else False
"""
if value is None:
return False
if isinstance(value, bool):
return value
if isinstance(value, int):
return value > 0
trues = ('1', 'true', 'y', 'yes', 'ok')
falses = ('', '0', 'false', 'n', 'none', 'no')
if value.lower().strip() in falses:
return False
elif value.lower().strip() in trues:
return True
else:
if default:
return default
else:
raise ValueError('Invalid argument given to truthy: {0}'.format(value)) | python | def is_truthy(value, default=False):
if value is None:
return False
if isinstance(value, bool):
return value
if isinstance(value, int):
return value > 0
trues = ('1', 'true', 'y', 'yes', 'ok')
falses = ('', '0', 'false', 'n', 'none', 'no')
if value.lower().strip() in falses:
return False
elif value.lower().strip() in trues:
return True
else:
if default:
return default
else:
raise ValueError('Invalid argument given to truthy: {0}'.format(value)) | [
"def",
"is_truthy",
"(",
"value",
",",
"default",
"=",
"False",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"False",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"int",
"... | Evaluate a value for truthiness
>>> is_truthy('Yes')
True
>>> is_truthy('False')
False
>>> is_truthy(1)
True
Args:
value (Any): Value to evaluate
default (bool): Optional default value, if the input does not match the true or false values
Returns:
True if a truthy value is passed, else False | [
"Evaluate",
"a",
"value",
"for",
"truthiness"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L97-L137 |
232,207 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | validate_email | def validate_email(email, partial_match=False):
"""Perform email address validation
>>> validate_email('akjaer@riotgames.com')
True
>>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com')
False
>>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com', partial_match=True)
True
Args:
email (str): Email address to match
partial_match (bool): If False (default), the entire string must be a valid email address. If true, any valid
email address in the string will trigger a valid response
Returns:
True if the value contains an email address, else False
"""
rgx = re.compile(RGX_EMAIL_VALIDATION_PATTERN, re.I)
if partial_match:
return rgx.search(email) is not None
else:
return rgx.match(email) is not None | python | def validate_email(email, partial_match=False):
rgx = re.compile(RGX_EMAIL_VALIDATION_PATTERN, re.I)
if partial_match:
return rgx.search(email) is not None
else:
return rgx.match(email) is not None | [
"def",
"validate_email",
"(",
"email",
",",
"partial_match",
"=",
"False",
")",
":",
"rgx",
"=",
"re",
".",
"compile",
"(",
"RGX_EMAIL_VALIDATION_PATTERN",
",",
"re",
".",
"I",
")",
"if",
"partial_match",
":",
"return",
"rgx",
".",
"search",
"(",
"email",
... | Perform email address validation
>>> validate_email('akjaer@riotgames.com')
True
>>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com')
False
>>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com', partial_match=True)
True
Args:
email (str): Email address to match
partial_match (bool): If False (default), the entire string must be a valid email address. If true, any valid
email address in the string will trigger a valid response
Returns:
True if the value contains an email address, else False | [
"Perform",
"email",
"address",
"validation"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L140-L162 |
232,208 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | get_template | def get_template(template):
"""Return a Jinja2 template by filename
Args:
template (str): Name of the template to return
Returns:
A Jinja2 Template object
"""
from cloud_inquisitor.database import db
tmpl = db.Template.find_one(template_name=template)
if not tmpl:
raise InquisitorError('No such template found: {}'.format(template))
tmplenv = Environment(loader=BaseLoader, autoescape=True)
tmplenv.filters['json_loads'] = json.loads
tmplenv.filters['slack_quote_join'] = lambda data: ', '.join('`{}`'.format(x) for x in data)
return tmplenv.from_string(tmpl.template) | python | def get_template(template):
from cloud_inquisitor.database import db
tmpl = db.Template.find_one(template_name=template)
if not tmpl:
raise InquisitorError('No such template found: {}'.format(template))
tmplenv = Environment(loader=BaseLoader, autoescape=True)
tmplenv.filters['json_loads'] = json.loads
tmplenv.filters['slack_quote_join'] = lambda data: ', '.join('`{}`'.format(x) for x in data)
return tmplenv.from_string(tmpl.template) | [
"def",
"get_template",
"(",
"template",
")",
":",
"from",
"cloud_inquisitor",
".",
"database",
"import",
"db",
"tmpl",
"=",
"db",
".",
"Template",
".",
"find_one",
"(",
"template_name",
"=",
"template",
")",
"if",
"not",
"tmpl",
":",
"raise",
"InquisitorErro... | Return a Jinja2 template by filename
Args:
template (str): Name of the template to return
Returns:
A Jinja2 Template object | [
"Return",
"a",
"Jinja2",
"template",
"by",
"filename"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L165-L184 |
232,209 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | to_utc_date | def to_utc_date(date):
"""Convert a datetime object from local to UTC format
>>> import datetime
>>> d = datetime.datetime(2017, 8, 15, 18, 24, 31)
>>> to_utc_date(d)
datetime.datetime(2017, 8, 16, 1, 24, 31)
Args:
date (`datetime`): Input datetime object
Returns:
`datetime`
"""
return datetime.utcfromtimestamp(float(date.strftime('%s'))).replace(tzinfo=None) if date else None | python | def to_utc_date(date):
return datetime.utcfromtimestamp(float(date.strftime('%s'))).replace(tzinfo=None) if date else None | [
"def",
"to_utc_date",
"(",
"date",
")",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"float",
"(",
"date",
".",
"strftime",
"(",
"'%s'",
")",
")",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"if",
"date",
"else",
"None"
] | Convert a datetime object from local to UTC format
>>> import datetime
>>> d = datetime.datetime(2017, 8, 15, 18, 24, 31)
>>> to_utc_date(d)
datetime.datetime(2017, 8, 16, 1, 24, 31)
Args:
date (`datetime`): Input datetime object
Returns:
`datetime` | [
"Convert",
"a",
"datetime",
"object",
"from",
"local",
"to",
"UTC",
"format"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L206-L220 |
232,210 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | generate_password | def generate_password(length=32):
"""Generate a cryptographically secure random string to use for passwords
Args:
length (int): Length of password, defaults to 32 characters
Returns:
Randomly generated string
"""
return ''.join(random.SystemRandom().choice(string.ascii_letters + '!@#$+.,') for _ in range(length)) | python | def generate_password(length=32):
return ''.join(random.SystemRandom().choice(string.ascii_letters + '!@#$+.,') for _ in range(length)) | [
"def",
"generate_password",
"(",
"length",
"=",
"32",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"'!@#$+.,'",
")",
"for",
"_",
"in",
"range",
"(",
"lengt... | Generate a cryptographically secure random string to use for passwords
Args:
length (int): Length of password, defaults to 32 characters
Returns:
Randomly generated string | [
"Generate",
"a",
"cryptographically",
"secure",
"random",
"string",
"to",
"use",
"for",
"passwords"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L240-L249 |
232,211 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | get_jwt_key_data | def get_jwt_key_data():
"""Returns the data for the JWT private key used for encrypting the user login token as a string object
Returns:
`str`
"""
global __jwt_data
if __jwt_data:
return __jwt_data
from cloud_inquisitor import config_path
from cloud_inquisitor.config import dbconfig
jwt_key_file = dbconfig.get('jwt_key_file_path', default='ssl/private.key')
if not os.path.isabs(jwt_key_file):
jwt_key_file = os.path.join(config_path, jwt_key_file)
with open(os.path.join(jwt_key_file), 'r') as f:
__jwt_data = f.read()
return __jwt_data | python | def get_jwt_key_data():
global __jwt_data
if __jwt_data:
return __jwt_data
from cloud_inquisitor import config_path
from cloud_inquisitor.config import dbconfig
jwt_key_file = dbconfig.get('jwt_key_file_path', default='ssl/private.key')
if not os.path.isabs(jwt_key_file):
jwt_key_file = os.path.join(config_path, jwt_key_file)
with open(os.path.join(jwt_key_file), 'r') as f:
__jwt_data = f.read()
return __jwt_data | [
"def",
"get_jwt_key_data",
"(",
")",
":",
"global",
"__jwt_data",
"if",
"__jwt_data",
":",
"return",
"__jwt_data",
"from",
"cloud_inquisitor",
"import",
"config_path",
"from",
"cloud_inquisitor",
".",
"config",
"import",
"dbconfig",
"jwt_key_file",
"=",
"dbconfig",
... | Returns the data for the JWT private key used for encrypting the user login token as a string object
Returns:
`str` | [
"Returns",
"the",
"data",
"for",
"the",
"JWT",
"private",
"key",
"used",
"for",
"encrypting",
"the",
"user",
"login",
"token",
"as",
"a",
"string",
"object"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L300-L321 |
232,212 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | has_access | def has_access(user, required_roles, match_all=True):
"""Check if the user meets the role requirements. If mode is set to AND, all the provided roles must apply
Args:
user (:obj:`User`): User object
required_roles (`list` of `str`): List of roles that the user must have applied
match_all (`bool`): If true, all the required_roles must be applied to the user, else any one match will
return `True`
Returns:
`bool`
"""
# Admins have access to everything
if ROLE_ADMIN in user.roles:
return True
if isinstance(required_roles, str):
if required_roles in user.roles:
return True
return False
# If we received a list of roles to match against
if match_all:
for role in required_roles:
if role not in user.roles:
return False
return True
else:
for role in required_roles:
if role in user.roles:
return True
return False | python | def has_access(user, required_roles, match_all=True):
# Admins have access to everything
if ROLE_ADMIN in user.roles:
return True
if isinstance(required_roles, str):
if required_roles in user.roles:
return True
return False
# If we received a list of roles to match against
if match_all:
for role in required_roles:
if role not in user.roles:
return False
return True
else:
for role in required_roles:
if role in user.roles:
return True
return False | [
"def",
"has_access",
"(",
"user",
",",
"required_roles",
",",
"match_all",
"=",
"True",
")",
":",
"# Admins have access to everything",
"if",
"ROLE_ADMIN",
"in",
"user",
".",
"roles",
":",
"return",
"True",
"if",
"isinstance",
"(",
"required_roles",
",",
"str",
... | Check if the user meets the role requirements. If mode is set to AND, all the provided roles must apply
Args:
user (:obj:`User`): User object
required_roles (`list` of `str`): List of roles that the user must have applied
match_all (`bool`): If true, all the required_roles must be applied to the user, else any one match will
return `True`
Returns:
`bool` | [
"Check",
"if",
"the",
"user",
"meets",
"the",
"role",
"requirements",
".",
"If",
"mode",
"is",
"set",
"to",
"AND",
"all",
"the",
"provided",
"roles",
"must",
"apply"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L324-L359 |
232,213 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | merge_lists | def merge_lists(*args):
"""Merge an arbitrary number of lists into a single list and dedupe it
Args:
*args: Two or more lists
Returns:
A deduped merged list of all the provided lists as a single list
"""
out = {}
for contacts in filter(None, args):
for contact in contacts:
out[contact.value] = contact
return list(out.values()) | python | def merge_lists(*args):
out = {}
for contacts in filter(None, args):
for contact in contacts:
out[contact.value] = contact
return list(out.values()) | [
"def",
"merge_lists",
"(",
"*",
"args",
")",
":",
"out",
"=",
"{",
"}",
"for",
"contacts",
"in",
"filter",
"(",
"None",
",",
"args",
")",
":",
"for",
"contact",
"in",
"contacts",
":",
"out",
"[",
"contact",
".",
"value",
"]",
"=",
"contact",
"retur... | Merge an arbitrary number of lists into a single list and dedupe it
Args:
*args: Two or more lists
Returns:
A deduped merged list of all the provided lists as a single list | [
"Merge",
"an",
"arbitrary",
"number",
"of",
"lists",
"into",
"a",
"single",
"list",
"and",
"dedupe",
"it"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L362-L377 |
232,214 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | get_resource_id | def get_resource_id(prefix, *data):
"""Returns a unique ID based on the SHA256 hash of the provided data. The input data is flattened and sorted to
ensure identical hashes are generated regardless of the order of the input. Values must be of types `str`, `int` or
`float`, any other input type will raise a `ValueError`
>>> get_resource_id('ec2', 'lots', 'of', 'data')
'ec2-1d21940125214123'
>>> get_resource_id('ecs', 'foo', ['more', 'data', 'here', 2, 3])
'ecs-e536b036ea6fd463'
>>> get_resource_id('ecs', ['more'], 'data', 'here', [[2], 3], 'foo')
'ecs-e536b036ea6fd463'
Args:
prefix (`str`): Key prefix
*data (`str`, `int`, `float`, `list`, `tuple`): Data used to generate a unique ID
Returns:
`str`
"""
parts = flatten(data)
for part in parts:
if type(part) not in (str, int, float):
raise ValueError('Supported data types: int, float, list, tuple, str. Got: {}'.format(type(part)))
return '{}-{}'.format(
prefix,
get_hash('-'.join(sorted(map(str, parts))))[-16:]
) | python | def get_resource_id(prefix, *data):
parts = flatten(data)
for part in parts:
if type(part) not in (str, int, float):
raise ValueError('Supported data types: int, float, list, tuple, str. Got: {}'.format(type(part)))
return '{}-{}'.format(
prefix,
get_hash('-'.join(sorted(map(str, parts))))[-16:]
) | [
"def",
"get_resource_id",
"(",
"prefix",
",",
"*",
"data",
")",
":",
"parts",
"=",
"flatten",
"(",
"data",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"type",
"(",
"part",
")",
"not",
"in",
"(",
"str",
",",
"int",
",",
"float",
")",
":",
"raise... | Returns a unique ID based on the SHA256 hash of the provided data. The input data is flattened and sorted to
ensure identical hashes are generated regardless of the order of the input. Values must be of types `str`, `int` or
`float`, any other input type will raise a `ValueError`
>>> get_resource_id('ec2', 'lots', 'of', 'data')
'ec2-1d21940125214123'
>>> get_resource_id('ecs', 'foo', ['more', 'data', 'here', 2, 3])
'ecs-e536b036ea6fd463'
>>> get_resource_id('ecs', ['more'], 'data', 'here', [[2], 3], 'foo')
'ecs-e536b036ea6fd463'
Args:
prefix (`str`): Key prefix
*data (`str`, `int`, `float`, `list`, `tuple`): Data used to generate a unique ID
Returns:
`str` | [
"Returns",
"a",
"unique",
"ID",
"based",
"on",
"the",
"SHA256",
"hash",
"of",
"the",
"provided",
"data",
".",
"The",
"input",
"data",
"is",
"flattened",
"and",
"sorted",
"to",
"ensure",
"identical",
"hashes",
"are",
"generated",
"regardless",
"of",
"the",
... | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L410-L437 |
232,215 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | parse_date | def parse_date(date_string, ignoretz=True):
"""Parse a string as a date. If the string fails to parse, `None` will be returned instead
>>> parse_date('2017-08-15T18:24:31')
datetime.datetime(2017, 8, 15, 18, 24, 31)
Args:
date_string (`str`): Date in string format to parse
ignoretz (`bool`): If set ``True``, ignore time zones and return a naive :class:`datetime` object.
Returns:
`datetime`, `None`
"""
try:
return parser.parse(date_string, ignoretz=ignoretz)
except TypeError:
return None | python | def parse_date(date_string, ignoretz=True):
try:
return parser.parse(date_string, ignoretz=ignoretz)
except TypeError:
return None | [
"def",
"parse_date",
"(",
"date_string",
",",
"ignoretz",
"=",
"True",
")",
":",
"try",
":",
"return",
"parser",
".",
"parse",
"(",
"date_string",
",",
"ignoretz",
"=",
"ignoretz",
")",
"except",
"TypeError",
":",
"return",
"None"
] | Parse a string as a date. If the string fails to parse, `None` will be returned instead
>>> parse_date('2017-08-15T18:24:31')
datetime.datetime(2017, 8, 15, 18, 24, 31)
Args:
date_string (`str`): Date in string format to parse
ignoretz (`bool`): If set ``True``, ignore time zones and return a naive :class:`datetime` object.
Returns:
`datetime`, `None` | [
"Parse",
"a",
"string",
"as",
"a",
"date",
".",
"If",
"the",
"string",
"fails",
"to",
"parse",
"None",
"will",
"be",
"returned",
"instead"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L440-L456 |
232,216 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | get_user_data_configuration | def get_user_data_configuration():
"""Retrieve and update the application configuration with information from the user-data
Returns:
`None`
"""
from cloud_inquisitor import get_local_aws_session, app_config
kms_region = app_config.kms_region
session = get_local_aws_session()
if session.get_credentials().method == 'iam-role':
kms = session.client('kms', region_name=kms_region)
else:
sts = session.client('sts')
audit_role = sts.assume_role(RoleArn=app_config.aws_api.instance_role_arn, RoleSessionName='cloud_inquisitor')
kms = boto3.session.Session(
audit_role['Credentials']['AccessKeyId'],
audit_role['Credentials']['SecretAccessKey'],
audit_role['Credentials']['SessionToken'],
).client('kms', region_name=kms_region)
user_data_url = app_config.user_data_url
res = requests.get(user_data_url)
if res.status_code == 200:
data = kms.decrypt(CiphertextBlob=b64decode(res.content))
kms_config = json.loads(zlib.decompress(data['Plaintext']).decode('utf-8'))
app_config.database_uri = kms_config['db_uri']
else:
raise RuntimeError('Failed loading user-data, cannot continue: {}: {}'.format(res.status_code, res.content)) | python | def get_user_data_configuration():
from cloud_inquisitor import get_local_aws_session, app_config
kms_region = app_config.kms_region
session = get_local_aws_session()
if session.get_credentials().method == 'iam-role':
kms = session.client('kms', region_name=kms_region)
else:
sts = session.client('sts')
audit_role = sts.assume_role(RoleArn=app_config.aws_api.instance_role_arn, RoleSessionName='cloud_inquisitor')
kms = boto3.session.Session(
audit_role['Credentials']['AccessKeyId'],
audit_role['Credentials']['SecretAccessKey'],
audit_role['Credentials']['SessionToken'],
).client('kms', region_name=kms_region)
user_data_url = app_config.user_data_url
res = requests.get(user_data_url)
if res.status_code == 200:
data = kms.decrypt(CiphertextBlob=b64decode(res.content))
kms_config = json.loads(zlib.decompress(data['Plaintext']).decode('utf-8'))
app_config.database_uri = kms_config['db_uri']
else:
raise RuntimeError('Failed loading user-data, cannot continue: {}: {}'.format(res.status_code, res.content)) | [
"def",
"get_user_data_configuration",
"(",
")",
":",
"from",
"cloud_inquisitor",
"import",
"get_local_aws_session",
",",
"app_config",
"kms_region",
"=",
"app_config",
".",
"kms_region",
"session",
"=",
"get_local_aws_session",
"(",
")",
"if",
"session",
".",
"get_cre... | Retrieve and update the application configuration with information from the user-data
Returns:
`None` | [
"Retrieve",
"and",
"update",
"the",
"application",
"configuration",
"with",
"information",
"from",
"the",
"user",
"-",
"data"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L459-L490 |
232,217 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | flatten | def flatten(data):
"""Returns a flattened version of a list.
Courtesy of https://stackoverflow.com/a/12472564
Args:
data (`tuple` or `list`): Input data
Returns:
`list`
"""
if not data:
return data
if type(data[0]) in (list, tuple):
return list(flatten(data[0])) + list(flatten(data[1:]))
return list(data[:1]) + list(flatten(data[1:])) | python | def flatten(data):
if not data:
return data
if type(data[0]) in (list, tuple):
return list(flatten(data[0])) + list(flatten(data[1:]))
return list(data[:1]) + list(flatten(data[1:])) | [
"def",
"flatten",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"data",
"if",
"type",
"(",
"data",
"[",
"0",
"]",
")",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"return",
"list",
"(",
"flatten",
"(",
"data",
"[",
"0",
"]",
")",
... | Returns a flattened version of a list.
Courtesy of https://stackoverflow.com/a/12472564
Args:
data (`tuple` or `list`): Input data
Returns:
`list` | [
"Returns",
"a",
"flattened",
"version",
"of",
"a",
"list",
"."
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L529-L546 |
232,218 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | diff | def diff(a, b):
"""Return the difference between two strings
Will return a human-readable difference between two strings. See
https://docs.python.org/3/library/difflib.html#difflib.Differ for more information about the output format
Args:
a (str): Original string
b (str): New string
Returns:
`str`
"""
return ''.join(
Differ().compare(
a.splitlines(keepends=True),
b.splitlines(keepends=True)
)
) | python | def diff(a, b):
return ''.join(
Differ().compare(
a.splitlines(keepends=True),
b.splitlines(keepends=True)
)
) | [
"def",
"diff",
"(",
"a",
",",
"b",
")",
":",
"return",
"''",
".",
"join",
"(",
"Differ",
"(",
")",
".",
"compare",
"(",
"a",
".",
"splitlines",
"(",
"keepends",
"=",
"True",
")",
",",
"b",
".",
"splitlines",
"(",
"keepends",
"=",
"True",
")",
"... | Return the difference between two strings
Will return a human-readable difference between two strings. See
https://docs.python.org/3/library/difflib.html#difflib.Differ for more information about the output format
Args:
a (str): Original string
b (str): New string
Returns:
`str` | [
"Return",
"the",
"difference",
"between",
"two",
"strings"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L588-L606 |
232,219 | RiotGames/cloud-inquisitor | frontend/build-scripts/build.py | build | def build(bucket_name, version, force, verbose):
"""Build and upload a new tarball
Args:
bucket_name (str): Name of the bucket to upload to
version (str): Override build version. Defaults to using SCM based versioning (git tags)
force (bool): Overwrite existing files in S3, if present
verbose (bool): Verbose output
"""
if verbose:
log.setLevel('DEBUG')
if not version:
version = setuptools_scm.get_version()
release = "dev" if "dev" in version else "release"
tarball = TARBALL_FORMAT.format(version)
tarball_path = os.path.join(tempfile.gettempdir(), tarball)
s3_key = os.path.join(release, tarball)
try:
run('npm i')
run('./node_modules/.bin/gulp build.prod')
except ExecutionError:
log.exception('Failed executing command')
return
log.debug('Creating archive')
tar = tarfile.open(tarball_path, "w:gz")
for root, dirnames, filenames in os.walk('dist'):
for f in filenames:
tar.add(os.path.join(root, f), recursive=False, filter=strip_path)
tar.close()
log.debug('Uploading {} to s3://{}/{}'.format(tarball, bucket_name, s3_key))
try:
bucket = get_bucket_resource(bucket_name)
if s3_file_exists(bucket, s3_key) and not force:
log.error('File already exists in S3, use --force to overwrite')
return
bucket.upload_file(tarball_path, os.path.join(release, tarball))
except ClientError:
log.exception('AWS API failure') | python | def build(bucket_name, version, force, verbose):
if verbose:
log.setLevel('DEBUG')
if not version:
version = setuptools_scm.get_version()
release = "dev" if "dev" in version else "release"
tarball = TARBALL_FORMAT.format(version)
tarball_path = os.path.join(tempfile.gettempdir(), tarball)
s3_key = os.path.join(release, tarball)
try:
run('npm i')
run('./node_modules/.bin/gulp build.prod')
except ExecutionError:
log.exception('Failed executing command')
return
log.debug('Creating archive')
tar = tarfile.open(tarball_path, "w:gz")
for root, dirnames, filenames in os.walk('dist'):
for f in filenames:
tar.add(os.path.join(root, f), recursive=False, filter=strip_path)
tar.close()
log.debug('Uploading {} to s3://{}/{}'.format(tarball, bucket_name, s3_key))
try:
bucket = get_bucket_resource(bucket_name)
if s3_file_exists(bucket, s3_key) and not force:
log.error('File already exists in S3, use --force to overwrite')
return
bucket.upload_file(tarball_path, os.path.join(release, tarball))
except ClientError:
log.exception('AWS API failure') | [
"def",
"build",
"(",
"bucket_name",
",",
"version",
",",
"force",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"log",
".",
"setLevel",
"(",
"'DEBUG'",
")",
"if",
"not",
"version",
":",
"version",
"=",
"setuptools_scm",
".",
"get_version",
"(",
")",
... | Build and upload a new tarball
Args:
bucket_name (str): Name of the bucket to upload to
version (str): Override build version. Defaults to using SCM based versioning (git tags)
force (bool): Overwrite existing files in S3, if present
verbose (bool): Verbose output | [
"Build",
"and",
"upload",
"a",
"new",
"tarball"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/frontend/build-scripts/build.py#L105-L150 |
232,220 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/issues.py | BaseIssue.get | def get(cls, issue_id):
"""Returns the class object identified by `issue_id`
Args:
issue_id (str): Unique EC2 Instance ID to load from database
Returns:
EC2 Instance object if found, else None
"""
res = Issue.get(issue_id, IssueType.get(cls.issue_type).issue_type_id)
return cls(res) if res else None | python | def get(cls, issue_id):
res = Issue.get(issue_id, IssueType.get(cls.issue_type).issue_type_id)
return cls(res) if res else None | [
"def",
"get",
"(",
"cls",
",",
"issue_id",
")",
":",
"res",
"=",
"Issue",
".",
"get",
"(",
"issue_id",
",",
"IssueType",
".",
"get",
"(",
"cls",
".",
"issue_type",
")",
".",
"issue_type_id",
")",
"return",
"cls",
"(",
"res",
")",
"if",
"res",
"else... | Returns the class object identified by `issue_id`
Args:
issue_id (str): Unique EC2 Instance ID to load from database
Returns:
EC2 Instance object if found, else None | [
"Returns",
"the",
"class",
"object",
"identified",
"by",
"issue_id"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/issues.py#L125-L135 |
232,221 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/issues.py | BaseIssue.create | def create(cls, issue_id, *, properties=None, auto_commit=False):
"""Creates a new Issue object with the properties and tags provided
Attributes:
issue_id (str): Unique identifier for the issue object
account (:obj:`Account`): Account which owns the issue
properties (dict): Dictionary of properties for the issue object.
"""
if cls.get(issue_id):
raise IssueException('Issue {} already exists'.format(issue_id))
res = Issue()
res.issue_id = issue_id
res.issue_type_id = IssueType.get(cls.issue_type).issue_type_id
if properties:
for name, value in properties.items():
prop = IssueProperty()
prop.issue_id = res.issue_id
prop.name = name
prop.value = value.isoformat() if type(value) == datetime else value
res.properties.append(prop)
db.session.add(prop)
db.session.add(res)
if auto_commit:
db.session.commit()
return cls.get(res.issue_id) | python | def create(cls, issue_id, *, properties=None, auto_commit=False):
if cls.get(issue_id):
raise IssueException('Issue {} already exists'.format(issue_id))
res = Issue()
res.issue_id = issue_id
res.issue_type_id = IssueType.get(cls.issue_type).issue_type_id
if properties:
for name, value in properties.items():
prop = IssueProperty()
prop.issue_id = res.issue_id
prop.name = name
prop.value = value.isoformat() if type(value) == datetime else value
res.properties.append(prop)
db.session.add(prop)
db.session.add(res)
if auto_commit:
db.session.commit()
return cls.get(res.issue_id) | [
"def",
"create",
"(",
"cls",
",",
"issue_id",
",",
"*",
",",
"properties",
"=",
"None",
",",
"auto_commit",
"=",
"False",
")",
":",
"if",
"cls",
".",
"get",
"(",
"issue_id",
")",
":",
"raise",
"IssueException",
"(",
"'Issue {} already exists'",
".",
"for... | Creates a new Issue object with the properties and tags provided
Attributes:
issue_id (str): Unique identifier for the issue object
account (:obj:`Account`): Account which owns the issue
properties (dict): Dictionary of properties for the issue object. | [
"Creates",
"a",
"new",
"Issue",
"object",
"with",
"the",
"properties",
"and",
"tags",
"provided"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/issues.py#L138-L166 |
232,222 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/issues.py | BaseIssue.get_all | def get_all(cls):
"""Returns a list of all issues of a given type
Returns:
list of issue objects
"""
issues = db.Issue.find(
Issue.issue_type_id == IssueType.get(cls.issue_type).issue_type_id
)
return {res.issue_id: cls(res) for res in issues} | python | def get_all(cls):
issues = db.Issue.find(
Issue.issue_type_id == IssueType.get(cls.issue_type).issue_type_id
)
return {res.issue_id: cls(res) for res in issues} | [
"def",
"get_all",
"(",
"cls",
")",
":",
"issues",
"=",
"db",
".",
"Issue",
".",
"find",
"(",
"Issue",
".",
"issue_type_id",
"==",
"IssueType",
".",
"get",
"(",
"cls",
".",
"issue_type",
")",
".",
"issue_type_id",
")",
"return",
"{",
"res",
".",
"issu... | Returns a list of all issues of a given type
Returns:
list of issue objects | [
"Returns",
"a",
"list",
"of",
"all",
"issues",
"of",
"a",
"given",
"type"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/issues.py#L169-L179 |
232,223 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/issues.py | BaseIssue.search | def search(cls, *, limit=100, page=1, properties=None, return_query=False):
"""Search for issues based on the provided filters
Args:
limit (`int`): Number of results to return. Default: 100
page (`int`): Pagination offset for results. Default: 1
properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list
of strings, in which case a boolean OR search is performed on the values
return_query (`bool`): Returns the query object prior to adding the limit and offset functions. Allows for
sub-classes to amend the search feature with extra conditions. The calling function must handle pagination
on its own
Returns:
`list` of `Issue`, `sqlalchemy.orm.Query`
"""
qry = db.Issue.order_by(Issue.issue_id).filter(
Issue.issue_type_id == IssueType.get(cls.issue_type).issue_type_id
)
if properties:
for prop_name, value in properties.items():
alias = aliased(IssueProperty)
qry = qry.join(alias, Issue.issue_id == alias.issue_id)
if type(value) == list:
where_clause = []
for item in value:
where_clause.append(alias.value == item)
qry = qry.filter(
and_(
alias.name == prop_name,
or_(*where_clause)
).self_group()
)
else:
qry = qry.filter(
and_(
alias.name == prop_name,
alias.value == value
).self_group()
)
if return_query:
return qry
total = qry.count()
qry = qry.limit(limit)
qry = qry.offset((page - 1) * limit if page > 1 else 0)
return total, [cls(x) for x in qry.all()] | python | def search(cls, *, limit=100, page=1, properties=None, return_query=False):
qry = db.Issue.order_by(Issue.issue_id).filter(
Issue.issue_type_id == IssueType.get(cls.issue_type).issue_type_id
)
if properties:
for prop_name, value in properties.items():
alias = aliased(IssueProperty)
qry = qry.join(alias, Issue.issue_id == alias.issue_id)
if type(value) == list:
where_clause = []
for item in value:
where_clause.append(alias.value == item)
qry = qry.filter(
and_(
alias.name == prop_name,
or_(*where_clause)
).self_group()
)
else:
qry = qry.filter(
and_(
alias.name == prop_name,
alias.value == value
).self_group()
)
if return_query:
return qry
total = qry.count()
qry = qry.limit(limit)
qry = qry.offset((page - 1) * limit if page > 1 else 0)
return total, [cls(x) for x in qry.all()] | [
"def",
"search",
"(",
"cls",
",",
"*",
",",
"limit",
"=",
"100",
",",
"page",
"=",
"1",
",",
"properties",
"=",
"None",
",",
"return_query",
"=",
"False",
")",
":",
"qry",
"=",
"db",
".",
"Issue",
".",
"order_by",
"(",
"Issue",
".",
"issue_id",
"... | Search for issues based on the provided filters
Args:
limit (`int`): Number of results to return. Default: 100
page (`int`): Pagination offset for results. Default: 1
properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list
of strings, in which case a boolean OR search is performed on the values
return_query (`bool`): Returns the query object prior to adding the limit and offset functions. Allows for
sub-classes to amend the search feature with extra conditions. The calling function must handle pagination
on its own
Returns:
`list` of `Issue`, `sqlalchemy.orm.Query` | [
"Search",
"for",
"issues",
"based",
"on",
"the",
"provided",
"filters"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/issues.py#L182-L231 |
232,224 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/issues.py | RequiredTagsIssue.state_name | def state_name(self):
"""Get a human-readable value of the state
Returns:
str: Name of the current state
"""
if self.state == 1:
return 'New Issue'
elif self.state == 2:
return 'Shutdown in 1 week'
elif self.state == 3:
return 'Shutdown in 1 day'
elif self.state == 4:
return 'Pending Shutdown'
elif self.state == 5:
return 'Stopped, delete in 12 weeks'
elif self.state == 6:
return 'Instance deleted'
else:
raise ValueError('Invalid state: {}'.format(self.state)) | python | def state_name(self):
if self.state == 1:
return 'New Issue'
elif self.state == 2:
return 'Shutdown in 1 week'
elif self.state == 3:
return 'Shutdown in 1 day'
elif self.state == 4:
return 'Pending Shutdown'
elif self.state == 5:
return 'Stopped, delete in 12 weeks'
elif self.state == 6:
return 'Instance deleted'
else:
raise ValueError('Invalid state: {}'.format(self.state)) | [
"def",
"state_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"1",
":",
"return",
"'New Issue'",
"elif",
"self",
".",
"state",
"==",
"2",
":",
"return",
"'Shutdown in 1 week'",
"elif",
"self",
".",
"state",
"==",
"3",
":",
"return",
"'S... | Get a human-readable value of the state
Returns:
str: Name of the current state | [
"Get",
"a",
"human",
"-",
"readable",
"value",
"of",
"the",
"state"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/issues.py#L375-L400 |
232,225 | quodlibet/mutagen | mutagen/_tools/mid3cp.py | copy | def copy(src, dst, merge, write_v1=True, excluded_tags=None, verbose=False):
"""Returns 0 on success"""
if excluded_tags is None:
excluded_tags = []
try:
id3 = mutagen.id3.ID3(src, translate=False)
except mutagen.id3.ID3NoHeaderError:
print_(u"No ID3 header found in ", src, file=sys.stderr)
return 1
except Exception as err:
print_(str(err), file=sys.stderr)
return 1
if verbose:
print_(u"File", src, u"contains:", file=sys.stderr)
print_(id3.pprint(), file=sys.stderr)
for tag in excluded_tags:
id3.delall(tag)
if merge:
try:
target = mutagen.id3.ID3(dst, translate=False)
except mutagen.id3.ID3NoHeaderError:
# no need to merge
pass
except Exception as err:
print_(str(err), file=sys.stderr)
return 1
else:
for frame in id3.values():
target.add(frame)
id3 = target
# if the source is 2.3 save it as 2.3
if id3.version < (2, 4, 0):
id3.update_to_v23()
v2_version = 3
else:
id3.update_to_v24()
v2_version = 4
try:
id3.save(dst, v1=(2 if write_v1 else 0), v2_version=v2_version)
except Exception as err:
print_(u"Error saving", dst, u":\n%s" % text_type(err),
file=sys.stderr)
return 1
else:
if verbose:
print_(u"Successfully saved", dst, file=sys.stderr)
return 0 | python | def copy(src, dst, merge, write_v1=True, excluded_tags=None, verbose=False):
if excluded_tags is None:
excluded_tags = []
try:
id3 = mutagen.id3.ID3(src, translate=False)
except mutagen.id3.ID3NoHeaderError:
print_(u"No ID3 header found in ", src, file=sys.stderr)
return 1
except Exception as err:
print_(str(err), file=sys.stderr)
return 1
if verbose:
print_(u"File", src, u"contains:", file=sys.stderr)
print_(id3.pprint(), file=sys.stderr)
for tag in excluded_tags:
id3.delall(tag)
if merge:
try:
target = mutagen.id3.ID3(dst, translate=False)
except mutagen.id3.ID3NoHeaderError:
# no need to merge
pass
except Exception as err:
print_(str(err), file=sys.stderr)
return 1
else:
for frame in id3.values():
target.add(frame)
id3 = target
# if the source is 2.3 save it as 2.3
if id3.version < (2, 4, 0):
id3.update_to_v23()
v2_version = 3
else:
id3.update_to_v24()
v2_version = 4
try:
id3.save(dst, v1=(2 if write_v1 else 0), v2_version=v2_version)
except Exception as err:
print_(u"Error saving", dst, u":\n%s" % text_type(err),
file=sys.stderr)
return 1
else:
if verbose:
print_(u"Successfully saved", dst, file=sys.stderr)
return 0 | [
"def",
"copy",
"(",
"src",
",",
"dst",
",",
"merge",
",",
"write_v1",
"=",
"True",
",",
"excluded_tags",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"excluded_tags",
"is",
"None",
":",
"excluded_tags",
"=",
"[",
"]",
"try",
":",
"id3",... | Returns 0 on success | [
"Returns",
"0",
"on",
"success"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_tools/mid3cp.py#L46-L100 |
232,226 | quodlibet/mutagen | mutagen/id3/_file.py | ID3FileType.add_tags | def add_tags(self, ID3=None):
"""Add an empty ID3 tag to the file.
Args:
ID3 (ID3): An ID3 subclass to use or `None` to use the one
that used when loading.
A custom tag reader may be used in instead of the default
`ID3` object, e.g. an `mutagen.easyid3.EasyID3` reader.
"""
if ID3 is None:
ID3 = self.ID3
if self.tags is None:
self.ID3 = ID3
self.tags = ID3()
else:
raise error("an ID3 tag already exists") | python | def add_tags(self, ID3=None):
if ID3 is None:
ID3 = self.ID3
if self.tags is None:
self.ID3 = ID3
self.tags = ID3()
else:
raise error("an ID3 tag already exists") | [
"def",
"add_tags",
"(",
"self",
",",
"ID3",
"=",
"None",
")",
":",
"if",
"ID3",
"is",
"None",
":",
"ID3",
"=",
"self",
".",
"ID3",
"if",
"self",
".",
"tags",
"is",
"None",
":",
"self",
".",
"ID3",
"=",
"ID3",
"self",
".",
"tags",
"=",
"ID3",
... | Add an empty ID3 tag to the file.
Args:
ID3 (ID3): An ID3 subclass to use or `None` to use the one
that used when loading.
A custom tag reader may be used in instead of the default
`ID3` object, e.g. an `mutagen.easyid3.EasyID3` reader. | [
"Add",
"an",
"empty",
"ID3",
"tag",
"to",
"the",
"file",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_file.py#L378-L395 |
232,227 | quodlibet/mutagen | mutagen/easymp4.py | EasyMP4Tags.RegisterKey | def RegisterKey(cls, key,
getter=None, setter=None, deleter=None, lister=None):
"""Register a new key mapping.
A key mapping is four functions, a getter, setter, deleter,
and lister. The key may be either a string or a glob pattern.
The getter, deleted, and lister receive an MP4Tags instance
and the requested key name. The setter also receives the
desired value, which will be a list of strings.
The getter, setter, and deleter are used to implement __getitem__,
__setitem__, and __delitem__.
The lister is used to implement keys(). It should return a
list of keys that are actually in the MP4 instance, provided
by its associated getter.
"""
key = key.lower()
if getter is not None:
cls.Get[key] = getter
if setter is not None:
cls.Set[key] = setter
if deleter is not None:
cls.Delete[key] = deleter
if lister is not None:
cls.List[key] = lister | python | def RegisterKey(cls, key,
getter=None, setter=None, deleter=None, lister=None):
key = key.lower()
if getter is not None:
cls.Get[key] = getter
if setter is not None:
cls.Set[key] = setter
if deleter is not None:
cls.Delete[key] = deleter
if lister is not None:
cls.List[key] = lister | [
"def",
"RegisterKey",
"(",
"cls",
",",
"key",
",",
"getter",
"=",
"None",
",",
"setter",
"=",
"None",
",",
"deleter",
"=",
"None",
",",
"lister",
"=",
"None",
")",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"if",
"getter",
"is",
"not",
"None... | Register a new key mapping.
A key mapping is four functions, a getter, setter, deleter,
and lister. The key may be either a string or a glob pattern.
The getter, deleted, and lister receive an MP4Tags instance
and the requested key name. The setter also receives the
desired value, which will be a list of strings.
The getter, setter, and deleter are used to implement __getitem__,
__setitem__, and __delitem__.
The lister is used to implement keys(). It should return a
list of keys that are actually in the MP4 instance, provided
by its associated getter. | [
"Register",
"a",
"new",
"key",
"mapping",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/easymp4.py#L54-L80 |
232,228 | quodlibet/mutagen | mutagen/easymp4.py | EasyMP4Tags.RegisterIntKey | def RegisterIntKey(cls, key, atomid, min_value=0, max_value=(2 ** 16) - 1):
"""Register a scalar integer key.
"""
def getter(tags, key):
return list(map(text_type, tags[atomid]))
def setter(tags, key, value):
clamp = lambda x: int(min(max(min_value, x), max_value))
tags[atomid] = [clamp(v) for v in map(int, value)]
def deleter(tags, key):
del(tags[atomid])
cls.RegisterKey(key, getter, setter, deleter) | python | def RegisterIntKey(cls, key, atomid, min_value=0, max_value=(2 ** 16) - 1):
def getter(tags, key):
return list(map(text_type, tags[atomid]))
def setter(tags, key, value):
clamp = lambda x: int(min(max(min_value, x), max_value))
tags[atomid] = [clamp(v) for v in map(int, value)]
def deleter(tags, key):
del(tags[atomid])
cls.RegisterKey(key, getter, setter, deleter) | [
"def",
"RegisterIntKey",
"(",
"cls",
",",
"key",
",",
"atomid",
",",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"(",
"2",
"**",
"16",
")",
"-",
"1",
")",
":",
"def",
"getter",
"(",
"tags",
",",
"key",
")",
":",
"return",
"list",
"(",
"map",
... | Register a scalar integer key. | [
"Register",
"a",
"scalar",
"integer",
"key",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/easymp4.py#L104-L118 |
232,229 | quodlibet/mutagen | mutagen/easymp4.py | EasyMP4Tags.pprint | def pprint(self):
"""Print tag key=value pairs."""
strings = []
for key in sorted(self.keys()):
values = self[key]
for value in values:
strings.append("%s=%s" % (key, value))
return "\n".join(strings) | python | def pprint(self):
strings = []
for key in sorted(self.keys()):
values = self[key]
for value in values:
strings.append("%s=%s" % (key, value))
return "\n".join(strings) | [
"def",
"pprint",
"(",
"self",
")",
":",
"strings",
"=",
"[",
"]",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"keys",
"(",
")",
")",
":",
"values",
"=",
"self",
"[",
"key",
"]",
"for",
"value",
"in",
"values",
":",
"strings",
".",
"append",
... | Print tag key=value pairs. | [
"Print",
"tag",
"key",
"=",
"value",
"pairs",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/easymp4.py#L223-L230 |
232,230 | quodlibet/mutagen | mutagen/id3/_util.py | _BitPaddedMixin.has_valid_padding | def has_valid_padding(value, bits=7):
"""Whether the padding bits are all zero"""
assert bits <= 8
mask = (((1 << (8 - bits)) - 1) << bits)
if isinstance(value, integer_types):
while value:
if value & mask:
return False
value >>= 8
elif isinstance(value, bytes):
for byte in bytearray(value):
if byte & mask:
return False
else:
raise TypeError
return True | python | def has_valid_padding(value, bits=7):
assert bits <= 8
mask = (((1 << (8 - bits)) - 1) << bits)
if isinstance(value, integer_types):
while value:
if value & mask:
return False
value >>= 8
elif isinstance(value, bytes):
for byte in bytearray(value):
if byte & mask:
return False
else:
raise TypeError
return True | [
"def",
"has_valid_padding",
"(",
"value",
",",
"bits",
"=",
"7",
")",
":",
"assert",
"bits",
"<=",
"8",
"mask",
"=",
"(",
"(",
"(",
"1",
"<<",
"(",
"8",
"-",
"bits",
")",
")",
"-",
"1",
")",
"<<",
"bits",
")",
"if",
"isinstance",
"(",
"value",
... | Whether the padding bits are all zero | [
"Whether",
"the",
"padding",
"bits",
"are",
"all",
"zero"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_util.py#L106-L125 |
232,231 | quodlibet/mutagen | mutagen/aac.py | _ADTSStream.find_stream | def find_stream(cls, fileobj, max_bytes):
"""Returns a possibly valid _ADTSStream or None.
Args:
max_bytes (int): maximum bytes to read
"""
r = BitReader(fileobj)
stream = cls(r)
if stream.sync(max_bytes):
stream.offset = (r.get_position() - 12) // 8
return stream | python | def find_stream(cls, fileobj, max_bytes):
r = BitReader(fileobj)
stream = cls(r)
if stream.sync(max_bytes):
stream.offset = (r.get_position() - 12) // 8
return stream | [
"def",
"find_stream",
"(",
"cls",
",",
"fileobj",
",",
"max_bytes",
")",
":",
"r",
"=",
"BitReader",
"(",
"fileobj",
")",
"stream",
"=",
"cls",
"(",
"r",
")",
"if",
"stream",
".",
"sync",
"(",
"max_bytes",
")",
":",
"stream",
".",
"offset",
"=",
"(... | Returns a possibly valid _ADTSStream or None.
Args:
max_bytes (int): maximum bytes to read | [
"Returns",
"a",
"possibly",
"valid",
"_ADTSStream",
"or",
"None",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/aac.py#L41-L52 |
232,232 | quodlibet/mutagen | mutagen/aac.py | _ADTSStream.sync | def sync(self, max_bytes):
"""Find the next sync.
Returns True if found."""
# at least 2 bytes for the sync
max_bytes = max(max_bytes, 2)
r = self._r
r.align()
while max_bytes > 0:
try:
b = r.bytes(1)
if b == b"\xff":
if r.bits(4) == 0xf:
return True
r.align()
max_bytes -= 2
else:
max_bytes -= 1
except BitReaderError:
return False
return False | python | def sync(self, max_bytes):
# at least 2 bytes for the sync
max_bytes = max(max_bytes, 2)
r = self._r
r.align()
while max_bytes > 0:
try:
b = r.bytes(1)
if b == b"\xff":
if r.bits(4) == 0xf:
return True
r.align()
max_bytes -= 2
else:
max_bytes -= 1
except BitReaderError:
return False
return False | [
"def",
"sync",
"(",
"self",
",",
"max_bytes",
")",
":",
"# at least 2 bytes for the sync",
"max_bytes",
"=",
"max",
"(",
"max_bytes",
",",
"2",
")",
"r",
"=",
"self",
".",
"_r",
"r",
".",
"align",
"(",
")",
"while",
"max_bytes",
">",
"0",
":",
"try",
... | Find the next sync.
Returns True if found. | [
"Find",
"the",
"next",
"sync",
".",
"Returns",
"True",
"if",
"found",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/aac.py#L54-L75 |
232,233 | quodlibet/mutagen | mutagen/dsf.py | _DSFID3.save | def save(self, filething=None, v2_version=4, v23_sep='/', padding=None):
"""Save ID3v2 data to the DSF file"""
fileobj = filething.fileobj
fileobj.seek(0)
dsd_header = DSDChunk(fileobj)
if dsd_header.offset_metdata_chunk == 0:
# create a new ID3 chunk at the end of the file
fileobj.seek(0, 2)
# store reference to ID3 location
dsd_header.offset_metdata_chunk = fileobj.tell()
dsd_header.write()
try:
data = self._prepare_data(
fileobj, dsd_header.offset_metdata_chunk, self.size,
v2_version, v23_sep, padding)
except ID3Error as e:
reraise(error, e, sys.exc_info()[2])
fileobj.seek(dsd_header.offset_metdata_chunk)
fileobj.write(data)
fileobj.truncate()
# Update total file size
dsd_header.total_size = fileobj.tell()
dsd_header.write() | python | def save(self, filething=None, v2_version=4, v23_sep='/', padding=None):
fileobj = filething.fileobj
fileobj.seek(0)
dsd_header = DSDChunk(fileobj)
if dsd_header.offset_metdata_chunk == 0:
# create a new ID3 chunk at the end of the file
fileobj.seek(0, 2)
# store reference to ID3 location
dsd_header.offset_metdata_chunk = fileobj.tell()
dsd_header.write()
try:
data = self._prepare_data(
fileobj, dsd_header.offset_metdata_chunk, self.size,
v2_version, v23_sep, padding)
except ID3Error as e:
reraise(error, e, sys.exc_info()[2])
fileobj.seek(dsd_header.offset_metdata_chunk)
fileobj.write(data)
fileobj.truncate()
# Update total file size
dsd_header.total_size = fileobj.tell()
dsd_header.write() | [
"def",
"save",
"(",
"self",
",",
"filething",
"=",
"None",
",",
"v2_version",
"=",
"4",
",",
"v23_sep",
"=",
"'/'",
",",
"padding",
"=",
"None",
")",
":",
"fileobj",
"=",
"filething",
".",
"fileobj",
"fileobj",
".",
"seek",
"(",
"0",
")",
"dsd_header... | Save ID3v2 data to the DSF file | [
"Save",
"ID3v2",
"data",
"to",
"the",
"DSF",
"file"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/dsf.py#L202-L230 |
232,234 | quodlibet/mutagen | mutagen/mp4/_atom.py | Atom.read | def read(self, fileobj):
"""Return if all data could be read and the atom payload"""
fileobj.seek(self._dataoffset, 0)
data = fileobj.read(self.datalength)
return len(data) == self.datalength, data | python | def read(self, fileobj):
fileobj.seek(self._dataoffset, 0)
data = fileobj.read(self.datalength)
return len(data) == self.datalength, data | [
"def",
"read",
"(",
"self",
",",
"fileobj",
")",
":",
"fileobj",
".",
"seek",
"(",
"self",
".",
"_dataoffset",
",",
"0",
")",
"data",
"=",
"fileobj",
".",
"read",
"(",
"self",
".",
"datalength",
")",
"return",
"len",
"(",
"data",
")",
"==",
"self",... | Return if all data could be read and the atom payload | [
"Return",
"if",
"all",
"data",
"could",
"be",
"read",
"and",
"the",
"atom",
"payload"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_atom.py#L84-L89 |
232,235 | quodlibet/mutagen | mutagen/mp4/_atom.py | Atom.render | def render(name, data):
"""Render raw atom data."""
# this raises OverflowError if Py_ssize_t can't handle the atom data
size = len(data) + 8
if size <= 0xFFFFFFFF:
return struct.pack(">I4s", size, name) + data
else:
return struct.pack(">I4sQ", 1, name, size + 8) + data | python | def render(name, data):
# this raises OverflowError if Py_ssize_t can't handle the atom data
size = len(data) + 8
if size <= 0xFFFFFFFF:
return struct.pack(">I4s", size, name) + data
else:
return struct.pack(">I4sQ", 1, name, size + 8) + data | [
"def",
"render",
"(",
"name",
",",
"data",
")",
":",
"# this raises OverflowError if Py_ssize_t can't handle the atom data",
"size",
"=",
"len",
"(",
"data",
")",
"+",
"8",
"if",
"size",
"<=",
"0xFFFFFFFF",
":",
"return",
"struct",
".",
"pack",
"(",
"\">I4s\"",
... | Render raw atom data. | [
"Render",
"raw",
"atom",
"data",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_atom.py#L92-L99 |
232,236 | quodlibet/mutagen | mutagen/mp4/_atom.py | Atom.findall | def findall(self, name, recursive=False):
"""Recursively find all child atoms by specified name."""
if self.children is not None:
for child in self.children:
if child.name == name:
yield child
if recursive:
for atom in child.findall(name, True):
yield atom | python | def findall(self, name, recursive=False):
if self.children is not None:
for child in self.children:
if child.name == name:
yield child
if recursive:
for atom in child.findall(name, True):
yield atom | [
"def",
"findall",
"(",
"self",
",",
"name",
",",
"recursive",
"=",
"False",
")",
":",
"if",
"self",
".",
"children",
"is",
"not",
"None",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"child",
".",
"name",
"==",
"name",
":",
"yield... | Recursively find all child atoms by specified name. | [
"Recursively",
"find",
"all",
"child",
"atoms",
"by",
"specified",
"name",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_atom.py#L101-L109 |
232,237 | quodlibet/mutagen | mutagen/mp4/_atom.py | Atoms.path | def path(self, *names):
"""Look up and return the complete path of an atom.
For example, atoms.path('moov', 'udta', 'meta') will return a
list of three atoms, corresponding to the moov, udta, and meta
atoms.
"""
path = [self]
for name in names:
path.append(path[-1][name, ])
return path[1:] | python | def path(self, *names):
path = [self]
for name in names:
path.append(path[-1][name, ])
return path[1:] | [
"def",
"path",
"(",
"self",
",",
"*",
"names",
")",
":",
"path",
"=",
"[",
"self",
"]",
"for",
"name",
"in",
"names",
":",
"path",
".",
"append",
"(",
"path",
"[",
"-",
"1",
"]",
"[",
"name",
",",
"]",
")",
"return",
"path",
"[",
"1",
":",
... | Look up and return the complete path of an atom.
For example, atoms.path('moov', 'udta', 'meta') will return a
list of three atoms, corresponding to the moov, udta, and meta
atoms. | [
"Look",
"up",
"and",
"return",
"the",
"complete",
"path",
"of",
"an",
"atom",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_atom.py#L156-L167 |
232,238 | quodlibet/mutagen | mutagen/asf/_attrs.py | ASFValue | def ASFValue(value, kind, **kwargs):
"""Create a tag value of a specific kind.
::
ASFValue(u"My Value", UNICODE)
:rtype: ASFBaseAttribute
:raises TypeError: in case a wrong type was passed
:raises ValueError: in case the value can't be be represented as ASFValue.
"""
try:
attr_type = ASFBaseAttribute._get_type(kind)
except KeyError:
raise ValueError("Unknown value type %r" % kind)
else:
return attr_type(value=value, **kwargs) | python | def ASFValue(value, kind, **kwargs):
try:
attr_type = ASFBaseAttribute._get_type(kind)
except KeyError:
raise ValueError("Unknown value type %r" % kind)
else:
return attr_type(value=value, **kwargs) | [
"def",
"ASFValue",
"(",
"value",
",",
"kind",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"attr_type",
"=",
"ASFBaseAttribute",
".",
"_get_type",
"(",
"kind",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Unknown value type %r\"",
"%",
... | Create a tag value of a specific kind.
::
ASFValue(u"My Value", UNICODE)
:rtype: ASFBaseAttribute
:raises TypeError: in case a wrong type was passed
:raises ValueError: in case the value can't be be represented as ASFValue. | [
"Create",
"a",
"tag",
"value",
"of",
"a",
"specific",
"kind",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/asf/_attrs.py#L422-L439 |
232,239 | quodlibet/mutagen | mutagen/id3/_specs.py | iter_text_fixups | def iter_text_fixups(data, encoding):
"""Yields a series of repaired text values for decoding"""
yield data
if encoding == Encoding.UTF16BE:
# wrong termination
yield data + b"\x00"
elif encoding == Encoding.UTF16:
# wrong termination
yield data + b"\x00"
# utf-16 is missing BOM, content is usually utf-16-le
yield codecs.BOM_UTF16_LE + data
# both cases combined
yield codecs.BOM_UTF16_LE + data + b"\x00" | python | def iter_text_fixups(data, encoding):
yield data
if encoding == Encoding.UTF16BE:
# wrong termination
yield data + b"\x00"
elif encoding == Encoding.UTF16:
# wrong termination
yield data + b"\x00"
# utf-16 is missing BOM, content is usually utf-16-le
yield codecs.BOM_UTF16_LE + data
# both cases combined
yield codecs.BOM_UTF16_LE + data + b"\x00" | [
"def",
"iter_text_fixups",
"(",
"data",
",",
"encoding",
")",
":",
"yield",
"data",
"if",
"encoding",
"==",
"Encoding",
".",
"UTF16BE",
":",
"# wrong termination",
"yield",
"data",
"+",
"b\"\\x00\"",
"elif",
"encoding",
"==",
"Encoding",
".",
"UTF16",
":",
"... | Yields a series of repaired text values for decoding | [
"Yields",
"a",
"series",
"of",
"repaired",
"text",
"values",
"for",
"decoding"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_specs.py#L442-L455 |
232,240 | quodlibet/mutagen | mutagen/_util.py | verify_fileobj | def verify_fileobj(fileobj, writable=False):
"""Verifies that the passed fileobj is a file like object which
we can use.
Args:
writable (bool): verify that the file object is writable as well
Raises:
ValueError: In case the object is not a file object that is readable
(or writable if required) or is not opened in bytes mode.
"""
try:
data = fileobj.read(0)
except Exception:
if not hasattr(fileobj, "read"):
raise ValueError("%r not a valid file object" % fileobj)
raise ValueError("Can't read from file object %r" % fileobj)
if not isinstance(data, bytes):
raise ValueError(
"file object %r not opened in binary mode" % fileobj)
if writable:
try:
fileobj.write(b"")
except Exception:
if not hasattr(fileobj, "write"):
raise ValueError("%r not a valid file object" % fileobj)
raise ValueError("Can't write to file object %r" % fileobj) | python | def verify_fileobj(fileobj, writable=False):
try:
data = fileobj.read(0)
except Exception:
if not hasattr(fileobj, "read"):
raise ValueError("%r not a valid file object" % fileobj)
raise ValueError("Can't read from file object %r" % fileobj)
if not isinstance(data, bytes):
raise ValueError(
"file object %r not opened in binary mode" % fileobj)
if writable:
try:
fileobj.write(b"")
except Exception:
if not hasattr(fileobj, "write"):
raise ValueError("%r not a valid file object" % fileobj)
raise ValueError("Can't write to file object %r" % fileobj) | [
"def",
"verify_fileobj",
"(",
"fileobj",
",",
"writable",
"=",
"False",
")",
":",
"try",
":",
"data",
"=",
"fileobj",
".",
"read",
"(",
"0",
")",
"except",
"Exception",
":",
"if",
"not",
"hasattr",
"(",
"fileobj",
",",
"\"read\"",
")",
":",
"raise",
... | Verifies that the passed fileobj is a file like object which
we can use.
Args:
writable (bool): verify that the file object is writable as well
Raises:
ValueError: In case the object is not a file object that is readable
(or writable if required) or is not opened in bytes mode. | [
"Verifies",
"that",
"the",
"passed",
"fileobj",
"is",
"a",
"file",
"like",
"object",
"which",
"we",
"can",
"use",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L57-L86 |
232,241 | quodlibet/mutagen | mutagen/_util.py | loadfile | def loadfile(method=True, writable=False, create=False):
"""A decorator for functions taking a `filething` as a first argument.
Passes a FileThing instance as the first argument to the wrapped function.
Args:
method (bool): If the wrapped functions is a method
writable (bool): If a filename is passed opens the file readwrite, if
passed a file object verifies that it is writable.
create (bool): If passed a filename that does not exist will create
a new empty file.
"""
def convert_file_args(args, kwargs):
filething = args[0] if args else None
filename = kwargs.pop("filename", None)
fileobj = kwargs.pop("fileobj", None)
return filething, filename, fileobj, args[1:], kwargs
def wrap(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
filething, filename, fileobj, args, kwargs = \
convert_file_args(args, kwargs)
with _openfile(self, filething, filename, fileobj,
writable, create) as h:
return func(self, h, *args, **kwargs)
@wraps(func)
def wrapper_func(*args, **kwargs):
filething, filename, fileobj, args, kwargs = \
convert_file_args(args, kwargs)
with _openfile(None, filething, filename, fileobj,
writable, create) as h:
return func(h, *args, **kwargs)
return wrapper if method else wrapper_func
return wrap | python | def loadfile(method=True, writable=False, create=False):
def convert_file_args(args, kwargs):
filething = args[0] if args else None
filename = kwargs.pop("filename", None)
fileobj = kwargs.pop("fileobj", None)
return filething, filename, fileobj, args[1:], kwargs
def wrap(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
filething, filename, fileobj, args, kwargs = \
convert_file_args(args, kwargs)
with _openfile(self, filething, filename, fileobj,
writable, create) as h:
return func(self, h, *args, **kwargs)
@wraps(func)
def wrapper_func(*args, **kwargs):
filething, filename, fileobj, args, kwargs = \
convert_file_args(args, kwargs)
with _openfile(None, filething, filename, fileobj,
writable, create) as h:
return func(h, *args, **kwargs)
return wrapper if method else wrapper_func
return wrap | [
"def",
"loadfile",
"(",
"method",
"=",
"True",
",",
"writable",
"=",
"False",
",",
"create",
"=",
"False",
")",
":",
"def",
"convert_file_args",
"(",
"args",
",",
"kwargs",
")",
":",
"filething",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"Non... | A decorator for functions taking a `filething` as a first argument.
Passes a FileThing instance as the first argument to the wrapped function.
Args:
method (bool): If the wrapped functions is a method
writable (bool): If a filename is passed opens the file readwrite, if
passed a file object verifies that it is writable.
create (bool): If passed a filename that does not exist will create
a new empty file. | [
"A",
"decorator",
"for",
"functions",
"taking",
"a",
"filething",
"as",
"a",
"first",
"argument",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L113-L152 |
232,242 | quodlibet/mutagen | mutagen/_util.py | convert_error | def convert_error(exc_src, exc_dest):
"""A decorator for reraising exceptions with a different type.
Mostly useful for IOError.
Args:
exc_src (type): The source exception type
exc_dest (type): The target exception type.
"""
def wrap(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc_dest:
raise
except exc_src as err:
reraise(exc_dest, err, sys.exc_info()[2])
return wrapper
return wrap | python | def convert_error(exc_src, exc_dest):
def wrap(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc_dest:
raise
except exc_src as err:
reraise(exc_dest, err, sys.exc_info()[2])
return wrapper
return wrap | [
"def",
"convert_error",
"(",
"exc_src",
",",
"exc_dest",
")",
":",
"def",
"wrap",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*"... | A decorator for reraising exceptions with a different type.
Mostly useful for IOError.
Args:
exc_src (type): The source exception type
exc_dest (type): The target exception type. | [
"A",
"decorator",
"for",
"reraising",
"exceptions",
"with",
"a",
"different",
"type",
".",
"Mostly",
"useful",
"for",
"IOError",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L155-L177 |
232,243 | quodlibet/mutagen | mutagen/_util.py | _openfile | def _openfile(instance, filething, filename, fileobj, writable, create):
"""yields a FileThing
Args:
filething: Either a file name, a file object or None
filename: Either a file name or None
fileobj: Either a file object or None
writable (bool): if the file should be opened
create (bool): if the file should be created if it doesn't exist.
implies writable
Raises:
MutagenError: In case opening the file failed
TypeError: in case neither a file name or a file object is passed
"""
assert not create or writable
# to allow stacked context managers, just pass the result through
if isinstance(filething, FileThing):
filename = filething.filename
fileobj = filething.fileobj
filething = None
if filething is not None:
if is_fileobj(filething):
fileobj = filething
elif hasattr(filething, "__fspath__"):
filename = filething.__fspath__()
if not isinstance(filename, (bytes, text_type)):
raise TypeError("expected __fspath__() to return a filename")
else:
filename = filething
if instance is not None:
# XXX: take "not writable" as loading the file..
if not writable:
instance.filename = filename
elif filename is None:
filename = getattr(instance, "filename", None)
if fileobj is not None:
verify_fileobj(fileobj, writable=writable)
yield FileThing(fileobj, filename, filename or fileobj_name(fileobj))
elif filename is not None:
verify_filename(filename)
inmemory_fileobj = False
try:
fileobj = open(filename, "rb+" if writable else "rb")
except IOError as e:
if writable and e.errno == errno.EOPNOTSUPP:
# Some file systems (gvfs over fuse) don't support opening
# files read/write. To make things still work read the whole
# file into an in-memory file like object and write it back
# later.
# https://github.com/quodlibet/mutagen/issues/300
try:
with open(filename, "rb") as fileobj:
fileobj = BytesIO(fileobj.read())
except IOError as e2:
raise MutagenError(e2)
inmemory_fileobj = True
elif create and e.errno == errno.ENOENT:
assert writable
try:
fileobj = open(filename, "wb+")
except IOError as e2:
raise MutagenError(e2)
else:
raise MutagenError(e)
with fileobj as fileobj:
yield FileThing(fileobj, filename, filename)
if inmemory_fileobj:
assert writable
data = fileobj.getvalue()
try:
with open(filename, "wb") as fileobj:
fileobj.write(data)
except IOError as e:
raise MutagenError(e)
else:
raise TypeError("Missing filename or fileobj argument") | python | def _openfile(instance, filething, filename, fileobj, writable, create):
assert not create or writable
# to allow stacked context managers, just pass the result through
if isinstance(filething, FileThing):
filename = filething.filename
fileobj = filething.fileobj
filething = None
if filething is not None:
if is_fileobj(filething):
fileobj = filething
elif hasattr(filething, "__fspath__"):
filename = filething.__fspath__()
if not isinstance(filename, (bytes, text_type)):
raise TypeError("expected __fspath__() to return a filename")
else:
filename = filething
if instance is not None:
# XXX: take "not writable" as loading the file..
if not writable:
instance.filename = filename
elif filename is None:
filename = getattr(instance, "filename", None)
if fileobj is not None:
verify_fileobj(fileobj, writable=writable)
yield FileThing(fileobj, filename, filename or fileobj_name(fileobj))
elif filename is not None:
verify_filename(filename)
inmemory_fileobj = False
try:
fileobj = open(filename, "rb+" if writable else "rb")
except IOError as e:
if writable and e.errno == errno.EOPNOTSUPP:
# Some file systems (gvfs over fuse) don't support opening
# files read/write. To make things still work read the whole
# file into an in-memory file like object and write it back
# later.
# https://github.com/quodlibet/mutagen/issues/300
try:
with open(filename, "rb") as fileobj:
fileobj = BytesIO(fileobj.read())
except IOError as e2:
raise MutagenError(e2)
inmemory_fileobj = True
elif create and e.errno == errno.ENOENT:
assert writable
try:
fileobj = open(filename, "wb+")
except IOError as e2:
raise MutagenError(e2)
else:
raise MutagenError(e)
with fileobj as fileobj:
yield FileThing(fileobj, filename, filename)
if inmemory_fileobj:
assert writable
data = fileobj.getvalue()
try:
with open(filename, "wb") as fileobj:
fileobj.write(data)
except IOError as e:
raise MutagenError(e)
else:
raise TypeError("Missing filename or fileobj argument") | [
"def",
"_openfile",
"(",
"instance",
",",
"filething",
",",
"filename",
",",
"fileobj",
",",
"writable",
",",
"create",
")",
":",
"assert",
"not",
"create",
"or",
"writable",
"# to allow stacked context managers, just pass the result through",
"if",
"isinstance",
"(",... | yields a FileThing
Args:
filething: Either a file name, a file object or None
filename: Either a file name or None
fileobj: Either a file object or None
writable (bool): if the file should be opened
create (bool): if the file should be created if it doesn't exist.
implies writable
Raises:
MutagenError: In case opening the file failed
TypeError: in case neither a file name or a file object is passed | [
"yields",
"a",
"FileThing"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L187-L270 |
232,244 | quodlibet/mutagen | mutagen/_util.py | hashable | def hashable(cls):
"""Makes sure the class is hashable.
Needs a working __eq__ and __hash__ and will add a __ne__.
"""
# py2
assert "__hash__" in cls.__dict__
# py3
assert cls.__dict__["__hash__"] is not None
assert "__eq__" in cls.__dict__
cls.__ne__ = lambda self, other: not self.__eq__(other)
return cls | python | def hashable(cls):
# py2
assert "__hash__" in cls.__dict__
# py3
assert cls.__dict__["__hash__"] is not None
assert "__eq__" in cls.__dict__
cls.__ne__ = lambda self, other: not self.__eq__(other)
return cls | [
"def",
"hashable",
"(",
"cls",
")",
":",
"# py2",
"assert",
"\"__hash__\"",
"in",
"cls",
".",
"__dict__",
"# py3",
"assert",
"cls",
".",
"__dict__",
"[",
"\"__hash__\"",
"]",
"is",
"not",
"None",
"assert",
"\"__eq__\"",
"in",
"cls",
".",
"__dict__",
"cls",... | Makes sure the class is hashable.
Needs a working __eq__ and __hash__ and will add a __ne__. | [
"Makes",
"sure",
"the",
"class",
"is",
"hashable",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L299-L313 |
232,245 | quodlibet/mutagen | mutagen/_util.py | enum | def enum(cls):
"""A decorator for creating an int enum class.
Makes the values a subclass of the type and implements repr/str.
The new class will be a subclass of int.
Args:
cls (type): The class to convert to an enum
Returns:
type: A new class
::
@enum
class Foo(object):
FOO = 1
BAR = 2
"""
assert cls.__bases__ == (object,)
d = dict(cls.__dict__)
new_type = type(cls.__name__, (int,), d)
new_type.__module__ = cls.__module__
map_ = {}
for key, value in iteritems(d):
if key.upper() == key and isinstance(value, integer_types):
value_instance = new_type(value)
setattr(new_type, key, value_instance)
map_[value] = key
def str_(self):
if self in map_:
return "%s.%s" % (type(self).__name__, map_[self])
return "%d" % int(self)
def repr_(self):
if self in map_:
return "<%s.%s: %d>" % (type(self).__name__, map_[self], int(self))
return "%d" % int(self)
setattr(new_type, "__repr__", repr_)
setattr(new_type, "__str__", str_)
return new_type | python | def enum(cls):
assert cls.__bases__ == (object,)
d = dict(cls.__dict__)
new_type = type(cls.__name__, (int,), d)
new_type.__module__ = cls.__module__
map_ = {}
for key, value in iteritems(d):
if key.upper() == key and isinstance(value, integer_types):
value_instance = new_type(value)
setattr(new_type, key, value_instance)
map_[value] = key
def str_(self):
if self in map_:
return "%s.%s" % (type(self).__name__, map_[self])
return "%d" % int(self)
def repr_(self):
if self in map_:
return "<%s.%s: %d>" % (type(self).__name__, map_[self], int(self))
return "%d" % int(self)
setattr(new_type, "__repr__", repr_)
setattr(new_type, "__str__", str_)
return new_type | [
"def",
"enum",
"(",
"cls",
")",
":",
"assert",
"cls",
".",
"__bases__",
"==",
"(",
"object",
",",
")",
"d",
"=",
"dict",
"(",
"cls",
".",
"__dict__",
")",
"new_type",
"=",
"type",
"(",
"cls",
".",
"__name__",
",",
"(",
"int",
",",
")",
",",
"d"... | A decorator for creating an int enum class.
Makes the values a subclass of the type and implements repr/str.
The new class will be a subclass of int.
Args:
cls (type): The class to convert to an enum
Returns:
type: A new class
::
@enum
class Foo(object):
FOO = 1
BAR = 2 | [
"A",
"decorator",
"for",
"creating",
"an",
"int",
"enum",
"class",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L316-L362 |
232,246 | quodlibet/mutagen | mutagen/_util.py | flags | def flags(cls):
"""A decorator for creating an int flags class.
Makes the values a subclass of the type and implements repr/str.
The new class will be a subclass of int.
Args:
cls (type): The class to convert to an flags
Returns:
type: A new class
::
@flags
class Foo(object):
FOO = 1
BAR = 2
"""
assert cls.__bases__ == (object,)
d = dict(cls.__dict__)
new_type = type(cls.__name__, (int,), d)
new_type.__module__ = cls.__module__
map_ = {}
for key, value in iteritems(d):
if key.upper() == key and isinstance(value, integer_types):
value_instance = new_type(value)
setattr(new_type, key, value_instance)
map_[value] = key
def str_(self):
value = int(self)
matches = []
for k, v in map_.items():
if value & k:
matches.append("%s.%s" % (type(self).__name__, v))
value &= ~k
if value != 0 or not matches:
matches.append(text_type(value))
return " | ".join(matches)
def repr_(self):
return "<%s: %d>" % (str(self), int(self))
setattr(new_type, "__repr__", repr_)
setattr(new_type, "__str__", str_)
return new_type | python | def flags(cls):
assert cls.__bases__ == (object,)
d = dict(cls.__dict__)
new_type = type(cls.__name__, (int,), d)
new_type.__module__ = cls.__module__
map_ = {}
for key, value in iteritems(d):
if key.upper() == key and isinstance(value, integer_types):
value_instance = new_type(value)
setattr(new_type, key, value_instance)
map_[value] = key
def str_(self):
value = int(self)
matches = []
for k, v in map_.items():
if value & k:
matches.append("%s.%s" % (type(self).__name__, v))
value &= ~k
if value != 0 or not matches:
matches.append(text_type(value))
return " | ".join(matches)
def repr_(self):
return "<%s: %d>" % (str(self), int(self))
setattr(new_type, "__repr__", repr_)
setattr(new_type, "__str__", str_)
return new_type | [
"def",
"flags",
"(",
"cls",
")",
":",
"assert",
"cls",
".",
"__bases__",
"==",
"(",
"object",
",",
")",
"d",
"=",
"dict",
"(",
"cls",
".",
"__dict__",
")",
"new_type",
"=",
"type",
"(",
"cls",
".",
"__name__",
",",
"(",
"int",
",",
")",
",",
"d... | A decorator for creating an int flags class.
Makes the values a subclass of the type and implements repr/str.
The new class will be a subclass of int.
Args:
cls (type): The class to convert to an flags
Returns:
type: A new class
::
@flags
class Foo(object):
FOO = 1
BAR = 2 | [
"A",
"decorator",
"for",
"creating",
"an",
"int",
"flags",
"class",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L365-L416 |
232,247 | quodlibet/mutagen | mutagen/_util.py | get_size | def get_size(fileobj):
"""Returns the size of the file.
The position when passed in will be preserved if no error occurs.
Args:
fileobj (fileobj)
Returns:
int: The size of the file
Raises:
IOError
"""
old_pos = fileobj.tell()
try:
fileobj.seek(0, 2)
return fileobj.tell()
finally:
fileobj.seek(old_pos, 0) | python | def get_size(fileobj):
old_pos = fileobj.tell()
try:
fileobj.seek(0, 2)
return fileobj.tell()
finally:
fileobj.seek(old_pos, 0) | [
"def",
"get_size",
"(",
"fileobj",
")",
":",
"old_pos",
"=",
"fileobj",
".",
"tell",
"(",
")",
"try",
":",
"fileobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"return",
"fileobj",
".",
"tell",
"(",
")",
"finally",
":",
"fileobj",
".",
"seek",
"(",
"... | Returns the size of the file.
The position when passed in will be preserved if no error occurs.
Args:
fileobj (fileobj)
Returns:
int: The size of the file
Raises:
IOError | [
"Returns",
"the",
"size",
"of",
"the",
"file",
".",
"The",
"position",
"when",
"passed",
"in",
"will",
"be",
"preserved",
"if",
"no",
"error",
"occurs",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L618-L635 |
232,248 | quodlibet/mutagen | mutagen/_util.py | read_full | def read_full(fileobj, size):
"""Like fileobj.read but raises IOError if not all requested data is
returned.
If you want to distinguish IOError and the EOS case, better handle
the error yourself instead of using this.
Args:
fileobj (fileobj)
size (int): amount of bytes to read
Raises:
IOError: In case read fails or not enough data is read
"""
if size < 0:
raise ValueError("size must not be negative")
data = fileobj.read(size)
if len(data) != size:
raise IOError
return data | python | def read_full(fileobj, size):
if size < 0:
raise ValueError("size must not be negative")
data = fileobj.read(size)
if len(data) != size:
raise IOError
return data | [
"def",
"read_full",
"(",
"fileobj",
",",
"size",
")",
":",
"if",
"size",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"size must not be negative\"",
")",
"data",
"=",
"fileobj",
".",
"read",
"(",
"size",
")",
"if",
"len",
"(",
"data",
")",
"!=",
"size"... | Like fileobj.read but raises IOError if not all requested data is
returned.
If you want to distinguish IOError and the EOS case, better handle
the error yourself instead of using this.
Args:
fileobj (fileobj)
size (int): amount of bytes to read
Raises:
IOError: In case read fails or not enough data is read | [
"Like",
"fileobj",
".",
"read",
"but",
"raises",
"IOError",
"if",
"not",
"all",
"requested",
"data",
"is",
"returned",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L638-L658 |
232,249 | quodlibet/mutagen | mutagen/_util.py | resize_file | def resize_file(fobj, diff, BUFFER_SIZE=2 ** 16):
"""Resize a file by `diff`.
New space will be filled with zeros.
Args:
fobj (fileobj)
diff (int): amount of size to change
Raises:
IOError
"""
fobj.seek(0, 2)
filesize = fobj.tell()
if diff < 0:
if filesize + diff < 0:
raise ValueError
# truncate flushes internally
fobj.truncate(filesize + diff)
elif diff > 0:
try:
while diff:
addsize = min(BUFFER_SIZE, diff)
fobj.write(b"\x00" * addsize)
diff -= addsize
fobj.flush()
except IOError as e:
if e.errno == errno.ENOSPC:
# To reduce the chance of corrupt files in case of missing
# space try to revert the file expansion back. Of course
# in reality every in-file-write can also fail due to COW etc.
# Note: IOError gets also raised in flush() due to buffering
fobj.truncate(filesize)
raise | python | def resize_file(fobj, diff, BUFFER_SIZE=2 ** 16):
fobj.seek(0, 2)
filesize = fobj.tell()
if diff < 0:
if filesize + diff < 0:
raise ValueError
# truncate flushes internally
fobj.truncate(filesize + diff)
elif diff > 0:
try:
while diff:
addsize = min(BUFFER_SIZE, diff)
fobj.write(b"\x00" * addsize)
diff -= addsize
fobj.flush()
except IOError as e:
if e.errno == errno.ENOSPC:
# To reduce the chance of corrupt files in case of missing
# space try to revert the file expansion back. Of course
# in reality every in-file-write can also fail due to COW etc.
# Note: IOError gets also raised in flush() due to buffering
fobj.truncate(filesize)
raise | [
"def",
"resize_file",
"(",
"fobj",
",",
"diff",
",",
"BUFFER_SIZE",
"=",
"2",
"**",
"16",
")",
":",
"fobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"filesize",
"=",
"fobj",
".",
"tell",
"(",
")",
"if",
"diff",
"<",
"0",
":",
"if",
"filesize",
"+"... | Resize a file by `diff`.
New space will be filled with zeros.
Args:
fobj (fileobj)
diff (int): amount of size to change
Raises:
IOError | [
"Resize",
"a",
"file",
"by",
"diff",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L744-L778 |
232,250 | quodlibet/mutagen | mutagen/_util.py | insert_bytes | def insert_bytes(fobj, size, offset, BUFFER_SIZE=2 ** 16):
"""Insert size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
Args:
fobj (fileobj)
size (int): The amount of space to insert
offset (int): The offset at which to insert the space
Raises:
IOError
"""
if size < 0 or offset < 0:
raise ValueError
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset
if movesize < 0:
raise ValueError
resize_file(fobj, size, BUFFER_SIZE)
if mmap is not None:
try:
mmap_move(fobj, offset + size, offset, movesize)
except mmap.error:
fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE)
else:
fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE) | python | def insert_bytes(fobj, size, offset, BUFFER_SIZE=2 ** 16):
if size < 0 or offset < 0:
raise ValueError
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset
if movesize < 0:
raise ValueError
resize_file(fobj, size, BUFFER_SIZE)
if mmap is not None:
try:
mmap_move(fobj, offset + size, offset, movesize)
except mmap.error:
fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE)
else:
fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE) | [
"def",
"insert_bytes",
"(",
"fobj",
",",
"size",
",",
"offset",
",",
"BUFFER_SIZE",
"=",
"2",
"**",
"16",
")",
":",
"if",
"size",
"<",
"0",
"or",
"offset",
"<",
"0",
":",
"raise",
"ValueError",
"fobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"files... | Insert size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
Args:
fobj (fileobj)
size (int): The amount of space to insert
offset (int): The offset at which to insert the space
Raises:
IOError | [
"Insert",
"size",
"bytes",
"of",
"empty",
"space",
"starting",
"at",
"offset",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L824-L857 |
232,251 | quodlibet/mutagen | mutagen/_util.py | resize_bytes | def resize_bytes(fobj, old_size, new_size, offset):
"""Resize an area in a file adding and deleting at the end of it.
Does nothing if no resizing is needed.
Args:
fobj (fileobj)
old_size (int): The area starting at offset
new_size (int): The new size of the area
offset (int): The start of the area
Raises:
IOError
"""
if new_size < old_size:
delete_size = old_size - new_size
delete_at = offset + new_size
delete_bytes(fobj, delete_size, delete_at)
elif new_size > old_size:
insert_size = new_size - old_size
insert_at = offset + old_size
insert_bytes(fobj, insert_size, insert_at) | python | def resize_bytes(fobj, old_size, new_size, offset):
if new_size < old_size:
delete_size = old_size - new_size
delete_at = offset + new_size
delete_bytes(fobj, delete_size, delete_at)
elif new_size > old_size:
insert_size = new_size - old_size
insert_at = offset + old_size
insert_bytes(fobj, insert_size, insert_at) | [
"def",
"resize_bytes",
"(",
"fobj",
",",
"old_size",
",",
"new_size",
",",
"offset",
")",
":",
"if",
"new_size",
"<",
"old_size",
":",
"delete_size",
"=",
"old_size",
"-",
"new_size",
"delete_at",
"=",
"offset",
"+",
"new_size",
"delete_bytes",
"(",
"fobj",
... | Resize an area in a file adding and deleting at the end of it.
Does nothing if no resizing is needed.
Args:
fobj (fileobj)
old_size (int): The area starting at offset
new_size (int): The new size of the area
offset (int): The start of the area
Raises:
IOError | [
"Resize",
"an",
"area",
"in",
"a",
"file",
"adding",
"and",
"deleting",
"at",
"the",
"end",
"of",
"it",
".",
"Does",
"nothing",
"if",
"no",
"resizing",
"is",
"needed",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L896-L916 |
232,252 | quodlibet/mutagen | mutagen/_util.py | decode_terminated | def decode_terminated(data, encoding, strict=True):
"""Returns the decoded data until the first NULL terminator
and all data after it.
Args:
data (bytes): data to decode
encoding (str): The codec to use
strict (bool): If True will raise ValueError in case no NULL is found
but the available data decoded successfully.
Returns:
Tuple[`text`, `bytes`]: A tuple containing the decoded text and the
remaining data after the found NULL termination.
Raises:
UnicodeError: In case the data can't be decoded.
LookupError:In case the encoding is not found.
ValueError: In case the data isn't null terminated (even if it is
encoded correctly) except if strict is False, then the decoded
string will be returned anyway.
"""
codec_info = codecs.lookup(encoding)
# normalize encoding name so we can compare by name
encoding = codec_info.name
# fast path
if encoding in ("utf-8", "iso8859-1"):
index = data.find(b"\x00")
if index == -1:
# make sure we raise UnicodeError first, like in the slow path
res = data.decode(encoding), b""
if strict:
raise ValueError("not null terminated")
else:
return res
return data[:index].decode(encoding), data[index + 1:]
# slow path
decoder = codec_info.incrementaldecoder()
r = []
for i, b in enumerate(iterbytes(data)):
c = decoder.decode(b)
if c == u"\x00":
return u"".join(r), data[i + 1:]
r.append(c)
else:
# make sure the decoder is finished
r.append(decoder.decode(b"", True))
if strict:
raise ValueError("not null terminated")
return u"".join(r), b"" | python | def decode_terminated(data, encoding, strict=True):
codec_info = codecs.lookup(encoding)
# normalize encoding name so we can compare by name
encoding = codec_info.name
# fast path
if encoding in ("utf-8", "iso8859-1"):
index = data.find(b"\x00")
if index == -1:
# make sure we raise UnicodeError first, like in the slow path
res = data.decode(encoding), b""
if strict:
raise ValueError("not null terminated")
else:
return res
return data[:index].decode(encoding), data[index + 1:]
# slow path
decoder = codec_info.incrementaldecoder()
r = []
for i, b in enumerate(iterbytes(data)):
c = decoder.decode(b)
if c == u"\x00":
return u"".join(r), data[i + 1:]
r.append(c)
else:
# make sure the decoder is finished
r.append(decoder.decode(b"", True))
if strict:
raise ValueError("not null terminated")
return u"".join(r), b"" | [
"def",
"decode_terminated",
"(",
"data",
",",
"encoding",
",",
"strict",
"=",
"True",
")",
":",
"codec_info",
"=",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
"# normalize encoding name so we can compare by name",
"encoding",
"=",
"codec_info",
".",
"name",
"# ... | Returns the decoded data until the first NULL terminator
and all data after it.
Args:
data (bytes): data to decode
encoding (str): The codec to use
strict (bool): If True will raise ValueError in case no NULL is found
but the available data decoded successfully.
Returns:
Tuple[`text`, `bytes`]: A tuple containing the decoded text and the
remaining data after the found NULL termination.
Raises:
UnicodeError: In case the data can't be decoded.
LookupError:In case the encoding is not found.
ValueError: In case the data isn't null terminated (even if it is
encoded correctly) except if strict is False, then the decoded
string will be returned anyway. | [
"Returns",
"the",
"decoded",
"data",
"until",
"the",
"first",
"NULL",
"terminator",
"and",
"all",
"data",
"after",
"it",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L974-L1025 |
232,253 | quodlibet/mutagen | mutagen/_util.py | BitReader.bits | def bits(self, count):
"""Reads `count` bits and returns an uint, MSB read first.
May raise BitReaderError if not enough data could be read or
IOError by the underlying file object.
"""
if count < 0:
raise ValueError
if count > self._bits:
n_bytes = (count - self._bits + 7) // 8
data = self._fileobj.read(n_bytes)
if len(data) != n_bytes:
raise BitReaderError("not enough data")
for b in bytearray(data):
self._buffer = (self._buffer << 8) | b
self._bits += n_bytes * 8
self._bits -= count
value = self._buffer >> self._bits
self._buffer &= (1 << self._bits) - 1
assert self._bits < 8
return value | python | def bits(self, count):
if count < 0:
raise ValueError
if count > self._bits:
n_bytes = (count - self._bits + 7) // 8
data = self._fileobj.read(n_bytes)
if len(data) != n_bytes:
raise BitReaderError("not enough data")
for b in bytearray(data):
self._buffer = (self._buffer << 8) | b
self._bits += n_bytes * 8
self._bits -= count
value = self._buffer >> self._bits
self._buffer &= (1 << self._bits) - 1
assert self._bits < 8
return value | [
"def",
"bits",
"(",
"self",
",",
"count",
")",
":",
"if",
"count",
"<",
"0",
":",
"raise",
"ValueError",
"if",
"count",
">",
"self",
".",
"_bits",
":",
"n_bytes",
"=",
"(",
"count",
"-",
"self",
".",
"_bits",
"+",
"7",
")",
"//",
"8",
"data",
"... | Reads `count` bits and returns an uint, MSB read first.
May raise BitReaderError if not enough data could be read or
IOError by the underlying file object. | [
"Reads",
"count",
"bits",
"and",
"returns",
"an",
"uint",
"MSB",
"read",
"first",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L1040-L1063 |
232,254 | quodlibet/mutagen | mutagen/_util.py | BitReader.bytes | def bytes(self, count):
"""Returns a bytearray of length `count`. Works unaligned."""
if count < 0:
raise ValueError
# fast path
if self._bits == 0:
data = self._fileobj.read(count)
if len(data) != count:
raise BitReaderError("not enough data")
return data
return bytes(bytearray(self.bits(8) for _ in xrange(count))) | python | def bytes(self, count):
if count < 0:
raise ValueError
# fast path
if self._bits == 0:
data = self._fileobj.read(count)
if len(data) != count:
raise BitReaderError("not enough data")
return data
return bytes(bytearray(self.bits(8) for _ in xrange(count))) | [
"def",
"bytes",
"(",
"self",
",",
"count",
")",
":",
"if",
"count",
"<",
"0",
":",
"raise",
"ValueError",
"# fast path",
"if",
"self",
".",
"_bits",
"==",
"0",
":",
"data",
"=",
"self",
".",
"_fileobj",
".",
"read",
"(",
"count",
")",
"if",
"len",
... | Returns a bytearray of length `count`. Works unaligned. | [
"Returns",
"a",
"bytearray",
"of",
"length",
"count",
".",
"Works",
"unaligned",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L1065-L1078 |
232,255 | quodlibet/mutagen | mutagen/_util.py | BitReader.skip | def skip(self, count):
"""Skip `count` bits.
Might raise BitReaderError if there wasn't enough data to skip,
but might also fail on the next bits() instead.
"""
if count < 0:
raise ValueError
if count <= self._bits:
self.bits(count)
else:
count -= self.align()
n_bytes = count // 8
self._fileobj.seek(n_bytes, 1)
count -= n_bytes * 8
self.bits(count) | python | def skip(self, count):
if count < 0:
raise ValueError
if count <= self._bits:
self.bits(count)
else:
count -= self.align()
n_bytes = count // 8
self._fileobj.seek(n_bytes, 1)
count -= n_bytes * 8
self.bits(count) | [
"def",
"skip",
"(",
"self",
",",
"count",
")",
":",
"if",
"count",
"<",
"0",
":",
"raise",
"ValueError",
"if",
"count",
"<=",
"self",
".",
"_bits",
":",
"self",
".",
"bits",
"(",
"count",
")",
"else",
":",
"count",
"-=",
"self",
".",
"align",
"("... | Skip `count` bits.
Might raise BitReaderError if there wasn't enough data to skip,
but might also fail on the next bits() instead. | [
"Skip",
"count",
"bits",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L1080-L1097 |
232,256 | quodlibet/mutagen | mutagen/_util.py | BitReader.align | def align(self):
"""Align to the next byte, returns the amount of bits skipped"""
bits = self._bits
self._buffer = 0
self._bits = 0
return bits | python | def align(self):
bits = self._bits
self._buffer = 0
self._bits = 0
return bits | [
"def",
"align",
"(",
"self",
")",
":",
"bits",
"=",
"self",
".",
"_bits",
"self",
".",
"_buffer",
"=",
"0",
"self",
".",
"_bits",
"=",
"0",
"return",
"bits"
] | Align to the next byte, returns the amount of bits skipped | [
"Align",
"to",
"the",
"next",
"byte",
"returns",
"the",
"amount",
"of",
"bits",
"skipped"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L1104-L1110 |
232,257 | quodlibet/mutagen | mutagen/_senf/_argv.py | _get_win_argv | def _get_win_argv():
"""Returns a unicode argv under Windows and standard sys.argv otherwise
Returns:
List[`fsnative`]
"""
assert is_win
argc = ctypes.c_int()
try:
argv = winapi.CommandLineToArgvW(
winapi.GetCommandLineW(), ctypes.byref(argc))
except WindowsError:
return []
if not argv:
return []
res = argv[max(0, argc.value - len(sys.argv)):argc.value]
winapi.LocalFree(argv)
return res | python | def _get_win_argv():
assert is_win
argc = ctypes.c_int()
try:
argv = winapi.CommandLineToArgvW(
winapi.GetCommandLineW(), ctypes.byref(argc))
except WindowsError:
return []
if not argv:
return []
res = argv[max(0, argc.value - len(sys.argv)):argc.value]
winapi.LocalFree(argv)
return res | [
"def",
"_get_win_argv",
"(",
")",
":",
"assert",
"is_win",
"argc",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"try",
":",
"argv",
"=",
"winapi",
".",
"CommandLineToArgvW",
"(",
"winapi",
".",
"GetCommandLineW",
"(",
")",
",",
"ctypes",
".",
"byref",
"(",
"... | Returns a unicode argv under Windows and standard sys.argv otherwise
Returns:
List[`fsnative`] | [
"Returns",
"a",
"unicode",
"argv",
"under",
"Windows",
"and",
"standard",
"sys",
".",
"argv",
"otherwise"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_argv.py#L36-L59 |
232,258 | quodlibet/mutagen | mutagen/_senf/_stdlib.py | _get_userdir | def _get_userdir(user=None):
"""Returns the user dir or None"""
if user is not None and not isinstance(user, fsnative):
raise TypeError
if is_win:
if "HOME" in environ:
path = environ["HOME"]
elif "USERPROFILE" in environ:
path = environ["USERPROFILE"]
elif "HOMEPATH" in environ and "HOMEDRIVE" in environ:
path = os.path.join(environ["HOMEDRIVE"], environ["HOMEPATH"])
else:
return
if user is None:
return path
else:
return os.path.join(os.path.dirname(path), user)
else:
import pwd
if user is None:
if "HOME" in environ:
return environ["HOME"]
else:
try:
return path2fsn(pwd.getpwuid(os.getuid()).pw_dir)
except KeyError:
return
else:
try:
return path2fsn(pwd.getpwnam(user).pw_dir)
except KeyError:
return | python | def _get_userdir(user=None):
if user is not None and not isinstance(user, fsnative):
raise TypeError
if is_win:
if "HOME" in environ:
path = environ["HOME"]
elif "USERPROFILE" in environ:
path = environ["USERPROFILE"]
elif "HOMEPATH" in environ and "HOMEDRIVE" in environ:
path = os.path.join(environ["HOMEDRIVE"], environ["HOMEPATH"])
else:
return
if user is None:
return path
else:
return os.path.join(os.path.dirname(path), user)
else:
import pwd
if user is None:
if "HOME" in environ:
return environ["HOME"]
else:
try:
return path2fsn(pwd.getpwuid(os.getuid()).pw_dir)
except KeyError:
return
else:
try:
return path2fsn(pwd.getpwnam(user).pw_dir)
except KeyError:
return | [
"def",
"_get_userdir",
"(",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"user",
",",
"fsnative",
")",
":",
"raise",
"TypeError",
"if",
"is_win",
":",
"if",
"\"HOME\"",
"in",
"environ",
":",
"path",... | Returns the user dir or None | [
"Returns",
"the",
"user",
"dir",
"or",
"None"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_stdlib.py#L53-L88 |
232,259 | quodlibet/mutagen | mutagen/ogg.py | OggPage.write | def write(self):
"""Return a string encoding of the page header and data.
A ValueError is raised if the data is too big to fit in a
single page.
"""
data = [
struct.pack("<4sBBqIIi", b"OggS", self.version, self.__type_flags,
self.position, self.serial, self.sequence, 0)
]
lacing_data = []
for datum in self.packets:
quot, rem = divmod(len(datum), 255)
lacing_data.append(b"\xff" * quot + chr_(rem))
lacing_data = b"".join(lacing_data)
if not self.complete and lacing_data.endswith(b"\x00"):
lacing_data = lacing_data[:-1]
data.append(chr_(len(lacing_data)))
data.append(lacing_data)
data.extend(self.packets)
data = b"".join(data)
# Python's CRC is swapped relative to Ogg's needs.
# crc32 returns uint prior to py2.6 on some platforms, so force uint
crc = (~zlib.crc32(data.translate(cdata.bitswap), -1)) & 0xffffffff
# Although we're using to_uint_be, this actually makes the CRC
# a proper le integer, since Python's CRC is byteswapped.
crc = cdata.to_uint_be(crc).translate(cdata.bitswap)
data = data[:22] + crc + data[26:]
return data | python | def write(self):
data = [
struct.pack("<4sBBqIIi", b"OggS", self.version, self.__type_flags,
self.position, self.serial, self.sequence, 0)
]
lacing_data = []
for datum in self.packets:
quot, rem = divmod(len(datum), 255)
lacing_data.append(b"\xff" * quot + chr_(rem))
lacing_data = b"".join(lacing_data)
if not self.complete and lacing_data.endswith(b"\x00"):
lacing_data = lacing_data[:-1]
data.append(chr_(len(lacing_data)))
data.append(lacing_data)
data.extend(self.packets)
data = b"".join(data)
# Python's CRC is swapped relative to Ogg's needs.
# crc32 returns uint prior to py2.6 on some platforms, so force uint
crc = (~zlib.crc32(data.translate(cdata.bitswap), -1)) & 0xffffffff
# Although we're using to_uint_be, this actually makes the CRC
# a proper le integer, since Python's CRC is byteswapped.
crc = cdata.to_uint_be(crc).translate(cdata.bitswap)
data = data[:22] + crc + data[26:]
return data | [
"def",
"write",
"(",
"self",
")",
":",
"data",
"=",
"[",
"struct",
".",
"pack",
"(",
"\"<4sBBqIIi\"",
",",
"b\"OggS\"",
",",
"self",
".",
"version",
",",
"self",
".",
"__type_flags",
",",
"self",
".",
"position",
",",
"self",
".",
"serial",
",",
"sel... | Return a string encoding of the page header and data.
A ValueError is raised if the data is too big to fit in a
single page. | [
"Return",
"a",
"string",
"encoding",
"of",
"the",
"page",
"header",
"and",
"data",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L133-L164 |
232,260 | quodlibet/mutagen | mutagen/ogg.py | OggPage.size | def size(self):
"""Total frame size."""
size = 27 # Initial header size
for datum in self.packets:
quot, rem = divmod(len(datum), 255)
size += quot + 1
if not self.complete and rem == 0:
# Packet contains a multiple of 255 bytes and is not
# terminated, so we don't have a \x00 at the end.
size -= 1
size += sum(map(len, self.packets))
return size | python | def size(self):
size = 27 # Initial header size
for datum in self.packets:
quot, rem = divmod(len(datum), 255)
size += quot + 1
if not self.complete and rem == 0:
# Packet contains a multiple of 255 bytes and is not
# terminated, so we don't have a \x00 at the end.
size -= 1
size += sum(map(len, self.packets))
return size | [
"def",
"size",
"(",
"self",
")",
":",
"size",
"=",
"27",
"# Initial header size",
"for",
"datum",
"in",
"self",
".",
"packets",
":",
"quot",
",",
"rem",
"=",
"divmod",
"(",
"len",
"(",
"datum",
")",
",",
"255",
")",
"size",
"+=",
"quot",
"+",
"1",
... | Total frame size. | [
"Total",
"frame",
"size",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L167-L179 |
232,261 | quodlibet/mutagen | mutagen/ogg.py | OggPage.renumber | def renumber(fileobj, serial, start):
"""Renumber pages belonging to a specified logical stream.
fileobj must be opened with mode r+b or w+b.
Starting at page number 'start', renumber all pages belonging
to logical stream 'serial'. Other pages will be ignored.
fileobj must point to the start of a valid Ogg page; any
occuring after it and part of the specified logical stream
will be numbered. No adjustment will be made to the data in
the pages nor the granule position; only the page number, and
so also the CRC.
If an error occurs (e.g. non-Ogg data is found), fileobj will
be left pointing to the place in the stream the error occured,
but the invalid data will be left intact (since this function
does not change the total file size).
"""
number = start
while True:
try:
page = OggPage(fileobj)
except EOFError:
break
else:
if page.serial != serial:
# Wrong stream, skip this page.
continue
# Changing the number can't change the page size,
# so seeking back based on the current size is safe.
fileobj.seek(-page.size, 1)
page.sequence = number
fileobj.write(page.write())
fileobj.seek(page.offset + page.size, 0)
number += 1 | python | def renumber(fileobj, serial, start):
number = start
while True:
try:
page = OggPage(fileobj)
except EOFError:
break
else:
if page.serial != serial:
# Wrong stream, skip this page.
continue
# Changing the number can't change the page size,
# so seeking back based on the current size is safe.
fileobj.seek(-page.size, 1)
page.sequence = number
fileobj.write(page.write())
fileobj.seek(page.offset + page.size, 0)
number += 1 | [
"def",
"renumber",
"(",
"fileobj",
",",
"serial",
",",
"start",
")",
":",
"number",
"=",
"start",
"while",
"True",
":",
"try",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"except",
"EOFError",
":",
"break",
"else",
":",
"if",
"page",
".",
"seri... | Renumber pages belonging to a specified logical stream.
fileobj must be opened with mode r+b or w+b.
Starting at page number 'start', renumber all pages belonging
to logical stream 'serial'. Other pages will be ignored.
fileobj must point to the start of a valid Ogg page; any
occuring after it and part of the specified logical stream
will be numbered. No adjustment will be made to the data in
the pages nor the granule position; only the page number, and
so also the CRC.
If an error occurs (e.g. non-Ogg data is found), fileobj will
be left pointing to the place in the stream the error occured,
but the invalid data will be left intact (since this function
does not change the total file size). | [
"Renumber",
"pages",
"belonging",
"to",
"a",
"specified",
"logical",
"stream",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L204-L240 |
232,262 | quodlibet/mutagen | mutagen/ogg.py | OggPage.to_packets | def to_packets(pages, strict=False):
"""Construct a list of packet data from a list of Ogg pages.
If strict is true, the first page must start a new packet,
and the last page must end the last packet.
"""
serial = pages[0].serial
sequence = pages[0].sequence
packets = []
if strict:
if pages[0].continued:
raise ValueError("first packet is continued")
if not pages[-1].complete:
raise ValueError("last packet does not complete")
elif pages and pages[0].continued:
packets.append([b""])
for page in pages:
if serial != page.serial:
raise ValueError("invalid serial number in %r" % page)
elif sequence != page.sequence:
raise ValueError("bad sequence number in %r" % page)
else:
sequence += 1
if page.continued:
packets[-1].append(page.packets[0])
else:
packets.append([page.packets[0]])
packets.extend([p] for p in page.packets[1:])
return [b"".join(p) for p in packets] | python | def to_packets(pages, strict=False):
serial = pages[0].serial
sequence = pages[0].sequence
packets = []
if strict:
if pages[0].continued:
raise ValueError("first packet is continued")
if not pages[-1].complete:
raise ValueError("last packet does not complete")
elif pages and pages[0].continued:
packets.append([b""])
for page in pages:
if serial != page.serial:
raise ValueError("invalid serial number in %r" % page)
elif sequence != page.sequence:
raise ValueError("bad sequence number in %r" % page)
else:
sequence += 1
if page.continued:
packets[-1].append(page.packets[0])
else:
packets.append([page.packets[0]])
packets.extend([p] for p in page.packets[1:])
return [b"".join(p) for p in packets] | [
"def",
"to_packets",
"(",
"pages",
",",
"strict",
"=",
"False",
")",
":",
"serial",
"=",
"pages",
"[",
"0",
"]",
".",
"serial",
"sequence",
"=",
"pages",
"[",
"0",
"]",
".",
"sequence",
"packets",
"=",
"[",
"]",
"if",
"strict",
":",
"if",
"pages",
... | Construct a list of packet data from a list of Ogg pages.
If strict is true, the first page must start a new packet,
and the last page must end the last packet. | [
"Construct",
"a",
"list",
"of",
"packet",
"data",
"from",
"a",
"list",
"of",
"Ogg",
"pages",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L243-L276 |
232,263 | quodlibet/mutagen | mutagen/ogg.py | OggPage.from_packets | def from_packets(packets, sequence=0, default_size=4096,
wiggle_room=2048):
"""Construct a list of Ogg pages from a list of packet data.
The algorithm will generate pages of approximately
default_size in size (rounded down to the nearest multiple of
255). However, it will also allow pages to increase to
approximately default_size + wiggle_room if allowing the
wiggle room would finish a packet (only one packet will be
finished in this way per page; if the next packet would fit
into the wiggle room, it still starts on a new page).
This method reduces packet fragmentation when packet sizes are
slightly larger than the default page size, while still
ensuring most pages are of the average size.
Pages are numbered started at 'sequence'; other information is
uninitialized.
"""
chunk_size = (default_size // 255) * 255
pages = []
page = OggPage()
page.sequence = sequence
for packet in packets:
page.packets.append(b"")
while packet:
data, packet = packet[:chunk_size], packet[chunk_size:]
if page.size < default_size and len(page.packets) < 255:
page.packets[-1] += data
else:
# If we've put any packet data into this page yet,
# we need to mark it incomplete. However, we can
# also have just started this packet on an already
# full page, in which case, just start the new
# page with this packet.
if page.packets[-1]:
page.complete = False
if len(page.packets) == 1:
page.position = -1
else:
page.packets.pop(-1)
pages.append(page)
page = OggPage()
page.continued = not pages[-1].complete
page.sequence = pages[-1].sequence + 1
page.packets.append(data)
if len(packet) < wiggle_room:
page.packets[-1] += packet
packet = b""
if page.packets:
pages.append(page)
return pages | python | def from_packets(packets, sequence=0, default_size=4096,
wiggle_room=2048):
chunk_size = (default_size // 255) * 255
pages = []
page = OggPage()
page.sequence = sequence
for packet in packets:
page.packets.append(b"")
while packet:
data, packet = packet[:chunk_size], packet[chunk_size:]
if page.size < default_size and len(page.packets) < 255:
page.packets[-1] += data
else:
# If we've put any packet data into this page yet,
# we need to mark it incomplete. However, we can
# also have just started this packet on an already
# full page, in which case, just start the new
# page with this packet.
if page.packets[-1]:
page.complete = False
if len(page.packets) == 1:
page.position = -1
else:
page.packets.pop(-1)
pages.append(page)
page = OggPage()
page.continued = not pages[-1].complete
page.sequence = pages[-1].sequence + 1
page.packets.append(data)
if len(packet) < wiggle_room:
page.packets[-1] += packet
packet = b""
if page.packets:
pages.append(page)
return pages | [
"def",
"from_packets",
"(",
"packets",
",",
"sequence",
"=",
"0",
",",
"default_size",
"=",
"4096",
",",
"wiggle_room",
"=",
"2048",
")",
":",
"chunk_size",
"=",
"(",
"default_size",
"//",
"255",
")",
"*",
"255",
"pages",
"=",
"[",
"]",
"page",
"=",
... | Construct a list of Ogg pages from a list of packet data.
The algorithm will generate pages of approximately
default_size in size (rounded down to the nearest multiple of
255). However, it will also allow pages to increase to
approximately default_size + wiggle_room if allowing the
wiggle room would finish a packet (only one packet will be
finished in this way per page; if the next packet would fit
into the wiggle room, it still starts on a new page).
This method reduces packet fragmentation when packet sizes are
slightly larger than the default page size, while still
ensuring most pages are of the average size.
Pages are numbered started at 'sequence'; other information is
uninitialized. | [
"Construct",
"a",
"list",
"of",
"Ogg",
"pages",
"from",
"a",
"list",
"of",
"packet",
"data",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L312-L370 |
232,264 | quodlibet/mutagen | mutagen/ogg.py | OggPage.replace | def replace(cls, fileobj, old_pages, new_pages):
"""Replace old_pages with new_pages within fileobj.
old_pages must have come from reading fileobj originally.
new_pages are assumed to have the 'same' data as old_pages,
and so the serial and sequence numbers will be copied, as will
the flags for the first and last pages.
fileobj will be resized and pages renumbered as necessary. As
such, it must be opened r+b or w+b.
"""
if not len(old_pages) or not len(new_pages):
raise ValueError("empty pages list not allowed")
# Number the new pages starting from the first old page.
first = old_pages[0].sequence
for page, seq in izip(new_pages,
xrange(first, first + len(new_pages))):
page.sequence = seq
page.serial = old_pages[0].serial
new_pages[0].first = old_pages[0].first
new_pages[0].last = old_pages[0].last
new_pages[0].continued = old_pages[0].continued
new_pages[-1].first = old_pages[-1].first
new_pages[-1].last = old_pages[-1].last
new_pages[-1].complete = old_pages[-1].complete
if not new_pages[-1].complete and len(new_pages[-1].packets) == 1:
new_pages[-1].position = -1
new_data = [cls.write(p) for p in new_pages]
# Add dummy data or merge the remaining data together so multiple
# new pages replace an old one
pages_diff = len(old_pages) - len(new_data)
if pages_diff > 0:
new_data.extend([b""] * pages_diff)
elif pages_diff < 0:
new_data[pages_diff - 1:] = [b"".join(new_data[pages_diff - 1:])]
# Replace pages one by one. If the sizes match no resize happens.
offset_adjust = 0
new_data_end = None
assert len(old_pages) == len(new_data)
for old_page, data in izip(old_pages, new_data):
offset = old_page.offset + offset_adjust
data_size = len(data)
resize_bytes(fileobj, old_page.size, data_size, offset)
fileobj.seek(offset, 0)
fileobj.write(data)
new_data_end = offset + data_size
offset_adjust += (data_size - old_page.size)
# Finally, if there's any discrepency in length, we need to
# renumber the pages for the logical stream.
if len(old_pages) != len(new_pages):
fileobj.seek(new_data_end, 0)
serial = new_pages[-1].serial
sequence = new_pages[-1].sequence + 1
cls.renumber(fileobj, serial, sequence) | python | def replace(cls, fileobj, old_pages, new_pages):
if not len(old_pages) or not len(new_pages):
raise ValueError("empty pages list not allowed")
# Number the new pages starting from the first old page.
first = old_pages[0].sequence
for page, seq in izip(new_pages,
xrange(first, first + len(new_pages))):
page.sequence = seq
page.serial = old_pages[0].serial
new_pages[0].first = old_pages[0].first
new_pages[0].last = old_pages[0].last
new_pages[0].continued = old_pages[0].continued
new_pages[-1].first = old_pages[-1].first
new_pages[-1].last = old_pages[-1].last
new_pages[-1].complete = old_pages[-1].complete
if not new_pages[-1].complete and len(new_pages[-1].packets) == 1:
new_pages[-1].position = -1
new_data = [cls.write(p) for p in new_pages]
# Add dummy data or merge the remaining data together so multiple
# new pages replace an old one
pages_diff = len(old_pages) - len(new_data)
if pages_diff > 0:
new_data.extend([b""] * pages_diff)
elif pages_diff < 0:
new_data[pages_diff - 1:] = [b"".join(new_data[pages_diff - 1:])]
# Replace pages one by one. If the sizes match no resize happens.
offset_adjust = 0
new_data_end = None
assert len(old_pages) == len(new_data)
for old_page, data in izip(old_pages, new_data):
offset = old_page.offset + offset_adjust
data_size = len(data)
resize_bytes(fileobj, old_page.size, data_size, offset)
fileobj.seek(offset, 0)
fileobj.write(data)
new_data_end = offset + data_size
offset_adjust += (data_size - old_page.size)
# Finally, if there's any discrepency in length, we need to
# renumber the pages for the logical stream.
if len(old_pages) != len(new_pages):
fileobj.seek(new_data_end, 0)
serial = new_pages[-1].serial
sequence = new_pages[-1].sequence + 1
cls.renumber(fileobj, serial, sequence) | [
"def",
"replace",
"(",
"cls",
",",
"fileobj",
",",
"old_pages",
",",
"new_pages",
")",
":",
"if",
"not",
"len",
"(",
"old_pages",
")",
"or",
"not",
"len",
"(",
"new_pages",
")",
":",
"raise",
"ValueError",
"(",
"\"empty pages list not allowed\"",
")",
"# N... | Replace old_pages with new_pages within fileobj.
old_pages must have come from reading fileobj originally.
new_pages are assumed to have the 'same' data as old_pages,
and so the serial and sequence numbers will be copied, as will
the flags for the first and last pages.
fileobj will be resized and pages renumbered as necessary. As
such, it must be opened r+b or w+b. | [
"Replace",
"old_pages",
"with",
"new_pages",
"within",
"fileobj",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L373-L434 |
232,265 | quodlibet/mutagen | mutagen/ogg.py | OggPage.find_last | def find_last(fileobj, serial, finishing=False):
"""Find the last page of the stream 'serial'.
If the file is not multiplexed this function is fast. If it is,
it must read the whole the stream.
This finds the last page in the actual file object, or the last
page in the stream (with eos set), whichever comes first.
If finishing is True it returns the last page which contains a packet
finishing on it. If there exist pages but none with finishing packets
returns None.
Returns None in case no page with the serial exists.
Raises error in case this isn't a valid ogg stream.
Raises IOError.
"""
# For non-muxed streams, look at the last page.
seek_end(fileobj, 256 * 256)
data = fileobj.read()
try:
index = data.rindex(b"OggS")
except ValueError:
raise error("unable to find final Ogg header")
bytesobj = cBytesIO(data[index:])
def is_valid(page):
return not finishing or page.position != -1
best_page = None
try:
page = OggPage(bytesobj)
except error:
pass
else:
if page.serial == serial and is_valid(page):
if page.last:
return page
else:
best_page = page
else:
best_page = None
# The stream is muxed, so use the slow way.
fileobj.seek(0)
try:
page = OggPage(fileobj)
while True:
if page.serial == serial:
if is_valid(page):
best_page = page
if page.last:
break
page = OggPage(fileobj)
return best_page
except error:
return best_page
except EOFError:
return best_page | python | def find_last(fileobj, serial, finishing=False):
# For non-muxed streams, look at the last page.
seek_end(fileobj, 256 * 256)
data = fileobj.read()
try:
index = data.rindex(b"OggS")
except ValueError:
raise error("unable to find final Ogg header")
bytesobj = cBytesIO(data[index:])
def is_valid(page):
return not finishing or page.position != -1
best_page = None
try:
page = OggPage(bytesobj)
except error:
pass
else:
if page.serial == serial and is_valid(page):
if page.last:
return page
else:
best_page = page
else:
best_page = None
# The stream is muxed, so use the slow way.
fileobj.seek(0)
try:
page = OggPage(fileobj)
while True:
if page.serial == serial:
if is_valid(page):
best_page = page
if page.last:
break
page = OggPage(fileobj)
return best_page
except error:
return best_page
except EOFError:
return best_page | [
"def",
"find_last",
"(",
"fileobj",
",",
"serial",
",",
"finishing",
"=",
"False",
")",
":",
"# For non-muxed streams, look at the last page.",
"seek_end",
"(",
"fileobj",
",",
"256",
"*",
"256",
")",
"data",
"=",
"fileobj",
".",
"read",
"(",
")",
"try",
":"... | Find the last page of the stream 'serial'.
If the file is not multiplexed this function is fast. If it is,
it must read the whole the stream.
This finds the last page in the actual file object, or the last
page in the stream (with eos set), whichever comes first.
If finishing is True it returns the last page which contains a packet
finishing on it. If there exist pages but none with finishing packets
returns None.
Returns None in case no page with the serial exists.
Raises error in case this isn't a valid ogg stream.
Raises IOError. | [
"Find",
"the",
"last",
"page",
"of",
"the",
"stream",
"serial",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L437-L497 |
232,266 | quodlibet/mutagen | mutagen/asf/_util.py | guid2bytes | def guid2bytes(s):
"""Converts a GUID to the serialized bytes representation"""
assert isinstance(s, str)
assert len(s) == 36
p = struct.pack
return b"".join([
p("<IHH", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)),
p(">H", int(s[19:23], 16)),
p(">Q", int(s[24:], 16))[2:],
]) | python | def guid2bytes(s):
assert isinstance(s, str)
assert len(s) == 36
p = struct.pack
return b"".join([
p("<IHH", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)),
p(">H", int(s[19:23], 16)),
p(">Q", int(s[24:], 16))[2:],
]) | [
"def",
"guid2bytes",
"(",
"s",
")",
":",
"assert",
"isinstance",
"(",
"s",
",",
"str",
")",
"assert",
"len",
"(",
"s",
")",
"==",
"36",
"p",
"=",
"struct",
".",
"pack",
"return",
"b\"\"",
".",
"join",
"(",
"[",
"p",
"(",
"\"<IHH\"",
",",
"int",
... | Converts a GUID to the serialized bytes representation | [
"Converts",
"a",
"GUID",
"to",
"the",
"serialized",
"bytes",
"representation"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/asf/_util.py#L27-L38 |
232,267 | quodlibet/mutagen | mutagen/asf/_util.py | bytes2guid | def bytes2guid(s):
"""Converts a serialized GUID to a text GUID"""
assert isinstance(s, bytes)
u = struct.unpack
v = []
v.extend(u("<IHH", s[:8]))
v.extend(u(">HQ", s[8:10] + b"\x00\x00" + s[10:]))
return "%08X-%04X-%04X-%04X-%012X" % tuple(v) | python | def bytes2guid(s):
assert isinstance(s, bytes)
u = struct.unpack
v = []
v.extend(u("<IHH", s[:8]))
v.extend(u(">HQ", s[8:10] + b"\x00\x00" + s[10:]))
return "%08X-%04X-%04X-%04X-%012X" % tuple(v) | [
"def",
"bytes2guid",
"(",
"s",
")",
":",
"assert",
"isinstance",
"(",
"s",
",",
"bytes",
")",
"u",
"=",
"struct",
".",
"unpack",
"v",
"=",
"[",
"]",
"v",
".",
"extend",
"(",
"u",
"(",
"\"<IHH\"",
",",
"s",
"[",
":",
"8",
"]",
")",
")",
"v",
... | Converts a serialized GUID to a text GUID | [
"Converts",
"a",
"serialized",
"GUID",
"to",
"a",
"text",
"GUID"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/asf/_util.py#L41-L50 |
232,268 | quodlibet/mutagen | mutagen/_tags.py | PaddingInfo.get_default_padding | def get_default_padding(self):
"""The default implementation which tries to select a reasonable
amount of padding and which might change in future versions.
Returns:
int: Amount of padding after saving
"""
high = 1024 * 10 + self.size // 100 # 10 KiB + 1% of trailing data
low = 1024 + self.size // 1000 # 1 KiB + 0.1% of trailing data
if self.padding >= 0:
# enough padding left
if self.padding > high:
# padding too large, reduce
return low
# just use existing padding as is
return self.padding
else:
# not enough padding, add some
return low | python | def get_default_padding(self):
high = 1024 * 10 + self.size // 100 # 10 KiB + 1% of trailing data
low = 1024 + self.size // 1000 # 1 KiB + 0.1% of trailing data
if self.padding >= 0:
# enough padding left
if self.padding > high:
# padding too large, reduce
return low
# just use existing padding as is
return self.padding
else:
# not enough padding, add some
return low | [
"def",
"get_default_padding",
"(",
"self",
")",
":",
"high",
"=",
"1024",
"*",
"10",
"+",
"self",
".",
"size",
"//",
"100",
"# 10 KiB + 1% of trailing data",
"low",
"=",
"1024",
"+",
"self",
".",
"size",
"//",
"1000",
"# 1 KiB + 0.1% of trailing data",
"if",
... | The default implementation which tries to select a reasonable
amount of padding and which might change in future versions.
Returns:
int: Amount of padding after saving | [
"The",
"default",
"implementation",
"which",
"tries",
"to",
"select",
"a",
"reasonable",
"amount",
"of",
"padding",
"and",
"which",
"might",
"change",
"in",
"future",
"versions",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_tags.py#L44-L64 |
232,269 | quodlibet/mutagen | mutagen/mp4/__init__.py | MP4Tags.__update_offset_table | def __update_offset_table(self, fileobj, fmt, atom, delta, offset):
"""Update offset table in the specified atom."""
if atom.offset > offset:
atom.offset += delta
fileobj.seek(atom.offset + 12)
data = fileobj.read(atom.length - 12)
fmt = fmt % cdata.uint_be(data[:4])
offsets = struct.unpack(fmt, data[4:])
offsets = [o + (0, delta)[offset < o] for o in offsets]
fileobj.seek(atom.offset + 16)
fileobj.write(struct.pack(fmt, *offsets)) | python | def __update_offset_table(self, fileobj, fmt, atom, delta, offset):
if atom.offset > offset:
atom.offset += delta
fileobj.seek(atom.offset + 12)
data = fileobj.read(atom.length - 12)
fmt = fmt % cdata.uint_be(data[:4])
offsets = struct.unpack(fmt, data[4:])
offsets = [o + (0, delta)[offset < o] for o in offsets]
fileobj.seek(atom.offset + 16)
fileobj.write(struct.pack(fmt, *offsets)) | [
"def",
"__update_offset_table",
"(",
"self",
",",
"fileobj",
",",
"fmt",
",",
"atom",
",",
"delta",
",",
"offset",
")",
":",
"if",
"atom",
".",
"offset",
">",
"offset",
":",
"atom",
".",
"offset",
"+=",
"delta",
"fileobj",
".",
"seek",
"(",
"atom",
"... | Update offset table in the specified atom. | [
"Update",
"offset",
"table",
"in",
"the",
"specified",
"atom",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/__init__.py#L518-L528 |
232,270 | quodlibet/mutagen | mutagen/mp4/__init__.py | MP4Tags.__update_offsets | def __update_offsets(self, fileobj, atoms, delta, offset):
"""Update offset tables in all 'stco' and 'co64' atoms."""
if delta == 0:
return
moov = atoms[b"moov"]
for atom in moov.findall(b'stco', True):
self.__update_offset_table(fileobj, ">%dI", atom, delta, offset)
for atom in moov.findall(b'co64', True):
self.__update_offset_table(fileobj, ">%dQ", atom, delta, offset)
try:
for atom in atoms[b"moof"].findall(b'tfhd', True):
self.__update_tfhd(fileobj, atom, delta, offset)
except KeyError:
pass | python | def __update_offsets(self, fileobj, atoms, delta, offset):
if delta == 0:
return
moov = atoms[b"moov"]
for atom in moov.findall(b'stco', True):
self.__update_offset_table(fileobj, ">%dI", atom, delta, offset)
for atom in moov.findall(b'co64', True):
self.__update_offset_table(fileobj, ">%dQ", atom, delta, offset)
try:
for atom in atoms[b"moof"].findall(b'tfhd', True):
self.__update_tfhd(fileobj, atom, delta, offset)
except KeyError:
pass | [
"def",
"__update_offsets",
"(",
"self",
",",
"fileobj",
",",
"atoms",
",",
"delta",
",",
"offset",
")",
":",
"if",
"delta",
"==",
"0",
":",
"return",
"moov",
"=",
"atoms",
"[",
"b\"moov\"",
"]",
"for",
"atom",
"in",
"moov",
".",
"findall",
"(",
"b'st... | Update offset tables in all 'stco' and 'co64' atoms. | [
"Update",
"offset",
"tables",
"in",
"all",
"stco",
"and",
"co64",
"atoms",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/__init__.py#L543-L556 |
232,271 | quodlibet/mutagen | mutagen/mp4/__init__.py | MP4Tags.delete | def delete(self, filename):
"""Remove the metadata from the given filename."""
self._failed_atoms.clear()
self.clear()
self.save(filename, padding=lambda x: 0) | python | def delete(self, filename):
self._failed_atoms.clear()
self.clear()
self.save(filename, padding=lambda x: 0) | [
"def",
"delete",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_failed_atoms",
".",
"clear",
"(",
")",
"self",
".",
"clear",
"(",
")",
"self",
".",
"save",
"(",
"filename",
",",
"padding",
"=",
"lambda",
"x",
":",
"0",
")"
] | Remove the metadata from the given filename. | [
"Remove",
"the",
"metadata",
"from",
"the",
"given",
"filename",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/__init__.py#L826-L831 |
232,272 | quodlibet/mutagen | mutagen/mp4/__init__.py | MP4Info._parse_stsd | def _parse_stsd(self, atom, fileobj):
"""Sets channels, bits_per_sample, sample_rate and optionally bitrate.
Can raise MP4StreamInfoError.
"""
assert atom.name == b"stsd"
ok, data = atom.read(fileobj)
if not ok:
raise MP4StreamInfoError("Invalid stsd")
try:
version, flags, data = parse_full_atom(data)
except ValueError as e:
raise MP4StreamInfoError(e)
if version != 0:
raise MP4StreamInfoError("Unsupported stsd version")
try:
num_entries, offset = cdata.uint32_be_from(data, 0)
except cdata.error as e:
raise MP4StreamInfoError(e)
if num_entries == 0:
return
# look at the first entry if there is one
entry_fileobj = cBytesIO(data[offset:])
try:
entry_atom = Atom(entry_fileobj)
except AtomError as e:
raise MP4StreamInfoError(e)
try:
entry = AudioSampleEntry(entry_atom, entry_fileobj)
except ASEntryError as e:
raise MP4StreamInfoError(e)
else:
self.channels = entry.channels
self.bits_per_sample = entry.sample_size
self.sample_rate = entry.sample_rate
self.bitrate = entry.bitrate
self.codec = entry.codec
self.codec_description = entry.codec_description | python | def _parse_stsd(self, atom, fileobj):
assert atom.name == b"stsd"
ok, data = atom.read(fileobj)
if not ok:
raise MP4StreamInfoError("Invalid stsd")
try:
version, flags, data = parse_full_atom(data)
except ValueError as e:
raise MP4StreamInfoError(e)
if version != 0:
raise MP4StreamInfoError("Unsupported stsd version")
try:
num_entries, offset = cdata.uint32_be_from(data, 0)
except cdata.error as e:
raise MP4StreamInfoError(e)
if num_entries == 0:
return
# look at the first entry if there is one
entry_fileobj = cBytesIO(data[offset:])
try:
entry_atom = Atom(entry_fileobj)
except AtomError as e:
raise MP4StreamInfoError(e)
try:
entry = AudioSampleEntry(entry_atom, entry_fileobj)
except ASEntryError as e:
raise MP4StreamInfoError(e)
else:
self.channels = entry.channels
self.bits_per_sample = entry.sample_size
self.sample_rate = entry.sample_rate
self.bitrate = entry.bitrate
self.codec = entry.codec
self.codec_description = entry.codec_description | [
"def",
"_parse_stsd",
"(",
"self",
",",
"atom",
",",
"fileobj",
")",
":",
"assert",
"atom",
".",
"name",
"==",
"b\"stsd\"",
"ok",
",",
"data",
"=",
"atom",
".",
"read",
"(",
"fileobj",
")",
"if",
"not",
"ok",
":",
"raise",
"MP4StreamInfoError",
"(",
... | Sets channels, bits_per_sample, sample_rate and optionally bitrate.
Can raise MP4StreamInfoError. | [
"Sets",
"channels",
"bits_per_sample",
"sample_rate",
"and",
"optionally",
"bitrate",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/__init__.py#L978-L1023 |
232,273 | quodlibet/mutagen | mutagen/mp4/_as_entry.py | BaseDescriptor._parse_desc_length_file | def _parse_desc_length_file(cls, fileobj):
"""May raise ValueError"""
value = 0
for i in xrange(4):
try:
b = cdata.uint8(fileobj.read(1))
except cdata.error as e:
raise ValueError(e)
value = (value << 7) | (b & 0x7f)
if not b >> 7:
break
else:
raise ValueError("invalid descriptor length")
return value | python | def _parse_desc_length_file(cls, fileobj):
value = 0
for i in xrange(4):
try:
b = cdata.uint8(fileobj.read(1))
except cdata.error as e:
raise ValueError(e)
value = (value << 7) | (b & 0x7f)
if not b >> 7:
break
else:
raise ValueError("invalid descriptor length")
return value | [
"def",
"_parse_desc_length_file",
"(",
"cls",
",",
"fileobj",
")",
":",
"value",
"=",
"0",
"for",
"i",
"in",
"xrange",
"(",
"4",
")",
":",
"try",
":",
"b",
"=",
"cdata",
".",
"uint8",
"(",
"fileobj",
".",
"read",
"(",
"1",
")",
")",
"except",
"cd... | May raise ValueError | [
"May",
"raise",
"ValueError"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_as_entry.py#L210-L225 |
232,274 | quodlibet/mutagen | mutagen/mp4/_as_entry.py | BaseDescriptor.parse | def parse(cls, fileobj):
"""Returns a parsed instance of the called type.
The file position is right after the descriptor after this returns.
Raises DescriptorError
"""
try:
length = cls._parse_desc_length_file(fileobj)
except ValueError as e:
raise DescriptorError(e)
pos = fileobj.tell()
instance = cls(fileobj, length)
left = length - (fileobj.tell() - pos)
if left < 0:
raise DescriptorError("descriptor parsing read too much data")
fileobj.seek(left, 1)
return instance | python | def parse(cls, fileobj):
try:
length = cls._parse_desc_length_file(fileobj)
except ValueError as e:
raise DescriptorError(e)
pos = fileobj.tell()
instance = cls(fileobj, length)
left = length - (fileobj.tell() - pos)
if left < 0:
raise DescriptorError("descriptor parsing read too much data")
fileobj.seek(left, 1)
return instance | [
"def",
"parse",
"(",
"cls",
",",
"fileobj",
")",
":",
"try",
":",
"length",
"=",
"cls",
".",
"_parse_desc_length_file",
"(",
"fileobj",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"DescriptorError",
"(",
"e",
")",
"pos",
"=",
"fileobj",
".",
... | Returns a parsed instance of the called type.
The file position is right after the descriptor after this returns.
Raises DescriptorError | [
"Returns",
"a",
"parsed",
"instance",
"of",
"the",
"called",
"type",
".",
"The",
"file",
"position",
"is",
"right",
"after",
"the",
"descriptor",
"after",
"this",
"returns",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_as_entry.py#L228-L245 |
232,275 | quodlibet/mutagen | mutagen/mp4/_as_entry.py | DecoderConfigDescriptor.codec_desc | def codec_desc(self):
"""string or None"""
info = self.decSpecificInfo
desc = None
if info is not None:
desc = info.description
return desc | python | def codec_desc(self):
info = self.decSpecificInfo
desc = None
if info is not None:
desc = info.description
return desc | [
"def",
"codec_desc",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"decSpecificInfo",
"desc",
"=",
"None",
"if",
"info",
"is",
"not",
"None",
":",
"desc",
"=",
"info",
".",
"description",
"return",
"desc"
] | string or None | [
"string",
"or",
"None"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_as_entry.py#L328-L335 |
232,276 | quodlibet/mutagen | mutagen/mp4/_as_entry.py | DecoderSpecificInfo.description | def description(self):
"""string or None if unknown"""
name = None
try:
name = self._TYPE_NAMES[self.audioObjectType]
except IndexError:
pass
if name is None:
return
if self.sbrPresentFlag == 1:
name += "+SBR"
if self.psPresentFlag == 1:
name += "+PS"
return text_type(name) | python | def description(self):
name = None
try:
name = self._TYPE_NAMES[self.audioObjectType]
except IndexError:
pass
if name is None:
return
if self.sbrPresentFlag == 1:
name += "+SBR"
if self.psPresentFlag == 1:
name += "+PS"
return text_type(name) | [
"def",
"description",
"(",
"self",
")",
":",
"name",
"=",
"None",
"try",
":",
"name",
"=",
"self",
".",
"_TYPE_NAMES",
"[",
"self",
".",
"audioObjectType",
"]",
"except",
"IndexError",
":",
"pass",
"if",
"name",
"is",
"None",
":",
"return",
"if",
"self... | string or None if unknown | [
"string",
"or",
"None",
"if",
"unknown"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_as_entry.py#L360-L374 |
232,277 | quodlibet/mutagen | mutagen/mp4/_as_entry.py | DecoderSpecificInfo.channels | def channels(self):
"""channel count or 0 for unknown"""
# from ProgramConfigElement()
if hasattr(self, "pce_channels"):
return self.pce_channels
conf = getattr(
self, "extensionChannelConfiguration", self.channelConfiguration)
if conf == 1:
if self.psPresentFlag == -1:
return 0
elif self.psPresentFlag == 1:
return 2
else:
return 1
elif conf == 7:
return 8
elif conf > 7:
return 0
else:
return conf | python | def channels(self):
# from ProgramConfigElement()
if hasattr(self, "pce_channels"):
return self.pce_channels
conf = getattr(
self, "extensionChannelConfiguration", self.channelConfiguration)
if conf == 1:
if self.psPresentFlag == -1:
return 0
elif self.psPresentFlag == 1:
return 2
else:
return 1
elif conf == 7:
return 8
elif conf > 7:
return 0
else:
return conf | [
"def",
"channels",
"(",
"self",
")",
":",
"# from ProgramConfigElement()",
"if",
"hasattr",
"(",
"self",
",",
"\"pce_channels\"",
")",
":",
"return",
"self",
".",
"pce_channels",
"conf",
"=",
"getattr",
"(",
"self",
",",
"\"extensionChannelConfiguration\"",
",",
... | channel count or 0 for unknown | [
"channel",
"count",
"or",
"0",
"for",
"unknown"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_as_entry.py#L396-L418 |
232,278 | quodlibet/mutagen | mutagen/smf.py | _read_track | def _read_track(chunk):
"""Retuns a list of midi events and tempo change events"""
TEMPO, MIDI = range(2)
# Deviations: The running status should be reset on non midi events, but
# some files contain meta events inbetween.
# TODO: Offset and time signature are not considered.
tempos = []
events = []
chunk = bytearray(chunk)
deltasum = 0
status = 0
off = 0
while off < len(chunk):
delta, off = _var_int(chunk, off)
deltasum += delta
event_type = chunk[off]
off += 1
if event_type == 0xFF:
meta_type = chunk[off]
off += 1
num, off = _var_int(chunk, off)
# TODO: support offset/time signature
if meta_type == 0x51:
data = chunk[off:off + num]
if len(data) != 3:
raise SMFError
tempo = struct.unpack(">I", b"\x00" + bytes(data))[0]
tempos.append((deltasum, TEMPO, tempo))
off += num
elif event_type in (0xF0, 0xF7):
val, off = _var_int(chunk, off)
off += val
else:
if event_type < 0x80:
# if < 0x80 take the type from the previous midi event
off += 1
event_type = status
elif event_type < 0xF0:
off += 2
status = event_type
else:
raise SMFError("invalid event")
if event_type >> 4 in (0xD, 0xC):
off -= 1
events.append((deltasum, MIDI, delta))
return events, tempos | python | def _read_track(chunk):
TEMPO, MIDI = range(2)
# Deviations: The running status should be reset on non midi events, but
# some files contain meta events inbetween.
# TODO: Offset and time signature are not considered.
tempos = []
events = []
chunk = bytearray(chunk)
deltasum = 0
status = 0
off = 0
while off < len(chunk):
delta, off = _var_int(chunk, off)
deltasum += delta
event_type = chunk[off]
off += 1
if event_type == 0xFF:
meta_type = chunk[off]
off += 1
num, off = _var_int(chunk, off)
# TODO: support offset/time signature
if meta_type == 0x51:
data = chunk[off:off + num]
if len(data) != 3:
raise SMFError
tempo = struct.unpack(">I", b"\x00" + bytes(data))[0]
tempos.append((deltasum, TEMPO, tempo))
off += num
elif event_type in (0xF0, 0xF7):
val, off = _var_int(chunk, off)
off += val
else:
if event_type < 0x80:
# if < 0x80 take the type from the previous midi event
off += 1
event_type = status
elif event_type < 0xF0:
off += 2
status = event_type
else:
raise SMFError("invalid event")
if event_type >> 4 in (0xD, 0xC):
off -= 1
events.append((deltasum, MIDI, delta))
return events, tempos | [
"def",
"_read_track",
"(",
"chunk",
")",
":",
"TEMPO",
",",
"MIDI",
"=",
"range",
"(",
"2",
")",
"# Deviations: The running status should be reset on non midi events, but",
"# some files contain meta events inbetween.",
"# TODO: Offset and time signature are not considered.",
"temp... | Retuns a list of midi events and tempo change events | [
"Retuns",
"a",
"list",
"of",
"midi",
"events",
"and",
"tempo",
"change",
"events"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/smf.py#L36-L88 |
232,279 | quodlibet/mutagen | mutagen/smf.py | _read_midi_length | def _read_midi_length(fileobj):
"""Returns the duration in seconds. Can raise all kind of errors..."""
TEMPO, MIDI = range(2)
def read_chunk(fileobj):
info = fileobj.read(8)
if len(info) != 8:
raise SMFError("truncated")
chunklen = struct.unpack(">I", info[4:])[0]
data = fileobj.read(chunklen)
if len(data) != chunklen:
raise SMFError("truncated")
return info[:4], data
identifier, chunk = read_chunk(fileobj)
if identifier != b"MThd":
raise SMFError("Not a MIDI file")
if len(chunk) != 6:
raise SMFError("truncated")
format_, ntracks, tickdiv = struct.unpack(">HHH", chunk)
if format_ > 1:
raise SMFError("Not supported format %d" % format_)
if tickdiv >> 15:
# fps = (-(tickdiv >> 8)) & 0xFF
# subres = tickdiv & 0xFF
# never saw one of those
raise SMFError("Not supported timing interval")
# get a list of events and tempo changes for each track
tracks = []
first_tempos = None
for tracknum in xrange(ntracks):
identifier, chunk = read_chunk(fileobj)
if identifier != b"MTrk":
continue
events, tempos = _read_track(chunk)
# In case of format == 1, copy the first tempo list to all tracks
first_tempos = first_tempos or tempos
if format_ == 1:
tempos = list(first_tempos)
events += tempos
events.sort()
tracks.append(events)
# calculate the duration of each track
durations = []
for events in tracks:
tempo = 500000
parts = []
deltasum = 0
for (dummy, type_, data) in events:
if type_ == TEMPO:
parts.append((deltasum, tempo))
tempo = data
deltasum = 0
else:
deltasum += data
parts.append((deltasum, tempo))
duration = 0
for (deltasum, tempo) in parts:
quarter, tpq = deltasum / float(tickdiv), tempo
duration += (quarter * tpq)
duration /= 10 ** 6
durations.append(duration)
# return the longest one
return max(durations) | python | def _read_midi_length(fileobj):
TEMPO, MIDI = range(2)
def read_chunk(fileobj):
info = fileobj.read(8)
if len(info) != 8:
raise SMFError("truncated")
chunklen = struct.unpack(">I", info[4:])[0]
data = fileobj.read(chunklen)
if len(data) != chunklen:
raise SMFError("truncated")
return info[:4], data
identifier, chunk = read_chunk(fileobj)
if identifier != b"MThd":
raise SMFError("Not a MIDI file")
if len(chunk) != 6:
raise SMFError("truncated")
format_, ntracks, tickdiv = struct.unpack(">HHH", chunk)
if format_ > 1:
raise SMFError("Not supported format %d" % format_)
if tickdiv >> 15:
# fps = (-(tickdiv >> 8)) & 0xFF
# subres = tickdiv & 0xFF
# never saw one of those
raise SMFError("Not supported timing interval")
# get a list of events and tempo changes for each track
tracks = []
first_tempos = None
for tracknum in xrange(ntracks):
identifier, chunk = read_chunk(fileobj)
if identifier != b"MTrk":
continue
events, tempos = _read_track(chunk)
# In case of format == 1, copy the first tempo list to all tracks
first_tempos = first_tempos or tempos
if format_ == 1:
tempos = list(first_tempos)
events += tempos
events.sort()
tracks.append(events)
# calculate the duration of each track
durations = []
for events in tracks:
tempo = 500000
parts = []
deltasum = 0
for (dummy, type_, data) in events:
if type_ == TEMPO:
parts.append((deltasum, tempo))
tempo = data
deltasum = 0
else:
deltasum += data
parts.append((deltasum, tempo))
duration = 0
for (deltasum, tempo) in parts:
quarter, tpq = deltasum / float(tickdiv), tempo
duration += (quarter * tpq)
duration /= 10 ** 6
durations.append(duration)
# return the longest one
return max(durations) | [
"def",
"_read_midi_length",
"(",
"fileobj",
")",
":",
"TEMPO",
",",
"MIDI",
"=",
"range",
"(",
"2",
")",
"def",
"read_chunk",
"(",
"fileobj",
")",
":",
"info",
"=",
"fileobj",
".",
"read",
"(",
"8",
")",
"if",
"len",
"(",
"info",
")",
"!=",
"8",
... | Returns the duration in seconds. Can raise all kind of errors... | [
"Returns",
"the",
"duration",
"in",
"seconds",
".",
"Can",
"raise",
"all",
"kind",
"of",
"errors",
"..."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/smf.py#L91-L164 |
232,280 | quodlibet/mutagen | mutagen/_senf/_fsnative.py | _swap_bytes | def _swap_bytes(data):
"""swaps bytes for 16 bit, leaves remaining trailing bytes alone"""
a, b = data[1::2], data[::2]
data = bytearray().join(bytearray(x) for x in zip(a, b))
if len(b) > len(a):
data += b[-1:]
return bytes(data) | python | def _swap_bytes(data):
a, b = data[1::2], data[::2]
data = bytearray().join(bytearray(x) for x in zip(a, b))
if len(b) > len(a):
data += b[-1:]
return bytes(data) | [
"def",
"_swap_bytes",
"(",
"data",
")",
":",
"a",
",",
"b",
"=",
"data",
"[",
"1",
":",
":",
"2",
"]",
",",
"data",
"[",
":",
":",
"2",
"]",
"data",
"=",
"bytearray",
"(",
")",
".",
"join",
"(",
"bytearray",
"(",
"x",
")",
"for",
"x",
"in",... | swaps bytes for 16 bit, leaves remaining trailing bytes alone | [
"swaps",
"bytes",
"for",
"16",
"bit",
"leaves",
"remaining",
"trailing",
"bytes",
"alone"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_fsnative.py#L49-L56 |
232,281 | quodlibet/mutagen | mutagen/_senf/_fsnative.py | _codec_can_decode_with_surrogatepass | def _codec_can_decode_with_surrogatepass(codec, _cache={}):
"""Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4
"""
try:
return _cache[codec]
except KeyError:
try:
u"\ud83d".encode(
codec, _surrogatepass).decode(codec, _surrogatepass)
except UnicodeDecodeError:
_cache[codec] = False
else:
_cache[codec] = True
return _cache[codec] | python | def _codec_can_decode_with_surrogatepass(codec, _cache={}):
try:
return _cache[codec]
except KeyError:
try:
u"\ud83d".encode(
codec, _surrogatepass).decode(codec, _surrogatepass)
except UnicodeDecodeError:
_cache[codec] = False
else:
_cache[codec] = True
return _cache[codec] | [
"def",
"_codec_can_decode_with_surrogatepass",
"(",
"codec",
",",
"_cache",
"=",
"{",
"}",
")",
":",
"try",
":",
"return",
"_cache",
"[",
"codec",
"]",
"except",
"KeyError",
":",
"try",
":",
"u\"\\ud83d\"",
".",
"encode",
"(",
"codec",
",",
"_surrogatepass",... | Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4 | [
"Returns",
"if",
"a",
"codec",
"supports",
"the",
"surrogatepass",
"error",
"handler",
"when",
"decoding",
".",
"Some",
"codecs",
"were",
"broken",
"in",
"Python",
"<3",
".",
"4"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_fsnative.py#L77-L92 |
232,282 | quodlibet/mutagen | mutagen/_senf/_fsnative.py | _winpath2bytes_py3 | def _winpath2bytes_py3(text, codec):
"""Fallback implementation for text including surrogates"""
# merge surrogate codepoints
if _normalize_codec(codec).startswith("utf-16"):
# fast path, utf-16 merges anyway
return text.encode(codec, _surrogatepass)
return _decode_surrogatepass(
text.encode("utf-16-le", _surrogatepass),
"utf-16-le").encode(codec, _surrogatepass) | python | def _winpath2bytes_py3(text, codec):
# merge surrogate codepoints
if _normalize_codec(codec).startswith("utf-16"):
# fast path, utf-16 merges anyway
return text.encode(codec, _surrogatepass)
return _decode_surrogatepass(
text.encode("utf-16-le", _surrogatepass),
"utf-16-le").encode(codec, _surrogatepass) | [
"def",
"_winpath2bytes_py3",
"(",
"text",
",",
"codec",
")",
":",
"# merge surrogate codepoints",
"if",
"_normalize_codec",
"(",
"codec",
")",
".",
"startswith",
"(",
"\"utf-16\"",
")",
":",
"# fast path, utf-16 merges anyway",
"return",
"text",
".",
"encode",
"(",
... | Fallback implementation for text including surrogates | [
"Fallback",
"implementation",
"for",
"text",
"including",
"surrogates"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_fsnative.py#L123-L132 |
232,283 | quodlibet/mutagen | mutagen/_senf/_fsnative.py | _get_encoding | def _get_encoding():
"""The encoding used for paths, argv, environ, stdout and stdin"""
encoding = sys.getfilesystemencoding()
if encoding is None:
if is_darwin:
encoding = "utf-8"
elif is_win:
encoding = "mbcs"
else:
encoding = "ascii"
encoding = _normalize_codec(encoding)
return encoding | python | def _get_encoding():
encoding = sys.getfilesystemencoding()
if encoding is None:
if is_darwin:
encoding = "utf-8"
elif is_win:
encoding = "mbcs"
else:
encoding = "ascii"
encoding = _normalize_codec(encoding)
return encoding | [
"def",
"_get_encoding",
"(",
")",
":",
"encoding",
"=",
"sys",
".",
"getfilesystemencoding",
"(",
")",
"if",
"encoding",
"is",
"None",
":",
"if",
"is_darwin",
":",
"encoding",
"=",
"\"utf-8\"",
"elif",
"is_win",
":",
"encoding",
"=",
"\"mbcs\"",
"else",
":... | The encoding used for paths, argv, environ, stdout and stdin | [
"The",
"encoding",
"used",
"for",
"paths",
"argv",
"environ",
"stdout",
"and",
"stdin"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_senf/_fsnative.py#L360-L372 |
232,284 | quodlibet/mutagen | mutagen/flac.py | MetadataBlock._writeblock | def _writeblock(cls, block, is_last=False):
"""Returns the block content + header.
Raises error.
"""
data = bytearray()
code = (block.code | 128) if is_last else block.code
datum = block.write()
size = len(datum)
if size > cls._MAX_SIZE:
if block._distrust_size and block._invalid_overflow_size != -1:
# The original size of this block was (1) wrong and (2)
# the real size doesn't allow us to save the file
# according to the spec (too big for 24 bit uint). Instead
# simply write back the original wrong size.. at least
# we don't make the file more "broken" as it is.
size = block._invalid_overflow_size
else:
raise error("block is too long to write")
assert not size > cls._MAX_SIZE
length = struct.pack(">I", size)[-3:]
data.append(code)
data += length
data += datum
return data | python | def _writeblock(cls, block, is_last=False):
data = bytearray()
code = (block.code | 128) if is_last else block.code
datum = block.write()
size = len(datum)
if size > cls._MAX_SIZE:
if block._distrust_size and block._invalid_overflow_size != -1:
# The original size of this block was (1) wrong and (2)
# the real size doesn't allow us to save the file
# according to the spec (too big for 24 bit uint). Instead
# simply write back the original wrong size.. at least
# we don't make the file more "broken" as it is.
size = block._invalid_overflow_size
else:
raise error("block is too long to write")
assert not size > cls._MAX_SIZE
length = struct.pack(">I", size)[-3:]
data.append(code)
data += length
data += datum
return data | [
"def",
"_writeblock",
"(",
"cls",
",",
"block",
",",
"is_last",
"=",
"False",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"code",
"=",
"(",
"block",
".",
"code",
"|",
"128",
")",
"if",
"is_last",
"else",
"block",
".",
"code",
"datum",
"=",
"block... | Returns the block content + header.
Raises error. | [
"Returns",
"the",
"block",
"content",
"+",
"header",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L118-L143 |
232,285 | quodlibet/mutagen | mutagen/flac.py | MetadataBlock._writeblocks | def _writeblocks(cls, blocks, available, cont_size, padding_func):
"""Render metadata block as a byte string."""
# write everything except padding
data = bytearray()
for block in blocks:
if isinstance(block, Padding):
continue
data += cls._writeblock(block)
blockssize = len(data)
# take the padding overhead into account. we always add one
# to make things simple.
padding_block = Padding()
blockssize += len(cls._writeblock(padding_block))
# finally add a padding block
info = PaddingInfo(available - blockssize, cont_size)
padding_block.length = min(info._get_padding(padding_func),
cls._MAX_SIZE)
data += cls._writeblock(padding_block, is_last=True)
return data | python | def _writeblocks(cls, blocks, available, cont_size, padding_func):
# write everything except padding
data = bytearray()
for block in blocks:
if isinstance(block, Padding):
continue
data += cls._writeblock(block)
blockssize = len(data)
# take the padding overhead into account. we always add one
# to make things simple.
padding_block = Padding()
blockssize += len(cls._writeblock(padding_block))
# finally add a padding block
info = PaddingInfo(available - blockssize, cont_size)
padding_block.length = min(info._get_padding(padding_func),
cls._MAX_SIZE)
data += cls._writeblock(padding_block, is_last=True)
return data | [
"def",
"_writeblocks",
"(",
"cls",
",",
"blocks",
",",
"available",
",",
"cont_size",
",",
"padding_func",
")",
":",
"# write everything except padding",
"data",
"=",
"bytearray",
"(",
")",
"for",
"block",
"in",
"blocks",
":",
"if",
"isinstance",
"(",
"block",... | Render metadata block as a byte string. | [
"Render",
"metadata",
"block",
"as",
"a",
"byte",
"string",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L146-L168 |
232,286 | quodlibet/mutagen | mutagen/flac.py | FLAC.add_tags | def add_tags(self):
"""Add a Vorbis comment block to the file."""
if self.tags is None:
self.tags = VCFLACDict()
self.metadata_blocks.append(self.tags)
else:
raise FLACVorbisError("a Vorbis comment already exists") | python | def add_tags(self):
if self.tags is None:
self.tags = VCFLACDict()
self.metadata_blocks.append(self.tags)
else:
raise FLACVorbisError("a Vorbis comment already exists") | [
"def",
"add_tags",
"(",
"self",
")",
":",
"if",
"self",
".",
"tags",
"is",
"None",
":",
"self",
".",
"tags",
"=",
"VCFLACDict",
"(",
")",
"self",
".",
"metadata_blocks",
".",
"append",
"(",
"self",
".",
"tags",
")",
"else",
":",
"raise",
"FLACVorbisE... | Add a Vorbis comment block to the file. | [
"Add",
"a",
"Vorbis",
"comment",
"block",
"to",
"the",
"file",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L751-L757 |
232,287 | quodlibet/mutagen | mutagen/flac.py | FLAC.delete | def delete(self, filething=None):
"""Remove Vorbis comments from a file.
If no filename is given, the one most recently loaded is used.
"""
if self.tags is not None:
temp_blocks = [
b for b in self.metadata_blocks if b.code != VCFLACDict.code]
self._save(filething, temp_blocks, False, padding=lambda x: 0)
self.metadata_blocks[:] = [
b for b in self.metadata_blocks
if b.code != VCFLACDict.code or b is self.tags]
self.tags.clear() | python | def delete(self, filething=None):
if self.tags is not None:
temp_blocks = [
b for b in self.metadata_blocks if b.code != VCFLACDict.code]
self._save(filething, temp_blocks, False, padding=lambda x: 0)
self.metadata_blocks[:] = [
b for b in self.metadata_blocks
if b.code != VCFLACDict.code or b is self.tags]
self.tags.clear() | [
"def",
"delete",
"(",
"self",
",",
"filething",
"=",
"None",
")",
":",
"if",
"self",
".",
"tags",
"is",
"not",
"None",
":",
"temp_blocks",
"=",
"[",
"b",
"for",
"b",
"in",
"self",
".",
"metadata_blocks",
"if",
"b",
".",
"code",
"!=",
"VCFLACDict",
... | Remove Vorbis comments from a file.
If no filename is given, the one most recently loaded is used. | [
"Remove",
"Vorbis",
"comments",
"from",
"a",
"file",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L763-L776 |
232,288 | quodlibet/mutagen | mutagen/flac.py | FLAC.load | def load(self, filething):
"""Load file information from a filename."""
fileobj = filething.fileobj
self.metadata_blocks = []
self.tags = None
self.cuesheet = None
self.seektable = None
fileobj = StrictFileObject(fileobj)
self.__check_header(fileobj, filething.name)
while self.__read_metadata_block(fileobj):
pass
try:
self.metadata_blocks[0].length
except (AttributeError, IndexError):
raise FLACNoHeaderError("Stream info block not found")
if self.info.length:
start = fileobj.tell()
fileobj.seek(0, 2)
self.info.bitrate = int(
float(fileobj.tell() - start) * 8 / self.info.length)
else:
self.info.bitrate = 0 | python | def load(self, filething):
fileobj = filething.fileobj
self.metadata_blocks = []
self.tags = None
self.cuesheet = None
self.seektable = None
fileobj = StrictFileObject(fileobj)
self.__check_header(fileobj, filething.name)
while self.__read_metadata_block(fileobj):
pass
try:
self.metadata_blocks[0].length
except (AttributeError, IndexError):
raise FLACNoHeaderError("Stream info block not found")
if self.info.length:
start = fileobj.tell()
fileobj.seek(0, 2)
self.info.bitrate = int(
float(fileobj.tell() - start) * 8 / self.info.length)
else:
self.info.bitrate = 0 | [
"def",
"load",
"(",
"self",
",",
"filething",
")",
":",
"fileobj",
"=",
"filething",
".",
"fileobj",
"self",
".",
"metadata_blocks",
"=",
"[",
"]",
"self",
".",
"tags",
"=",
"None",
"self",
".",
"cuesheet",
"=",
"None",
"self",
".",
"seektable",
"=",
... | Load file information from a filename. | [
"Load",
"file",
"information",
"from",
"a",
"filename",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L782-L808 |
232,289 | quodlibet/mutagen | mutagen/flac.py | FLAC.clear_pictures | def clear_pictures(self):
"""Delete all pictures from the file."""
blocks = [b for b in self.metadata_blocks if b.code != Picture.code]
self.metadata_blocks = blocks | python | def clear_pictures(self):
blocks = [b for b in self.metadata_blocks if b.code != Picture.code]
self.metadata_blocks = blocks | [
"def",
"clear_pictures",
"(",
"self",
")",
":",
"blocks",
"=",
"[",
"b",
"for",
"b",
"in",
"self",
".",
"metadata_blocks",
"if",
"b",
".",
"code",
"!=",
"Picture",
".",
"code",
"]",
"self",
".",
"metadata_blocks",
"=",
"blocks"
] | Delete all pictures from the file. | [
"Delete",
"all",
"pictures",
"from",
"the",
"file",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L822-L826 |
232,290 | quodlibet/mutagen | mutagen/flac.py | FLAC.save | def save(self, filething=None, deleteid3=False, padding=None):
"""Save metadata blocks to a file.
Args:
filething (filething)
deleteid3 (bool): delete id3 tags while at it
padding (:obj:`mutagen.PaddingFunction`)
If no filename is given, the one most recently loaded is used.
"""
self._save(filething, self.metadata_blocks, deleteid3, padding) | python | def save(self, filething=None, deleteid3=False, padding=None):
self._save(filething, self.metadata_blocks, deleteid3, padding) | [
"def",
"save",
"(",
"self",
",",
"filething",
"=",
"None",
",",
"deleteid3",
"=",
"False",
",",
"padding",
"=",
"None",
")",
":",
"self",
".",
"_save",
"(",
"filething",
",",
"self",
".",
"metadata_blocks",
",",
"deleteid3",
",",
"padding",
")"
] | Save metadata blocks to a file.
Args:
filething (filething)
deleteid3 (bool): delete id3 tags while at it
padding (:obj:`mutagen.PaddingFunction`)
If no filename is given, the one most recently loaded is used. | [
"Save",
"metadata",
"blocks",
"to",
"a",
"file",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L836-L847 |
232,291 | quodlibet/mutagen | mutagen/_tools/mid3v2.py | frame_from_fsnative | def frame_from_fsnative(arg):
"""Takes item from argv and returns ascii native str
or raises ValueError.
"""
assert isinstance(arg, fsnative)
text = fsn2text(arg, strict=True)
if PY2:
return text.encode("ascii")
else:
return text.encode("ascii").decode("ascii") | python | def frame_from_fsnative(arg):
assert isinstance(arg, fsnative)
text = fsn2text(arg, strict=True)
if PY2:
return text.encode("ascii")
else:
return text.encode("ascii").decode("ascii") | [
"def",
"frame_from_fsnative",
"(",
"arg",
")",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"fsnative",
")",
"text",
"=",
"fsn2text",
"(",
"arg",
",",
"strict",
"=",
"True",
")",
"if",
"PY2",
":",
"return",
"text",
".",
"encode",
"(",
"\"ascii\"",
")"... | Takes item from argv and returns ascii native str
or raises ValueError. | [
"Takes",
"item",
"from",
"argv",
"and",
"returns",
"ascii",
"native",
"str",
"or",
"raises",
"ValueError",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_tools/mid3v2.py#L115-L126 |
232,292 | quodlibet/mutagen | mutagen/_tools/mid3v2.py | value_from_fsnative | def value_from_fsnative(arg, escape):
"""Takes an item from argv and returns a text_type value without
surrogate escapes or raises ValueError.
"""
assert isinstance(arg, fsnative)
if escape:
bytes_ = fsn2bytes(arg)
if PY2:
bytes_ = bytes_.decode("string_escape")
else:
# With py3.7 this has started to warn for invalid escapes, but we
# don't control the input so ignore it.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
bytes_ = codecs.escape_decode(bytes_)[0]
arg = bytes2fsn(bytes_)
text = fsn2text(arg, strict=True)
return text | python | def value_from_fsnative(arg, escape):
assert isinstance(arg, fsnative)
if escape:
bytes_ = fsn2bytes(arg)
if PY2:
bytes_ = bytes_.decode("string_escape")
else:
# With py3.7 this has started to warn for invalid escapes, but we
# don't control the input so ignore it.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
bytes_ = codecs.escape_decode(bytes_)[0]
arg = bytes2fsn(bytes_)
text = fsn2text(arg, strict=True)
return text | [
"def",
"value_from_fsnative",
"(",
"arg",
",",
"escape",
")",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"fsnative",
")",
"if",
"escape",
":",
"bytes_",
"=",
"fsn2bytes",
"(",
"arg",
")",
"if",
"PY2",
":",
"bytes_",
"=",
"bytes_",
".",
"decode",
"("... | Takes an item from argv and returns a text_type value without
surrogate escapes or raises ValueError. | [
"Takes",
"an",
"item",
"from",
"argv",
"and",
"returns",
"a",
"text_type",
"value",
"without",
"surrogate",
"escapes",
"or",
"raises",
"ValueError",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_tools/mid3v2.py#L129-L149 |
232,293 | quodlibet/mutagen | mutagen/mp3/__init__.py | skip_id3 | def skip_id3(fileobj):
"""Might raise IOError"""
# WMP writes multiple id3s, so skip as many as we find
while True:
idata = fileobj.read(10)
try:
id3, insize = struct.unpack('>3sxxx4s', idata)
except struct.error:
id3, insize = b'', 0
insize = BitPaddedInt(insize)
if id3 == b'ID3' and insize > 0:
fileobj.seek(insize, 1)
else:
fileobj.seek(-len(idata), 1)
break | python | def skip_id3(fileobj):
# WMP writes multiple id3s, so skip as many as we find
while True:
idata = fileobj.read(10)
try:
id3, insize = struct.unpack('>3sxxx4s', idata)
except struct.error:
id3, insize = b'', 0
insize = BitPaddedInt(insize)
if id3 == b'ID3' and insize > 0:
fileobj.seek(insize, 1)
else:
fileobj.seek(-len(idata), 1)
break | [
"def",
"skip_id3",
"(",
"fileobj",
")",
":",
"# WMP writes multiple id3s, so skip as many as we find",
"while",
"True",
":",
"idata",
"=",
"fileobj",
".",
"read",
"(",
"10",
")",
"try",
":",
"id3",
",",
"insize",
"=",
"struct",
".",
"unpack",
"(",
"'>3sxxx4s'"... | Might raise IOError | [
"Might",
"raise",
"IOError"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp3/__init__.py#L229-L244 |
232,294 | quodlibet/mutagen | mutagen/mp3/__init__.py | iter_sync | def iter_sync(fileobj, max_read):
"""Iterate over a fileobj and yields on each mpeg sync.
When yielding the fileobj offset is right before the sync and can be
changed between iterations without affecting the iteration process.
Might raise IOError.
"""
read = 0
size = 2
last_byte = b""
is_second = lambda b: ord(b) & 0xe0 == 0xe0
while read < max_read:
data_offset = fileobj.tell()
new_data = fileobj.read(min(max_read - read, size))
if not new_data:
return
read += len(new_data)
if last_byte == b"\xff" and is_second(new_data[0:1]):
fileobj.seek(data_offset - 1, 0)
yield
size *= 2
last_byte = new_data[-1:]
find_offset = 0
while True:
index = new_data.find(b"\xff", find_offset)
# if not found or the last byte -> read more
if index == -1 or index == len(new_data) - 1:
break
if is_second(new_data[index + 1:index + 2]):
fileobj.seek(data_offset + index, 0)
yield
find_offset = index + 1
fileobj.seek(data_offset + len(new_data), 0) | python | def iter_sync(fileobj, max_read):
read = 0
size = 2
last_byte = b""
is_second = lambda b: ord(b) & 0xe0 == 0xe0
while read < max_read:
data_offset = fileobj.tell()
new_data = fileobj.read(min(max_read - read, size))
if not new_data:
return
read += len(new_data)
if last_byte == b"\xff" and is_second(new_data[0:1]):
fileobj.seek(data_offset - 1, 0)
yield
size *= 2
last_byte = new_data[-1:]
find_offset = 0
while True:
index = new_data.find(b"\xff", find_offset)
# if not found or the last byte -> read more
if index == -1 or index == len(new_data) - 1:
break
if is_second(new_data[index + 1:index + 2]):
fileobj.seek(data_offset + index, 0)
yield
find_offset = index + 1
fileobj.seek(data_offset + len(new_data), 0) | [
"def",
"iter_sync",
"(",
"fileobj",
",",
"max_read",
")",
":",
"read",
"=",
"0",
"size",
"=",
"2",
"last_byte",
"=",
"b\"\"",
"is_second",
"=",
"lambda",
"b",
":",
"ord",
"(",
"b",
")",
"&",
"0xe0",
"==",
"0xe0",
"while",
"read",
"<",
"max_read",
"... | Iterate over a fileobj and yields on each mpeg sync.
When yielding the fileobj offset is right before the sync and can be
changed between iterations without affecting the iteration process.
Might raise IOError. | [
"Iterate",
"over",
"a",
"fileobj",
"and",
"yields",
"on",
"each",
"mpeg",
"sync",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp3/__init__.py#L247-L287 |
232,295 | quodlibet/mutagen | mutagen/mp3/__init__.py | MPEGFrame._parse_vbr_header | def _parse_vbr_header(self, fileobj, frame_offset, frame_size,
frame_length):
"""Does not raise"""
# Xing
xing_offset = XingHeader.get_offset(self)
fileobj.seek(frame_offset + xing_offset, 0)
try:
xing = XingHeader(fileobj)
except XingHeaderError:
pass
else:
lame = xing.lame_header
self.sketchy = False
self.bitrate_mode = _guess_xing_bitrate_mode(xing)
self.encoder_settings = xing.get_encoder_settings()
if xing.frames != -1:
samples = frame_size * xing.frames
if xing.bytes != -1 and samples > 0:
# the first frame is only included in xing.bytes but
# not in xing.frames, skip it.
audio_bytes = max(0, xing.bytes - frame_length)
self.bitrate = intround((
audio_bytes * 8 * self.sample_rate) / float(samples))
if lame is not None:
samples -= lame.encoder_delay_start
samples -= lame.encoder_padding_end
if samples < 0:
# older lame versions wrote bogus delay/padding for short
# files with low bitrate
samples = 0
self.length = float(samples) / self.sample_rate
if xing.lame_version_desc:
self.encoder_info = u"LAME %s" % xing.lame_version_desc
if lame is not None:
self.track_gain = lame.track_gain_adjustment
self.track_peak = lame.track_peak
self.album_gain = lame.album_gain_adjustment
return
# VBRI
vbri_offset = VBRIHeader.get_offset(self)
fileobj.seek(frame_offset + vbri_offset, 0)
try:
vbri = VBRIHeader(fileobj)
except VBRIHeaderError:
pass
else:
self.bitrate_mode = BitrateMode.VBR
self.encoder_info = u"FhG"
self.sketchy = False
self.length = float(frame_size * vbri.frames) / self.sample_rate
if self.length:
self.bitrate = int((vbri.bytes * 8) / self.length) | python | def _parse_vbr_header(self, fileobj, frame_offset, frame_size,
frame_length):
# Xing
xing_offset = XingHeader.get_offset(self)
fileobj.seek(frame_offset + xing_offset, 0)
try:
xing = XingHeader(fileobj)
except XingHeaderError:
pass
else:
lame = xing.lame_header
self.sketchy = False
self.bitrate_mode = _guess_xing_bitrate_mode(xing)
self.encoder_settings = xing.get_encoder_settings()
if xing.frames != -1:
samples = frame_size * xing.frames
if xing.bytes != -1 and samples > 0:
# the first frame is only included in xing.bytes but
# not in xing.frames, skip it.
audio_bytes = max(0, xing.bytes - frame_length)
self.bitrate = intround((
audio_bytes * 8 * self.sample_rate) / float(samples))
if lame is not None:
samples -= lame.encoder_delay_start
samples -= lame.encoder_padding_end
if samples < 0:
# older lame versions wrote bogus delay/padding for short
# files with low bitrate
samples = 0
self.length = float(samples) / self.sample_rate
if xing.lame_version_desc:
self.encoder_info = u"LAME %s" % xing.lame_version_desc
if lame is not None:
self.track_gain = lame.track_gain_adjustment
self.track_peak = lame.track_peak
self.album_gain = lame.album_gain_adjustment
return
# VBRI
vbri_offset = VBRIHeader.get_offset(self)
fileobj.seek(frame_offset + vbri_offset, 0)
try:
vbri = VBRIHeader(fileobj)
except VBRIHeaderError:
pass
else:
self.bitrate_mode = BitrateMode.VBR
self.encoder_info = u"FhG"
self.sketchy = False
self.length = float(frame_size * vbri.frames) / self.sample_rate
if self.length:
self.bitrate = int((vbri.bytes * 8) / self.length) | [
"def",
"_parse_vbr_header",
"(",
"self",
",",
"fileobj",
",",
"frame_offset",
",",
"frame_size",
",",
"frame_length",
")",
":",
"# Xing",
"xing_offset",
"=",
"XingHeader",
".",
"get_offset",
"(",
"self",
")",
"fileobj",
".",
"seek",
"(",
"frame_offset",
"+",
... | Does not raise | [
"Does",
"not",
"raise"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp3/__init__.py#L173-L226 |
232,296 | quodlibet/mutagen | mutagen/easyid3.py | EasyID3.RegisterTXXXKey | def RegisterTXXXKey(cls, key, desc):
"""Register a user-defined text frame key.
Some ID3 tags are stored in TXXX frames, which allow a
freeform 'description' which acts as a subkey,
e.g. TXXX:BARCODE.::
EasyID3.RegisterTXXXKey('barcode', 'BARCODE').
"""
frameid = "TXXX:" + desc
def getter(id3, key):
return list(id3[frameid])
def setter(id3, key, value):
enc = 0
# Store 8859-1 if we can, per MusicBrainz spec.
for v in value:
if v and max(v) > u'\x7f':
enc = 3
break
id3.add(mutagen.id3.TXXX(encoding=enc, text=value, desc=desc))
def deleter(id3, key):
del(id3[frameid])
cls.RegisterKey(key, getter, setter, deleter) | python | def RegisterTXXXKey(cls, key, desc):
frameid = "TXXX:" + desc
def getter(id3, key):
return list(id3[frameid])
def setter(id3, key, value):
enc = 0
# Store 8859-1 if we can, per MusicBrainz spec.
for v in value:
if v and max(v) > u'\x7f':
enc = 3
break
id3.add(mutagen.id3.TXXX(encoding=enc, text=value, desc=desc))
def deleter(id3, key):
del(id3[frameid])
cls.RegisterKey(key, getter, setter, deleter) | [
"def",
"RegisterTXXXKey",
"(",
"cls",
",",
"key",
",",
"desc",
")",
":",
"frameid",
"=",
"\"TXXX:\"",
"+",
"desc",
"def",
"getter",
"(",
"id3",
",",
"key",
")",
":",
"return",
"list",
"(",
"id3",
"[",
"frameid",
"]",
")",
"def",
"setter",
"(",
"id3... | Register a user-defined text frame key.
Some ID3 tags are stored in TXXX frames, which allow a
freeform 'description' which acts as a subkey,
e.g. TXXX:BARCODE.::
EasyID3.RegisterTXXXKey('barcode', 'BARCODE'). | [
"Register",
"a",
"user",
"-",
"defined",
"text",
"frame",
"key",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/easyid3.py#L138-L165 |
232,297 | quodlibet/mutagen | mutagen/apev2.py | _get_value_type | def _get_value_type(kind):
"""Returns a _APEValue subclass or raises ValueError"""
if kind == TEXT:
return APETextValue
elif kind == BINARY:
return APEBinaryValue
elif kind == EXTERNAL:
return APEExtValue
raise ValueError("unknown kind %r" % kind) | python | def _get_value_type(kind):
if kind == TEXT:
return APETextValue
elif kind == BINARY:
return APEBinaryValue
elif kind == EXTERNAL:
return APEExtValue
raise ValueError("unknown kind %r" % kind) | [
"def",
"_get_value_type",
"(",
"kind",
")",
":",
"if",
"kind",
"==",
"TEXT",
":",
"return",
"APETextValue",
"elif",
"kind",
"==",
"BINARY",
":",
"return",
"APEBinaryValue",
"elif",
"kind",
"==",
"EXTERNAL",
":",
"return",
"APEExtValue",
"raise",
"ValueError",
... | Returns a _APEValue subclass or raises ValueError | [
"Returns",
"a",
"_APEValue",
"subclass",
"or",
"raises",
"ValueError"
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/apev2.py#L523-L532 |
232,298 | quodlibet/mutagen | mutagen/apev2.py | APEValue | def APEValue(value, kind):
"""APEv2 tag value factory.
Use this if you need to specify the value's type manually. Binary
and text data are automatically detected by APEv2.__setitem__.
"""
try:
type_ = _get_value_type(kind)
except ValueError:
raise ValueError("kind must be TEXT, BINARY, or EXTERNAL")
else:
return type_(value) | python | def APEValue(value, kind):
try:
type_ = _get_value_type(kind)
except ValueError:
raise ValueError("kind must be TEXT, BINARY, or EXTERNAL")
else:
return type_(value) | [
"def",
"APEValue",
"(",
"value",
",",
"kind",
")",
":",
"try",
":",
"type_",
"=",
"_get_value_type",
"(",
"kind",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"kind must be TEXT, BINARY, or EXTERNAL\"",
")",
"else",
":",
"return",
"type_",
"... | APEv2 tag value factory.
Use this if you need to specify the value's type manually. Binary
and text data are automatically detected by APEv2.__setitem__. | [
"APEv2",
"tag",
"value",
"factory",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/apev2.py#L535-L547 |
232,299 | quodlibet/mutagen | mutagen/apev2.py | APEv2.pprint | def pprint(self):
"""Return tag key=value pairs in a human-readable format."""
items = sorted(self.items())
return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items) | python | def pprint(self):
items = sorted(self.items())
return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items) | [
"def",
"pprint",
"(",
"self",
")",
":",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
")",
"return",
"u\"\\n\"",
".",
"join",
"(",
"u\"%s=%s\"",
"%",
"(",
"k",
",",
"v",
".",
"pprint",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
... | Return tag key=value pairs in a human-readable format. | [
"Return",
"tag",
"key",
"=",
"value",
"pairs",
"in",
"a",
"human",
"-",
"readable",
"format",
"."
] | e393df5971ba41ba5a50de9c2c9e7e5484d82c4e | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/apev2.py#L284-L288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.