repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
spulec/moto | moto/iam/models.py | IAMBackend._validate_tag_key | def _validate_tag_key(self, tag_key, exception_param='tags.X.member.key'):
"""Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the message. This is to reflect
the difference between the tag and untag APIs.
:return:
"""
# Validate that the key length is correct:
if len(tag_key) > 128:
raise TagKeyTooBig(tag_key, param=exception_param)
# Validate that the tag key fits the proper Regex:
# [\w\s_.:/=+\-@]+ SHOULD be the same as the Java regex on the AWS documentation: [\p{L}\p{Z}\p{N}_.:/=+\-@]+
match = re.findall(r'[\w\s_.:/=+\-@]+', tag_key)
# Kudos if you can come up with a better way of doing a global search :)
if not len(match) or len(match[0]) < len(tag_key):
raise InvalidTagCharacters(tag_key, param=exception_param) | python | def _validate_tag_key(self, tag_key, exception_param='tags.X.member.key'):
"""Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the message. This is to reflect
the difference between the tag and untag APIs.
:return:
"""
# Validate that the key length is correct:
if len(tag_key) > 128:
raise TagKeyTooBig(tag_key, param=exception_param)
# Validate that the tag key fits the proper Regex:
# [\w\s_.:/=+\-@]+ SHOULD be the same as the Java regex on the AWS documentation: [\p{L}\p{Z}\p{N}_.:/=+\-@]+
match = re.findall(r'[\w\s_.:/=+\-@]+', tag_key)
# Kudos if you can come up with a better way of doing a global search :)
if not len(match) or len(match[0]) < len(tag_key):
raise InvalidTagCharacters(tag_key, param=exception_param) | [
"def",
"_validate_tag_key",
"(",
"self",
",",
"tag_key",
",",
"exception_param",
"=",
"'tags.X.member.key'",
")",
":",
"# Validate that the key length is correct:",
"if",
"len",
"(",
"tag_key",
")",
">",
"128",
":",
"raise",
"TagKeyTooBig",
"(",
"tag_key",
",",
"p... | Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the message. This is to reflect
the difference between the tag and untag APIs.
:return: | [
"Validates",
"the",
"tag",
"key",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iam/models.py#L639-L657 | train | 217,100 |
spulec/moto | moto/iam/models.py | IAMBackend.enable_mfa_device | def enable_mfa_device(self,
user_name,
serial_number,
authentication_code_1,
authentication_code_2):
"""Enable MFA Device for user."""
user = self.get_user(user_name)
if serial_number in user.mfa_devices:
raise IAMConflictException(
"EntityAlreadyExists",
"Device {0} already exists".format(serial_number)
)
user.enable_mfa_device(
serial_number,
authentication_code_1,
authentication_code_2
) | python | def enable_mfa_device(self,
user_name,
serial_number,
authentication_code_1,
authentication_code_2):
"""Enable MFA Device for user."""
user = self.get_user(user_name)
if serial_number in user.mfa_devices:
raise IAMConflictException(
"EntityAlreadyExists",
"Device {0} already exists".format(serial_number)
)
user.enable_mfa_device(
serial_number,
authentication_code_1,
authentication_code_2
) | [
"def",
"enable_mfa_device",
"(",
"self",
",",
"user_name",
",",
"serial_number",
",",
"authentication_code_1",
",",
"authentication_code_2",
")",
":",
"user",
"=",
"self",
".",
"get_user",
"(",
"user_name",
")",
"if",
"serial_number",
"in",
"user",
".",
"mfa_dev... | Enable MFA Device for user. | [
"Enable",
"MFA",
"Device",
"for",
"user",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iam/models.py#L1066-L1083 | train | 217,101 |
spulec/moto | moto/iam/models.py | IAMBackend.deactivate_mfa_device | def deactivate_mfa_device(self, user_name, serial_number):
"""Deactivate and detach MFA Device from user if device exists."""
user = self.get_user(user_name)
if serial_number not in user.mfa_devices:
raise IAMNotFoundException(
"Device {0} not found".format(serial_number)
)
user.deactivate_mfa_device(serial_number) | python | def deactivate_mfa_device(self, user_name, serial_number):
"""Deactivate and detach MFA Device from user if device exists."""
user = self.get_user(user_name)
if serial_number not in user.mfa_devices:
raise IAMNotFoundException(
"Device {0} not found".format(serial_number)
)
user.deactivate_mfa_device(serial_number) | [
"def",
"deactivate_mfa_device",
"(",
"self",
",",
"user_name",
",",
"serial_number",
")",
":",
"user",
"=",
"self",
".",
"get_user",
"(",
"user_name",
")",
"if",
"serial_number",
"not",
"in",
"user",
".",
"mfa_devices",
":",
"raise",
"IAMNotFoundException",
"(... | Deactivate and detach MFA Device from user if device exists. | [
"Deactivate",
"and",
"detach",
"MFA",
"Device",
"from",
"user",
"if",
"device",
"exists",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iam/models.py#L1085-L1093 | train | 217,102 |
spulec/moto | moto/route53/models.py | RecordSet.delete | def delete(self, *args, **kwargs):
''' Not exposed as part of the Route 53 API - used for CloudFormation. args are ignored '''
hosted_zone = route53_backend.get_hosted_zone_by_name(
self.hosted_zone_name)
if not hosted_zone:
hosted_zone = route53_backend.get_hosted_zone(self.hosted_zone_id)
hosted_zone.delete_rrset_by_name(self.name) | python | def delete(self, *args, **kwargs):
''' Not exposed as part of the Route 53 API - used for CloudFormation. args are ignored '''
hosted_zone = route53_backend.get_hosted_zone_by_name(
self.hosted_zone_name)
if not hosted_zone:
hosted_zone = route53_backend.get_hosted_zone(self.hosted_zone_id)
hosted_zone.delete_rrset_by_name(self.name) | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"hosted_zone",
"=",
"route53_backend",
".",
"get_hosted_zone_by_name",
"(",
"self",
".",
"hosted_zone_name",
")",
"if",
"not",
"hosted_zone",
":",
"hosted_zone",
"=",
"route53... | Not exposed as part of the Route 53 API - used for CloudFormation. args are ignored | [
"Not",
"exposed",
"as",
"part",
"of",
"the",
"Route",
"53",
"API",
"-",
"used",
"for",
"CloudFormation",
".",
"args",
"are",
"ignored"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/route53/models.py#L159-L165 | train | 217,103 |
spulec/moto | moto/packages/httpretty/http.py | last_requestline | def last_requestline(sent_data):
"""
Find the last line in sent_data that can be parsed with parse_requestline
"""
for line in reversed(sent_data):
try:
parse_requestline(decode_utf8(line))
except ValueError:
pass
else:
return line | python | def last_requestline(sent_data):
"""
Find the last line in sent_data that can be parsed with parse_requestline
"""
for line in reversed(sent_data):
try:
parse_requestline(decode_utf8(line))
except ValueError:
pass
else:
return line | [
"def",
"last_requestline",
"(",
"sent_data",
")",
":",
"for",
"line",
"in",
"reversed",
"(",
"sent_data",
")",
":",
"try",
":",
"parse_requestline",
"(",
"decode_utf8",
"(",
"line",
")",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"return",
"lin... | Find the last line in sent_data that can be parsed with parse_requestline | [
"Find",
"the",
"last",
"line",
"in",
"sent_data",
"that",
"can",
"be",
"parsed",
"with",
"parse_requestline"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/packages/httpretty/http.py#L144-L154 | train | 217,104 |
spulec/moto | moto/sqs/models.py | Message.attribute_md5 | def attribute_md5(self):
"""
The MD5 of all attributes is calculated by first generating a
utf-8 string from each attribute and MD5-ing the concatenation
of them all. Each attribute is encoded with some bytes that
describe the length of each part and the type of attribute.
Not yet implemented:
List types (https://github.com/aws/aws-sdk-java/blob/7844c64cf248aed889811bf2e871ad6b276a89ca/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/MessageMD5ChecksumHandler.java#L58k)
"""
def utf8(str):
if isinstance(str, six.string_types):
return str.encode('utf-8')
return str
md5 = hashlib.md5()
struct_format = "!I".encode('ascii') # ensure it's a bytestring
for name in sorted(self.message_attributes.keys()):
attr = self.message_attributes[name]
data_type = attr['data_type']
encoded = utf8('')
# Each part of each attribute is encoded right after it's
# own length is packed into a 4-byte integer
# 'timestamp' -> b'\x00\x00\x00\t'
encoded += struct.pack(struct_format, len(utf8(name))) + utf8(name)
# The datatype is additionally given a final byte
# representing which type it is
encoded += struct.pack(struct_format, len(data_type)) + utf8(data_type)
encoded += TRANSPORT_TYPE_ENCODINGS[data_type]
if data_type == 'String' or data_type == 'Number':
value = attr['string_value']
elif data_type == 'Binary':
print(data_type, attr['binary_value'], type(attr['binary_value']))
value = base64.b64decode(attr['binary_value'])
else:
print("Moto hasn't implemented MD5 hashing for {} attributes".format(data_type))
# The following should be enough of a clue to users that
# they are not, in fact, looking at a correct MD5 while
# also following the character and length constraints of
# MD5 so as not to break client softwre
return('deadbeefdeadbeefdeadbeefdeadbeef')
encoded += struct.pack(struct_format, len(utf8(value))) + utf8(value)
md5.update(encoded)
return md5.hexdigest() | python | def attribute_md5(self):
"""
The MD5 of all attributes is calculated by first generating a
utf-8 string from each attribute and MD5-ing the concatenation
of them all. Each attribute is encoded with some bytes that
describe the length of each part and the type of attribute.
Not yet implemented:
List types (https://github.com/aws/aws-sdk-java/blob/7844c64cf248aed889811bf2e871ad6b276a89ca/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/MessageMD5ChecksumHandler.java#L58k)
"""
def utf8(str):
if isinstance(str, six.string_types):
return str.encode('utf-8')
return str
md5 = hashlib.md5()
struct_format = "!I".encode('ascii') # ensure it's a bytestring
for name in sorted(self.message_attributes.keys()):
attr = self.message_attributes[name]
data_type = attr['data_type']
encoded = utf8('')
# Each part of each attribute is encoded right after it's
# own length is packed into a 4-byte integer
# 'timestamp' -> b'\x00\x00\x00\t'
encoded += struct.pack(struct_format, len(utf8(name))) + utf8(name)
# The datatype is additionally given a final byte
# representing which type it is
encoded += struct.pack(struct_format, len(data_type)) + utf8(data_type)
encoded += TRANSPORT_TYPE_ENCODINGS[data_type]
if data_type == 'String' or data_type == 'Number':
value = attr['string_value']
elif data_type == 'Binary':
print(data_type, attr['binary_value'], type(attr['binary_value']))
value = base64.b64decode(attr['binary_value'])
else:
print("Moto hasn't implemented MD5 hashing for {} attributes".format(data_type))
# The following should be enough of a clue to users that
# they are not, in fact, looking at a correct MD5 while
# also following the character and length constraints of
# MD5 so as not to break client softwre
return('deadbeefdeadbeefdeadbeefdeadbeef')
encoded += struct.pack(struct_format, len(utf8(value))) + utf8(value)
md5.update(encoded)
return md5.hexdigest() | [
"def",
"attribute_md5",
"(",
"self",
")",
":",
"def",
"utf8",
"(",
"str",
")",
":",
"if",
"isinstance",
"(",
"str",
",",
"six",
".",
"string_types",
")",
":",
"return",
"str",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"str",
"md5",
"=",
"hashlib"... | The MD5 of all attributes is calculated by first generating a
utf-8 string from each attribute and MD5-ing the concatenation
of them all. Each attribute is encoded with some bytes that
describe the length of each part and the type of attribute.
Not yet implemented:
List types (https://github.com/aws/aws-sdk-java/blob/7844c64cf248aed889811bf2e871ad6b276a89ca/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/MessageMD5ChecksumHandler.java#L58k) | [
"The",
"MD5",
"of",
"all",
"attributes",
"is",
"calculated",
"by",
"first",
"generating",
"a",
"utf",
"-",
"8",
"string",
"from",
"each",
"attribute",
"and",
"MD5",
"-",
"ing",
"the",
"concatenation",
"of",
"them",
"all",
".",
"Each",
"attribute",
"is",
... | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/sqs/models.py#L54-L100 | train | 217,105 |
spulec/moto | moto/sqs/models.py | Message.mark_received | def mark_received(self, visibility_timeout=None):
"""
When a message is received we will set the first receive timestamp,
tap the ``approximate_receive_count`` and the ``visible_at`` time.
"""
if visibility_timeout:
visibility_timeout = int(visibility_timeout)
else:
visibility_timeout = 0
if not self.approximate_first_receive_timestamp:
self.approximate_first_receive_timestamp = int(unix_time_millis())
self.approximate_receive_count += 1
# Make message visible again in the future unless its
# destroyed.
if visibility_timeout:
self.change_visibility(visibility_timeout)
self.receipt_handle = generate_receipt_handle() | python | def mark_received(self, visibility_timeout=None):
"""
When a message is received we will set the first receive timestamp,
tap the ``approximate_receive_count`` and the ``visible_at`` time.
"""
if visibility_timeout:
visibility_timeout = int(visibility_timeout)
else:
visibility_timeout = 0
if not self.approximate_first_receive_timestamp:
self.approximate_first_receive_timestamp = int(unix_time_millis())
self.approximate_receive_count += 1
# Make message visible again in the future unless its
# destroyed.
if visibility_timeout:
self.change_visibility(visibility_timeout)
self.receipt_handle = generate_receipt_handle() | [
"def",
"mark_received",
"(",
"self",
",",
"visibility_timeout",
"=",
"None",
")",
":",
"if",
"visibility_timeout",
":",
"visibility_timeout",
"=",
"int",
"(",
"visibility_timeout",
")",
"else",
":",
"visibility_timeout",
"=",
"0",
"if",
"not",
"self",
".",
"ap... | When a message is received we will set the first receive timestamp,
tap the ``approximate_receive_count`` and the ``visible_at`` time. | [
"When",
"a",
"message",
"is",
"received",
"we",
"will",
"set",
"the",
"first",
"receive",
"timestamp",
"tap",
"the",
"approximate_receive_count",
"and",
"the",
"visible_at",
"time",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/sqs/models.py#L111-L131 | train | 217,106 |
spulec/moto | moto/sqs/models.py | SQSBackend.receive_messages | def receive_messages(self, queue_name, count, wait_seconds_timeout, visibility_timeout):
"""
Attempt to retrieve visible messages from a queue.
If a message was read by client and not deleted it is considered to be
"inflight" and cannot be read. We make attempts to obtain ``count``
messages but we may return less if messages are in-flight or there
are simple not enough messages in the queue.
:param string queue_name: The name of the queue to read from.
:param int count: The maximum amount of messages to retrieve.
:param int visibility_timeout: The number of seconds the message should remain invisible to other queue readers.
:param int wait_seconds_timeout: The duration (in seconds) for which the call waits for a message to arrive in
the queue before returning. If a message is available, the call returns sooner than WaitTimeSeconds
"""
queue = self.get_queue(queue_name)
result = []
previous_result_count = len(result)
polling_end = unix_time() + wait_seconds_timeout
# queue.messages only contains visible messages
while True:
if result or (wait_seconds_timeout and unix_time() > polling_end):
break
messages_to_dlq = []
for message in queue.messages:
if not message.visible:
continue
if message in queue.pending_messages:
# The message is pending but is visible again, so the
# consumer must have timed out.
queue.pending_messages.remove(message)
if message.group_id and queue.fifo_queue:
if message.group_id in queue.pending_message_groups:
# There is already one active message with the same
# group, so we cannot deliver this one.
continue
queue.pending_messages.add(message)
if queue.dead_letter_queue is not None and message.approximate_receive_count >= queue.redrive_policy['maxReceiveCount']:
messages_to_dlq.append(message)
continue
message.mark_received(
visibility_timeout=visibility_timeout
)
result.append(message)
if len(result) >= count:
break
for message in messages_to_dlq:
queue._messages.remove(message)
queue.dead_letter_queue.add_message(message)
if previous_result_count == len(result):
if wait_seconds_timeout == 0:
# There is timeout and we have added no additional results,
# so break to avoid an infinite loop.
break
import time
time.sleep(0.01)
continue
previous_result_count = len(result)
return result | python | def receive_messages(self, queue_name, count, wait_seconds_timeout, visibility_timeout):
"""
Attempt to retrieve visible messages from a queue.
If a message was read by client and not deleted it is considered to be
"inflight" and cannot be read. We make attempts to obtain ``count``
messages but we may return less if messages are in-flight or there
are simple not enough messages in the queue.
:param string queue_name: The name of the queue to read from.
:param int count: The maximum amount of messages to retrieve.
:param int visibility_timeout: The number of seconds the message should remain invisible to other queue readers.
:param int wait_seconds_timeout: The duration (in seconds) for which the call waits for a message to arrive in
the queue before returning. If a message is available, the call returns sooner than WaitTimeSeconds
"""
queue = self.get_queue(queue_name)
result = []
previous_result_count = len(result)
polling_end = unix_time() + wait_seconds_timeout
# queue.messages only contains visible messages
while True:
if result or (wait_seconds_timeout and unix_time() > polling_end):
break
messages_to_dlq = []
for message in queue.messages:
if not message.visible:
continue
if message in queue.pending_messages:
# The message is pending but is visible again, so the
# consumer must have timed out.
queue.pending_messages.remove(message)
if message.group_id and queue.fifo_queue:
if message.group_id in queue.pending_message_groups:
# There is already one active message with the same
# group, so we cannot deliver this one.
continue
queue.pending_messages.add(message)
if queue.dead_letter_queue is not None and message.approximate_receive_count >= queue.redrive_policy['maxReceiveCount']:
messages_to_dlq.append(message)
continue
message.mark_received(
visibility_timeout=visibility_timeout
)
result.append(message)
if len(result) >= count:
break
for message in messages_to_dlq:
queue._messages.remove(message)
queue.dead_letter_queue.add_message(message)
if previous_result_count == len(result):
if wait_seconds_timeout == 0:
# There is timeout and we have added no additional results,
# so break to avoid an infinite loop.
break
import time
time.sleep(0.01)
continue
previous_result_count = len(result)
return result | [
"def",
"receive_messages",
"(",
"self",
",",
"queue_name",
",",
"count",
",",
"wait_seconds_timeout",
",",
"visibility_timeout",
")",
":",
"queue",
"=",
"self",
".",
"get_queue",
"(",
"queue_name",
")",
"result",
"=",
"[",
"]",
"previous_result_count",
"=",
"l... | Attempt to retrieve visible messages from a queue.
If a message was read by client and not deleted it is considered to be
"inflight" and cannot be read. We make attempts to obtain ``count``
messages but we may return less if messages are in-flight or there
are simple not enough messages in the queue.
:param string queue_name: The name of the queue to read from.
:param int count: The maximum amount of messages to retrieve.
:param int visibility_timeout: The number of seconds the message should remain invisible to other queue readers.
:param int wait_seconds_timeout: The duration (in seconds) for which the call waits for a message to arrive in
the queue before returning. If a message is available, the call returns sooner than WaitTimeSeconds | [
"Attempt",
"to",
"retrieve",
"visible",
"messages",
"from",
"a",
"queue",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/sqs/models.py#L469-L542 | train | 217,107 |
spulec/moto | moto/dynamodb2/models.py | DynamoDBBackend.get_table_keys_name | def get_table_keys_name(self, table_name, keys):
"""
Given a set of keys, extracts the key and range key
"""
table = self.tables.get(table_name)
if not table:
return None, None
else:
if len(keys) == 1:
for key in keys:
if key in table.hash_key_names:
return key, None
# for potential_hash, potential_range in zip(table.hash_key_names, table.range_key_names):
# if set([potential_hash, potential_range]) == set(keys):
# return potential_hash, potential_range
potential_hash, potential_range = None, None
for key in set(keys):
if key in table.hash_key_names:
potential_hash = key
elif key in table.range_key_names:
potential_range = key
return potential_hash, potential_range | python | def get_table_keys_name(self, table_name, keys):
"""
Given a set of keys, extracts the key and range key
"""
table = self.tables.get(table_name)
if not table:
return None, None
else:
if len(keys) == 1:
for key in keys:
if key in table.hash_key_names:
return key, None
# for potential_hash, potential_range in zip(table.hash_key_names, table.range_key_names):
# if set([potential_hash, potential_range]) == set(keys):
# return potential_hash, potential_range
potential_hash, potential_range = None, None
for key in set(keys):
if key in table.hash_key_names:
potential_hash = key
elif key in table.range_key_names:
potential_range = key
return potential_hash, potential_range | [
"def",
"get_table_keys_name",
"(",
"self",
",",
"table_name",
",",
"keys",
")",
":",
"table",
"=",
"self",
".",
"tables",
".",
"get",
"(",
"table_name",
")",
"if",
"not",
"table",
":",
"return",
"None",
",",
"None",
"else",
":",
"if",
"len",
"(",
"ke... | Given a set of keys, extracts the key and range key | [
"Given",
"a",
"set",
"of",
"keys",
"extracts",
"the",
"key",
"and",
"range",
"key"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/dynamodb2/models.py#L834-L855 | train | 217,108 |
spulec/moto | moto/instance_metadata/responses.py | InstanceMetadataResponse.metadata_response | def metadata_response(self, request, full_url, headers):
"""
Mock response for localhost metadata
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
"""
parsed_url = urlparse(full_url)
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
credentials = dict(
AccessKeyId="test-key",
SecretAccessKey="test-secret-key",
Token="test-session-token",
Expiration=tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ")
)
path = parsed_url.path
meta_data_prefix = "/latest/meta-data/"
# Strip prefix if it is there
if path.startswith(meta_data_prefix):
path = path[len(meta_data_prefix):]
if path == '':
result = 'iam'
elif path == 'iam':
result = json.dumps({
'security-credentials': {
'default-role': credentials
}
})
elif path == 'iam/security-credentials/':
result = 'default-role'
elif path == 'iam/security-credentials/default-role':
result = json.dumps(credentials)
else:
raise NotImplementedError(
"The {0} metadata path has not been implemented".format(path))
return 200, headers, result | python | def metadata_response(self, request, full_url, headers):
"""
Mock response for localhost metadata
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
"""
parsed_url = urlparse(full_url)
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
credentials = dict(
AccessKeyId="test-key",
SecretAccessKey="test-secret-key",
Token="test-session-token",
Expiration=tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ")
)
path = parsed_url.path
meta_data_prefix = "/latest/meta-data/"
# Strip prefix if it is there
if path.startswith(meta_data_prefix):
path = path[len(meta_data_prefix):]
if path == '':
result = 'iam'
elif path == 'iam':
result = json.dumps({
'security-credentials': {
'default-role': credentials
}
})
elif path == 'iam/security-credentials/':
result = 'default-role'
elif path == 'iam/security-credentials/default-role':
result = json.dumps(credentials)
else:
raise NotImplementedError(
"The {0} metadata path has not been implemented".format(path))
return 200, headers, result | [
"def",
"metadata_response",
"(",
"self",
",",
"request",
",",
"full_url",
",",
"headers",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"full_url",
")",
"tomorrow",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta... | Mock response for localhost metadata
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html | [
"Mock",
"response",
"for",
"localhost",
"metadata"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/instance_metadata/responses.py#L11-L49 | train | 217,109 |
spulec/moto | moto/cloudwatch/models.py | CloudWatchBackend._list_element_starts_with | def _list_element_starts_with(items, needle):
"""True of any of the list elements starts with needle"""
for item in items:
if item.startswith(needle):
return True
return False | python | def _list_element_starts_with(items, needle):
"""True of any of the list elements starts with needle"""
for item in items:
if item.startswith(needle):
return True
return False | [
"def",
"_list_element_starts_with",
"(",
"items",
",",
"needle",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"item",
".",
"startswith",
"(",
"needle",
")",
":",
"return",
"True",
"return",
"False"
] | True of any of the list elements starts with needle | [
"True",
"of",
"any",
"of",
"the",
"list",
"elements",
"starts",
"with",
"needle"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/cloudwatch/models.py#L193-L198 | train | 217,110 |
spulec/moto | moto/batch/models.py | BatchBackend._validate_compute_resources | def _validate_compute_resources(self, cr):
"""
Checks contents of sub dictionary for managed clusters
:param cr: computeResources
:type cr: dict
"""
for param in ('instanceRole', 'maxvCpus', 'minvCpus', 'instanceTypes', 'securityGroupIds', 'subnets', 'type'):
if param not in cr:
raise InvalidParameterValueException('computeResources must contain {0}'.format(param))
if self.iam_backend.get_role_by_arn(cr['instanceRole']) is None:
raise InvalidParameterValueException('could not find instanceRole {0}'.format(cr['instanceRole']))
if cr['maxvCpus'] < 0:
raise InvalidParameterValueException('maxVCpus must be positive')
if cr['minvCpus'] < 0:
raise InvalidParameterValueException('minVCpus must be positive')
if cr['maxvCpus'] < cr['minvCpus']:
raise InvalidParameterValueException('maxVCpus must be greater than minvCpus')
if len(cr['instanceTypes']) == 0:
raise InvalidParameterValueException('At least 1 instance type must be provided')
for instance_type in cr['instanceTypes']:
if instance_type == 'optimal':
pass # Optimal should pick from latest of current gen
elif instance_type not in EC2_INSTANCE_TYPES:
raise InvalidParameterValueException('Instance type {0} does not exist'.format(instance_type))
for sec_id in cr['securityGroupIds']:
if self.ec2_backend.get_security_group_from_id(sec_id) is None:
raise InvalidParameterValueException('security group {0} does not exist'.format(sec_id))
if len(cr['securityGroupIds']) == 0:
raise InvalidParameterValueException('At least 1 security group must be provided')
for subnet_id in cr['subnets']:
try:
self.ec2_backend.get_subnet(subnet_id)
except InvalidSubnetIdError:
raise InvalidParameterValueException('subnet {0} does not exist'.format(subnet_id))
if len(cr['subnets']) == 0:
raise InvalidParameterValueException('At least 1 subnet must be provided')
if cr['type'] not in ('EC2', 'SPOT'):
raise InvalidParameterValueException('computeResources.type must be either EC2 | SPOT')
if cr['type'] == 'SPOT':
raise InternalFailure('SPOT NOT SUPPORTED YET') | python | def _validate_compute_resources(self, cr):
"""
Checks contents of sub dictionary for managed clusters
:param cr: computeResources
:type cr: dict
"""
for param in ('instanceRole', 'maxvCpus', 'minvCpus', 'instanceTypes', 'securityGroupIds', 'subnets', 'type'):
if param not in cr:
raise InvalidParameterValueException('computeResources must contain {0}'.format(param))
if self.iam_backend.get_role_by_arn(cr['instanceRole']) is None:
raise InvalidParameterValueException('could not find instanceRole {0}'.format(cr['instanceRole']))
if cr['maxvCpus'] < 0:
raise InvalidParameterValueException('maxVCpus must be positive')
if cr['minvCpus'] < 0:
raise InvalidParameterValueException('minVCpus must be positive')
if cr['maxvCpus'] < cr['minvCpus']:
raise InvalidParameterValueException('maxVCpus must be greater than minvCpus')
if len(cr['instanceTypes']) == 0:
raise InvalidParameterValueException('At least 1 instance type must be provided')
for instance_type in cr['instanceTypes']:
if instance_type == 'optimal':
pass # Optimal should pick from latest of current gen
elif instance_type not in EC2_INSTANCE_TYPES:
raise InvalidParameterValueException('Instance type {0} does not exist'.format(instance_type))
for sec_id in cr['securityGroupIds']:
if self.ec2_backend.get_security_group_from_id(sec_id) is None:
raise InvalidParameterValueException('security group {0} does not exist'.format(sec_id))
if len(cr['securityGroupIds']) == 0:
raise InvalidParameterValueException('At least 1 security group must be provided')
for subnet_id in cr['subnets']:
try:
self.ec2_backend.get_subnet(subnet_id)
except InvalidSubnetIdError:
raise InvalidParameterValueException('subnet {0} does not exist'.format(subnet_id))
if len(cr['subnets']) == 0:
raise InvalidParameterValueException('At least 1 subnet must be provided')
if cr['type'] not in ('EC2', 'SPOT'):
raise InvalidParameterValueException('computeResources.type must be either EC2 | SPOT')
if cr['type'] == 'SPOT':
raise InternalFailure('SPOT NOT SUPPORTED YET') | [
"def",
"_validate_compute_resources",
"(",
"self",
",",
"cr",
")",
":",
"for",
"param",
"in",
"(",
"'instanceRole'",
",",
"'maxvCpus'",
",",
"'minvCpus'",
",",
"'instanceTypes'",
",",
"'securityGroupIds'",
",",
"'subnets'",
",",
"'type'",
")",
":",
"if",
"para... | Checks contents of sub dictionary for managed clusters
:param cr: computeResources
:type cr: dict | [
"Checks",
"contents",
"of",
"sub",
"dictionary",
"for",
"managed",
"clusters"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/batch/models.py#L669-L716 | train | 217,111 |
spulec/moto | moto/batch/models.py | BatchBackend.find_min_instances_to_meet_vcpus | def find_min_instances_to_meet_vcpus(instance_types, target):
"""
Finds the minimum needed instances to meed a vcpu target
:param instance_types: Instance types, like ['t2.medium', 't2.small']
:type instance_types: list of str
:param target: VCPU target
:type target: float
:return: List of instance types
:rtype: list of str
"""
# vcpus = [ (vcpus, instance_type), (vcpus, instance_type), ... ]
instance_vcpus = []
instances = []
for instance_type in instance_types:
if instance_type == 'optimal':
instance_type = 'm4.4xlarge'
instance_vcpus.append(
(EC2_INSTANCE_TYPES[instance_type]['vcpus'], instance_type)
)
instance_vcpus = sorted(instance_vcpus, key=lambda item: item[0], reverse=True)
# Loop through,
# if biggest instance type smaller than target, and len(instance_types)> 1, then use biggest type
# if biggest instance type bigger than target, and len(instance_types)> 1, then remove it and move on
# if biggest instance type bigger than target and len(instan_types) == 1 then add instance and finish
# if biggest instance type smaller than target and len(instan_types) == 1 then loop adding instances until target == 0
# ^^ boils down to keep adding last till target vcpus is negative
# #Algorithm ;-) ... Could probably be done better with some quality lambdas
while target > 0:
current_vcpu, current_instance = instance_vcpus[0]
if len(instance_vcpus) > 1:
if current_vcpu <= target:
target -= current_vcpu
instances.append(current_instance)
else:
# try next biggest instance
instance_vcpus.pop(0)
else:
# Were on the last instance
target -= current_vcpu
instances.append(current_instance)
return instances | python | def find_min_instances_to_meet_vcpus(instance_types, target):
"""
Finds the minimum needed instances to meed a vcpu target
:param instance_types: Instance types, like ['t2.medium', 't2.small']
:type instance_types: list of str
:param target: VCPU target
:type target: float
:return: List of instance types
:rtype: list of str
"""
# vcpus = [ (vcpus, instance_type), (vcpus, instance_type), ... ]
instance_vcpus = []
instances = []
for instance_type in instance_types:
if instance_type == 'optimal':
instance_type = 'm4.4xlarge'
instance_vcpus.append(
(EC2_INSTANCE_TYPES[instance_type]['vcpus'], instance_type)
)
instance_vcpus = sorted(instance_vcpus, key=lambda item: item[0], reverse=True)
# Loop through,
# if biggest instance type smaller than target, and len(instance_types)> 1, then use biggest type
# if biggest instance type bigger than target, and len(instance_types)> 1, then remove it and move on
# if biggest instance type bigger than target and len(instan_types) == 1 then add instance and finish
# if biggest instance type smaller than target and len(instan_types) == 1 then loop adding instances until target == 0
# ^^ boils down to keep adding last till target vcpus is negative
# #Algorithm ;-) ... Could probably be done better with some quality lambdas
while target > 0:
current_vcpu, current_instance = instance_vcpus[0]
if len(instance_vcpus) > 1:
if current_vcpu <= target:
target -= current_vcpu
instances.append(current_instance)
else:
# try next biggest instance
instance_vcpus.pop(0)
else:
# Were on the last instance
target -= current_vcpu
instances.append(current_instance)
return instances | [
"def",
"find_min_instances_to_meet_vcpus",
"(",
"instance_types",
",",
"target",
")",
":",
"# vcpus = [ (vcpus, instance_type), (vcpus, instance_type), ... ]",
"instance_vcpus",
"=",
"[",
"]",
"instances",
"=",
"[",
"]",
"for",
"instance_type",
"in",
"instance_types",
":",
... | Finds the minimum needed instances to meed a vcpu target
:param instance_types: Instance types, like ['t2.medium', 't2.small']
:type instance_types: list of str
:param target: VCPU target
:type target: float
:return: List of instance types
:rtype: list of str | [
"Finds",
"the",
"minimum",
"needed",
"instances",
"to",
"meed",
"a",
"vcpu",
"target"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/batch/models.py#L719-L766 | train | 217,112 |
spulec/moto | moto/batch/models.py | BatchBackend.create_job_queue | def create_job_queue(self, queue_name, priority, state, compute_env_order):
"""
Create a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
:param compute_env_order: Compute environment list
:type compute_env_order: list of dict
:return: Tuple of Name, ARN
:rtype: tuple of str
"""
for variable, var_name in ((queue_name, 'jobQueueName'), (priority, 'priority'), (state, 'state'), (compute_env_order, 'computeEnvironmentOrder')):
if variable is None:
raise ClientException('{0} must be provided'.format(var_name))
if state not in ('ENABLED', 'DISABLED'):
raise ClientException('state {0} must be one of ENABLED | DISABLED'.format(state))
if self.get_job_queue_by_name(queue_name) is not None:
raise ClientException('Job queue {0} already exists'.format(queue_name))
if len(compute_env_order) == 0:
raise ClientException('At least 1 compute environment must be provided')
try:
# orders and extracts computeEnvironment names
ordered_compute_environments = [item['computeEnvironment'] for item in sorted(compute_env_order, key=lambda x: x['order'])]
env_objects = []
# Check each ARN exists, then make a list of compute env's
for arn in ordered_compute_environments:
env = self.get_compute_environment_by_arn(arn)
if env is None:
raise ClientException('Compute environment {0} does not exist'.format(arn))
env_objects.append(env)
except Exception:
raise ClientException('computeEnvironmentOrder is malformed')
# Create new Job Queue
queue = JobQueue(queue_name, priority, state, env_objects, compute_env_order, self.region_name)
self._job_queues[queue.arn] = queue
return queue_name, queue.arn | python | def create_job_queue(self, queue_name, priority, state, compute_env_order):
"""
Create a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
:param compute_env_order: Compute environment list
:type compute_env_order: list of dict
:return: Tuple of Name, ARN
:rtype: tuple of str
"""
for variable, var_name in ((queue_name, 'jobQueueName'), (priority, 'priority'), (state, 'state'), (compute_env_order, 'computeEnvironmentOrder')):
if variable is None:
raise ClientException('{0} must be provided'.format(var_name))
if state not in ('ENABLED', 'DISABLED'):
raise ClientException('state {0} must be one of ENABLED | DISABLED'.format(state))
if self.get_job_queue_by_name(queue_name) is not None:
raise ClientException('Job queue {0} already exists'.format(queue_name))
if len(compute_env_order) == 0:
raise ClientException('At least 1 compute environment must be provided')
try:
# orders and extracts computeEnvironment names
ordered_compute_environments = [item['computeEnvironment'] for item in sorted(compute_env_order, key=lambda x: x['order'])]
env_objects = []
# Check each ARN exists, then make a list of compute env's
for arn in ordered_compute_environments:
env = self.get_compute_environment_by_arn(arn)
if env is None:
raise ClientException('Compute environment {0} does not exist'.format(arn))
env_objects.append(env)
except Exception:
raise ClientException('computeEnvironmentOrder is malformed')
# Create new Job Queue
queue = JobQueue(queue_name, priority, state, env_objects, compute_env_order, self.region_name)
self._job_queues[queue.arn] = queue
return queue_name, queue.arn | [
"def",
"create_job_queue",
"(",
"self",
",",
"queue_name",
",",
"priority",
",",
"state",
",",
"compute_env_order",
")",
":",
"for",
"variable",
",",
"var_name",
"in",
"(",
"(",
"queue_name",
",",
"'jobQueueName'",
")",
",",
"(",
"priority",
",",
"'priority'... | Create a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
:param compute_env_order: Compute environment list
:type compute_env_order: list of dict
:return: Tuple of Name, ARN
:rtype: tuple of str | [
"Create",
"a",
"job",
"queue"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/batch/models.py#L814-L857 | train | 217,113 |
spulec/moto | moto/batch/models.py | BatchBackend.update_job_queue | def update_job_queue(self, queue_name, priority, state, compute_env_order):
"""
Update a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
:param compute_env_order: Compute environment list
:type compute_env_order: list of dict
:return: Tuple of Name, ARN
:rtype: tuple of str
"""
if queue_name is None:
raise ClientException('jobQueueName must be provided')
job_queue = self.get_job_queue(queue_name)
if job_queue is None:
raise ClientException('Job queue {0} does not exist'.format(queue_name))
if state is not None:
if state not in ('ENABLED', 'DISABLED'):
raise ClientException('state {0} must be one of ENABLED | DISABLED'.format(state))
job_queue.state = state
if compute_env_order is not None:
if len(compute_env_order) == 0:
raise ClientException('At least 1 compute environment must be provided')
try:
# orders and extracts computeEnvironment names
ordered_compute_environments = [item['computeEnvironment'] for item in sorted(compute_env_order, key=lambda x: x['order'])]
env_objects = []
# Check each ARN exists, then make a list of compute env's
for arn in ordered_compute_environments:
env = self.get_compute_environment_by_arn(arn)
if env is None:
raise ClientException('Compute environment {0} does not exist'.format(arn))
env_objects.append(env)
except Exception:
raise ClientException('computeEnvironmentOrder is malformed')
job_queue.env_order_json = compute_env_order
job_queue.environments = env_objects
if priority is not None:
job_queue.priority = priority
return queue_name, job_queue.arn | python | def update_job_queue(self, queue_name, priority, state, compute_env_order):
"""
Update a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
:param compute_env_order: Compute environment list
:type compute_env_order: list of dict
:return: Tuple of Name, ARN
:rtype: tuple of str
"""
if queue_name is None:
raise ClientException('jobQueueName must be provided')
job_queue = self.get_job_queue(queue_name)
if job_queue is None:
raise ClientException('Job queue {0} does not exist'.format(queue_name))
if state is not None:
if state not in ('ENABLED', 'DISABLED'):
raise ClientException('state {0} must be one of ENABLED | DISABLED'.format(state))
job_queue.state = state
if compute_env_order is not None:
if len(compute_env_order) == 0:
raise ClientException('At least 1 compute environment must be provided')
try:
# orders and extracts computeEnvironment names
ordered_compute_environments = [item['computeEnvironment'] for item in sorted(compute_env_order, key=lambda x: x['order'])]
env_objects = []
# Check each ARN exists, then make a list of compute env's
for arn in ordered_compute_environments:
env = self.get_compute_environment_by_arn(arn)
if env is None:
raise ClientException('Compute environment {0} does not exist'.format(arn))
env_objects.append(env)
except Exception:
raise ClientException('computeEnvironmentOrder is malformed')
job_queue.env_order_json = compute_env_order
job_queue.environments = env_objects
if priority is not None:
job_queue.priority = priority
return queue_name, job_queue.arn | [
"def",
"update_job_queue",
"(",
"self",
",",
"queue_name",
",",
"priority",
",",
"state",
",",
"compute_env_order",
")",
":",
"if",
"queue_name",
"is",
"None",
":",
"raise",
"ClientException",
"(",
"'jobQueueName must be provided'",
")",
"job_queue",
"=",
"self",
... | Update a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
:param compute_env_order: Compute environment list
:type compute_env_order: list of dict
:return: Tuple of Name, ARN
:rtype: tuple of str | [
"Update",
"a",
"job",
"queue"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/batch/models.py#L874-L924 | train | 217,114 |
chrismattmann/tika-python | tika/tika.py | toFilename | def toFilename(url):
'''
gets url and returns filename
'''
urlp = urlparse(url)
path = urlp.path
if not path:
path = "file_{}".format(int(time.time()))
value = re.sub(r'[^\w\s\.\-]', '-', path).strip().lower()
return re.sub(r'[-\s]+', '-', value).strip("-")[-200:] | python | def toFilename(url):
'''
gets url and returns filename
'''
urlp = urlparse(url)
path = urlp.path
if not path:
path = "file_{}".format(int(time.time()))
value = re.sub(r'[^\w\s\.\-]', '-', path).strip().lower()
return re.sub(r'[-\s]+', '-', value).strip("-")[-200:] | [
"def",
"toFilename",
"(",
"url",
")",
":",
"urlp",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"urlp",
".",
"path",
"if",
"not",
"path",
":",
"path",
"=",
"\"file_{}\"",
".",
"format",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
... | gets url and returns filename | [
"gets",
"url",
"and",
"returns",
"filename"
] | ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L672-L681 | train | 217,115 |
chrismattmann/tika-python | tika/tika.py | main | def main(argv=None):
"""Run Tika from command line according to USAGE."""
global Verbose
global EncodeUtf8
global csvOutput
if argv is None:
argv = sys.argv
if (len(argv) < 3 and not (('-h' in argv) or ('--help' in argv))):
log.exception('Bad args')
raise TikaException('Bad args')
try:
opts, argv = getopt.getopt(argv[1:], 'hi:s:o:p:v:e:c',
['help', 'install=', 'server=', 'output=', 'port=', 'verbose', 'encode', 'csv'])
except getopt.GetoptError as opt_error:
msg, bad_opt = opt_error
log.exception("%s error: Bad option: %s, %s" % (argv[0], bad_opt, msg))
raise TikaException("%s error: Bad option: %s, %s" % (argv[0], bad_opt, msg))
tikaServerJar = TikaServerJar
serverHost = ServerHost
outDir = '.'
port = Port
for opt, val in opts:
if opt in ('-h', '--help'): echo2(USAGE); sys.exit()
elif opt in ('--install'): tikaServerJar = val
elif opt in ('--server'): serverHost = val
elif opt in ('-o', '--output'): outDir = val
elif opt in ('--port'): port = val
elif opt in ('-v', '--verbose'): Verbose = 1
elif opt in ('-e', '--encode'): EncodeUtf8 = 1
elif opt in ('-c', '--csv'): csvOutput = 1
else:
raise TikaException(USAGE)
cmd = argv[0]
option = argv[1]
try:
paths = argv[2:]
except:
paths = None
return runCommand(cmd, option, paths, port, outDir, serverHost=serverHost, tikaServerJar=tikaServerJar, verbose=Verbose, encode=EncodeUtf8) | python | def main(argv=None):
"""Run Tika from command line according to USAGE."""
global Verbose
global EncodeUtf8
global csvOutput
if argv is None:
argv = sys.argv
if (len(argv) < 3 and not (('-h' in argv) or ('--help' in argv))):
log.exception('Bad args')
raise TikaException('Bad args')
try:
opts, argv = getopt.getopt(argv[1:], 'hi:s:o:p:v:e:c',
['help', 'install=', 'server=', 'output=', 'port=', 'verbose', 'encode', 'csv'])
except getopt.GetoptError as opt_error:
msg, bad_opt = opt_error
log.exception("%s error: Bad option: %s, %s" % (argv[0], bad_opt, msg))
raise TikaException("%s error: Bad option: %s, %s" % (argv[0], bad_opt, msg))
tikaServerJar = TikaServerJar
serverHost = ServerHost
outDir = '.'
port = Port
for opt, val in opts:
if opt in ('-h', '--help'): echo2(USAGE); sys.exit()
elif opt in ('--install'): tikaServerJar = val
elif opt in ('--server'): serverHost = val
elif opt in ('-o', '--output'): outDir = val
elif opt in ('--port'): port = val
elif opt in ('-v', '--verbose'): Verbose = 1
elif opt in ('-e', '--encode'): EncodeUtf8 = 1
elif opt in ('-c', '--csv'): csvOutput = 1
else:
raise TikaException(USAGE)
cmd = argv[0]
option = argv[1]
try:
paths = argv[2:]
except:
paths = None
return runCommand(cmd, option, paths, port, outDir, serverHost=serverHost, tikaServerJar=tikaServerJar, verbose=Verbose, encode=EncodeUtf8) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"global",
"Verbose",
"global",
"EncodeUtf8",
"global",
"csvOutput",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"if",
"(",
"len",
"(",
"argv",
")",
"<",
"3",
"and",
"not",
"("... | Run Tika from command line according to USAGE. | [
"Run",
"Tika",
"from",
"command",
"line",
"according",
"to",
"USAGE",
"."
] | ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L771-L812 | train | 217,116 |
ahupp/python-magic | magic.py | from_file | def from_file(filename, mime=False):
""""
Accepts a filename and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_file("testdata/test.pdf", mime=True)
'application/pdf'
"""
m = _get_magic_type(mime)
return m.from_file(filename) | python | def from_file(filename, mime=False):
""""
Accepts a filename and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_file("testdata/test.pdf", mime=True)
'application/pdf'
"""
m = _get_magic_type(mime)
return m.from_file(filename) | [
"def",
"from_file",
"(",
"filename",
",",
"mime",
"=",
"False",
")",
":",
"m",
"=",
"_get_magic_type",
"(",
"mime",
")",
"return",
"m",
".",
"from_file",
"(",
"filename",
")"
] | Accepts a filename and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_file("testdata/test.pdf", mime=True)
'application/pdf' | [
"Accepts",
"a",
"filename",
"and",
"returns",
"the",
"detected",
"filetype",
".",
"Return",
"value",
"is",
"the",
"mimetype",
"if",
"mime",
"=",
"True",
"otherwise",
"a",
"human",
"readable",
"name",
"."
] | c5b386b08bfbc01330e2ba836d97749d242429dc | https://github.com/ahupp/python-magic/blob/c5b386b08bfbc01330e2ba836d97749d242429dc/magic.py#L133-L143 | train | 217,117 |
ahupp/python-magic | magic.py | from_buffer | def from_buffer(buffer, mime=False):
"""
Accepts a binary string and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2'
"""
m = _get_magic_type(mime)
return m.from_buffer(buffer) | python | def from_buffer(buffer, mime=False):
"""
Accepts a binary string and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2'
"""
m = _get_magic_type(mime)
return m.from_buffer(buffer) | [
"def",
"from_buffer",
"(",
"buffer",
",",
"mime",
"=",
"False",
")",
":",
"m",
"=",
"_get_magic_type",
"(",
"mime",
")",
"return",
"m",
".",
"from_buffer",
"(",
"buffer",
")"
] | Accepts a binary string and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2' | [
"Accepts",
"a",
"binary",
"string",
"and",
"returns",
"the",
"detected",
"filetype",
".",
"Return",
"value",
"is",
"the",
"mimetype",
"if",
"mime",
"=",
"True",
"otherwise",
"a",
"human",
"readable",
"name",
"."
] | c5b386b08bfbc01330e2ba836d97749d242429dc | https://github.com/ahupp/python-magic/blob/c5b386b08bfbc01330e2ba836d97749d242429dc/magic.py#L146-L156 | train | 217,118 |
yhat/ggpy | ggplot/colors/palettes.py | desaturate | def desaturate(color, prop):
"""Decrease the saturation channel of a color by some percent.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
prop : float
saturation channel of color will be multiplied by this value
Returns
-------
new_color : rgb tuple
desaturated color code in RGB tuple representation
"""
# Check inputs
if not 0 <= prop <= 1:
raise ValueError("prop must be between 0 and 1")
# Get rgb tuple rep
rgb = mplcol.colorConverter.to_rgb(color)
# Convert to hls
h, l, s = colorsys.rgb_to_hls(*rgb)
# Desaturate the saturation channel
s *= prop
# Convert back to rgb
new_color = colorsys.hls_to_rgb(h, l, s)
return new_color | python | def desaturate(color, prop):
"""Decrease the saturation channel of a color by some percent.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
prop : float
saturation channel of color will be multiplied by this value
Returns
-------
new_color : rgb tuple
desaturated color code in RGB tuple representation
"""
# Check inputs
if not 0 <= prop <= 1:
raise ValueError("prop must be between 0 and 1")
# Get rgb tuple rep
rgb = mplcol.colorConverter.to_rgb(color)
# Convert to hls
h, l, s = colorsys.rgb_to_hls(*rgb)
# Desaturate the saturation channel
s *= prop
# Convert back to rgb
new_color = colorsys.hls_to_rgb(h, l, s)
return new_color | [
"def",
"desaturate",
"(",
"color",
",",
"prop",
")",
":",
"# Check inputs",
"if",
"not",
"0",
"<=",
"prop",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"\"prop must be between 0 and 1\"",
")",
"# Get rgb tuple rep",
"rgb",
"=",
"mplcol",
".",
"colorConverter",
... | Decrease the saturation channel of a color by some percent.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
prop : float
saturation channel of color will be multiplied by this value
Returns
-------
new_color : rgb tuple
desaturated color code in RGB tuple representation | [
"Decrease",
"the",
"saturation",
"channel",
"of",
"a",
"color",
"by",
"some",
"percent",
"."
] | b6d23c22d52557b983da8ce7a3a6992501dadcd6 | https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L17-L49 | train | 217,119 |
yhat/ggpy | ggplot/colors/palettes.py | color_palette | def color_palette(name=None, n_colors=6, desat=None):
"""Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any matplotlib palette
Matplotlib paletes can be specified as reversed palettes by appending
"_r" to the name or as dark palettes by appending "_d" to the name.
This function can also be used in a ``with`` statement to temporarily
set the color cycle for a plot or set of plots.
Parameters
----------
name: None, string, or sequence
Name of palette or None to return current palette. If a
sequence, input colors are used but possibly cycled and
desaturated.
n_colors : int
Number of colors in the palette. If larger than the number of
colors in the palette, they will cycle.
desat : float
Value to desaturate each color by.
Returns
-------
palette : list of RGB tuples.
Color palette.
Examples
--------
>>> p = color_palette("muted")
>>> p = color_palette("Blues_d", 10)
>>> p = color_palette("Set1", desat=.7)
>>> import matplotlib.pyplot as plt
>>> with color_palette("husl", 8):
... f, ax = plt.subplots()
... ax.plot(x, y) # doctest: +SKIP
See Also
--------
set_palette : set the default color cycle for all plots.
axes_style : define parameters to set the style of plots
plotting_context : define parameters to scale plot elements
"""
seaborn_palettes = dict(
deep=["#4C72B0", "#55A868", "#C44E52",
"#8172B2", "#CCB974", "#64B5CD"],
muted=["#4878CF", "#6ACC65", "#D65F5F",
"#B47CC7", "#C4AD66", "#77BEDB"],
pastel=["#92C6FF", "#97F0AA", "#FF9F9A",
"#D0BBFF", "#FFFEA3", "#B0E0E6"],
bright=["#003FFF", "#03ED3A", "#E8000B",
"#8A2BE2", "#FFC400", "#00D7FF"],
dark=["#001C7F", "#017517", "#8C0900",
"#7600A1", "#B8860B", "#006374"],
colorblind=["#0072B2", "#009E73", "#D55E00",
"#CC79A7", "#F0E442", "#56B4E9"],
)
if name is None:
palette = mpl.rcParams["axes.color_cycle"]
elif not isinstance(name, string_types):
palette = name
elif name == "hls":
palette = hls_palette(n_colors)
elif name == "husl":
palette = husl_palette(n_colors)
elif name in seaborn_palettes:
palette = seaborn_palettes[name]
elif name in dir(mpl.cm):
palette = mpl_palette(name, n_colors)
elif name[:-2] in dir(mpl.cm):
palette = mpl_palette(name, n_colors)
else:
raise ValueError("%s is not a valid palette name" % name)
if desat is not None:
palette = [desaturate(c, desat) for c in palette]
# Always return as many colors as we asked for
pal_cycle = cycle(palette)
palette = [next(pal_cycle) for _ in range(n_colors)]
# Always return in r, g, b tuple format
try:
palette = map(mpl.colors.colorConverter.to_rgb, palette)
palette = _ColorPalette(palette)
except ValueError:
raise ValueError("Could not generate a palette for %s" % str(name))
return palette | python | def color_palette(name=None, n_colors=6, desat=None):
"""Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any matplotlib palette
Matplotlib paletes can be specified as reversed palettes by appending
"_r" to the name or as dark palettes by appending "_d" to the name.
This function can also be used in a ``with`` statement to temporarily
set the color cycle for a plot or set of plots.
Parameters
----------
name: None, string, or sequence
Name of palette or None to return current palette. If a
sequence, input colors are used but possibly cycled and
desaturated.
n_colors : int
Number of colors in the palette. If larger than the number of
colors in the palette, they will cycle.
desat : float
Value to desaturate each color by.
Returns
-------
palette : list of RGB tuples.
Color palette.
Examples
--------
>>> p = color_palette("muted")
>>> p = color_palette("Blues_d", 10)
>>> p = color_palette("Set1", desat=.7)
>>> import matplotlib.pyplot as plt
>>> with color_palette("husl", 8):
... f, ax = plt.subplots()
... ax.plot(x, y) # doctest: +SKIP
See Also
--------
set_palette : set the default color cycle for all plots.
axes_style : define parameters to set the style of plots
plotting_context : define parameters to scale plot elements
"""
seaborn_palettes = dict(
deep=["#4C72B0", "#55A868", "#C44E52",
"#8172B2", "#CCB974", "#64B5CD"],
muted=["#4878CF", "#6ACC65", "#D65F5F",
"#B47CC7", "#C4AD66", "#77BEDB"],
pastel=["#92C6FF", "#97F0AA", "#FF9F9A",
"#D0BBFF", "#FFFEA3", "#B0E0E6"],
bright=["#003FFF", "#03ED3A", "#E8000B",
"#8A2BE2", "#FFC400", "#00D7FF"],
dark=["#001C7F", "#017517", "#8C0900",
"#7600A1", "#B8860B", "#006374"],
colorblind=["#0072B2", "#009E73", "#D55E00",
"#CC79A7", "#F0E442", "#56B4E9"],
)
if name is None:
palette = mpl.rcParams["axes.color_cycle"]
elif not isinstance(name, string_types):
palette = name
elif name == "hls":
palette = hls_palette(n_colors)
elif name == "husl":
palette = husl_palette(n_colors)
elif name in seaborn_palettes:
palette = seaborn_palettes[name]
elif name in dir(mpl.cm):
palette = mpl_palette(name, n_colors)
elif name[:-2] in dir(mpl.cm):
palette = mpl_palette(name, n_colors)
else:
raise ValueError("%s is not a valid palette name" % name)
if desat is not None:
palette = [desaturate(c, desat) for c in palette]
# Always return as many colors as we asked for
pal_cycle = cycle(palette)
palette = [next(pal_cycle) for _ in range(n_colors)]
# Always return in r, g, b tuple format
try:
palette = map(mpl.colors.colorConverter.to_rgb, palette)
palette = _ColorPalette(palette)
except ValueError:
raise ValueError("Could not generate a palette for %s" % str(name))
return palette | [
"def",
"color_palette",
"(",
"name",
"=",
"None",
",",
"n_colors",
"=",
"6",
",",
"desat",
"=",
"None",
")",
":",
"seaborn_palettes",
"=",
"dict",
"(",
"deep",
"=",
"[",
"\"#4C72B0\"",
",",
"\"#55A868\"",
",",
"\"#C44E52\"",
",",
"\"#8172B2\"",
",",
"\"#... | Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any matplotlib palette
Matplotlib paletes can be specified as reversed palettes by appending
"_r" to the name or as dark palettes by appending "_d" to the name.
This function can also be used in a ``with`` statement to temporarily
set the color cycle for a plot or set of plots.
Parameters
----------
name: None, string, or sequence
Name of palette or None to return current palette. If a
sequence, input colors are used but possibly cycled and
desaturated.
n_colors : int
Number of colors in the palette. If larger than the number of
colors in the palette, they will cycle.
desat : float
Value to desaturate each color by.
Returns
-------
palette : list of RGB tuples.
Color palette.
Examples
--------
>>> p = color_palette("muted")
>>> p = color_palette("Blues_d", 10)
>>> p = color_palette("Set1", desat=.7)
>>> import matplotlib.pyplot as plt
>>> with color_palette("husl", 8):
... f, ax = plt.subplots()
... ax.plot(x, y) # doctest: +SKIP
See Also
--------
set_palette : set the default color cycle for all plots.
axes_style : define parameters to set the style of plots
plotting_context : define parameters to scale plot elements | [
"Return",
"a",
"list",
"of",
"colors",
"defining",
"a",
"color",
"palette",
"."
] | b6d23c22d52557b983da8ce7a3a6992501dadcd6 | https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L67-L165 | train | 217,120 |
yhat/ggpy | ggplot/colors/palettes.py | mpl_palette | def mpl_palette(name, n_colors=6):
"""Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
----------
name : string
name of the palette
n_colors : int
number of colors in the palette
Returns
-------
palette : list of tuples
palette colors in r, g, b format
"""
brewer_qual_pals = {"Accent": 8, "Dark2": 8, "Paired": 12,
"Pastel1": 9, "Pastel2": 8,
"Set1": 9, "Set2": 8, "Set3": 12}
if name.endswith("_d"):
pal = ["#333333"]
pal.extend(color_palette(name.replace("_d", "_r"), 2))
cmap = blend_palette(pal, n_colors, as_cmap=True)
else:
cmap = getattr(mpl.cm, name)
if name in brewer_qual_pals:
bins = np.linspace(0, 1, brewer_qual_pals[name])[:n_colors]
else:
bins = np.linspace(0, 1, n_colors + 2)[1:-1]
palette = list(map(tuple, cmap(bins)[:, :3]))
return palette | python | def mpl_palette(name, n_colors=6):
"""Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
----------
name : string
name of the palette
n_colors : int
number of colors in the palette
Returns
-------
palette : list of tuples
palette colors in r, g, b format
"""
brewer_qual_pals = {"Accent": 8, "Dark2": 8, "Paired": 12,
"Pastel1": 9, "Pastel2": 8,
"Set1": 9, "Set2": 8, "Set3": 12}
if name.endswith("_d"):
pal = ["#333333"]
pal.extend(color_palette(name.replace("_d", "_r"), 2))
cmap = blend_palette(pal, n_colors, as_cmap=True)
else:
cmap = getattr(mpl.cm, name)
if name in brewer_qual_pals:
bins = np.linspace(0, 1, brewer_qual_pals[name])[:n_colors]
else:
bins = np.linspace(0, 1, n_colors + 2)[1:-1]
palette = list(map(tuple, cmap(bins)[:, :3]))
return palette | [
"def",
"mpl_palette",
"(",
"name",
",",
"n_colors",
"=",
"6",
")",
":",
"brewer_qual_pals",
"=",
"{",
"\"Accent\"",
":",
"8",
",",
"\"Dark2\"",
":",
"8",
",",
"\"Paired\"",
":",
"12",
",",
"\"Pastel1\"",
":",
"9",
",",
"\"Pastel2\"",
":",
"8",
",",
"... | Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
----------
name : string
name of the palette
n_colors : int
number of colors in the palette
Returns
-------
palette : list of tuples
palette colors in r, g, b format | [
"Return",
"discrete",
"colors",
"from",
"a",
"matplotlib",
"palette",
"."
] | b6d23c22d52557b983da8ce7a3a6992501dadcd6 | https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L232-L269 | train | 217,121 |
yhat/ggpy | ggplot/colors/palettes.py | dark_palette | def dark_palette(color, n_colors=6, reverse=False, as_cmap=False):
"""Make a palette that blends from a deep gray to `color`.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
if True, return as a matplotlib colormap instead of list
Returns
-------
palette : list or colormap
"""
gray = "#222222"
colors = [color, gray] if reverse else [gray, color]
return blend_palette(colors, n_colors, as_cmap) | python | def dark_palette(color, n_colors=6, reverse=False, as_cmap=False):
"""Make a palette that blends from a deep gray to `color`.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
if True, return as a matplotlib colormap instead of list
Returns
-------
palette : list or colormap
"""
gray = "#222222"
colors = [color, gray] if reverse else [gray, color]
return blend_palette(colors, n_colors, as_cmap) | [
"def",
"dark_palette",
"(",
"color",
",",
"n_colors",
"=",
"6",
",",
"reverse",
"=",
"False",
",",
"as_cmap",
"=",
"False",
")",
":",
"gray",
"=",
"\"#222222\"",
"colors",
"=",
"[",
"color",
",",
"gray",
"]",
"if",
"reverse",
"else",
"[",
"gray",
","... | Make a palette that blends from a deep gray to `color`.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
if True, return as a matplotlib colormap instead of list
Returns
-------
palette : list or colormap | [
"Make",
"a",
"palette",
"that",
"blends",
"from",
"a",
"deep",
"gray",
"to",
"color",
"."
] | b6d23c22d52557b983da8ce7a3a6992501dadcd6 | https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L272-L293 | train | 217,122 |
yhat/ggpy | ggplot/colors/palettes.py | blend_palette | def blend_palette(colors, n_colors=6, as_cmap=False):
"""Make a palette that blends between a list of colors.
Parameters
----------
colors : sequence of matplotlib colors
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
as_cmap : bool, optional
if True, return as a matplotlib colormap instead of list
Returns
-------
palette : list or colormap
"""
name = "-".join(map(str, colors))
pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)
if not as_cmap:
pal = pal(np.linspace(0, 1, n_colors))
return pal | python | def blend_palette(colors, n_colors=6, as_cmap=False):
"""Make a palette that blends between a list of colors.
Parameters
----------
colors : sequence of matplotlib colors
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
as_cmap : bool, optional
if True, return as a matplotlib colormap instead of list
Returns
-------
palette : list or colormap
"""
name = "-".join(map(str, colors))
pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)
if not as_cmap:
pal = pal(np.linspace(0, 1, n_colors))
return pal | [
"def",
"blend_palette",
"(",
"colors",
",",
"n_colors",
"=",
"6",
",",
"as_cmap",
"=",
"False",
")",
":",
"name",
"=",
"\"-\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"colors",
")",
")",
"pal",
"=",
"mpl",
".",
"colors",
".",
"LinearSegmentedColor... | Make a palette that blends between a list of colors.
Parameters
----------
colors : sequence of matplotlib colors
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
as_cmap : bool, optional
if True, return as a matplotlib colormap instead of list
Returns
-------
palette : list or colormap | [
"Make",
"a",
"palette",
"that",
"blends",
"between",
"a",
"list",
"of",
"colors",
"."
] | b6d23c22d52557b983da8ce7a3a6992501dadcd6 | https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L296-L317 | train | 217,123 |
yhat/ggpy | ggplot/colors/palettes.py | xkcd_palette | def xkcd_palette(colors):
"""Make a palette with color names from the xkcd color survey.
This is just a simple wrapper around the seaborn.xkcd_rbg dictionary.
See xkcd for the full list of colors: http://xkcd.com/color/rgb/
"""
palette = [xkcd_rgb[name] for name in colors]
return color_palette(palette, len(palette)) | python | def xkcd_palette(colors):
"""Make a palette with color names from the xkcd color survey.
This is just a simple wrapper around the seaborn.xkcd_rbg dictionary.
See xkcd for the full list of colors: http://xkcd.com/color/rgb/
"""
palette = [xkcd_rgb[name] for name in colors]
return color_palette(palette, len(palette)) | [
"def",
"xkcd_palette",
"(",
"colors",
")",
":",
"palette",
"=",
"[",
"xkcd_rgb",
"[",
"name",
"]",
"for",
"name",
"in",
"colors",
"]",
"return",
"color_palette",
"(",
"palette",
",",
"len",
"(",
"palette",
")",
")"
] | Make a palette with color names from the xkcd color survey.
This is just a simple wrapper around the seaborn.xkcd_rbg dictionary.
See xkcd for the full list of colors: http://xkcd.com/color/rgb/ | [
"Make",
"a",
"palette",
"with",
"color",
"names",
"from",
"the",
"xkcd",
"color",
"survey",
"."
] | b6d23c22d52557b983da8ce7a3a6992501dadcd6 | https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L320-L329 | train | 217,124 |
yhat/ggpy | ggplot/colors/palettes.py | cubehelix_palette | def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,
light=.85, dark=.15, reverse=False, as_cmap=False):
"""Make a sequential palette from the cubehelix system.
This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserved if printed to
black and white or viewed by someone who is colorblind. "cubehelix" is
also availible as a matplotlib-based palette, but this function gives the
user more control over the look of the palette and has a different set of
defaults.
Parameters
----------
n_colors : int
Number of colors in the palette.
start : float, 0 <= start <= 3
The hue at the start of the helix.
rot : float
Rotations around the hue wheel over the range of the palette.
gamma : float 0 <= gamma
Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)
colors.
hue : float, 0 <= hue <= 1
Saturation of the colors.
dark : float 0 <= dark <= 1
Intensity of the darkest color in the palette.
light : float 0 <= light <= 1
Intensity of the lightest color in the palette.
reverse : bool
If True, the palette will go from dark to light.
as_cmap : bool
If True, return a matplotlib colormap instead of a list of colors.
Returns
-------
palette : list or colormap
References
----------
Green, D. A. (2011). "A colour scheme for the display of astronomical
intensity images". Bulletin of the Astromical Society of India, Vol. 39,
p. 289-295.
"""
cdict = mpl._cm.cubehelix(gamma, start, rot, hue)
cmap = mpl.colors.LinearSegmentedColormap("cubehelix", cdict)
x = np.linspace(light, dark, n_colors)
pal = cmap(x)[:, :3].tolist()
if reverse:
pal = pal[::-1]
if as_cmap:
x_256 = np.linspace(light, dark, 256)
if reverse:
x_256 = x_256[::-1]
pal_256 = cmap(x_256)
cmap = mpl.colors.ListedColormap(pal_256)
return cmap
else:
return pal | python | def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,
light=.85, dark=.15, reverse=False, as_cmap=False):
"""Make a sequential palette from the cubehelix system.
This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserved if printed to
black and white or viewed by someone who is colorblind. "cubehelix" is
also availible as a matplotlib-based palette, but this function gives the
user more control over the look of the palette and has a different set of
defaults.
Parameters
----------
n_colors : int
Number of colors in the palette.
start : float, 0 <= start <= 3
The hue at the start of the helix.
rot : float
Rotations around the hue wheel over the range of the palette.
gamma : float 0 <= gamma
Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)
colors.
hue : float, 0 <= hue <= 1
Saturation of the colors.
dark : float 0 <= dark <= 1
Intensity of the darkest color in the palette.
light : float 0 <= light <= 1
Intensity of the lightest color in the palette.
reverse : bool
If True, the palette will go from dark to light.
as_cmap : bool
If True, return a matplotlib colormap instead of a list of colors.
Returns
-------
palette : list or colormap
References
----------
Green, D. A. (2011). "A colour scheme for the display of astronomical
intensity images". Bulletin of the Astromical Society of India, Vol. 39,
p. 289-295.
"""
cdict = mpl._cm.cubehelix(gamma, start, rot, hue)
cmap = mpl.colors.LinearSegmentedColormap("cubehelix", cdict)
x = np.linspace(light, dark, n_colors)
pal = cmap(x)[:, :3].tolist()
if reverse:
pal = pal[::-1]
if as_cmap:
x_256 = np.linspace(light, dark, 256)
if reverse:
x_256 = x_256[::-1]
pal_256 = cmap(x_256)
cmap = mpl.colors.ListedColormap(pal_256)
return cmap
else:
return pal | [
"def",
"cubehelix_palette",
"(",
"n_colors",
"=",
"6",
",",
"start",
"=",
"0",
",",
"rot",
"=",
".4",
",",
"gamma",
"=",
"1.0",
",",
"hue",
"=",
"0.8",
",",
"light",
"=",
".85",
",",
"dark",
"=",
".15",
",",
"reverse",
"=",
"False",
",",
"as_cmap... | Make a sequential palette from the cubehelix system.
This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserved if printed to
black and white or viewed by someone who is colorblind. "cubehelix" is
also availible as a matplotlib-based palette, but this function gives the
user more control over the look of the palette and has a different set of
defaults.
Parameters
----------
n_colors : int
Number of colors in the palette.
start : float, 0 <= start <= 3
The hue at the start of the helix.
rot : float
Rotations around the hue wheel over the range of the palette.
gamma : float 0 <= gamma
Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)
colors.
hue : float, 0 <= hue <= 1
Saturation of the colors.
dark : float 0 <= dark <= 1
Intensity of the darkest color in the palette.
light : float 0 <= light <= 1
Intensity of the lightest color in the palette.
reverse : bool
If True, the palette will go from dark to light.
as_cmap : bool
If True, return a matplotlib colormap instead of a list of colors.
Returns
-------
palette : list or colormap
References
----------
Green, D. A. (2011). "A colour scheme for the display of astronomical
intensity images". Bulletin of the Astromical Society of India, Vol. 39,
p. 289-295. | [
"Make",
"a",
"sequential",
"palette",
"from",
"the",
"cubehelix",
"system",
"."
] | b6d23c22d52557b983da8ce7a3a6992501dadcd6 | https://github.com/yhat/ggpy/blob/b6d23c22d52557b983da8ce7a3a6992501dadcd6/ggplot/colors/palettes.py#L332-L392 | train | 217,125 |
kkroening/ffmpeg-python | ffmpeg/_run.py | get_args | def get_args(stream_spec, overwrite_output=False):
"""Build command-line arguments to be passed to ffmpeg."""
nodes = get_stream_spec_nodes(stream_spec)
args = []
# TODO: group nodes together, e.g. `-i somefile -r somerate`.
sorted_nodes, outgoing_edge_maps = topo_sort(nodes)
input_nodes = [node for node in sorted_nodes if isinstance(node, InputNode)]
output_nodes = [node for node in sorted_nodes if isinstance(node, OutputNode)]
global_nodes = [node for node in sorted_nodes if isinstance(node, GlobalNode)]
filter_nodes = [node for node in sorted_nodes if isinstance(node, FilterNode)]
stream_name_map = {(node, None): str(i) for i, node in enumerate(input_nodes)}
filter_arg = _get_filter_arg(filter_nodes, outgoing_edge_maps, stream_name_map)
args += reduce(operator.add, [_get_input_args(node) for node in input_nodes])
if filter_arg:
args += ['-filter_complex', filter_arg]
args += reduce(operator.add, [_get_output_args(node, stream_name_map) for node in output_nodes])
args += reduce(operator.add, [_get_global_args(node) for node in global_nodes], [])
if overwrite_output:
args += ['-y']
return args | python | def get_args(stream_spec, overwrite_output=False):
"""Build command-line arguments to be passed to ffmpeg."""
nodes = get_stream_spec_nodes(stream_spec)
args = []
# TODO: group nodes together, e.g. `-i somefile -r somerate`.
sorted_nodes, outgoing_edge_maps = topo_sort(nodes)
input_nodes = [node for node in sorted_nodes if isinstance(node, InputNode)]
output_nodes = [node for node in sorted_nodes if isinstance(node, OutputNode)]
global_nodes = [node for node in sorted_nodes if isinstance(node, GlobalNode)]
filter_nodes = [node for node in sorted_nodes if isinstance(node, FilterNode)]
stream_name_map = {(node, None): str(i) for i, node in enumerate(input_nodes)}
filter_arg = _get_filter_arg(filter_nodes, outgoing_edge_maps, stream_name_map)
args += reduce(operator.add, [_get_input_args(node) for node in input_nodes])
if filter_arg:
args += ['-filter_complex', filter_arg]
args += reduce(operator.add, [_get_output_args(node, stream_name_map) for node in output_nodes])
args += reduce(operator.add, [_get_global_args(node) for node in global_nodes], [])
if overwrite_output:
args += ['-y']
return args | [
"def",
"get_args",
"(",
"stream_spec",
",",
"overwrite_output",
"=",
"False",
")",
":",
"nodes",
"=",
"get_stream_spec_nodes",
"(",
"stream_spec",
")",
"args",
"=",
"[",
"]",
"# TODO: group nodes together, e.g. `-i somefile -r somerate`.",
"sorted_nodes",
",",
"outgoing... | Build command-line arguments to be passed to ffmpeg. | [
"Build",
"command",
"-",
"line",
"arguments",
"to",
"be",
"passed",
"to",
"ffmpeg",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_run.py#L135-L154 | train | 217,126 |
kkroening/ffmpeg-python | ffmpeg/_run.py | compile | def compile(stream_spec, cmd='ffmpeg', overwrite_output=False):
"""Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
manually for whatever reason.
This is the same as calling :meth:`get_args` except that it also
includes the ``ffmpeg`` command as the first argument.
"""
if isinstance(cmd, basestring):
cmd = [cmd]
elif type(cmd) != list:
cmd = list(cmd)
return cmd + get_args(stream_spec, overwrite_output=overwrite_output) | python | def compile(stream_spec, cmd='ffmpeg', overwrite_output=False):
"""Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
manually for whatever reason.
This is the same as calling :meth:`get_args` except that it also
includes the ``ffmpeg`` command as the first argument.
"""
if isinstance(cmd, basestring):
cmd = [cmd]
elif type(cmd) != list:
cmd = list(cmd)
return cmd + get_args(stream_spec, overwrite_output=overwrite_output) | [
"def",
"compile",
"(",
"stream_spec",
",",
"cmd",
"=",
"'ffmpeg'",
",",
"overwrite_output",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"cmd",
",",
"basestring",
")",
":",
"cmd",
"=",
"[",
"cmd",
"]",
"elif",
"type",
"(",
"cmd",
")",
"!=",
"list... | Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
manually for whatever reason.
This is the same as calling :meth:`get_args` except that it also
includes the ``ffmpeg`` command as the first argument. | [
"Build",
"command",
"-",
"line",
"for",
"invoking",
"ffmpeg",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_run.py#L158-L173 | train | 217,127 |
kkroening/ffmpeg-python | ffmpeg/_run.py | run_async | def run_async(
stream_spec, cmd='ffmpeg', pipe_stdin=False, pipe_stdout=False, pipe_stderr=False,
quiet=False, overwrite_output=False):
"""Asynchronously invoke ffmpeg for the supplied node graph.
Args:
pipe_stdin: if True, connect pipe to subprocess stdin (to be
used with ``pipe:`` ffmpeg inputs).
pipe_stdout: if True, connect pipe to subprocess stdout (to be
used with ``pipe:`` ffmpeg outputs).
pipe_stderr: if True, connect pipe to subprocess stderr.
quiet: shorthand for setting ``capture_stdout`` and
``capture_stderr``.
**kwargs: keyword-arguments passed to ``get_args()`` (e.g.
``overwrite_output=True``).
Returns:
A `subprocess Popen`_ object representing the child process.
Examples:
Run and stream input::
process = (
ffmpeg
.input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))
.output(out_filename, pix_fmt='yuv420p')
.overwrite_output()
.run_async(pipe_stdin=True)
)
process.communicate(input=input_data)
Run and capture output::
process = (
ffmpeg
.input(in_filename)
.output('pipe':, format='rawvideo', pix_fmt='rgb24')
.run_async(pipe_stdout=True, pipe_stderr=True)
)
out, err = process.communicate()
Process video frame-by-frame using numpy::
process1 = (
ffmpeg
.input(in_filename)
.output('pipe:', format='rawvideo', pix_fmt='rgb24')
.run_async(pipe_stdout=True)
)
process2 = (
ffmpeg
.input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))
.output(out_filename, pix_fmt='yuv420p')
.overwrite_output()
.run_async(pipe_stdin=True)
)
while True:
in_bytes = process1.stdout.read(width * height * 3)
if not in_bytes:
break
in_frame = (
np
.frombuffer(in_bytes, np.uint8)
.reshape([height, width, 3])
)
out_frame = in_frame * 0.3
process2.stdin.write(
frame
.astype(np.uint8)
.tobytes()
)
process2.stdin.close()
process1.wait()
process2.wait()
.. _subprocess Popen: https://docs.python.org/3/library/subprocess.html#popen-objects
"""
args = compile(stream_spec, cmd, overwrite_output=overwrite_output)
stdin_stream = subprocess.PIPE if pipe_stdin else None
stdout_stream = subprocess.PIPE if pipe_stdout or quiet else None
stderr_stream = subprocess.PIPE if pipe_stderr or quiet else None
return subprocess.Popen(
args, stdin=stdin_stream, stdout=stdout_stream, stderr=stderr_stream) | python | def run_async(
stream_spec, cmd='ffmpeg', pipe_stdin=False, pipe_stdout=False, pipe_stderr=False,
quiet=False, overwrite_output=False):
"""Asynchronously invoke ffmpeg for the supplied node graph.
Args:
pipe_stdin: if True, connect pipe to subprocess stdin (to be
used with ``pipe:`` ffmpeg inputs).
pipe_stdout: if True, connect pipe to subprocess stdout (to be
used with ``pipe:`` ffmpeg outputs).
pipe_stderr: if True, connect pipe to subprocess stderr.
quiet: shorthand for setting ``capture_stdout`` and
``capture_stderr``.
**kwargs: keyword-arguments passed to ``get_args()`` (e.g.
``overwrite_output=True``).
Returns:
A `subprocess Popen`_ object representing the child process.
Examples:
Run and stream input::
process = (
ffmpeg
.input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))
.output(out_filename, pix_fmt='yuv420p')
.overwrite_output()
.run_async(pipe_stdin=True)
)
process.communicate(input=input_data)
Run and capture output::
process = (
ffmpeg
.input(in_filename)
.output('pipe':, format='rawvideo', pix_fmt='rgb24')
.run_async(pipe_stdout=True, pipe_stderr=True)
)
out, err = process.communicate()
Process video frame-by-frame using numpy::
process1 = (
ffmpeg
.input(in_filename)
.output('pipe:', format='rawvideo', pix_fmt='rgb24')
.run_async(pipe_stdout=True)
)
process2 = (
ffmpeg
.input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))
.output(out_filename, pix_fmt='yuv420p')
.overwrite_output()
.run_async(pipe_stdin=True)
)
while True:
in_bytes = process1.stdout.read(width * height * 3)
if not in_bytes:
break
in_frame = (
np
.frombuffer(in_bytes, np.uint8)
.reshape([height, width, 3])
)
out_frame = in_frame * 0.3
process2.stdin.write(
frame
.astype(np.uint8)
.tobytes()
)
process2.stdin.close()
process1.wait()
process2.wait()
.. _subprocess Popen: https://docs.python.org/3/library/subprocess.html#popen-objects
"""
args = compile(stream_spec, cmd, overwrite_output=overwrite_output)
stdin_stream = subprocess.PIPE if pipe_stdin else None
stdout_stream = subprocess.PIPE if pipe_stdout or quiet else None
stderr_stream = subprocess.PIPE if pipe_stderr or quiet else None
return subprocess.Popen(
args, stdin=stdin_stream, stdout=stdout_stream, stderr=stderr_stream) | [
"def",
"run_async",
"(",
"stream_spec",
",",
"cmd",
"=",
"'ffmpeg'",
",",
"pipe_stdin",
"=",
"False",
",",
"pipe_stdout",
"=",
"False",
",",
"pipe_stderr",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"overwrite_output",
"=",
"False",
")",
":",
"args",
... | Asynchronously invoke ffmpeg for the supplied node graph.
Args:
pipe_stdin: if True, connect pipe to subprocess stdin (to be
used with ``pipe:`` ffmpeg inputs).
pipe_stdout: if True, connect pipe to subprocess stdout (to be
used with ``pipe:`` ffmpeg outputs).
pipe_stderr: if True, connect pipe to subprocess stderr.
quiet: shorthand for setting ``capture_stdout`` and
``capture_stderr``.
**kwargs: keyword-arguments passed to ``get_args()`` (e.g.
``overwrite_output=True``).
Returns:
A `subprocess Popen`_ object representing the child process.
Examples:
Run and stream input::
process = (
ffmpeg
.input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))
.output(out_filename, pix_fmt='yuv420p')
.overwrite_output()
.run_async(pipe_stdin=True)
)
process.communicate(input=input_data)
Run and capture output::
process = (
ffmpeg
.input(in_filename)
.output('pipe':, format='rawvideo', pix_fmt='rgb24')
.run_async(pipe_stdout=True, pipe_stderr=True)
)
out, err = process.communicate()
Process video frame-by-frame using numpy::
process1 = (
ffmpeg
.input(in_filename)
.output('pipe:', format='rawvideo', pix_fmt='rgb24')
.run_async(pipe_stdout=True)
)
process2 = (
ffmpeg
.input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))
.output(out_filename, pix_fmt='yuv420p')
.overwrite_output()
.run_async(pipe_stdin=True)
)
while True:
in_bytes = process1.stdout.read(width * height * 3)
if not in_bytes:
break
in_frame = (
np
.frombuffer(in_bytes, np.uint8)
.reshape([height, width, 3])
)
out_frame = in_frame * 0.3
process2.stdin.write(
frame
.astype(np.uint8)
.tobytes()
)
process2.stdin.close()
process1.wait()
process2.wait()
.. _subprocess Popen: https://docs.python.org/3/library/subprocess.html#popen-objects | [
"Asynchronously",
"invoke",
"ffmpeg",
"for",
"the",
"supplied",
"node",
"graph",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_run.py#L177-L262 | train | 217,128 |
kkroening/ffmpeg-python | ffmpeg/_run.py | run | def run(
stream_spec, cmd='ffmpeg', capture_stdout=False, capture_stderr=False, input=None,
quiet=False, overwrite_output=False):
"""Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
capture_stderr: if True, capture stderr.
quiet: shorthand for setting ``capture_stdout`` and ``capture_stderr``.
input: text to be sent to stdin (to be used with ``pipe:``
ffmpeg inputs)
**kwargs: keyword-arguments passed to ``get_args()`` (e.g.
``overwrite_output=True``).
Returns: (out, err) tuple containing captured stdout and stderr data.
"""
process = run_async(
stream_spec,
cmd,
pipe_stdin=input is not None,
pipe_stdout=capture_stdout,
pipe_stderr=capture_stderr,
quiet=quiet,
overwrite_output=overwrite_output,
)
out, err = process.communicate(input)
retcode = process.poll()
if retcode:
raise Error('ffmpeg', out, err)
return out, err | python | def run(
stream_spec, cmd='ffmpeg', capture_stdout=False, capture_stderr=False, input=None,
quiet=False, overwrite_output=False):
"""Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
capture_stderr: if True, capture stderr.
quiet: shorthand for setting ``capture_stdout`` and ``capture_stderr``.
input: text to be sent to stdin (to be used with ``pipe:``
ffmpeg inputs)
**kwargs: keyword-arguments passed to ``get_args()`` (e.g.
``overwrite_output=True``).
Returns: (out, err) tuple containing captured stdout and stderr data.
"""
process = run_async(
stream_spec,
cmd,
pipe_stdin=input is not None,
pipe_stdout=capture_stdout,
pipe_stderr=capture_stderr,
quiet=quiet,
overwrite_output=overwrite_output,
)
out, err = process.communicate(input)
retcode = process.poll()
if retcode:
raise Error('ffmpeg', out, err)
return out, err | [
"def",
"run",
"(",
"stream_spec",
",",
"cmd",
"=",
"'ffmpeg'",
",",
"capture_stdout",
"=",
"False",
",",
"capture_stderr",
"=",
"False",
",",
"input",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"overwrite_output",
"=",
"False",
")",
":",
"process",
"=... | Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
capture_stderr: if True, capture stderr.
quiet: shorthand for setting ``capture_stdout`` and ``capture_stderr``.
input: text to be sent to stdin (to be used with ``pipe:``
ffmpeg inputs)
**kwargs: keyword-arguments passed to ``get_args()`` (e.g.
``overwrite_output=True``).
Returns: (out, err) tuple containing captured stdout and stderr data. | [
"Invoke",
"ffmpeg",
"for",
"the",
"supplied",
"node",
"graph",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_run.py#L266-L296 | train | 217,129 |
kkroening/ffmpeg-python | ffmpeg/_ffmpeg.py | output | def output(*streams_and_filename, **kwargs):
"""Output file URL
Syntax:
`ffmpeg.output(stream1[, stream2, stream3...], filename, **ffmpeg_args)`
Any supplied keyword arguments are passed to ffmpeg verbatim (e.g.
``t=20``, ``f='mp4'``, ``acodec='pcm'``, ``vcodec='rawvideo'``,
etc.). Some keyword-arguments are handled specially, as shown below.
Args:
video_bitrate: parameter for ``-b:v``, e.g. ``video_bitrate=1000``.
audio_bitrate: parameter for ``-b:a``, e.g. ``audio_bitrate=200``.
format: alias for ``-f`` parameter, e.g. ``format='mp4'``
(equivalent to ``f='mp4'``).
If multiple streams are provided, they are mapped to the same
output.
To tell ffmpeg to write to stdout, use ``pipe:`` as the filename.
Official documentation: `Synopsis <https://ffmpeg.org/ffmpeg.html#Synopsis>`__
"""
streams_and_filename = list(streams_and_filename)
if 'filename' not in kwargs:
if not isinstance(streams_and_filename[-1], basestring):
raise ValueError('A filename must be provided')
kwargs['filename'] = streams_and_filename.pop(-1)
streams = streams_and_filename
fmt = kwargs.pop('f', None)
if fmt:
if 'format' in kwargs:
raise ValueError("Can't specify both `format` and `f` kwargs")
kwargs['format'] = fmt
return OutputNode(streams, output.__name__, kwargs=kwargs).stream() | python | def output(*streams_and_filename, **kwargs):
"""Output file URL
Syntax:
`ffmpeg.output(stream1[, stream2, stream3...], filename, **ffmpeg_args)`
Any supplied keyword arguments are passed to ffmpeg verbatim (e.g.
``t=20``, ``f='mp4'``, ``acodec='pcm'``, ``vcodec='rawvideo'``,
etc.). Some keyword-arguments are handled specially, as shown below.
Args:
video_bitrate: parameter for ``-b:v``, e.g. ``video_bitrate=1000``.
audio_bitrate: parameter for ``-b:a``, e.g. ``audio_bitrate=200``.
format: alias for ``-f`` parameter, e.g. ``format='mp4'``
(equivalent to ``f='mp4'``).
If multiple streams are provided, they are mapped to the same
output.
To tell ffmpeg to write to stdout, use ``pipe:`` as the filename.
Official documentation: `Synopsis <https://ffmpeg.org/ffmpeg.html#Synopsis>`__
"""
streams_and_filename = list(streams_and_filename)
if 'filename' not in kwargs:
if not isinstance(streams_and_filename[-1], basestring):
raise ValueError('A filename must be provided')
kwargs['filename'] = streams_and_filename.pop(-1)
streams = streams_and_filename
fmt = kwargs.pop('f', None)
if fmt:
if 'format' in kwargs:
raise ValueError("Can't specify both `format` and `f` kwargs")
kwargs['format'] = fmt
return OutputNode(streams, output.__name__, kwargs=kwargs).stream() | [
"def",
"output",
"(",
"*",
"streams_and_filename",
",",
"*",
"*",
"kwargs",
")",
":",
"streams_and_filename",
"=",
"list",
"(",
"streams_and_filename",
")",
"if",
"'filename'",
"not",
"in",
"kwargs",
":",
"if",
"not",
"isinstance",
"(",
"streams_and_filename",
... | Output file URL
Syntax:
`ffmpeg.output(stream1[, stream2, stream3...], filename, **ffmpeg_args)`
Any supplied keyword arguments are passed to ffmpeg verbatim (e.g.
``t=20``, ``f='mp4'``, ``acodec='pcm'``, ``vcodec='rawvideo'``,
etc.). Some keyword-arguments are handled specially, as shown below.
Args:
video_bitrate: parameter for ``-b:v``, e.g. ``video_bitrate=1000``.
audio_bitrate: parameter for ``-b:a``, e.g. ``audio_bitrate=200``.
format: alias for ``-f`` parameter, e.g. ``format='mp4'``
(equivalent to ``f='mp4'``).
If multiple streams are provided, they are mapped to the same
output.
To tell ffmpeg to write to stdout, use ``pipe:`` as the filename.
Official documentation: `Synopsis <https://ffmpeg.org/ffmpeg.html#Synopsis>`__ | [
"Output",
"file",
"URL"
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_ffmpeg.py#L59-L94 | train | 217,130 |
kkroening/ffmpeg-python | examples/show_progress.py | _do_watch_progress | def _do_watch_progress(filename, sock, handler):
"""Function to run in a separate gevent greenlet to read progress
events from a unix-domain socket."""
connection, client_address = sock.accept()
data = b''
try:
while True:
more_data = connection.recv(16)
if not more_data:
break
data += more_data
lines = data.split(b'\n')
for line in lines[:-1]:
line = line.decode()
parts = line.split('=')
key = parts[0] if len(parts) > 0 else None
value = parts[1] if len(parts) > 1 else None
handler(key, value)
data = lines[-1]
finally:
connection.close() | python | def _do_watch_progress(filename, sock, handler):
"""Function to run in a separate gevent greenlet to read progress
events from a unix-domain socket."""
connection, client_address = sock.accept()
data = b''
try:
while True:
more_data = connection.recv(16)
if not more_data:
break
data += more_data
lines = data.split(b'\n')
for line in lines[:-1]:
line = line.decode()
parts = line.split('=')
key = parts[0] if len(parts) > 0 else None
value = parts[1] if len(parts) > 1 else None
handler(key, value)
data = lines[-1]
finally:
connection.close() | [
"def",
"_do_watch_progress",
"(",
"filename",
",",
"sock",
",",
"handler",
")",
":",
"connection",
",",
"client_address",
"=",
"sock",
".",
"accept",
"(",
")",
"data",
"=",
"b''",
"try",
":",
"while",
"True",
":",
"more_data",
"=",
"connection",
".",
"re... | Function to run in a separate gevent greenlet to read progress
events from a unix-domain socket. | [
"Function",
"to",
"run",
"in",
"a",
"separate",
"gevent",
"greenlet",
"to",
"read",
"progress",
"events",
"from",
"a",
"unix",
"-",
"domain",
"socket",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/show_progress.py#L42-L62 | train | 217,131 |
kkroening/ffmpeg-python | examples/show_progress.py | _watch_progress | def _watch_progress(handler):
"""Context manager for creating a unix-domain socket and listen for
ffmpeg progress events.
The socket filename is yielded from the context manager and the
socket is closed when the context manager is exited.
Args:
handler: a function to be called when progress events are
received; receives a ``key`` argument and ``value``
argument. (The example ``show_progress`` below uses tqdm)
Yields:
socket_filename: the name of the socket file.
"""
with _tmpdir_scope() as tmpdir:
socket_filename = os.path.join(tmpdir, 'sock')
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
with contextlib.closing(sock):
sock.bind(socket_filename)
sock.listen(1)
child = gevent.spawn(_do_watch_progress, socket_filename, sock, handler)
try:
yield socket_filename
except:
gevent.kill(child)
raise | python | def _watch_progress(handler):
"""Context manager for creating a unix-domain socket and listen for
ffmpeg progress events.
The socket filename is yielded from the context manager and the
socket is closed when the context manager is exited.
Args:
handler: a function to be called when progress events are
received; receives a ``key`` argument and ``value``
argument. (The example ``show_progress`` below uses tqdm)
Yields:
socket_filename: the name of the socket file.
"""
with _tmpdir_scope() as tmpdir:
socket_filename = os.path.join(tmpdir, 'sock')
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
with contextlib.closing(sock):
sock.bind(socket_filename)
sock.listen(1)
child = gevent.spawn(_do_watch_progress, socket_filename, sock, handler)
try:
yield socket_filename
except:
gevent.kill(child)
raise | [
"def",
"_watch_progress",
"(",
"handler",
")",
":",
"with",
"_tmpdir_scope",
"(",
")",
"as",
"tmpdir",
":",
"socket_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"'sock'",
")",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
... | Context manager for creating a unix-domain socket and listen for
ffmpeg progress events.
The socket filename is yielded from the context manager and the
socket is closed when the context manager is exited.
Args:
handler: a function to be called when progress events are
received; receives a ``key`` argument and ``value``
argument. (The example ``show_progress`` below uses tqdm)
Yields:
socket_filename: the name of the socket file. | [
"Context",
"manager",
"for",
"creating",
"a",
"unix",
"-",
"domain",
"socket",
"and",
"listen",
"for",
"ffmpeg",
"progress",
"events",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/show_progress.py#L66-L92 | train | 217,132 |
kkroening/ffmpeg-python | examples/show_progress.py | show_progress | def show_progress(total_duration):
"""Create a unix-domain socket to watch progress and render tqdm
progress bar."""
with tqdm(total=round(total_duration, 2)) as bar:
def handler(key, value):
if key == 'out_time_ms':
time = round(float(value) / 1000000., 2)
bar.update(time - bar.n)
elif key == 'progress' and value == 'end':
bar.update(bar.total - bar.n)
with _watch_progress(handler) as socket_filename:
yield socket_filename | python | def show_progress(total_duration):
"""Create a unix-domain socket to watch progress and render tqdm
progress bar."""
with tqdm(total=round(total_duration, 2)) as bar:
def handler(key, value):
if key == 'out_time_ms':
time = round(float(value) / 1000000., 2)
bar.update(time - bar.n)
elif key == 'progress' and value == 'end':
bar.update(bar.total - bar.n)
with _watch_progress(handler) as socket_filename:
yield socket_filename | [
"def",
"show_progress",
"(",
"total_duration",
")",
":",
"with",
"tqdm",
"(",
"total",
"=",
"round",
"(",
"total_duration",
",",
"2",
")",
")",
"as",
"bar",
":",
"def",
"handler",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'out_time_ms'",
... | Create a unix-domain socket to watch progress and render tqdm
progress bar. | [
"Create",
"a",
"unix",
"-",
"domain",
"socket",
"to",
"watch",
"progress",
"and",
"render",
"tqdm",
"progress",
"bar",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/show_progress.py#L97-L108 | train | 217,133 |
kkroening/ffmpeg-python | ffmpeg/_probe.py | probe | def probe(filename, cmd='ffprobe', **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code,
an :class:`Error` is returned with a generic error message.
The stderr output can be retrieved by accessing the
``stderr`` property of the exception.
"""
args = [cmd, '-show_format', '-show_streams', '-of', 'json']
args += convert_kwargs_to_cmd_line_args(kwargs)
args += [filename]
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
raise Error('ffprobe', out, err)
return json.loads(out.decode('utf-8')) | python | def probe(filename, cmd='ffprobe', **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code,
an :class:`Error` is returned with a generic error message.
The stderr output can be retrieved by accessing the
``stderr`` property of the exception.
"""
args = [cmd, '-show_format', '-show_streams', '-of', 'json']
args += convert_kwargs_to_cmd_line_args(kwargs)
args += [filename]
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
raise Error('ffprobe', out, err)
return json.loads(out.decode('utf-8')) | [
"def",
"probe",
"(",
"filename",
",",
"cmd",
"=",
"'ffprobe'",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"cmd",
",",
"'-show_format'",
",",
"'-show_streams'",
",",
"'-of'",
",",
"'json'",
"]",
"args",
"+=",
"convert_kwargs_to_cmd_line_args",
"("... | Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code,
an :class:`Error` is returned with a generic error message.
The stderr output can be retrieved by accessing the
``stderr`` property of the exception. | [
"Run",
"ffprobe",
"on",
"the",
"specified",
"file",
"and",
"return",
"a",
"JSON",
"representation",
"of",
"the",
"output",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_probe.py#L7-L24 | train | 217,134 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | filter_multi_output | def filter_multi_output(stream_spec, filter_name, *args, **kwargs):
"""Apply custom filter with one or more outputs.
This is the same as ``filter_`` except that the filter can produce more than one output.
To reference an output stream, use either the ``.stream`` operator or bracket shorthand:
Example:
```
split = ffmpeg.input('in.mp4').filter_multi_output('split')
split0 = split.stream(0)
split1 = split[1]
ffmpeg.concat(split0, split1).output('out.mp4').run()
```
"""
return FilterNode(stream_spec, filter_name, args=args, kwargs=kwargs, max_inputs=None) | python | def filter_multi_output(stream_spec, filter_name, *args, **kwargs):
"""Apply custom filter with one or more outputs.
This is the same as ``filter_`` except that the filter can produce more than one output.
To reference an output stream, use either the ``.stream`` operator or bracket shorthand:
Example:
```
split = ffmpeg.input('in.mp4').filter_multi_output('split')
split0 = split.stream(0)
split1 = split[1]
ffmpeg.concat(split0, split1).output('out.mp4').run()
```
"""
return FilterNode(stream_spec, filter_name, args=args, kwargs=kwargs, max_inputs=None) | [
"def",
"filter_multi_output",
"(",
"stream_spec",
",",
"filter_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FilterNode",
"(",
"stream_spec",
",",
"filter_name",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"max_inp... | Apply custom filter with one or more outputs.
This is the same as ``filter_`` except that the filter can produce more than one output.
To reference an output stream, use either the ``.stream`` operator or bracket shorthand:
Example:
```
split = ffmpeg.input('in.mp4').filter_multi_output('split')
split0 = split.stream(0)
split1 = split[1]
ffmpeg.concat(split0, split1).output('out.mp4').run()
``` | [
"Apply",
"custom",
"filter",
"with",
"one",
"or",
"more",
"outputs",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L8-L24 | train | 217,135 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | filter | def filter(stream_spec, filter_name, *args, **kwargs):
"""Apply custom filter.
``filter_`` is normally used by higher-level filter functions such as ``hflip``, but if a filter implementation
is missing from ``fmpeg-python``, you can call ``filter_`` directly to have ``fmpeg-python`` pass the filter name
and arguments to ffmpeg verbatim.
Args:
stream_spec: a Stream, list of Streams, or label-to-Stream dictionary mapping
filter_name: ffmpeg filter name, e.g. `colorchannelmixer`
*args: list of args to pass to ffmpeg verbatim
**kwargs: list of keyword-args to pass to ffmpeg verbatim
The function name is suffixed with ``_`` in order avoid confusion with the standard python ``filter`` function.
Example:
``ffmpeg.input('in.mp4').filter('hflip').output('out.mp4').run()``
"""
return filter_multi_output(stream_spec, filter_name, *args, **kwargs).stream() | python | def filter(stream_spec, filter_name, *args, **kwargs):
"""Apply custom filter.
``filter_`` is normally used by higher-level filter functions such as ``hflip``, but if a filter implementation
is missing from ``fmpeg-python``, you can call ``filter_`` directly to have ``fmpeg-python`` pass the filter name
and arguments to ffmpeg verbatim.
Args:
stream_spec: a Stream, list of Streams, or label-to-Stream dictionary mapping
filter_name: ffmpeg filter name, e.g. `colorchannelmixer`
*args: list of args to pass to ffmpeg verbatim
**kwargs: list of keyword-args to pass to ffmpeg verbatim
The function name is suffixed with ``_`` in order avoid confusion with the standard python ``filter`` function.
Example:
``ffmpeg.input('in.mp4').filter('hflip').output('out.mp4').run()``
"""
return filter_multi_output(stream_spec, filter_name, *args, **kwargs).stream() | [
"def",
"filter",
"(",
"stream_spec",
",",
"filter_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"filter_multi_output",
"(",
"stream_spec",
",",
"filter_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"stream",
"(",
"... | Apply custom filter.
``filter_`` is normally used by higher-level filter functions such as ``hflip``, but if a filter implementation
is missing from ``fmpeg-python``, you can call ``filter_`` directly to have ``fmpeg-python`` pass the filter name
and arguments to ffmpeg verbatim.
Args:
stream_spec: a Stream, list of Streams, or label-to-Stream dictionary mapping
filter_name: ffmpeg filter name, e.g. `colorchannelmixer`
*args: list of args to pass to ffmpeg verbatim
**kwargs: list of keyword-args to pass to ffmpeg verbatim
The function name is suffixed with ``_`` in order avoid confusion with the standard python ``filter`` function.
Example:
``ffmpeg.input('in.mp4').filter('hflip').output('out.mp4').run()`` | [
"Apply",
"custom",
"filter",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L28-L47 | train | 217,136 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | filter_ | def filter_(stream_spec, filter_name, *args, **kwargs):
"""Alternate name for ``filter``, so as to not collide with the
built-in python ``filter`` operator.
"""
return filter(stream_spec, filter_name, *args, **kwargs) | python | def filter_(stream_spec, filter_name, *args, **kwargs):
"""Alternate name for ``filter``, so as to not collide with the
built-in python ``filter`` operator.
"""
return filter(stream_spec, filter_name, *args, **kwargs) | [
"def",
"filter_",
"(",
"stream_spec",
",",
"filter_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"filter",
"(",
"stream_spec",
",",
"filter_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Alternate name for ``filter``, so as to not collide with the
built-in python ``filter`` operator. | [
"Alternate",
"name",
"for",
"filter",
"so",
"as",
"to",
"not",
"collide",
"with",
"the",
"built",
"-",
"in",
"python",
"filter",
"operator",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L51-L55 | train | 217,137 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | trim | def trim(stream, **kwargs):
"""Trim the input so that the output contains one continuous subpart of the input.
Args:
start: Specify the time of the start of the kept section, i.e. the frame with the timestamp start will be the
first frame in the output.
end: Specify the time of the first frame that will be dropped, i.e. the frame immediately preceding the one
with the timestamp end will be the last frame in the output.
start_pts: This is the same as start, except this option sets the start timestamp in timebase units instead of
seconds.
end_pts: This is the same as end, except this option sets the end timestamp in timebase units instead of
seconds.
duration: The maximum duration of the output in seconds.
start_frame: The number of the first frame that should be passed to the output.
end_frame: The number of the first frame that should be dropped.
Official documentation: `trim <https://ffmpeg.org/ffmpeg-filters.html#trim>`__
"""
return FilterNode(stream, trim.__name__, kwargs=kwargs).stream() | python | def trim(stream, **kwargs):
"""Trim the input so that the output contains one continuous subpart of the input.
Args:
start: Specify the time of the start of the kept section, i.e. the frame with the timestamp start will be the
first frame in the output.
end: Specify the time of the first frame that will be dropped, i.e. the frame immediately preceding the one
with the timestamp end will be the last frame in the output.
start_pts: This is the same as start, except this option sets the start timestamp in timebase units instead of
seconds.
end_pts: This is the same as end, except this option sets the end timestamp in timebase units instead of
seconds.
duration: The maximum duration of the output in seconds.
start_frame: The number of the first frame that should be passed to the output.
end_frame: The number of the first frame that should be dropped.
Official documentation: `trim <https://ffmpeg.org/ffmpeg-filters.html#trim>`__
"""
return FilterNode(stream, trim.__name__, kwargs=kwargs).stream() | [
"def",
"trim",
"(",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FilterNode",
"(",
"stream",
",",
"trim",
".",
"__name__",
",",
"kwargs",
"=",
"kwargs",
")",
".",
"stream",
"(",
")"
] | Trim the input so that the output contains one continuous subpart of the input.
Args:
start: Specify the time of the start of the kept section, i.e. the frame with the timestamp start will be the
first frame in the output.
end: Specify the time of the first frame that will be dropped, i.e. the frame immediately preceding the one
with the timestamp end will be the last frame in the output.
start_pts: This is the same as start, except this option sets the start timestamp in timebase units instead of
seconds.
end_pts: This is the same as end, except this option sets the end timestamp in timebase units instead of
seconds.
duration: The maximum duration of the output in seconds.
start_frame: The number of the first frame that should be passed to the output.
end_frame: The number of the first frame that should be dropped.
Official documentation: `trim <https://ffmpeg.org/ffmpeg-filters.html#trim>`__ | [
"Trim",
"the",
"input",
"so",
"that",
"the",
"output",
"contains",
"one",
"continuous",
"subpart",
"of",
"the",
"input",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L81-L99 | train | 217,138 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | overlay | def overlay(main_parent_node, overlay_parent_node, eof_action='repeat', **kwargs):
"""Overlay one video on top of another.
Args:
x: Set the expression for the x coordinates of the overlaid video on the main video. Default value is 0. In
case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed
within the output visible area).
y: Set the expression for the y coordinates of the overlaid video on the main video. Default value is 0. In
case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed
within the output visible area).
eof_action: The action to take when EOF is encountered on the secondary input; it accepts one of the following
values:
* ``repeat``: Repeat the last frame (the default).
* ``endall``: End both streams.
* ``pass``: Pass the main input through.
eval: Set when the expressions for x, and y are evaluated.
It accepts the following values:
* ``init``: only evaluate expressions once during the filter initialization or when a command is
processed
* ``frame``: evaluate expressions for each incoming frame
Default value is ``frame``.
shortest: If set to 1, force the output to terminate when the shortest input terminates. Default value is 0.
format: Set the format for the output video.
It accepts the following values:
* ``yuv420``: force YUV420 output
* ``yuv422``: force YUV422 output
* ``yuv444``: force YUV444 output
* ``rgb``: force packed RGB output
* ``gbrp``: force planar RGB output
Default value is ``yuv420``.
rgb (deprecated): If set to 1, force the filter to accept inputs in the RGB color space. Default value is 0.
This option is deprecated, use format instead.
repeatlast: If set to 1, force the filter to draw the last overlay frame over the main input until the end of
the stream. A value of 0 disables this behavior. Default value is 1.
Official documentation: `overlay <https://ffmpeg.org/ffmpeg-filters.html#overlay-1>`__
"""
kwargs['eof_action'] = eof_action
return FilterNode([main_parent_node, overlay_parent_node], overlay.__name__, kwargs=kwargs, max_inputs=2).stream() | python | def overlay(main_parent_node, overlay_parent_node, eof_action='repeat', **kwargs):
"""Overlay one video on top of another.
Args:
x: Set the expression for the x coordinates of the overlaid video on the main video. Default value is 0. In
case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed
within the output visible area).
y: Set the expression for the y coordinates of the overlaid video on the main video. Default value is 0. In
case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed
within the output visible area).
eof_action: The action to take when EOF is encountered on the secondary input; it accepts one of the following
values:
* ``repeat``: Repeat the last frame (the default).
* ``endall``: End both streams.
* ``pass``: Pass the main input through.
eval: Set when the expressions for x, and y are evaluated.
It accepts the following values:
* ``init``: only evaluate expressions once during the filter initialization or when a command is
processed
* ``frame``: evaluate expressions for each incoming frame
Default value is ``frame``.
shortest: If set to 1, force the output to terminate when the shortest input terminates. Default value is 0.
format: Set the format for the output video.
It accepts the following values:
* ``yuv420``: force YUV420 output
* ``yuv422``: force YUV422 output
* ``yuv444``: force YUV444 output
* ``rgb``: force packed RGB output
* ``gbrp``: force planar RGB output
Default value is ``yuv420``.
rgb (deprecated): If set to 1, force the filter to accept inputs in the RGB color space. Default value is 0.
This option is deprecated, use format instead.
repeatlast: If set to 1, force the filter to draw the last overlay frame over the main input until the end of
the stream. A value of 0 disables this behavior. Default value is 1.
Official documentation: `overlay <https://ffmpeg.org/ffmpeg-filters.html#overlay-1>`__
"""
kwargs['eof_action'] = eof_action
return FilterNode([main_parent_node, overlay_parent_node], overlay.__name__, kwargs=kwargs, max_inputs=2).stream() | [
"def",
"overlay",
"(",
"main_parent_node",
",",
"overlay_parent_node",
",",
"eof_action",
"=",
"'repeat'",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'eof_action'",
"]",
"=",
"eof_action",
"return",
"FilterNode",
"(",
"[",
"main_parent_node",
",",
"ove... | Overlay one video on top of another.
Args:
x: Set the expression for the x coordinates of the overlaid video on the main video. Default value is 0. In
case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed
within the output visible area).
y: Set the expression for the y coordinates of the overlaid video on the main video. Default value is 0. In
case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed
within the output visible area).
eof_action: The action to take when EOF is encountered on the secondary input; it accepts one of the following
values:
* ``repeat``: Repeat the last frame (the default).
* ``endall``: End both streams.
* ``pass``: Pass the main input through.
eval: Set when the expressions for x, and y are evaluated.
It accepts the following values:
* ``init``: only evaluate expressions once during the filter initialization or when a command is
processed
* ``frame``: evaluate expressions for each incoming frame
Default value is ``frame``.
shortest: If set to 1, force the output to terminate when the shortest input terminates. Default value is 0.
format: Set the format for the output video.
It accepts the following values:
* ``yuv420``: force YUV420 output
* ``yuv422``: force YUV422 output
* ``yuv444``: force YUV444 output
* ``rgb``: force packed RGB output
* ``gbrp``: force planar RGB output
Default value is ``yuv420``.
rgb (deprecated): If set to 1, force the filter to accept inputs in the RGB color space. Default value is 0.
This option is deprecated, use format instead.
repeatlast: If set to 1, force the filter to draw the last overlay frame over the main input until the end of
the stream. A value of 0 disables this behavior. Default value is 1.
Official documentation: `overlay <https://ffmpeg.org/ffmpeg-filters.html#overlay-1>`__ | [
"Overlay",
"one",
"video",
"on",
"top",
"of",
"another",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L103-L147 | train | 217,139 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | crop | def crop(stream, x, y, width, height, **kwargs):
"""Crop the input video.
Args:
x: The horizontal position, in the input video, of the left edge of
the output video.
y: The vertical position, in the input video, of the top edge of the
output video.
width: The width of the output video. Must be greater than 0.
heigth: The height of the output video. Must be greater than 0.
Official documentation: `crop <https://ffmpeg.org/ffmpeg-filters.html#crop>`__
"""
return FilterNode(
stream,
crop.__name__,
args=[width, height, x, y],
kwargs=kwargs
).stream() | python | def crop(stream, x, y, width, height, **kwargs):
"""Crop the input video.
Args:
x: The horizontal position, in the input video, of the left edge of
the output video.
y: The vertical position, in the input video, of the top edge of the
output video.
width: The width of the output video. Must be greater than 0.
heigth: The height of the output video. Must be greater than 0.
Official documentation: `crop <https://ffmpeg.org/ffmpeg-filters.html#crop>`__
"""
return FilterNode(
stream,
crop.__name__,
args=[width, height, x, y],
kwargs=kwargs
).stream() | [
"def",
"crop",
"(",
"stream",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FilterNode",
"(",
"stream",
",",
"crop",
".",
"__name__",
",",
"args",
"=",
"[",
"width",
",",
"height",
",",
"x",
",",
... | Crop the input video.
Args:
x: The horizontal position, in the input video, of the left edge of
the output video.
y: The vertical position, in the input video, of the top edge of the
output video.
width: The width of the output video. Must be greater than 0.
heigth: The height of the output video. Must be greater than 0.
Official documentation: `crop <https://ffmpeg.org/ffmpeg-filters.html#crop>`__ | [
"Crop",
"the",
"input",
"video",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L169-L187 | train | 217,140 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | drawbox | def drawbox(stream, x, y, width, height, color, thickness=None, **kwargs):
"""Draw a colored box on the input image.
Args:
x: The expression which specifies the top left corner x coordinate of the box. It defaults to 0.
y: The expression which specifies the top left corner y coordinate of the box. It defaults to 0.
width: Specify the width of the box; if 0 interpreted as the input width. It defaults to 0.
heigth: Specify the height of the box; if 0 interpreted as the input height. It defaults to 0.
color: Specify the color of the box to write. For the general syntax of this option, check the "Color" section
in the ffmpeg-utils manual. If the special value invert is used, the box edge color is the same as the
video with inverted luma.
thickness: The expression which sets the thickness of the box edge. Default value is 3.
w: Alias for ``width``.
h: Alias for ``height``.
c: Alias for ``color``.
t: Alias for ``thickness``.
Official documentation: `drawbox <https://ffmpeg.org/ffmpeg-filters.html#drawbox>`__
"""
if thickness:
kwargs['t'] = thickness
return FilterNode(stream, drawbox.__name__, args=[x, y, width, height, color], kwargs=kwargs).stream() | python | def drawbox(stream, x, y, width, height, color, thickness=None, **kwargs):
"""Draw a colored box on the input image.
Args:
x: The expression which specifies the top left corner x coordinate of the box. It defaults to 0.
y: The expression which specifies the top left corner y coordinate of the box. It defaults to 0.
width: Specify the width of the box; if 0 interpreted as the input width. It defaults to 0.
heigth: Specify the height of the box; if 0 interpreted as the input height. It defaults to 0.
color: Specify the color of the box to write. For the general syntax of this option, check the "Color" section
in the ffmpeg-utils manual. If the special value invert is used, the box edge color is the same as the
video with inverted luma.
thickness: The expression which sets the thickness of the box edge. Default value is 3.
w: Alias for ``width``.
h: Alias for ``height``.
c: Alias for ``color``.
t: Alias for ``thickness``.
Official documentation: `drawbox <https://ffmpeg.org/ffmpeg-filters.html#drawbox>`__
"""
if thickness:
kwargs['t'] = thickness
return FilterNode(stream, drawbox.__name__, args=[x, y, width, height, color], kwargs=kwargs).stream() | [
"def",
"drawbox",
"(",
"stream",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
",",
"thickness",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"thickness",
":",
"kwargs",
"[",
"'t'",
"]",
"=",
"thickness",
"return",
"Filter... | Draw a colored box on the input image.
Args:
x: The expression which specifies the top left corner x coordinate of the box. It defaults to 0.
y: The expression which specifies the top left corner y coordinate of the box. It defaults to 0.
width: Specify the width of the box; if 0 interpreted as the input width. It defaults to 0.
heigth: Specify the height of the box; if 0 interpreted as the input height. It defaults to 0.
color: Specify the color of the box to write. For the general syntax of this option, check the "Color" section
in the ffmpeg-utils manual. If the special value invert is used, the box edge color is the same as the
video with inverted luma.
thickness: The expression which sets the thickness of the box edge. Default value is 3.
w: Alias for ``width``.
h: Alias for ``height``.
c: Alias for ``color``.
t: Alias for ``thickness``.
Official documentation: `drawbox <https://ffmpeg.org/ffmpeg-filters.html#drawbox>`__ | [
"Draw",
"a",
"colored",
"box",
"on",
"the",
"input",
"image",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L191-L212 | train | 217,141 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | drawtext | def drawtext(stream, text=None, x=0, y=0, escape_text=True, **kwargs):
"""Draw a text string or text from a specified file on top of a video, using the libfreetype library.
To enable compilation of this filter, you need to configure FFmpeg with ``--enable-libfreetype``. To enable default
font fallback and the font option you need to configure FFmpeg with ``--enable-libfontconfig``. To enable the
text_shaping option, you need to configure FFmpeg with ``--enable-libfribidi``.
Args:
box: Used to draw a box around text using the background color. The value must be either 1 (enable) or 0
(disable). The default value of box is 0.
boxborderw: Set the width of the border to be drawn around the box using boxcolor. The default value of
boxborderw is 0.
boxcolor: The color to be used for drawing box around text. For the syntax of this option, check the "Color"
section in the ffmpeg-utils manual. The default value of boxcolor is "white".
line_spacing: Set the line spacing in pixels of the border to be drawn around the box using box. The default
value of line_spacing is 0.
borderw: Set the width of the border to be drawn around the text using bordercolor. The default value of
borderw is 0.
bordercolor: Set the color to be used for drawing border around text. For the syntax of this option, check the
"Color" section in the ffmpeg-utils manual. The default value of bordercolor is "black".
expansion: Select how the text is expanded. Can be either none, strftime (deprecated) or normal (default). See
the Text expansion section below for details.
basetime: Set a start time for the count. Value is in microseconds. Only applied in the deprecated strftime
expansion mode. To emulate in normal expansion mode use the pts function, supplying the start time (in
seconds) as the second argument.
fix_bounds: If true, check and fix text coords to avoid clipping.
fontcolor: The color to be used for drawing fonts. For the syntax of this option, check the "Color" section in
the ffmpeg-utils manual. The default value of fontcolor is "black".
fontcolor_expr: String which is expanded the same way as text to obtain dynamic fontcolor value. By default
this option has empty value and is not processed. When this option is set, it overrides fontcolor option.
font: The font family to be used for drawing text. By default Sans.
fontfile: The font file to be used for drawing text. The path must be included. This parameter is mandatory if
the fontconfig support is disabled.
alpha: Draw the text applying alpha blending. The value can be a number between 0.0 and 1.0. The expression
accepts the same variables x, y as well. The default value is 1. Please see fontcolor_expr.
fontsize: The font size to be used for drawing text. The default value of fontsize is 16.
text_shaping: If set to 1, attempt to shape the text (for example, reverse the order of right-to-left text and
join Arabic characters) before drawing it. Otherwise, just draw the text exactly as given. By default 1 (if
supported).
ft_load_flags: The flags to be used for loading the fonts. The flags map the corresponding flags supported by
libfreetype, and are a combination of the following values:
* ``default``
* ``no_scale``
* ``no_hinting``
* ``render``
* ``no_bitmap``
* ``vertical_layout``
* ``force_autohint``
* ``crop_bitmap``
* ``pedantic``
* ``ignore_global_advance_width``
* ``no_recurse``
* ``ignore_transform``
* ``monochrome``
* ``linear_design``
* ``no_autohint``
Default value is "default". For more information consult the documentation for the FT_LOAD_* libfreetype
flags.
shadowcolor: The color to be used for drawing a shadow behind the drawn text. For the syntax of this option,
check the "Color" section in the ffmpeg-utils manual. The default value of shadowcolor is "black".
shadowx: The x offset for the text shadow position with respect to the position of the text. It can be either
positive or negative values. The default value is "0".
shadowy: The y offset for the text shadow position with respect to the position of the text. It can be either
positive or negative values. The default value is "0".
start_number: The starting frame number for the n/frame_num variable. The default value is "0".
tabsize: The size in number of spaces to use for rendering the tab. Default value is 4.
timecode: Set the initial timecode representation in "hh:mm:ss[:;.]ff" format. It can be used with or without
text parameter. timecode_rate option must be specified.
rate: Set the timecode frame rate (timecode only).
timecode_rate: Alias for ``rate``.
r: Alias for ``rate``.
tc24hmax: If set to 1, the output of the timecode option will wrap around at 24 hours. Default is 0 (disabled).
text: The text string to be drawn. The text must be a sequence of UTF-8 encoded characters. This parameter is
mandatory if no file is specified with the parameter textfile.
textfile: A text file containing text to be drawn. The text must be a sequence of UTF-8 encoded characters.
This parameter is mandatory if no text string is specified with the parameter text. If both text and
textfile are specified, an error is thrown.
reload: If set to 1, the textfile will be reloaded before each frame. Be sure to update it atomically, or it
may be read partially, or even fail.
x: The expression which specifies the offset where text will be drawn within the video frame. It is relative to
the left border of the output image. The default value is "0".
y: The expression which specifies the offset where text will be drawn within the video frame. It is relative to
the top border of the output image. The default value is "0". See below for the list of accepted constants
and functions.
Expression constants:
The parameters for x and y are expressions containing the following constants and functions:
- dar: input display aspect ratio, it is the same as ``(w / h) * sar``
- hsub: horizontal chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub
is 1.
- vsub: vertical chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub
is 1.
- line_h: the height of each text line
- lh: Alias for ``line_h``.
- main_h: the input height
- h: Alias for ``main_h``.
- H: Alias for ``main_h``.
- main_w: the input width
- w: Alias for ``main_w``.
- W: Alias for ``main_w``.
- ascent: the maximum distance from the baseline to the highest/upper grid coordinate used to place a glyph
outline point, for all the rendered glyphs. It is a positive value, due to the grid's orientation with the Y
axis upwards.
- max_glyph_a: Alias for ``ascent``.
- descent: the maximum distance from the baseline to the lowest grid coordinate used to place a glyph outline
point, for all the rendered glyphs. This is a negative value, due to the grid's orientation, with the Y axis
upwards.
- max_glyph_d: Alias for ``descent``.
- max_glyph_h: maximum glyph height, that is the maximum height for all the glyphs contained in the rendered
text, it is equivalent to ascent - descent.
- max_glyph_w: maximum glyph width, that is the maximum width for all the glyphs contained in the rendered
text.
- n: the number of input frame, starting from 0
- rand(min, max): return a random number included between min and max
- sar: The input sample aspect ratio.
- t: timestamp expressed in seconds, NAN if the input timestamp is unknown
- text_h: the height of the rendered text
- th: Alias for ``text_h``.
- text_w: the width of the rendered text
- tw: Alias for ``text_w``.
- x: the x offset coordinates where the text is drawn.
- y: the y offset coordinates where the text is drawn.
These parameters allow the x and y expressions to refer each other, so you can for example specify
``y=x/dar``.
Official documentation: `drawtext <https://ffmpeg.org/ffmpeg-filters.html#drawtext>`__
"""
if text is not None:
if escape_text:
text = escape_chars(text, '\\\'%')
kwargs['text'] = text
if x != 0:
kwargs['x'] = x
if y != 0:
kwargs['y'] = y
return filter(stream, drawtext.__name__, **kwargs) | python | def drawtext(stream, text=None, x=0, y=0, escape_text=True, **kwargs):
"""Draw a text string or text from a specified file on top of a video, using the libfreetype library.
To enable compilation of this filter, you need to configure FFmpeg with ``--enable-libfreetype``. To enable default
font fallback and the font option you need to configure FFmpeg with ``--enable-libfontconfig``. To enable the
text_shaping option, you need to configure FFmpeg with ``--enable-libfribidi``.
Args:
box: Used to draw a box around text using the background color. The value must be either 1 (enable) or 0
(disable). The default value of box is 0.
boxborderw: Set the width of the border to be drawn around the box using boxcolor. The default value of
boxborderw is 0.
boxcolor: The color to be used for drawing box around text. For the syntax of this option, check the "Color"
section in the ffmpeg-utils manual. The default value of boxcolor is "white".
line_spacing: Set the line spacing in pixels of the border to be drawn around the box using box. The default
value of line_spacing is 0.
borderw: Set the width of the border to be drawn around the text using bordercolor. The default value of
borderw is 0.
bordercolor: Set the color to be used for drawing border around text. For the syntax of this option, check the
"Color" section in the ffmpeg-utils manual. The default value of bordercolor is "black".
expansion: Select how the text is expanded. Can be either none, strftime (deprecated) or normal (default). See
the Text expansion section below for details.
basetime: Set a start time for the count. Value is in microseconds. Only applied in the deprecated strftime
expansion mode. To emulate in normal expansion mode use the pts function, supplying the start time (in
seconds) as the second argument.
fix_bounds: If true, check and fix text coords to avoid clipping.
fontcolor: The color to be used for drawing fonts. For the syntax of this option, check the "Color" section in
the ffmpeg-utils manual. The default value of fontcolor is "black".
fontcolor_expr: String which is expanded the same way as text to obtain dynamic fontcolor value. By default
this option has empty value and is not processed. When this option is set, it overrides fontcolor option.
font: The font family to be used for drawing text. By default Sans.
fontfile: The font file to be used for drawing text. The path must be included. This parameter is mandatory if
the fontconfig support is disabled.
alpha: Draw the text applying alpha blending. The value can be a number between 0.0 and 1.0. The expression
accepts the same variables x, y as well. The default value is 1. Please see fontcolor_expr.
fontsize: The font size to be used for drawing text. The default value of fontsize is 16.
text_shaping: If set to 1, attempt to shape the text (for example, reverse the order of right-to-left text and
join Arabic characters) before drawing it. Otherwise, just draw the text exactly as given. By default 1 (if
supported).
ft_load_flags: The flags to be used for loading the fonts. The flags map the corresponding flags supported by
libfreetype, and are a combination of the following values:
* ``default``
* ``no_scale``
* ``no_hinting``
* ``render``
* ``no_bitmap``
* ``vertical_layout``
* ``force_autohint``
* ``crop_bitmap``
* ``pedantic``
* ``ignore_global_advance_width``
* ``no_recurse``
* ``ignore_transform``
* ``monochrome``
* ``linear_design``
* ``no_autohint``
Default value is "default". For more information consult the documentation for the FT_LOAD_* libfreetype
flags.
shadowcolor: The color to be used for drawing a shadow behind the drawn text. For the syntax of this option,
check the "Color" section in the ffmpeg-utils manual. The default value of shadowcolor is "black".
shadowx: The x offset for the text shadow position with respect to the position of the text. It can be either
positive or negative values. The default value is "0".
shadowy: The y offset for the text shadow position with respect to the position of the text. It can be either
positive or negative values. The default value is "0".
start_number: The starting frame number for the n/frame_num variable. The default value is "0".
tabsize: The size in number of spaces to use for rendering the tab. Default value is 4.
timecode: Set the initial timecode representation in "hh:mm:ss[:;.]ff" format. It can be used with or without
text parameter. timecode_rate option must be specified.
rate: Set the timecode frame rate (timecode only).
timecode_rate: Alias for ``rate``.
r: Alias for ``rate``.
tc24hmax: If set to 1, the output of the timecode option will wrap around at 24 hours. Default is 0 (disabled).
text: The text string to be drawn. The text must be a sequence of UTF-8 encoded characters. This parameter is
mandatory if no file is specified with the parameter textfile.
textfile: A text file containing text to be drawn. The text must be a sequence of UTF-8 encoded characters.
This parameter is mandatory if no text string is specified with the parameter text. If both text and
textfile are specified, an error is thrown.
reload: If set to 1, the textfile will be reloaded before each frame. Be sure to update it atomically, or it
may be read partially, or even fail.
x: The expression which specifies the offset where text will be drawn within the video frame. It is relative to
the left border of the output image. The default value is "0".
y: The expression which specifies the offset where text will be drawn within the video frame. It is relative to
the top border of the output image. The default value is "0". See below for the list of accepted constants
and functions.
Expression constants:
The parameters for x and y are expressions containing the following constants and functions:
- dar: input display aspect ratio, it is the same as ``(w / h) * sar``
- hsub: horizontal chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub
is 1.
- vsub: vertical chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub
is 1.
- line_h: the height of each text line
- lh: Alias for ``line_h``.
- main_h: the input height
- h: Alias for ``main_h``.
- H: Alias for ``main_h``.
- main_w: the input width
- w: Alias for ``main_w``.
- W: Alias for ``main_w``.
- ascent: the maximum distance from the baseline to the highest/upper grid coordinate used to place a glyph
outline point, for all the rendered glyphs. It is a positive value, due to the grid's orientation with the Y
axis upwards.
- max_glyph_a: Alias for ``ascent``.
- descent: the maximum distance from the baseline to the lowest grid coordinate used to place a glyph outline
point, for all the rendered glyphs. This is a negative value, due to the grid's orientation, with the Y axis
upwards.
- max_glyph_d: Alias for ``descent``.
- max_glyph_h: maximum glyph height, that is the maximum height for all the glyphs contained in the rendered
text, it is equivalent to ascent - descent.
- max_glyph_w: maximum glyph width, that is the maximum width for all the glyphs contained in the rendered
text.
- n: the number of input frame, starting from 0
- rand(min, max): return a random number included between min and max
- sar: The input sample aspect ratio.
- t: timestamp expressed in seconds, NAN if the input timestamp is unknown
- text_h: the height of the rendered text
- th: Alias for ``text_h``.
- text_w: the width of the rendered text
- tw: Alias for ``text_w``.
- x: the x offset coordinates where the text is drawn.
- y: the y offset coordinates where the text is drawn.
These parameters allow the x and y expressions to refer each other, so you can for example specify
``y=x/dar``.
Official documentation: `drawtext <https://ffmpeg.org/ffmpeg-filters.html#drawtext>`__
"""
if text is not None:
if escape_text:
text = escape_chars(text, '\\\'%')
kwargs['text'] = text
if x != 0:
kwargs['x'] = x
if y != 0:
kwargs['y'] = y
return filter(stream, drawtext.__name__, **kwargs) | [
"def",
"drawtext",
"(",
"stream",
",",
"text",
"=",
"None",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"escape_text",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"text",
"is",
"not",
"None",
":",
"if",
"escape_text",
":",
"text",
"=... | Draw a text string or text from a specified file on top of a video, using the libfreetype library.
To enable compilation of this filter, you need to configure FFmpeg with ``--enable-libfreetype``. To enable default
font fallback and the font option you need to configure FFmpeg with ``--enable-libfontconfig``. To enable the
text_shaping option, you need to configure FFmpeg with ``--enable-libfribidi``.
Args:
box: Used to draw a box around text using the background color. The value must be either 1 (enable) or 0
(disable). The default value of box is 0.
boxborderw: Set the width of the border to be drawn around the box using boxcolor. The default value of
boxborderw is 0.
boxcolor: The color to be used for drawing box around text. For the syntax of this option, check the "Color"
section in the ffmpeg-utils manual. The default value of boxcolor is "white".
line_spacing: Set the line spacing in pixels of the border to be drawn around the box using box. The default
value of line_spacing is 0.
borderw: Set the width of the border to be drawn around the text using bordercolor. The default value of
borderw is 0.
bordercolor: Set the color to be used for drawing border around text. For the syntax of this option, check the
"Color" section in the ffmpeg-utils manual. The default value of bordercolor is "black".
expansion: Select how the text is expanded. Can be either none, strftime (deprecated) or normal (default). See
the Text expansion section below for details.
basetime: Set a start time for the count. Value is in microseconds. Only applied in the deprecated strftime
expansion mode. To emulate in normal expansion mode use the pts function, supplying the start time (in
seconds) as the second argument.
fix_bounds: If true, check and fix text coords to avoid clipping.
fontcolor: The color to be used for drawing fonts. For the syntax of this option, check the "Color" section in
the ffmpeg-utils manual. The default value of fontcolor is "black".
fontcolor_expr: String which is expanded the same way as text to obtain dynamic fontcolor value. By default
this option has empty value and is not processed. When this option is set, it overrides fontcolor option.
font: The font family to be used for drawing text. By default Sans.
fontfile: The font file to be used for drawing text. The path must be included. This parameter is mandatory if
the fontconfig support is disabled.
alpha: Draw the text applying alpha blending. The value can be a number between 0.0 and 1.0. The expression
accepts the same variables x, y as well. The default value is 1. Please see fontcolor_expr.
fontsize: The font size to be used for drawing text. The default value of fontsize is 16.
text_shaping: If set to 1, attempt to shape the text (for example, reverse the order of right-to-left text and
join Arabic characters) before drawing it. Otherwise, just draw the text exactly as given. By default 1 (if
supported).
ft_load_flags: The flags to be used for loading the fonts. The flags map the corresponding flags supported by
libfreetype, and are a combination of the following values:
* ``default``
* ``no_scale``
* ``no_hinting``
* ``render``
* ``no_bitmap``
* ``vertical_layout``
* ``force_autohint``
* ``crop_bitmap``
* ``pedantic``
* ``ignore_global_advance_width``
* ``no_recurse``
* ``ignore_transform``
* ``monochrome``
* ``linear_design``
* ``no_autohint``
Default value is "default". For more information consult the documentation for the FT_LOAD_* libfreetype
flags.
shadowcolor: The color to be used for drawing a shadow behind the drawn text. For the syntax of this option,
check the "Color" section in the ffmpeg-utils manual. The default value of shadowcolor is "black".
shadowx: The x offset for the text shadow position with respect to the position of the text. It can be either
positive or negative values. The default value is "0".
shadowy: The y offset for the text shadow position with respect to the position of the text. It can be either
positive or negative values. The default value is "0".
start_number: The starting frame number for the n/frame_num variable. The default value is "0".
tabsize: The size in number of spaces to use for rendering the tab. Default value is 4.
timecode: Set the initial timecode representation in "hh:mm:ss[:;.]ff" format. It can be used with or without
text parameter. timecode_rate option must be specified.
rate: Set the timecode frame rate (timecode only).
timecode_rate: Alias for ``rate``.
r: Alias for ``rate``.
tc24hmax: If set to 1, the output of the timecode option will wrap around at 24 hours. Default is 0 (disabled).
text: The text string to be drawn. The text must be a sequence of UTF-8 encoded characters. This parameter is
mandatory if no file is specified with the parameter textfile.
textfile: A text file containing text to be drawn. The text must be a sequence of UTF-8 encoded characters.
This parameter is mandatory if no text string is specified with the parameter text. If both text and
textfile are specified, an error is thrown.
reload: If set to 1, the textfile will be reloaded before each frame. Be sure to update it atomically, or it
may be read partially, or even fail.
x: The expression which specifies the offset where text will be drawn within the video frame. It is relative to
the left border of the output image. The default value is "0".
y: The expression which specifies the offset where text will be drawn within the video frame. It is relative to
the top border of the output image. The default value is "0". See below for the list of accepted constants
and functions.
Expression constants:
The parameters for x and y are expressions containing the following constants and functions:
- dar: input display aspect ratio, it is the same as ``(w / h) * sar``
- hsub: horizontal chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub
is 1.
- vsub: vertical chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub
is 1.
- line_h: the height of each text line
- lh: Alias for ``line_h``.
- main_h: the input height
- h: Alias for ``main_h``.
- H: Alias for ``main_h``.
- main_w: the input width
- w: Alias for ``main_w``.
- W: Alias for ``main_w``.
- ascent: the maximum distance from the baseline to the highest/upper grid coordinate used to place a glyph
outline point, for all the rendered glyphs. It is a positive value, due to the grid's orientation with the Y
axis upwards.
- max_glyph_a: Alias for ``ascent``.
- descent: the maximum distance from the baseline to the lowest grid coordinate used to place a glyph outline
point, for all the rendered glyphs. This is a negative value, due to the grid's orientation, with the Y axis
upwards.
- max_glyph_d: Alias for ``descent``.
- max_glyph_h: maximum glyph height, that is the maximum height for all the glyphs contained in the rendered
text, it is equivalent to ascent - descent.
- max_glyph_w: maximum glyph width, that is the maximum width for all the glyphs contained in the rendered
text.
- n: the number of input frame, starting from 0
- rand(min, max): return a random number included between min and max
- sar: The input sample aspect ratio.
- t: timestamp expressed in seconds, NAN if the input timestamp is unknown
- text_h: the height of the rendered text
- th: Alias for ``text_h``.
- text_w: the width of the rendered text
- tw: Alias for ``text_w``.
- x: the x offset coordinates where the text is drawn.
- y: the y offset coordinates where the text is drawn.
These parameters allow the x and y expressions to refer each other, so you can for example specify
``y=x/dar``.
Official documentation: `drawtext <https://ffmpeg.org/ffmpeg-filters.html#drawtext>`__ | [
"Draw",
"a",
"text",
"string",
"or",
"text",
"from",
"a",
"specified",
"file",
"on",
"top",
"of",
"a",
"video",
"using",
"the",
"libfreetype",
"library",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L216-L354 | train | 217,142 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | concat | def concat(*streams, **kwargs):
"""Concatenate audio and video streams, joining them together one after the other.
The filter works on segments of synchronized video and audio streams. All segments must have the same number of
streams of each type, and that will also be the number of streams at output.
Args:
unsafe: Activate unsafe mode: do not fail if segments have a different format.
Related streams do not always have exactly the same duration, for various reasons including codec frame size or
sloppy authoring. For that reason, related synchronized streams (e.g. a video and its audio track) should be
concatenated at once. The concat filter will use the duration of the longest stream in each segment (except the
last one), and if necessary pad shorter audio streams with silence.
For this filter to work correctly, all segments must start at timestamp 0.
All corresponding streams must have the same parameters in all segments; the filtering system will automatically
select a common pixel format for video streams, and a common sample format, sample rate and channel layout for
audio streams, but other settings, such as resolution, must be converted explicitly by the user.
Different frame rates are acceptable but will result in variable frame rate at output; be sure to configure the
output file to handle it.
Official documentation: `concat <https://ffmpeg.org/ffmpeg-filters.html#concat>`__
"""
video_stream_count = kwargs.get('v', 1)
audio_stream_count = kwargs.get('a', 0)
stream_count = video_stream_count + audio_stream_count
if len(streams) % stream_count != 0:
raise ValueError(
'Expected concat input streams to have length multiple of {} (v={}, a={}); got {}'
.format(stream_count, video_stream_count, audio_stream_count, len(streams)))
kwargs['n'] = int(len(streams) / stream_count)
return FilterNode(streams, concat.__name__, kwargs=kwargs, max_inputs=None).stream() | python | def concat(*streams, **kwargs):
"""Concatenate audio and video streams, joining them together one after the other.
The filter works on segments of synchronized video and audio streams. All segments must have the same number of
streams of each type, and that will also be the number of streams at output.
Args:
unsafe: Activate unsafe mode: do not fail if segments have a different format.
Related streams do not always have exactly the same duration, for various reasons including codec frame size or
sloppy authoring. For that reason, related synchronized streams (e.g. a video and its audio track) should be
concatenated at once. The concat filter will use the duration of the longest stream in each segment (except the
last one), and if necessary pad shorter audio streams with silence.
For this filter to work correctly, all segments must start at timestamp 0.
All corresponding streams must have the same parameters in all segments; the filtering system will automatically
select a common pixel format for video streams, and a common sample format, sample rate and channel layout for
audio streams, but other settings, such as resolution, must be converted explicitly by the user.
Different frame rates are acceptable but will result in variable frame rate at output; be sure to configure the
output file to handle it.
Official documentation: `concat <https://ffmpeg.org/ffmpeg-filters.html#concat>`__
"""
video_stream_count = kwargs.get('v', 1)
audio_stream_count = kwargs.get('a', 0)
stream_count = video_stream_count + audio_stream_count
if len(streams) % stream_count != 0:
raise ValueError(
'Expected concat input streams to have length multiple of {} (v={}, a={}); got {}'
.format(stream_count, video_stream_count, audio_stream_count, len(streams)))
kwargs['n'] = int(len(streams) / stream_count)
return FilterNode(streams, concat.__name__, kwargs=kwargs, max_inputs=None).stream() | [
"def",
"concat",
"(",
"*",
"streams",
",",
"*",
"*",
"kwargs",
")",
":",
"video_stream_count",
"=",
"kwargs",
".",
"get",
"(",
"'v'",
",",
"1",
")",
"audio_stream_count",
"=",
"kwargs",
".",
"get",
"(",
"'a'",
",",
"0",
")",
"stream_count",
"=",
"vid... | Concatenate audio and video streams, joining them together one after the other.
The filter works on segments of synchronized video and audio streams. All segments must have the same number of
streams of each type, and that will also be the number of streams at output.
Args:
unsafe: Activate unsafe mode: do not fail if segments have a different format.
Related streams do not always have exactly the same duration, for various reasons including codec frame size or
sloppy authoring. For that reason, related synchronized streams (e.g. a video and its audio track) should be
concatenated at once. The concat filter will use the duration of the longest stream in each segment (except the
last one), and if necessary pad shorter audio streams with silence.
For this filter to work correctly, all segments must start at timestamp 0.
All corresponding streams must have the same parameters in all segments; the filtering system will automatically
select a common pixel format for video streams, and a common sample format, sample rate and channel layout for
audio streams, but other settings, such as resolution, must be converted explicitly by the user.
Different frame rates are acceptable but will result in variable frame rate at output; be sure to configure the
output file to handle it.
Official documentation: `concat <https://ffmpeg.org/ffmpeg-filters.html#concat>`__ | [
"Concatenate",
"audio",
"and",
"video",
"streams",
"joining",
"them",
"together",
"one",
"after",
"the",
"other",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L358-L391 | train | 217,143 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | zoompan | def zoompan(stream, **kwargs):
"""Apply Zoom & Pan effect.
Args:
zoom: Set the zoom expression. Default is 1.
x: Set the x expression. Default is 0.
y: Set the y expression. Default is 0.
d: Set the duration expression in number of frames. This sets for how many number of frames effect will last
for single input image.
s: Set the output image size, default is ``hd720``.
fps: Set the output frame rate, default is 25.
z: Alias for ``zoom``.
Official documentation: `zoompan <https://ffmpeg.org/ffmpeg-filters.html#zoompan>`__
"""
return FilterNode(stream, zoompan.__name__, kwargs=kwargs).stream() | python | def zoompan(stream, **kwargs):
"""Apply Zoom & Pan effect.
Args:
zoom: Set the zoom expression. Default is 1.
x: Set the x expression. Default is 0.
y: Set the y expression. Default is 0.
d: Set the duration expression in number of frames. This sets for how many number of frames effect will last
for single input image.
s: Set the output image size, default is ``hd720``.
fps: Set the output frame rate, default is 25.
z: Alias for ``zoom``.
Official documentation: `zoompan <https://ffmpeg.org/ffmpeg-filters.html#zoompan>`__
"""
return FilterNode(stream, zoompan.__name__, kwargs=kwargs).stream() | [
"def",
"zoompan",
"(",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FilterNode",
"(",
"stream",
",",
"zoompan",
".",
"__name__",
",",
"kwargs",
"=",
"kwargs",
")",
".",
"stream",
"(",
")"
] | Apply Zoom & Pan effect.
Args:
zoom: Set the zoom expression. Default is 1.
x: Set the x expression. Default is 0.
y: Set the y expression. Default is 0.
d: Set the duration expression in number of frames. This sets for how many number of frames effect will last
for single input image.
s: Set the output image size, default is ``hd720``.
fps: Set the output frame rate, default is 25.
z: Alias for ``zoom``.
Official documentation: `zoompan <https://ffmpeg.org/ffmpeg-filters.html#zoompan>`__ | [
"Apply",
"Zoom",
"&",
"Pan",
"effect",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L395-L410 | train | 217,144 |
kkroening/ffmpeg-python | ffmpeg/_filters.py | colorchannelmixer | def colorchannelmixer(stream, *args, **kwargs):
"""Adjust video input frames by re-mixing color channels.
Official documentation: `colorchannelmixer <https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer>`__
"""
return FilterNode(stream, colorchannelmixer.__name__, kwargs=kwargs).stream() | python | def colorchannelmixer(stream, *args, **kwargs):
"""Adjust video input frames by re-mixing color channels.
Official documentation: `colorchannelmixer <https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer>`__
"""
return FilterNode(stream, colorchannelmixer.__name__, kwargs=kwargs).stream() | [
"def",
"colorchannelmixer",
"(",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FilterNode",
"(",
"stream",
",",
"colorchannelmixer",
".",
"__name__",
",",
"kwargs",
"=",
"kwargs",
")",
".",
"stream",
"(",
")"
] | Adjust video input frames by re-mixing color channels.
Official documentation: `colorchannelmixer <https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer>`__ | [
"Adjust",
"video",
"input",
"frames",
"by",
"re",
"-",
"mixing",
"color",
"channels",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L429-L434 | train | 217,145 |
kkroening/ffmpeg-python | ffmpeg/_utils.py | _recursive_repr | def _recursive_repr(item):
"""Hack around python `repr` to deterministically represent dictionaries.
This is able to represent more things than json.dumps, since it does not require things to be JSON serializable
(e.g. datetimes).
"""
if isinstance(item, basestring):
result = str(item)
elif isinstance(item, list):
result = '[{}]'.format(', '.join([_recursive_repr(x) for x in item]))
elif isinstance(item, dict):
kv_pairs = ['{}: {}'.format(_recursive_repr(k), _recursive_repr(item[k])) for k in sorted(item)]
result = '{' + ', '.join(kv_pairs) + '}'
else:
result = repr(item)
return result | python | def _recursive_repr(item):
"""Hack around python `repr` to deterministically represent dictionaries.
This is able to represent more things than json.dumps, since it does not require things to be JSON serializable
(e.g. datetimes).
"""
if isinstance(item, basestring):
result = str(item)
elif isinstance(item, list):
result = '[{}]'.format(', '.join([_recursive_repr(x) for x in item]))
elif isinstance(item, dict):
kv_pairs = ['{}: {}'.format(_recursive_repr(k), _recursive_repr(item[k])) for k in sorted(item)]
result = '{' + ', '.join(kv_pairs) + '}'
else:
result = repr(item)
return result | [
"def",
"_recursive_repr",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"basestring",
")",
":",
"result",
"=",
"str",
"(",
"item",
")",
"elif",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"result",
"=",
"'[{}]'",
".",
"format",
"... | Hack around python `repr` to deterministically represent dictionaries.
This is able to represent more things than json.dumps, since it does not require things to be JSON serializable
(e.g. datetimes). | [
"Hack",
"around",
"python",
"repr",
"to",
"deterministically",
"represent",
"dictionaries",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_utils.py#L44-L59 | train | 217,146 |
kkroening/ffmpeg-python | ffmpeg/_utils.py | escape_chars | def escape_chars(text, chars):
"""Helper function to escape uncomfortable characters."""
text = str(text)
chars = list(set(chars))
if '\\' in chars:
chars.remove('\\')
chars.insert(0, '\\')
for ch in chars:
text = text.replace(ch, '\\' + ch)
return text | python | def escape_chars(text, chars):
"""Helper function to escape uncomfortable characters."""
text = str(text)
chars = list(set(chars))
if '\\' in chars:
chars.remove('\\')
chars.insert(0, '\\')
for ch in chars:
text = text.replace(ch, '\\' + ch)
return text | [
"def",
"escape_chars",
"(",
"text",
",",
"chars",
")",
":",
"text",
"=",
"str",
"(",
"text",
")",
"chars",
"=",
"list",
"(",
"set",
"(",
"chars",
")",
")",
"if",
"'\\\\'",
"in",
"chars",
":",
"chars",
".",
"remove",
"(",
"'\\\\'",
")",
"chars",
"... | Helper function to escape uncomfortable characters. | [
"Helper",
"function",
"to",
"escape",
"uncomfortable",
"characters",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_utils.py#L71-L80 | train | 217,147 |
kkroening/ffmpeg-python | ffmpeg/_utils.py | convert_kwargs_to_cmd_line_args | def convert_kwargs_to_cmd_line_args(kwargs):
"""Helper function to build command line arguments out of dict."""
args = []
for k in sorted(kwargs.keys()):
v = kwargs[k]
args.append('-{}'.format(k))
if v is not None:
args.append('{}'.format(v))
return args | python | def convert_kwargs_to_cmd_line_args(kwargs):
"""Helper function to build command line arguments out of dict."""
args = []
for k in sorted(kwargs.keys()):
v = kwargs[k]
args.append('-{}'.format(k))
if v is not None:
args.append('{}'.format(v))
return args | [
"def",
"convert_kwargs_to_cmd_line_args",
"(",
"kwargs",
")",
":",
"args",
"=",
"[",
"]",
"for",
"k",
"in",
"sorted",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
":",
"v",
"=",
"kwargs",
"[",
"k",
"]",
"args",
".",
"append",
"(",
"'-{}'",
".",
"form... | Helper function to build command line arguments out of dict. | [
"Helper",
"function",
"to",
"build",
"command",
"line",
"arguments",
"out",
"of",
"dict",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_utils.py#L83-L91 | train | 217,148 |
kkroening/ffmpeg-python | ffmpeg/nodes.py | Node.stream | def stream(self, label=None, selector=None):
"""Create an outgoing stream originating from this node.
More nodes may be attached onto the outgoing stream.
"""
return self.__outgoing_stream_type(self, label, upstream_selector=selector) | python | def stream(self, label=None, selector=None):
"""Create an outgoing stream originating from this node.
More nodes may be attached onto the outgoing stream.
"""
return self.__outgoing_stream_type(self, label, upstream_selector=selector) | [
"def",
"stream",
"(",
"self",
",",
"label",
"=",
"None",
",",
"selector",
"=",
"None",
")",
":",
"return",
"self",
".",
"__outgoing_stream_type",
"(",
"self",
",",
"label",
",",
"upstream_selector",
"=",
"selector",
")"
] | Create an outgoing stream originating from this node.
More nodes may be attached onto the outgoing stream. | [
"Create",
"an",
"outgoing",
"stream",
"originating",
"from",
"this",
"node",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/nodes.py#L128-L133 | train | 217,149 |
kkroening/ffmpeg-python | examples/tensorflow_stream.py | DeepDream._tffunc | def _tffunc(*argtypes):
'''Helper that transforms TF-graph generating function into a regular one.
See `_resize` function below.
'''
placeholders = list(map(tf.placeholder, argtypes))
def wrap(f):
out = f(*placeholders)
def wrapper(*args, **kw):
return out.eval(dict(zip(placeholders, args)), session=kw.get('session'))
return wrapper
return wrap | python | def _tffunc(*argtypes):
'''Helper that transforms TF-graph generating function into a regular one.
See `_resize` function below.
'''
placeholders = list(map(tf.placeholder, argtypes))
def wrap(f):
out = f(*placeholders)
def wrapper(*args, **kw):
return out.eval(dict(zip(placeholders, args)), session=kw.get('session'))
return wrapper
return wrap | [
"def",
"_tffunc",
"(",
"*",
"argtypes",
")",
":",
"placeholders",
"=",
"list",
"(",
"map",
"(",
"tf",
".",
"placeholder",
",",
"argtypes",
")",
")",
"def",
"wrap",
"(",
"f",
")",
":",
"out",
"=",
"f",
"(",
"*",
"placeholders",
")",
"def",
"wrapper"... | Helper that transforms TF-graph generating function into a regular one.
See `_resize` function below. | [
"Helper",
"that",
"transforms",
"TF",
"-",
"graph",
"generating",
"function",
"into",
"a",
"regular",
"one",
".",
"See",
"_resize",
"function",
"below",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/tensorflow_stream.py#L159-L169 | train | 217,150 |
kkroening/ffmpeg-python | examples/tensorflow_stream.py | DeepDream._base_resize | def _base_resize(img, size):
'''Helper function that uses TF to resize an image'''
img = tf.expand_dims(img, 0)
return tf.image.resize_bilinear(img, size)[0,:,:,:] | python | def _base_resize(img, size):
'''Helper function that uses TF to resize an image'''
img = tf.expand_dims(img, 0)
return tf.image.resize_bilinear(img, size)[0,:,:,:] | [
"def",
"_base_resize",
"(",
"img",
",",
"size",
")",
":",
"img",
"=",
"tf",
".",
"expand_dims",
"(",
"img",
",",
"0",
")",
"return",
"tf",
".",
"image",
".",
"resize_bilinear",
"(",
"img",
",",
"size",
")",
"[",
"0",
",",
":",
",",
":",
",",
":... | Helper function that uses TF to resize an image | [
"Helper",
"function",
"that",
"uses",
"TF",
"to",
"resize",
"an",
"image"
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/tensorflow_stream.py#L172-L175 | train | 217,151 |
kkroening/ffmpeg-python | examples/tensorflow_stream.py | DeepDream._calc_grad_tiled | def _calc_grad_tiled(self, img, t_grad, tile_size=512):
'''Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations.'''
sz = tile_size
h, w = img.shape[:2]
sx, sy = np.random.randint(sz, size=2)
img_shift = np.roll(np.roll(img, sx, 1), sy, 0)
grad = np.zeros_like(img)
for y in range(0, max(h-sz//2, sz),sz):
for x in range(0, max(w-sz//2, sz),sz):
sub = img_shift[y:y+sz,x:x+sz]
g = self._session.run(t_grad, {self._t_input:sub})
grad[y:y+sz,x:x+sz] = g
return np.roll(np.roll(grad, -sx, 1), -sy, 0) | python | def _calc_grad_tiled(self, img, t_grad, tile_size=512):
'''Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations.'''
sz = tile_size
h, w = img.shape[:2]
sx, sy = np.random.randint(sz, size=2)
img_shift = np.roll(np.roll(img, sx, 1), sy, 0)
grad = np.zeros_like(img)
for y in range(0, max(h-sz//2, sz),sz):
for x in range(0, max(w-sz//2, sz),sz):
sub = img_shift[y:y+sz,x:x+sz]
g = self._session.run(t_grad, {self._t_input:sub})
grad[y:y+sz,x:x+sz] = g
return np.roll(np.roll(grad, -sx, 1), -sy, 0) | [
"def",
"_calc_grad_tiled",
"(",
"self",
",",
"img",
",",
"t_grad",
",",
"tile_size",
"=",
"512",
")",
":",
"sz",
"=",
"tile_size",
"h",
",",
"w",
"=",
"img",
".",
"shape",
"[",
":",
"2",
"]",
"sx",
",",
"sy",
"=",
"np",
".",
"random",
".",
"ran... | Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations. | [
"Compute",
"the",
"value",
"of",
"tensor",
"t_grad",
"over",
"the",
"image",
"in",
"a",
"tiled",
"way",
".",
"Random",
"shifts",
"are",
"applied",
"to",
"the",
"image",
"to",
"blur",
"tile",
"boundaries",
"over",
"multiple",
"iterations",
"."
] | ac111dc3a976ddbb872bc7d6d4fe24a267c1a956 | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/tensorflow_stream.py#L199-L213 | train | 217,152 |
python-diamond/Diamond | src/collectors/xen_collector/xen_collector.py | XENCollector.collect | def collect(self):
"""
Collect libvirt data
"""
if libvirt is None:
self.log.error('Unable to import either libvirt')
return {}
# Open a restricted (non-root) connection to the hypervisor
conn = libvirt.openReadOnly(None)
# Get hardware info
conninfo = conn.getInfo()
# Initialize variables
memallocated = 0
coresallocated = 0
totalcores = 0
results = {}
domIds = conn.listDomainsID()
if 0 in domIds:
# Total cores
domU = conn.lookupByID(0)
totalcores = domU.info()[3]
# Free Space
s = os.statvfs('/')
freeSpace = (s.f_bavail * s.f_frsize) / 1024
# Calculate allocated memory and cores
for i in domIds:
# Ignore 0
if i == 0:
continue
domU = conn.lookupByID(i)
dominfo = domU.info()
memallocated += dominfo[2]
if i > 0:
coresallocated += dominfo[3]
results = {
'InstalledMem': conninfo[1],
'MemAllocated': memallocated / 1024,
'MemFree': conninfo[1] - (memallocated / 1024),
'AllocatedCores': coresallocated,
'DiskFree': freeSpace,
'TotalCores': totalcores,
'FreeCores': (totalcores - coresallocated)
}
for k in results.keys():
self.publish(k, results[k], 0) | python | def collect(self):
"""
Collect libvirt data
"""
if libvirt is None:
self.log.error('Unable to import either libvirt')
return {}
# Open a restricted (non-root) connection to the hypervisor
conn = libvirt.openReadOnly(None)
# Get hardware info
conninfo = conn.getInfo()
# Initialize variables
memallocated = 0
coresallocated = 0
totalcores = 0
results = {}
domIds = conn.listDomainsID()
if 0 in domIds:
# Total cores
domU = conn.lookupByID(0)
totalcores = domU.info()[3]
# Free Space
s = os.statvfs('/')
freeSpace = (s.f_bavail * s.f_frsize) / 1024
# Calculate allocated memory and cores
for i in domIds:
# Ignore 0
if i == 0:
continue
domU = conn.lookupByID(i)
dominfo = domU.info()
memallocated += dominfo[2]
if i > 0:
coresallocated += dominfo[3]
results = {
'InstalledMem': conninfo[1],
'MemAllocated': memallocated / 1024,
'MemFree': conninfo[1] - (memallocated / 1024),
'AllocatedCores': coresallocated,
'DiskFree': freeSpace,
'TotalCores': totalcores,
'FreeCores': (totalcores - coresallocated)
}
for k in results.keys():
self.publish(k, results[k], 0) | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"libvirt",
"is",
"None",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Unable to import either libvirt'",
")",
"return",
"{",
"}",
"# Open a restricted (non-root) connection to the hypervisor",
"conn",
"=",
"libvirt",
... | Collect libvirt data | [
"Collect",
"libvirt",
"data"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/xen_collector/xen_collector.py#L38-L82 | train | 217,153 |
python-diamond/Diamond | src/collectors/elb/elb.py | ElbCollector.publish_delayed_metric | def publish_delayed_metric(self, name, value, timestamp, raw_value=None,
precision=0, metric_type='GAUGE',
instance=None):
"""
Metrics may not be immediately available when querying cloudwatch.
Hence, allow the ability to publish a metric from some the past given
its timestamp.
"""
# Get metric Path
path = self.get_metric_path(name, instance)
# Get metric TTL
ttl = float(self.config['interval']) * float(
self.config['ttl_multiplier'])
# Create Metric
metric = Metric(path, value, raw_value=raw_value, timestamp=timestamp,
precision=precision, host=self.get_hostname(),
metric_type=metric_type, ttl=ttl)
# Publish Metric
self.publish_metric(metric) | python | def publish_delayed_metric(self, name, value, timestamp, raw_value=None,
precision=0, metric_type='GAUGE',
instance=None):
"""
Metrics may not be immediately available when querying cloudwatch.
Hence, allow the ability to publish a metric from some the past given
its timestamp.
"""
# Get metric Path
path = self.get_metric_path(name, instance)
# Get metric TTL
ttl = float(self.config['interval']) * float(
self.config['ttl_multiplier'])
# Create Metric
metric = Metric(path, value, raw_value=raw_value, timestamp=timestamp,
precision=precision, host=self.get_hostname(),
metric_type=metric_type, ttl=ttl)
# Publish Metric
self.publish_metric(metric) | [
"def",
"publish_delayed_metric",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"raw_value",
"=",
"None",
",",
"precision",
"=",
"0",
",",
"metric_type",
"=",
"'GAUGE'",
",",
"instance",
"=",
"None",
")",
":",
"# Get metric Path",
"path",
"... | Metrics may not be immediately available when querying cloudwatch.
Hence, allow the ability to publish a metric from some the past given
its timestamp. | [
"Metrics",
"may",
"not",
"be",
"immediately",
"available",
"when",
"querying",
"cloudwatch",
".",
"Hence",
"allow",
"the",
"ability",
"to",
"publish",
"a",
"metric",
"from",
"some",
"the",
"past",
"given",
"its",
"timestamp",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elb/elb.py#L184-L205 | train | 217,154 |
python-diamond/Diamond | src/collectors/netapp/netappDisk.py | netappDiskCol.agr_busy | def agr_busy(self):
""" Collector for average disk busyness per aggregate
As of Nov 22nd 2013 there is no API call for agr busyness.
You have to collect all disk busyness and then compute agr
busyness. #fml
"""
c1 = {} # Counters from time a
c2 = {} # Counters from time b
disk_results = {} # Disk busyness results %
agr_results = {} # Aggregate busyness results $
names = ['disk_busy', 'base_for_disk_busy', 'raid_name',
'base_for_disk_busy', 'instance_uuid']
netapp_api = NaElement('perf-object-get-instances')
netapp_api.child_add_string('objectname', 'disk')
disk_1 = self.get_netapp_elem(netapp_api, 'instances')
time.sleep(1)
disk_2 = self.get_netapp_elem(netapp_api, 'instances')
for instance_data in disk_1:
temp = {}
for element in instance_data.findall(".//counters/counter-data"):
if element.find('name').text in names:
temp[element.find('name').text] = element.find(
'value').text
agr_name = temp['raid_name']
agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)]
temp['raid_name'] = agr_name.lstrip('/')
c1[temp.pop('instance_uuid')] = temp
for instance_data in disk_2:
temp = {}
for element in instance_data.findall(".//counters/counter-data"):
if element.find('name').text in names:
temp[element.find('name').text] = element.find(
'value').text
agr_name = temp['raid_name']
agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)]
temp['raid_name'] = agr_name.lstrip('/')
c2[temp.pop('instance_uuid')] = temp
for item in c1:
t_c1 = int(c1[item]['disk_busy']) # time_counter_1
t_b1 = int(c1[item]['base_for_disk_busy']) # time_base_1
t_c2 = int(c2[item]['disk_busy'])
t_b2 = int(c2[item]['base_for_disk_busy'])
disk_busy = 100 * (t_c2 - t_c1) / (t_b2 - t_b1)
if c1[item]['raid_name'] in disk_results:
disk_results[c1[item]['raid_name']].append(disk_busy)
else:
disk_results[c1[item]['raid_name']] = [disk_busy]
for aggregate in disk_results:
agr_results[aggregate] = \
sum(disk_results[aggregate]) / len(disk_results[aggregate])
for aggregate in agr_results:
self.push('avg_busy', 'aggregate.' + aggregate,
agr_results[aggregate]) | python | def agr_busy(self):
""" Collector for average disk busyness per aggregate
As of Nov 22nd 2013 there is no API call for agr busyness.
You have to collect all disk busyness and then compute agr
busyness. #fml
"""
c1 = {} # Counters from time a
c2 = {} # Counters from time b
disk_results = {} # Disk busyness results %
agr_results = {} # Aggregate busyness results $
names = ['disk_busy', 'base_for_disk_busy', 'raid_name',
'base_for_disk_busy', 'instance_uuid']
netapp_api = NaElement('perf-object-get-instances')
netapp_api.child_add_string('objectname', 'disk')
disk_1 = self.get_netapp_elem(netapp_api, 'instances')
time.sleep(1)
disk_2 = self.get_netapp_elem(netapp_api, 'instances')
for instance_data in disk_1:
temp = {}
for element in instance_data.findall(".//counters/counter-data"):
if element.find('name').text in names:
temp[element.find('name').text] = element.find(
'value').text
agr_name = temp['raid_name']
agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)]
temp['raid_name'] = agr_name.lstrip('/')
c1[temp.pop('instance_uuid')] = temp
for instance_data in disk_2:
temp = {}
for element in instance_data.findall(".//counters/counter-data"):
if element.find('name').text in names:
temp[element.find('name').text] = element.find(
'value').text
agr_name = temp['raid_name']
agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)]
temp['raid_name'] = agr_name.lstrip('/')
c2[temp.pop('instance_uuid')] = temp
for item in c1:
t_c1 = int(c1[item]['disk_busy']) # time_counter_1
t_b1 = int(c1[item]['base_for_disk_busy']) # time_base_1
t_c2 = int(c2[item]['disk_busy'])
t_b2 = int(c2[item]['base_for_disk_busy'])
disk_busy = 100 * (t_c2 - t_c1) / (t_b2 - t_b1)
if c1[item]['raid_name'] in disk_results:
disk_results[c1[item]['raid_name']].append(disk_busy)
else:
disk_results[c1[item]['raid_name']] = [disk_busy]
for aggregate in disk_results:
agr_results[aggregate] = \
sum(disk_results[aggregate]) / len(disk_results[aggregate])
for aggregate in agr_results:
self.push('avg_busy', 'aggregate.' + aggregate,
agr_results[aggregate]) | [
"def",
"agr_busy",
"(",
"self",
")",
":",
"c1",
"=",
"{",
"}",
"# Counters from time a",
"c2",
"=",
"{",
"}",
"# Counters from time b",
"disk_results",
"=",
"{",
"}",
"# Disk busyness results %",
"agr_results",
"=",
"{",
"}",
"# Aggregate busyness results $",
"nam... | Collector for average disk busyness per aggregate
As of Nov 22nd 2013 there is no API call for agr busyness.
You have to collect all disk busyness and then compute agr
busyness. #fml | [
"Collector",
"for",
"average",
"disk",
"busyness",
"per",
"aggregate"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L71-L135 | train | 217,155 |
python-diamond/Diamond | src/collectors/netapp/netappDisk.py | netappDiskCol.consistency_point | def consistency_point(self):
""" Collector for getting count of consistancy points
"""
cp_delta = {}
xml_path = 'instances/instance-data/counters'
netapp_api = NaElement('perf-object-get-instances')
netapp_api.child_add_string('objectname', 'wafl')
instance = NaElement('instances')
instance.child_add_string('instance', 'wafl')
counter = NaElement('counters')
counter.child_add_string('counter', 'cp_count')
netapp_api.child_add(counter)
netapp_api.child_add(instance)
cp_1 = self.get_netapp_elem(netapp_api, xml_path)
time.sleep(3)
cp_2 = self.get_netapp_elem(netapp_api, xml_path)
for element in cp_1:
if element.find('name').text == 'cp_count':
cp_1 = element.find('value').text.rsplit(',')
break
for element in cp_2:
if element.find('name').text == 'cp_count':
cp_2 = element.find('value').text.rsplit(',')
break
if not type(cp_2) is list or not type(cp_1) is list:
log.error("consistency point data not available for filer: %s"
% self.device)
return
cp_1 = {
'wafl_timer': cp_1[0],
'snapshot': cp_1[1],
'wafl_avail_bufs': cp_1[2],
'dirty_blk_cnt': cp_1[3],
'full_nv_log': cp_1[4],
'b2b': cp_1[5],
'flush_gen': cp_1[6],
'sync_gen': cp_1[7],
'def_b2b': cp_1[8],
'con_ind_pin': cp_1[9],
'low_mbuf_gen': cp_1[10],
'low_datavec_gen': cp_1[11]
}
cp_2 = {
'wafl_timer': cp_2[0],
'snapshot': cp_2[1],
'wafl_avail_bufs': cp_2[2],
'dirty_blk_cnt': cp_2[3],
'full_nv_log': cp_2[4],
'b2b': cp_2[5],
'flush_gen': cp_2[6],
'sync_gen': cp_2[7],
'def_b2b': cp_2[8],
'con_ind_pin': cp_2[9],
'low_mbuf_gen': cp_2[10],
'low_datavec_gen': cp_2[11]
}
for item in cp_1:
c1 = int(cp_1[item])
c2 = int(cp_2[item])
cp_delta[item] = c2 - c1
for item in cp_delta:
self.push(item + '_CP', 'system.system', cp_delta[item]) | python | def consistency_point(self):
""" Collector for getting count of consistancy points
"""
cp_delta = {}
xml_path = 'instances/instance-data/counters'
netapp_api = NaElement('perf-object-get-instances')
netapp_api.child_add_string('objectname', 'wafl')
instance = NaElement('instances')
instance.child_add_string('instance', 'wafl')
counter = NaElement('counters')
counter.child_add_string('counter', 'cp_count')
netapp_api.child_add(counter)
netapp_api.child_add(instance)
cp_1 = self.get_netapp_elem(netapp_api, xml_path)
time.sleep(3)
cp_2 = self.get_netapp_elem(netapp_api, xml_path)
for element in cp_1:
if element.find('name').text == 'cp_count':
cp_1 = element.find('value').text.rsplit(',')
break
for element in cp_2:
if element.find('name').text == 'cp_count':
cp_2 = element.find('value').text.rsplit(',')
break
if not type(cp_2) is list or not type(cp_1) is list:
log.error("consistency point data not available for filer: %s"
% self.device)
return
cp_1 = {
'wafl_timer': cp_1[0],
'snapshot': cp_1[1],
'wafl_avail_bufs': cp_1[2],
'dirty_blk_cnt': cp_1[3],
'full_nv_log': cp_1[4],
'b2b': cp_1[5],
'flush_gen': cp_1[6],
'sync_gen': cp_1[7],
'def_b2b': cp_1[8],
'con_ind_pin': cp_1[9],
'low_mbuf_gen': cp_1[10],
'low_datavec_gen': cp_1[11]
}
cp_2 = {
'wafl_timer': cp_2[0],
'snapshot': cp_2[1],
'wafl_avail_bufs': cp_2[2],
'dirty_blk_cnt': cp_2[3],
'full_nv_log': cp_2[4],
'b2b': cp_2[5],
'flush_gen': cp_2[6],
'sync_gen': cp_2[7],
'def_b2b': cp_2[8],
'con_ind_pin': cp_2[9],
'low_mbuf_gen': cp_2[10],
'low_datavec_gen': cp_2[11]
}
for item in cp_1:
c1 = int(cp_1[item])
c2 = int(cp_2[item])
cp_delta[item] = c2 - c1
for item in cp_delta:
self.push(item + '_CP', 'system.system', cp_delta[item]) | [
"def",
"consistency_point",
"(",
"self",
")",
":",
"cp_delta",
"=",
"{",
"}",
"xml_path",
"=",
"'instances/instance-data/counters'",
"netapp_api",
"=",
"NaElement",
"(",
"'perf-object-get-instances'",
")",
"netapp_api",
".",
"child_add_string",
"(",
"'objectname'",
",... | Collector for getting count of consistancy points | [
"Collector",
"for",
"getting",
"count",
"of",
"consistancy",
"points"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L137-L206 | train | 217,156 |
python-diamond/Diamond | src/collectors/netapp/netappDisk.py | netappDiskCol.zero_disk | def zero_disk(self, disk_xml=None):
""" Collector and publish not zeroed disk metrics
"""
troubled_disks = 0
for filer_disk in disk_xml:
raid_state = filer_disk.find('raid-state').text
if not raid_state == 'spare':
continue
is_zeroed = filer_disk.find('is-zeroed').text
if is_zeroed == 'false':
troubled_disks += 1
self.push('not_zeroed', 'disk', troubled_disks) | python | def zero_disk(self, disk_xml=None):
""" Collector and publish not zeroed disk metrics
"""
troubled_disks = 0
for filer_disk in disk_xml:
raid_state = filer_disk.find('raid-state').text
if not raid_state == 'spare':
continue
is_zeroed = filer_disk.find('is-zeroed').text
if is_zeroed == 'false':
troubled_disks += 1
self.push('not_zeroed', 'disk', troubled_disks) | [
"def",
"zero_disk",
"(",
"self",
",",
"disk_xml",
"=",
"None",
")",
":",
"troubled_disks",
"=",
"0",
"for",
"filer_disk",
"in",
"disk_xml",
":",
"raid_state",
"=",
"filer_disk",
".",
"find",
"(",
"'raid-state'",
")",
".",
"text",
"if",
"not",
"raid_state",... | Collector and publish not zeroed disk metrics | [
"Collector",
"and",
"publish",
"not",
"zeroed",
"disk",
"metrics"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L225-L238 | train | 217,157 |
python-diamond/Diamond | src/collectors/netapp/netappDisk.py | netappDiskCol.spare_disk | def spare_disk(self, disk_xml=None):
""" Number of spare disk per type.
For example: storage.ontap.filer201.disk.SATA
"""
spare_disk = {}
disk_types = set()
for filer_disk in disk_xml:
disk_types.add(filer_disk.find('effective-disk-type').text)
if not filer_disk.find('raid-state').text == 'spare':
continue
disk_type = filer_disk.find('effective-disk-type').text
if disk_type in spare_disk:
spare_disk[disk_type] += 1
else:
spare_disk[disk_type] = 1
for disk_type in disk_types:
if disk_type in spare_disk:
self.push('spare_' + disk_type, 'disk', spare_disk[disk_type])
else:
self.push('spare_' + disk_type, 'disk', 0) | python | def spare_disk(self, disk_xml=None):
""" Number of spare disk per type.
For example: storage.ontap.filer201.disk.SATA
"""
spare_disk = {}
disk_types = set()
for filer_disk in disk_xml:
disk_types.add(filer_disk.find('effective-disk-type').text)
if not filer_disk.find('raid-state').text == 'spare':
continue
disk_type = filer_disk.find('effective-disk-type').text
if disk_type in spare_disk:
spare_disk[disk_type] += 1
else:
spare_disk[disk_type] = 1
for disk_type in disk_types:
if disk_type in spare_disk:
self.push('spare_' + disk_type, 'disk', spare_disk[disk_type])
else:
self.push('spare_' + disk_type, 'disk', 0) | [
"def",
"spare_disk",
"(",
"self",
",",
"disk_xml",
"=",
"None",
")",
":",
"spare_disk",
"=",
"{",
"}",
"disk_types",
"=",
"set",
"(",
")",
"for",
"filer_disk",
"in",
"disk_xml",
":",
"disk_types",
".",
"add",
"(",
"filer_disk",
".",
"find",
"(",
"'effe... | Number of spare disk per type.
For example: storage.ontap.filer201.disk.SATA | [
"Number",
"of",
"spare",
"disk",
"per",
"type",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L240-L265 | train | 217,158 |
python-diamond/Diamond | src/collectors/netapp/netappDisk.py | netappDiskCol.get_netapp_elem | def get_netapp_elem(self, netapp_api=None, sub_element=None):
""" Retrieve netapp elem
"""
netapp_data = self.server.invoke_elem(netapp_api)
if netapp_data.results_status() == 'failed':
self.log.error(
'While using netapp API failed to retrieve '
'disk-list-info for netapp filer %s' % self.device)
print(netapp_data.sprintf())
return
netapp_xml = \
ET.fromstring(netapp_data.sprintf()).find(sub_element)
return netapp_xml | python | def get_netapp_elem(self, netapp_api=None, sub_element=None):
""" Retrieve netapp elem
"""
netapp_data = self.server.invoke_elem(netapp_api)
if netapp_data.results_status() == 'failed':
self.log.error(
'While using netapp API failed to retrieve '
'disk-list-info for netapp filer %s' % self.device)
print(netapp_data.sprintf())
return
netapp_xml = \
ET.fromstring(netapp_data.sprintf()).find(sub_element)
return netapp_xml | [
"def",
"get_netapp_elem",
"(",
"self",
",",
"netapp_api",
"=",
"None",
",",
"sub_element",
"=",
"None",
")",
":",
"netapp_data",
"=",
"self",
".",
"server",
".",
"invoke_elem",
"(",
"netapp_api",
")",
"if",
"netapp_data",
".",
"results_status",
"(",
")",
"... | Retrieve netapp elem | [
"Retrieve",
"netapp",
"elem"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L267-L282 | train | 217,159 |
python-diamond/Diamond | src/collectors/netapp/netappDisk.py | netappDiskCol._netapp_login | def _netapp_login(self):
""" Login to our netapp filer
"""
self.server = NaServer(self.ip, 1, 3)
self.server.set_transport_type('HTTPS')
self.server.set_style('LOGIN')
self.server.set_admin_user(self.netapp_user, self.netapp_password) | python | def _netapp_login(self):
""" Login to our netapp filer
"""
self.server = NaServer(self.ip, 1, 3)
self.server.set_transport_type('HTTPS')
self.server.set_style('LOGIN')
self.server.set_admin_user(self.netapp_user, self.netapp_password) | [
"def",
"_netapp_login",
"(",
"self",
")",
":",
"self",
".",
"server",
"=",
"NaServer",
"(",
"self",
".",
"ip",
",",
"1",
",",
"3",
")",
"self",
".",
"server",
".",
"set_transport_type",
"(",
"'HTTPS'",
")",
"self",
".",
"server",
".",
"set_style",
"(... | Login to our netapp filer | [
"Login",
"to",
"our",
"netapp",
"filer"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L284-L291 | train | 217,160 |
python-diamond/Diamond | src/collectors/ceph/ceph.py | CephCollector._get_socket_paths | def _get_socket_paths(self):
"""Return a sequence of paths to sockets for communicating
with ceph daemons.
"""
socket_pattern = os.path.join(self.config['socket_path'],
(self.config['socket_prefix'] +
'*.' + self.config['socket_ext']))
return glob.glob(socket_pattern) | python | def _get_socket_paths(self):
"""Return a sequence of paths to sockets for communicating
with ceph daemons.
"""
socket_pattern = os.path.join(self.config['socket_path'],
(self.config['socket_prefix'] +
'*.' + self.config['socket_ext']))
return glob.glob(socket_pattern) | [
"def",
"_get_socket_paths",
"(",
"self",
")",
":",
"socket_pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"config",
"[",
"'socket_path'",
"]",
",",
"(",
"self",
".",
"config",
"[",
"'socket_prefix'",
"]",
"+",
"'*.'",
"+",
"self",
"."... | Return a sequence of paths to sockets for communicating
with ceph daemons. | [
"Return",
"a",
"sequence",
"of",
"paths",
"to",
"sockets",
"for",
"communicating",
"with",
"ceph",
"daemons",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L78-L85 | train | 217,161 |
python-diamond/Diamond | src/collectors/ceph/ceph.py | CephCollector._get_counter_prefix_from_socket_name | def _get_counter_prefix_from_socket_name(self, name):
"""Given the name of a UDS socket, return the prefix
for counters coming from that source.
"""
base = os.path.splitext(os.path.basename(name))[0]
if base.startswith(self.config['socket_prefix']):
base = base[len(self.config['socket_prefix']):]
return 'ceph.' + base | python | def _get_counter_prefix_from_socket_name(self, name):
"""Given the name of a UDS socket, return the prefix
for counters coming from that source.
"""
base = os.path.splitext(os.path.basename(name))[0]
if base.startswith(self.config['socket_prefix']):
base = base[len(self.config['socket_prefix']):]
return 'ceph.' + base | [
"def",
"_get_counter_prefix_from_socket_name",
"(",
"self",
",",
"name",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"name",
")",
")",
"[",
"0",
"]",
"if",
"base",
".",
"startswith",
"(",
"... | Given the name of a UDS socket, return the prefix
for counters coming from that source. | [
"Given",
"the",
"name",
"of",
"a",
"UDS",
"socket",
"return",
"the",
"prefix",
"for",
"counters",
"coming",
"from",
"that",
"source",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L87-L94 | train | 217,162 |
python-diamond/Diamond | src/collectors/ceph/ceph.py | CephCollector._get_stats_from_socket | def _get_stats_from_socket(self, name):
"""Return the parsed JSON data returned when ceph is told to
dump the stats from the named socket.
In the event of an error error, the exception is logged, and
an empty result set is returned.
"""
try:
json_blob = subprocess.check_output(
[self.config['ceph_binary'],
'--admin-daemon',
name,
'perf',
'dump',
])
except subprocess.CalledProcessError as err:
self.log.info('Could not get stats from %s: %s',
name, err)
self.log.exception('Could not get stats from %s' % name)
return {}
try:
json_data = json.loads(json_blob)
except Exception as err:
self.log.info('Could not parse stats from %s: %s',
name, err)
self.log.exception('Could not parse stats from %s' % name)
return {}
return json_data | python | def _get_stats_from_socket(self, name):
"""Return the parsed JSON data returned when ceph is told to
dump the stats from the named socket.
In the event of an error error, the exception is logged, and
an empty result set is returned.
"""
try:
json_blob = subprocess.check_output(
[self.config['ceph_binary'],
'--admin-daemon',
name,
'perf',
'dump',
])
except subprocess.CalledProcessError as err:
self.log.info('Could not get stats from %s: %s',
name, err)
self.log.exception('Could not get stats from %s' % name)
return {}
try:
json_data = json.loads(json_blob)
except Exception as err:
self.log.info('Could not parse stats from %s: %s',
name, err)
self.log.exception('Could not parse stats from %s' % name)
return {}
return json_data | [
"def",
"_get_stats_from_socket",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"json_blob",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"self",
".",
"config",
"[",
"'ceph_binary'",
"]",
",",
"'--admin-daemon'",
",",
"name",
",",
"'perf'",
",",
"'du... | Return the parsed JSON data returned when ceph is told to
dump the stats from the named socket.
In the event of an error error, the exception is logged, and
an empty result set is returned. | [
"Return",
"the",
"parsed",
"JSON",
"data",
"returned",
"when",
"ceph",
"is",
"told",
"to",
"dump",
"the",
"stats",
"from",
"the",
"named",
"socket",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L96-L125 | train | 217,163 |
python-diamond/Diamond | src/collectors/ceph/ceph.py | CephCollector._publish_stats | def _publish_stats(self, counter_prefix, stats):
"""Given a stats dictionary from _get_stats_from_socket,
publish the individual values.
"""
for stat_name, stat_value in flatten_dictionary(
stats,
prefix=counter_prefix,
):
self.publish_gauge(stat_name, stat_value) | python | def _publish_stats(self, counter_prefix, stats):
"""Given a stats dictionary from _get_stats_from_socket,
publish the individual values.
"""
for stat_name, stat_value in flatten_dictionary(
stats,
prefix=counter_prefix,
):
self.publish_gauge(stat_name, stat_value) | [
"def",
"_publish_stats",
"(",
"self",
",",
"counter_prefix",
",",
"stats",
")",
":",
"for",
"stat_name",
",",
"stat_value",
"in",
"flatten_dictionary",
"(",
"stats",
",",
"prefix",
"=",
"counter_prefix",
",",
")",
":",
"self",
".",
"publish_gauge",
"(",
"sta... | Given a stats dictionary from _get_stats_from_socket,
publish the individual values. | [
"Given",
"a",
"stats",
"dictionary",
"from",
"_get_stats_from_socket",
"publish",
"the",
"individual",
"values",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L127-L135 | train | 217,164 |
python-diamond/Diamond | src/diamond/handler/graphitepickle.py | GraphitePickleHandler._pickle_batch | def _pickle_batch(self):
"""
Pickle the metrics into a form that can be understood
by the graphite pickle connector.
"""
# Pickle
payload = pickle.dumps(self.batch)
# Pack Message
header = struct.pack("!L", len(payload))
message = header + payload
# Return Message
return message | python | def _pickle_batch(self):
"""
Pickle the metrics into a form that can be understood
by the graphite pickle connector.
"""
# Pickle
payload = pickle.dumps(self.batch)
# Pack Message
header = struct.pack("!L", len(payload))
message = header + payload
# Return Message
return message | [
"def",
"_pickle_batch",
"(",
"self",
")",
":",
"# Pickle",
"payload",
"=",
"pickle",
".",
"dumps",
"(",
"self",
".",
"batch",
")",
"# Pack Message",
"header",
"=",
"struct",
".",
"pack",
"(",
"\"!L\"",
",",
"len",
"(",
"payload",
")",
")",
"message",
"... | Pickle the metrics into a form that can be understood
by the graphite pickle connector. | [
"Pickle",
"the",
"metrics",
"into",
"a",
"form",
"that",
"can",
"be",
"understood",
"by",
"the",
"graphite",
"pickle",
"connector",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/graphitepickle.py#L88-L101 | train | 217,165 |
python-diamond/Diamond | src/diamond/handler/g_metric.py | GmetricHandler._send | def _send(self, metric):
"""
Send data to gmond.
"""
metric_name = self.get_name_from_path(metric.path)
tmax = "60"
dmax = "0"
slope = "both"
# FIXME: Badness, shouldn't *assume* double type
metric_type = "double"
units = ""
group = ""
self.gmetric.send(metric_name,
metric.value,
metric_type,
units,
slope,
tmax,
dmax,
group) | python | def _send(self, metric):
"""
Send data to gmond.
"""
metric_name = self.get_name_from_path(metric.path)
tmax = "60"
dmax = "0"
slope = "both"
# FIXME: Badness, shouldn't *assume* double type
metric_type = "double"
units = ""
group = ""
self.gmetric.send(metric_name,
metric.value,
metric_type,
units,
slope,
tmax,
dmax,
group) | [
"def",
"_send",
"(",
"self",
",",
"metric",
")",
":",
"metric_name",
"=",
"self",
".",
"get_name_from_path",
"(",
"metric",
".",
"path",
")",
"tmax",
"=",
"\"60\"",
"dmax",
"=",
"\"0\"",
"slope",
"=",
"\"both\"",
"# FIXME: Badness, shouldn't *assume* double type... | Send data to gmond. | [
"Send",
"data",
"to",
"gmond",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/g_metric.py#L87-L106 | train | 217,166 |
python-diamond/Diamond | src/diamond/handler/mqtt.py | MQTTHandler.process | def process(self, metric):
"""
Process a metric by converting metric name to MQTT topic name;
the payload is metric and timestamp.
"""
if not mosquitto:
return
line = str(metric)
topic, value, timestamp = line.split()
if len(self.prefix):
topic = "%s/%s" % (self.prefix, topic)
topic = topic.replace('.', '/')
topic = topic.replace('#', '&') # Topic must not contain wildcards
if self.timestamp == 0:
self.mqttc.publish(topic, "%s" % (value), self.qos)
else:
self.mqttc.publish(topic, "%s %s" % (value, timestamp), self.qos) | python | def process(self, metric):
"""
Process a metric by converting metric name to MQTT topic name;
the payload is metric and timestamp.
"""
if not mosquitto:
return
line = str(metric)
topic, value, timestamp = line.split()
if len(self.prefix):
topic = "%s/%s" % (self.prefix, topic)
topic = topic.replace('.', '/')
topic = topic.replace('#', '&') # Topic must not contain wildcards
if self.timestamp == 0:
self.mqttc.publish(topic, "%s" % (value), self.qos)
else:
self.mqttc.publish(topic, "%s %s" % (value, timestamp), self.qos) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"if",
"not",
"mosquitto",
":",
"return",
"line",
"=",
"str",
"(",
"metric",
")",
"topic",
",",
"value",
",",
"timestamp",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"self",
".",
... | Process a metric by converting metric name to MQTT topic name;
the payload is metric and timestamp. | [
"Process",
"a",
"metric",
"by",
"converting",
"metric",
"name",
"to",
"MQTT",
"topic",
"name",
";",
"the",
"payload",
"is",
"metric",
"and",
"timestamp",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/mqtt.py#L175-L194 | train | 217,167 |
python-diamond/Diamond | src/diamond/handler/tsdb.py | TSDBHandler.process | def process(self, metric):
"""
Process a metric by sending it to TSDB
"""
entry = {'timestamp': metric.timestamp, 'value': metric.value,
"tags": {}}
entry["tags"]["hostname"] = metric.host
if self.cleanMetrics:
metric = MetricWrapper(metric, self.log)
if self.skipAggregates and metric.isAggregate():
return
for tagKey in metric.getTags():
entry["tags"][tagKey] = metric.getTags()[tagKey]
entry['metric'] = (self.prefix + metric.getCollectorPath() +
'.' + metric.getMetricPath())
for [key, value] in self.tags:
entry["tags"][key] = value
self.entrys.append(entry)
# send data if list is long enough
if (len(self.entrys) >= self.batch):
# Compress data
if self.compression >= 1:
data = StringIO.StringIO()
with contextlib.closing(gzip.GzipFile(fileobj=data,
compresslevel=self.compression,
mode="w")) as f:
f.write(json.dumps(self.entrys))
self._send(data.getvalue())
else:
# no compression
data = json.dumps(self.entrys)
self._send(data) | python | def process(self, metric):
"""
Process a metric by sending it to TSDB
"""
entry = {'timestamp': metric.timestamp, 'value': metric.value,
"tags": {}}
entry["tags"]["hostname"] = metric.host
if self.cleanMetrics:
metric = MetricWrapper(metric, self.log)
if self.skipAggregates and metric.isAggregate():
return
for tagKey in metric.getTags():
entry["tags"][tagKey] = metric.getTags()[tagKey]
entry['metric'] = (self.prefix + metric.getCollectorPath() +
'.' + metric.getMetricPath())
for [key, value] in self.tags:
entry["tags"][key] = value
self.entrys.append(entry)
# send data if list is long enough
if (len(self.entrys) >= self.batch):
# Compress data
if self.compression >= 1:
data = StringIO.StringIO()
with contextlib.closing(gzip.GzipFile(fileobj=data,
compresslevel=self.compression,
mode="w")) as f:
f.write(json.dumps(self.entrys))
self._send(data.getvalue())
else:
# no compression
data = json.dumps(self.entrys)
self._send(data) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"entry",
"=",
"{",
"'timestamp'",
":",
"metric",
".",
"timestamp",
",",
"'value'",
":",
"metric",
".",
"value",
",",
"\"tags\"",
":",
"{",
"}",
"}",
"entry",
"[",
"\"tags\"",
"]",
"[",
"\"hostna... | Process a metric by sending it to TSDB | [
"Process",
"a",
"metric",
"by",
"sending",
"it",
"to",
"TSDB"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/tsdb.py#L189-L225 | train | 217,168 |
python-diamond/Diamond | src/diamond/handler/tsdb.py | TSDBHandler._send | def _send(self, content):
"""
Send content to TSDB.
"""
retry = 0
success = False
while retry < 3 and success is False:
self.log.debug(content)
try:
request = urllib2.Request("http://"+self.host+":" +
str(self.port)+"/api/put",
content, self.httpheader)
response = urllib2.urlopen(url=request, timeout=self.timeout)
if response.getcode() < 301:
self.log.debug(response.read())
# Transaction should be finished
self.log.debug(response.getcode())
success = True
except urllib2.HTTPError as e:
self.log.error("HTTP Error Code: "+str(e.code))
self.log.error("Message : "+str(e.reason))
except urllib2.URLError as e:
self.log.error("Connection Error: "+str(e.reason))
finally:
retry += 1
self.entrys = [] | python | def _send(self, content):
"""
Send content to TSDB.
"""
retry = 0
success = False
while retry < 3 and success is False:
self.log.debug(content)
try:
request = urllib2.Request("http://"+self.host+":" +
str(self.port)+"/api/put",
content, self.httpheader)
response = urllib2.urlopen(url=request, timeout=self.timeout)
if response.getcode() < 301:
self.log.debug(response.read())
# Transaction should be finished
self.log.debug(response.getcode())
success = True
except urllib2.HTTPError as e:
self.log.error("HTTP Error Code: "+str(e.code))
self.log.error("Message : "+str(e.reason))
except urllib2.URLError as e:
self.log.error("Connection Error: "+str(e.reason))
finally:
retry += 1
self.entrys = [] | [
"def",
"_send",
"(",
"self",
",",
"content",
")",
":",
"retry",
"=",
"0",
"success",
"=",
"False",
"while",
"retry",
"<",
"3",
"and",
"success",
"is",
"False",
":",
"self",
".",
"log",
".",
"debug",
"(",
"content",
")",
"try",
":",
"request",
"=",
... | Send content to TSDB. | [
"Send",
"content",
"to",
"TSDB",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/tsdb.py#L227-L252 | train | 217,169 |
python-diamond/Diamond | src/collectors/snmp/snmp.py | SNMPCollector.get | def get(self, oid, host, port, community):
"""
Perform SNMP get for a given OID
"""
# Initialize return value
ret = {}
# Convert OID to tuple if necessary
if not isinstance(oid, tuple):
oid = self._convert_to_oid(oid)
# Convert Host to IP if necessary
host = socket.gethostbyname(host)
# Assemble SNMP Auth Data
snmpAuthData = cmdgen.CommunityData(
'agent-{}'.format(community),
community)
# Assemble SNMP Transport Data
snmpTransportData = cmdgen.UdpTransportTarget(
(host, port),
int(self.config['timeout']),
int(self.config['retries']))
# Assemble SNMP Next Command
result = self.snmpCmdGen.getCmd(snmpAuthData, snmpTransportData, oid)
varBind = result[3]
# TODO: Error check
for o, v in varBind:
ret[str(o)] = v.prettyPrint()
return ret | python | def get(self, oid, host, port, community):
"""
Perform SNMP get for a given OID
"""
# Initialize return value
ret = {}
# Convert OID to tuple if necessary
if not isinstance(oid, tuple):
oid = self._convert_to_oid(oid)
# Convert Host to IP if necessary
host = socket.gethostbyname(host)
# Assemble SNMP Auth Data
snmpAuthData = cmdgen.CommunityData(
'agent-{}'.format(community),
community)
# Assemble SNMP Transport Data
snmpTransportData = cmdgen.UdpTransportTarget(
(host, port),
int(self.config['timeout']),
int(self.config['retries']))
# Assemble SNMP Next Command
result = self.snmpCmdGen.getCmd(snmpAuthData, snmpTransportData, oid)
varBind = result[3]
# TODO: Error check
for o, v in varBind:
ret[str(o)] = v.prettyPrint()
return ret | [
"def",
"get",
"(",
"self",
",",
"oid",
",",
"host",
",",
"port",
",",
"community",
")",
":",
"# Initialize return value",
"ret",
"=",
"{",
"}",
"# Convert OID to tuple if necessary",
"if",
"not",
"isinstance",
"(",
"oid",
",",
"tuple",
")",
":",
"oid",
"="... | Perform SNMP get for a given OID | [
"Perform",
"SNMP",
"get",
"for",
"a",
"given",
"OID"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/snmp/snmp.py#L75-L109 | train | 217,170 |
python-diamond/Diamond | src/collectors/snmp/snmp.py | SNMPCollector.walk | def walk(self, oid, host, port, community):
"""
Perform an SNMP walk on a given OID
"""
# Initialize return value
ret = {}
# Convert OID to tuple if necessary
if not isinstance(oid, tuple):
oid = self._convert_to_oid(oid)
# Convert Host to IP if necessary
host = socket.gethostbyname(host)
# Assemble SNMP Auth Data
snmpAuthData = cmdgen.CommunityData(
'agent-{}'.format(community),
community)
# Assemble SNMP Transport Data
snmpTransportData = cmdgen.UdpTransportTarget(
(host, port),
int(self.config['timeout']),
int(self.config['retries']))
# Assemble SNMP Next Command
resultTable = self.snmpCmdGen.nextCmd(snmpAuthData,
snmpTransportData,
oid)
varBindTable = resultTable[3]
# TODO: Error Check
for varBindTableRow in varBindTable:
for o, v in varBindTableRow:
ret[str(o)] = v.prettyPrint()
return ret | python | def walk(self, oid, host, port, community):
"""
Perform an SNMP walk on a given OID
"""
# Initialize return value
ret = {}
# Convert OID to tuple if necessary
if not isinstance(oid, tuple):
oid = self._convert_to_oid(oid)
# Convert Host to IP if necessary
host = socket.gethostbyname(host)
# Assemble SNMP Auth Data
snmpAuthData = cmdgen.CommunityData(
'agent-{}'.format(community),
community)
# Assemble SNMP Transport Data
snmpTransportData = cmdgen.UdpTransportTarget(
(host, port),
int(self.config['timeout']),
int(self.config['retries']))
# Assemble SNMP Next Command
resultTable = self.snmpCmdGen.nextCmd(snmpAuthData,
snmpTransportData,
oid)
varBindTable = resultTable[3]
# TODO: Error Check
for varBindTableRow in varBindTable:
for o, v in varBindTableRow:
ret[str(o)] = v.prettyPrint()
return ret | [
"def",
"walk",
"(",
"self",
",",
"oid",
",",
"host",
",",
"port",
",",
"community",
")",
":",
"# Initialize return value",
"ret",
"=",
"{",
"}",
"# Convert OID to tuple if necessary",
"if",
"not",
"isinstance",
"(",
"oid",
",",
"tuple",
")",
":",
"oid",
"=... | Perform an SNMP walk on a given OID | [
"Perform",
"an",
"SNMP",
"walk",
"on",
"a",
"given",
"OID"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/snmp/snmp.py#L111-L148 | train | 217,171 |
python-diamond/Diamond | src/collectors/diskusage/diskusage.py | DiskUsageCollector.get_disk_statistics | def get_disk_statistics(self):
"""
Create a map of disks in the machine.
http://www.kernel.org/doc/Documentation/iostats.txt
Returns:
(major, minor) -> DiskStatistics(device, ...)
"""
result = {}
if os.access('/proc/diskstats', os.R_OK):
self.proc_diskstats = True
fp = open('/proc/diskstats')
try:
for line in fp:
try:
columns = line.split()
# On early linux v2.6 versions, partitions have only 4
# output fields not 11. From linux 2.6.25 partitions
# have the full stats set.
if len(columns) < 14:
continue
major = int(columns[0])
minor = int(columns[1])
device = columns[2]
if ((device.startswith('ram') or
device.startswith('loop'))):
continue
result[(major, minor)] = {
'device': device,
'reads': float(columns[3]),
'reads_merged': float(columns[4]),
'reads_sectors': float(columns[5]),
'reads_milliseconds': float(columns[6]),
'writes': float(columns[7]),
'writes_merged': float(columns[8]),
'writes_sectors': float(columns[9]),
'writes_milliseconds': float(columns[10]),
'io_in_progress': float(columns[11]),
'io_milliseconds': float(columns[12]),
'io_milliseconds_weighted': float(columns[13])
}
except ValueError:
continue
finally:
fp.close()
else:
self.proc_diskstats = False
if not psutil:
self.log.error('Unable to import psutil')
return None
disks = psutil.disk_io_counters(True)
sector_size = int(self.config['sector_size'])
for disk in disks:
result[(0, len(result))] = {
'device': disk,
'reads': disks[disk].read_count,
'reads_sectors': disks[disk].read_bytes / sector_size,
'reads_milliseconds': disks[disk].read_time,
'writes': disks[disk].write_count,
'writes_sectors': disks[disk].write_bytes / sector_size,
'writes_milliseconds': disks[disk].write_time,
'io_milliseconds':
disks[disk].read_time + disks[disk].write_time,
'io_milliseconds_weighted':
disks[disk].read_time + disks[disk].write_time
}
return result | python | def get_disk_statistics(self):
"""
Create a map of disks in the machine.
http://www.kernel.org/doc/Documentation/iostats.txt
Returns:
(major, minor) -> DiskStatistics(device, ...)
"""
result = {}
if os.access('/proc/diskstats', os.R_OK):
self.proc_diskstats = True
fp = open('/proc/diskstats')
try:
for line in fp:
try:
columns = line.split()
# On early linux v2.6 versions, partitions have only 4
# output fields not 11. From linux 2.6.25 partitions
# have the full stats set.
if len(columns) < 14:
continue
major = int(columns[0])
minor = int(columns[1])
device = columns[2]
if ((device.startswith('ram') or
device.startswith('loop'))):
continue
result[(major, minor)] = {
'device': device,
'reads': float(columns[3]),
'reads_merged': float(columns[4]),
'reads_sectors': float(columns[5]),
'reads_milliseconds': float(columns[6]),
'writes': float(columns[7]),
'writes_merged': float(columns[8]),
'writes_sectors': float(columns[9]),
'writes_milliseconds': float(columns[10]),
'io_in_progress': float(columns[11]),
'io_milliseconds': float(columns[12]),
'io_milliseconds_weighted': float(columns[13])
}
except ValueError:
continue
finally:
fp.close()
else:
self.proc_diskstats = False
if not psutil:
self.log.error('Unable to import psutil')
return None
disks = psutil.disk_io_counters(True)
sector_size = int(self.config['sector_size'])
for disk in disks:
result[(0, len(result))] = {
'device': disk,
'reads': disks[disk].read_count,
'reads_sectors': disks[disk].read_bytes / sector_size,
'reads_milliseconds': disks[disk].read_time,
'writes': disks[disk].write_count,
'writes_sectors': disks[disk].write_bytes / sector_size,
'writes_milliseconds': disks[disk].write_time,
'io_milliseconds':
disks[disk].read_time + disks[disk].write_time,
'io_milliseconds_weighted':
disks[disk].read_time + disks[disk].write_time
}
return result | [
"def",
"get_disk_statistics",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"if",
"os",
".",
"access",
"(",
"'/proc/diskstats'",
",",
"os",
".",
"R_OK",
")",
":",
"self",
".",
"proc_diskstats",
"=",
"True",
"fp",
"=",
"open",
"(",
"'/proc/diskstats'",
... | Create a map of disks in the machine.
http://www.kernel.org/doc/Documentation/iostats.txt
Returns:
(major, minor) -> DiskStatistics(device, ...) | [
"Create",
"a",
"map",
"of",
"disks",
"in",
"the",
"machine",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/diskusage/diskusage.py#L72-L145 | train | 217,172 |
python-diamond/Diamond | src/diamond/handler/riemann.py | RiemannHandler.process | def process(self, metric):
"""
Send a metric to Riemann.
"""
event = self._metric_to_riemann_event(metric)
try:
self.client.send_event(event)
except Exception as e:
self.log.error(
"RiemannHandler: Error sending event to Riemann: %s", e) | python | def process(self, metric):
"""
Send a metric to Riemann.
"""
event = self._metric_to_riemann_event(metric)
try:
self.client.send_event(event)
except Exception as e:
self.log.error(
"RiemannHandler: Error sending event to Riemann: %s", e) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"event",
"=",
"self",
".",
"_metric_to_riemann_event",
"(",
"metric",
")",
"try",
":",
"self",
".",
"client",
".",
"send_event",
"(",
"event",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
"... | Send a metric to Riemann. | [
"Send",
"a",
"metric",
"to",
"Riemann",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/riemann.py#L83-L92 | train | 217,173 |
python-diamond/Diamond | src/diamond/handler/riemann.py | RiemannHandler._metric_to_riemann_event | def _metric_to_riemann_event(self, metric):
"""
Convert a metric to a dictionary representing a Riemann event.
"""
# Riemann has a separate "host" field, so remove from the path.
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.getMetricPath()
)
return self.client.create_event({
'host': metric.host,
'service': path,
'time': metric.timestamp,
'metric_f': float(metric.value),
'ttl': metric.ttl,
}) | python | def _metric_to_riemann_event(self, metric):
"""
Convert a metric to a dictionary representing a Riemann event.
"""
# Riemann has a separate "host" field, so remove from the path.
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.getMetricPath()
)
return self.client.create_event({
'host': metric.host,
'service': path,
'time': metric.timestamp,
'metric_f': float(metric.value),
'ttl': metric.ttl,
}) | [
"def",
"_metric_to_riemann_event",
"(",
"self",
",",
"metric",
")",
":",
"# Riemann has a separate \"host\" field, so remove from the path.",
"path",
"=",
"'%s.%s.%s'",
"%",
"(",
"metric",
".",
"getPathPrefix",
"(",
")",
",",
"metric",
".",
"getCollectorPath",
"(",
")... | Convert a metric to a dictionary representing a Riemann event. | [
"Convert",
"a",
"metric",
"to",
"a",
"dictionary",
"representing",
"a",
"Riemann",
"event",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/riemann.py#L94-L111 | train | 217,174 |
python-diamond/Diamond | src/collectors/s3/s3.py | S3BucketCollector.collect | def collect(self):
"""
Collect s3 bucket stats
"""
if boto is None:
self.log.error("Unable to import boto python module")
return {}
for s3instance in self.config['s3']:
self.log.info("S3: byte_unit: %s" % self.config['byte_unit'])
aws_access = self.config['s3'][s3instance]['aws_access_key']
aws_secret = self.config['s3'][s3instance]['aws_secret_key']
for bucket_name in self.config['s3'][s3instance]['buckets']:
bucket = self.getBucket(aws_access, aws_secret, bucket_name)
# collect bucket size
total_size = self.getBucketSize(bucket)
for byte_unit in self.config['byte_unit']:
new_size = diamond.convertor.binary.convert(
value=total_size,
oldUnit='byte',
newUnit=byte_unit
)
self.publish("%s.size.%s" % (bucket_name, byte_unit),
new_size) | python | def collect(self):
"""
Collect s3 bucket stats
"""
if boto is None:
self.log.error("Unable to import boto python module")
return {}
for s3instance in self.config['s3']:
self.log.info("S3: byte_unit: %s" % self.config['byte_unit'])
aws_access = self.config['s3'][s3instance]['aws_access_key']
aws_secret = self.config['s3'][s3instance]['aws_secret_key']
for bucket_name in self.config['s3'][s3instance]['buckets']:
bucket = self.getBucket(aws_access, aws_secret, bucket_name)
# collect bucket size
total_size = self.getBucketSize(bucket)
for byte_unit in self.config['byte_unit']:
new_size = diamond.convertor.binary.convert(
value=total_size,
oldUnit='byte',
newUnit=byte_unit
)
self.publish("%s.size.%s" % (bucket_name, byte_unit),
new_size) | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"boto",
"is",
"None",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Unable to import boto python module\"",
")",
"return",
"{",
"}",
"for",
"s3instance",
"in",
"self",
".",
"config",
"[",
"'s3'",
"]",
":",
... | Collect s3 bucket stats | [
"Collect",
"s3",
"bucket",
"stats"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/s3/s3.py#L51-L74 | train | 217,175 |
python-diamond/Diamond | src/collectors/scribe/scribe.py | ScribeCollector.key_to_metric | def key_to_metric(self, key):
"""Replace all non-letter characters with underscores"""
return ''.join(l if l in string.letters else '_' for l in key) | python | def key_to_metric(self, key):
"""Replace all non-letter characters with underscores"""
return ''.join(l if l in string.letters else '_' for l in key) | [
"def",
"key_to_metric",
"(",
"self",
",",
"key",
")",
":",
"return",
"''",
".",
"join",
"(",
"l",
"if",
"l",
"in",
"string",
".",
"letters",
"else",
"'_'",
"for",
"l",
"in",
"key",
")"
] | Replace all non-letter characters with underscores | [
"Replace",
"all",
"non",
"-",
"letter",
"characters",
"with",
"underscores"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/scribe/scribe.py#L37-L39 | train | 217,176 |
python-diamond/Diamond | src/collectors/ipmisensor/ipmisensor.py | IPMISensorCollector.parse_value | def parse_value(self, value):
"""
Convert value string to float for reporting
"""
value = value.strip()
# Skip missing sensors
if value == 'na':
return None
# Try just getting the float value
try:
return float(value)
except:
pass
# Next best guess is a hex value
try:
return float.fromhex(value)
except:
pass
# No luck, bail
return None | python | def parse_value(self, value):
"""
Convert value string to float for reporting
"""
value = value.strip()
# Skip missing sensors
if value == 'na':
return None
# Try just getting the float value
try:
return float(value)
except:
pass
# Next best guess is a hex value
try:
return float.fromhex(value)
except:
pass
# No luck, bail
return None | [
"def",
"parse_value",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"# Skip missing sensors",
"if",
"value",
"==",
"'na'",
":",
"return",
"None",
"# Try just getting the float value",
"try",
":",
"return",
"float",
"(",
... | Convert value string to float for reporting | [
"Convert",
"value",
"string",
"to",
"float",
"for",
"reporting"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ipmisensor/ipmisensor.py#L51-L74 | train | 217,177 |
python-diamond/Diamond | src/collectors/nagiosperfdata/nagiosperfdata.py | NagiosPerfdataCollector.collect | def collect(self):
"""Collect statistics from a Nagios perfdata directory.
"""
perfdata_dir = self.config['perfdata_dir']
try:
filenames = os.listdir(perfdata_dir)
except OSError:
self.log.error("Cannot read directory `{dir}'".format(
dir=perfdata_dir))
return
for filename in filenames:
self._process_file(os.path.join(perfdata_dir, filename)) | python | def collect(self):
"""Collect statistics from a Nagios perfdata directory.
"""
perfdata_dir = self.config['perfdata_dir']
try:
filenames = os.listdir(perfdata_dir)
except OSError:
self.log.error("Cannot read directory `{dir}'".format(
dir=perfdata_dir))
return
for filename in filenames:
self._process_file(os.path.join(perfdata_dir, filename)) | [
"def",
"collect",
"(",
"self",
")",
":",
"perfdata_dir",
"=",
"self",
".",
"config",
"[",
"'perfdata_dir'",
"]",
"try",
":",
"filenames",
"=",
"os",
".",
"listdir",
"(",
"perfdata_dir",
")",
"except",
"OSError",
":",
"self",
".",
"log",
".",
"error",
"... | Collect statistics from a Nagios perfdata directory. | [
"Collect",
"statistics",
"from",
"a",
"Nagios",
"perfdata",
"directory",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L99-L112 | train | 217,178 |
python-diamond/Diamond | src/collectors/nagiosperfdata/nagiosperfdata.py | NagiosPerfdataCollector._fields_valid | def _fields_valid(self, d):
"""Verify that all necessary fields are present
Determine whether the fields parsed represent a host or
service perfdata. If the perfdata is unknown, return False.
If the perfdata does not contain all fields required for that
type, return False. Otherwise, return True.
"""
if 'DATATYPE' not in d:
return False
datatype = d['DATATYPE']
if datatype == 'HOSTPERFDATA':
fields = self.GENERIC_FIELDS + self.HOST_FIELDS
elif datatype == 'SERVICEPERFDATA':
fields = self.GENERIC_FIELDS + self.SERVICE_FIELDS
else:
return False
for field in fields:
if field not in d:
return False
return True | python | def _fields_valid(self, d):
"""Verify that all necessary fields are present
Determine whether the fields parsed represent a host or
service perfdata. If the perfdata is unknown, return False.
If the perfdata does not contain all fields required for that
type, return False. Otherwise, return True.
"""
if 'DATATYPE' not in d:
return False
datatype = d['DATATYPE']
if datatype == 'HOSTPERFDATA':
fields = self.GENERIC_FIELDS + self.HOST_FIELDS
elif datatype == 'SERVICEPERFDATA':
fields = self.GENERIC_FIELDS + self.SERVICE_FIELDS
else:
return False
for field in fields:
if field not in d:
return False
return True | [
"def",
"_fields_valid",
"(",
"self",
",",
"d",
")",
":",
"if",
"'DATATYPE'",
"not",
"in",
"d",
":",
"return",
"False",
"datatype",
"=",
"d",
"[",
"'DATATYPE'",
"]",
"if",
"datatype",
"==",
"'HOSTPERFDATA'",
":",
"fields",
"=",
"self",
".",
"GENERIC_FIELD... | Verify that all necessary fields are present
Determine whether the fields parsed represent a host or
service perfdata. If the perfdata is unknown, return False.
If the perfdata does not contain all fields required for that
type, return False. Otherwise, return True. | [
"Verify",
"that",
"all",
"necessary",
"fields",
"are",
"present"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L127-L150 | train | 217,179 |
python-diamond/Diamond | src/collectors/nagiosperfdata/nagiosperfdata.py | NagiosPerfdataCollector._normalize_to_unit | def _normalize_to_unit(self, value, unit):
"""Normalize the value to the unit returned.
We use base-1000 for second-based units, and base-1024 for
byte-based units. Sadly, the Nagios-Plugins specification doesn't
disambiguate base-1000 (KB) and base-1024 (KiB).
"""
if unit == 'ms':
return value / 1000.0
if unit == 'us':
return value / 1000000.0
if unit == 'KB':
return value * 1024
if unit == 'MB':
return value * 1024 * 1024
if unit == 'GB':
return value * 1024 * 1024 * 1024
if unit == 'TB':
return value * 1024 * 1024 * 1024 * 1024
return value | python | def _normalize_to_unit(self, value, unit):
"""Normalize the value to the unit returned.
We use base-1000 for second-based units, and base-1024 for
byte-based units. Sadly, the Nagios-Plugins specification doesn't
disambiguate base-1000 (KB) and base-1024 (KiB).
"""
if unit == 'ms':
return value / 1000.0
if unit == 'us':
return value / 1000000.0
if unit == 'KB':
return value * 1024
if unit == 'MB':
return value * 1024 * 1024
if unit == 'GB':
return value * 1024 * 1024 * 1024
if unit == 'TB':
return value * 1024 * 1024 * 1024 * 1024
return value | [
"def",
"_normalize_to_unit",
"(",
"self",
",",
"value",
",",
"unit",
")",
":",
"if",
"unit",
"==",
"'ms'",
":",
"return",
"value",
"/",
"1000.0",
"if",
"unit",
"==",
"'us'",
":",
"return",
"value",
"/",
"1000000.0",
"if",
"unit",
"==",
"'KB'",
":",
"... | Normalize the value to the unit returned.
We use base-1000 for second-based units, and base-1024 for
byte-based units. Sadly, the Nagios-Plugins specification doesn't
disambiguate base-1000 (KB) and base-1024 (KiB). | [
"Normalize",
"the",
"value",
"to",
"the",
"unit",
"returned",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L152-L172 | train | 217,180 |
python-diamond/Diamond | src/collectors/nagiosperfdata/nagiosperfdata.py | NagiosPerfdataCollector._parse_perfdata | def _parse_perfdata(self, s):
"""Parse performance data from a perfdata string
"""
metrics = []
counters = re.findall(self.TOKENIZER_RE, s)
if counters is None:
self.log.warning("Failed to parse performance data: {s}".format(
s=s))
return metrics
for (key, value, uom, warn, crit, min, max) in counters:
try:
norm_value = self._normalize_to_unit(float(value), uom)
metrics.append((key, norm_value))
except ValueError:
self.log.warning(
"Couldn't convert value '{value}' to float".format(
value=value))
return metrics | python | def _parse_perfdata(self, s):
"""Parse performance data from a perfdata string
"""
metrics = []
counters = re.findall(self.TOKENIZER_RE, s)
if counters is None:
self.log.warning("Failed to parse performance data: {s}".format(
s=s))
return metrics
for (key, value, uom, warn, crit, min, max) in counters:
try:
norm_value = self._normalize_to_unit(float(value), uom)
metrics.append((key, norm_value))
except ValueError:
self.log.warning(
"Couldn't convert value '{value}' to float".format(
value=value))
return metrics | [
"def",
"_parse_perfdata",
"(",
"self",
",",
"s",
")",
":",
"metrics",
"=",
"[",
"]",
"counters",
"=",
"re",
".",
"findall",
"(",
"self",
".",
"TOKENIZER_RE",
",",
"s",
")",
"if",
"counters",
"is",
"None",
":",
"self",
".",
"log",
".",
"warning",
"(... | Parse performance data from a perfdata string | [
"Parse",
"performance",
"data",
"from",
"a",
"perfdata",
"string"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L174-L193 | train | 217,181 |
python-diamond/Diamond | src/collectors/nagiosperfdata/nagiosperfdata.py | NagiosPerfdataCollector._process_file | def _process_file(self, path):
"""Parse and submit the metrics from a file
"""
try:
f = open(path)
for line in f:
self._process_line(line)
os.remove(path)
except IOError as ex:
self.log.error("Could not open file `{path}': {error}".format(
path=path, error=ex.strerror)) | python | def _process_file(self, path):
"""Parse and submit the metrics from a file
"""
try:
f = open(path)
for line in f:
self._process_line(line)
os.remove(path)
except IOError as ex:
self.log.error("Could not open file `{path}': {error}".format(
path=path, error=ex.strerror)) | [
"def",
"_process_file",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"path",
")",
"for",
"line",
"in",
"f",
":",
"self",
".",
"_process_line",
"(",
"line",
")",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"IOError",
... | Parse and submit the metrics from a file | [
"Parse",
"and",
"submit",
"the",
"metrics",
"from",
"a",
"file"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L195-L206 | train | 217,182 |
python-diamond/Diamond | src/collectors/nagiosperfdata/nagiosperfdata.py | NagiosPerfdataCollector._process_line | def _process_line(self, line):
"""Parse and submit the metrics from a line of perfdata output
"""
fields = self._extract_fields(line)
if not self._fields_valid(fields):
self.log.warning("Missing required fields for line: {line}".format(
line=line))
metric_path_base = []
graphite_prefix = fields.get('GRAPHITEPREFIX')
graphite_postfix = fields.get('GRAPHITEPOSTFIX')
if graphite_prefix:
metric_path_base.append(graphite_prefix)
hostname = fields['HOSTNAME'].lower()
metric_path_base.append(hostname)
datatype = fields['DATATYPE']
if datatype == 'HOSTPERFDATA':
metric_path_base.append('host')
elif datatype == 'SERVICEPERFDATA':
service_desc = fields.get('SERVICEDESC')
graphite_postfix = fields.get('GRAPHITEPOSTFIX')
if graphite_postfix:
metric_path_base.append(graphite_postfix)
else:
metric_path_base.append(service_desc)
perfdata = fields[datatype]
counters = self._parse_perfdata(perfdata)
for (counter, value) in counters:
metric_path = metric_path_base + [counter]
metric_path = [self._sanitize(x) for x in metric_path]
metric_name = '.'.join(metric_path)
self.publish(metric_name, value) | python | def _process_line(self, line):
"""Parse and submit the metrics from a line of perfdata output
"""
fields = self._extract_fields(line)
if not self._fields_valid(fields):
self.log.warning("Missing required fields for line: {line}".format(
line=line))
metric_path_base = []
graphite_prefix = fields.get('GRAPHITEPREFIX')
graphite_postfix = fields.get('GRAPHITEPOSTFIX')
if graphite_prefix:
metric_path_base.append(graphite_prefix)
hostname = fields['HOSTNAME'].lower()
metric_path_base.append(hostname)
datatype = fields['DATATYPE']
if datatype == 'HOSTPERFDATA':
metric_path_base.append('host')
elif datatype == 'SERVICEPERFDATA':
service_desc = fields.get('SERVICEDESC')
graphite_postfix = fields.get('GRAPHITEPOSTFIX')
if graphite_postfix:
metric_path_base.append(graphite_postfix)
else:
metric_path_base.append(service_desc)
perfdata = fields[datatype]
counters = self._parse_perfdata(perfdata)
for (counter, value) in counters:
metric_path = metric_path_base + [counter]
metric_path = [self._sanitize(x) for x in metric_path]
metric_name = '.'.join(metric_path)
self.publish(metric_name, value) | [
"def",
"_process_line",
"(",
"self",
",",
"line",
")",
":",
"fields",
"=",
"self",
".",
"_extract_fields",
"(",
"line",
")",
"if",
"not",
"self",
".",
"_fields_valid",
"(",
"fields",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"Missing required ... | Parse and submit the metrics from a line of perfdata output | [
"Parse",
"and",
"submit",
"the",
"metrics",
"from",
"a",
"line",
"of",
"perfdata",
"output"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L208-L244 | train | 217,183 |
python-diamond/Diamond | src/diamond/handler/rabbitmq_topic.py | rmqHandler._bind | def _bind(self):
"""
Create socket and bind
"""
credentials = pika.PlainCredentials(self.user, self.password)
params = pika.ConnectionParameters(credentials=credentials,
host=self.server,
virtual_host=self.vhost,
port=self.port)
self.connection = pika.BlockingConnection(params)
self.channel = self.connection.channel()
# NOTE : PIKA version uses 'exchange_type' instead of 'type'
self.channel.exchange_declare(exchange=self.topic_exchange,
exchange_type="topic") | python | def _bind(self):
"""
Create socket and bind
"""
credentials = pika.PlainCredentials(self.user, self.password)
params = pika.ConnectionParameters(credentials=credentials,
host=self.server,
virtual_host=self.vhost,
port=self.port)
self.connection = pika.BlockingConnection(params)
self.channel = self.connection.channel()
# NOTE : PIKA version uses 'exchange_type' instead of 'type'
self.channel.exchange_declare(exchange=self.topic_exchange,
exchange_type="topic") | [
"def",
"_bind",
"(",
"self",
")",
":",
"credentials",
"=",
"pika",
".",
"PlainCredentials",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",
")",
"params",
"=",
"pika",
".",
"ConnectionParameters",
"(",
"credentials",
"=",
"credentials",
",",
"host"... | Create socket and bind | [
"Create",
"socket",
"and",
"bind"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_topic.py#L95-L112 | train | 217,184 |
python-diamond/Diamond | src/diamond/handler/rabbitmq_topic.py | rmqHandler.process | def process(self, metric):
"""
Process a metric and send it to RabbitMQ topic exchange
"""
# Send the data as ......
if not pika:
return
routingKeyDic = {
'metric': lambda: metric.path,
'custom': lambda: self.custom_routing_key,
# These option and the below are really not needed because
# with Rabbitmq you can use regular expressions to indicate
# what routing_keys to subscribe to. But I figure this is
# a good example of how to allow more routing keys
'host': lambda: metric.host,
'metric.path': metric.getMetricPath,
'path.prefix': metric.getPathPrefix,
'collector.path': metric.getCollectorPath,
}
try:
self.channel.basic_publish(
exchange=self.topic_exchange,
routing_key=routingKeyDic[self.routing_key](),
body="%s" % metric)
except Exception: # Rough connection re-try logic.
self.log.info(
"Failed publishing to rabbitMQ. Attempting reconnect")
self._bind() | python | def process(self, metric):
"""
Process a metric and send it to RabbitMQ topic exchange
"""
# Send the data as ......
if not pika:
return
routingKeyDic = {
'metric': lambda: metric.path,
'custom': lambda: self.custom_routing_key,
# These option and the below are really not needed because
# with Rabbitmq you can use regular expressions to indicate
# what routing_keys to subscribe to. But I figure this is
# a good example of how to allow more routing keys
'host': lambda: metric.host,
'metric.path': metric.getMetricPath,
'path.prefix': metric.getPathPrefix,
'collector.path': metric.getCollectorPath,
}
try:
self.channel.basic_publish(
exchange=self.topic_exchange,
routing_key=routingKeyDic[self.routing_key](),
body="%s" % metric)
except Exception: # Rough connection re-try logic.
self.log.info(
"Failed publishing to rabbitMQ. Attempting reconnect")
self._bind() | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"# Send the data as ......",
"if",
"not",
"pika",
":",
"return",
"routingKeyDic",
"=",
"{",
"'metric'",
":",
"lambda",
":",
"metric",
".",
"path",
",",
"'custom'",
":",
"lambda",
":",
"self",
".",
"... | Process a metric and send it to RabbitMQ topic exchange | [
"Process",
"a",
"metric",
"and",
"send",
"it",
"to",
"RabbitMQ",
"topic",
"exchange"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_topic.py#L123-L155 | train | 217,185 |
python-diamond/Diamond | src/collectors/pgq/pgq.py | PgQCollector._collect_for_instance | def _collect_for_instance(self, instance, connection):
"""Collects metrics for a named connection."""
with connection.cursor() as cursor:
for queue, metrics in self.get_queue_info(instance, cursor):
for name, metric in metrics.items():
self.publish('.'.join((instance, queue, name)), metric)
with connection.cursor() as cursor:
consumers = self.get_consumer_info(instance, cursor)
for queue, consumer, metrics in consumers:
for name, metric in metrics.items():
key_parts = (instance, queue, 'consumers', consumer, name)
self.publish('.'.join(key_parts), metric) | python | def _collect_for_instance(self, instance, connection):
"""Collects metrics for a named connection."""
with connection.cursor() as cursor:
for queue, metrics in self.get_queue_info(instance, cursor):
for name, metric in metrics.items():
self.publish('.'.join((instance, queue, name)), metric)
with connection.cursor() as cursor:
consumers = self.get_consumer_info(instance, cursor)
for queue, consumer, metrics in consumers:
for name, metric in metrics.items():
key_parts = (instance, queue, 'consumers', consumer, name)
self.publish('.'.join(key_parts), metric) | [
"def",
"_collect_for_instance",
"(",
"self",
",",
"instance",
",",
"connection",
")",
":",
"with",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"for",
"queue",
",",
"metrics",
"in",
"self",
".",
"get_queue_info",
"(",
"instance",
",",
"curso... | Collects metrics for a named connection. | [
"Collects",
"metrics",
"for",
"a",
"named",
"connection",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/pgq/pgq.py#L62-L74 | train | 217,186 |
python-diamond/Diamond | src/collectors/pgq/pgq.py | PgQCollector.get_queue_info | def get_queue_info(self, instance, cursor):
"""Collects metrics for all queues on the connected database."""
cursor.execute(self.QUEUE_INFO_STATEMENT)
for queue_name, ticker_lag, ev_per_sec in cursor:
yield queue_name, {
'ticker_lag': ticker_lag,
'ev_per_sec': ev_per_sec,
} | python | def get_queue_info(self, instance, cursor):
"""Collects metrics for all queues on the connected database."""
cursor.execute(self.QUEUE_INFO_STATEMENT)
for queue_name, ticker_lag, ev_per_sec in cursor:
yield queue_name, {
'ticker_lag': ticker_lag,
'ev_per_sec': ev_per_sec,
} | [
"def",
"get_queue_info",
"(",
"self",
",",
"instance",
",",
"cursor",
")",
":",
"cursor",
".",
"execute",
"(",
"self",
".",
"QUEUE_INFO_STATEMENT",
")",
"for",
"queue_name",
",",
"ticker_lag",
",",
"ev_per_sec",
"in",
"cursor",
":",
"yield",
"queue_name",
",... | Collects metrics for all queues on the connected database. | [
"Collects",
"metrics",
"for",
"all",
"queues",
"on",
"the",
"connected",
"database",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/pgq/pgq.py#L84-L91 | train | 217,187 |
python-diamond/Diamond | src/collectors/pgq/pgq.py | PgQCollector.get_consumer_info | def get_consumer_info(self, instance, cursor):
"""Collects metrics for all consumers on the connected database."""
cursor.execute(self.CONSUMER_INFO_STATEMENT)
for queue_name, consumer_name, lag, pending_events, last_seen in cursor:
yield queue_name, consumer_name, {
'lag': lag,
'pending_events': pending_events,
'last_seen': last_seen,
} | python | def get_consumer_info(self, instance, cursor):
"""Collects metrics for all consumers on the connected database."""
cursor.execute(self.CONSUMER_INFO_STATEMENT)
for queue_name, consumer_name, lag, pending_events, last_seen in cursor:
yield queue_name, consumer_name, {
'lag': lag,
'pending_events': pending_events,
'last_seen': last_seen,
} | [
"def",
"get_consumer_info",
"(",
"self",
",",
"instance",
",",
"cursor",
")",
":",
"cursor",
".",
"execute",
"(",
"self",
".",
"CONSUMER_INFO_STATEMENT",
")",
"for",
"queue_name",
",",
"consumer_name",
",",
"lag",
",",
"pending_events",
",",
"last_seen",
"in",... | Collects metrics for all consumers on the connected database. | [
"Collects",
"metrics",
"for",
"all",
"consumers",
"on",
"the",
"connected",
"database",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/pgq/pgq.py#L103-L111 | train | 217,188 |
python-diamond/Diamond | src/collectors/mdstat/mdstat.py | MdStatCollector.collect | def collect(self):
"""Publish all mdstat metrics."""
def traverse(d, metric_name=''):
"""
Traverse the given nested dict using depth-first search.
If a value is reached it will be published with a metric name
consisting of the hierarchically concatenated keys
of its branch.
"""
for key, value in d.iteritems():
if isinstance(value, dict):
if metric_name == '':
metric_name_next = key
else:
metric_name_next = metric_name + '.' + key
traverse(value, metric_name_next)
else:
metric_name_finished = metric_name + '.' + key
self.publish_gauge(
name=metric_name_finished,
value=value,
precision=1
)
md_state = self._parse_mdstat()
traverse(md_state, '') | python | def collect(self):
"""Publish all mdstat metrics."""
def traverse(d, metric_name=''):
"""
Traverse the given nested dict using depth-first search.
If a value is reached it will be published with a metric name
consisting of the hierarchically concatenated keys
of its branch.
"""
for key, value in d.iteritems():
if isinstance(value, dict):
if metric_name == '':
metric_name_next = key
else:
metric_name_next = metric_name + '.' + key
traverse(value, metric_name_next)
else:
metric_name_finished = metric_name + '.' + key
self.publish_gauge(
name=metric_name_finished,
value=value,
precision=1
)
md_state = self._parse_mdstat()
traverse(md_state, '') | [
"def",
"collect",
"(",
"self",
")",
":",
"def",
"traverse",
"(",
"d",
",",
"metric_name",
"=",
"''",
")",
":",
"\"\"\"\n Traverse the given nested dict using depth-first search.\n\n If a value is reached it will be published with a metric name\n consi... | Publish all mdstat metrics. | [
"Publish",
"all",
"mdstat",
"metrics",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L70-L97 | train | 217,189 |
python-diamond/Diamond | src/collectors/mdstat/mdstat.py | MdStatCollector._parse_array_member_state | def _parse_array_member_state(self, block):
"""
Parse the state of the the md array members.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_member_state(block)
{
'active': 2,
'faulty': 0,
'spare': 1
}
:return: dictionary of states with according count
:rtype: dict
"""
members = block.split('\n')[0].split(' : ')[1].split(' ')[2:]
device_regexp = re.compile(
'^(?P<member_name>.*)'
'\[(?P<member_role_number>\d*)\]'
'\(?(?P<member_state>[FS])?\)?$'
)
ret = {
'active': 0,
'faulty': 0,
'spare': 0
}
for member in members:
member_dict = device_regexp.match(member).groupdict()
if member_dict['member_state'] == 'S':
ret['spare'] += 1
elif member_dict['member_state'] == 'F':
ret['faulty'] += 1
else:
ret['active'] += 1
return ret | python | def _parse_array_member_state(self, block):
"""
Parse the state of the the md array members.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_member_state(block)
{
'active': 2,
'faulty': 0,
'spare': 1
}
:return: dictionary of states with according count
:rtype: dict
"""
members = block.split('\n')[0].split(' : ')[1].split(' ')[2:]
device_regexp = re.compile(
'^(?P<member_name>.*)'
'\[(?P<member_role_number>\d*)\]'
'\(?(?P<member_state>[FS])?\)?$'
)
ret = {
'active': 0,
'faulty': 0,
'spare': 0
}
for member in members:
member_dict = device_regexp.match(member).groupdict()
if member_dict['member_state'] == 'S':
ret['spare'] += 1
elif member_dict['member_state'] == 'F':
ret['faulty'] += 1
else:
ret['active'] += 1
return ret | [
"def",
"_parse_array_member_state",
"(",
"self",
",",
"block",
")",
":",
"members",
"=",
"block",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
".",
"split",
"(",
"' : '",
")",
"[",
"1",
"]",
".",
"split",
"(",
"' '",
")",
"[",
"2",
":",
"]",
... | Parse the state of the the md array members.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_member_state(block)
{
'active': 2,
'faulty': 0,
'spare': 1
}
:return: dictionary of states with according count
:rtype: dict | [
"Parse",
"the",
"state",
"of",
"the",
"the",
"md",
"array",
"members",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L176-L216 | train | 217,190 |
python-diamond/Diamond | src/collectors/mdstat/mdstat.py | MdStatCollector._parse_array_status | def _parse_array_status(self, block):
"""
Parse the status of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_status(block)
{
'total_members': '2',
'actual_members': '2',
'superblock_version': '1.2',
'blocks': '100171776'
}
:return: dictionary of status information
:rtype: dict
"""
array_status_regexp = re.compile(
'^ *(?P<blocks>\d*) blocks '
'(?:super (?P<superblock_version>\d\.\d) )?'
'(?:level (?P<raid_level>\d), '
'(?P<chunk_size>\d*)k chunk, '
'algorithm (?P<algorithm>\d) )?'
'(?:\[(?P<total_members>\d*)/(?P<actual_members>\d*)\])?'
'(?:(?P<rounding_factor>\d*)k rounding)?.*$'
)
array_status_dict = \
array_status_regexp.match(block.split('\n')[1]).groupdict()
array_status_dict_sanitizied = {}
# convert all non None values to float
for key, value in array_status_dict.iteritems():
if not value:
continue
if key == 'superblock_version':
array_status_dict_sanitizied[key] = float(value)
else:
array_status_dict_sanitizied[key] = int(value)
if 'chunk_size' in array_status_dict_sanitizied:
# convert chunk size from kBytes to Bytes
array_status_dict_sanitizied['chunk_size'] *= 1024
if 'rounding_factor' in array_status_dict_sanitizied:
# convert rounding_factor from kBytes to Bytes
array_status_dict_sanitizied['rounding_factor'] *= 1024
return array_status_dict_sanitizied | python | def _parse_array_status(self, block):
"""
Parse the status of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_status(block)
{
'total_members': '2',
'actual_members': '2',
'superblock_version': '1.2',
'blocks': '100171776'
}
:return: dictionary of status information
:rtype: dict
"""
array_status_regexp = re.compile(
'^ *(?P<blocks>\d*) blocks '
'(?:super (?P<superblock_version>\d\.\d) )?'
'(?:level (?P<raid_level>\d), '
'(?P<chunk_size>\d*)k chunk, '
'algorithm (?P<algorithm>\d) )?'
'(?:\[(?P<total_members>\d*)/(?P<actual_members>\d*)\])?'
'(?:(?P<rounding_factor>\d*)k rounding)?.*$'
)
array_status_dict = \
array_status_regexp.match(block.split('\n')[1]).groupdict()
array_status_dict_sanitizied = {}
# convert all non None values to float
for key, value in array_status_dict.iteritems():
if not value:
continue
if key == 'superblock_version':
array_status_dict_sanitizied[key] = float(value)
else:
array_status_dict_sanitizied[key] = int(value)
if 'chunk_size' in array_status_dict_sanitizied:
# convert chunk size from kBytes to Bytes
array_status_dict_sanitizied['chunk_size'] *= 1024
if 'rounding_factor' in array_status_dict_sanitizied:
# convert rounding_factor from kBytes to Bytes
array_status_dict_sanitizied['rounding_factor'] *= 1024
return array_status_dict_sanitizied | [
"def",
"_parse_array_status",
"(",
"self",
",",
"block",
")",
":",
"array_status_regexp",
"=",
"re",
".",
"compile",
"(",
"'^ *(?P<blocks>\\d*) blocks '",
"'(?:super (?P<superblock_version>\\d\\.\\d) )?'",
"'(?:level (?P<raid_level>\\d), '",
"'(?P<chunk_size>\\d*)k chunk, '",
"'a... | Parse the status of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_status(block)
{
'total_members': '2',
'actual_members': '2',
'superblock_version': '1.2',
'blocks': '100171776'
}
:return: dictionary of status information
:rtype: dict | [
"Parse",
"the",
"status",
"of",
"the",
"md",
"array",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L218-L268 | train | 217,191 |
python-diamond/Diamond | src/collectors/mdstat/mdstat.py | MdStatCollector._parse_array_bitmap | def _parse_array_bitmap(self, block):
"""
Parse the bitmap status of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_bitmap(block)
{
'total_pages': '1',
'allocated_pages': '1',
'page_size': 4096,
'chunk_size': 67108864
}
:return: dictionary of bitmap status information
:rtype: dict
"""
array_bitmap_regexp = re.compile(
'^ *bitmap: (?P<allocated_pages>[0-9]*)/'
'(?P<total_pages>[0-9]*) pages '
'\[(?P<page_size>[0-9]*)KB\], '
'(?P<chunk_size>[0-9]*)KB chunk.*$',
re.MULTILINE
)
regexp_res = array_bitmap_regexp.search(block)
# bitmap is optionally in mdstat
if not regexp_res:
return None
array_bitmap_dict = regexp_res.groupdict()
array_bitmap_dict_sanitizied = {}
# convert all values to int
for key, value in array_bitmap_dict.iteritems():
if not value:
continue
array_bitmap_dict_sanitizied[key] = int(value)
# convert page_size to bytes
array_bitmap_dict_sanitizied['page_size'] *= 1024
# convert chunk_size to bytes
array_bitmap_dict_sanitizied['chunk_size'] *= 1024
return array_bitmap_dict | python | def _parse_array_bitmap(self, block):
"""
Parse the bitmap status of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_bitmap(block)
{
'total_pages': '1',
'allocated_pages': '1',
'page_size': 4096,
'chunk_size': 67108864
}
:return: dictionary of bitmap status information
:rtype: dict
"""
array_bitmap_regexp = re.compile(
'^ *bitmap: (?P<allocated_pages>[0-9]*)/'
'(?P<total_pages>[0-9]*) pages '
'\[(?P<page_size>[0-9]*)KB\], '
'(?P<chunk_size>[0-9]*)KB chunk.*$',
re.MULTILINE
)
regexp_res = array_bitmap_regexp.search(block)
# bitmap is optionally in mdstat
if not regexp_res:
return None
array_bitmap_dict = regexp_res.groupdict()
array_bitmap_dict_sanitizied = {}
# convert all values to int
for key, value in array_bitmap_dict.iteritems():
if not value:
continue
array_bitmap_dict_sanitizied[key] = int(value)
# convert page_size to bytes
array_bitmap_dict_sanitizied['page_size'] *= 1024
# convert chunk_size to bytes
array_bitmap_dict_sanitizied['chunk_size'] *= 1024
return array_bitmap_dict | [
"def",
"_parse_array_bitmap",
"(",
"self",
",",
"block",
")",
":",
"array_bitmap_regexp",
"=",
"re",
".",
"compile",
"(",
"'^ *bitmap: (?P<allocated_pages>[0-9]*)/'",
"'(?P<total_pages>[0-9]*) pages '",
"'\\[(?P<page_size>[0-9]*)KB\\], '",
"'(?P<chunk_size>[0-9]*)KB chunk.*$'",
"... | Parse the bitmap status of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_bitmap(block)
{
'total_pages': '1',
'allocated_pages': '1',
'page_size': 4096,
'chunk_size': 67108864
}
:return: dictionary of bitmap status information
:rtype: dict | [
"Parse",
"the",
"bitmap",
"status",
"of",
"the",
"md",
"array",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L270-L317 | train | 217,192 |
python-diamond/Diamond | src/collectors/mdstat/mdstat.py | MdStatCollector._parse_array_recovery | def _parse_array_recovery(self, block):
"""
Parse the recovery progress of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' [===================>.] recovery = 99.5% '
>>> '(102272/102272) finish=13.37min speed=102272K/sec\n'
>>> '\n'
>>> print _parse_array_recovery(block)
{
'percent': '99.5',
'speed': 104726528,
'remaining_time': 802199
}
:return: dictionary of recovery progress status information
:rtype: dict
"""
array_recovery_regexp = re.compile(
'^ *\[.*\] *recovery = (?P<percent>\d*\.?\d*)%'
' \(\d*/\d*\) finish=(?P<remaining_time>\d*\.?\d*)min '
'speed=(?P<speed>\d*)K/sec$',
re.MULTILINE
)
regexp_res = array_recovery_regexp.search(block)
# recovery is optionally in mdstat
if not regexp_res:
return None
array_recovery_dict = regexp_res.groupdict()
array_recovery_dict['percent'] = \
float(array_recovery_dict['percent'])
# convert speed to bits
array_recovery_dict['speed'] = \
int(array_recovery_dict['speed']) * 1024
# convert minutes to milliseconds
array_recovery_dict['remaining_time'] = \
int(float(array_recovery_dict['remaining_time'])*60*1000)
return array_recovery_dict | python | def _parse_array_recovery(self, block):
"""
Parse the recovery progress of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' [===================>.] recovery = 99.5% '
>>> '(102272/102272) finish=13.37min speed=102272K/sec\n'
>>> '\n'
>>> print _parse_array_recovery(block)
{
'percent': '99.5',
'speed': 104726528,
'remaining_time': 802199
}
:return: dictionary of recovery progress status information
:rtype: dict
"""
array_recovery_regexp = re.compile(
'^ *\[.*\] *recovery = (?P<percent>\d*\.?\d*)%'
' \(\d*/\d*\) finish=(?P<remaining_time>\d*\.?\d*)min '
'speed=(?P<speed>\d*)K/sec$',
re.MULTILINE
)
regexp_res = array_recovery_regexp.search(block)
# recovery is optionally in mdstat
if not regexp_res:
return None
array_recovery_dict = regexp_res.groupdict()
array_recovery_dict['percent'] = \
float(array_recovery_dict['percent'])
# convert speed to bits
array_recovery_dict['speed'] = \
int(array_recovery_dict['speed']) * 1024
# convert minutes to milliseconds
array_recovery_dict['remaining_time'] = \
int(float(array_recovery_dict['remaining_time'])*60*1000)
return array_recovery_dict | [
"def",
"_parse_array_recovery",
"(",
"self",
",",
"block",
")",
":",
"array_recovery_regexp",
"=",
"re",
".",
"compile",
"(",
"'^ *\\[.*\\] *recovery = (?P<percent>\\d*\\.?\\d*)%'",
"' \\(\\d*/\\d*\\) finish=(?P<remaining_time>\\d*\\.?\\d*)min '",
"'speed=(?P<speed>\\d*)K/sec$'",
"... | Parse the recovery progress of the md array.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' [===================>.] recovery = 99.5% '
>>> '(102272/102272) finish=13.37min speed=102272K/sec\n'
>>> '\n'
>>> print _parse_array_recovery(block)
{
'percent': '99.5',
'speed': 104726528,
'remaining_time': 802199
}
:return: dictionary of recovery progress status information
:rtype: dict | [
"Parse",
"the",
"recovery",
"progress",
"of",
"the",
"md",
"array",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L319-L364 | train | 217,193 |
python-diamond/Diamond | src/collectors/passenger_stats/passenger_stats.py | PassengerCollector.get_passenger_memory_stats | def get_passenger_memory_stats(self):
"""
Execute passenger-memory-stats, parse its output, return dictionary with
stats.
"""
command = [self.config["passenger_memory_stats_bin"]]
if str_to_bool(self.config["use_sudo"]):
command.insert(0, self.config["sudo_cmd"])
try:
proc1 = subprocess.Popen(command, stdout=subprocess.PIPE)
(std_out, std_err) = proc1.communicate()
except OSError:
return {}
if std_out is None:
return {}
dict_stats = {
"apache_procs": [],
"nginx_procs": [],
"passenger_procs": [],
"apache_mem_total": 0.0,
"nginx_mem_total": 0.0,
"passenger_mem_total": 0.0,
}
#
re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]")
re_digit = re.compile("^\d")
#
apache_flag = 0
nginx_flag = 0
passenger_flag = 0
for raw_line in std_out.splitlines():
line = re_colour.sub("", raw_line)
if "Apache processes" in line:
apache_flag = 1
elif "Nginx processes" in line:
nginx_flag = 1
elif "Passenger processes" in line:
passenger_flag = 1
elif re_digit.match(line):
# If line starts with digit, then store PID and memory consumed
line_splitted = line.split()
if apache_flag == 1:
dict_stats["apache_procs"].append(line_splitted[0])
dict_stats["apache_mem_total"] += float(line_splitted[4])
elif nginx_flag == 1:
dict_stats["nginx_procs"].append(line_splitted[0])
dict_stats["nginx_mem_total"] += float(line_splitted[4])
elif passenger_flag == 1:
dict_stats["passenger_procs"].append(line_splitted[0])
dict_stats["passenger_mem_total"] += float(line_splitted[3])
elif "Processes:" in line:
passenger_flag = 0
apache_flag = 0
nginx_flag = 0
return dict_stats | python | def get_passenger_memory_stats(self):
"""
Execute passenger-memory-stats, parse its output, return dictionary with
stats.
"""
command = [self.config["passenger_memory_stats_bin"]]
if str_to_bool(self.config["use_sudo"]):
command.insert(0, self.config["sudo_cmd"])
try:
proc1 = subprocess.Popen(command, stdout=subprocess.PIPE)
(std_out, std_err) = proc1.communicate()
except OSError:
return {}
if std_out is None:
return {}
dict_stats = {
"apache_procs": [],
"nginx_procs": [],
"passenger_procs": [],
"apache_mem_total": 0.0,
"nginx_mem_total": 0.0,
"passenger_mem_total": 0.0,
}
#
re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]")
re_digit = re.compile("^\d")
#
apache_flag = 0
nginx_flag = 0
passenger_flag = 0
for raw_line in std_out.splitlines():
line = re_colour.sub("", raw_line)
if "Apache processes" in line:
apache_flag = 1
elif "Nginx processes" in line:
nginx_flag = 1
elif "Passenger processes" in line:
passenger_flag = 1
elif re_digit.match(line):
# If line starts with digit, then store PID and memory consumed
line_splitted = line.split()
if apache_flag == 1:
dict_stats["apache_procs"].append(line_splitted[0])
dict_stats["apache_mem_total"] += float(line_splitted[4])
elif nginx_flag == 1:
dict_stats["nginx_procs"].append(line_splitted[0])
dict_stats["nginx_mem_total"] += float(line_splitted[4])
elif passenger_flag == 1:
dict_stats["passenger_procs"].append(line_splitted[0])
dict_stats["passenger_mem_total"] += float(line_splitted[3])
elif "Processes:" in line:
passenger_flag = 0
apache_flag = 0
nginx_flag = 0
return dict_stats | [
"def",
"get_passenger_memory_stats",
"(",
"self",
")",
":",
"command",
"=",
"[",
"self",
".",
"config",
"[",
"\"passenger_memory_stats_bin\"",
"]",
"]",
"if",
"str_to_bool",
"(",
"self",
".",
"config",
"[",
"\"use_sudo\"",
"]",
")",
":",
"command",
".",
"ins... | Execute passenger-memory-stats, parse its output, return dictionary with
stats. | [
"Execute",
"passenger",
"-",
"memory",
"-",
"stats",
"parse",
"its",
"output",
"return",
"dictionary",
"with",
"stats",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L69-L128 | train | 217,194 |
python-diamond/Diamond | src/collectors/passenger_stats/passenger_stats.py | PassengerCollector.get_passenger_cpu_usage | def get_passenger_cpu_usage(self, dict_stats):
"""
Execute % top; and return STDOUT.
"""
try:
proc1 = subprocess.Popen(
["top", "-b", "-n", "2"],
stdout=subprocess.PIPE)
(std_out, std_err) = proc1.communicate()
except OSError:
return (-1)
re_lspaces = re.compile("^\s*")
re_digit = re.compile("^\d")
overall_cpu = 0
for raw_line in std_out.splitlines():
line = re_lspaces.sub("", raw_line)
if not re_digit.match(line):
continue
line_splitted = line.split()
if line_splitted[0] in dict_stats["apache_procs"]:
overall_cpu += float(line_splitted[8])
elif line_splitted[0] in dict_stats["nginx_procs"]:
overall_cpu += float(line_splitted[8])
elif line_splitted[0] in dict_stats["passenger_procs"]:
overall_cpu += float(line_splitted[8])
return overall_cpu | python | def get_passenger_cpu_usage(self, dict_stats):
"""
Execute % top; and return STDOUT.
"""
try:
proc1 = subprocess.Popen(
["top", "-b", "-n", "2"],
stdout=subprocess.PIPE)
(std_out, std_err) = proc1.communicate()
except OSError:
return (-1)
re_lspaces = re.compile("^\s*")
re_digit = re.compile("^\d")
overall_cpu = 0
for raw_line in std_out.splitlines():
line = re_lspaces.sub("", raw_line)
if not re_digit.match(line):
continue
line_splitted = line.split()
if line_splitted[0] in dict_stats["apache_procs"]:
overall_cpu += float(line_splitted[8])
elif line_splitted[0] in dict_stats["nginx_procs"]:
overall_cpu += float(line_splitted[8])
elif line_splitted[0] in dict_stats["passenger_procs"]:
overall_cpu += float(line_splitted[8])
return overall_cpu | [
"def",
"get_passenger_cpu_usage",
"(",
"self",
",",
"dict_stats",
")",
":",
"try",
":",
"proc1",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"top\"",
",",
"\"-b\"",
",",
"\"-n\"",
",",
"\"2\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
... | Execute % top; and return STDOUT. | [
"Execute",
"%",
"top",
";",
"and",
"return",
"STDOUT",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L130-L158 | train | 217,195 |
python-diamond/Diamond | src/collectors/passenger_stats/passenger_stats.py | PassengerCollector.get_passenger_queue_stats | def get_passenger_queue_stats(self):
"""
Execute passenger-stats, parse its output, returnand requests in queue
"""
queue_stats = {
"top_level_queue_size": 0.0,
"passenger_queue_size": 0.0,
}
command = [self.config["passenger_status_bin"]]
if str_to_bool(self.config["use_sudo"]):
command.insert(0, self.config["sudo_cmd"])
try:
proc1 = subprocess.Popen(command, stdout=subprocess.PIPE)
(std_out, std_err) = proc1.communicate()
except OSError:
return {}
if std_out is None:
return {}
re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]")
re_requests = re.compile(r"Requests")
re_topqueue = re.compile(r"^top-level")
gen_info_flag = 0
app_groups_flag = 0
for raw_line in std_out.splitlines():
line = re_colour.sub("", raw_line)
if "General information" in line:
gen_info_flag = 1
if "Application groups" in line:
app_groups_flag = 1
elif re_requests.match(line) and re_topqueue.search(line):
# If line starts with Requests and line has top-level queue then
# store queue size
line_splitted = line.split()
if gen_info_flag == 1 and line_splitted:
queue_stats["top_level_queue_size"] = float(
line_splitted[5])
elif re_requests.search(line) and not re_topqueue.search(line):
# If line has Requests and nothing else special
line_splitted = line.split()
if app_groups_flag == 1 and line_splitted:
queue_stats["passenger_queue_size"] = float(
line_splitted[3])
return queue_stats | python | def get_passenger_queue_stats(self):
"""
Execute passenger-stats, parse its output, returnand requests in queue
"""
queue_stats = {
"top_level_queue_size": 0.0,
"passenger_queue_size": 0.0,
}
command = [self.config["passenger_status_bin"]]
if str_to_bool(self.config["use_sudo"]):
command.insert(0, self.config["sudo_cmd"])
try:
proc1 = subprocess.Popen(command, stdout=subprocess.PIPE)
(std_out, std_err) = proc1.communicate()
except OSError:
return {}
if std_out is None:
return {}
re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]")
re_requests = re.compile(r"Requests")
re_topqueue = re.compile(r"^top-level")
gen_info_flag = 0
app_groups_flag = 0
for raw_line in std_out.splitlines():
line = re_colour.sub("", raw_line)
if "General information" in line:
gen_info_flag = 1
if "Application groups" in line:
app_groups_flag = 1
elif re_requests.match(line) and re_topqueue.search(line):
# If line starts with Requests and line has top-level queue then
# store queue size
line_splitted = line.split()
if gen_info_flag == 1 and line_splitted:
queue_stats["top_level_queue_size"] = float(
line_splitted[5])
elif re_requests.search(line) and not re_topqueue.search(line):
# If line has Requests and nothing else special
line_splitted = line.split()
if app_groups_flag == 1 and line_splitted:
queue_stats["passenger_queue_size"] = float(
line_splitted[3])
return queue_stats | [
"def",
"get_passenger_queue_stats",
"(",
"self",
")",
":",
"queue_stats",
"=",
"{",
"\"top_level_queue_size\"",
":",
"0.0",
",",
"\"passenger_queue_size\"",
":",
"0.0",
",",
"}",
"command",
"=",
"[",
"self",
".",
"config",
"[",
"\"passenger_status_bin\"",
"]",
"... | Execute passenger-stats, parse its output, returnand requests in queue | [
"Execute",
"passenger",
"-",
"stats",
"parse",
"its",
"output",
"returnand",
"requests",
"in",
"queue"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L160-L209 | train | 217,196 |
python-diamond/Diamond | src/collectors/passenger_stats/passenger_stats.py | PassengerCollector.collect | def collect(self):
"""
Collector Passenger stats
"""
if not os.access(self.config["bin"], os.X_OK):
self.log.error("Path %s does not exist or is not executable",
self.config["bin"])
return {}
dict_stats = self.get_passenger_memory_stats()
if len(dict_stats.keys()) == 0:
return {}
queue_stats = self.get_passenger_queue_stats()
if len(queue_stats.keys()) == 0:
return {}
overall_cpu = self.get_passenger_cpu_usage(dict_stats)
if overall_cpu >= 0:
self.publish("phusion_passenger_cpu", overall_cpu)
self.publish("total_passenger_procs", len(
dict_stats["passenger_procs"]))
self.publish("total_nginx_procs", len(dict_stats["nginx_procs"]))
self.publish("total_apache_procs", len(dict_stats["apache_procs"]))
self.publish("total_apache_memory", dict_stats["apache_mem_total"])
self.publish("total_nginx_memory", dict_stats["nginx_mem_total"])
self.publish("total_passenger_memory",
dict_stats["passenger_mem_total"])
self.publish("top_level_queue_size", queue_stats[
"top_level_queue_size"])
self.publish("passenger_queue_size", queue_stats[
"passenger_queue_size"]) | python | def collect(self):
"""
Collector Passenger stats
"""
if not os.access(self.config["bin"], os.X_OK):
self.log.error("Path %s does not exist or is not executable",
self.config["bin"])
return {}
dict_stats = self.get_passenger_memory_stats()
if len(dict_stats.keys()) == 0:
return {}
queue_stats = self.get_passenger_queue_stats()
if len(queue_stats.keys()) == 0:
return {}
overall_cpu = self.get_passenger_cpu_usage(dict_stats)
if overall_cpu >= 0:
self.publish("phusion_passenger_cpu", overall_cpu)
self.publish("total_passenger_procs", len(
dict_stats["passenger_procs"]))
self.publish("total_nginx_procs", len(dict_stats["nginx_procs"]))
self.publish("total_apache_procs", len(dict_stats["apache_procs"]))
self.publish("total_apache_memory", dict_stats["apache_mem_total"])
self.publish("total_nginx_memory", dict_stats["nginx_mem_total"])
self.publish("total_passenger_memory",
dict_stats["passenger_mem_total"])
self.publish("top_level_queue_size", queue_stats[
"top_level_queue_size"])
self.publish("passenger_queue_size", queue_stats[
"passenger_queue_size"]) | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"self",
".",
"config",
"[",
"\"bin\"",
"]",
",",
"os",
".",
"X_OK",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Path %s does not exist or is not executable\"",
",",
... | Collector Passenger stats | [
"Collector",
"Passenger",
"stats"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L211-L243 | train | 217,197 |
python-diamond/Diamond | src/collectors/haproxy/haproxy.py | HAProxyCollector._collect | def _collect(self, section=None):
"""
Collect HAProxy Stats
"""
if self.config['method'] == 'http':
csv_data = self.http_get_csv_data(section)
elif self.config['method'] == 'unix':
csv_data = self.unix_get_csv_data()
else:
self.log.error("Unknown collection method: %s",
self.config['method'])
csv_data = []
data = list(csv.reader(csv_data))
headings = self._generate_headings(data[0])
section_name = section and self._sanitize(section.lower()) + '.' or ''
for row in data:
if ((self._get_config_value(section, 'ignore_servers') and
row[1].lower() not in ['frontend', 'backend'])):
continue
part_one = self._sanitize(row[0].lower())
part_two = self._sanitize(row[1].lower())
metric_name = '%s%s.%s' % (section_name, part_one, part_two)
for index, metric_string in enumerate(row):
try:
metric_value = float(metric_string)
except ValueError:
continue
stat_name = '%s.%s' % (metric_name, headings[index])
self.publish(stat_name, metric_value, metric_type='GAUGE') | python | def _collect(self, section=None):
"""
Collect HAProxy Stats
"""
if self.config['method'] == 'http':
csv_data = self.http_get_csv_data(section)
elif self.config['method'] == 'unix':
csv_data = self.unix_get_csv_data()
else:
self.log.error("Unknown collection method: %s",
self.config['method'])
csv_data = []
data = list(csv.reader(csv_data))
headings = self._generate_headings(data[0])
section_name = section and self._sanitize(section.lower()) + '.' or ''
for row in data:
if ((self._get_config_value(section, 'ignore_servers') and
row[1].lower() not in ['frontend', 'backend'])):
continue
part_one = self._sanitize(row[0].lower())
part_two = self._sanitize(row[1].lower())
metric_name = '%s%s.%s' % (section_name, part_one, part_two)
for index, metric_string in enumerate(row):
try:
metric_value = float(metric_string)
except ValueError:
continue
stat_name = '%s.%s' % (metric_name, headings[index])
self.publish(stat_name, metric_value, metric_type='GAUGE') | [
"def",
"_collect",
"(",
"self",
",",
"section",
"=",
"None",
")",
":",
"if",
"self",
".",
"config",
"[",
"'method'",
"]",
"==",
"'http'",
":",
"csv_data",
"=",
"self",
".",
"http_get_csv_data",
"(",
"section",
")",
"elif",
"self",
".",
"config",
"[",
... | Collect HAProxy Stats | [
"Collect",
"HAProxy",
"Stats"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/haproxy/haproxy.py#L137-L170 | train | 217,198 |
python-diamond/Diamond | src/collectors/processresources/processresources.py | match_process | def match_process(pid, name, cmdline, exe, cfg):
"""
Decides whether a process matches with a given process descriptor
:param pid: process pid
:param exe: process executable
:param name: process name
:param cmdline: process cmdline
:param cfg: the dictionary from processes that describes with the
process group we're testing for
:return: True if it matches
:rtype: bool
"""
if cfg['selfmon'] and pid == os.getpid():
return True
for exe_re in cfg['exe']:
if exe_re.search(exe):
return True
for name_re in cfg['name']:
if name_re.search(name):
return True
for cmdline_re in cfg['cmdline']:
if cmdline_re.search(' '.join(cmdline)):
return True
return False | python | def match_process(pid, name, cmdline, exe, cfg):
"""
Decides whether a process matches with a given process descriptor
:param pid: process pid
:param exe: process executable
:param name: process name
:param cmdline: process cmdline
:param cfg: the dictionary from processes that describes with the
process group we're testing for
:return: True if it matches
:rtype: bool
"""
if cfg['selfmon'] and pid == os.getpid():
return True
for exe_re in cfg['exe']:
if exe_re.search(exe):
return True
for name_re in cfg['name']:
if name_re.search(name):
return True
for cmdline_re in cfg['cmdline']:
if cmdline_re.search(' '.join(cmdline)):
return True
return False | [
"def",
"match_process",
"(",
"pid",
",",
"name",
",",
"cmdline",
",",
"exe",
",",
"cfg",
")",
":",
"if",
"cfg",
"[",
"'selfmon'",
"]",
"and",
"pid",
"==",
"os",
".",
"getpid",
"(",
")",
":",
"return",
"True",
"for",
"exe_re",
"in",
"cfg",
"[",
"'... | Decides whether a process matches with a given process descriptor
:param pid: process pid
:param exe: process executable
:param name: process name
:param cmdline: process cmdline
:param cfg: the dictionary from processes that describes with the
process group we're testing for
:return: True if it matches
:rtype: bool | [
"Decides",
"whether",
"a",
"process",
"matches",
"with",
"a",
"given",
"process",
"descriptor"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/processresources/processresources.py#L49-L73 | train | 217,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.