partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | BatchClient.unit_client | Return a client with same settings of the batch client | statsdmetrics/client/__init__.py | def unit_client(self):
# type: () -> Client
"""Return a client with same settings of the batch client"""
client = Client(self.host, self.port, self.prefix)
self._configure_client(client)
return client | def unit_client(self):
# type: () -> Client
"""Return a client with same settings of the batch client"""
client = Client(self.host, self.port, self.prefix)
self._configure_client(client)
return client | [
"Return",
"a",
"client",
"with",
"same",
"settings",
"of",
"the",
"batch",
"client"
] | farzadghanei/statsd-metrics | python | https://github.com/farzadghanei/statsd-metrics/blob/153ff37b79777f208e49bb9d3fb737ba52b99f98/statsdmetrics/client/__init__.py#L352-L358 | [
"def",
"unit_client",
"(",
"self",
")",
":",
"# type: () -> Client",
"client",
"=",
"Client",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"self",
".",
"prefix",
")",
"self",
".",
"_configure_client",
"(",
"client",
")",
"return",
"client"
] | 153ff37b79777f208e49bb9d3fb737ba52b99f98 |
test | BatchClient.flush | Send buffered metrics in batch requests | statsdmetrics/client/__init__.py | def flush(self):
# type: () -> BatchClient
"""Send buffered metrics in batch requests"""
address = self.remote_address
while len(self._batches) > 0:
self._socket.sendto(self._batches[0], address)
self._batches.popleft()
return self | def flush(self):
# type: () -> BatchClient
"""Send buffered metrics in batch requests"""
address = self.remote_address
while len(self._batches) > 0:
self._socket.sendto(self._batches[0], address)
self._batches.popleft()
return self | [
"Send",
"buffered",
"metrics",
"in",
"batch",
"requests"
] | farzadghanei/statsd-metrics | python | https://github.com/farzadghanei/statsd-metrics/blob/153ff37b79777f208e49bb9d3fb737ba52b99f98/statsdmetrics/client/__init__.py#L360-L368 | [
"def",
"flush",
"(",
"self",
")",
":",
"# type: () -> BatchClient",
"address",
"=",
"self",
".",
"remote_address",
"while",
"len",
"(",
"self",
".",
"_batches",
")",
">",
"0",
":",
"self",
".",
"_socket",
".",
"sendto",
"(",
"self",
".",
"_batches",
"[",
"0",
"]",
",",
"address",
")",
"self",
".",
"_batches",
".",
"popleft",
"(",
")",
"return",
"self"
] | 153ff37b79777f208e49bb9d3fb737ba52b99f98 |
test | my_permission_factory | My permission factory. | examples/permsapp.py | def my_permission_factory(record, *args, **kwargs):
"""My permission factory."""
def can(self):
rec = Record.get_record(record.id)
return rec.get('access', '') == 'open'
return type('MyPermissionChecker', (), {'can': can})() | def my_permission_factory(record, *args, **kwargs):
"""My permission factory."""
def can(self):
rec = Record.get_record(record.id)
return rec.get('access', '') == 'open'
return type('MyPermissionChecker', (), {'can': can})() | [
"My",
"permission",
"factory",
"."
] | inveniosoftware/invenio-records-ui | python | https://github.com/inveniosoftware/invenio-records-ui/blob/ae92367978f2e1e96634685bd296f0fd92b4da54/examples/permsapp.py#L66-L71 | [
"def",
"my_permission_factory",
"(",
"record",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"can",
"(",
"self",
")",
":",
"rec",
"=",
"Record",
".",
"get_record",
"(",
"record",
".",
"id",
")",
"return",
"rec",
".",
"get",
"(",
"'access'",
",",
"''",
")",
"==",
"'open'",
"return",
"type",
"(",
"'MyPermissionChecker'",
",",
"(",
")",
",",
"{",
"'can'",
":",
"can",
"}",
")",
"(",
")"
] | ae92367978f2e1e96634685bd296f0fd92b4da54 |
test | TCPClient.batch_client | Return a TCP batch client with same settings of the TCP client | statsdmetrics/client/tcp.py | def batch_client(self, size=512):
# type: (int) -> TCPBatchClient
"""Return a TCP batch client with same settings of the TCP client"""
batch_client = TCPBatchClient(self.host, self.port, self.prefix, size)
self._configure_client(batch_client)
return batch_client | def batch_client(self, size=512):
# type: (int) -> TCPBatchClient
"""Return a TCP batch client with same settings of the TCP client"""
batch_client = TCPBatchClient(self.host, self.port, self.prefix, size)
self._configure_client(batch_client)
return batch_client | [
"Return",
"a",
"TCP",
"batch",
"client",
"with",
"same",
"settings",
"of",
"the",
"TCP",
"client"
] | farzadghanei/statsd-metrics | python | https://github.com/farzadghanei/statsd-metrics/blob/153ff37b79777f208e49bb9d3fb737ba52b99f98/statsdmetrics/client/tcp.py#L34-L40 | [
"def",
"batch_client",
"(",
"self",
",",
"size",
"=",
"512",
")",
":",
"# type: (int) -> TCPBatchClient",
"batch_client",
"=",
"TCPBatchClient",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"self",
".",
"prefix",
",",
"size",
")",
"self",
".",
"_configure_client",
"(",
"batch_client",
")",
"return",
"batch_client"
] | 153ff37b79777f208e49bb9d3fb737ba52b99f98 |
test | TCPBatchClient.flush | Send buffered metrics in batch requests over TCP | statsdmetrics/client/tcp.py | def flush(self):
"""Send buffered metrics in batch requests over TCP"""
# type: () -> TCPBatchClient
while len(self._batches) > 0:
self._socket.sendall(self._batches[0])
self._batches.popleft()
return self | def flush(self):
"""Send buffered metrics in batch requests over TCP"""
# type: () -> TCPBatchClient
while len(self._batches) > 0:
self._socket.sendall(self._batches[0])
self._batches.popleft()
return self | [
"Send",
"buffered",
"metrics",
"in",
"batch",
"requests",
"over",
"TCP"
] | farzadghanei/statsd-metrics | python | https://github.com/farzadghanei/statsd-metrics/blob/153ff37b79777f208e49bb9d3fb737ba52b99f98/statsdmetrics/client/tcp.py#L65-L71 | [
"def",
"flush",
"(",
"self",
")",
":",
"# type: () -> TCPBatchClient",
"while",
"len",
"(",
"self",
".",
"_batches",
")",
">",
"0",
":",
"self",
".",
"_socket",
".",
"sendall",
"(",
"self",
".",
"_batches",
"[",
"0",
"]",
")",
"self",
".",
"_batches",
".",
"popleft",
"(",
")",
"return",
"self"
] | 153ff37b79777f208e49bb9d3fb737ba52b99f98 |
test | TCPBatchClient.unit_client | Return a TCPClient with same settings of the batch TCP client | statsdmetrics/client/tcp.py | def unit_client(self):
# type: () -> TCPClient
"""Return a TCPClient with same settings of the batch TCP client"""
client = TCPClient(self.host, self.port, self.prefix)
self._configure_client(client)
return client | def unit_client(self):
# type: () -> TCPClient
"""Return a TCPClient with same settings of the batch TCP client"""
client = TCPClient(self.host, self.port, self.prefix)
self._configure_client(client)
return client | [
"Return",
"a",
"TCPClient",
"with",
"same",
"settings",
"of",
"the",
"batch",
"TCP",
"client"
] | farzadghanei/statsd-metrics | python | https://github.com/farzadghanei/statsd-metrics/blob/153ff37b79777f208e49bb9d3fb737ba52b99f98/statsdmetrics/client/tcp.py#L73-L79 | [
"def",
"unit_client",
"(",
"self",
")",
":",
"# type: () -> TCPClient",
"client",
"=",
"TCPClient",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"self",
".",
"prefix",
")",
"self",
".",
"_configure_client",
"(",
"client",
")",
"return",
"client"
] | 153ff37b79777f208e49bb9d3fb737ba52b99f98 |
test | weighted_choice | Supposes that choices is sequence of two elements items,
where first one is the probability and second is the
result object or callable
>>> result = weighted_choice([(20,'x'), (100, 'y')])
>>> result in ['x', 'y']
True | django_any/xunit.py | def weighted_choice(choices):
"""
Supposes that choices is sequence of two elements items,
where first one is the probability and second is the
result object or callable
>>> result = weighted_choice([(20,'x'), (100, 'y')])
>>> result in ['x', 'y']
True
"""
total = sum([weight for (weight, _) in choices])
i = random.randint(0, total - 1)
for weight, choice in choices:
i -= weight
if i < 0:
if callable(choice):
return choice()
return choice
raise Exception('Bug') | def weighted_choice(choices):
"""
Supposes that choices is sequence of two elements items,
where first one is the probability and second is the
result object or callable
>>> result = weighted_choice([(20,'x'), (100, 'y')])
>>> result in ['x', 'y']
True
"""
total = sum([weight for (weight, _) in choices])
i = random.randint(0, total - 1)
for weight, choice in choices:
i -= weight
if i < 0:
if callable(choice):
return choice()
return choice
raise Exception('Bug') | [
"Supposes",
"that",
"choices",
"is",
"sequence",
"of",
"two",
"elements",
"items",
"where",
"first",
"one",
"is",
"the",
"probability",
"and",
"second",
"is",
"the",
"result",
"object",
"or",
"callable",
">>>",
"result",
"=",
"weighted_choice",
"(",
"[",
"(",
"20",
"x",
")",
"(",
"100",
"y",
")",
"]",
")",
">>>",
"result",
"in",
"[",
"x",
"y",
"]",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/xunit.py#L10-L28 | [
"def",
"weighted_choice",
"(",
"choices",
")",
":",
"total",
"=",
"sum",
"(",
"[",
"weight",
"for",
"(",
"weight",
",",
"_",
")",
"in",
"choices",
"]",
")",
"i",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"total",
"-",
"1",
")",
"for",
"weight",
",",
"choice",
"in",
"choices",
":",
"i",
"-=",
"weight",
"if",
"i",
"<",
"0",
":",
"if",
"callable",
"(",
"choice",
")",
":",
"return",
"choice",
"(",
")",
"return",
"choice",
"raise",
"Exception",
"(",
"'Bug'",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_float | Returns random float
>>> result = any_float(min_value=0, max_value=100, precision=2)
>>> type(result)
<type 'float'>
>>> result >=0 and result <= 100
True | django_any/xunit.py | def any_float(min_value=0, max_value=100, precision=2):
"""
Returns random float
>>> result = any_float(min_value=0, max_value=100, precision=2)
>>> type(result)
<type 'float'>
>>> result >=0 and result <= 100
True
"""
return round(random.uniform(min_value, max_value), precision) | def any_float(min_value=0, max_value=100, precision=2):
"""
Returns random float
>>> result = any_float(min_value=0, max_value=100, precision=2)
>>> type(result)
<type 'float'>
>>> result >=0 and result <= 100
True
"""
return round(random.uniform(min_value, max_value), precision) | [
"Returns",
"random",
"float",
">>>",
"result",
"=",
"any_float",
"(",
"min_value",
"=",
"0",
"max_value",
"=",
"100",
"precision",
"=",
"2",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"float",
">",
">>>",
"result",
">",
"=",
"0",
"and",
"result",
"<",
"=",
"100",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/xunit.py#L56-L67 | [
"def",
"any_float",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"100",
",",
"precision",
"=",
"2",
")",
":",
"return",
"round",
"(",
"random",
".",
"uniform",
"(",
"min_value",
",",
"max_value",
")",
",",
"precision",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_string | Return string with random content
>>> result = any_string(letters = ascii_letters, min_length=3, max_length=100)
>>> type(result)
<type 'str'>
>>> len(result) in range(3,101)
True
>>> any([c in ascii_letters for c in result])
True | django_any/xunit.py | def any_string(letters = ascii_letters, min_length=3, max_length=100):
"""
Return string with random content
>>> result = any_string(letters = ascii_letters, min_length=3, max_length=100)
>>> type(result)
<type 'str'>
>>> len(result) in range(3,101)
True
>>> any([c in ascii_letters for c in result])
True
"""
length = random.randint(min_length, max_length)
letters = [any_letter(letters=letters) for _ in range(0, length)]
return "".join(letters) | def any_string(letters = ascii_letters, min_length=3, max_length=100):
"""
Return string with random content
>>> result = any_string(letters = ascii_letters, min_length=3, max_length=100)
>>> type(result)
<type 'str'>
>>> len(result) in range(3,101)
True
>>> any([c in ascii_letters for c in result])
True
"""
length = random.randint(min_length, max_length)
letters = [any_letter(letters=letters) for _ in range(0, length)]
return "".join(letters) | [
"Return",
"string",
"with",
"random",
"content",
">>>",
"result",
"=",
"any_string",
"(",
"letters",
"=",
"ascii_letters",
"min_length",
"=",
"3",
"max_length",
"=",
"100",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">",
">>>",
"len",
"(",
"result",
")",
"in",
"range",
"(",
"3",
"101",
")",
"True",
">>>",
"any",
"(",
"[",
"c",
"in",
"ascii_letters",
"for",
"c",
"in",
"result",
"]",
")",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/xunit.py#L86-L101 | [
"def",
"any_string",
"(",
"letters",
"=",
"ascii_letters",
",",
"min_length",
"=",
"3",
",",
"max_length",
"=",
"100",
")",
":",
"length",
"=",
"random",
".",
"randint",
"(",
"min_length",
",",
"max_length",
")",
"letters",
"=",
"[",
"any_letter",
"(",
"letters",
"=",
"letters",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"length",
")",
"]",
"return",
"\"\"",
".",
"join",
"(",
"letters",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_date | Return random date from the [from_date, to_date] interval
>>> result = any_date(from_date=date(1990,1,1), to_date=date(1990,1,3))
>>> type(result)
<type 'datetime.date'>
>>> result >= date(1990,1,1) and result <= date(1990,1,3)
True | django_any/xunit.py | def any_date(from_date=date(1990, 1, 1), to_date=date.today()):
"""
Return random date from the [from_date, to_date] interval
>>> result = any_date(from_date=date(1990,1,1), to_date=date(1990,1,3))
>>> type(result)
<type 'datetime.date'>
>>> result >= date(1990,1,1) and result <= date(1990,1,3)
True
"""
days = any_int(min_value=0, max_value=(to_date - from_date).days)
return from_date + timedelta(days=days) | def any_date(from_date=date(1990, 1, 1), to_date=date.today()):
"""
Return random date from the [from_date, to_date] interval
>>> result = any_date(from_date=date(1990,1,1), to_date=date(1990,1,3))
>>> type(result)
<type 'datetime.date'>
>>> result >= date(1990,1,1) and result <= date(1990,1,3)
True
"""
days = any_int(min_value=0, max_value=(to_date - from_date).days)
return from_date + timedelta(days=days) | [
"Return",
"random",
"date",
"from",
"the",
"[",
"from_date",
"to_date",
"]",
"interval",
">>>",
"result",
"=",
"any_date",
"(",
"from_date",
"=",
"date",
"(",
"1990",
"1",
"1",
")",
"to_date",
"=",
"date",
"(",
"1990",
"1",
"3",
"))",
">>>",
"type",
"(",
"result",
")",
"<type",
"datetime",
".",
"date",
">",
">>>",
"result",
">",
"=",
"date",
"(",
"1990",
"1",
"1",
")",
"and",
"result",
"<",
"=",
"date",
"(",
"1990",
"1",
"3",
")",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/xunit.py#L104-L116 | [
"def",
"any_date",
"(",
"from_date",
"=",
"date",
"(",
"1990",
",",
"1",
",",
"1",
")",
",",
"to_date",
"=",
"date",
".",
"today",
"(",
")",
")",
":",
"days",
"=",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"(",
"to_date",
"-",
"from_date",
")",
".",
"days",
")",
"return",
"from_date",
"+",
"timedelta",
"(",
"days",
"=",
"days",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_datetime | Return random datetime from the [from_date, to_date] interval
>>> result = any_datetime(from_date=datetime(1990,1,1), to_date=datetime(1990,1,3))
>>> type(result)
<type 'datetime.datetime'>
>>> result >= datetime(1990,1,1) and result <= datetime(1990,1,3)
True | django_any/xunit.py | def any_datetime(from_date=datetime(1990, 1, 1), to_date=datetime.now()):
"""
Return random datetime from the [from_date, to_date] interval
>>> result = any_datetime(from_date=datetime(1990,1,1), to_date=datetime(1990,1,3))
>>> type(result)
<type 'datetime.datetime'>
>>> result >= datetime(1990,1,1) and result <= datetime(1990,1,3)
True
"""
days = any_int(min_value=0, max_value=(to_date - from_date).days-1)
time = timedelta(seconds=any_int(min_value=0, max_value=24*3600-1))
return from_date + timedelta(days=days) + time | def any_datetime(from_date=datetime(1990, 1, 1), to_date=datetime.now()):
"""
Return random datetime from the [from_date, to_date] interval
>>> result = any_datetime(from_date=datetime(1990,1,1), to_date=datetime(1990,1,3))
>>> type(result)
<type 'datetime.datetime'>
>>> result >= datetime(1990,1,1) and result <= datetime(1990,1,3)
True
"""
days = any_int(min_value=0, max_value=(to_date - from_date).days-1)
time = timedelta(seconds=any_int(min_value=0, max_value=24*3600-1))
return from_date + timedelta(days=days) + time | [
"Return",
"random",
"datetime",
"from",
"the",
"[",
"from_date",
"to_date",
"]",
"interval",
">>>",
"result",
"=",
"any_datetime",
"(",
"from_date",
"=",
"datetime",
"(",
"1990",
"1",
"1",
")",
"to_date",
"=",
"datetime",
"(",
"1990",
"1",
"3",
"))",
">>>",
"type",
"(",
"result",
")",
"<type",
"datetime",
".",
"datetime",
">",
">>>",
"result",
">",
"=",
"datetime",
"(",
"1990",
"1",
"1",
")",
"and",
"result",
"<",
"=",
"datetime",
"(",
"1990",
"1",
"3",
")",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/xunit.py#L119-L132 | [
"def",
"any_datetime",
"(",
"from_date",
"=",
"datetime",
"(",
"1990",
",",
"1",
",",
"1",
")",
",",
"to_date",
"=",
"datetime",
".",
"now",
"(",
")",
")",
":",
"days",
"=",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"(",
"to_date",
"-",
"from_date",
")",
".",
"days",
"-",
"1",
")",
"time",
"=",
"timedelta",
"(",
"seconds",
"=",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"24",
"*",
"3600",
"-",
"1",
")",
")",
"return",
"from_date",
"+",
"timedelta",
"(",
"days",
"=",
"days",
")",
"+",
"time"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_decimal | Return random decimal from the [min_value, max_value] interval
>>> result = any_decimal(min_value=0.999, max_value=3, decimal_places=3)
>>> type(result)
<class 'decimal.Decimal'>
>>> result >= Decimal('0.999') and result <= Decimal(3)
True | django_any/xunit.py | def any_decimal(min_value=Decimal(0), max_value=Decimal('99.99'), decimal_places=2):
"""
Return random decimal from the [min_value, max_value] interval
>>> result = any_decimal(min_value=0.999, max_value=3, decimal_places=3)
>>> type(result)
<class 'decimal.Decimal'>
>>> result >= Decimal('0.999') and result <= Decimal(3)
True
"""
return Decimal(str(any_float(min_value=float(min_value),
max_value=float(max_value),
precision=decimal_places))) | def any_decimal(min_value=Decimal(0), max_value=Decimal('99.99'), decimal_places=2):
"""
Return random decimal from the [min_value, max_value] interval
>>> result = any_decimal(min_value=0.999, max_value=3, decimal_places=3)
>>> type(result)
<class 'decimal.Decimal'>
>>> result >= Decimal('0.999') and result <= Decimal(3)
True
"""
return Decimal(str(any_float(min_value=float(min_value),
max_value=float(max_value),
precision=decimal_places))) | [
"Return",
"random",
"decimal",
"from",
"the",
"[",
"min_value",
"max_value",
"]",
"interval",
">>>",
"result",
"=",
"any_decimal",
"(",
"min_value",
"=",
"0",
".",
"999",
"max_value",
"=",
"3",
"decimal_places",
"=",
"3",
")",
">>>",
"type",
"(",
"result",
")",
"<class",
"decimal",
".",
"Decimal",
">",
">>>",
"result",
">",
"=",
"Decimal",
"(",
"0",
".",
"999",
")",
"and",
"result",
"<",
"=",
"Decimal",
"(",
"3",
")",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/xunit.py#L135-L147 | [
"def",
"any_decimal",
"(",
"min_value",
"=",
"Decimal",
"(",
"0",
")",
",",
"max_value",
"=",
"Decimal",
"(",
"'99.99'",
")",
",",
"decimal_places",
"=",
"2",
")",
":",
"return",
"Decimal",
"(",
"str",
"(",
"any_float",
"(",
"min_value",
"=",
"float",
"(",
"min_value",
")",
",",
"max_value",
"=",
"float",
"(",
"max_value",
")",
",",
"precision",
"=",
"decimal_places",
")",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_user | Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user | django_any/contrib/auth.py | def any_user(password=None, permissions=[], groups=[], **kwargs):
"""
Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user
"""
is_active = kwargs.pop('is_active', True)
is_superuser = kwargs.pop('is_superuser', False)
is_staff = kwargs.pop('is_staff', False)
user = any_model(User, is_active = is_active, is_superuser = is_superuser,
is_staff = is_staff, **kwargs)
for group_name in groups :
group = Group.objects.get(name=group_name)
user.groups.add(group)
for permission_name in permissions:
app_label, codename = permission_name.split('.')
permission = Permission.objects.get(
content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(permission)
if password:
user.set_password(password)
user.save()
return user | def any_user(password=None, permissions=[], groups=[], **kwargs):
"""
Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user
"""
is_active = kwargs.pop('is_active', True)
is_superuser = kwargs.pop('is_superuser', False)
is_staff = kwargs.pop('is_staff', False)
user = any_model(User, is_active = is_active, is_superuser = is_superuser,
is_staff = is_staff, **kwargs)
for group_name in groups :
group = Group.objects.get(name=group_name)
user.groups.add(group)
for permission_name in permissions:
app_label, codename = permission_name.split('.')
permission = Permission.objects.get(
content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(permission)
if password:
user.set_password(password)
user.save()
return user | [
"Shortcut",
"for",
"creating",
"Users"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/contrib/auth.py#L5-L37 | [
"def",
"any_user",
"(",
"password",
"=",
"None",
",",
"permissions",
"=",
"[",
"]",
",",
"groups",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"is_active",
"=",
"kwargs",
".",
"pop",
"(",
"'is_active'",
",",
"True",
")",
"is_superuser",
"=",
"kwargs",
".",
"pop",
"(",
"'is_superuser'",
",",
"False",
")",
"is_staff",
"=",
"kwargs",
".",
"pop",
"(",
"'is_staff'",
",",
"False",
")",
"user",
"=",
"any_model",
"(",
"User",
",",
"is_active",
"=",
"is_active",
",",
"is_superuser",
"=",
"is_superuser",
",",
"is_staff",
"=",
"is_staff",
",",
"*",
"*",
"kwargs",
")",
"for",
"group_name",
"in",
"groups",
":",
"group",
"=",
"Group",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"group_name",
")",
"user",
".",
"groups",
".",
"add",
"(",
"group",
")",
"for",
"permission_name",
"in",
"permissions",
":",
"app_label",
",",
"codename",
"=",
"permission_name",
".",
"split",
"(",
"'.'",
")",
"permission",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"content_type__app_label",
"=",
"app_label",
",",
"codename",
"=",
"codename",
")",
"user",
".",
"user_permissions",
".",
"add",
"(",
"permission",
")",
"if",
"password",
":",
"user",
".",
"set_password",
"(",
"password",
")",
"user",
".",
"save",
"(",
")",
"return",
"user"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | interpretAsOpenMath | tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding objects using lambdaOM as the binder | openmath/helpers.py | def interpretAsOpenMath(x):
"""tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding objects using lambdaOM as the binder"""
if hasattr(x, "_ishelper") and x._ishelper:
# wrapped things in this class -> unwrap
return x._toOM()
elif isinstance(x, om.OMAny):
# already OM
return x
elif isinstance(x, six.integer_types):
# integers -> OMI
return om.OMInteger(x)
elif isinstance(x, float):
# floats -> OMF
return om.OMFloat(x)
elif isinstance(x, six.string_types):
# strings -> OMSTR
return om.OMString(x)
elif isinstance(x, WrappedHelper):
# wrapper -> wrapped object
return x.toOM()
elif inspect.isfunction(x):
# function -> OMBIND(lambda,...)
# get all the parameters of the function
paramMap = inspect.signature(x).parameters
params = [v for k, v in six.iteritems(paramMap)]
# make sure that all of them are positional
posArgKinds = [inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD]
if not all([p.kind in posArgKinds for p in params]):
raise CannotInterpretAsOpenMath("no sequence arguments allowed")
# call the function with appropriate OMVariables
paramsOM = [om.OMVariable(name=p.name) for p in params]
bodyOM = interpretAsOpenMath(x(*paramsOM))
return OMBinding(om.OMSymbol(name="lambda", cd="python", cdbase="http://python.org"), paramsOM, bodyOM)
else:
# fail
raise CannotInterpretAsOpenMath("unknown kind of object: " + str(x)) | def interpretAsOpenMath(x):
"""tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding objects using lambdaOM as the binder"""
if hasattr(x, "_ishelper") and x._ishelper:
# wrapped things in this class -> unwrap
return x._toOM()
elif isinstance(x, om.OMAny):
# already OM
return x
elif isinstance(x, six.integer_types):
# integers -> OMI
return om.OMInteger(x)
elif isinstance(x, float):
# floats -> OMF
return om.OMFloat(x)
elif isinstance(x, six.string_types):
# strings -> OMSTR
return om.OMString(x)
elif isinstance(x, WrappedHelper):
# wrapper -> wrapped object
return x.toOM()
elif inspect.isfunction(x):
# function -> OMBIND(lambda,...)
# get all the parameters of the function
paramMap = inspect.signature(x).parameters
params = [v for k, v in six.iteritems(paramMap)]
# make sure that all of them are positional
posArgKinds = [inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD]
if not all([p.kind in posArgKinds for p in params]):
raise CannotInterpretAsOpenMath("no sequence arguments allowed")
# call the function with appropriate OMVariables
paramsOM = [om.OMVariable(name=p.name) for p in params]
bodyOM = interpretAsOpenMath(x(*paramsOM))
return OMBinding(om.OMSymbol(name="lambda", cd="python", cdbase="http://python.org"), paramsOM, bodyOM)
else:
# fail
raise CannotInterpretAsOpenMath("unknown kind of object: " + str(x)) | [
"tries",
"to",
"convert",
"a",
"Python",
"object",
"into",
"an",
"OpenMath",
"object",
"this",
"is",
"not",
"a",
"replacement",
"for",
"using",
"a",
"Converter",
"for",
"exporting",
"Python",
"objects",
"instead",
"it",
"is",
"used",
"conveniently",
"building",
"OM",
"objects",
"in",
"DSL",
"embedded",
"in",
"Python",
"inparticular",
"it",
"converts",
"Python",
"functions",
"into",
"OMBinding",
"objects",
"using",
"lambdaOM",
"as",
"the",
"binder"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/helpers.py#L237-L287 | [
"def",
"interpretAsOpenMath",
"(",
"x",
")",
":",
"if",
"hasattr",
"(",
"x",
",",
"\"_ishelper\"",
")",
"and",
"x",
".",
"_ishelper",
":",
"# wrapped things in this class -> unwrap",
"return",
"x",
".",
"_toOM",
"(",
")",
"elif",
"isinstance",
"(",
"x",
",",
"om",
".",
"OMAny",
")",
":",
"# already OM",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"six",
".",
"integer_types",
")",
":",
"# integers -> OMI",
"return",
"om",
".",
"OMInteger",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"float",
")",
":",
"# floats -> OMF",
"return",
"om",
".",
"OMFloat",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
":",
"# strings -> OMSTR",
"return",
"om",
".",
"OMString",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"WrappedHelper",
")",
":",
"# wrapper -> wrapped object",
"return",
"x",
".",
"toOM",
"(",
")",
"elif",
"inspect",
".",
"isfunction",
"(",
"x",
")",
":",
"# function -> OMBIND(lambda,...)",
"# get all the parameters of the function",
"paramMap",
"=",
"inspect",
".",
"signature",
"(",
"x",
")",
".",
"parameters",
"params",
"=",
"[",
"v",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"paramMap",
")",
"]",
"# make sure that all of them are positional",
"posArgKinds",
"=",
"[",
"inspect",
".",
"Parameter",
".",
"POSITIONAL_ONLY",
",",
"inspect",
".",
"Parameter",
".",
"POSITIONAL_OR_KEYWORD",
"]",
"if",
"not",
"all",
"(",
"[",
"p",
".",
"kind",
"in",
"posArgKinds",
"for",
"p",
"in",
"params",
"]",
")",
":",
"raise",
"CannotInterpretAsOpenMath",
"(",
"\"no sequence arguments allowed\"",
")",
"# call the function with appropriate OMVariables",
"paramsOM",
"=",
"[",
"om",
".",
"OMVariable",
"(",
"name",
"=",
"p",
".",
"name",
")",
"for",
"p",
"in",
"params",
"]",
"bodyOM",
"=",
"interpretAsOpenMath",
"(",
"x",
"(",
"*",
"paramsOM",
")",
")",
"return",
"OMBinding",
"(",
"om",
".",
"OMSymbol",
"(",
"name",
"=",
"\"lambda\"",
",",
"cd",
"=",
"\"python\"",
",",
"cdbase",
"=",
"\"http://python.org\"",
")",
",",
"paramsOM",
",",
"bodyOM",
")",
"else",
":",
"# fail",
"raise",
"CannotInterpretAsOpenMath",
"(",
"\"unknown kind of object: \"",
"+",
"str",
"(",
"x",
")",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | convertAsOpenMath | Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method | openmath/helpers.py | def convertAsOpenMath(term, converter):
""" Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method """
# if we already have openmath, or have some of our magic helpers, use interpretAsOpenMath
if hasattr(term, "_ishelper") and term._ishelper or isinstance(term, om.OMAny):
return interpretAsOpenMath(term)
# next try to convert using the converter
if converter is not None:
try:
_converted = converter.to_openmath(term)
except Exception as e:
_converted = None
if isinstance(_converted, om.OMAny):
return _converted
# fallback to the openmath helper
return interpretAsOpenMath(term) | def convertAsOpenMath(term, converter):
""" Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method """
# if we already have openmath, or have some of our magic helpers, use interpretAsOpenMath
if hasattr(term, "_ishelper") and term._ishelper or isinstance(term, om.OMAny):
return interpretAsOpenMath(term)
# next try to convert using the converter
if converter is not None:
try:
_converted = converter.to_openmath(term)
except Exception as e:
_converted = None
if isinstance(_converted, om.OMAny):
return _converted
# fallback to the openmath helper
return interpretAsOpenMath(term) | [
"Converts",
"a",
"term",
"into",
"OpenMath",
"using",
"either",
"a",
"converter",
"or",
"the",
"interpretAsOpenMath",
"method"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/helpers.py#L289-L307 | [
"def",
"convertAsOpenMath",
"(",
"term",
",",
"converter",
")",
":",
"# if we already have openmath, or have some of our magic helpers, use interpretAsOpenMath",
"if",
"hasattr",
"(",
"term",
",",
"\"_ishelper\"",
")",
"and",
"term",
".",
"_ishelper",
"or",
"isinstance",
"(",
"term",
",",
"om",
".",
"OMAny",
")",
":",
"return",
"interpretAsOpenMath",
"(",
"term",
")",
"# next try to convert using the converter",
"if",
"converter",
"is",
"not",
"None",
":",
"try",
":",
"_converted",
"=",
"converter",
".",
"to_openmath",
"(",
"term",
")",
"except",
"Exception",
"as",
"e",
":",
"_converted",
"=",
"None",
"if",
"isinstance",
"(",
"_converted",
",",
"om",
".",
"OMAny",
")",
":",
"return",
"_converted",
"# fallback to the openmath helper",
"return",
"interpretAsOpenMath",
"(",
"term",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | Converter.to_python | Convert OpenMath object to Python | openmath/convert.py | def to_python(self, omobj):
""" Convert OpenMath object to Python """
# general overrides
if omobj.__class__ in self._omclass_to_py:
return self._omclass_to_py[omobj.__class__](omobj)
# oms
elif isinstance(omobj, om.OMSymbol):
return self._lookup_to_python(omobj.cdbase, omobj.cd, omobj.name)
# oma
elif isinstance(omobj, om.OMApplication):
elem = self.to_python(omobj.elem)
arguments = [self.to_python(x) for x in omobj.arguments]
return elem(*arguments)
raise ValueError('Cannot convert object of class %s to Python.' % omobj.__class__.__name__) | def to_python(self, omobj):
""" Convert OpenMath object to Python """
# general overrides
if omobj.__class__ in self._omclass_to_py:
return self._omclass_to_py[omobj.__class__](omobj)
# oms
elif isinstance(omobj, om.OMSymbol):
return self._lookup_to_python(omobj.cdbase, omobj.cd, omobj.name)
# oma
elif isinstance(omobj, om.OMApplication):
elem = self.to_python(omobj.elem)
arguments = [self.to_python(x) for x in omobj.arguments]
return elem(*arguments)
raise ValueError('Cannot convert object of class %s to Python.' % omobj.__class__.__name__) | [
"Convert",
"OpenMath",
"object",
"to",
"Python"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert.py#L136-L149 | [
"def",
"to_python",
"(",
"self",
",",
"omobj",
")",
":",
"# general overrides",
"if",
"omobj",
".",
"__class__",
"in",
"self",
".",
"_omclass_to_py",
":",
"return",
"self",
".",
"_omclass_to_py",
"[",
"omobj",
".",
"__class__",
"]",
"(",
"omobj",
")",
"# oms",
"elif",
"isinstance",
"(",
"omobj",
",",
"om",
".",
"OMSymbol",
")",
":",
"return",
"self",
".",
"_lookup_to_python",
"(",
"omobj",
".",
"cdbase",
",",
"omobj",
".",
"cd",
",",
"omobj",
".",
"name",
")",
"# oma",
"elif",
"isinstance",
"(",
"omobj",
",",
"om",
".",
"OMApplication",
")",
":",
"elem",
"=",
"self",
".",
"to_python",
"(",
"omobj",
".",
"elem",
")",
"arguments",
"=",
"[",
"self",
".",
"to_python",
"(",
"x",
")",
"for",
"x",
"in",
"omobj",
".",
"arguments",
"]",
"return",
"elem",
"(",
"*",
"arguments",
")",
"raise",
"ValueError",
"(",
"'Cannot convert object of class %s to Python.'",
"%",
"omobj",
".",
"__class__",
".",
"__name__",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | Converter.to_openmath | Convert Python object to OpenMath | openmath/convert.py | def to_openmath(self, obj):
""" Convert Python object to OpenMath """
for cl, conv in reversed(self._conv_to_om):
if cl is None or isinstance(obj, cl):
try:
return conv(obj)
except CannotConvertError:
continue
if hasattr(obj, '__openmath__'):
return obj.__openmath__()
raise ValueError('Cannot convert %r to OpenMath.' % obj) | def to_openmath(self, obj):
""" Convert Python object to OpenMath """
for cl, conv in reversed(self._conv_to_om):
if cl is None or isinstance(obj, cl):
try:
return conv(obj)
except CannotConvertError:
continue
if hasattr(obj, '__openmath__'):
return obj.__openmath__()
raise ValueError('Cannot convert %r to OpenMath.' % obj) | [
"Convert",
"Python",
"object",
"to",
"OpenMath"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert.py#L151-L163 | [
"def",
"to_openmath",
"(",
"self",
",",
"obj",
")",
":",
"for",
"cl",
",",
"conv",
"in",
"reversed",
"(",
"self",
".",
"_conv_to_om",
")",
":",
"if",
"cl",
"is",
"None",
"or",
"isinstance",
"(",
"obj",
",",
"cl",
")",
":",
"try",
":",
"return",
"conv",
"(",
"obj",
")",
"except",
"CannotConvertError",
":",
"continue",
"if",
"hasattr",
"(",
"obj",
",",
"'__openmath__'",
")",
":",
"return",
"obj",
".",
"__openmath__",
"(",
")",
"raise",
"ValueError",
"(",
"'Cannot convert %r to OpenMath.'",
"%",
"obj",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | Converter.register_to_openmath | Register a conversion from Python to OpenMath
:param py_class: A Python class the conversion is attached to, or None
:type py_class: None, type
:param converter: A conversion function or an OpenMath object
:type converter: Callable, OMAny
:rtype: None
``converter`` will used to convert any object of type ``py_class``,
or any object if ``py_class`` is ``None``. If ``converter`` is an
OpenMath object, it is returned immediately. If it is a callable, it
is called with the Python object as paramter; in this case, it must
either return an OpenMath object, or raise an exception. The
special exception ``CannotConvertError`` can be used to signify that
``converter`` does not know how to convert the current object, and that
``to_openmath`` shall continue with the other converters. Any other
exception stops conversion immediately.
Converters registered by this function are called in order from the
most recent to the oldest. | openmath/convert.py | def register_to_openmath(self, py_class, converter):
"""Register a conversion from Python to OpenMath
:param py_class: A Python class the conversion is attached to, or None
:type py_class: None, type
:param converter: A conversion function or an OpenMath object
:type converter: Callable, OMAny
:rtype: None
``converter`` will used to convert any object of type ``py_class``,
or any object if ``py_class`` is ``None``. If ``converter`` is an
OpenMath object, it is returned immediately. If it is a callable, it
is called with the Python object as paramter; in this case, it must
either return an OpenMath object, or raise an exception. The
special exception ``CannotConvertError`` can be used to signify that
``converter`` does not know how to convert the current object, and that
``to_openmath`` shall continue with the other converters. Any other
exception stops conversion immediately.
Converters registered by this function are called in order from the
most recent to the oldest.
"""
if py_class is not None and not isclass(py_class):
raise TypeError('Expected class, found %r' % py_class)
if not callable(converter) and not isinstance(converter, om.OMAny):
raise TypeError('Expected callable or openmath.OMAny object, found %r' % converter)
self._conv_to_om.append((py_class, converter)) | def register_to_openmath(self, py_class, converter):
"""Register a conversion from Python to OpenMath
:param py_class: A Python class the conversion is attached to, or None
:type py_class: None, type
:param converter: A conversion function or an OpenMath object
:type converter: Callable, OMAny
:rtype: None
``converter`` will used to convert any object of type ``py_class``,
or any object if ``py_class`` is ``None``. If ``converter`` is an
OpenMath object, it is returned immediately. If it is a callable, it
is called with the Python object as paramter; in this case, it must
either return an OpenMath object, or raise an exception. The
special exception ``CannotConvertError`` can be used to signify that
``converter`` does not know how to convert the current object, and that
``to_openmath`` shall continue with the other converters. Any other
exception stops conversion immediately.
Converters registered by this function are called in order from the
most recent to the oldest.
"""
if py_class is not None and not isclass(py_class):
raise TypeError('Expected class, found %r' % py_class)
if not callable(converter) and not isinstance(converter, om.OMAny):
raise TypeError('Expected callable or openmath.OMAny object, found %r' % converter)
self._conv_to_om.append((py_class, converter)) | [
"Register",
"a",
"conversion",
"from",
"Python",
"to",
"OpenMath"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert.py#L165-L193 | [
"def",
"register_to_openmath",
"(",
"self",
",",
"py_class",
",",
"converter",
")",
":",
"if",
"py_class",
"is",
"not",
"None",
"and",
"not",
"isclass",
"(",
"py_class",
")",
":",
"raise",
"TypeError",
"(",
"'Expected class, found %r'",
"%",
"py_class",
")",
"if",
"not",
"callable",
"(",
"converter",
")",
"and",
"not",
"isinstance",
"(",
"converter",
",",
"om",
".",
"OMAny",
")",
":",
"raise",
"TypeError",
"(",
"'Expected callable or openmath.OMAny object, found %r'",
"%",
"converter",
")",
"self",
".",
"_conv_to_om",
".",
"append",
"(",
"(",
"py_class",
",",
"converter",
")",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | Converter._deprecated_register_to_python | Register a conversion from OpenMath to Python
This function has two forms. A three-arguments one:
:param cd: A content dictionary name
:type cd: str
:param name: A symbol name
:type name: str
:param converter: A conversion function, or a Python object
:type: Callable, Any
Any object of type ``openmath.OMSymbol``, with content
dictionary equal to ``cd`` and name equal to ``name`` will be converted
using ``converter``. Also, any object of type ``openmath.OMApplication``
whose first child is an ``openmath.OMSymbol`` as above will be converted
using ``converter``. If ``converter`` is a callable, it will be called with the
OpenMath object as parameter; otherwise ``converter`` will be returned.
In the two-argument form
:param cd: A subclass of ``OMAny``
:type cd: type
:param name: A conversion function
:type name: Callable
Any object of type ``cd`` will be passed to ``name()``, and the
result will be returned. This forms is mainly to override default
conversions for basic OpenMath tags (OMInteger, OMString, etc.). It
is discouraged to use it for ``OMSymbol`` and ``OMApplication``. | openmath/convert.py | def _deprecated_register_to_python(self, cd, name, converter=None):
"""Register a conversion from OpenMath to Python
This function has two forms. A three-arguments one:
:param cd: A content dictionary name
:type cd: str
:param name: A symbol name
:type name: str
:param converter: A conversion function, or a Python object
:type: Callable, Any
Any object of type ``openmath.OMSymbol``, with content
dictionary equal to ``cd`` and name equal to ``name`` will be converted
using ``converter``. Also, any object of type ``openmath.OMApplication``
whose first child is an ``openmath.OMSymbol`` as above will be converted
using ``converter``. If ``converter`` is a callable, it will be called with the
OpenMath object as parameter; otherwise ``converter`` will be returned.
In the two-argument form
:param cd: A subclass of ``OMAny``
:type cd: type
:param name: A conversion function
:type name: Callable
Any object of type ``cd`` will be passed to ``name()``, and the
result will be returned. This forms is mainly to override default
conversions for basic OpenMath tags (OMInteger, OMString, etc.). It
is discouraged to use it for ``OMSymbol`` and ``OMApplication``.
"""
if converter is None:
if isclass(cd) and issubclass(cd, om.OMAny):
self._conv_to_py[cd] = name
else:
raise TypeError('Two-arguments form expects subclass of openmath.OMAny, found %r' % cd)
else:
if isinstance(cd, str) and isinstance(name, str):
self._conv_sym_to_py[(cd, name)] = converter
else:
raise TypeError('Three-arguments form expects string, found %r' % cd.__class__) | def _deprecated_register_to_python(self, cd, name, converter=None):
"""Register a conversion from OpenMath to Python
This function has two forms. A three-arguments one:
:param cd: A content dictionary name
:type cd: str
:param name: A symbol name
:type name: str
:param converter: A conversion function, or a Python object
:type: Callable, Any
Any object of type ``openmath.OMSymbol``, with content
dictionary equal to ``cd`` and name equal to ``name`` will be converted
using ``converter``. Also, any object of type ``openmath.OMApplication``
whose first child is an ``openmath.OMSymbol`` as above will be converted
using ``converter``. If ``converter`` is a callable, it will be called with the
OpenMath object as parameter; otherwise ``converter`` will be returned.
In the two-argument form
:param cd: A subclass of ``OMAny``
:type cd: type
:param name: A conversion function
:type name: Callable
Any object of type ``cd`` will be passed to ``name()``, and the
result will be returned. This forms is mainly to override default
conversions for basic OpenMath tags (OMInteger, OMString, etc.). It
is discouraged to use it for ``OMSymbol`` and ``OMApplication``.
"""
if converter is None:
if isclass(cd) and issubclass(cd, om.OMAny):
self._conv_to_py[cd] = name
else:
raise TypeError('Two-arguments form expects subclass of openmath.OMAny, found %r' % cd)
else:
if isinstance(cd, str) and isinstance(name, str):
self._conv_sym_to_py[(cd, name)] = converter
else:
raise TypeError('Three-arguments form expects string, found %r' % cd.__class__) | [
"Register",
"a",
"conversion",
"from",
"OpenMath",
"to",
"Python"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert.py#L196-L239 | [
"def",
"_deprecated_register_to_python",
"(",
"self",
",",
"cd",
",",
"name",
",",
"converter",
"=",
"None",
")",
":",
"if",
"converter",
"is",
"None",
":",
"if",
"isclass",
"(",
"cd",
")",
"and",
"issubclass",
"(",
"cd",
",",
"om",
".",
"OMAny",
")",
":",
"self",
".",
"_conv_to_py",
"[",
"cd",
"]",
"=",
"name",
"else",
":",
"raise",
"TypeError",
"(",
"'Two-arguments form expects subclass of openmath.OMAny, found %r'",
"%",
"cd",
")",
"else",
":",
"if",
"isinstance",
"(",
"cd",
",",
"str",
")",
"and",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"self",
".",
"_conv_sym_to_py",
"[",
"(",
"cd",
",",
"name",
")",
"]",
"=",
"converter",
"else",
":",
"raise",
"TypeError",
"(",
"'Three-arguments form expects string, found %r'",
"%",
"cd",
".",
"__class__",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | Converter._deprecated_register | This is a shorthand for:
``self.register_to_python(om_cd, om_name, to_py)``
``self.register_to_openmath(py_class, to_om)`` | openmath/convert.py | def _deprecated_register(self, py_class, to_om, om_cd, om_name, to_py=None):
"""
This is a shorthand for:
``self.register_to_python(om_cd, om_name, to_py)``
``self.register_to_openmath(py_class, to_om)``
"""
self.register_to_python(om_cd, om_name, to_py)
self.register_to_openmath(py_class, to_om) | def _deprecated_register(self, py_class, to_om, om_cd, om_name, to_py=None):
"""
This is a shorthand for:
``self.register_to_python(om_cd, om_name, to_py)``
``self.register_to_openmath(py_class, to_om)``
"""
self.register_to_python(om_cd, om_name, to_py)
self.register_to_openmath(py_class, to_om) | [
"This",
"is",
"a",
"shorthand",
"for",
":"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert.py#L242-L250 | [
"def",
"_deprecated_register",
"(",
"self",
",",
"py_class",
",",
"to_om",
",",
"om_cd",
",",
"om_name",
",",
"to_py",
"=",
"None",
")",
":",
"self",
".",
"register_to_python",
"(",
"om_cd",
",",
"om_name",
",",
"to_py",
")",
"self",
".",
"register_to_openmath",
"(",
"py_class",
",",
"to_om",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | Redis.init_app | Used to initialize redis with app object | lark/ext/flask/flask_redis.py | def init_app(self, app):
"""
Used to initialize redis with app object
"""
app.config.setdefault('REDIS_URLS', {
'main': 'redis://localhost:6379/0',
'admin': 'redis://localhost:6379/1',
})
app.before_request(self.before_request)
self.app = app | def init_app(self, app):
"""
Used to initialize redis with app object
"""
app.config.setdefault('REDIS_URLS', {
'main': 'redis://localhost:6379/0',
'admin': 'redis://localhost:6379/1',
})
app.before_request(self.before_request)
self.app = app | [
"Used",
"to",
"initialize",
"redis",
"with",
"app",
"object"
] | voidfiles/lark | python | https://github.com/voidfiles/lark/blob/e3f202d88b97f7b985a358fe28df7e52204f7846/lark/ext/flask/flask_redis.py#L14-L26 | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'REDIS_URLS'",
",",
"{",
"'main'",
":",
"'redis://localhost:6379/0'",
",",
"'admin'",
":",
"'redis://localhost:6379/1'",
",",
"}",
")",
"app",
".",
"before_request",
"(",
"self",
".",
"before_request",
")",
"self",
".",
"app",
"=",
"app"
] | e3f202d88b97f7b985a358fe28df7e52204f7846 |
test | valid_choices | Return list of choices's keys | django_any/functions.py | def valid_choices(choices):
"""
Return list of choices's keys
"""
for key, value in choices:
if isinstance(value, (list, tuple)):
for key, _ in value:
yield key
else:
yield key | def valid_choices(choices):
"""
Return list of choices's keys
"""
for key, value in choices:
if isinstance(value, (list, tuple)):
for key, _ in value:
yield key
else:
yield key | [
"Return",
"list",
"of",
"choices",
"s",
"keys"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/functions.py#L6-L15 | [
"def",
"valid_choices",
"(",
"choices",
")",
":",
"for",
"key",
",",
"value",
"in",
"choices",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"key",
",",
"_",
"in",
"value",
":",
"yield",
"key",
"else",
":",
"yield",
"key"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | split_model_kwargs | django_any birds language parser | django_any/functions.py | def split_model_kwargs(kw):
"""
django_any birds language parser
"""
from collections import defaultdict
model_fields = {}
fields_agrs = defaultdict(lambda : {})
for key in kw.keys():
if '__' in key:
field, _, subfield = key.partition('__')
fields_agrs[field][subfield] = kw[key]
else:
model_fields[key] = kw[key]
return model_fields, fields_agrs | def split_model_kwargs(kw):
"""
django_any birds language parser
"""
from collections import defaultdict
model_fields = {}
fields_agrs = defaultdict(lambda : {})
for key in kw.keys():
if '__' in key:
field, _, subfield = key.partition('__')
fields_agrs[field][subfield] = kw[key]
else:
model_fields[key] = kw[key]
return model_fields, fields_agrs | [
"django_any",
"birds",
"language",
"parser"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/functions.py#L18-L34 | [
"def",
"split_model_kwargs",
"(",
"kw",
")",
":",
"from",
"collections",
"import",
"defaultdict",
"model_fields",
"=",
"{",
"}",
"fields_agrs",
"=",
"defaultdict",
"(",
"lambda",
":",
"{",
"}",
")",
"for",
"key",
"in",
"kw",
".",
"keys",
"(",
")",
":",
"if",
"'__'",
"in",
"key",
":",
"field",
",",
"_",
",",
"subfield",
"=",
"key",
".",
"partition",
"(",
"'__'",
")",
"fields_agrs",
"[",
"field",
"]",
"[",
"subfield",
"]",
"=",
"kw",
"[",
"key",
"]",
"else",
":",
"model_fields",
"[",
"key",
"]",
"=",
"kw",
"[",
"key",
"]",
"return",
"model_fields",
",",
"fields_agrs"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | ExtensionMethod.register | Register form field data function.
Could be used as decorator | django_any/functions.py | def register(self, field_type, impl=None):
"""
Register form field data function.
Could be used as decorator
"""
def _wrapper(func):
self.registry[field_type] = func
return func
if impl:
return _wrapper(impl)
return _wrapper | def register(self, field_type, impl=None):
"""
Register form field data function.
Could be used as decorator
"""
def _wrapper(func):
self.registry[field_type] = func
return func
if impl:
return _wrapper(impl)
return _wrapper | [
"Register",
"form",
"field",
"data",
"function",
".",
"Could",
"be",
"used",
"as",
"decorator"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/functions.py#L46-L58 | [
"def",
"register",
"(",
"self",
",",
"field_type",
",",
"impl",
"=",
"None",
")",
":",
"def",
"_wrapper",
"(",
"func",
")",
":",
"self",
".",
"registry",
"[",
"field_type",
"]",
"=",
"func",
"return",
"func",
"if",
"impl",
":",
"return",
"_wrapper",
"(",
"impl",
")",
"return",
"_wrapper"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | ExtensionMethod._create_value | Lowest value generator.
Separated from __call__, because it seems that python
cache __call__ reference on module import | django_any/functions.py | def _create_value(self, *args, **kwargs):
"""
Lowest value generator.
Separated from __call__, because it seems that python
cache __call__ reference on module import
"""
if not len(args):
raise TypeError('Object instance is not provided')
if self.by_instance:
field_type = args[0]
else:
field_type = args[0].__class__
function = self.registry.get(field_type, self.default)
if function is None:
raise TypeError("no match %s" % field_type)
return function(*args, **kwargs) | def _create_value(self, *args, **kwargs):
"""
Lowest value generator.
Separated from __call__, because it seems that python
cache __call__ reference on module import
"""
if not len(args):
raise TypeError('Object instance is not provided')
if self.by_instance:
field_type = args[0]
else:
field_type = args[0].__class__
function = self.registry.get(field_type, self.default)
if function is None:
raise TypeError("no match %s" % field_type)
return function(*args, **kwargs) | [
"Lowest",
"value",
"generator",
"."
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/functions.py#L71-L91 | [
"def",
"_create_value",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"len",
"(",
"args",
")",
":",
"raise",
"TypeError",
"(",
"'Object instance is not provided'",
")",
"if",
"self",
".",
"by_instance",
":",
"field_type",
"=",
"args",
"[",
"0",
"]",
"else",
":",
"field_type",
"=",
"args",
"[",
"0",
"]",
".",
"__class__",
"function",
"=",
"self",
".",
"registry",
".",
"get",
"(",
"field_type",
",",
"self",
".",
"default",
")",
"if",
"function",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"no match %s\"",
"%",
"field_type",
")",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_form_default | Returns tuple with form data and files | django_any/forms.py | def any_form_default(form_cls, **kwargs):
"""
Returns tuple with form data and files
"""
form_data = {}
form_files = {}
form_fields, fields_args = split_model_kwargs(kwargs)
for name, field in form_cls.base_fields.iteritems():
if name in form_fields:
form_data[name] = kwargs[name]
else:
form_data[name] = any_form_field(field, **fields_args[name])
return form_data, form_files | def any_form_default(form_cls, **kwargs):
"""
Returns tuple with form data and files
"""
form_data = {}
form_files = {}
form_fields, fields_args = split_model_kwargs(kwargs)
for name, field in form_cls.base_fields.iteritems():
if name in form_fields:
form_data[name] = kwargs[name]
else:
form_data[name] = any_form_field(field, **fields_args[name])
return form_data, form_files | [
"Returns",
"tuple",
"with",
"form",
"data",
"and",
"files"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L20-L35 | [
"def",
"any_form_default",
"(",
"form_cls",
",",
"*",
"*",
"kwargs",
")",
":",
"form_data",
"=",
"{",
"}",
"form_files",
"=",
"{",
"}",
"form_fields",
",",
"fields_args",
"=",
"split_model_kwargs",
"(",
"kwargs",
")",
"for",
"name",
",",
"field",
"in",
"form_cls",
".",
"base_fields",
".",
"iteritems",
"(",
")",
":",
"if",
"name",
"in",
"form_fields",
":",
"form_data",
"[",
"name",
"]",
"=",
"kwargs",
"[",
"name",
"]",
"else",
":",
"form_data",
"[",
"name",
"]",
"=",
"any_form_field",
"(",
"field",
",",
"*",
"*",
"fields_args",
"[",
"name",
"]",
")",
"return",
"form_data",
",",
"form_files"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | field_required_attribute | Sometimes return None if field is not required
>>> result = any_form_field(forms.BooleanField(required=False))
>>> result in ['', 'True', 'False']
True | django_any/forms.py | def field_required_attribute(function):
"""
Sometimes return None if field is not required
>>> result = any_form_field(forms.BooleanField(required=False))
>>> result in ['', 'True', 'False']
True
"""
def _wrapper(field, **kwargs):
if not field.required and random.random < 0.1:
return None
return function(field, **kwargs)
return _wrapper | def field_required_attribute(function):
"""
Sometimes return None if field is not required
>>> result = any_form_field(forms.BooleanField(required=False))
>>> result in ['', 'True', 'False']
True
"""
def _wrapper(field, **kwargs):
if not field.required and random.random < 0.1:
return None
return function(field, **kwargs)
return _wrapper | [
"Sometimes",
"return",
"None",
"if",
"field",
"is",
"not",
"required"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L39-L51 | [
"def",
"field_required_attribute",
"(",
"function",
")",
":",
"def",
"_wrapper",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"field",
".",
"required",
"and",
"random",
".",
"random",
"<",
"0.1",
":",
"return",
"None",
"return",
"function",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | field_choices_attibute | Selection from field.choices | django_any/forms.py | def field_choices_attibute(function):
"""
Selection from field.choices
"""
def _wrapper(field, **kwargs):
if hasattr(field.widget, 'choices'):
return random.choice(list(valid_choices(field.widget.choices)))
return function(field, **kwargs)
return _wrapper | def field_choices_attibute(function):
"""
Selection from field.choices
"""
def _wrapper(field, **kwargs):
if hasattr(field.widget, 'choices'):
return random.choice(list(valid_choices(field.widget.choices)))
return function(field, **kwargs)
return _wrapper | [
"Selection",
"from",
"field",
".",
"choices"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L55-L64 | [
"def",
"field_choices_attibute",
"(",
"function",
")",
":",
"def",
"_wrapper",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"field",
".",
"widget",
",",
"'choices'",
")",
":",
"return",
"random",
".",
"choice",
"(",
"list",
"(",
"valid_choices",
"(",
"field",
".",
"widget",
".",
"choices",
")",
")",
")",
"return",
"function",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | char_field_data | Return random value for CharField
>>> result = any_form_field(forms.CharField(min_length=3, max_length=10))
>>> type(result)
<type 'str'> | django_any/forms.py | def char_field_data(field, **kwargs):
"""
Return random value for CharField
>>> result = any_form_field(forms.CharField(min_length=3, max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length or 255)
return xunit.any_string(min_length=field.min_length or min_length,
max_length=field.max_length or max_length) | def char_field_data(field, **kwargs):
"""
Return random value for CharField
>>> result = any_form_field(forms.CharField(min_length=3, max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length or 255)
return xunit.any_string(min_length=field.min_length or min_length,
max_length=field.max_length or max_length) | [
"Return",
"random",
"value",
"for",
"CharField",
">>>",
"result",
"=",
"any_form_field",
"(",
"forms",
".",
"CharField",
"(",
"min_length",
"=",
"3",
"max_length",
"=",
"10",
"))",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L80-L90 | [
"def",
"char_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_length",
"=",
"kwargs",
".",
"get",
"(",
"'min_length'",
",",
"1",
")",
"max_length",
"=",
"kwargs",
".",
"get",
"(",
"'max_length'",
",",
"field",
".",
"max_length",
"or",
"255",
")",
"return",
"xunit",
".",
"any_string",
"(",
"min_length",
"=",
"field",
".",
"min_length",
"or",
"min_length",
",",
"max_length",
"=",
"field",
".",
"max_length",
"or",
"max_length",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | decimal_field_data | Return random value for DecimalField
>>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2))
>>> type(result)
<type 'str'>
>>> from decimal import Decimal
>>> Decimal(result) >= 11, Decimal(result) <= Decimal('99.99')
(True, True) | django_any/forms.py | def decimal_field_data(field, **kwargs):
"""
Return random value for DecimalField
>>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2))
>>> type(result)
<type 'str'>
>>> from decimal import Decimal
>>> Decimal(result) >= 11, Decimal(result) <= Decimal('99.99')
(True, True)
"""
min_value = 0
max_value = 10
from django.core.validators import MinValueValidator, MaxValueValidator
for elem in field.validators:
if isinstance(elem, MinValueValidator):
min_value = elem.limit_value
if isinstance(elem, MaxValueValidator):
max_value = elem.limit_value
if (field.max_digits and field.decimal_places):
from decimal import Decimal
max_value = min(max_value,
Decimal('%s.%s' % ('9'*(field.max_digits-field.decimal_places),
'9'*field.decimal_places)))
min_value = kwargs.get('min_value') or min_value
max_value = kwargs.get('max_value') or max_value
return str(xunit.any_decimal(min_value=min_value,
max_value=max_value,
decimal_places = field.decimal_places or 2)) | def decimal_field_data(field, **kwargs):
"""
Return random value for DecimalField
>>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2))
>>> type(result)
<type 'str'>
>>> from decimal import Decimal
>>> Decimal(result) >= 11, Decimal(result) <= Decimal('99.99')
(True, True)
"""
min_value = 0
max_value = 10
from django.core.validators import MinValueValidator, MaxValueValidator
for elem in field.validators:
if isinstance(elem, MinValueValidator):
min_value = elem.limit_value
if isinstance(elem, MaxValueValidator):
max_value = elem.limit_value
if (field.max_digits and field.decimal_places):
from decimal import Decimal
max_value = min(max_value,
Decimal('%s.%s' % ('9'*(field.max_digits-field.decimal_places),
'9'*field.decimal_places)))
min_value = kwargs.get('min_value') or min_value
max_value = kwargs.get('max_value') or max_value
return str(xunit.any_decimal(min_value=min_value,
max_value=max_value,
decimal_places = field.decimal_places or 2)) | [
"Return",
"random",
"value",
"for",
"DecimalField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L94-L124 | [
"def",
"decimal_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"0",
"max_value",
"=",
"10",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"MinValueValidator",
",",
"MaxValueValidator",
"for",
"elem",
"in",
"field",
".",
"validators",
":",
"if",
"isinstance",
"(",
"elem",
",",
"MinValueValidator",
")",
":",
"min_value",
"=",
"elem",
".",
"limit_value",
"if",
"isinstance",
"(",
"elem",
",",
"MaxValueValidator",
")",
":",
"max_value",
"=",
"elem",
".",
"limit_value",
"if",
"(",
"field",
".",
"max_digits",
"and",
"field",
".",
"decimal_places",
")",
":",
"from",
"decimal",
"import",
"Decimal",
"max_value",
"=",
"min",
"(",
"max_value",
",",
"Decimal",
"(",
"'%s.%s'",
"%",
"(",
"'9'",
"*",
"(",
"field",
".",
"max_digits",
"-",
"field",
".",
"decimal_places",
")",
",",
"'9'",
"*",
"field",
".",
"decimal_places",
")",
")",
")",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
")",
"or",
"min_value",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
")",
"or",
"max_value",
"return",
"str",
"(",
"xunit",
".",
"any_decimal",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
",",
"decimal_places",
"=",
"field",
".",
"decimal_places",
"or",
"2",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | email_field_data | Return random value for EmailField
>>> result = any_form_field(forms.EmailField(min_length=10, max_length=30))
>>> type(result)
<type 'str'>
>>> len(result) <= 30, len(result) >= 10
(True, True) | django_any/forms.py | def email_field_data(field, **kwargs):
"""
Return random value for EmailField
>>> result = any_form_field(forms.EmailField(min_length=10, max_length=30))
>>> type(result)
<type 'str'>
>>> len(result) <= 30, len(result) >= 10
(True, True)
"""
max_length = 10
if field.max_length:
max_length = (field.max_length -5) / 2
min_length = 10
if field.min_length:
min_length = (field.min_length-4) / 2
return "%s@%s.%s" % (
xunit.any_string(min_length=min_length, max_length=max_length),
xunit.any_string(min_length=min_length, max_length=max_length),
xunit.any_string(min_length=2, max_length=3)) | def email_field_data(field, **kwargs):
"""
Return random value for EmailField
>>> result = any_form_field(forms.EmailField(min_length=10, max_length=30))
>>> type(result)
<type 'str'>
>>> len(result) <= 30, len(result) >= 10
(True, True)
"""
max_length = 10
if field.max_length:
max_length = (field.max_length -5) / 2
min_length = 10
if field.min_length:
min_length = (field.min_length-4) / 2
return "%s@%s.%s" % (
xunit.any_string(min_length=min_length, max_length=max_length),
xunit.any_string(min_length=min_length, max_length=max_length),
xunit.any_string(min_length=2, max_length=3)) | [
"Return",
"random",
"value",
"for",
"EmailField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L128-L147 | [
"def",
"email_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"max_length",
"=",
"10",
"if",
"field",
".",
"max_length",
":",
"max_length",
"=",
"(",
"field",
".",
"max_length",
"-",
"5",
")",
"/",
"2",
"min_length",
"=",
"10",
"if",
"field",
".",
"min_length",
":",
"min_length",
"=",
"(",
"field",
".",
"min_length",
"-",
"4",
")",
"/",
"2",
"return",
"\"%s@%s.%s\"",
"%",
"(",
"xunit",
".",
"any_string",
"(",
"min_length",
"=",
"min_length",
",",
"max_length",
"=",
"max_length",
")",
",",
"xunit",
".",
"any_string",
"(",
"min_length",
"=",
"min_length",
",",
"max_length",
"=",
"max_length",
")",
",",
"xunit",
".",
"any_string",
"(",
"min_length",
"=",
"2",
",",
"max_length",
"=",
"3",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | date_field_data | Return random value for DateField
>>> result = any_form_field(forms.DateField())
>>> type(result)
<type 'str'> | django_any/forms.py | def date_field_data(field, **kwargs):
"""
Return random value for DateField
>>> result = any_form_field(forms.DateField())
>>> type(result)
<type 'str'>
"""
from_date = kwargs.get('from_date', date(1990, 1, 1))
to_date = kwargs.get('to_date', date.today())
date_format = random.choice(field.input_formats or formats.get_format('DATE_INPUT_FORMATS'))
return xunit.any_date(from_date=from_date, to_date=to_date).strftime(date_format) | def date_field_data(field, **kwargs):
"""
Return random value for DateField
>>> result = any_form_field(forms.DateField())
>>> type(result)
<type 'str'>
"""
from_date = kwargs.get('from_date', date(1990, 1, 1))
to_date = kwargs.get('to_date', date.today())
date_format = random.choice(field.input_formats or formats.get_format('DATE_INPUT_FORMATS'))
return xunit.any_date(from_date=from_date, to_date=to_date).strftime(date_format) | [
"Return",
"random",
"value",
"for",
"DateField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L151-L164 | [
"def",
"date_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
".",
"get",
"(",
"'from_date'",
",",
"date",
"(",
"1990",
",",
"1",
",",
"1",
")",
")",
"to_date",
"=",
"kwargs",
".",
"get",
"(",
"'to_date'",
",",
"date",
".",
"today",
"(",
")",
")",
"date_format",
"=",
"random",
".",
"choice",
"(",
"field",
".",
"input_formats",
"or",
"formats",
".",
"get_format",
"(",
"'DATE_INPUT_FORMATS'",
")",
")",
"return",
"xunit",
".",
"any_date",
"(",
"from_date",
"=",
"from_date",
",",
"to_date",
"=",
"to_date",
")",
".",
"strftime",
"(",
"date_format",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | datetime_field_data | Return random value for DateTimeField
>>> result = any_form_field(forms.DateTimeField())
>>> type(result)
<type 'str'> | django_any/forms.py | def datetime_field_data(field, **kwargs):
"""
Return random value for DateTimeField
>>> result = any_form_field(forms.DateTimeField())
>>> type(result)
<type 'str'>
"""
from_date = kwargs.get('from_date', datetime(1990, 1, 1))
to_date = kwargs.get('to_date', datetime.today())
date_format = random.choice(field.input_formats or formats.get_format('DATETIME_INPUT_FORMATS'))
return xunit.any_datetime(from_date=from_date, to_date=to_date).strftime(date_format) | def datetime_field_data(field, **kwargs):
"""
Return random value for DateTimeField
>>> result = any_form_field(forms.DateTimeField())
>>> type(result)
<type 'str'>
"""
from_date = kwargs.get('from_date', datetime(1990, 1, 1))
to_date = kwargs.get('to_date', datetime.today())
date_format = random.choice(field.input_formats or formats.get_format('DATETIME_INPUT_FORMATS'))
return xunit.any_datetime(from_date=from_date, to_date=to_date).strftime(date_format) | [
"Return",
"random",
"value",
"for",
"DateTimeField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L168-L179 | [
"def",
"datetime_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
".",
"get",
"(",
"'from_date'",
",",
"datetime",
"(",
"1990",
",",
"1",
",",
"1",
")",
")",
"to_date",
"=",
"kwargs",
".",
"get",
"(",
"'to_date'",
",",
"datetime",
".",
"today",
"(",
")",
")",
"date_format",
"=",
"random",
".",
"choice",
"(",
"field",
".",
"input_formats",
"or",
"formats",
".",
"get_format",
"(",
"'DATETIME_INPUT_FORMATS'",
")",
")",
"return",
"xunit",
".",
"any_datetime",
"(",
"from_date",
"=",
"from_date",
",",
"to_date",
"=",
"to_date",
")",
".",
"strftime",
"(",
"date_format",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | float_field_data | Return random value for FloatField
>>> result = any_form_field(forms.FloatField(max_value=200, min_value=100))
>>> type(result)
<type 'str'>
>>> float(result) >=100, float(result) <=200
(True, True) | django_any/forms.py | def float_field_data(field, **kwargs):
"""
Return random value for FloatField
>>> result = any_form_field(forms.FloatField(max_value=200, min_value=100))
>>> type(result)
<type 'str'>
>>> float(result) >=100, float(result) <=200
(True, True)
"""
min_value = 0
max_value = 100
from django.core.validators import MinValueValidator, MaxValueValidator
for elem in field.validators:
if isinstance(elem, MinValueValidator):
min_value = elem.limit_value
if isinstance(elem, MaxValueValidator):
max_value = elem.limit_value
min_value = kwargs.get('min_value', min_value)
max_value = kwargs.get('max_value', max_value)
precision = kwargs.get('precision', 3)
return str(xunit.any_float(min_value=min_value, max_value=max_value, precision=precision)) | def float_field_data(field, **kwargs):
"""
Return random value for FloatField
>>> result = any_form_field(forms.FloatField(max_value=200, min_value=100))
>>> type(result)
<type 'str'>
>>> float(result) >=100, float(result) <=200
(True, True)
"""
min_value = 0
max_value = 100
from django.core.validators import MinValueValidator, MaxValueValidator
for elem in field.validators:
if isinstance(elem, MinValueValidator):
min_value = elem.limit_value
if isinstance(elem, MaxValueValidator):
max_value = elem.limit_value
min_value = kwargs.get('min_value', min_value)
max_value = kwargs.get('max_value', max_value)
precision = kwargs.get('precision', 3)
return str(xunit.any_float(min_value=min_value, max_value=max_value, precision=precision)) | [
"Return",
"random",
"value",
"for",
"FloatField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L183-L206 | [
"def",
"float_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"0",
"max_value",
"=",
"100",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"MinValueValidator",
",",
"MaxValueValidator",
"for",
"elem",
"in",
"field",
".",
"validators",
":",
"if",
"isinstance",
"(",
"elem",
",",
"MinValueValidator",
")",
":",
"min_value",
"=",
"elem",
".",
"limit_value",
"if",
"isinstance",
"(",
"elem",
",",
"MaxValueValidator",
")",
":",
"max_value",
"=",
"elem",
".",
"limit_value",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"min_value",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"max_value",
")",
"precision",
"=",
"kwargs",
".",
"get",
"(",
"'precision'",
",",
"3",
")",
"return",
"str",
"(",
"xunit",
".",
"any_float",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
",",
"precision",
"=",
"precision",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | integer_field_data | Return random value for IntegerField
>>> result = any_form_field(forms.IntegerField(max_value=200, min_value=100))
>>> type(result)
<type 'str'>
>>> int(result) >=100, int(result) <=200
(True, True) | django_any/forms.py | def integer_field_data(field, **kwargs):
"""
Return random value for IntegerField
>>> result = any_form_field(forms.IntegerField(max_value=200, min_value=100))
>>> type(result)
<type 'str'>
>>> int(result) >=100, int(result) <=200
(True, True)
"""
min_value = 0
max_value = 100
from django.core.validators import MinValueValidator, MaxValueValidator
for elem in field.validators:
if isinstance(elem, MinValueValidator):
min_value = elem.limit_value
if isinstance(elem, MaxValueValidator):
max_value = elem.limit_value
min_value = kwargs.get('min_value', min_value)
max_value = kwargs.get('max_value', max_value)
return str(xunit.any_int(min_value=min_value, max_value=max_value)) | def integer_field_data(field, **kwargs):
"""
Return random value for IntegerField
>>> result = any_form_field(forms.IntegerField(max_value=200, min_value=100))
>>> type(result)
<type 'str'>
>>> int(result) >=100, int(result) <=200
(True, True)
"""
min_value = 0
max_value = 100
from django.core.validators import MinValueValidator, MaxValueValidator
for elem in field.validators:
if isinstance(elem, MinValueValidator):
min_value = elem.limit_value
if isinstance(elem, MaxValueValidator):
max_value = elem.limit_value
min_value = kwargs.get('min_value', min_value)
max_value = kwargs.get('max_value', max_value)
return str(xunit.any_int(min_value=min_value, max_value=max_value)) | [
"Return",
"random",
"value",
"for",
"IntegerField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L210-L232 | [
"def",
"integer_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"0",
"max_value",
"=",
"100",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"MinValueValidator",
",",
"MaxValueValidator",
"for",
"elem",
"in",
"field",
".",
"validators",
":",
"if",
"isinstance",
"(",
"elem",
",",
"MinValueValidator",
")",
":",
"min_value",
"=",
"elem",
".",
"limit_value",
"if",
"isinstance",
"(",
"elem",
",",
"MaxValueValidator",
")",
":",
"max_value",
"=",
"elem",
".",
"limit_value",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"min_value",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"max_value",
")",
"return",
"str",
"(",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | ipaddress_field_data | Return random value for IPAddressField
>>> result = any_form_field(forms.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> import re
>>> re.match(ipv4_re, result) is not None
True | django_any/forms.py | def ipaddress_field_data(field, **kwargs):
"""
Return random value for IPAddressField
>>> result = any_form_field(forms.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> import re
>>> re.match(ipv4_re, result) is not None
True
"""
choices = kwargs.get('choices')
if choices:
return random.choice(choices)
else:
nums = [str(xunit.any_int(min_value=0, max_value=255)) for _ in xrange(0, 4)]
return ".".join(nums) | def ipaddress_field_data(field, **kwargs):
"""
Return random value for IPAddressField
>>> result = any_form_field(forms.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> import re
>>> re.match(ipv4_re, result) is not None
True
"""
choices = kwargs.get('choices')
if choices:
return random.choice(choices)
else:
nums = [str(xunit.any_int(min_value=0, max_value=255)) for _ in xrange(0, 4)]
return ".".join(nums) | [
"Return",
"random",
"value",
"for",
"IPAddressField",
">>>",
"result",
"=",
"any_form_field",
"(",
"forms",
".",
"IPAddressField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">",
">>>",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"ipv4_re",
">>>",
"import",
"re",
">>>",
"re",
".",
"match",
"(",
"ipv4_re",
"result",
")",
"is",
"not",
"None",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L236-L253 | [
"def",
"ipaddress_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"'choices'",
")",
"if",
"choices",
":",
"return",
"random",
".",
"choice",
"(",
"choices",
")",
"else",
":",
"nums",
"=",
"[",
"str",
"(",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"255",
")",
")",
"for",
"_",
"in",
"xrange",
"(",
"0",
",",
"4",
")",
"]",
"return",
"\".\"",
".",
"join",
"(",
"nums",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | slug_field_data | Return random value for SlugField
>>> result = any_form_field(forms.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> import re
>>> re.match(slug_re, result) is not None
True | django_any/forms.py | def slug_field_data(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_form_field(forms.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> import re
>>> re.match(slug_re, result) is not None
True
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length or 20)
from string import ascii_letters, digits
letters = ascii_letters + digits + '_-'
return xunit.any_string(letters = letters, min_length = min_length, max_length = max_length) | def slug_field_data(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_form_field(forms.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> import re
>>> re.match(slug_re, result) is not None
True
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length or 20)
from string import ascii_letters, digits
letters = ascii_letters + digits + '_-'
return xunit.any_string(letters = letters, min_length = min_length, max_length = max_length) | [
"Return",
"random",
"value",
"for",
"SlugField",
">>>",
"result",
"=",
"any_form_field",
"(",
"forms",
".",
"SlugField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">",
">>>",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"slug_re",
">>>",
"import",
"re",
">>>",
"re",
".",
"match",
"(",
"slug_re",
"result",
")",
"is",
"not",
"None",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L271-L288 | [
"def",
"slug_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_length",
"=",
"kwargs",
".",
"get",
"(",
"'min_length'",
",",
"1",
")",
"max_length",
"=",
"kwargs",
".",
"get",
"(",
"'max_length'",
",",
"field",
".",
"max_length",
"or",
"20",
")",
"from",
"string",
"import",
"ascii_letters",
",",
"digits",
"letters",
"=",
"ascii_letters",
"+",
"digits",
"+",
"'_-'",
"return",
"xunit",
".",
"any_string",
"(",
"letters",
"=",
"letters",
",",
"min_length",
"=",
"min_length",
",",
"max_length",
"=",
"max_length",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | time_field_data | Return random value for TimeField
>>> result = any_form_field(forms.TimeField())
>>> type(result)
<type 'str'> | django_any/forms.py | def time_field_data(field, **kwargs):
"""
Return random value for TimeField
>>> result = any_form_field(forms.TimeField())
>>> type(result)
<type 'str'>
"""
time_format = random.choice(field.input_formats or formats.get_format('TIME_INPUT_FORMATS'))
return time(xunit.any_int(min_value=0, max_value=23),
xunit.any_int(min_value=0, max_value=59),
xunit.any_int(min_value=0, max_value=59)).strftime(time_format) | def time_field_data(field, **kwargs):
"""
Return random value for TimeField
>>> result = any_form_field(forms.TimeField())
>>> type(result)
<type 'str'>
"""
time_format = random.choice(field.input_formats or formats.get_format('TIME_INPUT_FORMATS'))
return time(xunit.any_int(min_value=0, max_value=23),
xunit.any_int(min_value=0, max_value=59),
xunit.any_int(min_value=0, max_value=59)).strftime(time_format) | [
"Return",
"random",
"value",
"for",
"TimeField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L316-L328 | [
"def",
"time_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"time_format",
"=",
"random",
".",
"choice",
"(",
"field",
".",
"input_formats",
"or",
"formats",
".",
"get_format",
"(",
"'TIME_INPUT_FORMATS'",
")",
")",
"return",
"time",
"(",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"23",
")",
",",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"59",
")",
",",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"59",
")",
")",
".",
"strftime",
"(",
"time_format",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | choice_field_data | Return random value for ChoiceField
>>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')]
>>> result = any_form_field(forms.ChoiceField(choices=CHOICES))
>>> type(result)
<type 'str'>
>>> result in ['YNG', 'OLD']
True
>>> typed_result = any_form_field(forms.TypedChoiceField(choices=CHOICES))
>>> typed_result in ['YNG', 'OLD']
True | django_any/forms.py | def choice_field_data(field, **kwargs):
"""
Return random value for ChoiceField
>>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')]
>>> result = any_form_field(forms.ChoiceField(choices=CHOICES))
>>> type(result)
<type 'str'>
>>> result in ['YNG', 'OLD']
True
>>> typed_result = any_form_field(forms.TypedChoiceField(choices=CHOICES))
>>> typed_result in ['YNG', 'OLD']
True
"""
if field.choices:
return str(random.choice(list(valid_choices(field.choices))))
return 'None' | def choice_field_data(field, **kwargs):
"""
Return random value for ChoiceField
>>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')]
>>> result = any_form_field(forms.ChoiceField(choices=CHOICES))
>>> type(result)
<type 'str'>
>>> result in ['YNG', 'OLD']
True
>>> typed_result = any_form_field(forms.TypedChoiceField(choices=CHOICES))
>>> typed_result in ['YNG', 'OLD']
True
"""
if field.choices:
return str(random.choice(list(valid_choices(field.choices))))
return 'None' | [
"Return",
"random",
"value",
"for",
"ChoiceField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L333-L349 | [
"def",
"choice_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"field",
".",
"choices",
":",
"return",
"str",
"(",
"random",
".",
"choice",
"(",
"list",
"(",
"valid_choices",
"(",
"field",
".",
"choices",
")",
")",
")",
")",
"return",
"'None'"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | multiple_choice_field_data | Return random value for MultipleChoiceField
>>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')]
>>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES))
>>> type(result)
<type 'str'> | django_any/forms.py | def multiple_choice_field_data(field, **kwargs):
"""
Return random value for MultipleChoiceField
>>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')]
>>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES))
>>> type(result)
<type 'str'>
"""
if field.choices:
from django_any.functions import valid_choices
l = list(valid_choices(field.choices))
random.shuffle(l)
choices = []
count = xunit.any_int(min_value=1, max_value=len(field.choices))
for i in xrange(0, count):
choices.append(l[i])
return ' '.join(choices)
return 'None' | def multiple_choice_field_data(field, **kwargs):
"""
Return random value for MultipleChoiceField
>>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')]
>>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES))
>>> type(result)
<type 'str'>
"""
if field.choices:
from django_any.functions import valid_choices
l = list(valid_choices(field.choices))
random.shuffle(l)
choices = []
count = xunit.any_int(min_value=1, max_value=len(field.choices))
for i in xrange(0, count):
choices.append(l[i])
return ' '.join(choices)
return 'None' | [
"Return",
"random",
"value",
"for",
"MultipleChoiceField"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L353-L371 | [
"def",
"multiple_choice_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"field",
".",
"choices",
":",
"from",
"django_any",
".",
"functions",
"import",
"valid_choices",
"l",
"=",
"list",
"(",
"valid_choices",
"(",
"field",
".",
"choices",
")",
")",
"random",
".",
"shuffle",
"(",
"l",
")",
"choices",
"=",
"[",
"]",
"count",
"=",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"1",
",",
"max_value",
"=",
"len",
"(",
"field",
".",
"choices",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"count",
")",
":",
"choices",
".",
"append",
"(",
"l",
"[",
"i",
"]",
")",
"return",
"' '",
".",
"join",
"(",
"choices",
")",
"return",
"'None'"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | model_choice_field_data | Return one of first ten items for field queryset | django_any/forms.py | def model_choice_field_data(field, **kwargs):
"""
Return one of first ten items for field queryset
"""
data = list(field.queryset[:10])
if data:
return random.choice(data)
else:
raise TypeError('No %s available in queryset' % field.queryset.model) | def model_choice_field_data(field, **kwargs):
"""
Return one of first ten items for field queryset
"""
data = list(field.queryset[:10])
if data:
return random.choice(data)
else:
raise TypeError('No %s available in queryset' % field.queryset.model) | [
"Return",
"one",
"of",
"first",
"ten",
"items",
"for",
"field",
"queryset"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L375-L383 | [
"def",
"model_choice_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"list",
"(",
"field",
".",
"queryset",
"[",
":",
"10",
"]",
")",
"if",
"data",
":",
"return",
"random",
".",
"choice",
"(",
"data",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'No %s available in queryset'",
"%",
"field",
".",
"queryset",
".",
"model",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | encode_xml | Encodes an OpenMath object as an XML node.
:param obj: OpenMath object (or related item) to encode as XML.
:type obj: OMAny
:param ns: Namespace prefix to use for
http://www.openmath.org/OpenMath", or None if default namespace.
:type ns: str, None
:return: The XML node representing the OpenMath data structure.
:rtype: etree._Element | openmath/encoder.py | def encode_xml(obj, E=None):
""" Encodes an OpenMath object as an XML node.
:param obj: OpenMath object (or related item) to encode as XML.
:type obj: OMAny
:param ns: Namespace prefix to use for
http://www.openmath.org/OpenMath", or None if default namespace.
:type ns: str, None
:return: The XML node representing the OpenMath data structure.
:rtype: etree._Element
"""
if E is None:
E = default_E
elif isinstance(E, str):
E = ElementMaker(namespace=xml.openmath_ns,
nsmap={ E: xml.openmath_ns })
name = ""
attr = {}
children = []
if isinstance(obj, om.CDBaseAttribute) and obj.cdbase is not None:
attr["cdbase"] = obj.cdbase
if isinstance(obj, om.CommonAttributes) and obj.id is not None:
attr["id"] = obj.id
# Wrapper object
if isinstance(obj, om.OMObject):
children.append(encode_xml(obj.omel, E))
attr["version"] = obj.version
# Derived Objects
elif isinstance(obj, om.OMReference):
attr["href"] = obj.href
# Basic Objects
elif isinstance(obj, om.OMInteger):
children.append(str(obj.integer))
elif isinstance(obj, om.OMFloat):
attr["dec"] = obj.double
elif isinstance(obj, om.OMString):
if obj.string is not None:
children.append(str(obj.string))
elif isinstance(obj, om.OMBytes):
children.append(base64.b64encode(obj.bytes).decode('ascii'))
elif isinstance(obj, om.OMSymbol):
attr["name"] = obj.name
attr["cd"] = obj.cd
elif isinstance(obj, om.OMVariable):
attr["name"] = obj.name
# Derived Elements
elif isinstance(obj, om.OMForeign):
attr["encoding"] = obj.encoding
children.append(str(obj.obj))
# Compound Elements
elif isinstance(obj, om.OMApplication):
children = [encode_xml(obj.elem, E)]
children.extend(encode_xml(x, E) for x in obj.arguments)
elif isinstance(obj, om.OMAttribution):
children = [encode_xml(obj.pairs, E), encode_xml(obj.obj, E)]
elif isinstance(obj, om.OMAttributionPairs):
for (k, v) in obj.pairs:
children.append(encode_xml(k, E))
children.append(encode_xml(v, E))
elif isinstance(obj, om.OMBinding):
children = [
encode_xml(obj.binder, E),
encode_xml(obj.vars, E),
encode_xml(obj.obj, E)
]
elif isinstance(obj, om.OMBindVariables):
children = [encode_xml(x, E) for x in obj.vars]
elif isinstance(obj, om.OMAttVar):
children = [encode_xml(obj.pairs, E), encode_xml(obj.obj, E)]
elif isinstance(obj, om.OMError):
children = [encode_xml(obj.name, E)]
children.extend(encode_xml(x, E) for x in obj.params)
else:
raise TypeError("Expected obj to be of type OMAny, found %s." % obj.__class__.__name__)
attr = dict((k,str(v)) for k, v in attr.items() if v is not None)
return E(xml.object_to_tag(obj), *children, **attr) | def encode_xml(obj, E=None):
""" Encodes an OpenMath object as an XML node.
:param obj: OpenMath object (or related item) to encode as XML.
:type obj: OMAny
:param ns: Namespace prefix to use for
http://www.openmath.org/OpenMath", or None if default namespace.
:type ns: str, None
:return: The XML node representing the OpenMath data structure.
:rtype: etree._Element
"""
if E is None:
E = default_E
elif isinstance(E, str):
E = ElementMaker(namespace=xml.openmath_ns,
nsmap={ E: xml.openmath_ns })
name = ""
attr = {}
children = []
if isinstance(obj, om.CDBaseAttribute) and obj.cdbase is not None:
attr["cdbase"] = obj.cdbase
if isinstance(obj, om.CommonAttributes) and obj.id is not None:
attr["id"] = obj.id
# Wrapper object
if isinstance(obj, om.OMObject):
children.append(encode_xml(obj.omel, E))
attr["version"] = obj.version
# Derived Objects
elif isinstance(obj, om.OMReference):
attr["href"] = obj.href
# Basic Objects
elif isinstance(obj, om.OMInteger):
children.append(str(obj.integer))
elif isinstance(obj, om.OMFloat):
attr["dec"] = obj.double
elif isinstance(obj, om.OMString):
if obj.string is not None:
children.append(str(obj.string))
elif isinstance(obj, om.OMBytes):
children.append(base64.b64encode(obj.bytes).decode('ascii'))
elif isinstance(obj, om.OMSymbol):
attr["name"] = obj.name
attr["cd"] = obj.cd
elif isinstance(obj, om.OMVariable):
attr["name"] = obj.name
# Derived Elements
elif isinstance(obj, om.OMForeign):
attr["encoding"] = obj.encoding
children.append(str(obj.obj))
# Compound Elements
elif isinstance(obj, om.OMApplication):
children = [encode_xml(obj.elem, E)]
children.extend(encode_xml(x, E) for x in obj.arguments)
elif isinstance(obj, om.OMAttribution):
children = [encode_xml(obj.pairs, E), encode_xml(obj.obj, E)]
elif isinstance(obj, om.OMAttributionPairs):
for (k, v) in obj.pairs:
children.append(encode_xml(k, E))
children.append(encode_xml(v, E))
elif isinstance(obj, om.OMBinding):
children = [
encode_xml(obj.binder, E),
encode_xml(obj.vars, E),
encode_xml(obj.obj, E)
]
elif isinstance(obj, om.OMBindVariables):
children = [encode_xml(x, E) for x in obj.vars]
elif isinstance(obj, om.OMAttVar):
children = [encode_xml(obj.pairs, E), encode_xml(obj.obj, E)]
elif isinstance(obj, om.OMError):
children = [encode_xml(obj.name, E)]
children.extend(encode_xml(x, E) for x in obj.params)
else:
raise TypeError("Expected obj to be of type OMAny, found %s." % obj.__class__.__name__)
attr = dict((k,str(v)) for k, v in attr.items() if v is not None)
return E(xml.object_to_tag(obj), *children, **attr) | [
"Encodes",
"an",
"OpenMath",
"object",
"as",
"an",
"XML",
"node",
"."
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/encoder.py#L14-L104 | [
"def",
"encode_xml",
"(",
"obj",
",",
"E",
"=",
"None",
")",
":",
"if",
"E",
"is",
"None",
":",
"E",
"=",
"default_E",
"elif",
"isinstance",
"(",
"E",
",",
"str",
")",
":",
"E",
"=",
"ElementMaker",
"(",
"namespace",
"=",
"xml",
".",
"openmath_ns",
",",
"nsmap",
"=",
"{",
"E",
":",
"xml",
".",
"openmath_ns",
"}",
")",
"name",
"=",
"\"\"",
"attr",
"=",
"{",
"}",
"children",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"om",
".",
"CDBaseAttribute",
")",
"and",
"obj",
".",
"cdbase",
"is",
"not",
"None",
":",
"attr",
"[",
"\"cdbase\"",
"]",
"=",
"obj",
".",
"cdbase",
"if",
"isinstance",
"(",
"obj",
",",
"om",
".",
"CommonAttributes",
")",
"and",
"obj",
".",
"id",
"is",
"not",
"None",
":",
"attr",
"[",
"\"id\"",
"]",
"=",
"obj",
".",
"id",
"# Wrapper object",
"if",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMObject",
")",
":",
"children",
".",
"append",
"(",
"encode_xml",
"(",
"obj",
".",
"omel",
",",
"E",
")",
")",
"attr",
"[",
"\"version\"",
"]",
"=",
"obj",
".",
"version",
"# Derived Objects",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMReference",
")",
":",
"attr",
"[",
"\"href\"",
"]",
"=",
"obj",
".",
"href",
"# Basic Objects",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMInteger",
")",
":",
"children",
".",
"append",
"(",
"str",
"(",
"obj",
".",
"integer",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMFloat",
")",
":",
"attr",
"[",
"\"dec\"",
"]",
"=",
"obj",
".",
"double",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMString",
")",
":",
"if",
"obj",
".",
"string",
"is",
"not",
"None",
":",
"children",
".",
"append",
"(",
"str",
"(",
"obj",
".",
"string",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMBytes",
")",
":",
"children",
".",
"append",
"(",
"base64",
".",
"b64encode",
"(",
"obj",
".",
"bytes",
")",
".",
"decode",
"(",
"'ascii'",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMSymbol",
")",
":",
"attr",
"[",
"\"name\"",
"]",
"=",
"obj",
".",
"name",
"attr",
"[",
"\"cd\"",
"]",
"=",
"obj",
".",
"cd",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMVariable",
")",
":",
"attr",
"[",
"\"name\"",
"]",
"=",
"obj",
".",
"name",
"# Derived Elements",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMForeign",
")",
":",
"attr",
"[",
"\"encoding\"",
"]",
"=",
"obj",
".",
"encoding",
"children",
".",
"append",
"(",
"str",
"(",
"obj",
".",
"obj",
")",
")",
"# Compound Elements",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMApplication",
")",
":",
"children",
"=",
"[",
"encode_xml",
"(",
"obj",
".",
"elem",
",",
"E",
")",
"]",
"children",
".",
"extend",
"(",
"encode_xml",
"(",
"x",
",",
"E",
")",
"for",
"x",
"in",
"obj",
".",
"arguments",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMAttribution",
")",
":",
"children",
"=",
"[",
"encode_xml",
"(",
"obj",
".",
"pairs",
",",
"E",
")",
",",
"encode_xml",
"(",
"obj",
".",
"obj",
",",
"E",
")",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMAttributionPairs",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"obj",
".",
"pairs",
":",
"children",
".",
"append",
"(",
"encode_xml",
"(",
"k",
",",
"E",
")",
")",
"children",
".",
"append",
"(",
"encode_xml",
"(",
"v",
",",
"E",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMBinding",
")",
":",
"children",
"=",
"[",
"encode_xml",
"(",
"obj",
".",
"binder",
",",
"E",
")",
",",
"encode_xml",
"(",
"obj",
".",
"vars",
",",
"E",
")",
",",
"encode_xml",
"(",
"obj",
".",
"obj",
",",
"E",
")",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMBindVariables",
")",
":",
"children",
"=",
"[",
"encode_xml",
"(",
"x",
",",
"E",
")",
"for",
"x",
"in",
"obj",
".",
"vars",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMAttVar",
")",
":",
"children",
"=",
"[",
"encode_xml",
"(",
"obj",
".",
"pairs",
",",
"E",
")",
",",
"encode_xml",
"(",
"obj",
".",
"obj",
",",
"E",
")",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"om",
".",
"OMError",
")",
":",
"children",
"=",
"[",
"encode_xml",
"(",
"obj",
".",
"name",
",",
"E",
")",
"]",
"children",
".",
"extend",
"(",
"encode_xml",
"(",
"x",
",",
"E",
")",
"for",
"x",
"in",
"obj",
".",
"params",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Expected obj to be of type OMAny, found %s.\"",
"%",
"obj",
".",
"__class__",
".",
"__name__",
")",
"attr",
"=",
"dict",
"(",
"(",
"k",
",",
"str",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"attr",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
")",
"return",
"E",
"(",
"xml",
".",
"object_to_tag",
"(",
"obj",
")",
",",
"*",
"children",
",",
"*",
"*",
"attr",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | encode_bytes | Encodes an OpenMath element into a string.
:param obj: Object to encode as string.
:type obj: OMAny
:rtype: bytes | openmath/encoder.py | def encode_bytes(obj, nsprefix=None):
""" Encodes an OpenMath element into a string.
:param obj: Object to encode as string.
:type obj: OMAny
:rtype: bytes
"""
node = encode_xml(obj, nsprefix)
return etree.tostring(node) | def encode_bytes(obj, nsprefix=None):
""" Encodes an OpenMath element into a string.
:param obj: Object to encode as string.
:type obj: OMAny
:rtype: bytes
"""
node = encode_xml(obj, nsprefix)
return etree.tostring(node) | [
"Encodes",
"an",
"OpenMath",
"element",
"into",
"a",
"string",
"."
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/encoder.py#L107-L117 | [
"def",
"encode_bytes",
"(",
"obj",
",",
"nsprefix",
"=",
"None",
")",
":",
"node",
"=",
"encode_xml",
"(",
"obj",
",",
"nsprefix",
")",
"return",
"etree",
".",
"tostring",
"(",
"node",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | decode_bytes | Decodes a stream into an OpenMath object.
:param xml: XML to decode.
:type xml: bytes
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny | openmath/decoder.py | def decode_bytes(xml, validator=None, snippet=False):
""" Decodes a stream into an OpenMath object.
:param xml: XML to decode.
:type xml: bytes
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny
"""
return decode_stream(io.BytesIO(xml), validator, snippet) | def decode_bytes(xml, validator=None, snippet=False):
""" Decodes a stream into an OpenMath object.
:param xml: XML to decode.
:type xml: bytes
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny
"""
return decode_stream(io.BytesIO(xml), validator, snippet) | [
"Decodes",
"a",
"stream",
"into",
"an",
"OpenMath",
"object",
"."
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/decoder.py#L10-L23 | [
"def",
"decode_bytes",
"(",
"xml",
",",
"validator",
"=",
"None",
",",
"snippet",
"=",
"False",
")",
":",
"return",
"decode_stream",
"(",
"io",
".",
"BytesIO",
"(",
"xml",
")",
",",
"validator",
",",
"snippet",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | decode_stream | Decodes a stream into an OpenMath object.
:param stream: Stream to decode.
:type stream: Any
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny | openmath/decoder.py | def decode_stream(stream, validator=None, snippet=False):
""" Decodes a stream into an OpenMath object.
:param stream: Stream to decode.
:type stream: Any
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny
"""
# TODO: Complete the docstring above
tree = etree.parse(stream)
if validator is not None:
validator.assertValid(tree)
root = tree.getroot()
v = root.get("version")
if not snippet and (not v or v != "2.0"):
raise ValueError("Only OpenMath 2.0 is supported")
return decode_xml(root) | def decode_stream(stream, validator=None, snippet=False):
""" Decodes a stream into an OpenMath object.
:param stream: Stream to decode.
:type stream: Any
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny
"""
# TODO: Complete the docstring above
tree = etree.parse(stream)
if validator is not None:
validator.assertValid(tree)
root = tree.getroot()
v = root.get("version")
if not snippet and (not v or v != "2.0"):
raise ValueError("Only OpenMath 2.0 is supported")
return decode_xml(root) | [
"Decodes",
"a",
"stream",
"into",
"an",
"OpenMath",
"object",
"."
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/decoder.py#L25-L51 | [
"def",
"decode_stream",
"(",
"stream",
",",
"validator",
"=",
"None",
",",
"snippet",
"=",
"False",
")",
":",
"# TODO: Complete the docstring above",
"tree",
"=",
"etree",
".",
"parse",
"(",
"stream",
")",
"if",
"validator",
"is",
"not",
"None",
":",
"validator",
".",
"assertValid",
"(",
"tree",
")",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"v",
"=",
"root",
".",
"get",
"(",
"\"version\"",
")",
"if",
"not",
"snippet",
"and",
"(",
"not",
"v",
"or",
"v",
"!=",
"\"2.0\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Only OpenMath 2.0 is supported\"",
")",
"return",
"decode_xml",
"(",
"root",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | decode_xml | Decodes an XML element into an OpenMath object.
:param elem: Element to decode.
:type elem: etree._Element
:param _in_bind: Internal flag used to indicate if we should decode within
an OMBind.
:type _in_bind: bool
:rtype: OMAny | openmath/decoder.py | def decode_xml(elem, _in_bind = False):
""" Decodes an XML element into an OpenMath object.
:param elem: Element to decode.
:type elem: etree._Element
:param _in_bind: Internal flag used to indicate if we should decode within
an OMBind.
:type _in_bind: bool
:rtype: OMAny
"""
obj = xml.tag_to_object(elem)
attrs = {}
def a2d(*props):
for p in props:
attrs[p] = elem.get(p)
if issubclass(obj, om.CommonAttributes):
a2d("id")
if issubclass(obj, om.CDBaseAttribute):
a2d("cdbase")
# Root Object
if issubclass(obj, om.OMObject):
a2d("version")
attrs["omel"] = decode_xml(elem[0])
# Reference Objects
elif issubclass(obj, om.OMReference):
a2d("href")
# Basic Objects
elif issubclass(obj, om.OMInteger):
attrs["integer"] = int(elem.text)
elif issubclass(obj, om.OMFloat):
# TODO: Support Hex
attrs["double"] = float(elem.get('dec'))
elif issubclass(obj, om.OMString):
attrs["string"] = elem.text
elif issubclass(obj, om.OMBytes):
try:
attrs["bytes"] = base64.b64decode(elem.text)
except TypeError:
attrs["bytes"] = base64.b64decode(bytes(elem.text, "ascii"))
elif issubclass(obj, om.OMSymbol):
a2d("name", "cd")
elif issubclass(obj, om.OMVariable):
a2d("name")
# Derived Elements
elif issubclass(obj, om.OMForeign):
attrs["obj"] = elem.text
a2d("encoding")
# Compound Elements
elif issubclass(obj, om.OMApplication):
attrs["elem"] = decode_xml(elem[0])
attrs["arguments"] = list(map(decode_xml, elem[1:]))
elif issubclass(obj, om.OMAttribution):
attrs["pairs"] = decode_xml(elem[0])
attrs["obj"] = decode_xml(elem[1])
elif issubclass(obj, om.OMAttributionPairs):
if not _in_bind:
attrs["pairs"] = [(decode_xml(k), decode_xml(v)) for k, v in zip(elem[::2], elem[1::2])]
else:
obj = om.OMAttVar
attrs["pairs"] = decode_xml(elem[0], True)
attrs["obj"] = decode_xml(elem[1], True)
elif issubclass(obj, om.OMBinding):
attrs["binder"] = decode_xml(elem[0])
attrs["vars"] = decode_xml(elem[1])
attrs["obj"] = decode_xml(elem[2])
elif issubclass(obj, om.OMBindVariables):
attrs["vars"] = list(map(lambda x:decode_xml(x, True), elem[:]))
elif issubclass(obj, om.OMError):
attrs["name"] = decode_xml(elem[0])
attrs["params"] = list(map(decode_xml, elem[1:]))
else:
raise TypeError("Expected OMAny, found %s." % obj.__name__)
return obj(**attrs) | def decode_xml(elem, _in_bind = False):
""" Decodes an XML element into an OpenMath object.
:param elem: Element to decode.
:type elem: etree._Element
:param _in_bind: Internal flag used to indicate if we should decode within
an OMBind.
:type _in_bind: bool
:rtype: OMAny
"""
obj = xml.tag_to_object(elem)
attrs = {}
def a2d(*props):
for p in props:
attrs[p] = elem.get(p)
if issubclass(obj, om.CommonAttributes):
a2d("id")
if issubclass(obj, om.CDBaseAttribute):
a2d("cdbase")
# Root Object
if issubclass(obj, om.OMObject):
a2d("version")
attrs["omel"] = decode_xml(elem[0])
# Reference Objects
elif issubclass(obj, om.OMReference):
a2d("href")
# Basic Objects
elif issubclass(obj, om.OMInteger):
attrs["integer"] = int(elem.text)
elif issubclass(obj, om.OMFloat):
# TODO: Support Hex
attrs["double"] = float(elem.get('dec'))
elif issubclass(obj, om.OMString):
attrs["string"] = elem.text
elif issubclass(obj, om.OMBytes):
try:
attrs["bytes"] = base64.b64decode(elem.text)
except TypeError:
attrs["bytes"] = base64.b64decode(bytes(elem.text, "ascii"))
elif issubclass(obj, om.OMSymbol):
a2d("name", "cd")
elif issubclass(obj, om.OMVariable):
a2d("name")
# Derived Elements
elif issubclass(obj, om.OMForeign):
attrs["obj"] = elem.text
a2d("encoding")
# Compound Elements
elif issubclass(obj, om.OMApplication):
attrs["elem"] = decode_xml(elem[0])
attrs["arguments"] = list(map(decode_xml, elem[1:]))
elif issubclass(obj, om.OMAttribution):
attrs["pairs"] = decode_xml(elem[0])
attrs["obj"] = decode_xml(elem[1])
elif issubclass(obj, om.OMAttributionPairs):
if not _in_bind:
attrs["pairs"] = [(decode_xml(k), decode_xml(v)) for k, v in zip(elem[::2], elem[1::2])]
else:
obj = om.OMAttVar
attrs["pairs"] = decode_xml(elem[0], True)
attrs["obj"] = decode_xml(elem[1], True)
elif issubclass(obj, om.OMBinding):
attrs["binder"] = decode_xml(elem[0])
attrs["vars"] = decode_xml(elem[1])
attrs["obj"] = decode_xml(elem[2])
elif issubclass(obj, om.OMBindVariables):
attrs["vars"] = list(map(lambda x:decode_xml(x, True), elem[:]))
elif issubclass(obj, om.OMError):
attrs["name"] = decode_xml(elem[0])
attrs["params"] = list(map(decode_xml, elem[1:]))
else:
raise TypeError("Expected OMAny, found %s." % obj.__name__)
return obj(**attrs) | [
"Decodes",
"an",
"XML",
"element",
"into",
"an",
"OpenMath",
"object",
"."
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/decoder.py#L53-L137 | [
"def",
"decode_xml",
"(",
"elem",
",",
"_in_bind",
"=",
"False",
")",
":",
"obj",
"=",
"xml",
".",
"tag_to_object",
"(",
"elem",
")",
"attrs",
"=",
"{",
"}",
"def",
"a2d",
"(",
"*",
"props",
")",
":",
"for",
"p",
"in",
"props",
":",
"attrs",
"[",
"p",
"]",
"=",
"elem",
".",
"get",
"(",
"p",
")",
"if",
"issubclass",
"(",
"obj",
",",
"om",
".",
"CommonAttributes",
")",
":",
"a2d",
"(",
"\"id\"",
")",
"if",
"issubclass",
"(",
"obj",
",",
"om",
".",
"CDBaseAttribute",
")",
":",
"a2d",
"(",
"\"cdbase\"",
")",
"# Root Object",
"if",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMObject",
")",
":",
"a2d",
"(",
"\"version\"",
")",
"attrs",
"[",
"\"omel\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"0",
"]",
")",
"# Reference Objects",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMReference",
")",
":",
"a2d",
"(",
"\"href\"",
")",
"# Basic Objects",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMInteger",
")",
":",
"attrs",
"[",
"\"integer\"",
"]",
"=",
"int",
"(",
"elem",
".",
"text",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMFloat",
")",
":",
"# TODO: Support Hex",
"attrs",
"[",
"\"double\"",
"]",
"=",
"float",
"(",
"elem",
".",
"get",
"(",
"'dec'",
")",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMString",
")",
":",
"attrs",
"[",
"\"string\"",
"]",
"=",
"elem",
".",
"text",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMBytes",
")",
":",
"try",
":",
"attrs",
"[",
"\"bytes\"",
"]",
"=",
"base64",
".",
"b64decode",
"(",
"elem",
".",
"text",
")",
"except",
"TypeError",
":",
"attrs",
"[",
"\"bytes\"",
"]",
"=",
"base64",
".",
"b64decode",
"(",
"bytes",
"(",
"elem",
".",
"text",
",",
"\"ascii\"",
")",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMSymbol",
")",
":",
"a2d",
"(",
"\"name\"",
",",
"\"cd\"",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMVariable",
")",
":",
"a2d",
"(",
"\"name\"",
")",
"# Derived Elements",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMForeign",
")",
":",
"attrs",
"[",
"\"obj\"",
"]",
"=",
"elem",
".",
"text",
"a2d",
"(",
"\"encoding\"",
")",
"# Compound Elements",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMApplication",
")",
":",
"attrs",
"[",
"\"elem\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"0",
"]",
")",
"attrs",
"[",
"\"arguments\"",
"]",
"=",
"list",
"(",
"map",
"(",
"decode_xml",
",",
"elem",
"[",
"1",
":",
"]",
")",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMAttribution",
")",
":",
"attrs",
"[",
"\"pairs\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"0",
"]",
")",
"attrs",
"[",
"\"obj\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"1",
"]",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMAttributionPairs",
")",
":",
"if",
"not",
"_in_bind",
":",
"attrs",
"[",
"\"pairs\"",
"]",
"=",
"[",
"(",
"decode_xml",
"(",
"k",
")",
",",
"decode_xml",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"zip",
"(",
"elem",
"[",
":",
":",
"2",
"]",
",",
"elem",
"[",
"1",
":",
":",
"2",
"]",
")",
"]",
"else",
":",
"obj",
"=",
"om",
".",
"OMAttVar",
"attrs",
"[",
"\"pairs\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"0",
"]",
",",
"True",
")",
"attrs",
"[",
"\"obj\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"1",
"]",
",",
"True",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMBinding",
")",
":",
"attrs",
"[",
"\"binder\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"0",
"]",
")",
"attrs",
"[",
"\"vars\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"1",
"]",
")",
"attrs",
"[",
"\"obj\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"2",
"]",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMBindVariables",
")",
":",
"attrs",
"[",
"\"vars\"",
"]",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"decode_xml",
"(",
"x",
",",
"True",
")",
",",
"elem",
"[",
":",
"]",
")",
")",
"elif",
"issubclass",
"(",
"obj",
",",
"om",
".",
"OMError",
")",
":",
"attrs",
"[",
"\"name\"",
"]",
"=",
"decode_xml",
"(",
"elem",
"[",
"0",
"]",
")",
"attrs",
"[",
"\"params\"",
"]",
"=",
"list",
"(",
"map",
"(",
"decode_xml",
",",
"elem",
"[",
"1",
":",
"]",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Expected OMAny, found %s.\"",
"%",
"obj",
".",
"__name__",
")",
"return",
"obj",
"(",
"*",
"*",
"attrs",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | publish | Deploy the app to PYPI.
Args:
msg (str, optional): Description | fabfile.py | def publish(msg="checkpoint: publish package"):
"""Deploy the app to PYPI.
Args:
msg (str, optional): Description
"""
test = check()
if test.succeeded:
# clean()
# push(msg)
sdist = local("python setup.py sdist")
if sdist.succeeded:
build = local(
'python setup.py build && python setup.py bdist_egg')
if build.succeeded:
upload = local("twine upload dist/*")
if upload.succeeded:
tag() | def publish(msg="checkpoint: publish package"):
"""Deploy the app to PYPI.
Args:
msg (str, optional): Description
"""
test = check()
if test.succeeded:
# clean()
# push(msg)
sdist = local("python setup.py sdist")
if sdist.succeeded:
build = local(
'python setup.py build && python setup.py bdist_egg')
if build.succeeded:
upload = local("twine upload dist/*")
if upload.succeeded:
tag() | [
"Deploy",
"the",
"app",
"to",
"PYPI",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/fabfile.py#L42-L59 | [
"def",
"publish",
"(",
"msg",
"=",
"\"checkpoint: publish package\"",
")",
":",
"test",
"=",
"check",
"(",
")",
"if",
"test",
".",
"succeeded",
":",
"# clean()",
"# push(msg)",
"sdist",
"=",
"local",
"(",
"\"python setup.py sdist\"",
")",
"if",
"sdist",
".",
"succeeded",
":",
"build",
"=",
"local",
"(",
"'python setup.py build && python setup.py bdist_egg'",
")",
"if",
"build",
".",
"succeeded",
":",
"upload",
"=",
"local",
"(",
"\"twine upload dist/*\"",
")",
"if",
"upload",
".",
"succeeded",
":",
"tag",
"(",
")"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | tag | Deploy a version tag. | fabfile.py | def tag(version=__version__):
"""Deploy a version tag."""
build = local("git tag {0}".format(version))
if build.succeeded:
local("git push --tags") | def tag(version=__version__):
"""Deploy a version tag."""
build = local("git tag {0}".format(version))
if build.succeeded:
local("git push --tags") | [
"Deploy",
"a",
"version",
"tag",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/fabfile.py#L73-L77 | [
"def",
"tag",
"(",
"version",
"=",
"__version__",
")",
":",
"build",
"=",
"local",
"(",
"\"git tag {0}\"",
".",
"format",
"(",
"version",
")",
")",
"if",
"build",
".",
"succeeded",
":",
"local",
"(",
"\"git push --tags\"",
")"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | any_field_blank | Sometimes return None if field could be blank | django_any/models.py | def any_field_blank(function):
"""
Sometimes return None if field could be blank
"""
def wrapper(field, **kwargs):
if kwargs.get('isnull', False):
return None
if field.blank and random.random < 0.1:
return None
return function(field, **kwargs)
return wrapper | def any_field_blank(function):
"""
Sometimes return None if field could be blank
"""
def wrapper(field, **kwargs):
if kwargs.get('isnull', False):
return None
if field.blank and random.random < 0.1:
return None
return function(field, **kwargs)
return wrapper | [
"Sometimes",
"return",
"None",
"if",
"field",
"could",
"be",
"blank"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L27-L38 | [
"def",
"any_field_blank",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'isnull'",
",",
"False",
")",
":",
"return",
"None",
"if",
"field",
".",
"blank",
"and",
"random",
".",
"random",
"<",
"0.1",
":",
"return",
"None",
"return",
"function",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_field_choices | Selection from field.choices
>>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')]
>>> result = any_field(models.CharField(max_length=3, choices=CHOICES))
>>> result in ['YNG', 'OLD']
True | django_any/models.py | def any_field_choices(function):
"""
Selection from field.choices
>>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')]
>>> result = any_field(models.CharField(max_length=3, choices=CHOICES))
>>> result in ['YNG', 'OLD']
True
"""
def wrapper(field, **kwargs):
if field.choices:
return random.choice(list(valid_choices(field.choices)))
return function(field, **kwargs)
return wrapper | def any_field_choices(function):
"""
Selection from field.choices
>>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')]
>>> result = any_field(models.CharField(max_length=3, choices=CHOICES))
>>> result in ['YNG', 'OLD']
True
"""
def wrapper(field, **kwargs):
if field.choices:
return random.choice(list(valid_choices(field.choices)))
return function(field, **kwargs)
return wrapper | [
"Selection",
"from",
"field",
".",
"choices",
">>>",
"CHOICES",
"=",
"[",
"(",
"YNG",
"Child",
")",
"(",
"OLD",
"Parent",
")",
"]",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"3",
"choices",
"=",
"CHOICES",
"))",
">>>",
"result",
"in",
"[",
"YNG",
"OLD",
"]",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L42-L56 | [
"def",
"any_field_choices",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"field",
".",
"choices",
":",
"return",
"random",
".",
"choice",
"(",
"list",
"(",
"valid_choices",
"(",
"field",
".",
"choices",
")",
")",
")",
"return",
"function",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_biginteger_field | Return random value for BigIntegerField
>>> result = any_field(models.BigIntegerField())
>>> type(result)
<type 'long'> | django_any/models.py | def any_biginteger_field(field, **kwargs):
"""
Return random value for BigIntegerField
>>> result = any_field(models.BigIntegerField())
>>> type(result)
<type 'long'>
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 10**10)
return long(xunit.any_int(min_value=min_value, max_value=max_value)) | def any_biginteger_field(field, **kwargs):
"""
Return random value for BigIntegerField
>>> result = any_field(models.BigIntegerField())
>>> type(result)
<type 'long'>
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 10**10)
return long(xunit.any_int(min_value=min_value, max_value=max_value)) | [
"Return",
"random",
"value",
"for",
"BigIntegerField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"BigIntegerField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"long",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L60-L70 | [
"def",
"any_biginteger_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"1",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"10",
"**",
"10",
")",
"return",
"long",
"(",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_positiveinteger_field | An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True | django_any/models.py | def any_positiveinteger_field(field, **kwargs):
"""
An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 9999)
return xunit.any_int(min_value=min_value, max_value=max_value) | def any_positiveinteger_field(field, **kwargs):
"""
An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 9999)
return xunit.any_int(min_value=min_value, max_value=max_value) | [
"An",
"positive",
"integer",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"PositiveIntegerField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"int",
">",
">>>",
"result",
">",
"0",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L86-L98 | [
"def",
"any_positiveinteger_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"1",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"9999",
")",
"return",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_char_field | Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'> | django_any/models.py | def any_char_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length)
return xunit.any_string(min_length=min_length, max_length=max_length) | def any_char_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length)
return xunit.any_string(min_length=min_length, max_length=max_length) | [
"Return",
"random",
"value",
"for",
"CharField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"10",
"))",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L102-L112 | [
"def",
"any_char_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_length",
"=",
"kwargs",
".",
"get",
"(",
"'min_length'",
",",
"1",
")",
"max_length",
"=",
"kwargs",
".",
"get",
"(",
"'max_length'",
",",
"field",
".",
"max_length",
")",
"return",
"xunit",
".",
"any_string",
"(",
"min_length",
"=",
"min_length",
",",
"max_length",
"=",
"max_length",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_commaseparatedinteger_field | Return random value for CharField
>>> result = any_field(models.CommaSeparatedIntegerField(max_length=10))
>>> type(result)
<type 'str'>
>>> [int(num) for num in result.split(',')] and 'OK'
'OK' | django_any/models.py | def any_commaseparatedinteger_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CommaSeparatedIntegerField(max_length=10))
>>> type(result)
<type 'str'>
>>> [int(num) for num in result.split(',')] and 'OK'
'OK'
"""
nums_count = field.max_length/2
nums = [str(xunit.any_int(min_value=0, max_value=9)) for _ in xrange(0, nums_count)]
return ",".join(nums) | def any_commaseparatedinteger_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CommaSeparatedIntegerField(max_length=10))
>>> type(result)
<type 'str'>
>>> [int(num) for num in result.split(',')] and 'OK'
'OK'
"""
nums_count = field.max_length/2
nums = [str(xunit.any_int(min_value=0, max_value=9)) for _ in xrange(0, nums_count)]
return ",".join(nums) | [
"Return",
"random",
"value",
"for",
"CharField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"CommaSeparatedIntegerField",
"(",
"max_length",
"=",
"10",
"))",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">",
">>>",
"[",
"int",
"(",
"num",
")",
"for",
"num",
"in",
"result",
".",
"split",
"(",
")",
"]",
"and",
"OK",
"OK"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L116-L128 | [
"def",
"any_commaseparatedinteger_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"nums_count",
"=",
"field",
".",
"max_length",
"/",
"2",
"nums",
"=",
"[",
"str",
"(",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"9",
")",
")",
"for",
"_",
"in",
"xrange",
"(",
"0",
",",
"nums_count",
")",
"]",
"return",
"\",\"",
".",
"join",
"(",
"nums",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_date_field | Return random value for DateField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateField())
>>> type(result)
<type 'datetime.date'> | django_any/models.py | def any_date_field(field, **kwargs):
"""
Return random value for DateField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateField())
>>> type(result)
<type 'datetime.date'>
"""
if field.auto_now or field.auto_now_add:
return None
from_date = kwargs.get('from_date', date(1990, 1, 1))
to_date = kwargs.get('to_date', date.today())
return xunit.any_date(from_date=from_date, to_date=to_date) | def any_date_field(field, **kwargs):
"""
Return random value for DateField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateField())
>>> type(result)
<type 'datetime.date'>
"""
if field.auto_now or field.auto_now_add:
return None
from_date = kwargs.get('from_date', date(1990, 1, 1))
to_date = kwargs.get('to_date', date.today())
return xunit.any_date(from_date=from_date, to_date=to_date) | [
"Return",
"random",
"value",
"for",
"DateField",
"skips",
"auto_now",
"and",
"auto_now_add",
"fields",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"DateField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"datetime",
".",
"date",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L132-L145 | [
"def",
"any_date_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"field",
".",
"auto_now",
"or",
"field",
".",
"auto_now_add",
":",
"return",
"None",
"from_date",
"=",
"kwargs",
".",
"get",
"(",
"'from_date'",
",",
"date",
"(",
"1990",
",",
"1",
",",
"1",
")",
")",
"to_date",
"=",
"kwargs",
".",
"get",
"(",
"'to_date'",
",",
"date",
".",
"today",
"(",
")",
")",
"return",
"xunit",
".",
"any_date",
"(",
"from_date",
"=",
"from_date",
",",
"to_date",
"=",
"to_date",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_datetime_field | Return random value for DateTimeField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateTimeField())
>>> type(result)
<type 'datetime.datetime'> | django_any/models.py | def any_datetime_field(field, **kwargs):
"""
Return random value for DateTimeField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateTimeField())
>>> type(result)
<type 'datetime.datetime'>
"""
from_date = kwargs.get('from_date', datetime(1990, 1, 1))
to_date = kwargs.get('to_date', datetime.today())
return xunit.any_datetime(from_date=from_date, to_date=to_date) | def any_datetime_field(field, **kwargs):
"""
Return random value for DateTimeField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateTimeField())
>>> type(result)
<type 'datetime.datetime'>
"""
from_date = kwargs.get('from_date', datetime(1990, 1, 1))
to_date = kwargs.get('to_date', datetime.today())
return xunit.any_datetime(from_date=from_date, to_date=to_date) | [
"Return",
"random",
"value",
"for",
"DateTimeField",
"skips",
"auto_now",
"and",
"auto_now_add",
"fields",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"DateTimeField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"datetime",
".",
"datetime",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L149-L160 | [
"def",
"any_datetime_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
".",
"get",
"(",
"'from_date'",
",",
"datetime",
"(",
"1990",
",",
"1",
",",
"1",
")",
")",
"to_date",
"=",
"kwargs",
".",
"get",
"(",
"'to_date'",
",",
"datetime",
".",
"today",
"(",
")",
")",
"return",
"xunit",
".",
"any_datetime",
"(",
"from_date",
"=",
"from_date",
",",
"to_date",
"=",
"to_date",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_decimal_field | Return random value for DecimalField
>>> result = any_field(models.DecimalField(max_digits=5, decimal_places=2))
>>> type(result)
<class 'decimal.Decimal'> | django_any/models.py | def any_decimal_field(field, **kwargs):
"""
Return random value for DecimalField
>>> result = any_field(models.DecimalField(max_digits=5, decimal_places=2))
>>> type(result)
<class 'decimal.Decimal'>
"""
min_value = kwargs.get('min_value', 0)
max_value = kwargs.get('max_value',
Decimal('%s.%s' % ('9'*(field.max_digits-field.decimal_places),
'9'*field.decimal_places)))
decimal_places = kwargs.get('decimal_places', field.decimal_places)
return xunit.any_decimal(min_value=min_value, max_value=max_value,
decimal_places = decimal_places) | def any_decimal_field(field, **kwargs):
"""
Return random value for DecimalField
>>> result = any_field(models.DecimalField(max_digits=5, decimal_places=2))
>>> type(result)
<class 'decimal.Decimal'>
"""
min_value = kwargs.get('min_value', 0)
max_value = kwargs.get('max_value',
Decimal('%s.%s' % ('9'*(field.max_digits-field.decimal_places),
'9'*field.decimal_places)))
decimal_places = kwargs.get('decimal_places', field.decimal_places)
return xunit.any_decimal(min_value=min_value, max_value=max_value,
decimal_places = decimal_places) | [
"Return",
"random",
"value",
"for",
"DecimalField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"DecimalField",
"(",
"max_digits",
"=",
"5",
"decimal_places",
"=",
"2",
"))",
">>>",
"type",
"(",
"result",
")",
"<class",
"decimal",
".",
"Decimal",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L164-L178 | [
"def",
"any_decimal_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"0",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"Decimal",
"(",
"'%s.%s'",
"%",
"(",
"'9'",
"*",
"(",
"field",
".",
"max_digits",
"-",
"field",
".",
"decimal_places",
")",
",",
"'9'",
"*",
"field",
".",
"decimal_places",
")",
")",
")",
"decimal_places",
"=",
"kwargs",
".",
"get",
"(",
"'decimal_places'",
",",
"field",
".",
"decimal_places",
")",
"return",
"xunit",
".",
"any_decimal",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
",",
"decimal_places",
"=",
"decimal_places",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_email_field | Return random value for EmailField
>>> result = any_field(models.EmailField())
>>> type(result)
<type 'str'>
>>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None
True | django_any/models.py | def any_email_field(field, **kwargs):
"""
Return random value for EmailField
>>> result = any_field(models.EmailField())
>>> type(result)
<type 'str'>
>>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None
True
"""
return "%s@%s.%s" % (xunit.any_string(max_length=10),
xunit.any_string(max_length=10),
xunit.any_string(min_length=2, max_length=3)) | def any_email_field(field, **kwargs):
"""
Return random value for EmailField
>>> result = any_field(models.EmailField())
>>> type(result)
<type 'str'>
>>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None
True
"""
return "%s@%s.%s" % (xunit.any_string(max_length=10),
xunit.any_string(max_length=10),
xunit.any_string(min_length=2, max_length=3)) | [
"Return",
"random",
"value",
"for",
"EmailField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"EmailField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">",
">>>",
"re",
".",
"match",
"(",
"r",
"(",
"?",
":",
"^|",
"\\",
"s",
")",
"[",
"-",
"a",
"-",
"z0",
"-",
"9_",
".",
"]",
"+"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L182-L194 | [
"def",
"any_email_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"\"%s@%s.%s\"",
"%",
"(",
"xunit",
".",
"any_string",
"(",
"max_length",
"=",
"10",
")",
",",
"xunit",
".",
"any_string",
"(",
"max_length",
"=",
"10",
")",
",",
"xunit",
".",
"any_string",
"(",
"min_length",
"=",
"2",
",",
"max_length",
"=",
"3",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_float_field | Return random value for FloatField
>>> result = any_field(models.FloatField())
>>> type(result)
<type 'float'> | django_any/models.py | def any_float_field(field, **kwargs):
"""
Return random value for FloatField
>>> result = any_field(models.FloatField())
>>> type(result)
<type 'float'>
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 100)
precision = kwargs.get('precision', 3)
return xunit.any_float(min_value=min_value, max_value=max_value, precision=precision) | def any_float_field(field, **kwargs):
"""
Return random value for FloatField
>>> result = any_field(models.FloatField())
>>> type(result)
<type 'float'>
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 100)
precision = kwargs.get('precision', 3)
return xunit.any_float(min_value=min_value, max_value=max_value, precision=precision) | [
"Return",
"random",
"value",
"for",
"FloatField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"FloatField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"float",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L198-L209 | [
"def",
"any_float_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"1",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"100",
")",
"precision",
"=",
"kwargs",
".",
"get",
"(",
"'precision'",
",",
"3",
")",
"return",
"xunit",
".",
"any_float",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
",",
"precision",
"=",
"precision",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_file_field | Lookup for nearest existing file | django_any/models.py | def any_file_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = field.storage.listdir(path)
if files:
result_file = random.choice(files)
instance = field.storage.open("%s/%s" % (path, result_file)).file
return FieldFile(instance, field, result_file)
for subdir in subdirs:
result = get_some_file("%s/%s" % (path, subdir))
if result:
return result
result = get_some_file(field.upload_to)
if result is None and not field.null:
raise TypeError("Can't found file in %s for non nullable FileField" % field.upload_to)
return result | def any_file_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = field.storage.listdir(path)
if files:
result_file = random.choice(files)
instance = field.storage.open("%s/%s" % (path, result_file)).file
return FieldFile(instance, field, result_file)
for subdir in subdirs:
result = get_some_file("%s/%s" % (path, subdir))
if result:
return result
result = get_some_file(field.upload_to)
if result is None and not field.null:
raise TypeError("Can't found file in %s for non nullable FileField" % field.upload_to)
return result | [
"Lookup",
"for",
"nearest",
"existing",
"file"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L213-L235 | [
"def",
"any_file_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"get_some_file",
"(",
"path",
")",
":",
"subdirs",
",",
"files",
"=",
"field",
".",
"storage",
".",
"listdir",
"(",
"path",
")",
"if",
"files",
":",
"result_file",
"=",
"random",
".",
"choice",
"(",
"files",
")",
"instance",
"=",
"field",
".",
"storage",
".",
"open",
"(",
"\"%s/%s\"",
"%",
"(",
"path",
",",
"result_file",
")",
")",
".",
"file",
"return",
"FieldFile",
"(",
"instance",
",",
"field",
",",
"result_file",
")",
"for",
"subdir",
"in",
"subdirs",
":",
"result",
"=",
"get_some_file",
"(",
"\"%s/%s\"",
"%",
"(",
"path",
",",
"subdir",
")",
")",
"if",
"result",
":",
"return",
"result",
"result",
"=",
"get_some_file",
"(",
"field",
".",
"upload_to",
")",
"if",
"result",
"is",
"None",
"and",
"not",
"field",
".",
"null",
":",
"raise",
"TypeError",
"(",
"\"Can't found file in %s for non nullable FileField\"",
"%",
"field",
".",
"upload_to",
")",
"return",
"result"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_filepath_field | Lookup for nearest existing file | django_any/models.py | def any_filepath_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = [], []
for entry in os.listdir(path):
entry_path = os.path.join(path, entry)
if os.path.isdir(entry_path):
subdirs.append(entry_path)
else:
if not field.match or re.match(field.match,entry):
files.append(entry_path)
if files:
return random.choice(files)
if field.recursive:
for subdir in subdirs:
result = get_some_file(subdir)
if result:
return result
result = get_some_file(field.path)
if result is None and not field.null:
raise TypeError("Can't found file in %s for non nullable FilePathField" % field.path)
return result | def any_filepath_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = [], []
for entry in os.listdir(path):
entry_path = os.path.join(path, entry)
if os.path.isdir(entry_path):
subdirs.append(entry_path)
else:
if not field.match or re.match(field.match,entry):
files.append(entry_path)
if files:
return random.choice(files)
if field.recursive:
for subdir in subdirs:
result = get_some_file(subdir)
if result:
return result
result = get_some_file(field.path)
if result is None and not field.null:
raise TypeError("Can't found file in %s for non nullable FilePathField" % field.path)
return result | [
"Lookup",
"for",
"nearest",
"existing",
"file"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L239-L266 | [
"def",
"any_filepath_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"get_some_file",
"(",
"path",
")",
":",
"subdirs",
",",
"files",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"entry_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"entry",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"entry_path",
")",
":",
"subdirs",
".",
"append",
"(",
"entry_path",
")",
"else",
":",
"if",
"not",
"field",
".",
"match",
"or",
"re",
".",
"match",
"(",
"field",
".",
"match",
",",
"entry",
")",
":",
"files",
".",
"append",
"(",
"entry_path",
")",
"if",
"files",
":",
"return",
"random",
".",
"choice",
"(",
"files",
")",
"if",
"field",
".",
"recursive",
":",
"for",
"subdir",
"in",
"subdirs",
":",
"result",
"=",
"get_some_file",
"(",
"subdir",
")",
"if",
"result",
":",
"return",
"result",
"result",
"=",
"get_some_file",
"(",
"field",
".",
"path",
")",
"if",
"result",
"is",
"None",
"and",
"not",
"field",
".",
"null",
":",
"raise",
"TypeError",
"(",
"\"Can't found file in %s for non nullable FilePathField\"",
"%",
"field",
".",
"path",
")",
"return",
"result"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_ipaddress_field | Return random value for IPAddressField
>>> result = any_field(models.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> re.match(ipv4_re, result) is not None
True | django_any/models.py | def any_ipaddress_field(field, **kwargs):
"""
Return random value for IPAddressField
>>> result = any_field(models.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> re.match(ipv4_re, result) is not None
True
"""
nums = [str(xunit.any_int(min_value=0, max_value=255)) for _ in xrange(0, 4)]
return ".".join(nums) | def any_ipaddress_field(field, **kwargs):
"""
Return random value for IPAddressField
>>> result = any_field(models.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> re.match(ipv4_re, result) is not None
True
"""
nums = [str(xunit.any_int(min_value=0, max_value=255)) for _ in xrange(0, 4)]
return ".".join(nums) | [
"Return",
"random",
"value",
"for",
"IPAddressField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"IPAddressField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">",
">>>",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"ipv4_re",
">>>",
"re",
".",
"match",
"(",
"ipv4_re",
"result",
")",
"is",
"not",
"None",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L270-L281 | [
"def",
"any_ipaddress_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"nums",
"=",
"[",
"str",
"(",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"255",
")",
")",
"for",
"_",
"in",
"xrange",
"(",
"0",
",",
"4",
")",
"]",
"return",
"\".\"",
".",
"join",
"(",
"nums",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_positivesmallinteger_field | Return random value for PositiveSmallIntegerField
>>> result = any_field(models.PositiveSmallIntegerField())
>>> type(result)
<type 'int'>
>>> result < 256, result > 0
(True, True) | django_any/models.py | def any_positivesmallinteger_field(field, **kwargs):
"""
Return random value for PositiveSmallIntegerField
>>> result = any_field(models.PositiveSmallIntegerField())
>>> type(result)
<type 'int'>
>>> result < 256, result > 0
(True, True)
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 255)
return xunit.any_int(min_value=min_value, max_value=max_value) | def any_positivesmallinteger_field(field, **kwargs):
"""
Return random value for PositiveSmallIntegerField
>>> result = any_field(models.PositiveSmallIntegerField())
>>> type(result)
<type 'int'>
>>> result < 256, result > 0
(True, True)
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 255)
return xunit.any_int(min_value=min_value, max_value=max_value) | [
"Return",
"random",
"value",
"for",
"PositiveSmallIntegerField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"PositiveSmallIntegerField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"int",
">",
">>>",
"result",
"<",
"256",
"result",
">",
"0",
"(",
"True",
"True",
")"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L296-L307 | [
"def",
"any_positivesmallinteger_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"1",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"255",
")",
"return",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_slug_field | Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True | django_any/models.py | def any_slug_field(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True
"""
letters = ascii_letters + digits + '_-'
return xunit.any_string(letters = letters, max_length = field.max_length) | def any_slug_field(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True
"""
letters = ascii_letters + digits + '_-'
return xunit.any_string(letters = letters, max_length = field.max_length) | [
"Return",
"random",
"value",
"for",
"SlugField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"SlugField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"str",
">",
">>>",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"slug_re",
">>>",
"re",
".",
"match",
"(",
"slug_re",
"result",
")",
"is",
"not",
"None",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L311-L322 | [
"def",
"any_slug_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"letters",
"=",
"ascii_letters",
"+",
"digits",
"+",
"'_-'",
"return",
"xunit",
".",
"any_string",
"(",
"letters",
"=",
"letters",
",",
"max_length",
"=",
"field",
".",
"max_length",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_smallinteger_field | Return random value for SmallIntegerValue
>>> result = any_field(models.SmallIntegerField())
>>> type(result)
<type 'int'>
>>> result > -256, result < 256
(True, True) | django_any/models.py | def any_smallinteger_field(field, **kwargs):
"""
Return random value for SmallIntegerValue
>>> result = any_field(models.SmallIntegerField())
>>> type(result)
<type 'int'>
>>> result > -256, result < 256
(True, True)
"""
min_value = kwargs.get('min_value', -255)
max_value = kwargs.get('max_value', 255)
return xunit.any_int(min_value=min_value, max_value=max_value) | def any_smallinteger_field(field, **kwargs):
"""
Return random value for SmallIntegerValue
>>> result = any_field(models.SmallIntegerField())
>>> type(result)
<type 'int'>
>>> result > -256, result < 256
(True, True)
"""
min_value = kwargs.get('min_value', -255)
max_value = kwargs.get('max_value', 255)
return xunit.any_int(min_value=min_value, max_value=max_value) | [
"Return",
"random",
"value",
"for",
"SmallIntegerValue",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"SmallIntegerField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"int",
">",
">>>",
"result",
">",
"-",
"256",
"result",
"<",
"256",
"(",
"True",
"True",
")"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L326-L337 | [
"def",
"any_smallinteger_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"-",
"255",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"255",
")",
"return",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_integer_field | Return random value for IntegerField
>>> result = any_field(models.IntegerField())
>>> type(result)
<type 'int'> | django_any/models.py | def any_integer_field(field, **kwargs):
"""
Return random value for IntegerField
>>> result = any_field(models.IntegerField())
>>> type(result)
<type 'int'>
"""
min_value = kwargs.get('min_value', -10000)
max_value = kwargs.get('max_value', 10000)
return xunit.any_int(min_value=min_value, max_value=max_value) | def any_integer_field(field, **kwargs):
"""
Return random value for IntegerField
>>> result = any_field(models.IntegerField())
>>> type(result)
<type 'int'>
"""
min_value = kwargs.get('min_value', -10000)
max_value = kwargs.get('max_value', 10000)
return xunit.any_int(min_value=min_value, max_value=max_value) | [
"Return",
"random",
"value",
"for",
"IntegerField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"IntegerField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"int",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L341-L350 | [
"def",
"any_integer_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"-",
"10000",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"10000",
")",
"return",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_url_field | Return random value for URLField
>>> result = any_field(models.URLField())
>>> from django.core.validators import URLValidator
>>> re.match(URLValidator.regex, result) is not None
True | django_any/models.py | def any_url_field(field, **kwargs):
"""
Return random value for URLField
>>> result = any_field(models.URLField())
>>> from django.core.validators import URLValidator
>>> re.match(URLValidator.regex, result) is not None
True
"""
url = kwargs.get('url')
if not url:
verified = [validator for validator in field.validators \
if isinstance(validator, validators.URLValidator) and \
validator.verify_exists == True]
if verified:
url = choice(['http://news.yandex.ru/society.html',
'http://video.google.com/?hl=en&tab=wv',
'http://www.microsoft.com/en/us/default.aspx',
'http://habrahabr.ru/company/opera/',
'http://www.apple.com/support/hardware/',
'http://ya.ru',
'http://google.com',
'http://fr.wikipedia.org/wiki/France'])
else:
url = "http://%s.%s/%s" % (
xunit.any_string(max_length=10),
xunit.any_string(min_length=2, max_length=3),
xunit.any_string(max_length=20))
return url | def any_url_field(field, **kwargs):
"""
Return random value for URLField
>>> result = any_field(models.URLField())
>>> from django.core.validators import URLValidator
>>> re.match(URLValidator.regex, result) is not None
True
"""
url = kwargs.get('url')
if not url:
verified = [validator for validator in field.validators \
if isinstance(validator, validators.URLValidator) and \
validator.verify_exists == True]
if verified:
url = choice(['http://news.yandex.ru/society.html',
'http://video.google.com/?hl=en&tab=wv',
'http://www.microsoft.com/en/us/default.aspx',
'http://habrahabr.ru/company/opera/',
'http://www.apple.com/support/hardware/',
'http://ya.ru',
'http://google.com',
'http://fr.wikipedia.org/wiki/France'])
else:
url = "http://%s.%s/%s" % (
xunit.any_string(max_length=10),
xunit.any_string(min_length=2, max_length=3),
xunit.any_string(max_length=20))
return url | [
"Return",
"random",
"value",
"for",
"URLField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"URLField",
"()",
")",
">>>",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"URLValidator",
">>>",
"re",
".",
"match",
"(",
"URLValidator",
".",
"regex",
"result",
")",
"is",
"not",
"None",
"True"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L366-L395 | [
"def",
"any_url_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"kwargs",
".",
"get",
"(",
"'url'",
")",
"if",
"not",
"url",
":",
"verified",
"=",
"[",
"validator",
"for",
"validator",
"in",
"field",
".",
"validators",
"if",
"isinstance",
"(",
"validator",
",",
"validators",
".",
"URLValidator",
")",
"and",
"validator",
".",
"verify_exists",
"==",
"True",
"]",
"if",
"verified",
":",
"url",
"=",
"choice",
"(",
"[",
"'http://news.yandex.ru/society.html'",
",",
"'http://video.google.com/?hl=en&tab=wv'",
",",
"'http://www.microsoft.com/en/us/default.aspx'",
",",
"'http://habrahabr.ru/company/opera/'",
",",
"'http://www.apple.com/support/hardware/'",
",",
"'http://ya.ru'",
",",
"'http://google.com'",
",",
"'http://fr.wikipedia.org/wiki/France'",
"]",
")",
"else",
":",
"url",
"=",
"\"http://%s.%s/%s\"",
"%",
"(",
"xunit",
".",
"any_string",
"(",
"max_length",
"=",
"10",
")",
",",
"xunit",
".",
"any_string",
"(",
"min_length",
"=",
"2",
",",
"max_length",
"=",
"3",
")",
",",
"xunit",
".",
"any_string",
"(",
"max_length",
"=",
"20",
")",
")",
"return",
"url"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | any_time_field | Return random value for TimeField
>>> result = any_field(models.TimeField())
>>> type(result)
<type 'datetime.time'> | django_any/models.py | def any_time_field(field, **kwargs):
"""
Return random value for TimeField
>>> result = any_field(models.TimeField())
>>> type(result)
<type 'datetime.time'>
"""
return time(
xunit.any_int(min_value=0, max_value=23),
xunit.any_int(min_value=0, max_value=59),
xunit.any_int(min_value=0, max_value=59)) | def any_time_field(field, **kwargs):
"""
Return random value for TimeField
>>> result = any_field(models.TimeField())
>>> type(result)
<type 'datetime.time'>
"""
return time(
xunit.any_int(min_value=0, max_value=23),
xunit.any_int(min_value=0, max_value=59),
xunit.any_int(min_value=0, max_value=59)) | [
"Return",
"random",
"value",
"for",
"TimeField",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"TimeField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"datetime",
".",
"time",
">"
] | kmmbvnr/django-any | python | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L399-L409 | [
"def",
"any_time_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"time",
"(",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"23",
")",
",",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"59",
")",
",",
"xunit",
".",
"any_int",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"59",
")",
")"
] | 6f64ebd05476e2149e2e71deeefbb10f8edfc412 |
test | load_python_global | Evaluate an OpenMath symbol describing a global Python object
EXAMPLES::
>>> from openmath.convert_pickle import to_python
>>> from openmath.convert_pickle import load_python_global
>>> load_python_global('math', 'sin')
<built-in function sin>
>>> from openmath import openmath as om
>>> o = om.OMSymbol(cdbase="http://python.org/", cd='math', name='sin')
>>> to_python(o)
<built-in function sin> | openmath/convert_pickle.py | def load_python_global(module, name):
"""
Evaluate an OpenMath symbol describing a global Python object
EXAMPLES::
>>> from openmath.convert_pickle import to_python
>>> from openmath.convert_pickle import load_python_global
>>> load_python_global('math', 'sin')
<built-in function sin>
>>> from openmath import openmath as om
>>> o = om.OMSymbol(cdbase="http://python.org/", cd='math', name='sin')
>>> to_python(o)
<built-in function sin>
"""
# The builtin module has been renamed in python3
if module == '__builtin__' and six.PY3:
module = 'builtins'
module = importlib.import_module(module)
return getattr(module, name) | def load_python_global(module, name):
"""
Evaluate an OpenMath symbol describing a global Python object
EXAMPLES::
>>> from openmath.convert_pickle import to_python
>>> from openmath.convert_pickle import load_python_global
>>> load_python_global('math', 'sin')
<built-in function sin>
>>> from openmath import openmath as om
>>> o = om.OMSymbol(cdbase="http://python.org/", cd='math', name='sin')
>>> to_python(o)
<built-in function sin>
"""
# The builtin module has been renamed in python3
if module == '__builtin__' and six.PY3:
module = 'builtins'
module = importlib.import_module(module)
return getattr(module, name) | [
"Evaluate",
"an",
"OpenMath",
"symbol",
"describing",
"a",
"global",
"Python",
"object"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L286-L307 | [
"def",
"load_python_global",
"(",
"module",
",",
"name",
")",
":",
"# The builtin module has been renamed in python3",
"if",
"module",
"==",
"'__builtin__'",
"and",
"six",
".",
"PY3",
":",
"module",
"=",
"'builtins'",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module",
")",
"return",
"getattr",
"(",
"module",
",",
"name",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | cls_build | Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>> from openmath.convert_pickle import cls_build
>>> class A(object): pass
>>> inst = A.__new__(A)
>>> state = {"foo": 1, "bar": 4}
>>> inst2 = cls_build(inst,state)
>>> inst is inst2
True
>>> inst.foo
1
>>> inst.bar
4 | openmath/convert_pickle.py | def cls_build(inst, state):
"""
Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>> from openmath.convert_pickle import cls_build
>>> class A(object): pass
>>> inst = A.__new__(A)
>>> state = {"foo": 1, "bar": 4}
>>> inst2 = cls_build(inst,state)
>>> inst is inst2
True
>>> inst.foo
1
>>> inst.bar
4
"""
# Copied from Pickler.load_build
setstate = getattr(inst, "__setstate__", None)
if setstate:
setstate(state)
return inst
slotstate = None
if isinstance(state, tuple) and len(state) == 2:
state, slotstate = state
if state:
try:
d = inst.__dict__
try:
for k, v in six.iteritems(state):
d[six.moves.intern(k)] = v
# keys in state don't have to be strings
# don't blow up, but don't go out of our way
except TypeError:
d.update(state)
except RuntimeError:
# XXX In restricted execution, the instance's __dict__
# is not accessible. Use the old way of unpickling
# the instance variables. This is a semantic
# difference when unpickling in restricted
# vs. unrestricted modes.
# Note, however, that cPickle has never tried to do the
# .update() business, and always uses
# PyObject_SetItem(inst.__dict__, key, value) in a
# loop over state.items().
for k, v in state.items():
setattr(inst, k, v)
if slotstate:
for k, v in slotstate.items():
setattr(inst, k, v)
return inst | def cls_build(inst, state):
"""
Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>> from openmath.convert_pickle import cls_build
>>> class A(object): pass
>>> inst = A.__new__(A)
>>> state = {"foo": 1, "bar": 4}
>>> inst2 = cls_build(inst,state)
>>> inst is inst2
True
>>> inst.foo
1
>>> inst.bar
4
"""
# Copied from Pickler.load_build
setstate = getattr(inst, "__setstate__", None)
if setstate:
setstate(state)
return inst
slotstate = None
if isinstance(state, tuple) and len(state) == 2:
state, slotstate = state
if state:
try:
d = inst.__dict__
try:
for k, v in six.iteritems(state):
d[six.moves.intern(k)] = v
# keys in state don't have to be strings
# don't blow up, but don't go out of our way
except TypeError:
d.update(state)
except RuntimeError:
# XXX In restricted execution, the instance's __dict__
# is not accessible. Use the old way of unpickling
# the instance variables. This is a semantic
# difference when unpickling in restricted
# vs. unrestricted modes.
# Note, however, that cPickle has never tried to do the
# .update() business, and always uses
# PyObject_SetItem(inst.__dict__, key, value) in a
# loop over state.items().
for k, v in state.items():
setattr(inst, k, v)
if slotstate:
for k, v in slotstate.items():
setattr(inst, k, v)
return inst | [
"Apply",
"the",
"setstate",
"protocol",
"to",
"initialize",
"inst",
"from",
"state",
"."
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L331-L389 | [
"def",
"cls_build",
"(",
"inst",
",",
"state",
")",
":",
"# Copied from Pickler.load_build",
"setstate",
"=",
"getattr",
"(",
"inst",
",",
"\"__setstate__\"",
",",
"None",
")",
"if",
"setstate",
":",
"setstate",
"(",
"state",
")",
"return",
"inst",
"slotstate",
"=",
"None",
"if",
"isinstance",
"(",
"state",
",",
"tuple",
")",
"and",
"len",
"(",
"state",
")",
"==",
"2",
":",
"state",
",",
"slotstate",
"=",
"state",
"if",
"state",
":",
"try",
":",
"d",
"=",
"inst",
".",
"__dict__",
"try",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"state",
")",
":",
"d",
"[",
"six",
".",
"moves",
".",
"intern",
"(",
"k",
")",
"]",
"=",
"v",
"# keys in state don't have to be strings",
"# don't blow up, but don't go out of our way",
"except",
"TypeError",
":",
"d",
".",
"update",
"(",
"state",
")",
"except",
"RuntimeError",
":",
"# XXX In restricted execution, the instance's __dict__",
"# is not accessible. Use the old way of unpickling",
"# the instance variables. This is a semantic",
"# difference when unpickling in restricted",
"# vs. unrestricted modes.",
"# Note, however, that cPickle has never tried to do the",
"# .update() business, and always uses",
"# PyObject_SetItem(inst.__dict__, key, value) in a",
"# loop over state.items().",
"for",
"k",
",",
"v",
"in",
"state",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"inst",
",",
"k",
",",
"v",
")",
"if",
"slotstate",
":",
"for",
"k",
",",
"v",
"in",
"slotstate",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"inst",
",",
"k",
",",
"v",
")",
"return",
"inst"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | PickleConverter.OMSymbol | r"""
Helper function to build an OMS object
EXAMPLES::
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMSymbol(module="foo.bar", name="baz"); o
OMSymbol(name='baz', cd='foo.bar', id=None, cdbase='http://python.org/') | openmath/convert_pickle.py | def OMSymbol(self, module, name):
r"""
Helper function to build an OMS object
EXAMPLES::
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMSymbol(module="foo.bar", name="baz"); o
OMSymbol(name='baz', cd='foo.bar', id=None, cdbase='http://python.org/')
"""
return om.OMSymbol(cdbase=self._cdbase, cd=module, name=name) | def OMSymbol(self, module, name):
r"""
Helper function to build an OMS object
EXAMPLES::
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMSymbol(module="foo.bar", name="baz"); o
OMSymbol(name='baz', cd='foo.bar', id=None, cdbase='http://python.org/')
"""
return om.OMSymbol(cdbase=self._cdbase, cd=module, name=name) | [
"r",
"Helper",
"function",
"to",
"build",
"an",
"OMS",
"object",
"EXAMPLES",
"::"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L167-L178 | [
"def",
"OMSymbol",
"(",
"self",
",",
"module",
",",
"name",
")",
":",
"return",
"om",
".",
"OMSymbol",
"(",
"cdbase",
"=",
"self",
".",
"_cdbase",
",",
"cd",
"=",
"module",
",",
"name",
"=",
"name",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | PickleConverter.OMList | Convert a list of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMList([om.OMInteger(2), om.OMInteger(2)]); o
OMApplication(elem=OMSymbol(name='list', cd='Python', id=None, cdbase='http://python.org/'),
arguments=[OMInteger(integer=2, id=None),
OMInteger(integer=2, id=None)],
id=None, cdbase=None)
>>> converter.to_python(o)
[2, 2] | openmath/convert_pickle.py | def OMList(self, l):
"""
Convert a list of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMList([om.OMInteger(2), om.OMInteger(2)]); o
OMApplication(elem=OMSymbol(name='list', cd='Python', id=None, cdbase='http://python.org/'),
arguments=[OMInteger(integer=2, id=None),
OMInteger(integer=2, id=None)],
id=None, cdbase=None)
>>> converter.to_python(o)
[2, 2]
"""
# Except for the conversion of operands, this duplicates the default
# implementation of python's list conversion to openmath in py_openmath
return om.OMApplication(elem=om.OMSymbol(cdbase=self._cdbase, cd='Python', name='list', ), arguments=l) | def OMList(self, l):
"""
Convert a list of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMList([om.OMInteger(2), om.OMInteger(2)]); o
OMApplication(elem=OMSymbol(name='list', cd='Python', id=None, cdbase='http://python.org/'),
arguments=[OMInteger(integer=2, id=None),
OMInteger(integer=2, id=None)],
id=None, cdbase=None)
>>> converter.to_python(o)
[2, 2]
"""
# Except for the conversion of operands, this duplicates the default
# implementation of python's list conversion to openmath in py_openmath
return om.OMApplication(elem=om.OMSymbol(cdbase=self._cdbase, cd='Python', name='list', ), arguments=l) | [
"Convert",
"a",
"list",
"of",
"OM",
"objects",
"into",
"an",
"OM",
"object"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L216-L235 | [
"def",
"OMList",
"(",
"self",
",",
"l",
")",
":",
"# Except for the conversion of operands, this duplicates the default",
"# implementation of python's list conversion to openmath in py_openmath",
"return",
"om",
".",
"OMApplication",
"(",
"elem",
"=",
"om",
".",
"OMSymbol",
"(",
"cdbase",
"=",
"self",
".",
"_cdbase",
",",
"cd",
"=",
"'Python'",
",",
"name",
"=",
"'list'",
",",
")",
",",
"arguments",
"=",
"l",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | PickleConverter.OMTuple | Convert a tuple of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMTuple([om.OMInteger(2), om.OMInteger(3)]); o
OMApplication(elem=OMSymbol(name='tuple', cd='Python', id=None, cdbase='http://python.org/'),
arguments=[OMInteger(integer=2, id=None), OMInteger(integer=3, id=None)], id=None, cdbase=None)
>>> converter.to_python(o)
(2, 3) | openmath/convert_pickle.py | def OMTuple(self, l):
"""
Convert a tuple of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMTuple([om.OMInteger(2), om.OMInteger(3)]); o
OMApplication(elem=OMSymbol(name='tuple', cd='Python', id=None, cdbase='http://python.org/'),
arguments=[OMInteger(integer=2, id=None), OMInteger(integer=3, id=None)], id=None, cdbase=None)
>>> converter.to_python(o)
(2, 3)
"""
return om.OMApplication(elem=self.OMSymbol(module='Python', name='tuple'),
arguments=l) | def OMTuple(self, l):
"""
Convert a tuple of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMTuple([om.OMInteger(2), om.OMInteger(3)]); o
OMApplication(elem=OMSymbol(name='tuple', cd='Python', id=None, cdbase='http://python.org/'),
arguments=[OMInteger(integer=2, id=None), OMInteger(integer=3, id=None)], id=None, cdbase=None)
>>> converter.to_python(o)
(2, 3)
"""
return om.OMApplication(elem=self.OMSymbol(module='Python', name='tuple'),
arguments=l) | [
"Convert",
"a",
"tuple",
"of",
"OM",
"objects",
"into",
"an",
"OM",
"object"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L237-L253 | [
"def",
"OMTuple",
"(",
"self",
",",
"l",
")",
":",
"return",
"om",
".",
"OMApplication",
"(",
"elem",
"=",
"self",
".",
"OMSymbol",
"(",
"module",
"=",
"'Python'",
",",
"name",
"=",
"'tuple'",
")",
",",
"arguments",
"=",
"l",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | PickleConverter.OMDict | Convert a dictionary (or list of items thereof) of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> a = om.OMInteger(1)
>>> b = om.OMInteger(3)
>>> o = converter.OMDict([(a,b), (b,b)]); print(o)
OMApplication(
elem=OMSymbol(name='dict', cd='Python', cdbase='http://python.org/'),
arguments=[
OMApplication(
elem=OMSymbol(name='tuple', cd='Python', cdbase='http://python.org/'),
arguments=[
OMInteger(integer=1),
OMInteger(integer=3)]),
OMApplication(
elem=OMSymbol(name='tuple', cd='Python', cdbase='http://python.org/'),
arguments=[
OMInteger(integer=3),
OMInteger(integer=3)])])
>>> converter.to_python(o)
{1: 3, 3: 3} | openmath/convert_pickle.py | def OMDict(self, items):
"""
Convert a dictionary (or list of items thereof) of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> a = om.OMInteger(1)
>>> b = om.OMInteger(3)
>>> o = converter.OMDict([(a,b), (b,b)]); print(o)
OMApplication(
elem=OMSymbol(name='dict', cd='Python', cdbase='http://python.org/'),
arguments=[
OMApplication(
elem=OMSymbol(name='tuple', cd='Python', cdbase='http://python.org/'),
arguments=[
OMInteger(integer=1),
OMInteger(integer=3)]),
OMApplication(
elem=OMSymbol(name='tuple', cd='Python', cdbase='http://python.org/'),
arguments=[
OMInteger(integer=3),
OMInteger(integer=3)])])
>>> converter.to_python(o)
{1: 3, 3: 3}
"""
return om.OMApplication(elem=self.OMSymbol(module='Python', name='dict'),
arguments=[self.OMTuple(item) for item in items]) | def OMDict(self, items):
"""
Convert a dictionary (or list of items thereof) of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> a = om.OMInteger(1)
>>> b = om.OMInteger(3)
>>> o = converter.OMDict([(a,b), (b,b)]); print(o)
OMApplication(
elem=OMSymbol(name='dict', cd='Python', cdbase='http://python.org/'),
arguments=[
OMApplication(
elem=OMSymbol(name='tuple', cd='Python', cdbase='http://python.org/'),
arguments=[
OMInteger(integer=1),
OMInteger(integer=3)]),
OMApplication(
elem=OMSymbol(name='tuple', cd='Python', cdbase='http://python.org/'),
arguments=[
OMInteger(integer=3),
OMInteger(integer=3)])])
>>> converter.to_python(o)
{1: 3, 3: 3}
"""
return om.OMApplication(elem=self.OMSymbol(module='Python', name='dict'),
arguments=[self.OMTuple(item) for item in items]) | [
"Convert",
"a",
"dictionary",
"(",
"or",
"list",
"of",
"items",
"thereof",
")",
"of",
"OM",
"objects",
"into",
"an",
"OM",
"object"
] | OpenMath/py-openmath | python | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L255-L284 | [
"def",
"OMDict",
"(",
"self",
",",
"items",
")",
":",
"return",
"om",
".",
"OMApplication",
"(",
"elem",
"=",
"self",
".",
"OMSymbol",
"(",
"module",
"=",
"'Python'",
",",
"name",
"=",
"'dict'",
")",
",",
"arguments",
"=",
"[",
"self",
".",
"OMTuple",
"(",
"item",
")",
"for",
"item",
"in",
"items",
"]",
")"
] | 4906aa9ccf606f533675c28823772e07c30fd220 |
test | decode | Decodes a PackBit encoded data. | src/packbits.py | def decode(data):
"""
Decodes a PackBit encoded data.
"""
data = bytearray(data) # <- python 2/3 compatibility fix
result = bytearray()
pos = 0
while pos < len(data):
header_byte = data[pos]
if header_byte > 127:
header_byte -= 256
pos += 1
if 0 <= header_byte <= 127:
result.extend(data[pos:pos+header_byte+1])
pos += header_byte+1
elif header_byte == -128:
pass
else:
result.extend([data[pos]] * (1 - header_byte))
pos += 1
return bytes(result) | def decode(data):
"""
Decodes a PackBit encoded data.
"""
data = bytearray(data) # <- python 2/3 compatibility fix
result = bytearray()
pos = 0
while pos < len(data):
header_byte = data[pos]
if header_byte > 127:
header_byte -= 256
pos += 1
if 0 <= header_byte <= 127:
result.extend(data[pos:pos+header_byte+1])
pos += header_byte+1
elif header_byte == -128:
pass
else:
result.extend([data[pos]] * (1 - header_byte))
pos += 1
return bytes(result) | [
"Decodes",
"a",
"PackBit",
"encoded",
"data",
"."
] | psd-tools/packbits | python | https://github.com/psd-tools/packbits/blob/38909758005abfb891770996f321a630f3c9ece2/src/packbits.py#L4-L26 | [
"def",
"decode",
"(",
"data",
")",
":",
"data",
"=",
"bytearray",
"(",
"data",
")",
"# <- python 2/3 compatibility fix",
"result",
"=",
"bytearray",
"(",
")",
"pos",
"=",
"0",
"while",
"pos",
"<",
"len",
"(",
"data",
")",
":",
"header_byte",
"=",
"data",
"[",
"pos",
"]",
"if",
"header_byte",
">",
"127",
":",
"header_byte",
"-=",
"256",
"pos",
"+=",
"1",
"if",
"0",
"<=",
"header_byte",
"<=",
"127",
":",
"result",
".",
"extend",
"(",
"data",
"[",
"pos",
":",
"pos",
"+",
"header_byte",
"+",
"1",
"]",
")",
"pos",
"+=",
"header_byte",
"+",
"1",
"elif",
"header_byte",
"==",
"-",
"128",
":",
"pass",
"else",
":",
"result",
".",
"extend",
"(",
"[",
"data",
"[",
"pos",
"]",
"]",
"*",
"(",
"1",
"-",
"header_byte",
")",
")",
"pos",
"+=",
"1",
"return",
"bytes",
"(",
"result",
")"
] | 38909758005abfb891770996f321a630f3c9ece2 |
test | encode | Encodes data using PackBits encoding. | src/packbits.py | def encode(data):
"""
Encodes data using PackBits encoding.
"""
if len(data) == 0:
return data
if len(data) == 1:
return b'\x00' + data
data = bytearray(data)
result = bytearray()
buf = bytearray()
pos = 0
repeat_count = 0
MAX_LENGTH = 127
# we can safely start with RAW as empty RAW sequences
# are handled by finish_raw()
state = 'RAW'
def finish_raw():
if len(buf) == 0:
return
result.append(len(buf)-1)
result.extend(buf)
buf[:] = bytearray()
def finish_rle():
result.append(256-(repeat_count - 1))
result.append(data[pos])
while pos < len(data)-1:
current_byte = data[pos]
if data[pos] == data[pos+1]:
if state == 'RAW':
# end of RAW data
finish_raw()
state = 'RLE'
repeat_count = 1
elif state == 'RLE':
if repeat_count == MAX_LENGTH:
# restart the encoding
finish_rle()
repeat_count = 0
# move to next byte
repeat_count += 1
else:
if state == 'RLE':
repeat_count += 1
finish_rle()
state = 'RAW'
repeat_count = 0
elif state == 'RAW':
if len(buf) == MAX_LENGTH:
# restart the encoding
finish_raw()
buf.append(current_byte)
pos += 1
if state == 'RAW':
buf.append(data[pos])
finish_raw()
else:
repeat_count += 1
finish_rle()
return bytes(result) | def encode(data):
"""
Encodes data using PackBits encoding.
"""
if len(data) == 0:
return data
if len(data) == 1:
return b'\x00' + data
data = bytearray(data)
result = bytearray()
buf = bytearray()
pos = 0
repeat_count = 0
MAX_LENGTH = 127
# we can safely start with RAW as empty RAW sequences
# are handled by finish_raw()
state = 'RAW'
def finish_raw():
if len(buf) == 0:
return
result.append(len(buf)-1)
result.extend(buf)
buf[:] = bytearray()
def finish_rle():
result.append(256-(repeat_count - 1))
result.append(data[pos])
while pos < len(data)-1:
current_byte = data[pos]
if data[pos] == data[pos+1]:
if state == 'RAW':
# end of RAW data
finish_raw()
state = 'RLE'
repeat_count = 1
elif state == 'RLE':
if repeat_count == MAX_LENGTH:
# restart the encoding
finish_rle()
repeat_count = 0
# move to next byte
repeat_count += 1
else:
if state == 'RLE':
repeat_count += 1
finish_rle()
state = 'RAW'
repeat_count = 0
elif state == 'RAW':
if len(buf) == MAX_LENGTH:
# restart the encoding
finish_raw()
buf.append(current_byte)
pos += 1
if state == 'RAW':
buf.append(data[pos])
finish_raw()
else:
repeat_count += 1
finish_rle()
return bytes(result) | [
"Encodes",
"data",
"using",
"PackBits",
"encoding",
"."
] | psd-tools/packbits | python | https://github.com/psd-tools/packbits/blob/38909758005abfb891770996f321a630f3c9ece2/src/packbits.py#L29-L101 | [
"def",
"encode",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"data",
"if",
"len",
"(",
"data",
")",
"==",
"1",
":",
"return",
"b'\\x00'",
"+",
"data",
"data",
"=",
"bytearray",
"(",
"data",
")",
"result",
"=",
"bytearray",
"(",
")",
"buf",
"=",
"bytearray",
"(",
")",
"pos",
"=",
"0",
"repeat_count",
"=",
"0",
"MAX_LENGTH",
"=",
"127",
"# we can safely start with RAW as empty RAW sequences",
"# are handled by finish_raw()",
"state",
"=",
"'RAW'",
"def",
"finish_raw",
"(",
")",
":",
"if",
"len",
"(",
"buf",
")",
"==",
"0",
":",
"return",
"result",
".",
"append",
"(",
"len",
"(",
"buf",
")",
"-",
"1",
")",
"result",
".",
"extend",
"(",
"buf",
")",
"buf",
"[",
":",
"]",
"=",
"bytearray",
"(",
")",
"def",
"finish_rle",
"(",
")",
":",
"result",
".",
"append",
"(",
"256",
"-",
"(",
"repeat_count",
"-",
"1",
")",
")",
"result",
".",
"append",
"(",
"data",
"[",
"pos",
"]",
")",
"while",
"pos",
"<",
"len",
"(",
"data",
")",
"-",
"1",
":",
"current_byte",
"=",
"data",
"[",
"pos",
"]",
"if",
"data",
"[",
"pos",
"]",
"==",
"data",
"[",
"pos",
"+",
"1",
"]",
":",
"if",
"state",
"==",
"'RAW'",
":",
"# end of RAW data",
"finish_raw",
"(",
")",
"state",
"=",
"'RLE'",
"repeat_count",
"=",
"1",
"elif",
"state",
"==",
"'RLE'",
":",
"if",
"repeat_count",
"==",
"MAX_LENGTH",
":",
"# restart the encoding",
"finish_rle",
"(",
")",
"repeat_count",
"=",
"0",
"# move to next byte",
"repeat_count",
"+=",
"1",
"else",
":",
"if",
"state",
"==",
"'RLE'",
":",
"repeat_count",
"+=",
"1",
"finish_rle",
"(",
")",
"state",
"=",
"'RAW'",
"repeat_count",
"=",
"0",
"elif",
"state",
"==",
"'RAW'",
":",
"if",
"len",
"(",
"buf",
")",
"==",
"MAX_LENGTH",
":",
"# restart the encoding",
"finish_raw",
"(",
")",
"buf",
".",
"append",
"(",
"current_byte",
")",
"pos",
"+=",
"1",
"if",
"state",
"==",
"'RAW'",
":",
"buf",
".",
"append",
"(",
"data",
"[",
"pos",
"]",
")",
"finish_raw",
"(",
")",
"else",
":",
"repeat_count",
"+=",
"1",
"finish_rle",
"(",
")",
"return",
"bytes",
"(",
"result",
")"
] | 38909758005abfb891770996f321a630f3c9ece2 |
test | Accounting._check_currency_format | Summary.
Args:
format (TYPE, optional): Description
Returns:
name (TYPE): Description | accounting/accounting.py | def _check_currency_format(self, format=None):
"""
Summary.
Args:
format (TYPE, optional): Description
Returns:
name (TYPE): Description
"""
defaults = self.settings['currency']['format']
if hasattr(format, '__call__'):
format = format()
if is_str(format) and re.match('%v', format):
# Create and return positive, negative and zero formats:
return {
'pos': format,
'neg': format.replace("-", "").replace("%v", "-%v"),
'zero': format
}
elif not format or not format['por'] or not re.match('%v',
format['pos']):
self.settings['currency']['format'] = {
'pos': defaults,
'neg': defaults.replace("%v", "-%v"),
'zero': defaults
}
return self.settings
return format | def _check_currency_format(self, format=None):
"""
Summary.
Args:
format (TYPE, optional): Description
Returns:
name (TYPE): Description
"""
defaults = self.settings['currency']['format']
if hasattr(format, '__call__'):
format = format()
if is_str(format) and re.match('%v', format):
# Create and return positive, negative and zero formats:
return {
'pos': format,
'neg': format.replace("-", "").replace("%v", "-%v"),
'zero': format
}
elif not format or not format['por'] or not re.match('%v',
format['pos']):
self.settings['currency']['format'] = {
'pos': defaults,
'neg': defaults.replace("%v", "-%v"),
'zero': defaults
}
return self.settings
return format | [
"Summary",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/accounting/accounting.py#L66-L96 | [
"def",
"_check_currency_format",
"(",
"self",
",",
"format",
"=",
"None",
")",
":",
"defaults",
"=",
"self",
".",
"settings",
"[",
"'currency'",
"]",
"[",
"'format'",
"]",
"if",
"hasattr",
"(",
"format",
",",
"'__call__'",
")",
":",
"format",
"=",
"format",
"(",
")",
"if",
"is_str",
"(",
"format",
")",
"and",
"re",
".",
"match",
"(",
"'%v'",
",",
"format",
")",
":",
"# Create and return positive, negative and zero formats:",
"return",
"{",
"'pos'",
":",
"format",
",",
"'neg'",
":",
"format",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"%v\"",
",",
"\"-%v\"",
")",
",",
"'zero'",
":",
"format",
"}",
"elif",
"not",
"format",
"or",
"not",
"format",
"[",
"'por'",
"]",
"or",
"not",
"re",
".",
"match",
"(",
"'%v'",
",",
"format",
"[",
"'pos'",
"]",
")",
":",
"self",
".",
"settings",
"[",
"'currency'",
"]",
"[",
"'format'",
"]",
"=",
"{",
"'pos'",
":",
"defaults",
",",
"'neg'",
":",
"defaults",
".",
"replace",
"(",
"\"%v\"",
",",
"\"-%v\"",
")",
",",
"'zero'",
":",
"defaults",
"}",
"return",
"self",
".",
"settings",
"return",
"format"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | Accounting._change_precision | Check and normalise the value of precision (must be positive integer).
Args:
val (INT): must be positive integer
base (INT): Description
Returns:
VAL (INT): Description | accounting/accounting.py | def _change_precision(self, val, base=0):
"""
Check and normalise the value of precision (must be positive integer).
Args:
val (INT): must be positive integer
base (INT): Description
Returns:
VAL (INT): Description
"""
if not isinstance(val, int):
raise TypeError('The first argument must be an integer.')
val = round(abs(val))
val = (lambda num: base if is_num(num) else num)(val)
return val | def _change_precision(self, val, base=0):
"""
Check and normalise the value of precision (must be positive integer).
Args:
val (INT): must be positive integer
base (INT): Description
Returns:
VAL (INT): Description
"""
if not isinstance(val, int):
raise TypeError('The first argument must be an integer.')
val = round(abs(val))
val = (lambda num: base if is_num(num) else num)(val)
return val | [
"Check",
"and",
"normalise",
"the",
"value",
"of",
"precision",
"(",
"must",
"be",
"positive",
"integer",
")",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/accounting/accounting.py#L98-L113 | [
"def",
"_change_precision",
"(",
"self",
",",
"val",
",",
"base",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'The first argument must be an integer.'",
")",
"val",
"=",
"round",
"(",
"abs",
"(",
"val",
")",
")",
"val",
"=",
"(",
"lambda",
"num",
":",
"base",
"if",
"is_num",
"(",
"num",
")",
"else",
"num",
")",
"(",
"val",
")",
"return",
"val"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | Accounting.parse | Summary.
Takes a string/array of strings, removes all formatting/cruft and
returns the raw float value
Decimal must be included in the regular expression to match floats
(defaults to Accounting.settings.number.decimal),
so if the number uses a non-standard decimal
separator, provide it as the second argument.
*
Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
Doesn't throw any errors (`None`s become 0) but this may change
Args:
value (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description | accounting/accounting.py | def parse(self, value, decimal=None):
"""
Summary.
Takes a string/array of strings, removes all formatting/cruft and
returns the raw float value
Decimal must be included in the regular expression to match floats
(defaults to Accounting.settings.number.decimal),
so if the number uses a non-standard decimal
separator, provide it as the second argument.
*
Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
Doesn't throw any errors (`None`s become 0) but this may change
Args:
value (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description
"""
# Fails silently (need decent errors):
value = value or 0
# Recursively unformat arrays:
if check_type(value, 'list'):
return map(lambda val: self.parse(val, decimal))
# Return the value as-is if it's already a number:
if check_type(value, 'int') or check_type(value, 'float'):
return value
# Default decimal point comes from settings, but could be set to eg.","
decimal = decimal or self.settings.number.decimal
# Build regex to strip out everything except digits,
# decimal point and minus sign
regex = re.compile("[^0-9-" + decimal + "]")
unformatted = str(value)
unformatted = re.sub('/\((.*)\)/', "-$1", unformatted)
unformatted = re.sub(regex, '', unformatted)
unformatted = unformatted.replace('.', decimal)
formatted = (lambda val: unformatted if val else 0)(
is_num(unformatted))
return formatted | def parse(self, value, decimal=None):
"""
Summary.
Takes a string/array of strings, removes all formatting/cruft and
returns the raw float value
Decimal must be included in the regular expression to match floats
(defaults to Accounting.settings.number.decimal),
so if the number uses a non-standard decimal
separator, provide it as the second argument.
*
Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
Doesn't throw any errors (`None`s become 0) but this may change
Args:
value (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description
"""
# Fails silently (need decent errors):
value = value or 0
# Recursively unformat arrays:
if check_type(value, 'list'):
return map(lambda val: self.parse(val, decimal))
# Return the value as-is if it's already a number:
if check_type(value, 'int') or check_type(value, 'float'):
return value
# Default decimal point comes from settings, but could be set to eg.","
decimal = decimal or self.settings.number.decimal
# Build regex to strip out everything except digits,
# decimal point and minus sign
regex = re.compile("[^0-9-" + decimal + "]")
unformatted = str(value)
unformatted = re.sub('/\((.*)\)/', "-$1", unformatted)
unformatted = re.sub(regex, '', unformatted)
unformatted = unformatted.replace('.', decimal)
formatted = (lambda val: unformatted if val else 0)(
is_num(unformatted))
return formatted | [
"Summary",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/accounting/accounting.py#L115-L162 | [
"def",
"parse",
"(",
"self",
",",
"value",
",",
"decimal",
"=",
"None",
")",
":",
"# Fails silently (need decent errors):",
"value",
"=",
"value",
"or",
"0",
"# Recursively unformat arrays:",
"if",
"check_type",
"(",
"value",
",",
"'list'",
")",
":",
"return",
"map",
"(",
"lambda",
"val",
":",
"self",
".",
"parse",
"(",
"val",
",",
"decimal",
")",
")",
"# Return the value as-is if it's already a number:",
"if",
"check_type",
"(",
"value",
",",
"'int'",
")",
"or",
"check_type",
"(",
"value",
",",
"'float'",
")",
":",
"return",
"value",
"# Default decimal point comes from settings, but could be set to eg.\",\"",
"decimal",
"=",
"decimal",
"or",
"self",
".",
"settings",
".",
"number",
".",
"decimal",
"# Build regex to strip out everything except digits,",
"# decimal point and minus sign",
"regex",
"=",
"re",
".",
"compile",
"(",
"\"[^0-9-\"",
"+",
"decimal",
"+",
"\"]\"",
")",
"unformatted",
"=",
"str",
"(",
"value",
")",
"unformatted",
"=",
"re",
".",
"sub",
"(",
"'/\\((.*)\\)/'",
",",
"\"-$1\"",
",",
"unformatted",
")",
"unformatted",
"=",
"re",
".",
"sub",
"(",
"regex",
",",
"''",
",",
"unformatted",
")",
"unformatted",
"=",
"unformatted",
".",
"replace",
"(",
"'.'",
",",
"decimal",
")",
"formatted",
"=",
"(",
"lambda",
"val",
":",
"unformatted",
"if",
"val",
"else",
"0",
")",
"(",
"is_num",
"(",
"unformatted",
")",
")",
"return",
"formatted"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | Accounting.to_fixed | Implementation that treats floats more like decimals.
Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61")
that present problems for accounting and finance-related software. | accounting/accounting.py | def to_fixed(self, value, precision):
"""Implementation that treats floats more like decimals.
Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61")
that present problems for accounting and finance-related software.
"""
precision = self._change_precision(
precision, self.settings['number']['precision'])
power = pow(10, precision)
# Multiply up by precision, round accurately, then divide
power = round(self.parse(value) * power) / power
return '{0} {1}.{2}f'.format(value, precision, precision) | def to_fixed(self, value, precision):
"""Implementation that treats floats more like decimals.
Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61")
that present problems for accounting and finance-related software.
"""
precision = self._change_precision(
precision, self.settings['number']['precision'])
power = pow(10, precision)
# Multiply up by precision, round accurately, then divide
power = round(self.parse(value) * power) / power
return '{0} {1}.{2}f'.format(value, precision, precision) | [
"Implementation",
"that",
"treats",
"floats",
"more",
"like",
"decimals",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/accounting/accounting.py#L164-L177 | [
"def",
"to_fixed",
"(",
"self",
",",
"value",
",",
"precision",
")",
":",
"precision",
"=",
"self",
".",
"_change_precision",
"(",
"precision",
",",
"self",
".",
"settings",
"[",
"'number'",
"]",
"[",
"'precision'",
"]",
")",
"power",
"=",
"pow",
"(",
"10",
",",
"precision",
")",
"# Multiply up by precision, round accurately, then divide",
"power",
"=",
"round",
"(",
"self",
".",
"parse",
"(",
"value",
")",
"*",
"power",
")",
"/",
"power",
"return",
"'{0} {1}.{2}f'",
".",
"format",
"(",
"value",
",",
"precision",
",",
"precision",
")"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | Accounting.format | Format a given number.
Format a number, with comma-separated thousands and
custom precision/decimal places
Localise by overriding the precision and thousand / decimal separators
2nd parameter `precision` can be an object matching `settings.number`
Args:
number (TYPE): Description
precision (TYPE): Description
thousand (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description | accounting/accounting.py | def format(self, number, **kwargs):
"""Format a given number.
Format a number, with comma-separated thousands and
custom precision/decimal places
Localise by overriding the precision and thousand / decimal separators
2nd parameter `precision` can be an object matching `settings.number`
Args:
number (TYPE): Description
precision (TYPE): Description
thousand (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description
"""
# Resursively format lists
if check_type(number, 'list'):
return map(lambda val: self.format(val, **kwargs))
# Clean up number
number = self.parse(number)
# Build options object from second param (if object) or all params,
# extending defaults
if check_type(kwargs, 'dict'):
options = (self.settings['number'].update(kwargs))
# Clean up precision
precision = self._change_precision(options['precision'])
negative = (lambda num: "-" if num < 0 else "")(number)
base = str(int(self.to_fixed(abs(number) or 0, precision)), 10)
mod = (lambda num: len(num) % 3 if len(num) > 3 else 0)(base)
# Format the number:
num = negative + (lambda num: base[0:num] if num else '')(mod)
num += re.sub('/(\d{3})(?=\d)/g', '$1' +
options['thousand'], base[mod:])
num += (lambda val: options[
'decimal'] + self.to_fixed(abs(number), precision)
.split('.')[1] if val else '')(precision)
return num | def format(self, number, **kwargs):
"""Format a given number.
Format a number, with comma-separated thousands and
custom precision/decimal places
Localise by overriding the precision and thousand / decimal separators
2nd parameter `precision` can be an object matching `settings.number`
Args:
number (TYPE): Description
precision (TYPE): Description
thousand (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description
"""
# Resursively format lists
if check_type(number, 'list'):
return map(lambda val: self.format(val, **kwargs))
# Clean up number
number = self.parse(number)
# Build options object from second param (if object) or all params,
# extending defaults
if check_type(kwargs, 'dict'):
options = (self.settings['number'].update(kwargs))
# Clean up precision
precision = self._change_precision(options['precision'])
negative = (lambda num: "-" if num < 0 else "")(number)
base = str(int(self.to_fixed(abs(number) or 0, precision)), 10)
mod = (lambda num: len(num) % 3 if len(num) > 3 else 0)(base)
# Format the number:
num = negative + (lambda num: base[0:num] if num else '')(mod)
num += re.sub('/(\d{3})(?=\d)/g', '$1' +
options['thousand'], base[mod:])
num += (lambda val: options[
'decimal'] + self.to_fixed(abs(number), precision)
.split('.')[1] if val else '')(precision)
return num | [
"Format",
"a",
"given",
"number",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/accounting/accounting.py#L179-L223 | [
"def",
"format",
"(",
"self",
",",
"number",
",",
"*",
"*",
"kwargs",
")",
":",
"# Resursively format lists",
"if",
"check_type",
"(",
"number",
",",
"'list'",
")",
":",
"return",
"map",
"(",
"lambda",
"val",
":",
"self",
".",
"format",
"(",
"val",
",",
"*",
"*",
"kwargs",
")",
")",
"# Clean up number",
"number",
"=",
"self",
".",
"parse",
"(",
"number",
")",
"# Build options object from second param (if object) or all params,",
"# extending defaults",
"if",
"check_type",
"(",
"kwargs",
",",
"'dict'",
")",
":",
"options",
"=",
"(",
"self",
".",
"settings",
"[",
"'number'",
"]",
".",
"update",
"(",
"kwargs",
")",
")",
"# Clean up precision",
"precision",
"=",
"self",
".",
"_change_precision",
"(",
"options",
"[",
"'precision'",
"]",
")",
"negative",
"=",
"(",
"lambda",
"num",
":",
"\"-\"",
"if",
"num",
"<",
"0",
"else",
"\"\"",
")",
"(",
"number",
")",
"base",
"=",
"str",
"(",
"int",
"(",
"self",
".",
"to_fixed",
"(",
"abs",
"(",
"number",
")",
"or",
"0",
",",
"precision",
")",
")",
",",
"10",
")",
"mod",
"=",
"(",
"lambda",
"num",
":",
"len",
"(",
"num",
")",
"%",
"3",
"if",
"len",
"(",
"num",
")",
">",
"3",
"else",
"0",
")",
"(",
"base",
")",
"# Format the number:",
"num",
"=",
"negative",
"+",
"(",
"lambda",
"num",
":",
"base",
"[",
"0",
":",
"num",
"]",
"if",
"num",
"else",
"''",
")",
"(",
"mod",
")",
"num",
"+=",
"re",
".",
"sub",
"(",
"'/(\\d{3})(?=\\d)/g'",
",",
"'$1'",
"+",
"options",
"[",
"'thousand'",
"]",
",",
"base",
"[",
"mod",
":",
"]",
")",
"num",
"+=",
"(",
"lambda",
"val",
":",
"options",
"[",
"'decimal'",
"]",
"+",
"self",
".",
"to_fixed",
"(",
"abs",
"(",
"number",
")",
",",
"precision",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"if",
"val",
"else",
"''",
")",
"(",
"precision",
")",
"return",
"num"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | Accounting.as_money | Format a number into currency.
Usage: accounting.formatMoney(number, symbol, precision, thousandsSep,
decimalSep, format)
defaults: (0, "$", 2, ",", ".", "%s%v")
Localise by overriding the symbol, precision,
thousand / decimal separators and format
Second param can be an object matching `settings.currency`
which is the easiest way.
Args:
number (TYPE): Description
precision (TYPE): Description
thousand (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description | accounting/accounting.py | def as_money(self, number, **options):
"""Format a number into currency.
Usage: accounting.formatMoney(number, symbol, precision, thousandsSep,
decimalSep, format)
defaults: (0, "$", 2, ",", ".", "%s%v")
Localise by overriding the symbol, precision,
thousand / decimal separators and format
Second param can be an object matching `settings.currency`
which is the easiest way.
Args:
number (TYPE): Description
precision (TYPE): Description
thousand (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description
"""
# Resursively format arrays
if isinstance(number, list):
return map(lambda val: self.as_money(val, **options))
# Clean up number
decimal = options.get('decimal')
number = self.parse(number, decimal)
# Build options object from second param (if object) or all params,
# extending defaults
if check_type(options, 'dict'):
options = (self.settings['currency'].update(options))
# Check format (returns object with pos, neg and zero)
formats = self._check_currency_format(options['format'])
# Choose which format to use for this value
use_format = (lambda num: formats['pos'] if num > 0 else formats[
'neg'] if num < 0 else formats['zero'])(number)
precision = self._change_precision(number, options['precision'])
thousands = options['thousand']
decimal = options['decimal']
formater = self.format(abs(number), precision, thousands, decimal)
# Return with currency symbol added
amount = use_format.replace(
'%s', options['symbol']).replace('%v', formater)
return amount | def as_money(self, number, **options):
"""Format a number into currency.
Usage: accounting.formatMoney(number, symbol, precision, thousandsSep,
decimalSep, format)
defaults: (0, "$", 2, ",", ".", "%s%v")
Localise by overriding the symbol, precision,
thousand / decimal separators and format
Second param can be an object matching `settings.currency`
which is the easiest way.
Args:
number (TYPE): Description
precision (TYPE): Description
thousand (TYPE): Description
decimal (TYPE): Description
Returns:
name (TYPE): Description
"""
# Resursively format arrays
if isinstance(number, list):
return map(lambda val: self.as_money(val, **options))
# Clean up number
decimal = options.get('decimal')
number = self.parse(number, decimal)
# Build options object from second param (if object) or all params,
# extending defaults
if check_type(options, 'dict'):
options = (self.settings['currency'].update(options))
# Check format (returns object with pos, neg and zero)
formats = self._check_currency_format(options['format'])
# Choose which format to use for this value
use_format = (lambda num: formats['pos'] if num > 0 else formats[
'neg'] if num < 0 else formats['zero'])(number)
precision = self._change_precision(number, options['precision'])
thousands = options['thousand']
decimal = options['decimal']
formater = self.format(abs(number), precision, thousands, decimal)
# Return with currency symbol added
amount = use_format.replace(
'%s', options['symbol']).replace('%v', formater)
return amount | [
"Format",
"a",
"number",
"into",
"currency",
"."
] | ojengwa/accounting | python | https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/accounting/accounting.py#L225-L273 | [
"def",
"as_money",
"(",
"self",
",",
"number",
",",
"*",
"*",
"options",
")",
":",
"# Resursively format arrays",
"if",
"isinstance",
"(",
"number",
",",
"list",
")",
":",
"return",
"map",
"(",
"lambda",
"val",
":",
"self",
".",
"as_money",
"(",
"val",
",",
"*",
"*",
"options",
")",
")",
"# Clean up number",
"decimal",
"=",
"options",
".",
"get",
"(",
"'decimal'",
")",
"number",
"=",
"self",
".",
"parse",
"(",
"number",
",",
"decimal",
")",
"# Build options object from second param (if object) or all params,",
"# extending defaults",
"if",
"check_type",
"(",
"options",
",",
"'dict'",
")",
":",
"options",
"=",
"(",
"self",
".",
"settings",
"[",
"'currency'",
"]",
".",
"update",
"(",
"options",
")",
")",
"# Check format (returns object with pos, neg and zero)",
"formats",
"=",
"self",
".",
"_check_currency_format",
"(",
"options",
"[",
"'format'",
"]",
")",
"# Choose which format to use for this value",
"use_format",
"=",
"(",
"lambda",
"num",
":",
"formats",
"[",
"'pos'",
"]",
"if",
"num",
">",
"0",
"else",
"formats",
"[",
"'neg'",
"]",
"if",
"num",
"<",
"0",
"else",
"formats",
"[",
"'zero'",
"]",
")",
"(",
"number",
")",
"precision",
"=",
"self",
".",
"_change_precision",
"(",
"number",
",",
"options",
"[",
"'precision'",
"]",
")",
"thousands",
"=",
"options",
"[",
"'thousand'",
"]",
"decimal",
"=",
"options",
"[",
"'decimal'",
"]",
"formater",
"=",
"self",
".",
"format",
"(",
"abs",
"(",
"number",
")",
",",
"precision",
",",
"thousands",
",",
"decimal",
")",
"# Return with currency symbol added",
"amount",
"=",
"use_format",
".",
"replace",
"(",
"'%s'",
",",
"options",
"[",
"'symbol'",
"]",
")",
".",
"replace",
"(",
"'%v'",
",",
"formater",
")",
"return",
"amount"
] | 6343cf373a5c57941e407a92c101ac4bc45382e3 |
test | to_array | Import a blosc array into a numpy array.
Arguments:
data: A blosc packed numpy array
Returns:
A numpy array with data from a blosc compressed array | ndio/convert/blosc.py | def to_array(data):
"""
Import a blosc array into a numpy array.
Arguments:
data: A blosc packed numpy array
Returns:
A numpy array with data from a blosc compressed array
"""
try:
numpy_data = blosc.unpack_array(data)
except Exception as e:
raise ValueError("Could not load numpy data. {}".format(e))
return numpy_data | def to_array(data):
"""
Import a blosc array into a numpy array.
Arguments:
data: A blosc packed numpy array
Returns:
A numpy array with data from a blosc compressed array
"""
try:
numpy_data = blosc.unpack_array(data)
except Exception as e:
raise ValueError("Could not load numpy data. {}".format(e))
return numpy_data | [
"Import",
"a",
"blosc",
"array",
"into",
"a",
"numpy",
"array",
"."
] | neurodata/ndio | python | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/blosc.py#L6-L21 | [
"def",
"to_array",
"(",
"data",
")",
":",
"try",
":",
"numpy_data",
"=",
"blosc",
".",
"unpack_array",
"(",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Could not load numpy data. {}\"",
".",
"format",
"(",
"e",
")",
")",
"return",
"numpy_data"
] | 792dd5816bc770b05a3db2f4327da42ff6253531 |
test | from_array | Export a numpy array to a blosc array.
Arguments:
array: The numpy array to compress to blosc array
Returns:
Bytes/String. A blosc compressed array | ndio/convert/blosc.py | def from_array(array):
"""
Export a numpy array to a blosc array.
Arguments:
array: The numpy array to compress to blosc array
Returns:
Bytes/String. A blosc compressed array
"""
try:
raw_data = blosc.pack_array(array)
except Exception as e:
raise ValueError("Could not compress data from array. {}".format(e))
return raw_data | def from_array(array):
"""
Export a numpy array to a blosc array.
Arguments:
array: The numpy array to compress to blosc array
Returns:
Bytes/String. A blosc compressed array
"""
try:
raw_data = blosc.pack_array(array)
except Exception as e:
raise ValueError("Could not compress data from array. {}".format(e))
return raw_data | [
"Export",
"a",
"numpy",
"array",
"to",
"a",
"blosc",
"array",
"."
] | neurodata/ndio | python | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/blosc.py#L24-L39 | [
"def",
"from_array",
"(",
"array",
")",
":",
"try",
":",
"raw_data",
"=",
"blosc",
".",
"pack_array",
"(",
"array",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Could not compress data from array. {}\"",
".",
"format",
"(",
"e",
")",
")",
"return",
"raw_data"
] | 792dd5816bc770b05a3db2f4327da42ff6253531 |
test | Workspace.add | Add a workspace entry in user config file. | yoda/workspace.py | def add(self, name, path):
"""Add a workspace entry in user config file."""
if not (os.path.exists(path)):
raise ValueError("Workspace path `%s` doesn't exists." % path)
if (self.exists(name)):
raise ValueError("Workspace `%s` already exists." % name)
self.config["workspaces"][name] = {"path": path, "repositories": {}}
self.config.write() | def add(self, name, path):
"""Add a workspace entry in user config file."""
if not (os.path.exists(path)):
raise ValueError("Workspace path `%s` doesn't exists." % path)
if (self.exists(name)):
raise ValueError("Workspace `%s` already exists." % name)
self.config["workspaces"][name] = {"path": path, "repositories": {}}
self.config.write() | [
"Add",
"a",
"workspace",
"entry",
"in",
"user",
"config",
"file",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/workspace.py#L38-L47 | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"path",
")",
":",
"if",
"not",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Workspace path `%s` doesn't exists.\"",
"%",
"path",
")",
"if",
"(",
"self",
".",
"exists",
"(",
"name",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Workspace `%s` already exists.\"",
"%",
"name",
")",
"self",
".",
"config",
"[",
"\"workspaces\"",
"]",
"[",
"name",
"]",
"=",
"{",
"\"path\"",
":",
"path",
",",
"\"repositories\"",
":",
"{",
"}",
"}",
"self",
".",
"config",
".",
"write",
"(",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Workspace.remove | Remove workspace from config file. | yoda/workspace.py | def remove(self, name):
"""Remove workspace from config file."""
if not (self.exists(name)):
raise ValueError("Workspace `%s` doesn't exists." % name)
self.config["workspaces"].pop(name, 0)
self.config.write() | def remove(self, name):
"""Remove workspace from config file."""
if not (self.exists(name)):
raise ValueError("Workspace `%s` doesn't exists." % name)
self.config["workspaces"].pop(name, 0)
self.config.write() | [
"Remove",
"workspace",
"from",
"config",
"file",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/workspace.py#L49-L55 | [
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"(",
"self",
".",
"exists",
"(",
"name",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Workspace `%s` doesn't exists.\"",
"%",
"name",
")",
"self",
".",
"config",
"[",
"\"workspaces\"",
"]",
".",
"pop",
"(",
"name",
",",
"0",
")",
"self",
".",
"config",
".",
"write",
"(",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Workspace.list | List all available workspaces. | yoda/workspace.py | def list(self):
"""List all available workspaces."""
ws_list = {}
for key, value in self.config["workspaces"].items():
ws_list[key] = dict({"name": key}, **value)
return ws_list | def list(self):
"""List all available workspaces."""
ws_list = {}
for key, value in self.config["workspaces"].items():
ws_list[key] = dict({"name": key}, **value)
return ws_list | [
"List",
"all",
"available",
"workspaces",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/workspace.py#L57-L64 | [
"def",
"list",
"(",
"self",
")",
":",
"ws_list",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"config",
"[",
"\"workspaces\"",
"]",
".",
"items",
"(",
")",
":",
"ws_list",
"[",
"key",
"]",
"=",
"dict",
"(",
"{",
"\"name\"",
":",
"key",
"}",
",",
"*",
"*",
"value",
")",
"return",
"ws_list"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Workspace.get | Get workspace infos from name.
Return None if workspace doesn't exists. | yoda/workspace.py | def get(self, name):
"""
Get workspace infos from name.
Return None if workspace doesn't exists.
"""
ws_list = self.list()
return ws_list[name] if name in ws_list else None | def get(self, name):
"""
Get workspace infos from name.
Return None if workspace doesn't exists.
"""
ws_list = self.list()
return ws_list[name] if name in ws_list else None | [
"Get",
"workspace",
"infos",
"from",
"name",
".",
"Return",
"None",
"if",
"workspace",
"doesn",
"t",
"exists",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/workspace.py#L66-L72 | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"ws_list",
"=",
"self",
".",
"list",
"(",
")",
"return",
"ws_list",
"[",
"name",
"]",
"if",
"name",
"in",
"ws_list",
"else",
"None"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Workspace.repository_exists | Return True if workspace contains repository name. | yoda/workspace.py | def repository_exists(self, workspace, repo):
"""Return True if workspace contains repository name."""
if not self.exists(workspace):
return False
workspaces = self.list()
return repo in workspaces[workspace]["repositories"] | def repository_exists(self, workspace, repo):
"""Return True if workspace contains repository name."""
if not self.exists(workspace):
return False
workspaces = self.list()
return repo in workspaces[workspace]["repositories"] | [
"Return",
"True",
"if",
"workspace",
"contains",
"repository",
"name",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/workspace.py#L78-L84 | [
"def",
"repository_exists",
"(",
"self",
",",
"workspace",
",",
"repo",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
"workspace",
")",
":",
"return",
"False",
"workspaces",
"=",
"self",
".",
"list",
"(",
")",
"return",
"repo",
"in",
"workspaces",
"[",
"workspace",
"]",
"[",
"\"repositories\"",
"]"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Workspace.sync | Synchronise workspace's repositories. | yoda/workspace.py | def sync(self, ws_name):
"""Synchronise workspace's repositories."""
path = self.config["workspaces"][ws_name]["path"]
repositories = self.config["workspaces"][ws_name]["repositories"]
logger = logging.getLogger(__name__)
color = Color()
for r in os.listdir(path):
try:
repo = Repository(os.path.join(path, r))
except RepositoryError:
continue
else:
repositories[r] = repo.path
for repo_name, path in repositories.items():
logger.info(color.colored(
" - %s" % repo_name, "blue"))
self.config["workspaces"][ws_name]["repositories"]
self.config.write() | def sync(self, ws_name):
"""Synchronise workspace's repositories."""
path = self.config["workspaces"][ws_name]["path"]
repositories = self.config["workspaces"][ws_name]["repositories"]
logger = logging.getLogger(__name__)
color = Color()
for r in os.listdir(path):
try:
repo = Repository(os.path.join(path, r))
except RepositoryError:
continue
else:
repositories[r] = repo.path
for repo_name, path in repositories.items():
logger.info(color.colored(
" - %s" % repo_name, "blue"))
self.config["workspaces"][ws_name]["repositories"]
self.config.write() | [
"Synchronise",
"workspace",
"s",
"repositories",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/workspace.py#L86-L107 | [
"def",
"sync",
"(",
"self",
",",
"ws_name",
")",
":",
"path",
"=",
"self",
".",
"config",
"[",
"\"workspaces\"",
"]",
"[",
"ws_name",
"]",
"[",
"\"path\"",
"]",
"repositories",
"=",
"self",
".",
"config",
"[",
"\"workspaces\"",
"]",
"[",
"ws_name",
"]",
"[",
"\"repositories\"",
"]",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"color",
"=",
"Color",
"(",
")",
"for",
"r",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"try",
":",
"repo",
"=",
"Repository",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"r",
")",
")",
"except",
"RepositoryError",
":",
"continue",
"else",
":",
"repositories",
"[",
"r",
"]",
"=",
"repo",
".",
"path",
"for",
"repo_name",
",",
"path",
"in",
"repositories",
".",
"items",
"(",
")",
":",
"logger",
".",
"info",
"(",
"color",
".",
"colored",
"(",
"\" - %s\"",
"%",
"repo_name",
",",
"\"blue\"",
")",
")",
"self",
".",
"config",
"[",
"\"workspaces\"",
"]",
"[",
"ws_name",
"]",
"[",
"\"repositories\"",
"]",
"self",
".",
"config",
".",
"write",
"(",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | clone | Clone a repository. | yoda/repository.py | def clone(url, path):
"""Clone a repository."""
adapter = None
if url[:4] == "git@" or url[-4:] == ".git":
adapter = Git(path)
if url[:6] == "svn://":
adapter = Svn(path)
if url[:6] == "bzr://":
adapter = Bzr(path)
if url[:9] == "ssh://hg@":
adapter = Hg(path)
if adapter is None:
raise RepositoryAdapterNotFound(
"Can't find adapter for `%s` repository url" % url)
return adapter.clone(url) | def clone(url, path):
"""Clone a repository."""
adapter = None
if url[:4] == "git@" or url[-4:] == ".git":
adapter = Git(path)
if url[:6] == "svn://":
adapter = Svn(path)
if url[:6] == "bzr://":
adapter = Bzr(path)
if url[:9] == "ssh://hg@":
adapter = Hg(path)
if adapter is None:
raise RepositoryAdapterNotFound(
"Can't find adapter for `%s` repository url" % url)
return adapter.clone(url) | [
"Clone",
"a",
"repository",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/repository.py#L78-L94 | [
"def",
"clone",
"(",
"url",
",",
"path",
")",
":",
"adapter",
"=",
"None",
"if",
"url",
"[",
":",
"4",
"]",
"==",
"\"git@\"",
"or",
"url",
"[",
"-",
"4",
":",
"]",
"==",
"\".git\"",
":",
"adapter",
"=",
"Git",
"(",
"path",
")",
"if",
"url",
"[",
":",
"6",
"]",
"==",
"\"svn://\"",
":",
"adapter",
"=",
"Svn",
"(",
"path",
")",
"if",
"url",
"[",
":",
"6",
"]",
"==",
"\"bzr://\"",
":",
"adapter",
"=",
"Bzr",
"(",
"path",
")",
"if",
"url",
"[",
":",
"9",
"]",
"==",
"\"ssh://hg@\"",
":",
"adapter",
"=",
"Hg",
"(",
"path",
")",
"if",
"adapter",
"is",
"None",
":",
"raise",
"RepositoryAdapterNotFound",
"(",
"\"Can't find adapter for `%s` repository url\"",
"%",
"url",
")",
"return",
"adapter",
".",
"clone",
"(",
"url",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | check_version | Tells you if you have an old version of ndio. | ndio/__init__.py | def check_version():
"""
Tells you if you have an old version of ndio.
"""
import requests
r = requests.get('https://pypi.python.org/pypi/ndio/json').json()
r = r['info']['version']
if r != version:
print("A newer version of ndio is available. " +
"'pip install -U ndio' to update.")
return r | def check_version():
"""
Tells you if you have an old version of ndio.
"""
import requests
r = requests.get('https://pypi.python.org/pypi/ndio/json').json()
r = r['info']['version']
if r != version:
print("A newer version of ndio is available. " +
"'pip install -U ndio' to update.")
return r | [
"Tells",
"you",
"if",
"you",
"have",
"an",
"old",
"version",
"of",
"ndio",
"."
] | neurodata/ndio | python | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/__init__.py#L8-L18 | [
"def",
"check_version",
"(",
")",
":",
"import",
"requests",
"r",
"=",
"requests",
".",
"get",
"(",
"'https://pypi.python.org/pypi/ndio/json'",
")",
".",
"json",
"(",
")",
"r",
"=",
"r",
"[",
"'info'",
"]",
"[",
"'version'",
"]",
"if",
"r",
"!=",
"version",
":",
"print",
"(",
"\"A newer version of ndio is available. \"",
"+",
"\"'pip install -U ndio' to update.\"",
")",
"return",
"r"
] | 792dd5816bc770b05a3db2f4327da42ff6253531 |
test | to_voxels | Converts an array to its voxel list.
Arguments:
array (numpy.ndarray): A numpy nd array. This must be boolean!
Returns:
A list of n-tuples | ndio/convert/volume.py | def to_voxels(array):
"""
Converts an array to its voxel list.
Arguments:
array (numpy.ndarray): A numpy nd array. This must be boolean!
Returns:
A list of n-tuples
"""
if type(array) is not numpy.ndarray:
raise ValueError("array argument must be of type numpy.ndarray")
return numpy.argwhere(array) | def to_voxels(array):
"""
Converts an array to its voxel list.
Arguments:
array (numpy.ndarray): A numpy nd array. This must be boolean!
Returns:
A list of n-tuples
"""
if type(array) is not numpy.ndarray:
raise ValueError("array argument must be of type numpy.ndarray")
return numpy.argwhere(array) | [
"Converts",
"an",
"array",
"to",
"its",
"voxel",
"list",
"."
] | neurodata/ndio | python | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/volume.py#L5-L17 | [
"def",
"to_voxels",
"(",
"array",
")",
":",
"if",
"type",
"(",
"array",
")",
"is",
"not",
"numpy",
".",
"ndarray",
":",
"raise",
"ValueError",
"(",
"\"array argument must be of type numpy.ndarray\"",
")",
"return",
"numpy",
".",
"argwhere",
"(",
"array",
")"
] | 792dd5816bc770b05a3db2f4327da42ff6253531 |
test | from_voxels | Converts a voxel list to an ndarray.
Arguments:
voxels (tuple[]): A list of coordinates indicating coordinates of
populated voxels in an ndarray.
Returns:
numpy.ndarray The result of the transformation. | ndio/convert/volume.py | def from_voxels(voxels):
"""
Converts a voxel list to an ndarray.
Arguments:
voxels (tuple[]): A list of coordinates indicating coordinates of
populated voxels in an ndarray.
Returns:
numpy.ndarray The result of the transformation.
"""
dimensions = len(voxels[0])
for d in range(len(dimensions)):
size.append(max([i[d] for i in voxels]))
result = numpy.zeros(dimensions)
for v in voxels:
result[v] = 1
return result | def from_voxels(voxels):
"""
Converts a voxel list to an ndarray.
Arguments:
voxels (tuple[]): A list of coordinates indicating coordinates of
populated voxels in an ndarray.
Returns:
numpy.ndarray The result of the transformation.
"""
dimensions = len(voxels[0])
for d in range(len(dimensions)):
size.append(max([i[d] for i in voxels]))
result = numpy.zeros(dimensions)
for v in voxels:
result[v] = 1
return result | [
"Converts",
"a",
"voxel",
"list",
"to",
"an",
"ndarray",
"."
] | neurodata/ndio | python | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/volume.py#L20-L41 | [
"def",
"from_voxels",
"(",
"voxels",
")",
":",
"dimensions",
"=",
"len",
"(",
"voxels",
"[",
"0",
"]",
")",
"for",
"d",
"in",
"range",
"(",
"len",
"(",
"dimensions",
")",
")",
":",
"size",
".",
"append",
"(",
"max",
"(",
"[",
"i",
"[",
"d",
"]",
"for",
"i",
"in",
"voxels",
"]",
")",
")",
"result",
"=",
"numpy",
".",
"zeros",
"(",
"dimensions",
")",
"for",
"v",
"in",
"voxels",
":",
"result",
"[",
"v",
"]",
"=",
"1",
"return",
"result"
] | 792dd5816bc770b05a3db2f4327da42ff6253531 |
test | Update.execute | Execute update subcommand. | yoda/subcommand/update.py | def execute(self, args):
"""Execute update subcommand."""
if args.name is not None:
self.print_workspace(args.name)
elif args.all is not None:
self.print_all() | def execute(self, args):
"""Execute update subcommand."""
if args.name is not None:
self.print_workspace(args.name)
elif args.all is not None:
self.print_all() | [
"Execute",
"update",
"subcommand",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/subcommand/update.py#L44-L49 | [
"def",
"execute",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"name",
"is",
"not",
"None",
":",
"self",
".",
"print_workspace",
"(",
"args",
".",
"name",
")",
"elif",
"args",
".",
"all",
"is",
"not",
"None",
":",
"self",
".",
"print_all",
"(",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Update.print_update | Print repository update. | yoda/subcommand/update.py | def print_update(self, repo_name, repo_path):
"""Print repository update."""
color = Color()
self.logger.info(color.colored(
"=> [%s] %s" % (repo_name, repo_path), "green"))
try:
repo = Repository(repo_path)
repo.update()
except RepositoryError as e:
self.logger.error(e)
pass
print("\n") | def print_update(self, repo_name, repo_path):
"""Print repository update."""
color = Color()
self.logger.info(color.colored(
"=> [%s] %s" % (repo_name, repo_path), "green"))
try:
repo = Repository(repo_path)
repo.update()
except RepositoryError as e:
self.logger.error(e)
pass
print("\n") | [
"Print",
"repository",
"update",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/subcommand/update.py#L67-L78 | [
"def",
"print_update",
"(",
"self",
",",
"repo_name",
",",
"repo_path",
")",
":",
"color",
"=",
"Color",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"color",
".",
"colored",
"(",
"\"=> [%s] %s\"",
"%",
"(",
"repo_name",
",",
"repo_path",
")",
",",
"\"green\"",
")",
")",
"try",
":",
"repo",
"=",
"Repository",
"(",
"repo_path",
")",
"repo",
".",
"update",
"(",
")",
"except",
"RepositoryError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"e",
")",
"pass",
"print",
"(",
"\"\\n\"",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Logger.set_file_handler | Set FileHandler | yoda/logger.py | def set_file_handler(self, logfile):
"""Set FileHandler"""
handler = logging.FileHandler(logfile)
handler.setLevel(logging.NOTSET)
handler.setFormatter(Formatter(FORMAT))
self.addHandler(handler) | def set_file_handler(self, logfile):
"""Set FileHandler"""
handler = logging.FileHandler(logfile)
handler.setLevel(logging.NOTSET)
handler.setFormatter(Formatter(FORMAT))
self.addHandler(handler) | [
"Set",
"FileHandler"
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/logger.py#L65-L71 | [
"def",
"set_file_handler",
"(",
"self",
",",
"logfile",
")",
":",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"logfile",
")",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"NOTSET",
")",
"handler",
".",
"setFormatter",
"(",
"Formatter",
"(",
"FORMAT",
")",
")",
"self",
".",
"addHandler",
"(",
"handler",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Logger.set_console_handler | Set Console handler. | yoda/logger.py | def set_console_handler(self, debug=False):
"""Set Console handler."""
console = logging.StreamHandler()
console.setFormatter(Formatter(LFORMAT))
if not debug:
console.setLevel(logging.INFO)
self.addHandler(console) | def set_console_handler(self, debug=False):
"""Set Console handler."""
console = logging.StreamHandler()
console.setFormatter(Formatter(LFORMAT))
if not debug:
console.setLevel(logging.INFO)
self.addHandler(console) | [
"Set",
"Console",
"handler",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/logger.py#L73-L80 | [
"def",
"set_console_handler",
"(",
"self",
",",
"debug",
"=",
"False",
")",
":",
"console",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"console",
".",
"setFormatter",
"(",
"Formatter",
"(",
"LFORMAT",
")",
")",
"if",
"not",
"debug",
":",
"console",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"self",
".",
"addHandler",
"(",
"console",
")"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | Abstract.execute | Execute command with os.popen and return output. | yoda/adapter/abstract.py | def execute(self, command, path=None):
"""Execute command with os.popen and return output."""
logger = logging.getLogger(__name__)
self.check_executable()
logger.debug("Executing command `%s` (cwd: %s)" % (command, path))
process = subprocess.Popen(
command,
shell=True,
cwd=path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
exit_code = process.wait()
if stdout:
logger.info(stdout.decode("utf-8"))
if stderr:
if exit_code != 0:
logger.error(stderr.decode("utf-8"))
else:
logger.info(stderr.decode("utf-8"))
return process | def execute(self, command, path=None):
"""Execute command with os.popen and return output."""
logger = logging.getLogger(__name__)
self.check_executable()
logger.debug("Executing command `%s` (cwd: %s)" % (command, path))
process = subprocess.Popen(
command,
shell=True,
cwd=path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
exit_code = process.wait()
if stdout:
logger.info(stdout.decode("utf-8"))
if stderr:
if exit_code != 0:
logger.error(stderr.decode("utf-8"))
else:
logger.info(stderr.decode("utf-8"))
return process | [
"Execute",
"command",
"with",
"os",
".",
"popen",
"and",
"return",
"output",
"."
] | Numergy/yoda | python | https://github.com/Numergy/yoda/blob/109f0e9441130488b0155f05883ef6531cf46ee9/yoda/adapter/abstract.py#L37-L62 | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"path",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"self",
".",
"check_executable",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Executing command `%s` (cwd: %s)\"",
"%",
"(",
"command",
",",
"path",
")",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"path",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate",
"(",
")",
"exit_code",
"=",
"process",
".",
"wait",
"(",
")",
"if",
"stdout",
":",
"logger",
".",
"info",
"(",
"stdout",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"if",
"stderr",
":",
"if",
"exit_code",
"!=",
"0",
":",
"logger",
".",
"error",
"(",
"stderr",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"else",
":",
"logger",
".",
"info",
"(",
"stderr",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"return",
"process"
] | 109f0e9441130488b0155f05883ef6531cf46ee9 |
test | load | Import a png file into a numpy array.
Arguments:
png_filename (str): A string filename of a png datafile
Returns:
A numpy array with data from the png file | ndio/convert/png.py | def load(png_filename):
"""
Import a png file into a numpy array.
Arguments:
png_filename (str): A string filename of a png datafile
Returns:
A numpy array with data from the png file
"""
# Expand filename to be absolute
png_filename = os.path.expanduser(png_filename)
try:
img = Image.open(png_filename)
except Exception as e:
raise ValueError("Could not load file {0} for conversion."
.format(png_filename))
raise
return numpy.array(img) | def load(png_filename):
"""
Import a png file into a numpy array.
Arguments:
png_filename (str): A string filename of a png datafile
Returns:
A numpy array with data from the png file
"""
# Expand filename to be absolute
png_filename = os.path.expanduser(png_filename)
try:
img = Image.open(png_filename)
except Exception as e:
raise ValueError("Could not load file {0} for conversion."
.format(png_filename))
raise
return numpy.array(img) | [
"Import",
"a",
"png",
"file",
"into",
"a",
"numpy",
"array",
"."
] | neurodata/ndio | python | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/png.py#L8-L28 | [
"def",
"load",
"(",
"png_filename",
")",
":",
"# Expand filename to be absolute",
"png_filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"png_filename",
")",
"try",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"png_filename",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Could not load file {0} for conversion.\"",
".",
"format",
"(",
"png_filename",
")",
")",
"raise",
"return",
"numpy",
".",
"array",
"(",
"img",
")"
] | 792dd5816bc770b05a3db2f4327da42ff6253531 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.