repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
Richienb/quilt | src/quilt_lang/__init__.py | circleconvert | def circleconvert(amount, currentformat, newformat):
"""
Convert a circle measurement.
:type amount: number
:param amount: The number to convert.
:type currentformat: string
:param currentformat: The format of the provided value.
:type newformat: string
:param newformat: The intended format of the value.
>>> circleconvert(45, "radius", "diameter")
90
"""
# If the same format was provided
if currentformat.lower() == newformat.lower():
# Return the provided value
return amount
# If the lowercase version of the current format is 'radius'
if currentformat.lower() == 'radius':
# If the lowercase version of the new format is 'diameter'
if newformat.lower() == 'diameter':
# Return the converted value
return amount * 2
# If the lowercase version of the new format is 'circumference'
elif newformat.lower() == 'circumference':
# Return the converted value
return amount * 2 * math.pi
# Raise a warning
raise ValueError("Invalid new format provided.")
# If the lowercase version of the current format is 'diameter'
elif currentformat.lower() == 'diameter':
# If the lowercase version of the new format is 'radius'
if newformat.lower() == 'radius':
# Return the converted value
return amount / 2
# If the lowercase version of the new format is 'circumference'
elif newformat.lower() == 'circumference':
# Return the converted value
return amount * math.pi
# Raise a warning
raise ValueError("Invalid new format provided.")
# If the lowercase version of the current format is 'circumference'
elif currentformat.lower() == 'circumference':
# If the lowercase version of the new format is 'radius'
if newformat.lower() == 'radius':
# Return the converted value
return amount / math.pi / 2
# If the lowercase version of the new format is 'diameter'
elif newformat.lower() == 'diameter':
# Return the converted value
return amount / math.pi | python | def circleconvert(amount, currentformat, newformat):
"""
Convert a circle measurement.
:type amount: number
:param amount: The number to convert.
:type currentformat: string
:param currentformat: The format of the provided value.
:type newformat: string
:param newformat: The intended format of the value.
>>> circleconvert(45, "radius", "diameter")
90
"""
# If the same format was provided
if currentformat.lower() == newformat.lower():
# Return the provided value
return amount
# If the lowercase version of the current format is 'radius'
if currentformat.lower() == 'radius':
# If the lowercase version of the new format is 'diameter'
if newformat.lower() == 'diameter':
# Return the converted value
return amount * 2
# If the lowercase version of the new format is 'circumference'
elif newformat.lower() == 'circumference':
# Return the converted value
return amount * 2 * math.pi
# Raise a warning
raise ValueError("Invalid new format provided.")
# If the lowercase version of the current format is 'diameter'
elif currentformat.lower() == 'diameter':
# If the lowercase version of the new format is 'radius'
if newformat.lower() == 'radius':
# Return the converted value
return amount / 2
# If the lowercase version of the new format is 'circumference'
elif newformat.lower() == 'circumference':
# Return the converted value
return amount * math.pi
# Raise a warning
raise ValueError("Invalid new format provided.")
# If the lowercase version of the current format is 'circumference'
elif currentformat.lower() == 'circumference':
# If the lowercase version of the new format is 'radius'
if newformat.lower() == 'radius':
# Return the converted value
return amount / math.pi / 2
# If the lowercase version of the new format is 'diameter'
elif newformat.lower() == 'diameter':
# Return the converted value
return amount / math.pi | [
"def",
"circleconvert",
"(",
"amount",
",",
"currentformat",
",",
"newformat",
")",
":",
"# If the same format was provided",
"if",
"currentformat",
".",
"lower",
"(",
")",
"==",
"newformat",
".",
"lower",
"(",
")",
":",
"# Return the provided value",
"return",
"a... | Convert a circle measurement.
:type amount: number
:param amount: The number to convert.
:type currentformat: string
:param currentformat: The format of the provided value.
:type newformat: string
:param newformat: The intended format of the value.
>>> circleconvert(45, "radius", "diameter")
90 | [
"Convert",
"a",
"circle",
"measurement",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1135-L1197 |
Richienb/quilt | src/quilt_lang/__init__.py | amountdiv | def amountdiv(number, minnum, maxnum):
"""
Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
>>> amountdiv(20, 1, 15)
5
"""
# Set the amount to 0
amount = 0
# For each item in range of minimum and maximum
for i in range(minnum, maxnum + 1):
# If the remainder of the divided number is 0
if number % i == 0:
# Add 1 to the total amount
amount += 1
# Return the result
return amount | python | def amountdiv(number, minnum, maxnum):
"""
Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
>>> amountdiv(20, 1, 15)
5
"""
# Set the amount to 0
amount = 0
# For each item in range of minimum and maximum
for i in range(minnum, maxnum + 1):
# If the remainder of the divided number is 0
if number % i == 0:
# Add 1 to the total amount
amount += 1
# Return the result
return amount | [
"def",
"amountdiv",
"(",
"number",
",",
"minnum",
",",
"maxnum",
")",
":",
"# Set the amount to 0",
"amount",
"=",
"0",
"# For each item in range of minimum and maximum",
"for",
"i",
"in",
"range",
"(",
"minnum",
",",
"maxnum",
"+",
"1",
")",
":",
"# If the rema... | Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
>>> amountdiv(20, 1, 15)
5 | [
"Get",
"the",
"amount",
"of",
"numbers",
"divisable",
"by",
"a",
"number",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1200-L1228 |
Richienb/quilt | src/quilt_lang/__init__.py | constant | def constant(constanttype):
"""
Get A Constant
"""
constanttype = constanttype.lower()
if constanttype == 'pi':
return math.pi
elif constanttype == 'e':
return math.e
elif constanttype == 'tau':
return math.tau
elif constanttype == 'inf':
return math.inf
elif constanttype == 'nan':
return math.nan
elif constanttype in ['phi', 'golden']:
return (1 + 5**0.5) / 2 | python | def constant(constanttype):
"""
Get A Constant
"""
constanttype = constanttype.lower()
if constanttype == 'pi':
return math.pi
elif constanttype == 'e':
return math.e
elif constanttype == 'tau':
return math.tau
elif constanttype == 'inf':
return math.inf
elif constanttype == 'nan':
return math.nan
elif constanttype in ['phi', 'golden']:
return (1 + 5**0.5) / 2 | [
"def",
"constant",
"(",
"constanttype",
")",
":",
"constanttype",
"=",
"constanttype",
".",
"lower",
"(",
")",
"if",
"constanttype",
"==",
"'pi'",
":",
"return",
"math",
".",
"pi",
"elif",
"constanttype",
"==",
"'e'",
":",
"return",
"math",
".",
"e",
"el... | Get A Constant | [
"Get",
"A",
"Constant"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1231-L1247 |
Richienb/quilt | src/quilt_lang/__init__.py | average | def average(numbers, averagetype='mean'):
"""
Find the average of a list of numbers
:type numbers: list
:param numbers: The list of numbers to find the average of.
:type averagetype: string
:param averagetype: The type of average to find.
>>> average([1, 2, 3, 4, 5], 'median')
3
"""
try:
# Try to get the mean of the numbers
statistics.mean(numbers)
except RuntimeError:
# Raise a warning
raise ValueError('Unable to parse the list.')
# If the lowercase version of the average type is 'mean'
if averagetype.lower() == 'mean':
# Return the answer
return statistics.mean(numbers)
# If the lowercase version of the average type is 'mode'
elif averagetype.lower() == 'mode':
# Return the answer
return statistics.mode(numbers)
# If the lowercase version of the average type is 'median'
elif averagetype.lower() == 'median':
# Return the answer
return statistics.median(numbers)
# If the lowercase version of the average type is 'min'
elif averagetype.lower() == 'min':
# Return the answer
return min(numbers)
# If the lowercase version of the average type is 'max'
elif averagetype.lower() == 'max':
# Return the answer
return max(numbers)
# If the lowercase version of the average type is 'range'
elif averagetype.lower() == 'range':
# Return the answer
return max(numbers) - min(numbers)
# Raise a warning
raise ValueError('Invalid average type provided.') | python | def average(numbers, averagetype='mean'):
"""
Find the average of a list of numbers
:type numbers: list
:param numbers: The list of numbers to find the average of.
:type averagetype: string
:param averagetype: The type of average to find.
>>> average([1, 2, 3, 4, 5], 'median')
3
"""
try:
# Try to get the mean of the numbers
statistics.mean(numbers)
except RuntimeError:
# Raise a warning
raise ValueError('Unable to parse the list.')
# If the lowercase version of the average type is 'mean'
if averagetype.lower() == 'mean':
# Return the answer
return statistics.mean(numbers)
# If the lowercase version of the average type is 'mode'
elif averagetype.lower() == 'mode':
# Return the answer
return statistics.mode(numbers)
# If the lowercase version of the average type is 'median'
elif averagetype.lower() == 'median':
# Return the answer
return statistics.median(numbers)
# If the lowercase version of the average type is 'min'
elif averagetype.lower() == 'min':
# Return the answer
return min(numbers)
# If the lowercase version of the average type is 'max'
elif averagetype.lower() == 'max':
# Return the answer
return max(numbers)
# If the lowercase version of the average type is 'range'
elif averagetype.lower() == 'range':
# Return the answer
return max(numbers) - min(numbers)
# Raise a warning
raise ValueError('Invalid average type provided.') | [
"def",
"average",
"(",
"numbers",
",",
"averagetype",
"=",
"'mean'",
")",
":",
"try",
":",
"# Try to get the mean of the numbers",
"statistics",
".",
"mean",
"(",
"numbers",
")",
"except",
"RuntimeError",
":",
"# Raise a warning",
"raise",
"ValueError",
"(",
"'Una... | Find the average of a list of numbers
:type numbers: list
:param numbers: The list of numbers to find the average of.
:type averagetype: string
:param averagetype: The type of average to find.
>>> average([1, 2, 3, 4, 5], 'median')
3 | [
"Find",
"the",
"average",
"of",
"a",
"list",
"of",
"numbers"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1273-L1326 |
Richienb/quilt | src/quilt_lang/__init__.py | numprop | def numprop(value, propertyexpected):
"""
Check If A Number Is A Type
"""
if propertyexpected == 'triangular':
x = (math.sqrt(8 * value + 1) - 1) / 2
return bool(x - int(x) > 0)
elif propertyexpected == 'square':
return math.sqrt(value).is_integer()
elif propertyexpected == 'cube':
x = value**(1 / 3)
x = int(round(x))
return bool(x**3 == value)
elif propertyexpected == 'even':
return value % 2 == 0
elif propertyexpected == 'odd':
return not value % 2 == 0
elif propertyexpected == 'positive':
return bool(value > 0)
elif propertyexpected == 'negative':
return bool(value < 0)
elif propertyexpected == 'zero':
return bool(value == 0) | python | def numprop(value, propertyexpected):
"""
Check If A Number Is A Type
"""
if propertyexpected == 'triangular':
x = (math.sqrt(8 * value + 1) - 1) / 2
return bool(x - int(x) > 0)
elif propertyexpected == 'square':
return math.sqrt(value).is_integer()
elif propertyexpected == 'cube':
x = value**(1 / 3)
x = int(round(x))
return bool(x**3 == value)
elif propertyexpected == 'even':
return value % 2 == 0
elif propertyexpected == 'odd':
return not value % 2 == 0
elif propertyexpected == 'positive':
return bool(value > 0)
elif propertyexpected == 'negative':
return bool(value < 0)
elif propertyexpected == 'zero':
return bool(value == 0) | [
"def",
"numprop",
"(",
"value",
",",
"propertyexpected",
")",
":",
"if",
"propertyexpected",
"==",
"'triangular'",
":",
"x",
"=",
"(",
"math",
".",
"sqrt",
"(",
"8",
"*",
"value",
"+",
"1",
")",
"-",
"1",
")",
"/",
"2",
"return",
"bool",
"(",
"x",
... | Check If A Number Is A Type | [
"Check",
"If",
"A",
"Number",
"Is",
"A",
"Type"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1329-L1351 |
Richienb/quilt | src/quilt_lang/__init__.py | posnegtoggle | def posnegtoggle(number):
"""
Toggle a number between positive and negative.
The converter works as follows:
- 1 > -1
- -1 > 1
- 0 > 0
:type number: number
:param number: The number to toggle.
"""
if bool(number > 0):
return number - number * 2
elif bool(number < 0):
return number + abs(number) * 2
elif bool(number == 0):
return number | python | def posnegtoggle(number):
"""
Toggle a number between positive and negative.
The converter works as follows:
- 1 > -1
- -1 > 1
- 0 > 0
:type number: number
:param number: The number to toggle.
"""
if bool(number > 0):
return number - number * 2
elif bool(number < 0):
return number + abs(number) * 2
elif bool(number == 0):
return number | [
"def",
"posnegtoggle",
"(",
"number",
")",
":",
"if",
"bool",
"(",
"number",
">",
"0",
")",
":",
"return",
"number",
"-",
"number",
"*",
"2",
"elif",
"bool",
"(",
"number",
"<",
"0",
")",
":",
"return",
"number",
"+",
"abs",
"(",
"number",
")",
"... | Toggle a number between positive and negative.
The converter works as follows:
- 1 > -1
- -1 > 1
- 0 > 0
:type number: number
:param number: The number to toggle. | [
"Toggle",
"a",
"number",
"between",
"positive",
"and",
"negative",
".",
"The",
"converter",
"works",
"as",
"follows",
":"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1354-L1371 |
Richienb/quilt | src/quilt_lang/__init__.py | compare | def compare(value1, value2, comparison):
"""
Compare 2 values
:type value1: object
:param value1: The first value to compare.
:type value2: object
:param value2: The second value to compare.
:type comparison: string
:param comparison: The comparison to make. Can be "is", "or", "and".
:return: If the value is, or, and of another value
:rtype: boolean
"""
if not isinstance(comparison, str):
raise TypeError("Comparison argument must be a string.")
if comparison == 'is':
return value1 == value2
elif comparison == 'or':
return value1 or value2
elif comparison == 'and':
return value1 and value2
raise ValueError("Invalid comparison operator specified.") | python | def compare(value1, value2, comparison):
"""
Compare 2 values
:type value1: object
:param value1: The first value to compare.
:type value2: object
:param value2: The second value to compare.
:type comparison: string
:param comparison: The comparison to make. Can be "is", "or", "and".
:return: If the value is, or, and of another value
:rtype: boolean
"""
if not isinstance(comparison, str):
raise TypeError("Comparison argument must be a string.")
if comparison == 'is':
return value1 == value2
elif comparison == 'or':
return value1 or value2
elif comparison == 'and':
return value1 and value2
raise ValueError("Invalid comparison operator specified.") | [
"def",
"compare",
"(",
"value1",
",",
"value2",
",",
"comparison",
")",
":",
"if",
"not",
"isinstance",
"(",
"comparison",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Comparison argument must be a string.\"",
")",
"if",
"comparison",
"==",
"'is'",
":",... | Compare 2 values
:type value1: object
:param value1: The first value to compare.
:type value2: object
:param value2: The second value to compare.
:type comparison: string
:param comparison: The comparison to make. Can be "is", "or", "and".
:return: If the value is, or, and of another value
:rtype: boolean | [
"Compare",
"2",
"values"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1408-L1432 |
Richienb/quilt | src/quilt_lang/__init__.py | factors | def factors(number):
"""
Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for.
"""
if not (isinstance(number, int)):
raise TypeError(
"Incorrect number type provided. Only integers are accepted.")
factors = []
for i in range(1, number + 1):
if number % i == 0:
factors.append(i)
return factors | python | def factors(number):
"""
Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for.
"""
if not (isinstance(number, int)):
raise TypeError(
"Incorrect number type provided. Only integers are accepted.")
factors = []
for i in range(1, number + 1):
if number % i == 0:
factors.append(i)
return factors | [
"def",
"factors",
"(",
"number",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"number",
",",
"int",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Incorrect number type provided. Only integers are accepted.\"",
")",
"factors",
"=",
"[",
"]",
"for",
"i",
"in",
... | Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for. | [
"Find",
"all",
"of",
"the",
"factors",
"of",
"a",
"number",
"and",
"return",
"it",
"as",
"a",
"list",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1435-L1451 |
Richienb/quilt | src/quilt_lang/__init__.py | randomnum | def randomnum(minimum=1, maximum=2, seed=None):
"""
Generate a random number.
:type minimum: integer
:param minimum: The minimum number to generate.
:type maximum: integer
:param maximum: The maximum number to generate.
:type seed: integer
:param seed: A seed to use when generating the random number.
:return: The randomized number.
:rtype: integer
:raises TypeError: Minimum number is not a number.
:raises TypeError: Maximum number is not a number.
>>> randomnum(1, 100, 150)
42
"""
if not (isnum(minimum)):
raise TypeError("Minimum number is not a number.")
if not (isnum(maximum)):
raise TypeError("Maximum number is not a number.")
if seed is None:
return random.randint(minimum, maximum)
random.seed(seed)
return random.randint(minimum, maximum) | python | def randomnum(minimum=1, maximum=2, seed=None):
"""
Generate a random number.
:type minimum: integer
:param minimum: The minimum number to generate.
:type maximum: integer
:param maximum: The maximum number to generate.
:type seed: integer
:param seed: A seed to use when generating the random number.
:return: The randomized number.
:rtype: integer
:raises TypeError: Minimum number is not a number.
:raises TypeError: Maximum number is not a number.
>>> randomnum(1, 100, 150)
42
"""
if not (isnum(minimum)):
raise TypeError("Minimum number is not a number.")
if not (isnum(maximum)):
raise TypeError("Maximum number is not a number.")
if seed is None:
return random.randint(minimum, maximum)
random.seed(seed)
return random.randint(minimum, maximum) | [
"def",
"randomnum",
"(",
"minimum",
"=",
"1",
",",
"maximum",
"=",
"2",
",",
"seed",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isnum",
"(",
"minimum",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Minimum number is not a number.\"",
")",
"if",
"not",
"(... | Generate a random number.
:type minimum: integer
:param minimum: The minimum number to generate.
:type maximum: integer
:param maximum: The maximum number to generate.
:type seed: integer
:param seed: A seed to use when generating the random number.
:return: The randomized number.
:rtype: integer
:raises TypeError: Minimum number is not a number.
:raises TypeError: Maximum number is not a number.
>>> randomnum(1, 100, 150)
42 | [
"Generate",
"a",
"random",
"number",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1493-L1526 |
Richienb/quilt | src/quilt_lang/__init__.py | tokhex | def tokhex(length=10, urlsafe=False):
"""
Return a random string in hexadecimal
"""
if urlsafe is True:
return secrets.token_urlsafe(length)
return secrets.token_hex(length) | python | def tokhex(length=10, urlsafe=False):
"""
Return a random string in hexadecimal
"""
if urlsafe is True:
return secrets.token_urlsafe(length)
return secrets.token_hex(length) | [
"def",
"tokhex",
"(",
"length",
"=",
"10",
",",
"urlsafe",
"=",
"False",
")",
":",
"if",
"urlsafe",
"is",
"True",
":",
"return",
"secrets",
".",
"token_urlsafe",
"(",
"length",
")",
"return",
"secrets",
".",
"token_hex",
"(",
"length",
")"
] | Return a random string in hexadecimal | [
"Return",
"a",
"random",
"string",
"in",
"hexadecimal"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1529-L1535 |
Richienb/quilt | src/quilt_lang/__init__.py | isfib | def isfib(number):
"""
Check if a number is in the Fibonacci sequence.
:type number: integer
:param number: Number to check
"""
num1 = 1
num2 = 1
while True:
if num2 < number:
tempnum = num2
num2 += num1
num1 = tempnum
elif num2 == number:
return True
else:
return False | python | def isfib(number):
"""
Check if a number is in the Fibonacci sequence.
:type number: integer
:param number: Number to check
"""
num1 = 1
num2 = 1
while True:
if num2 < number:
tempnum = num2
num2 += num1
num1 = tempnum
elif num2 == number:
return True
else:
return False | [
"def",
"isfib",
"(",
"number",
")",
":",
"num1",
"=",
"1",
"num2",
"=",
"1",
"while",
"True",
":",
"if",
"num2",
"<",
"number",
":",
"tempnum",
"=",
"num2",
"num2",
"+=",
"num1",
"num1",
"=",
"tempnum",
"elif",
"num2",
"==",
"number",
":",
"return"... | Check if a number is in the Fibonacci sequence.
:type number: integer
:param number: Number to check | [
"Check",
"if",
"a",
"number",
"is",
"in",
"the",
"Fibonacci",
"sequence",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1538-L1556 |
Richienb/quilt | src/quilt_lang/__init__.py | isprime | def isprime(number):
"""
Check if a number is a prime number
:type number: integer
:param number: The number to check
"""
if number == 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True | python | def isprime(number):
"""
Check if a number is a prime number
:type number: integer
:param number: The number to check
"""
if number == 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True | [
"def",
"isprime",
"(",
"number",
")",
":",
"if",
"number",
"==",
"1",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"int",
"(",
"number",
"**",
"0.5",
")",
"+",
"1",
")",
":",
"if",
"number",
"%",
"i",
"==",
"0",
":",
"ret... | Check if a number is a prime number
:type number: integer
:param number: The number to check | [
"Check",
"if",
"a",
"number",
"is",
"a",
"prime",
"number"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1559-L1572 |
Richienb/quilt | src/quilt_lang/__init__.py | convertbase | def convertbase(number, base=10):
"""
Convert a number in base 10 to another base
:type number: number
:param number: The number to convert
:type base: integer
:param base: The base to convert to.
"""
integer = number
if not integer:
return '0'
sign = 1 if integer > 0 else -1
alphanum = string.digits + string.ascii_lowercase
nums = alphanum[:base]
res = ''
integer *= sign
while integer:
integer, mod = divmod(integer, base)
res += nums[mod]
return ('' if sign == 1 else '-') + res[::-1] | python | def convertbase(number, base=10):
"""
Convert a number in base 10 to another base
:type number: number
:param number: The number to convert
:type base: integer
:param base: The base to convert to.
"""
integer = number
if not integer:
return '0'
sign = 1 if integer > 0 else -1
alphanum = string.digits + string.ascii_lowercase
nums = alphanum[:base]
res = ''
integer *= sign
while integer:
integer, mod = divmod(integer, base)
res += nums[mod]
return ('' if sign == 1 else '-') + res[::-1] | [
"def",
"convertbase",
"(",
"number",
",",
"base",
"=",
"10",
")",
":",
"integer",
"=",
"number",
"if",
"not",
"integer",
":",
"return",
"'0'",
"sign",
"=",
"1",
"if",
"integer",
">",
"0",
"else",
"-",
"1",
"alphanum",
"=",
"string",
".",
"digits",
... | Convert a number in base 10 to another base
:type number: number
:param number: The number to convert
:type base: integer
:param base: The base to convert to. | [
"Convert",
"a",
"number",
"in",
"base",
"10",
"to",
"another",
"base"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1575-L1597 |
Richienb/quilt | src/quilt_lang/__init__.py | quadrant | def quadrant(xcoord, ycoord):
"""
Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for
"""
xneg = bool(xcoord < 0)
yneg = bool(ycoord < 0)
if xneg is True:
if yneg is False:
return 2
return 3
if yneg is False:
return 1
return 4 | python | def quadrant(xcoord, ycoord):
"""
Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for
"""
xneg = bool(xcoord < 0)
yneg = bool(ycoord < 0)
if xneg is True:
if yneg is False:
return 2
return 3
if yneg is False:
return 1
return 4 | [
"def",
"quadrant",
"(",
"xcoord",
",",
"ycoord",
")",
":",
"xneg",
"=",
"bool",
"(",
"xcoord",
"<",
"0",
")",
"yneg",
"=",
"bool",
"(",
"ycoord",
"<",
"0",
")",
"if",
"xneg",
"is",
"True",
":",
"if",
"yneg",
"is",
"False",
":",
"return",
"2",
"... | Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for | [
"Find",
"the",
"quadrant",
"a",
"pair",
"of",
"coordinates",
"are",
"located",
"in"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1614-L1633 |
Richienb/quilt | src/quilt_lang/__init__.py | flipcoords | def flipcoords(xcoord, ycoord, axis):
"""
Flip the coordinates over a specific axis, to a different quadrant
:type xcoord: integer
:param xcoord: The x coordinate to flip
:type ycoord: integer
:param ycoord: The y coordinate to flip
:type axis: string
:param axis: The axis to flip across. Could be 'x' or 'y'
"""
axis = axis.lower()
if axis == 'y':
if xcoord > 0:
return str(xcoord - xcoord - xcoord) + ', ' + str(ycoord)
elif xcoord < 0:
return str(xcoord + abs(xcoord) * 2) + ', ' + str(ycoord)
elif xcoord == 0:
return str(xcoord) + ', ' + str(ycoord)
raise ValueError(
"The X coordinate is neither larger, smaller or the same as 0.")
elif axis == 'x':
if ycoord > 0:
return str(xcoord) + ', ' + str(ycoord - ycoord - ycoord)
elif ycoord < 0:
return str(ycoord + abs(ycoord) * 2) + ', ' + str(xcoord)
elif ycoord == 0:
return str(xcoord) + ', ' + str(ycoord)
raise ValueError(
"The Y coordinate is neither larger, smaller or the same as 0.")
raise ValueError("Invalid axis. Neither x nor y was specified.") | python | def flipcoords(xcoord, ycoord, axis):
"""
Flip the coordinates over a specific axis, to a different quadrant
:type xcoord: integer
:param xcoord: The x coordinate to flip
:type ycoord: integer
:param ycoord: The y coordinate to flip
:type axis: string
:param axis: The axis to flip across. Could be 'x' or 'y'
"""
axis = axis.lower()
if axis == 'y':
if xcoord > 0:
return str(xcoord - xcoord - xcoord) + ', ' + str(ycoord)
elif xcoord < 0:
return str(xcoord + abs(xcoord) * 2) + ', ' + str(ycoord)
elif xcoord == 0:
return str(xcoord) + ', ' + str(ycoord)
raise ValueError(
"The X coordinate is neither larger, smaller or the same as 0.")
elif axis == 'x':
if ycoord > 0:
return str(xcoord) + ', ' + str(ycoord - ycoord - ycoord)
elif ycoord < 0:
return str(ycoord + abs(ycoord) * 2) + ', ' + str(xcoord)
elif ycoord == 0:
return str(xcoord) + ', ' + str(ycoord)
raise ValueError(
"The Y coordinate is neither larger, smaller or the same as 0.")
raise ValueError("Invalid axis. Neither x nor y was specified.") | [
"def",
"flipcoords",
"(",
"xcoord",
",",
"ycoord",
",",
"axis",
")",
":",
"axis",
"=",
"axis",
".",
"lower",
"(",
")",
"if",
"axis",
"==",
"'y'",
":",
"if",
"xcoord",
">",
"0",
":",
"return",
"str",
"(",
"xcoord",
"-",
"xcoord",
"-",
"xcoord",
")... | Flip the coordinates over a specific axis, to a different quadrant
:type xcoord: integer
:param xcoord: The x coordinate to flip
:type ycoord: integer
:param ycoord: The y coordinate to flip
:type axis: string
:param axis: The axis to flip across. Could be 'x' or 'y' | [
"Flip",
"the",
"coordinates",
"over",
"a",
"specific",
"axis",
"to",
"a",
"different",
"quadrant"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1636-L1670 |
Richienb/quilt | src/quilt_lang/__init__.py | lcm | def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
:type num1: number
:param num1: The first number to find the lcm for
:type num2: number
:param num2: The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bigger % num2 == 0:
return bigger
bigger += 1 | python | def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
:type num1: number
:param num1: The first number to find the lcm for
:type num2: number
:param num2: The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bigger % num2 == 0:
return bigger
bigger += 1 | [
"def",
"lcm",
"(",
"num1",
",",
"num2",
")",
":",
"if",
"num1",
">",
"num2",
":",
"bigger",
"=",
"num1",
"else",
":",
"bigger",
"=",
"num2",
"while",
"True",
":",
"if",
"bigger",
"%",
"num1",
"==",
"0",
"and",
"bigger",
"%",
"num2",
"==",
"0",
... | Find the lowest common multiple of 2 numbers
:type num1: number
:param num1: The first number to find the lcm for
:type num2: number
:param num2: The second number to find the lcm for | [
"Find",
"the",
"lowest",
"common",
"multiple",
"of",
"2",
"numbers"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1673-L1691 |
Richienb/quilt | src/quilt_lang/__init__.py | hcf | def hcf(num1, num2):
"""
Find the highest common factor of 2 numbers
:type num1: number
:param num1: The first number to find the hcf for
:type num2: number
:param num2: The second number to find the hcf for
"""
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1, smaller + 1):
if ((num1 % i == 0) and (num2 % i == 0)):
return i | python | def hcf(num1, num2):
"""
Find the highest common factor of 2 numbers
:type num1: number
:param num1: The first number to find the hcf for
:type num2: number
:param num2: The second number to find the hcf for
"""
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1, smaller + 1):
if ((num1 % i == 0) and (num2 % i == 0)):
return i | [
"def",
"hcf",
"(",
"num1",
",",
"num2",
")",
":",
"if",
"num1",
">",
"num2",
":",
"smaller",
"=",
"num2",
"else",
":",
"smaller",
"=",
"num1",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"smaller",
"+",
"1",
")",
":",
"if",
"(",
"(",
"num1",
"%... | Find the highest common factor of 2 numbers
:type num1: number
:param num1: The first number to find the hcf for
:type num2: number
:param num2: The second number to find the hcf for | [
"Find",
"the",
"highest",
"common",
"factor",
"of",
"2",
"numbers"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1694-L1711 |
Richienb/quilt | src/quilt_lang/__init__.py | randstring | def randstring(length=1):
"""
Generate a random string consisting of letters, digits and punctuation
:type length: integer
:param length: The length of the generated string.
"""
charstouse = string.ascii_letters + string.digits + string.punctuation
newpass = ''
for _ in range(length):
newpass += str(charstouse[random.randint(0, len(charstouse) - 1)])
return newpass | python | def randstring(length=1):
"""
Generate a random string consisting of letters, digits and punctuation
:type length: integer
:param length: The length of the generated string.
"""
charstouse = string.ascii_letters + string.digits + string.punctuation
newpass = ''
for _ in range(length):
newpass += str(charstouse[random.randint(0, len(charstouse) - 1)])
return newpass | [
"def",
"randstring",
"(",
"length",
"=",
"1",
")",
":",
"charstouse",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"string",
".",
"punctuation",
"newpass",
"=",
"''",
"for",
"_",
"in",
"range",
"(",
"length",
")",
":",
"newpa... | Generate a random string consisting of letters, digits and punctuation
:type length: integer
:param length: The length of the generated string. | [
"Generate",
"a",
"random",
"string",
"consisting",
"of",
"letters",
"digits",
"and",
"punctuation"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1733-L1744 |
Richienb/quilt | src/quilt_lang/__init__.py | shortentext | def shortentext(text, minlength, placeholder='...'):
"""
Shorten some text by replacing the last part with a placeholder (such as '...')
:type text: string
:param text: The text to shorten
:type minlength: integer
:param minlength: The minimum length before a shortening will occur
:type placeholder: string
:param placeholder: The text to append after removing protruding text.
"""
return textwrap.shorten(text, minlength, placeholder=str(placeholder)) | python | def shortentext(text, minlength, placeholder='...'):
"""
Shorten some text by replacing the last part with a placeholder (such as '...')
:type text: string
:param text: The text to shorten
:type minlength: integer
:param minlength: The minimum length before a shortening will occur
:type placeholder: string
:param placeholder: The text to append after removing protruding text.
"""
return textwrap.shorten(text, minlength, placeholder=str(placeholder)) | [
"def",
"shortentext",
"(",
"text",
",",
"minlength",
",",
"placeholder",
"=",
"'...'",
")",
":",
"return",
"textwrap",
".",
"shorten",
"(",
"text",
",",
"minlength",
",",
"placeholder",
"=",
"str",
"(",
"placeholder",
")",
")"
] | Shorten some text by replacing the last part with a placeholder (such as '...')
:type text: string
:param text: The text to shorten
:type minlength: integer
:param minlength: The minimum length before a shortening will occur
:type placeholder: string
:param placeholder: The text to append after removing protruding text. | [
"Shorten",
"some",
"text",
"by",
"replacing",
"the",
"last",
"part",
"with",
"a",
"placeholder",
"(",
"such",
"as",
"...",
")"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1797-L1811 |
Richienb/quilt | src/quilt_lang/__init__.py | case | def case(text, casingformat='sentence'):
"""
Change the casing of some text.
:type text: string
:param text: The text to change the casing of.
:type casingformat: string
:param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'.
:raises ValueError: Invalid text format specified.
>>> case("HELLO world", "uppercase")
'HELLO WORLD'
"""
# If the lowercase version of the casing format is 'uppercase'
if casingformat.lower() == 'uppercase':
# Return the uppercase version
return str(text.upper())
# If the lowercase version of the casing format is 'lowercase'
elif casingformat.lower() == 'lowercase':
# Return the lowercase version
return str(text.lower())
# If the lowercase version of the casing format is 'sentence'
elif casingformat.lower() == 'sentence':
# Return the sentence case version
return str(text[0].upper()) + str(text[1:])
# If the lowercase version of the casing format is 'caterpillar'
elif casingformat.lower() == 'caterpillar':
# Return the caterpillar case version
return str(text.lower().replace(" ", "_"))
# Raise a warning
raise ValueError("Invalid text format specified.") | python | def case(text, casingformat='sentence'):
"""
Change the casing of some text.
:type text: string
:param text: The text to change the casing of.
:type casingformat: string
:param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'.
:raises ValueError: Invalid text format specified.
>>> case("HELLO world", "uppercase")
'HELLO WORLD'
"""
# If the lowercase version of the casing format is 'uppercase'
if casingformat.lower() == 'uppercase':
# Return the uppercase version
return str(text.upper())
# If the lowercase version of the casing format is 'lowercase'
elif casingformat.lower() == 'lowercase':
# Return the lowercase version
return str(text.lower())
# If the lowercase version of the casing format is 'sentence'
elif casingformat.lower() == 'sentence':
# Return the sentence case version
return str(text[0].upper()) + str(text[1:])
# If the lowercase version of the casing format is 'caterpillar'
elif casingformat.lower() == 'caterpillar':
# Return the caterpillar case version
return str(text.lower().replace(" ", "_"))
# Raise a warning
raise ValueError("Invalid text format specified.") | [
"def",
"case",
"(",
"text",
",",
"casingformat",
"=",
"'sentence'",
")",
":",
"# If the lowercase version of the casing format is 'uppercase'",
"if",
"casingformat",
".",
"lower",
"(",
")",
"==",
"'uppercase'",
":",
"# Return the uppercase version",
"return",
"str",
"("... | Change the casing of some text.
:type text: string
:param text: The text to change the casing of.
:type casingformat: string
:param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'.
:raises ValueError: Invalid text format specified.
>>> case("HELLO world", "uppercase")
'HELLO WORLD' | [
"Change",
"the",
"casing",
"of",
"some",
"text",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1865-L1902 |
Richienb/quilt | src/quilt_lang/__init__.py | encryptstring | def encryptstring(text, password):
"""
Encrypt a string according to a specific password.
:type text: string
:param text: The text to encrypt.
:type pass: string
:param pass: The password to encrypt the text with.
"""
enc = []
for i in enumerate(text):
key_c = password[i[0] % len(password)]
enc_c = chr((ord(i[1]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc).encode()).decode() | python | def encryptstring(text, password):
"""
Encrypt a string according to a specific password.
:type text: string
:param text: The text to encrypt.
:type pass: string
:param pass: The password to encrypt the text with.
"""
enc = []
for i in enumerate(text):
key_c = password[i[0] % len(password)]
enc_c = chr((ord(i[1]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc).encode()).decode() | [
"def",
"encryptstring",
"(",
"text",
",",
"password",
")",
":",
"enc",
"=",
"[",
"]",
"for",
"i",
"in",
"enumerate",
"(",
"text",
")",
":",
"key_c",
"=",
"password",
"[",
"i",
"[",
"0",
"]",
"%",
"len",
"(",
"password",
")",
"]",
"enc_c",
"=",
... | Encrypt a string according to a specific password.
:type text: string
:param text: The text to encrypt.
:type pass: string
:param pass: The password to encrypt the text with. | [
"Encrypt",
"a",
"string",
"according",
"to",
"a",
"specific",
"password",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1934-L1950 |
Richienb/quilt | src/quilt_lang/__init__.py | decryptstring | def decryptstring(enc, password):
"""
Decrypt an encrypted string according to a specific password.
:type enc: string
:param enc: The encrypted text.
:type pass: string
:param pass: The password used to encrypt the text.
"""
dec = []
enc = base64.urlsafe_b64decode(enc).decode()
for i in enumerate(enc):
key_c = password[i[0] % len(password)]
dec_c = chr((256 + ord(i[1]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec) | python | def decryptstring(enc, password):
"""
Decrypt an encrypted string according to a specific password.
:type enc: string
:param enc: The encrypted text.
:type pass: string
:param pass: The password used to encrypt the text.
"""
dec = []
enc = base64.urlsafe_b64decode(enc).decode()
for i in enumerate(enc):
key_c = password[i[0] % len(password)]
dec_c = chr((256 + ord(i[1]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec) | [
"def",
"decryptstring",
"(",
"enc",
",",
"password",
")",
":",
"dec",
"=",
"[",
"]",
"enc",
"=",
"base64",
".",
"urlsafe_b64decode",
"(",
"enc",
")",
".",
"decode",
"(",
")",
"for",
"i",
"in",
"enumerate",
"(",
"enc",
")",
":",
"key_c",
"=",
"passw... | Decrypt an encrypted string according to a specific password.
:type enc: string
:param enc: The encrypted text.
:type pass: string
:param pass: The password used to encrypt the text. | [
"Decrypt",
"an",
"encrypted",
"string",
"according",
"to",
"a",
"specific",
"password",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1953-L1970 |
Richienb/quilt | src/quilt_lang/__init__.py | pipinstall | def pipinstall(packages):
"""
Install one or more pip packages.
:type packages: string or list
:param packages: The package or list of packages to install.
:raises TypeError: Nor a string or a list was provided.
"""
if isinstance(packages, str):
if hasattr(pip, 'main'):
pip.main(['install', packages])
else:
pip._internal.main(['install', packages])
elif isinstance(packages, list):
for i in enumerate(packages):
if hasattr(pip, 'main'):
pip.main(['install', i[1]])
else:
pip._internal.main(['install', i[1]])
else:
raise TypeError("Nor a string or a list was provided.") | python | def pipinstall(packages):
"""
Install one or more pip packages.
:type packages: string or list
:param packages: The package or list of packages to install.
:raises TypeError: Nor a string or a list was provided.
"""
if isinstance(packages, str):
if hasattr(pip, 'main'):
pip.main(['install', packages])
else:
pip._internal.main(['install', packages])
elif isinstance(packages, list):
for i in enumerate(packages):
if hasattr(pip, 'main'):
pip.main(['install', i[1]])
else:
pip._internal.main(['install', i[1]])
else:
raise TypeError("Nor a string or a list was provided.") | [
"def",
"pipinstall",
"(",
"packages",
")",
":",
"if",
"isinstance",
"(",
"packages",
",",
"str",
")",
":",
"if",
"hasattr",
"(",
"pip",
",",
"'main'",
")",
":",
"pip",
".",
"main",
"(",
"[",
"'install'",
",",
"packages",
"]",
")",
"else",
":",
"pip... | Install one or more pip packages.
:type packages: string or list
:param packages: The package or list of packages to install.
:raises TypeError: Nor a string or a list was provided. | [
"Install",
"one",
"or",
"more",
"pip",
"packages",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1992-L2014 |
Richienb/quilt | src/quilt_lang/__init__.py | pipupdate | def pipupdate():
"""
Update all currently installed pip packages
"""
packages = [d for d in pkg_resources.working_set]
subprocess.call('pip install --upgrade ' + ' '.join(packages)) | python | def pipupdate():
"""
Update all currently installed pip packages
"""
packages = [d for d in pkg_resources.working_set]
subprocess.call('pip install --upgrade ' + ' '.join(packages)) | [
"def",
"pipupdate",
"(",
")",
":",
"packages",
"=",
"[",
"d",
"for",
"d",
"in",
"pkg_resources",
".",
"working_set",
"]",
"subprocess",
".",
"call",
"(",
"'pip install --upgrade '",
"+",
"' '",
".",
"join",
"(",
"packages",
")",
")"
] | Update all currently installed pip packages | [
"Update",
"all",
"currently",
"installed",
"pip",
"packages"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2017-L2023 |
Richienb/quilt | src/quilt_lang/__init__.py | dirtool | def dirtool(operation, directory):
"""
Tools For Directories (If Exists, Make And Delete)
:raises ValueError: Nor a string or a list was provided.
"""
operation = operation.lower()
if operation == 'exists':
return bool(os.path.exists(directory))
if operation == 'create':
os.makedirs(directory)
elif operation == 'delete':
os.rmdir(directory)
else:
raise ValueError('Invalid operation provided.') | python | def dirtool(operation, directory):
"""
Tools For Directories (If Exists, Make And Delete)
:raises ValueError: Nor a string or a list was provided.
"""
operation = operation.lower()
if operation == 'exists':
return bool(os.path.exists(directory))
if operation == 'create':
os.makedirs(directory)
elif operation == 'delete':
os.rmdir(directory)
else:
raise ValueError('Invalid operation provided.') | [
"def",
"dirtool",
"(",
"operation",
",",
"directory",
")",
":",
"operation",
"=",
"operation",
".",
"lower",
"(",
")",
"if",
"operation",
"==",
"'exists'",
":",
"return",
"bool",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
")",
"if",
... | Tools For Directories (If Exists, Make And Delete)
:raises ValueError: Nor a string or a list was provided. | [
"Tools",
"For",
"Directories",
"(",
"If",
"Exists",
"Make",
"And",
"Delete",
")"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2026-L2040 |
Richienb/quilt | src/quilt_lang/__init__.py | file | def file(operation, path):
"""
Tools For Files (If Exists, Make And Delete)
"""
operation = operation.lower()
if operation == 'exists':
return bool(os.path.isfile(path))
if operation == 'read':
with open(path, 'r') as f:
return [line.strip() for line in f]
elif operation == 'delete':
os.remove(path)
elif operation == 'create':
open(path, 'w').close()
elif operation == 'clear':
open(path, 'w').close()
else:
raise ValueError('Invalid operation provided.') | python | def file(operation, path):
"""
Tools For Files (If Exists, Make And Delete)
"""
operation = operation.lower()
if operation == 'exists':
return bool(os.path.isfile(path))
if operation == 'read':
with open(path, 'r') as f:
return [line.strip() for line in f]
elif operation == 'delete':
os.remove(path)
elif operation == 'create':
open(path, 'w').close()
elif operation == 'clear':
open(path, 'w').close()
else:
raise ValueError('Invalid operation provided.') | [
"def",
"file",
"(",
"operation",
",",
"path",
")",
":",
"operation",
"=",
"operation",
".",
"lower",
"(",
")",
"if",
"operation",
"==",
"'exists'",
":",
"return",
"bool",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
")",
"if",
"operation"... | Tools For Files (If Exists, Make And Delete) | [
"Tools",
"For",
"Files",
"(",
"If",
"Exists",
"Make",
"And",
"Delete",
")"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2043-L2060 |
Richienb/quilt | src/quilt_lang/__init__.py | loglevel | def loglevel(leveltype=None, isequal=False):
"""
Set or get the logging level of Quilt
:type leveltype: string or integer
:param leveltype: Choose the logging level. Possible choices are none (0), debug (10), info (20), warning (30), error (40) and critical (50).
:type isequal: boolean
:param isequal: Check if level is equal to leveltype.
:return: If the level is equal to leveltype.
:rtype: boolean
>>> loglevel()
30
"""
log = logging.getLogger(__name__)
leveltype = leveltype
loglevels = {
"none": 0,
"debug": 10,
"info": 20,
"warning": 30,
"error": 40,
"critical": 50
}
if leveltype is None and isequal is False:
return log.getEffectiveLevel()
if leveltype is not None and isequal is True:
if leveltype in loglevels.values():
return leveltype == log.getEffectiveLevel()
elif leveltype in loglevels:
return loglevels[leveltype] == log.getEffectiveLevel()
raise ValueError(
"Incorrect input provided. It should be none, debug, info, warning, error or critical."
)
if leveltype in loglevels.values():
log.basicConfig(level=leveltype)
elif leveltype in loglevels:
log.basicConfig(level=loglevels[leveltype])
else:
raise ValueError(
"Incorrect input provided. It should be none, debug, info, warning, error or critical."
) | python | def loglevel(leveltype=None, isequal=False):
"""
Set or get the logging level of Quilt
:type leveltype: string or integer
:param leveltype: Choose the logging level. Possible choices are none (0), debug (10), info (20), warning (30), error (40) and critical (50).
:type isequal: boolean
:param isequal: Check if level is equal to leveltype.
:return: If the level is equal to leveltype.
:rtype: boolean
>>> loglevel()
30
"""
log = logging.getLogger(__name__)
leveltype = leveltype
loglevels = {
"none": 0,
"debug": 10,
"info": 20,
"warning": 30,
"error": 40,
"critical": 50
}
if leveltype is None and isequal is False:
return log.getEffectiveLevel()
if leveltype is not None and isequal is True:
if leveltype in loglevels.values():
return leveltype == log.getEffectiveLevel()
elif leveltype in loglevels:
return loglevels[leveltype] == log.getEffectiveLevel()
raise ValueError(
"Incorrect input provided. It should be none, debug, info, warning, error or critical."
)
if leveltype in loglevels.values():
log.basicConfig(level=leveltype)
elif leveltype in loglevels:
log.basicConfig(level=loglevels[leveltype])
else:
raise ValueError(
"Incorrect input provided. It should be none, debug, info, warning, error or critical."
) | [
"def",
"loglevel",
"(",
"leveltype",
"=",
"None",
",",
"isequal",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"leveltype",
"=",
"leveltype",
"loglevels",
"=",
"{",
"\"none\"",
":",
"0",
",",
"\"debug\"",
":",
... | Set or get the logging level of Quilt
:type leveltype: string or integer
:param leveltype: Choose the logging level. Possible choices are none (0), debug (10), info (20), warning (30), error (40) and critical (50).
:type isequal: boolean
:param isequal: Check if level is equal to leveltype.
:return: If the level is equal to leveltype.
:rtype: boolean
>>> loglevel()
30 | [
"Set",
"or",
"get",
"the",
"logging",
"level",
"of",
"Quilt"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2105-L2148 |
Richienb/quilt | src/quilt_lang/__init__.py | logfile | def logfile(targetfile="ros.log"):
"""
Set the file for Quilt to log to
targetfile:
Change the file to log to.
"""
log = logging.getLogger(__name__)
log.basicConfig(filename=str(targetfile)) | python | def logfile(targetfile="ros.log"):
"""
Set the file for Quilt to log to
targetfile:
Change the file to log to.
"""
log = logging.getLogger(__name__)
log.basicConfig(filename=str(targetfile)) | [
"def",
"logfile",
"(",
"targetfile",
"=",
"\"ros.log\"",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"log",
".",
"basicConfig",
"(",
"filename",
"=",
"str",
"(",
"targetfile",
")",
")"
] | Set the file for Quilt to log to
targetfile:
Change the file to log to. | [
"Set",
"the",
"file",
"for",
"Quilt",
"to",
"log",
"to",
"targetfile",
":",
"Change",
"the",
"file",
"to",
"log",
"to",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2151-L2158 |
Richienb/quilt | src/quilt_lang/__init__.py | text | def text(path, operation, content):
"""
Perform changes on text files
:type path: string
:param path: The path to perform the action on
:type operation: string
:param operation: The operation to use on the file
:type content: string
:param content: The content to use with the operation
"""
# If the operation is "write"
if operation.lower() == 'write':
# Open the file as "fh"
with open(path, 'w') as fh:
# Write to the file
fh.write(content)
# If the operation is "append"
elif operation.lower() == 'append':
# Open the file as "fh"
with open(path, 'a') as fh:
# Write to the file
fh.write(content)
# Raise a warning
raise ValueError("Invalid operation provided") | python | def text(path, operation, content):
"""
Perform changes on text files
:type path: string
:param path: The path to perform the action on
:type operation: string
:param operation: The operation to use on the file
:type content: string
:param content: The content to use with the operation
"""
# If the operation is "write"
if operation.lower() == 'write':
# Open the file as "fh"
with open(path, 'w') as fh:
# Write to the file
fh.write(content)
# If the operation is "append"
elif operation.lower() == 'append':
# Open the file as "fh"
with open(path, 'a') as fh:
# Write to the file
fh.write(content)
# Raise a warning
raise ValueError("Invalid operation provided") | [
"def",
"text",
"(",
"path",
",",
"operation",
",",
"content",
")",
":",
"# If the operation is \"write\"",
"if",
"operation",
".",
"lower",
"(",
")",
"==",
"'write'",
":",
"# Open the file as \"fh\"",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"fh",... | Perform changes on text files
:type path: string
:param path: The path to perform the action on
:type operation: string
:param operation: The operation to use on the file
:type content: string
:param content: The content to use with the operation | [
"Perform",
"changes",
"on",
"text",
"files"
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2161-L2190 |
Richienb/quilt | src/quilt_lang/__init__.py | getdatetime | def getdatetime(timedateformat='complete'):
"""
Get the current date or time in a specific format.
:type timedateformat: string
:param timedateformat: The type of date to query for. Can be: day, month, year, hour, minute, second, millisecond, yearmonthday, daymonthyear, hourminutesecond, secondminutehour, complete, datetime or timedate.
"""
timedateformat = timedateformat.lower()
if timedateformat == 'day':
return ((str(datetime.datetime.now())).split(' ')[0]).split('-')[2]
elif timedateformat == 'month':
return ((str(datetime.datetime.now())).split(' ')[0]).split('-')[1]
elif timedateformat == 'year':
return ((str(datetime.datetime.now())).split(' ')[0]).split('-')[0]
elif timedateformat == 'hour':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[0]
elif timedateformat == 'minute':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[1]
elif timedateformat == 'second':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[2]
elif timedateformat == 'millisecond':
return (str(datetime.datetime.now())).split('.')[1]
elif timedateformat == 'yearmonthday':
return (str(datetime.datetime.now())).split(' ')[0]
elif timedateformat == 'daymonthyear':
return ((str(datetime.datetime.now())).split(' ')[0]).split(
'-')[2] + '-' + ((str(
datetime.datetime.now())).split(' ')[0]).split('-')[1] + '-' + (
(str(datetime.datetime.now())).split(' ')[0]).split('-')[0]
elif timedateformat == 'hourminutesecond':
return ((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
elif timedateformat == 'secondminutehour':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[2] + ':' + (((str(datetime.datetime.now())).split(
' ')[1]).split('.')[0]).split(':')[1] + ':' + (
((str(datetime.datetime.now())).split(' ')[1]
).split('.')[0]).split(':')[0]
elif timedateformat == 'complete':
return str(datetime.datetime.now())
elif timedateformat == 'datetime':
return (str(datetime.datetime.now())).split('.')[0]
elif timedateformat == 'timedate':
return ((str(
datetime.datetime.now())).split('.')[0]).split(' ')[1] + ' ' + (
(str(datetime.datetime.now())).split('.')[0]).split(' ')[0]
else:
raise ValueError("Invalid time date format used.") | python | def getdatetime(timedateformat='complete'):
"""
Get the current date or time in a specific format.
:type timedateformat: string
:param timedateformat: The type of date to query for. Can be: day, month, year, hour, minute, second, millisecond, yearmonthday, daymonthyear, hourminutesecond, secondminutehour, complete, datetime or timedate.
"""
timedateformat = timedateformat.lower()
if timedateformat == 'day':
return ((str(datetime.datetime.now())).split(' ')[0]).split('-')[2]
elif timedateformat == 'month':
return ((str(datetime.datetime.now())).split(' ')[0]).split('-')[1]
elif timedateformat == 'year':
return ((str(datetime.datetime.now())).split(' ')[0]).split('-')[0]
elif timedateformat == 'hour':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[0]
elif timedateformat == 'minute':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[1]
elif timedateformat == 'second':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[2]
elif timedateformat == 'millisecond':
return (str(datetime.datetime.now())).split('.')[1]
elif timedateformat == 'yearmonthday':
return (str(datetime.datetime.now())).split(' ')[0]
elif timedateformat == 'daymonthyear':
return ((str(datetime.datetime.now())).split(' ')[0]).split(
'-')[2] + '-' + ((str(
datetime.datetime.now())).split(' ')[0]).split('-')[1] + '-' + (
(str(datetime.datetime.now())).split(' ')[0]).split('-')[0]
elif timedateformat == 'hourminutesecond':
return ((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
elif timedateformat == 'secondminutehour':
return (((str(datetime.datetime.now())).split(' ')[1]).split('.')[0]
).split(':')[2] + ':' + (((str(datetime.datetime.now())).split(
' ')[1]).split('.')[0]).split(':')[1] + ':' + (
((str(datetime.datetime.now())).split(' ')[1]
).split('.')[0]).split(':')[0]
elif timedateformat == 'complete':
return str(datetime.datetime.now())
elif timedateformat == 'datetime':
return (str(datetime.datetime.now())).split('.')[0]
elif timedateformat == 'timedate':
return ((str(
datetime.datetime.now())).split('.')[0]).split(' ')[1] + ' ' + (
(str(datetime.datetime.now())).split('.')[0]).split(' ')[0]
else:
raise ValueError("Invalid time date format used.") | [
"def",
"getdatetime",
"(",
"timedateformat",
"=",
"'complete'",
")",
":",
"timedateformat",
"=",
"timedateformat",
".",
"lower",
"(",
")",
"if",
"timedateformat",
"==",
"'day'",
":",
"return",
"(",
"(",
"str",
"(",
"datetime",
".",
"datetime",
".",
"now",
... | Get the current date or time in a specific format.
:type timedateformat: string
:param timedateformat: The type of date to query for. Can be: day, month, year, hour, minute, second, millisecond, yearmonthday, daymonthyear, hourminutesecond, secondminutehour, complete, datetime or timedate. | [
"Get",
"the",
"current",
"date",
"or",
"time",
"in",
"a",
"specific",
"format",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2452-L2502 |
Richienb/quilt | src/quilt_lang/__init__.py | mailto | def mailto(to, cc=None, bcc=None, subject=None, body=None):
"""
Generate and run mailto.
:type to: string
:param to: The recipient email address.
:type cc: string
:param cc: The recipient to copy to.
:type bcc: string
:param bcc: The recipient to blind copy to.
:type subject: string
:param subject: The subject to use.
:type body: string
:param body: The body content to use.
"""
mailurl = 'mailto:' + str(to)
if cc is None and bcc is None and subject is None and body is None:
return str(mailurl)
mailurl += '?'
if cc is not None:
mailurl += 'cc=' + str(cc)
added = True
added = False
if bcc is not None:
if added is True:
mailurl += '&'
mailurl += 'bcc=' + str(cc)
added = True
if subject is not None:
if added is True:
mailurl += '&'
mailurl += 'subject=' + str(subject)
added = True
if body is not None:
if added is True:
mailurl += '&'
mailurl += 'body=' + str(body)
added = True
return mailurl | python | def mailto(to, cc=None, bcc=None, subject=None, body=None):
"""
Generate and run mailto.
:type to: string
:param to: The recipient email address.
:type cc: string
:param cc: The recipient to copy to.
:type bcc: string
:param bcc: The recipient to blind copy to.
:type subject: string
:param subject: The subject to use.
:type body: string
:param body: The body content to use.
"""
mailurl = 'mailto:' + str(to)
if cc is None and bcc is None and subject is None and body is None:
return str(mailurl)
mailurl += '?'
if cc is not None:
mailurl += 'cc=' + str(cc)
added = True
added = False
if bcc is not None:
if added is True:
mailurl += '&'
mailurl += 'bcc=' + str(cc)
added = True
if subject is not None:
if added is True:
mailurl += '&'
mailurl += 'subject=' + str(subject)
added = True
if body is not None:
if added is True:
mailurl += '&'
mailurl += 'body=' + str(body)
added = True
return mailurl | [
"def",
"mailto",
"(",
"to",
",",
"cc",
"=",
"None",
",",
"bcc",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"mailurl",
"=",
"'mailto:'",
"+",
"str",
"(",
"to",
")",
"if",
"cc",
"is",
"None",
"and",
"bcc",
"is",... | Generate and run mailto.
:type to: string
:param to: The recipient email address.
:type cc: string
:param cc: The recipient to copy to.
:type bcc: string
:param bcc: The recipient to blind copy to.
:type subject: string
:param subject: The subject to use.
:type body: string
:param body: The body content to use. | [
"Generate",
"and",
"run",
"mailto",
"."
] | train | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L2543-L2586 |
bdastur/spam | pyansible/plugins/virsh.py | Virsh.execute_virsh_command | def execute_virsh_command(self,
**kwargs):
'''
common virsh execution function
'''
host_list = kwargs.get('host_list', None)
remote_user = kwargs.get('remote_user', None)
remote_pass = kwargs.get('remote_pass', None)
sudo = kwargs.get('sudo', False)
sudo_user = kwargs.get('sudo_user', None)
sudo_pass = kwargs.get('sudo_pass', None)
host_list, remote_user, remote_pass, \
sudo, sudo_user, sudo_pass = self.get_validated_params(
host_list, remote_user,
remote_pass, sudo,
sudo_user, sudo_pass)
if 'cmd' not in kwargs.keys():
print "Require a command to execute"
return None
cmd = kwargs['cmd']
if 'delimiter' not in kwargs.keys():
delimiter = ":"
else:
delimiter = kwargs['delimiter']
if 'output_type' not in kwargs.keys():
output_type = "LRVALUE"
else:
output_type = kwargs['output_type']
if output_type == "TABLE":
if 'fields' not in kwargs.keys():
print "Require to pass fields"
return None
fields = kwargs['fields']
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module="command",
module_args=cmd,
sudo=sudo,
sudo_user=sudo_user,
sudo_pass=sudo_pass)
virsh_result = None
if result['contacted'].keys():
virsh_result = {}
for node in result['contacted'].keys():
nodeobj = result['contacted'][node]
if output_type == "LRVALUE":
jsonoutput = rex.parse_lrvalue_string(nodeobj['stdout'],
delimiter)
elif output_type == "TABLE":
jsonoutput = rex.parse_tabular_string(nodeobj['stdout'],
fields)
else:
pass
virsh_result[node] = {}
virsh_result[node]['result'] = jsonoutput
return virsh_result | python | def execute_virsh_command(self,
**kwargs):
'''
common virsh execution function
'''
host_list = kwargs.get('host_list', None)
remote_user = kwargs.get('remote_user', None)
remote_pass = kwargs.get('remote_pass', None)
sudo = kwargs.get('sudo', False)
sudo_user = kwargs.get('sudo_user', None)
sudo_pass = kwargs.get('sudo_pass', None)
host_list, remote_user, remote_pass, \
sudo, sudo_user, sudo_pass = self.get_validated_params(
host_list, remote_user,
remote_pass, sudo,
sudo_user, sudo_pass)
if 'cmd' not in kwargs.keys():
print "Require a command to execute"
return None
cmd = kwargs['cmd']
if 'delimiter' not in kwargs.keys():
delimiter = ":"
else:
delimiter = kwargs['delimiter']
if 'output_type' not in kwargs.keys():
output_type = "LRVALUE"
else:
output_type = kwargs['output_type']
if output_type == "TABLE":
if 'fields' not in kwargs.keys():
print "Require to pass fields"
return None
fields = kwargs['fields']
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module="command",
module_args=cmd,
sudo=sudo,
sudo_user=sudo_user,
sudo_pass=sudo_pass)
virsh_result = None
if result['contacted'].keys():
virsh_result = {}
for node in result['contacted'].keys():
nodeobj = result['contacted'][node]
if output_type == "LRVALUE":
jsonoutput = rex.parse_lrvalue_string(nodeobj['stdout'],
delimiter)
elif output_type == "TABLE":
jsonoutput = rex.parse_tabular_string(nodeobj['stdout'],
fields)
else:
pass
virsh_result[node] = {}
virsh_result[node]['result'] = jsonoutput
return virsh_result | [
"def",
"execute_virsh_command",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"host_list",
"=",
"kwargs",
".",
"get",
"(",
"'host_list'",
",",
"None",
")",
"remote_user",
"=",
"kwargs",
".",
"get",
"(",
"'remote_user'",
",",
"None",
")",
"remote_pass",
... | common virsh execution function | [
"common",
"virsh",
"execution",
"function"
] | train | https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/plugins/virsh.py#L56-L122 |
bdastur/spam | pyansible/plugins/virsh.py | Virsh.virsh_version | def virsh_version(self,
host_list=None,
remote_user=None,
remote_pass=None,
sudo=False,
sudo_user=None,
sudo_pass=None):
'''
Get the virsh version
'''
host_list, remote_user, remote_pass, \
sudo, sudo_user, sudo_pass = self.get_validated_params(
host_list, remote_user, remote_pass, sudo, sudo_user,
sudo_pass)
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module="command",
module_args="virsh version",
sudo=sudo,
sudo_user=sudo_user,
sudo_pass=sudo_pass)
virsh_result = None
if result['contacted'].keys():
virsh_result = {}
for node in result['contacted'].keys():
nodeobj = result['contacted'][node]
jsonoutput = rex.parse_lrvalue_string(nodeobj['stdout'], ":")
virsh_result[node] = {}
virsh_result[node]['result'] = jsonoutput
return virsh_result | python | def virsh_version(self,
host_list=None,
remote_user=None,
remote_pass=None,
sudo=False,
sudo_user=None,
sudo_pass=None):
'''
Get the virsh version
'''
host_list, remote_user, remote_pass, \
sudo, sudo_user, sudo_pass = self.get_validated_params(
host_list, remote_user, remote_pass, sudo, sudo_user,
sudo_pass)
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module="command",
module_args="virsh version",
sudo=sudo,
sudo_user=sudo_user,
sudo_pass=sudo_pass)
virsh_result = None
if result['contacted'].keys():
virsh_result = {}
for node in result['contacted'].keys():
nodeobj = result['contacted'][node]
jsonoutput = rex.parse_lrvalue_string(nodeobj['stdout'], ":")
virsh_result[node] = {}
virsh_result[node]['result'] = jsonoutput
return virsh_result | [
"def",
"virsh_version",
"(",
"self",
",",
"host_list",
"=",
"None",
",",
"remote_user",
"=",
"None",
",",
"remote_pass",
"=",
"None",
",",
"sudo",
"=",
"False",
",",
"sudo_user",
"=",
"None",
",",
"sudo_pass",
"=",
"None",
")",
":",
"host_list",
",",
"... | Get the virsh version | [
"Get",
"the",
"virsh",
"version"
] | train | https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/plugins/virsh.py#L124-L160 |
bdastur/spam | pyansible/plugins/virsh.py | Virsh.virsh_per_domain_info | def virsh_per_domain_info(self,
**kwargs):
'''
Get per domain stats from each hosts passed as hostlist.
'''
host_list = kwargs.get('host_list', self.host_list)
remote_user = kwargs.get('remote_user', self.remote_user)
remote_pass = kwargs.get('remote_pass', self.remote_pass)
sudo = kwargs.get('sudo', self.sudo)
sudo_user = kwargs.get('sudo_user', self.sudo_user)
sudo_pass = kwargs.get('sudo_pass', self.sudo_pass)
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module="command",
module_args="virsh list",
sudo=sudo,
sudo_user=sudo_user,
sudo_pass=sudo_pass)
virsh_result = None
fields = ["Id", "Name", "state"]
if result['contacted'].keys():
virsh_result = {}
for node in result['contacted'].keys():
nodeobj = result['contacted'][node]
jsonoutput = rex.parse_tabular_string(nodeobj['stdout'],
fields)
virsh_result[node] = {}
virsh_result[node]['result'] = jsonoutput
print virsh_result
return virsh_result | python | def virsh_per_domain_info(self,
**kwargs):
'''
Get per domain stats from each hosts passed as hostlist.
'''
host_list = kwargs.get('host_list', self.host_list)
remote_user = kwargs.get('remote_user', self.remote_user)
remote_pass = kwargs.get('remote_pass', self.remote_pass)
sudo = kwargs.get('sudo', self.sudo)
sudo_user = kwargs.get('sudo_user', self.sudo_user)
sudo_pass = kwargs.get('sudo_pass', self.sudo_pass)
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module="command",
module_args="virsh list",
sudo=sudo,
sudo_user=sudo_user,
sudo_pass=sudo_pass)
virsh_result = None
fields = ["Id", "Name", "state"]
if result['contacted'].keys():
virsh_result = {}
for node in result['contacted'].keys():
nodeobj = result['contacted'][node]
jsonoutput = rex.parse_tabular_string(nodeobj['stdout'],
fields)
virsh_result[node] = {}
virsh_result[node]['result'] = jsonoutput
print virsh_result
return virsh_result | [
"def",
"virsh_per_domain_info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"host_list",
"=",
"kwargs",
".",
"get",
"(",
"'host_list'",
",",
"self",
".",
"host_list",
")",
"remote_user",
"=",
"kwargs",
".",
"get",
"(",
"'remote_user'",
",",
"self",
"... | Get per domain stats from each hosts passed as hostlist. | [
"Get",
"per",
"domain",
"stats",
"from",
"each",
"hosts",
"passed",
"as",
"hostlist",
"."
] | train | https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/plugins/virsh.py#L205-L243 |
fake-name/WebRequest | WebRequest/UA_Constants.py | getUserAgent | def getUserAgent():
'''
Generate a randomized user agent by permuting a large set of possible values.
The returned user agent should look like a valid, in-use brower, with a specified preferred language of english.
Return value is a list of tuples, where each tuple is one of the user-agent headers.
Currently can provide approximately 147 * 17 * 5 * 5 * 2 * 3 * 2 values, or ~749K possible
unique user-agents.
'''
coding = random.choice(ENCODINGS)
random.shuffle(coding)
coding = random.choice((", ", ",")).join(coding)
accept_list = [tmp for tmp in random.choice(ACCEPT)]
accept_list.append(random.choice(ACCEPT_POSTFIX))
accept_str = random.choice((", ", ",")).join(accept_list)
assert accept_str.count("*.*") <= 1
user_agent = [
('User-Agent' , random.choice(USER_AGENTS)),
('Accept-Language' , random.choice(ACCEPT_LANGUAGE)),
('Accept' , accept_str),
('Accept-Encoding' , coding)
]
return user_agent | python | def getUserAgent():
'''
Generate a randomized user agent by permuting a large set of possible values.
The returned user agent should look like a valid, in-use brower, with a specified preferred language of english.
Return value is a list of tuples, where each tuple is one of the user-agent headers.
Currently can provide approximately 147 * 17 * 5 * 5 * 2 * 3 * 2 values, or ~749K possible
unique user-agents.
'''
coding = random.choice(ENCODINGS)
random.shuffle(coding)
coding = random.choice((", ", ",")).join(coding)
accept_list = [tmp for tmp in random.choice(ACCEPT)]
accept_list.append(random.choice(ACCEPT_POSTFIX))
accept_str = random.choice((", ", ",")).join(accept_list)
assert accept_str.count("*.*") <= 1
user_agent = [
('User-Agent' , random.choice(USER_AGENTS)),
('Accept-Language' , random.choice(ACCEPT_LANGUAGE)),
('Accept' , accept_str),
('Accept-Encoding' , coding)
]
return user_agent | [
"def",
"getUserAgent",
"(",
")",
":",
"coding",
"=",
"random",
".",
"choice",
"(",
"ENCODINGS",
")",
"random",
".",
"shuffle",
"(",
"coding",
")",
"coding",
"=",
"random",
".",
"choice",
"(",
"(",
"\", \"",
",",
"\",\"",
")",
")",
".",
"join",
"(",
... | Generate a randomized user agent by permuting a large set of possible values.
The returned user agent should look like a valid, in-use brower, with a specified preferred language of english.
Return value is a list of tuples, where each tuple is one of the user-agent headers.
Currently can provide approximately 147 * 17 * 5 * 5 * 2 * 3 * 2 values, or ~749K possible
unique user-agents. | [
"Generate",
"a",
"randomized",
"user",
"agent",
"by",
"permuting",
"a",
"large",
"set",
"of",
"possible",
"values",
".",
"The",
"returned",
"user",
"agent",
"should",
"look",
"like",
"a",
"valid",
"in",
"-",
"use",
"brower",
"with",
"a",
"specified",
"pref... | train | https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/UA_Constants.py#L137-L164 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer.get_generator | def get_generator(self):
"""Return the generator object to anonymize data."""
faker = Faker()
try:
return getattr(faker, self.category)
except AttributeError:
raise ValueError('Category {} couldn\'t be found on faker') | python | def get_generator(self):
"""Return the generator object to anonymize data."""
faker = Faker()
try:
return getattr(faker, self.category)
except AttributeError:
raise ValueError('Category {} couldn\'t be found on faker') | [
"def",
"get_generator",
"(",
"self",
")",
":",
"faker",
"=",
"Faker",
"(",
")",
"try",
":",
"return",
"getattr",
"(",
"faker",
",",
"self",
".",
"category",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"'Category {} couldn\\'t be found on ... | Return the generator object to anonymize data. | [
"Return",
"the",
"generator",
"object",
"to",
"anonymize",
"data",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L56-L65 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer.anonymize_column | def anonymize_column(self, col):
"""Map the values of column to new ones of the same type.
It replaces the values from others generated using `faker`. It will however,
keep the original distribution. That mean that the generated `probability_map` for both
will have the same values, but different keys.
Args:
col (pandas.DataFrame): Dataframe containing the column to anonymize.
Returns:
pd.DataFrame: DataFrame with its values mapped to new ones,
keeping the original distribution.
Raises:
ValueError: A `ValueError` is raised if faker is not able to provide enought
different values.
"""
column = col[self.col_name]
generator = self.get_generator()
original_values = column[~pd.isnull(column)].unique()
new_values = [generator() for x in range(len(original_values))]
if len(new_values) != len(set(new_values)):
raise ValueError(
'There are not enought different values on faker provider'
'for category {}'.format(self.category)
)
value_map = dict(zip(original_values, new_values))
column = column.apply(value_map.get)
return column.to_frame() | python | def anonymize_column(self, col):
"""Map the values of column to new ones of the same type.
It replaces the values from others generated using `faker`. It will however,
keep the original distribution. That mean that the generated `probability_map` for both
will have the same values, but different keys.
Args:
col (pandas.DataFrame): Dataframe containing the column to anonymize.
Returns:
pd.DataFrame: DataFrame with its values mapped to new ones,
keeping the original distribution.
Raises:
ValueError: A `ValueError` is raised if faker is not able to provide enought
different values.
"""
column = col[self.col_name]
generator = self.get_generator()
original_values = column[~pd.isnull(column)].unique()
new_values = [generator() for x in range(len(original_values))]
if len(new_values) != len(set(new_values)):
raise ValueError(
'There are not enought different values on faker provider'
'for category {}'.format(self.category)
)
value_map = dict(zip(original_values, new_values))
column = column.apply(value_map.get)
return column.to_frame() | [
"def",
"anonymize_column",
"(",
"self",
",",
"col",
")",
":",
"column",
"=",
"col",
"[",
"self",
".",
"col_name",
"]",
"generator",
"=",
"self",
".",
"get_generator",
"(",
")",
"original_values",
"=",
"column",
"[",
"~",
"pd",
".",
"isnull",
"(",
"colu... | Map the values of column to new ones of the same type.
It replaces the values from others generated using `faker`. It will however,
keep the original distribution. That mean that the generated `probability_map` for both
will have the same values, but different keys.
Args:
col (pandas.DataFrame): Dataframe containing the column to anonymize.
Returns:
pd.DataFrame: DataFrame with its values mapped to new ones,
keeping the original distribution.
Raises:
ValueError: A `ValueError` is raised if faker is not able to provide enought
different values. | [
"Map",
"the",
"values",
"of",
"column",
"to",
"new",
"ones",
"of",
"the",
"same",
"type",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L67-L101 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer._fit | def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict()
# next set probability ranges on interval [0,1]
start = 0
end = 0
num_vals = len(col)
for val in frequencies:
prob = frequencies[val] / num_vals
end = start + prob
interval = (start, end)
mean = np.mean(interval)
std = prob / 6
self.probability_map[val] = (interval, mean, std)
start = end | python | def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict()
# next set probability ranges on interval [0,1]
start = 0
end = 0
num_vals = len(col)
for val in frequencies:
prob = frequencies[val] / num_vals
end = start + prob
interval = (start, end)
mean = np.mean(interval)
std = prob / 6
self.probability_map[val] = (interval, mean, std)
start = end | [
"def",
"_fit",
"(",
"self",
",",
"col",
")",
":",
"column",
"=",
"col",
"[",
"self",
".",
"col_name",
"]",
".",
"replace",
"(",
"{",
"np",
".",
"nan",
":",
"np",
".",
"inf",
"}",
")",
"frequencies",
"=",
"column",
".",
"groupby",
"(",
"column",
... | Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform. | [
"Create",
"a",
"map",
"of",
"the",
"empirical",
"probability",
"for",
"each",
"category",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L124-L145 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer.transform | def transform(self, col):
"""Prepare the transformer to convert data and return the processed table.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
out = pd.DataFrame()
# Make sure all nans are handled the same by replacing with None
column = col[self.col_name].replace({np.nan: None})
out[self.col_name] = column.apply(self.get_val)
return out | python | def transform(self, col):
"""Prepare the transformer to convert data and return the processed table.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
out = pd.DataFrame()
# Make sure all nans are handled the same by replacing with None
column = col[self.col_name].replace({np.nan: None})
out[self.col_name] = column.apply(self.get_val)
return out | [
"def",
"transform",
"(",
"self",
",",
"col",
")",
":",
"out",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"# Make sure all nans are handled the same by replacing with None",
"column",
"=",
"col",
"[",
"self",
".",
"col_name",
"]",
".",
"replace",
"(",
"{",
"np",
... | Prepare the transformer to convert data and return the processed table.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame | [
"Prepare",
"the",
"transformer",
"to",
"convert",
"data",
"and",
"return",
"the",
"processed",
"table",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L147-L163 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer.fit_transform | def fit_transform(self, col):
"""Prepare the transformer and return processed data.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
if self.anonymize:
col = self.anonymize_column(col)
self._fit(col)
return self.transform(col) | python | def fit_transform(self, col):
"""Prepare the transformer and return processed data.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
if self.anonymize:
col = self.anonymize_column(col)
self._fit(col)
return self.transform(col) | [
"def",
"fit_transform",
"(",
"self",
",",
"col",
")",
":",
"if",
"self",
".",
"anonymize",
":",
"col",
"=",
"self",
".",
"anonymize_column",
"(",
"col",
")",
"self",
".",
"_fit",
"(",
"col",
")",
"return",
"self",
".",
"transform",
"(",
"col",
")"
] | Prepare the transformer and return processed data.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame | [
"Prepare",
"the",
"transformer",
"and",
"return",
"processed",
"data",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L165-L179 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer.reverse_transform | def reverse_transform(self, col):
"""Converts data back into original format.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
output = pd.DataFrame()
output[self.col_name] = self.get_category(col[self.col_name])
return output | python | def reverse_transform(self, col):
"""Converts data back into original format.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
output = pd.DataFrame()
output[self.col_name] = self.get_category(col[self.col_name])
return output | [
"def",
"reverse_transform",
"(",
"self",
",",
"col",
")",
":",
"output",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"output",
"[",
"self",
".",
"col_name",
"]",
"=",
"self",
".",
"get_category",
"(",
"col",
"[",
"self",
".",
"col_name",
"]",
")",
"return... | Converts data back into original format.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame | [
"Converts",
"data",
"back",
"into",
"original",
"format",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L181-L194 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer.get_val | def get_val(self, x):
"""Convert cat value into num between 0 and 1."""
interval, mean, std = self.probability_map[x]
new_val = norm.rvs(mean, std)
return new_val | python | def get_val(self, x):
"""Convert cat value into num between 0 and 1."""
interval, mean, std = self.probability_map[x]
new_val = norm.rvs(mean, std)
return new_val | [
"def",
"get_val",
"(",
"self",
",",
"x",
")",
":",
"interval",
",",
"mean",
",",
"std",
"=",
"self",
".",
"probability_map",
"[",
"x",
"]",
"new_val",
"=",
"norm",
".",
"rvs",
"(",
"mean",
",",
"std",
")",
"return",
"new_val"
] | Convert cat value into num between 0 and 1. | [
"Convert",
"cat",
"value",
"into",
"num",
"between",
"0",
"and",
"1",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L196-L200 |
HDI-Project/RDT | rdt/transformers/category.py | CatTransformer.get_category | def get_category(self, column):
"""Returns categories for the specified numeric values
Args:
column(pandas.Series): Values to transform into categories
Returns:
pandas.Series
"""
result = pd.Series(index=column.index)
for category, stats in self.probability_map.items():
start, end = stats[0]
result[(start < column) & (column < end)] = category
return result | python | def get_category(self, column):
"""Returns categories for the specified numeric values
Args:
column(pandas.Series): Values to transform into categories
Returns:
pandas.Series
"""
result = pd.Series(index=column.index)
for category, stats in self.probability_map.items():
start, end = stats[0]
result[(start < column) & (column < end)] = category
return result | [
"def",
"get_category",
"(",
"self",
",",
"column",
")",
":",
"result",
"=",
"pd",
".",
"Series",
"(",
"index",
"=",
"column",
".",
"index",
")",
"for",
"category",
",",
"stats",
"in",
"self",
".",
"probability_map",
".",
"items",
"(",
")",
":",
"star... | Returns categories for the specified numeric values
Args:
column(pandas.Series): Values to transform into categories
Returns:
pandas.Series | [
"Returns",
"categories",
"for",
"the",
"specified",
"numeric",
"values"
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/category.py#L202-L217 |
HDI-Project/RDT | rdt/transformers/positive_number.py | PositiveNumberTransformer.transform | def transform(self, column):
"""Applies an exponential to values to turn them positive numbers.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame
"""
self.check_data_type()
return pd.DataFrame({self.col_name: np.exp(column[self.col_name])}) | python | def transform(self, column):
"""Applies an exponential to values to turn them positive numbers.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame
"""
self.check_data_type()
return pd.DataFrame({self.col_name: np.exp(column[self.col_name])}) | [
"def",
"transform",
"(",
"self",
",",
"column",
")",
":",
"self",
".",
"check_data_type",
"(",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"self",
".",
"col_name",
":",
"np",
".",
"exp",
"(",
"column",
"[",
"self",
".",
"col_name",
"]",
")",
"... | Applies an exponential to values to turn them positive numbers.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame | [
"Applies",
"an",
"exponential",
"to",
"values",
"to",
"turn",
"them",
"positive",
"numbers",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/positive_number.py#L14-L25 |
HDI-Project/RDT | rdt/transformers/positive_number.py | PositiveNumberTransformer.reverse_transform | def reverse_transform(self, column):
"""Applies the natural logarithm function to turn positive values into real ranged values.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame
"""
self.check_data_type()
return pd.DataFrame({self.col_name: np.log(column[self.col_name])}) | python | def reverse_transform(self, column):
"""Applies the natural logarithm function to turn positive values into real ranged values.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame
"""
self.check_data_type()
return pd.DataFrame({self.col_name: np.log(column[self.col_name])}) | [
"def",
"reverse_transform",
"(",
"self",
",",
"column",
")",
":",
"self",
".",
"check_data_type",
"(",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"self",
".",
"col_name",
":",
"np",
".",
"log",
"(",
"column",
"[",
"self",
".",
"col_name",
"]",
... | Applies the natural logarithm function to turn positive values into real ranged values.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame | [
"Applies",
"the",
"natural",
"logarithm",
"function",
"to",
"turn",
"positive",
"values",
"into",
"real",
"ranged",
"values",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/positive_number.py#L27-L38 |
josuebrunel/myql | myql/myql.py | YQL._payload_builder | def _payload_builder(self, query, format=None):
'''Build the payload'''
if self.community :
query = self.COMMUNITY_DATA + query # access to community data tables
if vars(self).get('yql_table_url') : # Attribute only defined when MYQL.use has been called before
query = "use '{0}' as {1}; ".format(self.yql_table_url, self.yql_table_name) + query
if vars(self).get('_func'): # if post query function filters
query = '| '.join((query, self._func))
self._query = query
self._query = self._add_limit()
self._query = self._add_offset()
logger.info("QUERY = %s" %(self._query,))
payload = {
'q': self._query,
'callback': '',#This is not javascript
'diagnostics': self.diagnostics,
'format': format if format else self.format,
'debug': self.debug,
'jsonCompact': 'new' if self.jsonCompact else ''
}
if vars(self).get('_vars'):
payload.update(self._vars)
if self.crossProduct:
payload['crossProduct'] = 'optimized'
self._payload = payload
logger.info("PAYLOAD = %s " %(payload, ))
return payload | python | def _payload_builder(self, query, format=None):
'''Build the payload'''
if self.community :
query = self.COMMUNITY_DATA + query # access to community data tables
if vars(self).get('yql_table_url') : # Attribute only defined when MYQL.use has been called before
query = "use '{0}' as {1}; ".format(self.yql_table_url, self.yql_table_name) + query
if vars(self).get('_func'): # if post query function filters
query = '| '.join((query, self._func))
self._query = query
self._query = self._add_limit()
self._query = self._add_offset()
logger.info("QUERY = %s" %(self._query,))
payload = {
'q': self._query,
'callback': '',#This is not javascript
'diagnostics': self.diagnostics,
'format': format if format else self.format,
'debug': self.debug,
'jsonCompact': 'new' if self.jsonCompact else ''
}
if vars(self).get('_vars'):
payload.update(self._vars)
if self.crossProduct:
payload['crossProduct'] = 'optimized'
self._payload = payload
logger.info("PAYLOAD = %s " %(payload, ))
return payload | [
"def",
"_payload_builder",
"(",
"self",
",",
"query",
",",
"format",
"=",
"None",
")",
":",
"if",
"self",
".",
"community",
":",
"query",
"=",
"self",
".",
"COMMUNITY_DATA",
"+",
"query",
"# access to community data tables",
"if",
"vars",
"(",
"self",
")",
... | Build the payload | [
"Build",
"the",
"payload"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L56-L92 |
josuebrunel/myql | myql/myql.py | YQL.raw_query | def raw_query(self, query, format=None, pretty=False):
'''Executes a YQL query and returns a response
>>>...
>>> resp = yql.raw_query('select * from weather.forecast where woeid=2502265')
>>>
'''
if format:
format = format
else:
format = self.format
payload = self._payload_builder(query, format=format)
response = self.execute_query(payload)
if pretty:
response = self.response_builder(response)
return response | python | def raw_query(self, query, format=None, pretty=False):
'''Executes a YQL query and returns a response
>>>...
>>> resp = yql.raw_query('select * from weather.forecast where woeid=2502265')
>>>
'''
if format:
format = format
else:
format = self.format
payload = self._payload_builder(query, format=format)
response = self.execute_query(payload)
if pretty:
response = self.response_builder(response)
return response | [
"def",
"raw_query",
"(",
"self",
",",
"query",
",",
"format",
"=",
"None",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"format",
":",
"format",
"=",
"format",
"else",
":",
"format",
"=",
"self",
".",
"format",
"payload",
"=",
"self",
".",
"_payload_... | Executes a YQL query and returns a response
>>>...
>>> resp = yql.raw_query('select * from weather.forecast where woeid=2502265')
>>> | [
"Executes",
"a",
"YQL",
"query",
"and",
"returns",
"a",
"response",
">>>",
"...",
">>>",
"resp",
"=",
"yql",
".",
"raw_query",
"(",
"select",
"*",
"from",
"weather",
".",
"forecast",
"where",
"woeid",
"=",
"2502265",
")",
">>>"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L94-L110 |
josuebrunel/myql | myql/myql.py | YQL.execute_query | def execute_query(self, payload):
'''Execute the query and returns and response'''
if vars(self).get('oauth'):
if not self.oauth.token_is_valid(): # Refresh token if token has expired
self.oauth.refresh_token()
response = self.oauth.session.get(self.PRIVATE_URL, params= payload, header_auth=True)
else:
response = requests.get(self.PUBLIC_URL, params= payload)
self._response = response # Saving last response object.
return response | python | def execute_query(self, payload):
'''Execute the query and returns and response'''
if vars(self).get('oauth'):
if not self.oauth.token_is_valid(): # Refresh token if token has expired
self.oauth.refresh_token()
response = self.oauth.session.get(self.PRIVATE_URL, params= payload, header_auth=True)
else:
response = requests.get(self.PUBLIC_URL, params= payload)
self._response = response # Saving last response object.
return response | [
"def",
"execute_query",
"(",
"self",
",",
"payload",
")",
":",
"if",
"vars",
"(",
"self",
")",
".",
"get",
"(",
"'oauth'",
")",
":",
"if",
"not",
"self",
".",
"oauth",
".",
"token_is_valid",
"(",
")",
":",
"# Refresh token if token has expired",
"self",
... | Execute the query and returns and response | [
"Execute",
"the",
"query",
"and",
"returns",
"and",
"response"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L112-L122 |
josuebrunel/myql | myql/myql.py | YQL._clause_formatter | def _clause_formatter(self, cond):
'''Formats conditions
args is a list of ['field', 'operator', 'value']
'''
if len(cond) == 2 :
cond = ' '.join(cond)
return cond
if 'in' in cond[1].lower() :
if not isinstance(cond[2], (tuple, list)):
raise TypeError('("{0}") must be of type <type tuple> or <type list>'.format(cond[2]))
if 'select' not in cond[2][0].lower() :
cond[2] = "({0})".format(','.join(map(str,["'{0}'".format(e) for e in cond[2]])))
else:
cond[2] = "({0})".format(','.join(map(str,["{0}".format(e) for e in cond[2]])))
cond = " ".join(cond)
else:
#if isinstance(cond[2], str):
# var = re.match('^@(\w+)$', cond[2])
#else:
# var = None
#if var :
if isinstance(cond[2], str) and cond[2].startswith('@'):
cond[2] = "{0}".format(cond[2])
else :
cond[2] = "'{0}'".format(cond[2])
cond = ' '.join(cond)
return cond | python | def _clause_formatter(self, cond):
'''Formats conditions
args is a list of ['field', 'operator', 'value']
'''
if len(cond) == 2 :
cond = ' '.join(cond)
return cond
if 'in' in cond[1].lower() :
if not isinstance(cond[2], (tuple, list)):
raise TypeError('("{0}") must be of type <type tuple> or <type list>'.format(cond[2]))
if 'select' not in cond[2][0].lower() :
cond[2] = "({0})".format(','.join(map(str,["'{0}'".format(e) for e in cond[2]])))
else:
cond[2] = "({0})".format(','.join(map(str,["{0}".format(e) for e in cond[2]])))
cond = " ".join(cond)
else:
#if isinstance(cond[2], str):
# var = re.match('^@(\w+)$', cond[2])
#else:
# var = None
#if var :
if isinstance(cond[2], str) and cond[2].startswith('@'):
cond[2] = "{0}".format(cond[2])
else :
cond[2] = "'{0}'".format(cond[2])
cond = ' '.join(cond)
return cond | [
"def",
"_clause_formatter",
"(",
"self",
",",
"cond",
")",
":",
"if",
"len",
"(",
"cond",
")",
"==",
"2",
":",
"cond",
"=",
"' '",
".",
"join",
"(",
"cond",
")",
"return",
"cond",
"if",
"'in'",
"in",
"cond",
"[",
"1",
"]",
".",
"lower",
"(",
")... | Formats conditions
args is a list of ['field', 'operator', 'value'] | [
"Formats",
"conditions",
"args",
"is",
"a",
"list",
"of",
"[",
"field",
"operator",
"value",
"]"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L124-L155 |
josuebrunel/myql | myql/myql.py | YQL.response_builder | def response_builder(self, response):
'''Try to return a pretty formatted response object
'''
try:
r = response.json()
result = r['query']['results']
response = {
'num_result': r['query']['count'] ,
'result': result
}
except (Exception,) as e:
print(e)
return response.content
return response | python | def response_builder(self, response):
'''Try to return a pretty formatted response object
'''
try:
r = response.json()
result = r['query']['results']
response = {
'num_result': r['query']['count'] ,
'result': result
}
except (Exception,) as e:
print(e)
return response.content
return response | [
"def",
"response_builder",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"r",
"=",
"response",
".",
"json",
"(",
")",
"result",
"=",
"r",
"[",
"'query'",
"]",
"[",
"'results'",
"]",
"response",
"=",
"{",
"'num_result'",
":",
"r",
"[",
"'query'"... | Try to return a pretty formatted response object | [
"Try",
"to",
"return",
"a",
"pretty",
"formatted",
"response",
"object"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L157-L171 |
josuebrunel/myql | myql/myql.py | YQL._func_filters | def _func_filters(self, filters):
'''Build post query filters
'''
if not isinstance(filters, (list,tuple)):
raise TypeError('func_filters must be a <type list> or <type tuple>')
for i, func in enumerate(filters) :
if isinstance(func, str) and func == 'reverse':
filters[i] = 'reverse()'
elif isinstance(func, tuple) and func[0] in YQL.FUNC_FILTERS:
filters[i] = '{:s}(count={:d})'.format(*func)
elif isinstance(func, dict) :
func_stmt = ''
func_name = list(func.keys())[0] # Because of Py3
values = [ "{0}='{1}'".format(v[0], v[1]) for v in func[func_name] ]
func_stmt = ','.join(values)
func_stmt = '{0}({1})'.format(func_name, func_stmt)
filters[i] = func_stmt
else:
raise TypeError('{0} is neither a <str>, a <tuple> or a <dict>'.format(func))
return '| '.join(filters) | python | def _func_filters(self, filters):
'''Build post query filters
'''
if not isinstance(filters, (list,tuple)):
raise TypeError('func_filters must be a <type list> or <type tuple>')
for i, func in enumerate(filters) :
if isinstance(func, str) and func == 'reverse':
filters[i] = 'reverse()'
elif isinstance(func, tuple) and func[0] in YQL.FUNC_FILTERS:
filters[i] = '{:s}(count={:d})'.format(*func)
elif isinstance(func, dict) :
func_stmt = ''
func_name = list(func.keys())[0] # Because of Py3
values = [ "{0}='{1}'".format(v[0], v[1]) for v in func[func_name] ]
func_stmt = ','.join(values)
func_stmt = '{0}({1})'.format(func_name, func_stmt)
filters[i] = func_stmt
else:
raise TypeError('{0} is neither a <str>, a <tuple> or a <dict>'.format(func))
return '| '.join(filters) | [
"def",
"_func_filters",
"(",
"self",
",",
"filters",
")",
":",
"if",
"not",
"isinstance",
"(",
"filters",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"'func_filters must be a <type list> or <type tuple>'",
")",
"for",
"i",
",",
... | Build post query filters | [
"Build",
"post",
"query",
"filters"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L173-L193 |
josuebrunel/myql | myql/myql.py | YQL.use | def use(self, url, name='mytable'):
'''Changes the data provider
>>> yql.use('http://myserver.com/mytables.xml')
'''
self.yql_table_url = url
self.yql_table_name = name
return {'table url': url, 'table name': name} | python | def use(self, url, name='mytable'):
'''Changes the data provider
>>> yql.use('http://myserver.com/mytables.xml')
'''
self.yql_table_url = url
self.yql_table_name = name
return {'table url': url, 'table name': name} | [
"def",
"use",
"(",
"self",
",",
"url",
",",
"name",
"=",
"'mytable'",
")",
":",
"self",
".",
"yql_table_url",
"=",
"url",
"self",
".",
"yql_table_name",
"=",
"name",
"return",
"{",
"'table url'",
":",
"url",
",",
"'table name'",
":",
"name",
"}"
] | Changes the data provider
>>> yql.use('http://myserver.com/mytables.xml') | [
"Changes",
"the",
"data",
"provider",
">>>",
"yql",
".",
"use",
"(",
"http",
":",
"//",
"myserver",
".",
"com",
"/",
"mytables",
".",
"xml",
")"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L209-L215 |
josuebrunel/myql | myql/myql.py | YQL.desc | def desc(self, table):
'''Returns table description
>>> yql.desc('geo.countries')
>>>
'''
query = "desc {0}".format(table)
response = self.raw_query(query)
return response | python | def desc(self, table):
'''Returns table description
>>> yql.desc('geo.countries')
>>>
'''
query = "desc {0}".format(table)
response = self.raw_query(query)
return response | [
"def",
"desc",
"(",
"self",
",",
"table",
")",
":",
"query",
"=",
"\"desc {0}\"",
".",
"format",
"(",
"table",
")",
"response",
"=",
"self",
".",
"raw_query",
"(",
"query",
")",
"return",
"response"
] | Returns table description
>>> yql.desc('geo.countries')
>>> | [
"Returns",
"table",
"description",
">>>",
"yql",
".",
"desc",
"(",
"geo",
".",
"countries",
")",
">>>"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L225-L233 |
josuebrunel/myql | myql/myql.py | YQL.get | def get(self, *args, **kwargs):
'''Just a select which returns a response
>>> yql.get("geo.countries', ['name', 'woeid'], 5")
'''
self = self.select(*args, **kwargs)
payload = self._payload_builder(self._query)
response = self.execute_query(payload)
return response | python | def get(self, *args, **kwargs):
'''Just a select which returns a response
>>> yql.get("geo.countries', ['name', 'woeid'], 5")
'''
self = self.select(*args, **kwargs)
payload = self._payload_builder(self._query)
response = self.execute_query(payload)
return response | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"self",
".",
"select",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"payload",
"=",
"self",
".",
"_payload_builder",
"(",
"self",
".",
"_query",
")",
... | Just a select which returns a response
>>> yql.get("geo.countries', ['name', 'woeid'], 5") | [
"Just",
"a",
"select",
"which",
"returns",
"a",
"response",
">>>",
"yql",
".",
"get",
"(",
"geo",
".",
"countries",
"[",
"name",
"woeid",
"]",
"5",
")"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L236-L245 |
josuebrunel/myql | myql/myql.py | YQL.select | def select(self, table, items=None, limit=None, offset=None, remote_filter=None, func_filters=None):
'''This method simulate a select on a table
>>> yql.select('geo.countries', limit=5)
>>> yql.select('social.profile', ['guid', 'givenName', 'gender'])
'''
self._table = table
if remote_filter:
if not isinstance(remote_filter, tuple):
raise TypeError("{0} must be of type <type tuple>".format(remote_filter))
table = "%s(%s)" %(table, ','.join(map(str, remote_filter)))
if not items:
items = ['*']
self._query = "SELECT {1} FROM {0} ".format(table, ','.join(items))
if func_filters:
self._func = self._func_filters(func_filters)
self._limit = limit
self._offset = offset
return self | python | def select(self, table, items=None, limit=None, offset=None, remote_filter=None, func_filters=None):
'''This method simulate a select on a table
>>> yql.select('geo.countries', limit=5)
>>> yql.select('social.profile', ['guid', 'givenName', 'gender'])
'''
self._table = table
if remote_filter:
if not isinstance(remote_filter, tuple):
raise TypeError("{0} must be of type <type tuple>".format(remote_filter))
table = "%s(%s)" %(table, ','.join(map(str, remote_filter)))
if not items:
items = ['*']
self._query = "SELECT {1} FROM {0} ".format(table, ','.join(items))
if func_filters:
self._func = self._func_filters(func_filters)
self._limit = limit
self._offset = offset
return self | [
"def",
"select",
"(",
"self",
",",
"table",
",",
"items",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"remote_filter",
"=",
"None",
",",
"func_filters",
"=",
"None",
")",
":",
"self",
".",
"_table",
"=",
"table",
"if",
... | This method simulate a select on a table
>>> yql.select('geo.countries', limit=5)
>>> yql.select('social.profile', ['guid', 'givenName', 'gender']) | [
"This",
"method",
"simulate",
"a",
"select",
"on",
"a",
"table",
">>>",
"yql",
".",
"select",
"(",
"geo",
".",
"countries",
"limit",
"=",
"5",
")",
">>>",
"yql",
".",
"select",
"(",
"social",
".",
"profile",
"[",
"guid",
"givenName",
"gender",
"]",
"... | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L248-L271 |
josuebrunel/myql | myql/myql.py | YQL.insert | def insert(self, table,items, values):
"""This method allows to insert data into table
>>> yql.insert('bi.ly.shorten',('login','apiKey','longUrl'),('YOUR LOGIN','YOUR API KEY','YOUR LONG URL'))
"""
values = ["'{0}'".format(e) for e in values]
self._query = "INSERT INTO {0} ({1}) VALUES ({2})".format(table,','.join(items),','.join(values))
payload = self._payload_builder(self._query)
response = self.execute_query(payload)
return response | python | def insert(self, table,items, values):
"""This method allows to insert data into table
>>> yql.insert('bi.ly.shorten',('login','apiKey','longUrl'),('YOUR LOGIN','YOUR API KEY','YOUR LONG URL'))
"""
values = ["'{0}'".format(e) for e in values]
self._query = "INSERT INTO {0} ({1}) VALUES ({2})".format(table,','.join(items),','.join(values))
payload = self._payload_builder(self._query)
response = self.execute_query(payload)
return response | [
"def",
"insert",
"(",
"self",
",",
"table",
",",
"items",
",",
"values",
")",
":",
"values",
"=",
"[",
"\"'{0}'\"",
".",
"format",
"(",
"e",
")",
"for",
"e",
"in",
"values",
"]",
"self",
".",
"_query",
"=",
"\"INSERT INTO {0} ({1}) VALUES ({2})\"",
".",
... | This method allows to insert data into table
>>> yql.insert('bi.ly.shorten',('login','apiKey','longUrl'),('YOUR LOGIN','YOUR API KEY','YOUR LONG URL')) | [
"This",
"method",
"allows",
"to",
"insert",
"data",
"into",
"table",
">>>",
"yql",
".",
"insert",
"(",
"bi",
".",
"ly",
".",
"shorten",
"(",
"login",
"apiKey",
"longUrl",
")",
"(",
"YOUR",
"LOGIN",
"YOUR",
"API",
"KEY",
"YOUR",
"LONG",
"URL",
"))"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L280-L289 |
josuebrunel/myql | myql/myql.py | YQL.update | def update(self, table, items, values):
"""Updates a YQL Table
>>> yql.update('yql.storage',['value'],['https://josuebrunel.orkg']).where(['name','=','store://YEl70PraLLMSMuYAauqNc7'])
"""
self._table = table
self._limit = None
items_values = ','.join(["{0} = '{1}'".format(k,v) for k,v in zip(items,values)])
self._query = "UPDATE {0} SET {1}".format(self._table, items_values)
return self | python | def update(self, table, items, values):
"""Updates a YQL Table
>>> yql.update('yql.storage',['value'],['https://josuebrunel.orkg']).where(['name','=','store://YEl70PraLLMSMuYAauqNc7'])
"""
self._table = table
self._limit = None
items_values = ','.join(["{0} = '{1}'".format(k,v) for k,v in zip(items,values)])
self._query = "UPDATE {0} SET {1}".format(self._table, items_values)
return self | [
"def",
"update",
"(",
"self",
",",
"table",
",",
"items",
",",
"values",
")",
":",
"self",
".",
"_table",
"=",
"table",
"self",
".",
"_limit",
"=",
"None",
"items_values",
"=",
"','",
".",
"join",
"(",
"[",
"\"{0} = '{1}'\"",
".",
"format",
"(",
"k",... | Updates a YQL Table
>>> yql.update('yql.storage',['value'],['https://josuebrunel.orkg']).where(['name','=','store://YEl70PraLLMSMuYAauqNc7']) | [
"Updates",
"a",
"YQL",
"Table",
">>>",
"yql",
".",
"update",
"(",
"yql",
".",
"storage",
"[",
"value",
"]",
"[",
"https",
":",
"//",
"josuebrunel",
".",
"orkg",
"]",
")",
".",
"where",
"(",
"[",
"name",
"=",
"store",
":",
"//",
"YEl70PraLLMSMuYAauqNc... | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L292-L301 |
josuebrunel/myql | myql/myql.py | YQL.delete | def delete(self, table):
"""Deletes record in table
>>> yql.delete('yql.storage').where(['name','=','store://YEl70PraLLMSMuYAauqNc7'])
"""
self._table = table
self._limit = None
self._query = "DELETE FROM {0}".format(self._table)
return self | python | def delete(self, table):
"""Deletes record in table
>>> yql.delete('yql.storage').where(['name','=','store://YEl70PraLLMSMuYAauqNc7'])
"""
self._table = table
self._limit = None
self._query = "DELETE FROM {0}".format(self._table)
return self | [
"def",
"delete",
"(",
"self",
",",
"table",
")",
":",
"self",
".",
"_table",
"=",
"table",
"self",
".",
"_limit",
"=",
"None",
"self",
".",
"_query",
"=",
"\"DELETE FROM {0}\"",
".",
"format",
"(",
"self",
".",
"_table",
")",
"return",
"self"
] | Deletes record in table
>>> yql.delete('yql.storage').where(['name','=','store://YEl70PraLLMSMuYAauqNc7']) | [
"Deletes",
"record",
"in",
"table",
">>>",
"yql",
".",
"delete",
"(",
"yql",
".",
"storage",
")",
".",
"where",
"(",
"[",
"name",
"=",
"store",
":",
"//",
"YEl70PraLLMSMuYAauqNc7",
"]",
")"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L304-L312 |
josuebrunel/myql | myql/myql.py | YQL.where | def where(self, *args):
''' This method simulates a where condition. Use as follow:
>>> yql.select('mytable').where(['name', '=', 'alain'], ['location', '!=', 'paris'])
'''
if not self._table:
raise errors.NoTableSelectedError('No Table Selected')
clause = []
self._query += ' WHERE '
clause = [ self._clause_formatter(x) for x in args if x ]
self._query += ' AND '.join(clause)
payload = self._payload_builder(self._query)
response = self.execute_query(payload)
return response | python | def where(self, *args):
''' This method simulates a where condition. Use as follow:
>>> yql.select('mytable').where(['name', '=', 'alain'], ['location', '!=', 'paris'])
'''
if not self._table:
raise errors.NoTableSelectedError('No Table Selected')
clause = []
self._query += ' WHERE '
clause = [ self._clause_formatter(x) for x in args if x ]
self._query += ' AND '.join(clause)
payload = self._payload_builder(self._query)
response = self.execute_query(payload)
return response | [
"def",
"where",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"self",
".",
"_table",
":",
"raise",
"errors",
".",
"NoTableSelectedError",
"(",
"'No Table Selected'",
")",
"clause",
"=",
"[",
"]",
"self",
".",
"_query",
"+=",
"' WHERE '",
"clause"... | This method simulates a where condition. Use as follow:
>>> yql.select('mytable').where(['name', '=', 'alain'], ['location', '!=', 'paris']) | [
"This",
"method",
"simulates",
"a",
"where",
"condition",
".",
"Use",
"as",
"follow",
":",
">>>",
"yql",
".",
"select",
"(",
"mytable",
")",
".",
"where",
"(",
"[",
"name",
"=",
"alain",
"]",
"[",
"location",
"!",
"=",
"paris",
"]",
")"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L315-L332 |
josuebrunel/myql | myql/myql.py | MYQL.show_tables | def show_tables(self, format='json'):
'''Return list of all available tables'''
query = 'SHOW TABLES'
payload = self._payload_builder(query, format)
response = self.execute_query(payload)
return response | python | def show_tables(self, format='json'):
'''Return list of all available tables'''
query = 'SHOW TABLES'
payload = self._payload_builder(query, format)
response = self.execute_query(payload)
return response | [
"def",
"show_tables",
"(",
"self",
",",
"format",
"=",
"'json'",
")",
":",
"query",
"=",
"'SHOW TABLES'",
"payload",
"=",
"self",
".",
"_payload_builder",
"(",
"query",
",",
"format",
")",
"response",
"=",
"self",
".",
"execute_query",
"(",
"payload",
")",... | Return list of all available tables | [
"Return",
"list",
"of",
"all",
"available",
"tables"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/myql.py#L357-L365 |
cmaugg/pystatemachine | pystatemachine.py | event | def event(from_states=None, to_state=None):
""" a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. """
from_states_tuple = (from_states, ) if isinstance(from_states, State) else tuple(from_states or [])
if not len(from_states_tuple) >= 1:
raise ValueError()
if not all(isinstance(state, State) for state in from_states_tuple):
raise TypeError()
if not isinstance(to_state, State):
raise TypeError()
def wrapper(wrapped):
@functools.wraps(wrapped)
def transition(instance, *a, **kw):
if instance.current_state not in from_states_tuple:
raise InvalidStateTransition()
try:
result = wrapped(instance, *a, **kw)
except Exception as error:
error_handlers = getattr(instance, '___pystatemachine_transition_failure_handlers', [])
for error_handler in error_handlers:
error_handler(instance, wrapped, instance.current_state, to_state, error)
if not error_handlers:
raise error
else:
StateInfo.set_current_state(instance, to_state)
return result
return transition
return wrapper | python | def event(from_states=None, to_state=None):
""" a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. """
from_states_tuple = (from_states, ) if isinstance(from_states, State) else tuple(from_states or [])
if not len(from_states_tuple) >= 1:
raise ValueError()
if not all(isinstance(state, State) for state in from_states_tuple):
raise TypeError()
if not isinstance(to_state, State):
raise TypeError()
def wrapper(wrapped):
@functools.wraps(wrapped)
def transition(instance, *a, **kw):
if instance.current_state not in from_states_tuple:
raise InvalidStateTransition()
try:
result = wrapped(instance, *a, **kw)
except Exception as error:
error_handlers = getattr(instance, '___pystatemachine_transition_failure_handlers', [])
for error_handler in error_handlers:
error_handler(instance, wrapped, instance.current_state, to_state, error)
if not error_handlers:
raise error
else:
StateInfo.set_current_state(instance, to_state)
return result
return transition
return wrapper | [
"def",
"event",
"(",
"from_states",
"=",
"None",
",",
"to_state",
"=",
"None",
")",
":",
"from_states_tuple",
"=",
"(",
"from_states",
",",
")",
"if",
"isinstance",
"(",
"from_states",
",",
"State",
")",
"else",
"tuple",
"(",
"from_states",
"or",
"[",
"]... | a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. | [
"a",
"decorator",
"for",
"transitioning",
"from",
"certain",
"states",
"to",
"a",
"target",
"state",
".",
"must",
"be",
"used",
"on",
"bound",
"methods",
"of",
"a",
"class",
"instance",
"only",
"."
] | train | https://github.com/cmaugg/pystatemachine/blob/5a6cd9cbd88180a86569cda1e564331753299c6c/pystatemachine.py#L108-L139 |
cmaugg/pystatemachine | pystatemachine.py | acts_as_state_machine | def acts_as_state_machine(cls):
"""
a decorator which sets two properties on a class:
* the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object
* the 'states' property: a tuple of all valid state machine states, as 'State' objects
class objects may use current_state and states freely
:param cls:
:return:
"""
assert not hasattr(cls, 'current_state'), '{0} already has a "current_state" attribute!'.format(cls)
assert not hasattr(cls, 'states'), '{0} already has a "states" attribute!'.format(cls)
def get_states(obj):
return StateInfo.get_states(obj.__class__)
def is_transition_failure_handler(obj):
return all([
any([
inspect.ismethod(obj), # python2
inspect.isfunction(obj), # python3
]),
getattr(obj, '___pystatemachine_is_transition_failure_handler', False),
])
transition_failure_handlers = sorted(
[value for name, value in inspect.getmembers(cls, is_transition_failure_handler)],
key=lambda m: getattr(m, '___pystatemachine_transition_failure_handler_calling_sequence', 0),
)
setattr(cls, '___pystatemachine_transition_failure_handlers', transition_failure_handlers)
cls.current_state = property(fget=StateInfo.get_current_state)
cls.states = property(fget=get_states)
return cls | python | def acts_as_state_machine(cls):
"""
a decorator which sets two properties on a class:
* the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object
* the 'states' property: a tuple of all valid state machine states, as 'State' objects
class objects may use current_state and states freely
:param cls:
:return:
"""
assert not hasattr(cls, 'current_state'), '{0} already has a "current_state" attribute!'.format(cls)
assert not hasattr(cls, 'states'), '{0} already has a "states" attribute!'.format(cls)
def get_states(obj):
return StateInfo.get_states(obj.__class__)
def is_transition_failure_handler(obj):
return all([
any([
inspect.ismethod(obj), # python2
inspect.isfunction(obj), # python3
]),
getattr(obj, '___pystatemachine_is_transition_failure_handler', False),
])
transition_failure_handlers = sorted(
[value for name, value in inspect.getmembers(cls, is_transition_failure_handler)],
key=lambda m: getattr(m, '___pystatemachine_transition_failure_handler_calling_sequence', 0),
)
setattr(cls, '___pystatemachine_transition_failure_handlers', transition_failure_handlers)
cls.current_state = property(fget=StateInfo.get_current_state)
cls.states = property(fget=get_states)
return cls | [
"def",
"acts_as_state_machine",
"(",
"cls",
")",
":",
"assert",
"not",
"hasattr",
"(",
"cls",
",",
"'current_state'",
")",
",",
"'{0} already has a \"current_state\" attribute!'",
".",
"format",
"(",
"cls",
")",
"assert",
"not",
"hasattr",
"(",
"cls",
",",
"'sta... | a decorator which sets two properties on a class:
* the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object
* the 'states' property: a tuple of all valid state machine states, as 'State' objects
class objects may use current_state and states freely
:param cls:
:return: | [
"a",
"decorator",
"which",
"sets",
"two",
"properties",
"on",
"a",
"class",
":",
"*",
"the",
"current_state",
"property",
":",
"a",
"read",
"-",
"only",
"property",
"returning",
"the",
"state",
"machine",
"s",
"current",
"state",
"as",
"State",
"object",
"... | train | https://github.com/cmaugg/pystatemachine/blob/5a6cd9cbd88180a86569cda1e564331753299c6c/pystatemachine.py#L151-L182 |
josuebrunel/myql | myql/contrib/weather/weather.py | Weather.get_weather_in | def get_weather_in(self, place, unit=None, items=None):
"""Return weather info according to place
"""
unit = unit if unit else self.unit
response = self.select('weather.forecast', items=items).where(['woeid','IN',('SELECT woeid FROM geo.places WHERE text="{0}"'.format(place),)], ['u','=',unit] if unit else [])
return response | python | def get_weather_in(self, place, unit=None, items=None):
"""Return weather info according to place
"""
unit = unit if unit else self.unit
response = self.select('weather.forecast', items=items).where(['woeid','IN',('SELECT woeid FROM geo.places WHERE text="{0}"'.format(place),)], ['u','=',unit] if unit else [])
return response | [
"def",
"get_weather_in",
"(",
"self",
",",
"place",
",",
"unit",
"=",
"None",
",",
"items",
"=",
"None",
")",
":",
"unit",
"=",
"unit",
"if",
"unit",
"else",
"self",
".",
"unit",
"response",
"=",
"self",
".",
"select",
"(",
"'weather.forecast'",
",",
... | Return weather info according to place | [
"Return",
"weather",
"info",
"according",
"to",
"place"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/weather/weather.py#L19-L24 |
josuebrunel/myql | myql/contrib/weather/weather.py | Weather.get_weather_forecast | def get_weather_forecast(self, place, unit=None):
"""Return weather forecast accoriding to place
"""
unit = unit if unit else self.unit
response = self.get_weather_in(place, items=['item.forecast'], unit=unit)
return response | python | def get_weather_forecast(self, place, unit=None):
"""Return weather forecast accoriding to place
"""
unit = unit if unit else self.unit
response = self.get_weather_in(place, items=['item.forecast'], unit=unit)
return response | [
"def",
"get_weather_forecast",
"(",
"self",
",",
"place",
",",
"unit",
"=",
"None",
")",
":",
"unit",
"=",
"unit",
"if",
"unit",
"else",
"self",
".",
"unit",
"response",
"=",
"self",
".",
"get_weather_in",
"(",
"place",
",",
"items",
"=",
"[",
"'item.f... | Return weather forecast accoriding to place | [
"Return",
"weather",
"forecast",
"accoriding",
"to",
"place"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/weather/weather.py#L26-L31 |
fake-name/WebRequest | WebRequest/ChromiumMixin.py | WebGetCrMixin.stepThroughJsWaf_bare_chromium | def stepThroughJsWaf_bare_chromium(self, url, titleContains='', titleNotContains='', extra_tid=None):
'''
Use Chromium to access a resource behind WAF protection.
Params:
``url`` - The URL to access that is protected by WAF
``titleContains`` - A string that is in the title of the protected page, and NOT the
WAF intermediate page. The presence of this string in the page title
is used to determine whether the WAF protection has been successfully
penetrated.
``titleContains`` - A string that is in the title of the WAF intermediate page
and NOT in the target page. The presence of this string in the page title
is used to determine whether the WAF protection has been successfully
penetrated.
The current WebGetRobust headers are installed into the selenium browser, which
is then used to access the protected resource.
Once the protected page has properly loaded, the WAF access cookie is
then extracted from the selenium browser, and installed back into the WebGetRobust
instance, so it can continue to use the WAF auth in normal requests.
'''
if (not titleContains) and (not titleNotContains):
raise ValueError("You must pass either a string the title should contain, or a string the title shouldn't contain!")
if titleContains and titleNotContains:
raise ValueError("You can only pass a single conditional statement!")
self.log.info("Attempting to access page through WAF browser verification.")
current_title = None
if extra_tid is True:
extra_tid = threading.get_ident()
with self._chrome_context(url, extra_tid=extra_tid) as cr:
self._syncIntoChromium(cr)
cr.blocking_navigate(url)
for _ in range(self.wrapper_step_through_timeout):
time.sleep(1)
current_title, _ = cr.get_page_url_title()
if titleContains and titleContains in current_title:
self._syncOutOfChromium(cr)
return True
if titleNotContains and current_title and titleNotContains not in current_title:
self._syncOutOfChromium(cr)
return True
self._syncOutOfChromium(cr)
self.log.error("Failed to step through. Current title: '%s'", current_title)
return False | python | def stepThroughJsWaf_bare_chromium(self, url, titleContains='', titleNotContains='', extra_tid=None):
'''
Use Chromium to access a resource behind WAF protection.
Params:
``url`` - The URL to access that is protected by WAF
``titleContains`` - A string that is in the title of the protected page, and NOT the
WAF intermediate page. The presence of this string in the page title
is used to determine whether the WAF protection has been successfully
penetrated.
``titleContains`` - A string that is in the title of the WAF intermediate page
and NOT in the target page. The presence of this string in the page title
is used to determine whether the WAF protection has been successfully
penetrated.
The current WebGetRobust headers are installed into the selenium browser, which
is then used to access the protected resource.
Once the protected page has properly loaded, the WAF access cookie is
then extracted from the selenium browser, and installed back into the WebGetRobust
instance, so it can continue to use the WAF auth in normal requests.
'''
if (not titleContains) and (not titleNotContains):
raise ValueError("You must pass either a string the title should contain, or a string the title shouldn't contain!")
if titleContains and titleNotContains:
raise ValueError("You can only pass a single conditional statement!")
self.log.info("Attempting to access page through WAF browser verification.")
current_title = None
if extra_tid is True:
extra_tid = threading.get_ident()
with self._chrome_context(url, extra_tid=extra_tid) as cr:
self._syncIntoChromium(cr)
cr.blocking_navigate(url)
for _ in range(self.wrapper_step_through_timeout):
time.sleep(1)
current_title, _ = cr.get_page_url_title()
if titleContains and titleContains in current_title:
self._syncOutOfChromium(cr)
return True
if titleNotContains and current_title and titleNotContains not in current_title:
self._syncOutOfChromium(cr)
return True
self._syncOutOfChromium(cr)
self.log.error("Failed to step through. Current title: '%s'", current_title)
return False | [
"def",
"stepThroughJsWaf_bare_chromium",
"(",
"self",
",",
"url",
",",
"titleContains",
"=",
"''",
",",
"titleNotContains",
"=",
"''",
",",
"extra_tid",
"=",
"None",
")",
":",
"if",
"(",
"not",
"titleContains",
")",
"and",
"(",
"not",
"titleNotContains",
")"... | Use Chromium to access a resource behind WAF protection.
Params:
``url`` - The URL to access that is protected by WAF
``titleContains`` - A string that is in the title of the protected page, and NOT the
WAF intermediate page. The presence of this string in the page title
is used to determine whether the WAF protection has been successfully
penetrated.
``titleContains`` - A string that is in the title of the WAF intermediate page
and NOT in the target page. The presence of this string in the page title
is used to determine whether the WAF protection has been successfully
penetrated.
The current WebGetRobust headers are installed into the selenium browser, which
is then used to access the protected resource.
Once the protected page has properly loaded, the WAF access cookie is
then extracted from the selenium browser, and installed back into the WebGetRobust
instance, so it can continue to use the WAF auth in normal requests. | [
"Use",
"Chromium",
"to",
"access",
"a",
"resource",
"behind",
"WAF",
"protection",
"."
] | train | https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/ChromiumMixin.py#L237-L292 |
fake-name/WebRequest | WebRequest/ChromiumMixin.py | WebGetCrMixin.chromiumContext | def chromiumContext(self, url, extra_tid=None):
'''
Return a active chromium context, useable for manual operations directly against
chromium.
The WebRequest user agent and other context is synchronized into the chromium
instance at startup, and changes are flushed back to the webrequest instance
from chromium at completion.
'''
assert url is not None, "You need to pass a URL to the contextmanager, so it can dispatch to the correct tab!"
if extra_tid is True:
extra_tid = threading.get_ident()
return self._chrome_context(url, extra_tid=extra_tid) | python | def chromiumContext(self, url, extra_tid=None):
'''
Return a active chromium context, useable for manual operations directly against
chromium.
The WebRequest user agent and other context is synchronized into the chromium
instance at startup, and changes are flushed back to the webrequest instance
from chromium at completion.
'''
assert url is not None, "You need to pass a URL to the contextmanager, so it can dispatch to the correct tab!"
if extra_tid is True:
extra_tid = threading.get_ident()
return self._chrome_context(url, extra_tid=extra_tid) | [
"def",
"chromiumContext",
"(",
"self",
",",
"url",
",",
"extra_tid",
"=",
"None",
")",
":",
"assert",
"url",
"is",
"not",
"None",
",",
"\"You need to pass a URL to the contextmanager, so it can dispatch to the correct tab!\"",
"if",
"extra_tid",
"is",
"True",
":",
"ex... | Return a active chromium context, useable for manual operations directly against
chromium.
The WebRequest user agent and other context is synchronized into the chromium
instance at startup, and changes are flushed back to the webrequest instance
from chromium at completion. | [
"Return",
"a",
"active",
"chromium",
"context",
"useable",
"for",
"manual",
"operations",
"directly",
"against",
"chromium",
"."
] | train | https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/ChromiumMixin.py#L295-L310 |
HDI-Project/RDT | rdt/transformers/__init__.py | load_data_table | def load_data_table(table_name, meta_file, meta):
"""Return the contents and metadata of a given table.
Args:
table_name(str): Name of the table.
meta_file(str): Path to the meta.json file.
meta(dict): Contents of meta.json.
Returns:
tuple(pandas.DataFrame, dict)
"""
for table in meta['tables']:
if table['name'] == table_name:
prefix = os.path.dirname(meta_file)
relative_path = os.path.join(prefix, meta['path'], table['path'])
return pd.read_csv(relative_path), table | python | def load_data_table(table_name, meta_file, meta):
"""Return the contents and metadata of a given table.
Args:
table_name(str): Name of the table.
meta_file(str): Path to the meta.json file.
meta(dict): Contents of meta.json.
Returns:
tuple(pandas.DataFrame, dict)
"""
for table in meta['tables']:
if table['name'] == table_name:
prefix = os.path.dirname(meta_file)
relative_path = os.path.join(prefix, meta['path'], table['path'])
return pd.read_csv(relative_path), table | [
"def",
"load_data_table",
"(",
"table_name",
",",
"meta_file",
",",
"meta",
")",
":",
"for",
"table",
"in",
"meta",
"[",
"'tables'",
"]",
":",
"if",
"table",
"[",
"'name'",
"]",
"==",
"table_name",
":",
"prefix",
"=",
"os",
".",
"path",
".",
"dirname",... | Return the contents and metadata of a given table.
Args:
table_name(str): Name of the table.
meta_file(str): Path to the meta.json file.
meta(dict): Contents of meta.json.
Returns:
tuple(pandas.DataFrame, dict) | [
"Return",
"the",
"contents",
"and",
"metadata",
"of",
"a",
"given",
"table",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/__init__.py#L13-L29 |
HDI-Project/RDT | rdt/transformers/__init__.py | get_col_info | def get_col_info(table_name, col_name, meta_file):
"""Return the content and metadata of a fiven column.
Args:
table_name(str): Name of the table.
col_name(str): Name of the column.
meta_file(str): Path to the meta.json file.
Returns:
tuple(pandas.Series, dict)
"""
with open(meta_file, 'r') as f:
meta = json.load(f)
data_table, table = load_data_table(table_name, meta_file, meta)
for field in table['fields']:
if field['name'] == col_name:
col_meta = field
col = data_table[col_name]
return (col, col_meta) | python | def get_col_info(table_name, col_name, meta_file):
"""Return the content and metadata of a fiven column.
Args:
table_name(str): Name of the table.
col_name(str): Name of the column.
meta_file(str): Path to the meta.json file.
Returns:
tuple(pandas.Series, dict)
"""
with open(meta_file, 'r') as f:
meta = json.load(f)
data_table, table = load_data_table(table_name, meta_file, meta)
for field in table['fields']:
if field['name'] == col_name:
col_meta = field
col = data_table[col_name]
return (col, col_meta) | [
"def",
"get_col_info",
"(",
"table_name",
",",
"col_name",
",",
"meta_file",
")",
":",
"with",
"open",
"(",
"meta_file",
",",
"'r'",
")",
"as",
"f",
":",
"meta",
"=",
"json",
".",
"load",
"(",
"f",
")",
"data_table",
",",
"table",
"=",
"load_data_table... | Return the content and metadata of a fiven column.
Args:
table_name(str): Name of the table.
col_name(str): Name of the column.
meta_file(str): Path to the meta.json file.
Returns:
tuple(pandas.Series, dict) | [
"Return",
"the",
"content",
"and",
"metadata",
"of",
"a",
"fiven",
"column",
"."
] | train | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/__init__.py#L32-L55 |
rapidpro/dash | dash/orgs/views.py | OrgPermsMixin.has_permission | def has_permission(self, request, *args, **kwargs):
"""
Figures out if the current user has permissions for this view.
"""
self.kwargs = kwargs
self.args = args
self.request = request
self.org = self.derive_org()
if self.get_user().is_superuser:
return True
if self.get_user().has_perm(self.permission):
return True
return self.has_org_perm(self.permission) | python | def has_permission(self, request, *args, **kwargs):
"""
Figures out if the current user has permissions for this view.
"""
self.kwargs = kwargs
self.args = args
self.request = request
self.org = self.derive_org()
if self.get_user().is_superuser:
return True
if self.get_user().has_perm(self.permission):
return True
return self.has_org_perm(self.permission) | [
"def",
"has_permission",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"kwargs",
"=",
"kwargs",
"self",
".",
"args",
"=",
"args",
"self",
".",
"request",
"=",
"request",
"self",
".",
"org",
"=",
"sel... | Figures out if the current user has permissions for this view. | [
"Figures",
"out",
"if",
"the",
"current",
"user",
"has",
"permissions",
"for",
"this",
"view",
"."
] | train | https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/orgs/views.py#L72-L87 |
schettino72/import-deps | dodo.py | task_coverage | def task_coverage():
"""show coverage for all modules including tests"""
cov = Coverage(
[PythonPackage('import_deps', 'tests')],
config={'branch':True,},
)
yield cov.all() # create task `coverage`
yield cov.src() | python | def task_coverage():
"""show coverage for all modules including tests"""
cov = Coverage(
[PythonPackage('import_deps', 'tests')],
config={'branch':True,},
)
yield cov.all() # create task `coverage`
yield cov.src() | [
"def",
"task_coverage",
"(",
")",
":",
"cov",
"=",
"Coverage",
"(",
"[",
"PythonPackage",
"(",
"'import_deps'",
",",
"'tests'",
")",
"]",
",",
"config",
"=",
"{",
"'branch'",
":",
"True",
",",
"}",
",",
")",
"yield",
"cov",
".",
"all",
"(",
")",
"#... | show coverage for all modules including tests | [
"show",
"coverage",
"for",
"all",
"modules",
"including",
"tests"
] | train | https://github.com/schettino72/import-deps/blob/311f2badd2c93f743d09664397f21e7eaa16e1f1/dodo.py#L17-L24 |
pior/caravan | caravan/swf.py | register_workflow | def register_workflow(connection, domain, workflow):
"""Register a workflow type.
Return False if this workflow already registered (and True otherwise).
"""
args = get_workflow_registration_parameter(workflow)
try:
connection.register_workflow_type(domain=domain, **args)
except ClientError as err:
if err.response['Error']['Code'] == 'TypeAlreadyExistsFault':
return False # Ignore this error
raise
return True | python | def register_workflow(connection, domain, workflow):
"""Register a workflow type.
Return False if this workflow already registered (and True otherwise).
"""
args = get_workflow_registration_parameter(workflow)
try:
connection.register_workflow_type(domain=domain, **args)
except ClientError as err:
if err.response['Error']['Code'] == 'TypeAlreadyExistsFault':
return False # Ignore this error
raise
return True | [
"def",
"register_workflow",
"(",
"connection",
",",
"domain",
",",
"workflow",
")",
":",
"args",
"=",
"get_workflow_registration_parameter",
"(",
"workflow",
")",
"try",
":",
"connection",
".",
"register_workflow_type",
"(",
"domain",
"=",
"domain",
",",
"*",
"*... | Register a workflow type.
Return False if this workflow already registered (and True otherwise). | [
"Register",
"a",
"workflow",
"type",
"."
] | train | https://github.com/pior/caravan/blob/7f298c63b5d839b23e5094f8209bc6d5d24f9f03/caravan/swf.py#L62-L76 |
josuebrunel/myql | myql/utils.py | pretty_json | def pretty_json(data):
"""Return a pretty formatted json
"""
data = json.loads(data.decode('utf-8'))
return json.dumps(data, indent=4, sort_keys=True) | python | def pretty_json(data):
"""Return a pretty formatted json
"""
data = json.loads(data.decode('utf-8'))
return json.dumps(data, indent=4, sort_keys=True) | [
"def",
"pretty_json",
"(",
"data",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"return",
"json",
".",
"dumps",
"(",
"data",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")"
] | Return a pretty formatted json | [
"Return",
"a",
"pretty",
"formatted",
"json"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/utils.py#L5-L9 |
josuebrunel/myql | myql/utils.py | pretty_xml | def pretty_xml(data):
"""Return a pretty formated xml
"""
parsed_string = minidom.parseString(data.decode('utf-8'))
return parsed_string.toprettyxml(indent='\t', encoding='utf-8') | python | def pretty_xml(data):
"""Return a pretty formated xml
"""
parsed_string = minidom.parseString(data.decode('utf-8'))
return parsed_string.toprettyxml(indent='\t', encoding='utf-8') | [
"def",
"pretty_xml",
"(",
"data",
")",
":",
"parsed_string",
"=",
"minidom",
".",
"parseString",
"(",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"return",
"parsed_string",
".",
"toprettyxml",
"(",
"indent",
"=",
"'\\t'",
",",
"encoding",
"=",
"'utf-8... | Return a pretty formated xml | [
"Return",
"a",
"pretty",
"formated",
"xml"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/utils.py#L12-L16 |
josuebrunel/myql | myql/utils.py | prettyfy | def prettyfy(response, format='json'):
"""A wrapper for pretty_json and pretty_xml
"""
if format == 'json':
return pretty_json(response.content)
else:
return pretty_xml(response.content) | python | def prettyfy(response, format='json'):
"""A wrapper for pretty_json and pretty_xml
"""
if format == 'json':
return pretty_json(response.content)
else:
return pretty_xml(response.content) | [
"def",
"prettyfy",
"(",
"response",
",",
"format",
"=",
"'json'",
")",
":",
"if",
"format",
"==",
"'json'",
":",
"return",
"pretty_json",
"(",
"response",
".",
"content",
")",
"else",
":",
"return",
"pretty_xml",
"(",
"response",
".",
"content",
")"
] | A wrapper for pretty_json and pretty_xml | [
"A",
"wrapper",
"for",
"pretty_json",
"and",
"pretty_xml"
] | train | https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/utils.py#L19-L25 |
noxdafox/vminspect | vminspect/timeline.py | parse_journal | def parse_journal(journal):
"""Parses the USN Journal content removing duplicates
and corrupted records.
"""
events = [e for e in journal if not isinstance(e, CorruptedUsnRecord)]
keyfunc = lambda e: str(e.file_reference_number) + e.file_name + e.timestamp
event_groups = (tuple(g) for k, g in groupby(events, key=keyfunc))
if len(events) < len(list(journal)):
LOGGER.debug(
"Corrupted records in UsnJrnl, some events might be missing.")
return [journal_event(g) for g in event_groups] | python | def parse_journal(journal):
"""Parses the USN Journal content removing duplicates
and corrupted records.
"""
events = [e for e in journal if not isinstance(e, CorruptedUsnRecord)]
keyfunc = lambda e: str(e.file_reference_number) + e.file_name + e.timestamp
event_groups = (tuple(g) for k, g in groupby(events, key=keyfunc))
if len(events) < len(list(journal)):
LOGGER.debug(
"Corrupted records in UsnJrnl, some events might be missing.")
return [journal_event(g) for g in event_groups] | [
"def",
"parse_journal",
"(",
"journal",
")",
":",
"events",
"=",
"[",
"e",
"for",
"e",
"in",
"journal",
"if",
"not",
"isinstance",
"(",
"e",
",",
"CorruptedUsnRecord",
")",
"]",
"keyfunc",
"=",
"lambda",
"e",
":",
"str",
"(",
"e",
".",
"file_reference_... | Parses the USN Journal content removing duplicates
and corrupted records. | [
"Parses",
"the",
"USN",
"Journal",
"content",
"removing",
"duplicates",
"and",
"corrupted",
"records",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L188-L201 |
noxdafox/vminspect | vminspect/timeline.py | journal_event | def journal_event(events):
"""Group multiple events into a single one."""
reasons = set(chain.from_iterable(e.reasons for e in events))
attributes = set(chain.from_iterable(e.file_attributes for e in events))
return JrnlEvent(events[0].file_reference_number,
events[0].parent_file_reference_number,
events[0].file_name,
events[0].timestamp,
list(reasons), list(attributes)) | python | def journal_event(events):
"""Group multiple events into a single one."""
reasons = set(chain.from_iterable(e.reasons for e in events))
attributes = set(chain.from_iterable(e.file_attributes for e in events))
return JrnlEvent(events[0].file_reference_number,
events[0].parent_file_reference_number,
events[0].file_name,
events[0].timestamp,
list(reasons), list(attributes)) | [
"def",
"journal_event",
"(",
"events",
")",
":",
"reasons",
"=",
"set",
"(",
"chain",
".",
"from_iterable",
"(",
"e",
".",
"reasons",
"for",
"e",
"in",
"events",
")",
")",
"attributes",
"=",
"set",
"(",
"chain",
".",
"from_iterable",
"(",
"e",
".",
"... | Group multiple events into a single one. | [
"Group",
"multiple",
"events",
"into",
"a",
"single",
"one",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L204-L213 |
noxdafox/vminspect | vminspect/timeline.py | generate_timeline | def generate_timeline(usnjrnl, filesystem_content):
"""Aggregates the data collected from the USN journal
and the filesystem content.
"""
journal_content = defaultdict(list)
for event in usnjrnl:
journal_content[event.inode].append(event)
for event in usnjrnl:
try:
dirent = lookup_dirent(event, filesystem_content, journal_content)
yield UsnJrnlEvent(
dirent.inode, dirent.path, dirent.size, dirent.allocated,
event.timestamp, event.changes, event.attributes)
except LookupError as error:
LOGGER.debug(error) | python | def generate_timeline(usnjrnl, filesystem_content):
"""Aggregates the data collected from the USN journal
and the filesystem content.
"""
journal_content = defaultdict(list)
for event in usnjrnl:
journal_content[event.inode].append(event)
for event in usnjrnl:
try:
dirent = lookup_dirent(event, filesystem_content, journal_content)
yield UsnJrnlEvent(
dirent.inode, dirent.path, dirent.size, dirent.allocated,
event.timestamp, event.changes, event.attributes)
except LookupError as error:
LOGGER.debug(error) | [
"def",
"generate_timeline",
"(",
"usnjrnl",
",",
"filesystem_content",
")",
":",
"journal_content",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"event",
"in",
"usnjrnl",
":",
"journal_content",
"[",
"event",
".",
"inode",
"]",
".",
"append",
"(",
"event",
"... | Aggregates the data collected from the USN journal
and the filesystem content. | [
"Aggregates",
"the",
"data",
"collected",
"from",
"the",
"USN",
"journal",
"and",
"the",
"filesystem",
"content",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L216-L233 |
noxdafox/vminspect | vminspect/timeline.py | lookup_dirent | def lookup_dirent(event, filesystem_content, journal_content):
"""Lookup the dirent given a journal event."""
for dirent in filesystem_content[event.inode]:
if dirent.path.endswith(event.name):
return dirent
path = lookup_folder(event, filesystem_content)
if path is not None:
return Dirent(event.inode, path, -1, None, False, 0, 0, 0, 0)
path = lookup_deleted_folder(event, filesystem_content, journal_content)
if path is not None:
return Dirent(event.inode, path, -1, None, False, 0, 0, 0, 0)
raise LookupError("File %s not found" % event.name) | python | def lookup_dirent(event, filesystem_content, journal_content):
"""Lookup the dirent given a journal event."""
for dirent in filesystem_content[event.inode]:
if dirent.path.endswith(event.name):
return dirent
path = lookup_folder(event, filesystem_content)
if path is not None:
return Dirent(event.inode, path, -1, None, False, 0, 0, 0, 0)
path = lookup_deleted_folder(event, filesystem_content, journal_content)
if path is not None:
return Dirent(event.inode, path, -1, None, False, 0, 0, 0, 0)
raise LookupError("File %s not found" % event.name) | [
"def",
"lookup_dirent",
"(",
"event",
",",
"filesystem_content",
",",
"journal_content",
")",
":",
"for",
"dirent",
"in",
"filesystem_content",
"[",
"event",
".",
"inode",
"]",
":",
"if",
"dirent",
".",
"path",
".",
"endswith",
"(",
"event",
".",
"name",
"... | Lookup the dirent given a journal event. | [
"Lookup",
"the",
"dirent",
"given",
"a",
"journal",
"event",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L236-L250 |
noxdafox/vminspect | vminspect/timeline.py | lookup_folder | def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and dirent.allocated:
return ntpath.join(dirent.path, event.name) | python | def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and dirent.allocated:
return ntpath.join(dirent.path, event.name) | [
"def",
"lookup_folder",
"(",
"event",
",",
"filesystem",
")",
":",
"for",
"dirent",
"in",
"filesystem",
"[",
"event",
".",
"parent_inode",
"]",
":",
"if",
"dirent",
".",
"type",
"==",
"'d'",
"and",
"dirent",
".",
"allocated",
":",
"return",
"ntpath",
"."... | Lookup the parent folder in the filesystem content. | [
"Lookup",
"the",
"parent",
"folder",
"in",
"the",
"filesystem",
"content",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L253-L257 |
noxdafox/vminspect | vminspect/timeline.py | lookup_deleted_folder | def lookup_deleted_folder(event, filesystem, journal):
"""Lookup the parent folder in the journal content."""
folder_events = (e for e in journal[event.parent_inode]
if 'DIRECTORY' in e.attributes
and 'FILE_DELETE' in e.changes)
for folder_event in folder_events:
path = lookup_deleted_folder(folder_event, filesystem, journal)
return ntpath.join(path, event.name)
return lookup_folder(event, filesystem) | python | def lookup_deleted_folder(event, filesystem, journal):
"""Lookup the parent folder in the journal content."""
folder_events = (e for e in journal[event.parent_inode]
if 'DIRECTORY' in e.attributes
and 'FILE_DELETE' in e.changes)
for folder_event in folder_events:
path = lookup_deleted_folder(folder_event, filesystem, journal)
return ntpath.join(path, event.name)
return lookup_folder(event, filesystem) | [
"def",
"lookup_deleted_folder",
"(",
"event",
",",
"filesystem",
",",
"journal",
")",
":",
"folder_events",
"=",
"(",
"e",
"for",
"e",
"in",
"journal",
"[",
"event",
".",
"parent_inode",
"]",
"if",
"'DIRECTORY'",
"in",
"e",
".",
"attributes",
"and",
"'FILE... | Lookup the parent folder in the journal content. | [
"Lookup",
"the",
"parent",
"folder",
"in",
"the",
"journal",
"content",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L260-L271 |
noxdafox/vminspect | vminspect/timeline.py | FSTimeline._visit_filesystem | def _visit_filesystem(self):
"""Walks through the filesystem content."""
self.logger.debug("Parsing File System content.")
root_partition = self._filesystem.inspect_get_roots()[0]
yield from self._root_dirent()
for entry in self._filesystem.filesystem_walk(root_partition):
yield Dirent(
entry['tsk_inode'],
self._filesystem.path('/' + entry['tsk_name']),
entry['tsk_size'], entry['tsk_type'],
True if entry['tsk_flags'] & TSK_ALLOC else False,
timestamp(entry['tsk_atime_sec'], entry['tsk_atime_nsec']),
timestamp(entry['tsk_mtime_sec'], entry['tsk_mtime_nsec']),
timestamp(entry['tsk_ctime_sec'], entry['tsk_ctime_nsec']),
timestamp(entry['tsk_crtime_sec'], entry['tsk_crtime_nsec'])) | python | def _visit_filesystem(self):
"""Walks through the filesystem content."""
self.logger.debug("Parsing File System content.")
root_partition = self._filesystem.inspect_get_roots()[0]
yield from self._root_dirent()
for entry in self._filesystem.filesystem_walk(root_partition):
yield Dirent(
entry['tsk_inode'],
self._filesystem.path('/' + entry['tsk_name']),
entry['tsk_size'], entry['tsk_type'],
True if entry['tsk_flags'] & TSK_ALLOC else False,
timestamp(entry['tsk_atime_sec'], entry['tsk_atime_nsec']),
timestamp(entry['tsk_mtime_sec'], entry['tsk_mtime_nsec']),
timestamp(entry['tsk_ctime_sec'], entry['tsk_ctime_nsec']),
timestamp(entry['tsk_crtime_sec'], entry['tsk_crtime_nsec'])) | [
"def",
"_visit_filesystem",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Parsing File System content.\"",
")",
"root_partition",
"=",
"self",
".",
"_filesystem",
".",
"inspect_get_roots",
"(",
")",
"[",
"0",
"]",
"yield",
"from",
"self",... | Walks through the filesystem content. | [
"Walks",
"through",
"the",
"filesystem",
"content",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L97-L114 |
noxdafox/vminspect | vminspect/timeline.py | FSTimeline._root_dirent | def _root_dirent(self):
"""Returns the root folder dirent as filesystem_walk API doesn't."""
fstat = self._filesystem.stat('/')
yield Dirent(fstat['ino'], self._filesystem.path('/'),
fstat['size'], 'd', True,
timestamp(fstat['atime'], 0),
timestamp(fstat['mtime'], 0),
timestamp(fstat['ctime'], 0),
0) | python | def _root_dirent(self):
"""Returns the root folder dirent as filesystem_walk API doesn't."""
fstat = self._filesystem.stat('/')
yield Dirent(fstat['ino'], self._filesystem.path('/'),
fstat['size'], 'd', True,
timestamp(fstat['atime'], 0),
timestamp(fstat['mtime'], 0),
timestamp(fstat['ctime'], 0),
0) | [
"def",
"_root_dirent",
"(",
"self",
")",
":",
"fstat",
"=",
"self",
".",
"_filesystem",
".",
"stat",
"(",
"'/'",
")",
"yield",
"Dirent",
"(",
"fstat",
"[",
"'ino'",
"]",
",",
"self",
".",
"_filesystem",
".",
"path",
"(",
"'/'",
")",
",",
"fstat",
"... | Returns the root folder dirent as filesystem_walk API doesn't. | [
"Returns",
"the",
"root",
"folder",
"dirent",
"as",
"filesystem_walk",
"API",
"doesn",
"t",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L116-L125 |
noxdafox/vminspect | vminspect/timeline.py | NTFSTimeline.usnjrnl_timeline | def usnjrnl_timeline(self):
"""Iterates over the changes occurred within the filesystem.
Yields UsnJrnlEvent namedtuples containing:
file_reference_number: known in Unix FS as inode.
path: full path of the file.
size: size of the file in bytes if recoverable.
allocated: whether the file exists or it has been deleted.
timestamp: timespamp of the change.
changes: list of changes applied to the file.
attributes: list of file attributes.
"""
filesystem_content = defaultdict(list)
self.logger.debug("Extracting Update Sequence Number journal.")
journal = self._read_journal()
for dirent in self._visit_filesystem():
filesystem_content[dirent.inode].append(dirent)
self.logger.debug("Generating timeline.")
yield from generate_timeline(journal, filesystem_content) | python | def usnjrnl_timeline(self):
"""Iterates over the changes occurred within the filesystem.
Yields UsnJrnlEvent namedtuples containing:
file_reference_number: known in Unix FS as inode.
path: full path of the file.
size: size of the file in bytes if recoverable.
allocated: whether the file exists or it has been deleted.
timestamp: timespamp of the change.
changes: list of changes applied to the file.
attributes: list of file attributes.
"""
filesystem_content = defaultdict(list)
self.logger.debug("Extracting Update Sequence Number journal.")
journal = self._read_journal()
for dirent in self._visit_filesystem():
filesystem_content[dirent.inode].append(dirent)
self.logger.debug("Generating timeline.")
yield from generate_timeline(journal, filesystem_content) | [
"def",
"usnjrnl_timeline",
"(",
"self",
")",
":",
"filesystem_content",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Extracting Update Sequence Number journal.\"",
")",
"journal",
"=",
"self",
".",
"_read_journal",
"(",
")",
... | Iterates over the changes occurred within the filesystem.
Yields UsnJrnlEvent namedtuples containing:
file_reference_number: known in Unix FS as inode.
path: full path of the file.
size: size of the file in bytes if recoverable.
allocated: whether the file exists or it has been deleted.
timestamp: timespamp of the change.
changes: list of changes applied to the file.
attributes: list of file attributes. | [
"Iterates",
"over",
"the",
"changes",
"occurred",
"within",
"the",
"filesystem",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L149-L173 |
noxdafox/vminspect | vminspect/timeline.py | NTFSTimeline._read_journal | def _read_journal(self):
"""Extracts the USN journal from the disk and parses its content."""
root = self._filesystem.inspect_get_roots()[0]
inode = self._filesystem.stat('C:\\$Extend\\$UsnJrnl')['ino']
with NamedTemporaryFile(buffering=0) as tempfile:
self._filesystem.download_inode(root, inode, tempfile.name)
journal = usn_journal(tempfile.name)
return parse_journal(journal) | python | def _read_journal(self):
"""Extracts the USN journal from the disk and parses its content."""
root = self._filesystem.inspect_get_roots()[0]
inode = self._filesystem.stat('C:\\$Extend\\$UsnJrnl')['ino']
with NamedTemporaryFile(buffering=0) as tempfile:
self._filesystem.download_inode(root, inode, tempfile.name)
journal = usn_journal(tempfile.name)
return parse_journal(journal) | [
"def",
"_read_journal",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"_filesystem",
".",
"inspect_get_roots",
"(",
")",
"[",
"0",
"]",
"inode",
"=",
"self",
".",
"_filesystem",
".",
"stat",
"(",
"'C:\\\\$Extend\\\\$UsnJrnl'",
")",
"[",
"'ino'",
"]",
... | Extracts the USN journal from the disk and parses its content. | [
"Extracts",
"the",
"USN",
"journal",
"from",
"the",
"disk",
"and",
"parses",
"its",
"content",
"."
] | train | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/timeline.py#L175-L185 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.put | def put(self, stream, cmd):
""" Spawn a new background process """
if len(self.q) < self.max_size:
if stream['id'] in self.q:
raise QueueDuplicate
p = self.call(stream, cmd)
self.q[stream['id']] = p
else:
raise QueueFull | python | def put(self, stream, cmd):
""" Spawn a new background process """
if len(self.q) < self.max_size:
if stream['id'] in self.q:
raise QueueDuplicate
p = self.call(stream, cmd)
self.q[stream['id']] = p
else:
raise QueueFull | [
"def",
"put",
"(",
"self",
",",
"stream",
",",
"cmd",
")",
":",
"if",
"len",
"(",
"self",
".",
"q",
")",
"<",
"self",
".",
"max_size",
":",
"if",
"stream",
"[",
"'id'",
"]",
"in",
"self",
".",
"q",
":",
"raise",
"QueueDuplicate",
"p",
"=",
"sel... | Spawn a new background process | [
"Spawn",
"a",
"new",
"background",
"process"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L63-L72 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.get_finished | def get_finished(self):
""" Clean up terminated processes and returns the list of their ids """
indices = []
for idf, v in self.q.items():
if v.poll() != None:
indices.append(idf)
for i in indices:
self.q.pop(i)
return indices | python | def get_finished(self):
""" Clean up terminated processes and returns the list of their ids """
indices = []
for idf, v in self.q.items():
if v.poll() != None:
indices.append(idf)
for i in indices:
self.q.pop(i)
return indices | [
"def",
"get_finished",
"(",
"self",
")",
":",
"indices",
"=",
"[",
"]",
"for",
"idf",
",",
"v",
"in",
"self",
".",
"q",
".",
"items",
"(",
")",
":",
"if",
"v",
".",
"poll",
"(",
")",
"!=",
"None",
":",
"indices",
".",
"append",
"(",
"idf",
")... | Clean up terminated processes and returns the list of their ids | [
"Clean",
"up",
"terminated",
"processes",
"and",
"returns",
"the",
"list",
"of",
"their",
"ids"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L74-L83 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.get_stdouts | def get_stdouts(self):
""" Get the list of stdout of each process """
souts = []
for v in self.q.values():
souts.append(v.stdout)
return souts | python | def get_stdouts(self):
""" Get the list of stdout of each process """
souts = []
for v in self.q.values():
souts.append(v.stdout)
return souts | [
"def",
"get_stdouts",
"(",
"self",
")",
":",
"souts",
"=",
"[",
"]",
"for",
"v",
"in",
"self",
".",
"q",
".",
"values",
"(",
")",
":",
"souts",
".",
"append",
"(",
"v",
".",
"stdout",
")",
"return",
"souts"
] | Get the list of stdout of each process | [
"Get",
"the",
"list",
"of",
"stdout",
"of",
"each",
"process"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L89-L94 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.terminate_process | def terminate_process(self, idf):
""" Terminate a process by id """
try:
p = self.q.pop(idf)
p.terminate()
return p
except:
return None | python | def terminate_process(self, idf):
""" Terminate a process by id """
try:
p = self.q.pop(idf)
p.terminate()
return p
except:
return None | [
"def",
"terminate_process",
"(",
"self",
",",
"idf",
")",
":",
"try",
":",
"p",
"=",
"self",
".",
"q",
".",
"pop",
"(",
"idf",
")",
"p",
".",
"terminate",
"(",
")",
"return",
"p",
"except",
":",
"return",
"None"
] | Terminate a process by id | [
"Terminate",
"a",
"process",
"by",
"id"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L96-L103 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | ProcessList.terminate | def terminate(self):
""" Terminate all processes """
for w in self.q.values():
try:
w.terminate()
except:
pass
self.q = {} | python | def terminate(self):
""" Terminate all processes """
for w in self.q.values():
try:
w.terminate()
except:
pass
self.q = {} | [
"def",
"terminate",
"(",
"self",
")",
":",
"for",
"w",
"in",
"self",
".",
"q",
".",
"values",
"(",
")",
":",
"try",
":",
"w",
".",
"terminate",
"(",
")",
"except",
":",
"pass",
"self",
".",
"q",
"=",
"{",
"}"
] | Terminate all processes | [
"Terminate",
"all",
"processes"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L105-L113 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.init | def init(self, s):
""" Initialize the text interface """
# Hide cursor
curses.curs_set(0)
self.s = s
self.s.keypad(1)
self.set_screen_size()
self.pads = {}
self.offsets = {}
self.init_help()
self.init_streams_pad()
self.current_pad = 'streams'
self.set_title(TITLE_STRING)
self.got_g = False
signal.signal(28, self.resize)
if self.config.CHECK_ONLINE_ON_START:
self.check_online_streams()
self.set_status('Ready') | python | def init(self, s):
""" Initialize the text interface """
# Hide cursor
curses.curs_set(0)
self.s = s
self.s.keypad(1)
self.set_screen_size()
self.pads = {}
self.offsets = {}
self.init_help()
self.init_streams_pad()
self.current_pad = 'streams'
self.set_title(TITLE_STRING)
self.got_g = False
signal.signal(28, self.resize)
if self.config.CHECK_ONLINE_ON_START:
self.check_online_streams()
self.set_status('Ready') | [
"def",
"init",
"(",
"self",
",",
"s",
")",
":",
"# Hide cursor",
"curses",
".",
"curs_set",
"(",
"0",
")",
"self",
".",
"s",
"=",
"s",
"self",
".",
"s",
".",
"keypad",
"(",
"1",
")",
"self",
".",
"set_screen_size",
"(",
")",
"self",
".",
"pads",
... | Initialize the text interface | [
"Initialize",
"the",
"text",
"interface"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L217-L244 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.getheightwidth | def getheightwidth(self):
""" getwidth() -> (int, int)
Return the height and width of the console in characters
https://groups.google.com/forum/#!msg/comp.lang.python/CpUszNNXUQM/QADpl11Z-nAJ"""
try:
return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
except KeyError:
height, width = struct.unpack(
"hhhh", ioctl(0, termios.TIOCGWINSZ ,"\000"*8))[0:2]
if not height:
return 25, 80
return height, width | python | def getheightwidth(self):
""" getwidth() -> (int, int)
Return the height and width of the console in characters
https://groups.google.com/forum/#!msg/comp.lang.python/CpUszNNXUQM/QADpl11Z-nAJ"""
try:
return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
except KeyError:
height, width = struct.unpack(
"hhhh", ioctl(0, termios.TIOCGWINSZ ,"\000"*8))[0:2]
if not height:
return 25, 80
return height, width | [
"def",
"getheightwidth",
"(",
"self",
")",
":",
"try",
":",
"return",
"int",
"(",
"os",
".",
"environ",
"[",
"\"LINES\"",
"]",
")",
",",
"int",
"(",
"os",
".",
"environ",
"[",
"\"COLUMNS\"",
"]",
")",
"except",
"KeyError",
":",
"height",
",",
"width"... | getwidth() -> (int, int)
Return the height and width of the console in characters
https://groups.google.com/forum/#!msg/comp.lang.python/CpUszNNXUQM/QADpl11Z-nAJ | [
"getwidth",
"()",
"-",
">",
"(",
"int",
"int",
")"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L246-L258 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.resize | def resize(self, signum, obj):
""" handler for SIGWINCH """
self.s.clear()
stream_cursor = self.pads['streams'].getyx()[0]
for pad in self.pads.values():
pad.clear()
self.s.refresh()
self.set_screen_size()
self.set_title(TITLE_STRING)
self.init_help()
self.init_streams_pad()
self.move(stream_cursor, absolute=True, pad_name='streams', refresh=False)
self.s.refresh()
self.show() | python | def resize(self, signum, obj):
""" handler for SIGWINCH """
self.s.clear()
stream_cursor = self.pads['streams'].getyx()[0]
for pad in self.pads.values():
pad.clear()
self.s.refresh()
self.set_screen_size()
self.set_title(TITLE_STRING)
self.init_help()
self.init_streams_pad()
self.move(stream_cursor, absolute=True, pad_name='streams', refresh=False)
self.s.refresh()
self.show() | [
"def",
"resize",
"(",
"self",
",",
"signum",
",",
"obj",
")",
":",
"self",
".",
"s",
".",
"clear",
"(",
")",
"stream_cursor",
"=",
"self",
".",
"pads",
"[",
"'streams'",
"]",
".",
"getyx",
"(",
")",
"[",
"0",
"]",
"for",
"pad",
"in",
"self",
".... | handler for SIGWINCH | [
"handler",
"for",
"SIGWINCH"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L260-L273 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.run | def run(self):
""" Main event loop """
# Show stream list
self.show_streams()
while True:
self.s.refresh()
# See if any stream has ended
self.check_stopped_streams()
# Wait on stdin or on the streams output
souts = self.q.get_stdouts()
souts.append(sys.stdin)
try:
(r, w, x) = select.select(souts, [], [], 1)
except select.error:
continue
if not r:
if self.config.CHECK_ONLINE_INTERVAL <= 0: continue
cur_time = int(time())
time_delta = cur_time - self.last_autocheck
if time_delta > self.config.CHECK_ONLINE_INTERVAL:
self.check_online_streams()
self.set_status('Next check at {0}'.format(
strftime('%H:%M:%S', localtime(time() + self.config.CHECK_ONLINE_INTERVAL))
))
continue
for fd in r:
if fd != sys.stdin:
# Set the new status line only if non-empty
msg = fd.readline()
if msg:
self.set_status(msg[:-1])
else:
# Main event loop
c = self.pads[self.current_pad].getch()
if c == curses.KEY_UP or c == ord('k'):
self.move(-1)
elif c == curses.KEY_DOWN or c == ord('j'):
self.move(1)
elif c == ord('f'):
if self.current_pad == 'streams':
self.filter_streams()
elif c == ord('F'):
if self.current_pad == 'streams':
self.clear_filter()
elif c == ord('g'):
if self.got_g:
self.move(0, absolute=True)
self.got_g = False
continue
self.got_g = True
elif c == ord('G'):
self.move(len(self.filtered_streams)-1, absolute=True)
elif c == ord('q'):
if self.current_pad == 'streams':
self.q.terminate()
return
else:
self.show_streams()
elif c == 27: # ESC
if self.current_pad != 'streams':
self.show_streams()
if self.current_pad == 'help':
continue
elif c == 10:
self.play_stream()
elif c == ord('s'):
self.stop_stream()
elif c == ord('c'):
self.reset_stream()
elif c == ord('n'):
self.edit_stream('name')
elif c == ord('r'):
self.edit_stream('res')
elif c == ord('u'):
self.edit_stream('url')
elif c == ord('l'):
self.show_commandline()
elif c == ord('L'):
self.shift_commandline()
elif c == ord('a'):
self.prompt_new_stream()
elif c == ord('d'):
self.delete_stream()
elif c == ord('o'):
self.show_offline_streams ^= True
self.refilter_streams()
elif c == ord('O'):
self.check_online_streams()
elif c == ord('h') or c == ord('?'):
self.show_help() | python | def run(self):
""" Main event loop """
# Show stream list
self.show_streams()
while True:
self.s.refresh()
# See if any stream has ended
self.check_stopped_streams()
# Wait on stdin or on the streams output
souts = self.q.get_stdouts()
souts.append(sys.stdin)
try:
(r, w, x) = select.select(souts, [], [], 1)
except select.error:
continue
if not r:
if self.config.CHECK_ONLINE_INTERVAL <= 0: continue
cur_time = int(time())
time_delta = cur_time - self.last_autocheck
if time_delta > self.config.CHECK_ONLINE_INTERVAL:
self.check_online_streams()
self.set_status('Next check at {0}'.format(
strftime('%H:%M:%S', localtime(time() + self.config.CHECK_ONLINE_INTERVAL))
))
continue
for fd in r:
if fd != sys.stdin:
# Set the new status line only if non-empty
msg = fd.readline()
if msg:
self.set_status(msg[:-1])
else:
# Main event loop
c = self.pads[self.current_pad].getch()
if c == curses.KEY_UP or c == ord('k'):
self.move(-1)
elif c == curses.KEY_DOWN or c == ord('j'):
self.move(1)
elif c == ord('f'):
if self.current_pad == 'streams':
self.filter_streams()
elif c == ord('F'):
if self.current_pad == 'streams':
self.clear_filter()
elif c == ord('g'):
if self.got_g:
self.move(0, absolute=True)
self.got_g = False
continue
self.got_g = True
elif c == ord('G'):
self.move(len(self.filtered_streams)-1, absolute=True)
elif c == ord('q'):
if self.current_pad == 'streams':
self.q.terminate()
return
else:
self.show_streams()
elif c == 27: # ESC
if self.current_pad != 'streams':
self.show_streams()
if self.current_pad == 'help':
continue
elif c == 10:
self.play_stream()
elif c == ord('s'):
self.stop_stream()
elif c == ord('c'):
self.reset_stream()
elif c == ord('n'):
self.edit_stream('name')
elif c == ord('r'):
self.edit_stream('res')
elif c == ord('u'):
self.edit_stream('url')
elif c == ord('l'):
self.show_commandline()
elif c == ord('L'):
self.shift_commandline()
elif c == ord('a'):
self.prompt_new_stream()
elif c == ord('d'):
self.delete_stream()
elif c == ord('o'):
self.show_offline_streams ^= True
self.refilter_streams()
elif c == ord('O'):
self.check_online_streams()
elif c == ord('h') or c == ord('?'):
self.show_help() | [
"def",
"run",
"(",
"self",
")",
":",
"# Show stream list",
"self",
".",
"show_streams",
"(",
")",
"while",
"True",
":",
"self",
".",
"s",
".",
"refresh",
"(",
")",
"# See if any stream has ended",
"self",
".",
"check_stopped_streams",
"(",
")",
"# Wait on stdi... | Main event loop | [
"Main",
"event",
"loop"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L275-L368 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_screen_size | def set_screen_size(self):
""" Setup screen size and padding
We have need 2 free lines at the top and 2 free lines at the bottom
"""
height, width = self.getheightwidth()
curses.resizeterm(height, width)
self.pad_x = 0
self.max_y, self.max_x = (height-1, width-1)
self.pad_h = height-3
self.pad_w = width-2*self.pad_x | python | def set_screen_size(self):
""" Setup screen size and padding
We have need 2 free lines at the top and 2 free lines at the bottom
"""
height, width = self.getheightwidth()
curses.resizeterm(height, width)
self.pad_x = 0
self.max_y, self.max_x = (height-1, width-1)
self.pad_h = height-3
self.pad_w = width-2*self.pad_x | [
"def",
"set_screen_size",
"(",
"self",
")",
":",
"height",
",",
"width",
"=",
"self",
".",
"getheightwidth",
"(",
")",
"curses",
".",
"resizeterm",
"(",
"height",
",",
"width",
")",
"self",
".",
"pad_x",
"=",
"0",
"self",
".",
"max_y",
",",
"self",
"... | Setup screen size and padding
We have need 2 free lines at the top and 2 free lines at the bottom | [
"Setup",
"screen",
"size",
"and",
"padding"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L370-L381 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_title | def set_title(self, msg):
""" Set first header line text """
self.s.move(0, 0)
self.overwrite_line(msg, curses.A_REVERSE) | python | def set_title(self, msg):
""" Set first header line text """
self.s.move(0, 0)
self.overwrite_line(msg, curses.A_REVERSE) | [
"def",
"set_title",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"s",
".",
"move",
"(",
"0",
",",
"0",
")",
"self",
".",
"overwrite_line",
"(",
"msg",
",",
"curses",
".",
"A_REVERSE",
")"
] | Set first header line text | [
"Set",
"first",
"header",
"line",
"text"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L388-L391 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_header | def set_header(self, msg):
""" Set second head line text """
self.s.move(1, 0)
self.overwrite_line(msg, attr=curses.A_NORMAL) | python | def set_header(self, msg):
""" Set second head line text """
self.s.move(1, 0)
self.overwrite_line(msg, attr=curses.A_NORMAL) | [
"def",
"set_header",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"s",
".",
"move",
"(",
"1",
",",
"0",
")",
"self",
".",
"overwrite_line",
"(",
"msg",
",",
"attr",
"=",
"curses",
".",
"A_NORMAL",
")"
] | Set second head line text | [
"Set",
"second",
"head",
"line",
"text"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L393-L396 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.set_footer | def set_footer(self, msg, reverse=True):
""" Set first footer line text """
self.s.move(self.max_y-1, 0)
if reverse:
self.overwrite_line(msg, attr=curses.A_REVERSE)
else:
self.overwrite_line(msg, attr=curses.A_NORMAL) | python | def set_footer(self, msg, reverse=True):
""" Set first footer line text """
self.s.move(self.max_y-1, 0)
if reverse:
self.overwrite_line(msg, attr=curses.A_REVERSE)
else:
self.overwrite_line(msg, attr=curses.A_NORMAL) | [
"def",
"set_footer",
"(",
"self",
",",
"msg",
",",
"reverse",
"=",
"True",
")",
":",
"self",
".",
"s",
".",
"move",
"(",
"self",
".",
"max_y",
"-",
"1",
",",
"0",
")",
"if",
"reverse",
":",
"self",
".",
"overwrite_line",
"(",
"msg",
",",
"attr",
... | Set first footer line text | [
"Set",
"first",
"footer",
"line",
"text"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L398-L404 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.show_help | def show_help(self):
""" Redraw Help screen and wait for any input to leave """
self.s.move(1,0)
self.s.clrtobot()
self.set_header('Help'.center(self.pad_w))
self.set_footer(' ESC or \'q\' to return to main menu')
self.s.refresh()
self.current_pad = 'help'
self.refresh_current_pad() | python | def show_help(self):
""" Redraw Help screen and wait for any input to leave """
self.s.move(1,0)
self.s.clrtobot()
self.set_header('Help'.center(self.pad_w))
self.set_footer(' ESC or \'q\' to return to main menu')
self.s.refresh()
self.current_pad = 'help'
self.refresh_current_pad() | [
"def",
"show_help",
"(",
"self",
")",
":",
"self",
".",
"s",
".",
"move",
"(",
"1",
",",
"0",
")",
"self",
".",
"s",
".",
"clrtobot",
"(",
")",
"self",
".",
"set_header",
"(",
"'Help'",
".",
"center",
"(",
"self",
".",
"pad_w",
")",
")",
"self"... | Redraw Help screen and wait for any input to leave | [
"Redraw",
"Help",
"screen",
"and",
"wait",
"for",
"any",
"input",
"to",
"leave"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L450-L458 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.init_streams_pad | def init_streams_pad(self, start_row=0):
""" Create a curses pad and populate it with a line by stream """
y = 0
pad = curses.newpad(max(1,len(self.filtered_streams)), self.pad_w)
pad.keypad(1)
for s in self.filtered_streams:
pad.addstr(y, 0, self.format_stream_line(s))
y+=1
self.offsets['streams'] = 0
pad.move(start_row, 0)
if not self.no_stream_shown:
pad.chgat(curses.A_REVERSE)
self.pads['streams'] = pad | python | def init_streams_pad(self, start_row=0):
""" Create a curses pad and populate it with a line by stream """
y = 0
pad = curses.newpad(max(1,len(self.filtered_streams)), self.pad_w)
pad.keypad(1)
for s in self.filtered_streams:
pad.addstr(y, 0, self.format_stream_line(s))
y+=1
self.offsets['streams'] = 0
pad.move(start_row, 0)
if not self.no_stream_shown:
pad.chgat(curses.A_REVERSE)
self.pads['streams'] = pad | [
"def",
"init_streams_pad",
"(",
"self",
",",
"start_row",
"=",
"0",
")",
":",
"y",
"=",
"0",
"pad",
"=",
"curses",
".",
"newpad",
"(",
"max",
"(",
"1",
",",
"len",
"(",
"self",
".",
"filtered_streams",
")",
")",
",",
"self",
".",
"pad_w",
")",
"p... | Create a curses pad and populate it with a line by stream | [
"Create",
"a",
"curses",
"pad",
"and",
"populate",
"it",
"with",
"a",
"line",
"by",
"stream"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L460-L472 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | StreamList.move | def move(self, direction, absolute=False, pad_name=None, refresh=True):
""" Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
Behaviour is affected by cursor_line and scroll_only below
absolute : (bool)
"""
# pad in this lists have the current line highlighted
cursor_line = [ 'streams' ]
# pads in this list will be moved screen-wise as opposed to line-wise
# if absolute is set, will go all the way top or all the way down depending
# on direction
scroll_only = [ 'help' ]
if not pad_name:
pad_name = self.current_pad
pad = self.pads[pad_name]
if pad_name == 'streams' and self.no_streams:
return
(row, col) = pad.getyx()
new_row = row
offset = self.offsets[pad_name]
new_offset = offset
if pad_name in scroll_only:
if absolute:
if direction > 0:
new_offset = pad.getmaxyx()[0] - self.pad_h + 1
else:
new_offset = 0
else:
if direction > 0:
new_offset = min(pad.getmaxyx()[0] - self.pad_h + 1, offset + self.pad_h)
elif offset > 0:
new_offset = max(0, offset - self.pad_h)
else:
if absolute and direction >= 0 and direction < pad.getmaxyx()[0]:
if direction < offset:
new_offset = direction
elif direction > offset + self.pad_h - 2:
new_offset = direction - self.pad_h + 2
new_row = direction
else:
if direction == -1 and row > 0:
if row == offset:
new_offset -= 1
new_row = row-1
elif direction == 1 and row < len(self.filtered_streams)-1:
if row == offset + self.pad_h - 2:
new_offset += 1
new_row = row+1
if pad_name in cursor_line:
pad.move(row, 0)
pad.chgat(curses.A_NORMAL)
self.offsets[pad_name] = new_offset
pad.move(new_row, 0)
if pad_name in cursor_line:
pad.chgat(curses.A_REVERSE)
if pad_name == 'streams':
self.redraw_stream_footer()
if refresh:
self.refresh_current_pad() | python | def move(self, direction, absolute=False, pad_name=None, refresh=True):
""" Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
Behaviour is affected by cursor_line and scroll_only below
absolute : (bool)
"""
# pad in this lists have the current line highlighted
cursor_line = [ 'streams' ]
# pads in this list will be moved screen-wise as opposed to line-wise
# if absolute is set, will go all the way top or all the way down depending
# on direction
scroll_only = [ 'help' ]
if not pad_name:
pad_name = self.current_pad
pad = self.pads[pad_name]
if pad_name == 'streams' and self.no_streams:
return
(row, col) = pad.getyx()
new_row = row
offset = self.offsets[pad_name]
new_offset = offset
if pad_name in scroll_only:
if absolute:
if direction > 0:
new_offset = pad.getmaxyx()[0] - self.pad_h + 1
else:
new_offset = 0
else:
if direction > 0:
new_offset = min(pad.getmaxyx()[0] - self.pad_h + 1, offset + self.pad_h)
elif offset > 0:
new_offset = max(0, offset - self.pad_h)
else:
if absolute and direction >= 0 and direction < pad.getmaxyx()[0]:
if direction < offset:
new_offset = direction
elif direction > offset + self.pad_h - 2:
new_offset = direction - self.pad_h + 2
new_row = direction
else:
if direction == -1 and row > 0:
if row == offset:
new_offset -= 1
new_row = row-1
elif direction == 1 and row < len(self.filtered_streams)-1:
if row == offset + self.pad_h - 2:
new_offset += 1
new_row = row+1
if pad_name in cursor_line:
pad.move(row, 0)
pad.chgat(curses.A_NORMAL)
self.offsets[pad_name] = new_offset
pad.move(new_row, 0)
if pad_name in cursor_line:
pad.chgat(curses.A_REVERSE)
if pad_name == 'streams':
self.redraw_stream_footer()
if refresh:
self.refresh_current_pad() | [
"def",
"move",
"(",
"self",
",",
"direction",
",",
"absolute",
"=",
"False",
",",
"pad_name",
"=",
"None",
",",
"refresh",
"=",
"True",
")",
":",
"# pad in this lists have the current line highlighted",
"cursor_line",
"=",
"[",
"'streams'",
"]",
"# pads in this li... | Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
Behaviour is affected by cursor_line and scroll_only below
absolute : (bool) | [
"Scroll",
"the",
"current",
"pad"
] | train | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L516-L580 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.