text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_nums(arr): """ Write a function count_nums which takes an array of integers and returns the number of elements which has a sum of digits > 0. e.g. -123 has signed digits -1, 2, and 3. """
def digits_sum(n): neg = 1 if n < 0: n, neg = -1 * n, -1 n = [int(i) for i in str(n)] n[0] = n[0] * neg return sum(n) return len(list(filter(lambda x: x > 0, [digits_sum(i) for i in arr])))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_one_ball(arr): """We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The numbers in the array will be randomly ordered. Your task is to determine if it is possible to get an array sorted in non-decreasing order by performing You are allowed to perform right shift operation any number of times. One right shift operation means shifting all elements of the array by one position in the right direction. The last element of the array will be moved to the starting position in the array i.e. 0th index. If it is possible to obtain the sorted array by performing the above operation then return True else return False. If the given array is empty then return True. be achieved for the given array. array by performing any number of right shift operations. """
if len(arr)==0: return True sorted_array=sorted(arr) my_arr=[] min_value=min(arr) min_index=arr.index(min_value) my_arr=arr[min_index:]+arr[0:min_index] for i in range(len(arr)): if my_arr[i]!=sorted_array[i]: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exchange(lst1, lst2): """In this problem, you will implement a function that takes two lists of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a list of only even numbers. There is no limit on the number of exchanged elements between lst1 and lst2. If it is possible to exchange elements between the lst1 and lst2 to make all the elements of lst1 to be even, return "YES". Otherwise, return "NO". It is assumed that the input lists will be non-empty. """
odd = 0 even = 0 for i in lst1: if i%2 == 1: odd += 1 for i in lst2: if i%2 == 0: even += 1 if even >= odd: return "YES" return "NO"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def histogram(test): """Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. histogram('') == {} """
dict1={} list1=test.split(" ") t=0 for i in list1: if(list1.count(i)>t) and i!='': t=list1.count(i) if t>0: for i in list1: if(list1.count(i)==t): dict1[i]=t return dict1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse_delete(s,c): """Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a tuple containing the result string and True/False for the check. Example For s = "abcde", c = "ae", the result should be ('bcd',False) For s = "abcdef", c = "b" the result should be ('acdef',False) For s = "abcdedcba", c = "ab", the result should be ('cdedc',True) """
s = ''.join([char for char in s if char not in c]) return (s,s[::-1] == s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def odd_count(lst): """Given a list of strings, where each string consists of only digits, return a list. Each element i of the output should be "the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of the input. ["the number of odd elements 4n the str4ng 4 of the 4nput."] ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."] """
res = [] for arr in lst: n = sum(int(d)%2==1 for d in arr) res.append("the number of odd elements " + str(n) + "n the str"+ str(n) +"ng "+ str(n) +" of the "+ str(n) +"nput.") return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minSubArraySum(nums): """ Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2, 4]) == 1 minSubArraySum([-1, -2, -3]) == -6 """
max_sum = 0 s = 0 for num in nums: s += -num if (s < 0): s = 0 max_sum = max(s, max_sum) if max_sum == 0: max_sum = max(-i for i in nums) min_sum = -max_sum return min_sum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_fill(grid, capacity): import math """ You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. """
return sum([math.ceil(sum(arr)/capacity) for arr in grid])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_array(arr): """ In this Kata, you have to sort an array of non-negative integers according to number of ones in their binary representation in ascending order. For similar number of ones, sort based on decimal value. """
return sorted(sorted(arr), key=lambda x: bin(x)[2:].count('1'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_words(s, n): """Given a string s and a natural number n, you have been tasked to implement a function that returns a list of all words from string s that contain exactly n consonants, in order these words appear in the string s. If the string s is empty then the function should return an empty list. """
result = [] for word in s.split(): n_consonants = 0 for i in range(0, len(word)): if word[i].lower() not in ["a","e","i","o","u"]: n_consonants += 1 if n_consonants == n: result.append(word) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_closest_vowel(word): """You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. """
if len(word) < 3: return "" vowels = {"a", "e", "i", "o", "u", "A", "E", 'O', 'U', 'I'} for i in range(len(word)-2, 0, -1): if word[i] in vowels: if (word[i+1] not in vowels) and (word[i-1] not in vowels): return word[i] return ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximum(arr, k): """ Given an array arr of integers and a positive integer k, return a sorted list of length k with the maximum k numbers in arr. 1. The length of the array will be in the range of [1, 1000]. 2. The elements in the array will be in the range of [-1000, 1000]. 3. 0 <= k <= len(arr) """
if k == 0: return [] arr.sort() ans = arr[-k:] return ans
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solution(lst): """Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. Examples """
return sum([x for idx, x in enumerate(lst) if idx%2==0 and x%2==1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_elements(arr, k): """ Given a non-empty array of integers arr and an integer k, return the sum of the elements with at most two digits from the first k elements of arr. 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr) """
return sum(elem for elem in arr[:k] if len(str(elem)) <= 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_odd_collatz(n): """ Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence. The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. 1. Collatz(1) is [1]. 2. returned list sorted in increasing order. get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. """
if n%2==0: odd_collatz = [] else: odd_collatz = [n] while n > 1: if n % 2 == 0: n = n/2 else: n = n*3 + 1 if n%2 == 1: odd_collatz.append(int(n)) return sorted(odd_collatz)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid_date(date): """You have to write a function which validates a given date string and returns True if the date is valid otherwise False. 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. """
try: date = date.strip() month, day, year = date.split('-') month, day, year = int(month), int(day), int(year) if month < 1 or month > 12: return False if month in [1,3,5,7,8,10,12] and day < 1 or day > 31: return False if month in [4,6,9,11] and day < 1 or day > 30: return False if month == 2 and day < 1 or day > 29: return False except: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersection(interval1, interval2): """You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". """
def is_prime(num): if num == 1 or num == 0: return False if num == 2: return True for i in range(2, num): if num%i == 0: return False return True l = max(interval1[0], interval2[0]) r = min(interval1[1], interval2[1]) length = r - l if length > 0 and is_prime(length): return "YES" return "NO"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prod_signs(arr): """ You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. """
if not arr: return None prod = 0 if 0 in arr else (-1) ** len(list(filter(lambda x: x < 0, arr))) return prod * sum([abs(i) for i in arr])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minPath(grid, k): """ Given a grid with N rows and N columns (N >= 2) and a positive integer k, inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. """
n = len(grid) val = n * n + 1 for i in range(n): for j in range(n): if grid[i][j] == 1: temp = [] if i != 0: temp.append(grid[i - 1][j]) if j != 0: temp.append(grid[i][j - 1]) if i != n - 1: temp.append(grid[i + 1][j]) if j != n - 1: temp.append(grid[i][j + 1]) val = min(temp) ans = [] for i in range(k): if i % 2 == 0: ans.append(1) else: ans.append(val) return ans
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tri(n): """Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. tri(1) = 3 tri(n) = 1 + n / 2, if n is even. tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd. tri(2) = 1 + (2 / 2) = 2 tri(4) = 3 tri(3) = tri(2) + tri(1) + tri(4) = 2 + 3 + 3 = 8 You are given a non-negative integer number n, you have to a return a list of the first n + 1 numbers of the Tribonacci sequence. tri(3) = [1, 3, 2, 8] """
if n == 0: return [1] my_tri = [1, 3] for i in range(2, n + 1): if i % 2 == 0: my_tri.append(i / 2 + 1) else: my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2) return my_tri
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def digits(n): """Given a positive integer n, return the product of the odd digits. Return 0 if all digits are even. digits(1) == 1 digits(4) == 0 digits(235) == 15 """
product = 1 odd_count = 0 for digit in str(n): int_digit = int(digit) if int_digit%2 == 1: product= product*int_digit odd_count+=1 if odd_count ==0: return 0 else: return product
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum_squares(lst): """You are given a list of numbers. You need to return the sum of squared numbers in the given list, round each element in the list to the upper int(Ceiling) first. For lst = [1,2,3] the output should be 14 For lst = [1,4,9] the output should be 98 For lst = [1,3,5,7] the output should be 84 For lst = [1.4,4.2,0] the output should be 29 For lst = [-2.4,1,1] the output should be 6 """
import math squared = 0 for i in lst: squared += math.ceil(i)**2 return squared
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_arrange(arr): """Create a function which returns the largest index of an element which is not greater than or equal to the element immediately preceding it. If no such element exists then return -1. The given array will not contain duplicate values. can_arrange([1,2,4,3,5]) = 3 can_arrange([1,2,3]) = -1 """
ind=-1 i=1 while i<len(arr): if arr[i]<arr[i-1]: ind=i i+=1 return ind
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_one(a, b): """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. compare_one(1, 2.5) ➞ 2.5 compare_one(1, "2,3") ➞ "2,3" compare_one("5,1", "6") ➞ "6" compare_one("1", 1) ➞ None """
temp_a, temp_b = a, b if isinstance(temp_a, str): temp_a = temp_a.replace(',','.') if isinstance(temp_b, str): temp_b = temp_b.replace(',','.') if float(temp_a) == float(temp_b): return None return a if float(temp_a) > float(temp_b) else b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_equal_to_sum_even(n): """Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example is_equal_to_sum_even(4) == False is_equal_to_sum_even(6) == False is_equal_to_sum_even(8) == True """
return n%2 == 0 and n >= 8
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def special_factorial(n): """ where n > 0 288 The function will receive an integer as input and should return the special factorial of this integer. """
fact_i = 1 special_fact = 1 for i in range(1, n+1): fact_i *= i special_fact *= fact_i return special_fact
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_spaces(text): """ Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all consecutive spaces with - fix_spaces("Example") == "Example" fix_spaces("Example 1") == "Example_1" fix_spaces(" Example 2") == "_Example_2" fix_spaces(" Example 3") == "_Example-3" """
new_text = "" i = 0 start, end = 0, 0 while i < len(text): if text[i] == " ": end += 1 else: if end - start > 2: new_text += "-"+text[i] elif end - start > 0: new_text += "_"*(end - start)+text[i] else: new_text += text[i] start, end = i+1, i+1 i+=1 if end - start > 2: new_text += "-" elif end - start > 0: new_text += "_" return new_text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_name_check(file_name): """Create a function which takes a string representing a file's name, and returns 'Yes' if the the file's name is valid, and returns 'No' otherwise. A file's name is considered to be valid if and only if all the following conditions - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot '.' - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). """
suf = ['txt', 'exe', 'dll'] lst = file_name.split(sep='.') if len(lst) != 2: return 'No' if not lst[1] in suf: return 'No' if len(lst[0]) == 0: return 'No' if not lst[0][0].isalpha(): return 'No' t = len([x for x in lst[0] if x.isdigit()]) if t > 3: return 'No' return 'Yes'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum_squares(lst): """" This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. For lst = [1,2,3] the output should be 6 For lst = [] the output should be 0 For lst = [-1,-5,2,-1,-5] the output should be -126 """
result =[] for i in range(len(lst)): if i %3 == 0: result.append(lst[i]**2) elif i % 4 == 0 and i%3 != 0: result.append(lst[i]**3) else: result.append(lst[i]) return sum(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def words_in_sentence(sentence): """ You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. """
new_lst = [] for word in sentence.split(): flg = 0 if len(word) == 1: flg = 1 for i in range(2, len(word)): if len(word)%i == 0: flg = 1 if flg == 0 or len(word) == 2: new_lst.append(word) return " ".join(new_lst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simplify(x, n): """Your task is to implement a function that will simplify the expression otherwise. Both x and n, are string representation of a fraction, and have the following format, <numerator>/<denominator> where both numerator and denominator are positive whole numbers. You can assume that x, and n are valid fractions, and do not have zero as denominator. simplify("1/5", "5/1") = True simplify("1/6", "2/1") = False simplify("7/10", "10/2") = False """
a, b = x.split("/") c, d = n.split("/") numerator = int(a) * int(c) denom = int(b) * int(d) if (numerator/denom == int(numerator/denom)): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def order_by_points(nums): """ Write a function which sorts the given list of integers in ascending order according to the sum of their digits. order them based on their index in original list. """
def digits_sum(n): neg = 1 if n < 0: n, neg = -1 * n, -1 n = [int(i) for i in str(n)] n[0] = n[0] * neg return sum(n) return sorted(nums, key=digits_sum)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def specialFilter(nums): """Write a function that takes an array of numbers as input and returns the number of elements in the array that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). """
count = 0 for num in nums: if num > 10: odd_digits = (1, 3, 5, 7, 9) number_as_string = str(num) if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in odd_digits: count += 1 return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_max_triples(n): """ You are given a positive integer n. You have to create an integer array a of length n. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """
A = [i*i - i + 1 for i in range(1,n+1)] ans = [] for i in range(n): for j in range(i+1,n): for k in range(j+1,n): if (A[i]+A[j]+A[k])%3 == 0: ans += [(A[i],A[j],A[k])] return len(ans)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sorted_list_sum(lst): """Write a function that accepts a list of strings as a parameter, deletes the strings that have odd lengths from it, and returns the resulted list with a sorted order, The list is always a list of strings and never an array of numbers, and it may contain duplicates. The order of the list should be ascending by length of each word, and you should return the list sorted by that rule. If two words have the same length, sort the list alphabetically. The function should return a list of strings in sorted order. You may assume that all words will have the same length. """
lst.sort() new_lst = [] for i in lst: if len(i)%2 == 0: new_lst.append(i) return sorted(new_lst, key=len)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def x_or_y(n, x, y): """A simple program which should return the value of x if n is a prime number and should return the value of y otherwise. for x_or_y(7, 34, 12) == 34 for x_or_y(15, 8, 5) == 5 """
if n == 1: return y for i in range(2, n): if n % i == 0: return y break else: return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(game,guess): """I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two arrays of scores and guesses of equal length, where each index shows a match. Return an array of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. """
return [abs(x-y) for x,y in zip(game,guess)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Strongest_Extension(class_name, extensions): """You will be given the name of a class (a string) and a list of extensions. The extensions are to be used to load additional classes to the class. The letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this If there are two or more extensions with the same strength, you should choose the one that comes first in the list. For example, if you are given "Slices" as the class and a list of the return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension (its strength is -1). for Strongest_Extension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA' """
strong = extensions[0] my_val = len([x for x in extensions[0] if x.isalpha() and x.isupper()]) - len([x for x in extensions[0] if x.isalpha() and x.islower()]) for s in extensions: val = len([x for x in s if x.isalpha() and x.isupper()]) - len([x for x in s if x.isalpha() and x.islower()]) if val > my_val: strong = s my_val = val ans = class_name + "." + strong return ans
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cycpattern_check(a , b): """You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word """
l = len(b) pat = b + b for i in range(len(a) - l + 1): for j in range(l + 1): if a[i:i+l] == pat[j:j+l]: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def even_odd_count(num): """Given an integer. return a tuple that has the number of even and odd digits respectively. """
even_count = 0 odd_count = 0 for i in str(abs(num)): if int(i)%2==0: even_count +=1 else: odd_count +=1 return (even_count, odd_count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int_to_mini_roman(number): """ Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. """
num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] sym = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"] i = 12 res = '' while number: div = number // num[i] number %= num[i] while div: res += sym[i] div -= 1 i -= 1 return res.lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_max(words): """Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. find_max(["name", "of", "string"]) == "string" find_max(["name", "enam", "game"]) == "enam" find_max(["aaaaaaa", "bb" ,"cc"]) == ""aaaaaaa" """
return sorted(words, key = lambda x: (-len(set(x)), x))[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eat(number, need, remaining): """ You're a hungry rabbit, and you already have eaten a certain number of carrots, but now you need to eat more carrots to complete the day's meals. you should return an array of [ total number of eaten carrots after your meals, the number of carrots left after your meals ] if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. the number of carrots that you have eaten. the number of carrots that you need to eat. the number of remaining carrots thet exist in stock """
if(need <= remaining): return [ number + need , remaining-need ] else: return [ number + remaining , 0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_algebra(operator, operand): """ Given two lists operator, and operand. The first list has basic algebra operations, and the second list is a list of integers. Use the two given lists to build the algebric expression and return the evaluation of this expression. Addition ( + ) Subtraction ( - ) Floor division ( // ) array = [2, 3, 4, 5] The length of operator list is equal to the length of operand list minus one. Operand is a list of of non-negative integers. Operator list has at least one operator, and operand list has at least two operands. """
expression = str(operand[0]) for oprt, oprn in zip(operator, operand[1:]): expression+= oprt + str(oprn) return eval(expression)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(s): """You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c" """
flg = 0 idx = 0 new_str = list(s) for i in s: if i.isalpha(): new_str[idx] = i.swapcase() flg = 1 idx += 1 s = "" for i in new_str: s += i if flg == 0: return s[len(s)::-1] return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_to_md5(text): """ Given a string 'text', return its md5 hash equivalent string. If 'text' is an empty string, return None. """
import hashlib return hashlib.md5(text.encode('ascii')).hexdigest() if text else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_integers(a, b): """ Given two positive integers a and b, return the even digits between a and b, in ascending order. """
lower = max(2, min(a, b)) upper = min(8, max(a, b)) return [i for i in range(lower, upper+1) if i % 2 == 0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __multiscale_gc_lo2hi_run(self): # , pyed): """ Run Graph-Cut segmentation with refinement of low resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties` """
# from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() self._msgc_lo2hi_resize_init() self.__msgc_step0_init() hard_constraints = self.__msgc_step12_low_resolution_segmentation() # ===== high resolution data processing seg = self.__msgc_step3_discontinuity_localization() self.stats["t3.1"] = (time.time() - self._start_time) graph = Graph( seg, voxelsize=self.voxelsize, nsplit=self.segparams["block_size"], edge_weight_table=self._msgc_npenalty_table, compute_low_nodes_index=True, ) # graph.run() = graph.generate_base_grid() + graph.split_voxels() # graph.run() graph.generate_base_grid() self.stats["t3.2"] = (time.time() - self._start_time) graph.split_voxels() self.stats["t3.3"] = (time.time() - self._start_time) self.stats.update(graph.stats) self.stats["t4"] = (time.time() - self._start_time) mul_mask, mul_val = self.__msgc_tlinks_area_weight_from_low_segmentation(seg) area_weight = 1 unariesalt = self.__create_tlinks( self.img, self.voxelsize, self.seeds, area_weight=area_weight, hard_constraints=hard_constraints, mul_mask=None, mul_val=None, ) # N-links prepared self.stats["t5"] = (time.time() - self._start_time) un, ind = np.unique(graph.msinds, return_index=True) self.stats["t6"] = (time.time() - self._start_time) self.stats["t7"] = (time.time() - self._start_time) unariesalt2_lo2hi = np.hstack( [unariesalt[ind, 0, 0].reshape(-1, 1), unariesalt[ind, 0, 1].reshape(-1, 1)] ) nlinks_lo2hi = np.hstack([graph.edges, graph.edges_weights.reshape(-1, 1)]) if self.debug_images: import sed3 ed = sed3.sed3(unariesalt[:, :, 0].reshape(self.img.shape)) ed.show() import sed3 ed = sed3.sed3(unariesalt[:, :, 1].reshape(self.img.shape)) ed.show() # ed = sed3.sed3(seg) # ed.show() # import sed3 # ed = sed3.sed3(graph.data) # ed.show() # import sed3 # ed = sed3.sed3(graph.msinds) # ed.show() # nlinks, unariesalt2, msinds = self.__msgc_step45678_construct_graph(area_weight, hard_constraints, seg) # self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds) self.__msgc_step9_finish_perform_gc_and_reshape( nlinks_lo2hi, unariesalt2_lo2hi, graph.msinds ) self._msgc_lo2hi_resize_clean_finish()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __multiscale_gc_hi2lo_run(self): # , pyed): """ Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties` """
# from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() self.__msgc_step0_init() hard_constraints = self.__msgc_step12_low_resolution_segmentation() # ===== high resolution data processing seg = self.__msgc_step3_discontinuity_localization() nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construct_graph( hard_constraints, seg ) self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __hi2lo_multiscale_indexes(self, mask, orig_shape): # , zoom): """ Function computes multiscale indexes of ndarray. mask: Says where is original resolution (0) and where is small resolution (1). Mask is in small resolution. orig_shape: Original shape of input data. zoom: Usually number greater then 1 result = [[0 1 2], [3 4 4], [5 4 4]] """
mask_orig = zoom_to_shape(mask, orig_shape, dtype=np.int8) inds_small = np.arange(mask.size).reshape(mask.shape) inds_small_in_orig = zoom_to_shape(inds_small, orig_shape, dtype=np.int8) inds_orig = np.arange(np.prod(orig_shape)).reshape(orig_shape) # inds_orig = inds_orig * mask_orig inds_orig += np.max(inds_small_in_orig) + 1 # print 'indexes' # import py3DSeedEditor as ped # import pdb; pdb.set_trace() # BREAKPOINT # '==' is not the same as 'is' for numpy.array inds_small_in_orig[mask_orig == True] = inds_orig[mask_orig == True] # noqa inds = inds_small_in_orig # print np.max(inds) # print np.min(inds) inds = relabel_squeeze(inds) logger.debug( "Index after relabeling: %s", scipy.stats.describe(inds, axis=None) ) # logger.debug("Minimal index after relabeling: " + str(np.min(inds))) # inds_orig[mask_orig==True] = 0 # inds_small_in_orig[mask_orig==False] = 0 # inds = (inds_orig + np.max(inds_small_in_orig) + 1) + inds_small_in_orig return inds, mask_orig
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interactivity(self, min_val=None, max_val=None, qt_app=None): """ Interactive seed setting with 3d seed editor """
from .seed_editor_qt import QTSeedEditor from PyQt4.QtGui import QApplication if min_val is None: min_val = np.min(self.img) if max_val is None: max_val = np.max(self.img) window_c = (max_val + min_val) / 2 # .astype(np.int16) window_w = max_val - min_val # .astype(np.int16) if qt_app is None: qt_app = QApplication(sys.argv) pyed = QTSeedEditor( self.img, modeFun=self.interactivity_loop, voxelSize=self.voxelsize, seeds=self.seeds, volume_unit=self.volume_unit, ) pyed.changeC(window_c) pyed.changeW(window_w) qt_app.exec_()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, run_fit_model=True): """ Run the Graph Cut segmentation according to preset parameters. :param run_fit_model: Allow to skip model fit when the model is prepared before :return: """
if run_fit_model: self.fit_model(self.img, self.voxelsize, self.seeds) self._start_time = time.time() if self.segparams["method"].lower() in ("graphcut", "gc"): self.__single_scale_gc_run() elif self.segparams["method"].lower() in ( "multiscale_graphcut", "multiscale_gc", "msgc", "msgc_lo2hi", "lo2hi", "multiscale_graphcut_lo2hi", ): logger.debug("performing multiscale Graph-Cut lo2hi") self.__multiscale_gc_lo2hi_run() elif self.segparams["method"].lower() in ( "msgc_hi2lo", "hi2lo", "multiscale_graphcut_hi2lo", ): logger.debug("performing multiscale Graph-Cut hi2lo") self.__multiscale_gc_hi2lo_run() else: logger.error("Unknown segmentation method: " + self.segparams["method"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __similarity_for_tlinks_obj_bgr( self, data, voxelsize, # voxels1, voxels2, # seeds, otherfeatures=None ): """ Compute edge values for graph cut tlinks based on image intensity and texture. """
# self.fit_model(data, voxelsize, seeds) # There is a need to have small vaues for good fit # R(obj) = -ln( Pr (Ip | O) ) # R(bck) = -ln( Pr (Ip | B) ) # Boykov2001b # ln is computed in likelihood tdata1 = (-(self.mdl.likelihood_from_image(data, voxelsize, 1))) * 10 tdata2 = (-(self.mdl.likelihood_from_image(data, voxelsize, 2))) * 10 # to spare some memory dtype = np.int16 if np.any(tdata1 > 32760): dtype = np.float32 if np.any(tdata2 > 32760): dtype = np.float32 if self.segparams["use_apriori_if_available"] and self.apriori is not None: logger.debug("using apriori information") gamma = self.segparams["apriori_gamma"] a1 = (-np.log(self.apriori * 0.998 + 0.001)) * 10 a2 = (-np.log(0.999 - (self.apriori * 0.998))) * 10 # logger.debug('max ' + str(np.max(tdata1)) + ' min ' + str(np.min(tdata1))) # logger.debug('max ' + str(np.max(tdata2)) + ' min ' + str(np.min(tdata2))) # logger.debug('max ' + str(np.max(a1)) + ' min ' + str(np.min(a1))) # logger.debug('max ' + str(np.max(a2)) + ' min ' + str(np.min(a2))) tdata1u = (((1 - gamma) * tdata1) + (gamma * a1)).astype(dtype) tdata2u = (((1 - gamma) * tdata2) + (gamma * a2)).astype(dtype) tdata1 = tdata1u tdata2 = tdata2u # logger.debug(' max ' + str(np.max(tdata1)) + ' min ' + str(np.min(tdata1))) # logger.debug(' max ' + str(np.max(tdata2)) + ' min ' + str(np.min(tdata2))) # logger.debug('gamma ' + str(gamma)) # import sed3 # ed = sed3.show_slices(tdata1) # ed = sed3.show_slices(tdata2) del tdata1u del tdata2u del a1 del a2 # if np.any(tdata1 < 0) or np.any(tdata2 <0): # logger.error("Problem with tlinks. Likelihood is < 0") # if self.debug_images: # self.__show_debug_tdata_images(tdata1, tdata2, suptitle="likelihood") return tdata1, tdata2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ssgc_prepare_data_and_run_computation( self, # voxels1, voxels2, hard_constraints=True, area_weight=1, ): """ Setting of data. You need set seeds if you want use hard_constraints. """
# from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() # import pdb; pdb.set_trace() # BREAKPOINT unariesalt = self.__create_tlinks( self.img, self.voxelsize, # voxels1, voxels2, self.seeds, area_weight, hard_constraints, ) # některém testu organ semgmentation dosahují unaries -15. což je podiné # stačí vyhodit print před if a je to vidět logger.debug("unaries %.3g , %.3g" % (np.max(unariesalt), np.min(unariesalt))) # create potts pairwise # pairwiseAlpha = -10 pairwise = -(np.eye(2) - 1) pairwise = (self.segparams["pairwise_alpha"] * pairwise).astype(np.int32) # pairwise = np.array([[0,30],[30,0]]).astype(np.int32) # print pairwise self.iparams = {} if self.segparams["use_boundary_penalties"]: sigma = self.segparams["boundary_penalties_sigma"] # set boundary penalties function # Default are penalties based on intensity differences boundary_penalties_fcn = lambda ax: self._boundary_penalties_array( axis=ax, sigma=sigma ) else: boundary_penalties_fcn = None nlinks = self.__create_nlinks( self.img, boundary_penalties_fcn=boundary_penalties_fcn ) self.stats["tlinks shape"].append(unariesalt.reshape(-1, 2).shape) self.stats["nlinks shape"].append(nlinks.shape) # we flatten the unaries # result_graph = cut_from_graph(nlinks, unaries.reshape(-1, 2), # pairwise) start = time.time() if self.debug_images: self._debug_show_unariesalt(unariesalt) result_graph = pygco.cut_from_graph(nlinks, unariesalt.reshape(-1, 2), pairwise) elapsed = time.time() - start self.stats["gc time"] = elapsed result_labeling = result_graph.reshape(self.img.shape) return result_labeling
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seed_zoom(seeds, zoom): """ Smart zoom for sparse matrix. If there is resize to bigger resolution thin line of label could be lost. This function prefers labels larger then zero. If there is only one small voxel in larger volume with zeros it is selected. """
# import scipy # loseeds=seeds labels = np.unique(seeds) # remove first label - 0 labels = np.delete(labels, 0) # @TODO smart interpolation for seeds in one block # loseeds = scipy.ndimage.interpolation.zoom( # seeds, zoom, order=0) loshape = np.ceil(np.array(seeds.shape) * 1.0 / zoom).astype(np.int) loseeds = np.zeros(loshape, dtype=np.int8) loseeds = loseeds.astype(np.int8) for label in labels: a, b, c = np.where(seeds == label) loa = np.round(a // zoom) lob = np.round(b // zoom) loc = np.round(c // zoom) # loseeds = np.zeros(loshape) loseeds[loa, lob, loc] += label # this is to detect conflict seeds loseeds[loseeds > label] = 100 # remove conflict seeds loseeds[loseeds > 99] = 0 # import py3DSeedEditor # ped = py3DSeedEditor.py3DSeedEditor(loseeds) # ped.show() return loseeds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zoom_to_shape(data, shape, dtype=None): """ Zoom data to specific shape. """
import scipy import scipy.ndimage zoomd = np.array(shape) / np.array(data.shape, dtype=np.double) import warnings datares = scipy.ndimage.interpolation.zoom(data, zoomd, order=0, mode="reflect") if datares.shape != shape: logger.warning("Zoom with different output shape") dataout = np.zeros(shape, dtype=dtype) shpmin = np.minimum(dataout.shape, shape) dataout[: shpmin[0], : shpmin[1], : shpmin[2]] = datares[ : shpmin[0], : shpmin[1], : shpmin[2] ] return datares
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crop(data, crinfo): """ Crop the data. crop(data, crinfo) :param crinfo: min and max for each axis - [[minX, maxX], [minY, maxY], [minZ, maxZ]] """
crinfo = fix_crinfo(crinfo) return data[ __int_or_none(crinfo[0][0]) : __int_or_none(crinfo[0][1]), __int_or_none(crinfo[1][0]) : __int_or_none(crinfo[1][1]), __int_or_none(crinfo[2][0]) : __int_or_none(crinfo[2][1]), ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combinecrinfo(crinfo1, crinfo2): """ Combine two crinfos. First used is crinfo1, second used is crinfo2. """
crinfo1 = fix_crinfo(crinfo1) crinfo2 = fix_crinfo(crinfo2) crinfo = [ [crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]], [crinfo1[1][0] + crinfo2[1][0], crinfo1[1][0] + crinfo2[1][1]], [crinfo1[2][0] + crinfo2[2][0], crinfo1[2][0] + crinfo2[2][1]], ] return crinfo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crinfo_from_specific_data(data, margin=0): """ Create crinfo of minimum orthogonal nonzero block in input data. :param data: input data :param margin: add margin to minimum block :return: """
# hledáme automatický ořez, nonzero dá indexy logger.debug("crinfo") logger.debug(str(margin)) nzi = np.nonzero(data) logger.debug(str(nzi)) if np.isscalar(margin): margin = [margin] * 3 x1 = np.min(nzi[0]) - margin[0] x2 = np.max(nzi[0]) + margin[0] + 1 y1 = np.min(nzi[1]) - margin[0] y2 = np.max(nzi[1]) + margin[0] + 1 z1 = np.min(nzi[2]) - margin[0] z2 = np.max(nzi[2]) + margin[0] + 1 # ošetření mezí polí if x1 < 0: x1 = 0 if y1 < 0: y1 = 0 if z1 < 0: z1 = 0 if x2 > data.shape[0]: x2 = data.shape[0] - 1 if y2 > data.shape[1]: y2 = data.shape[1] - 1 if z2 > data.shape[2]: z2 = data.shape[2] - 1 # ořez crinfo = [[x1, x2], [y1, y2], [z1, z2]] return crinfo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0): """ Put some boundary to input image. :param data: input data :param crinfo: array with minimum and maximum index along each axis [[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input image is placed into [0, 0, 0]. If crinfo is just series of three numbers, it is used as an initial point for input image placement. :param orig_shape: shape of uncropped image :param resize: True or False (default). Usefull if the data.shape does not fit to crinfo shape. :param outside_mode: 'constant', 'nearest' :return: """
if crinfo is None: crinfo = list(zip([0] * data.ndim, orig_shape)) elif np.asarray(crinfo).size == data.ndim: crinfo = list(zip(crinfo, np.asarray(crinfo) + data.shape)) crinfo = fix_crinfo(crinfo) data_out = np.ones(orig_shape, dtype=data.dtype) * cval # print 'uncrop ', crinfo # print orig_shape # print data.shape if resize: data = resize_to_shape(data, crinfo[:, 1] - crinfo[:, 0]) startx = np.round(crinfo[0][0]).astype(int) starty = np.round(crinfo[1][0]).astype(int) startz = np.round(crinfo[2][0]).astype(int) data_out[ # np.round(crinfo[0][0]).astype(int):np.round(crinfo[0][1]).astype(int)+1, # np.round(crinfo[1][0]).astype(int):np.round(crinfo[1][1]).astype(int)+1, # np.round(crinfo[2][0]).astype(int):np.round(crinfo[2][1]).astype(int)+1 startx : startx + data.shape[0], starty : starty + data.shape[1], startz : startz + data.shape[2], ] = data if outside_mode == "nearest": # for ax in range(data.ndims): # ax = 0 # copy border slice to pixels out of boundary - the higher part for ax in range(data.ndim): # the part under the crop start = np.round(crinfo[ax][0]).astype(int) slices = [slice(None), slice(None), slice(None)] slices[ax] = start repeated_slice = np.expand_dims(data_out[slices], ax) append_sz = start if append_sz > 0: tile0 = np.repeat(repeated_slice, append_sz, axis=ax) slices = [slice(None), slice(None), slice(None)] slices[ax] = slice(None, start) # data_out[start + data.shape[ax] : , :, :] = tile0 data_out[slices] = tile0 # plt.imshow(np.squeeze(repeated_slice)) # plt.show() # the part over the crop start = np.round(crinfo[ax][0]).astype(int) slices = [slice(None), slice(None), slice(None)] slices[ax] = start + data.shape[ax] - 1 repeated_slice = np.expand_dims(data_out[slices], ax) append_sz = data_out.shape[ax] - (start + data.shape[ax]) if append_sz > 0: tile0 = np.repeat(repeated_slice, append_sz, axis=ax) slices = [slice(None), slice(None), slice(None)] slices[ax] = slice(start + data.shape[ax], None) # data_out[start + data.shape[ax] : , :, :] = tile0 data_out[slices] = tile0 # plt.imshow(np.squeeze(repeated_slice)) # plt.show() return data_out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_crinfo(crinfo, to="axis"): """ Function recognize order of crinfo and convert it to proper format. """
crinfo = np.asarray(crinfo) if crinfo.shape[0] == 2: crinfo = crinfo.T return crinfo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_grid_2d(shape, voxelsize): """ Generate list of edges for a base grid. """
nr, nc = shape nrm1, ncm1 = nr - 1, nc - 1 # sh = nm.asarray(shape) # calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols) nedges = 0 for direction in range(len(shape)): sh = copy.copy(list(shape)) sh[direction] += -1 nedges += nm.prod(sh) nedges_old = ncm1 * nr + nrm1 * nc edges = nm.zeros((nedges, 2), dtype=nm.int16) edge_dir = nm.zeros((ncm1 * nr + nrm1 * nc,), dtype=nm.bool) nodes = nm.zeros((nm.prod(shape), 3), dtype=nm.float32) # edges idx = 0 row = nm.zeros((ncm1, 2), dtype=nm.int16) row[:, 0] = nm.arange(ncm1) row[:, 1] = nm.arange(ncm1) + 1 for ii in range(nr): edges[slice(idx, idx + ncm1), :] = row + nc * ii idx += ncm1 edge_dir[slice(0, idx)] = 0 # horizontal dir idx0 = idx col = nm.zeros((nrm1, 2), dtype=nm.int16) col[:, 0] = nm.arange(nrm1) * nc col[:, 1] = nm.arange(nrm1) * nc + nc for ii in range(nc): edges[slice(idx, idx + nrm1), :] = col + ii idx += nrm1 edge_dir[slice(idx0, idx)] = 1 # vertical dir # nodes idx = 0 row = nm.zeros((nc, 3), dtype=nm.float32) row[:, 0] = voxelsize[0] * (nm.arange(nc) + 0.5) row[:, 1] = voxelsize[1] * 0.5 for ii in range(nr): nodes[slice(idx, idx + nc), :] = row row[:, 1] += voxelsize[1] idx += nc return nodes, edges, edge_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_nodes(self, coors, node_low_or_high=None): """ Add new nodes at the end of the list. """
last = self.lastnode if type(coors) is nm.ndarray: if len(coors.shape) == 1: coors = coors.reshape((1, coors.size)) nadd = coors.shape[0] idx = slice(last, last + nadd) else: nadd = 1 idx = self.lastnode right_dimension = coors.shape[1] self.nodes[idx, :right_dimension] = coors self.node_flag[idx] = True self.lastnode += nadd self.nnodes += nadd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mul_block(self, index, val): """Multiply values in block"""
self._prepare_cache_slice(index) self.msinds[self.cache_slice] *= val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_fv_by_seeds(fv, seeds=None, unique_cls=None): """ Return features selected by seeds and unique_cls or selection from features and corresponding seed classes. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :param seeds: ndarray with seeds. Does not to be linear. :param unique_cls: number of used seeds clases. Like [1, 2] :return: fv, sd - selection from feature vector and selection from seeds or just fv for whole image """
if seeds is not None: if unique_cls is not None: return select_from_fv_by_seeds(fv, seeds, unique_cls) else: raise AssertionError("Input unique_cls has to be not None if seeds is not None.") else: return fv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, expression): """Expands logical constructions."""
self.logger.debug("expand : expression %s", str(expression)) if not is_string(expression): return expression result = self._pattern.sub(lambda var: str(self._variables[var.group(1)]), expression) result = result.strip() self.logger.debug('expand : %s - result : %s', expression, result) if is_number(result): if result.isdigit(): self.logger.debug(' expand is integer !!!') return int(result) else: self.logger.debug(' expand is float !!!') return float(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_gutter_client( alias='default', cache=CLIENT_CACHE, **kwargs ): """ Creates gutter clients and memoizes them in a registry for future quick access. Args: alias (str or None): Name of the client. Used for caching. If name is falsy then do not use the cache. cache (dict): cache to store gutter managers in. **kwargs: kwargs to be passed the Manger class. Returns (Manager): A gutter client. """
from gutter.client.models import Manager if not alias: return Manager(**kwargs) elif alias not in cache: cache[alias] = Manager(**kwargs) return cache[alias]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _modulo(self, decimal_argument): """ The mod operator is prone to floating point errors, so use decimal. 101.1 % 100 decimal_context.divmod(Decimal('100.1'), 100) """
_times, remainder = self._context.divmod(decimal_argument, 100) # match the builtin % behavior by adding the N to the result if negative return remainder if remainder >= 0 else remainder + 100
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enabled_for(self, inpt): """ Checks to see if this switch is enabled for the provided input. If ``compounded``, all switch conditions must be ``True`` for the switch to be enabled. Otherwise, *any* condition needs to be ``True`` for the switch to be enabled. The switch state is then checked to see if it is ``GLOBAL`` or ``DISABLED``. If it is not, then the switch is ``SELECTIVE`` and each condition is checked. Keyword Arguments: inpt -- An instance of the ``Input`` class. """
signals.switch_checked.call(self) signal_decorated = partial(self.__signal_and_return, inpt) if self.state is self.states.GLOBAL: return signal_decorated(True) elif self.state is self.states.DISABLED: return signal_decorated(False) conditions_dict = ConditionsDict.from_conditions_list(self.conditions) conditions = conditions_dict.get_by_input(inpt) if conditions: result = self.__enabled_func( cond.call(inpt) for cond in conditions if cond.argument(inpt).applies ) else: result = None return signal_decorated(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, inpt): """ Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ``argument``, then ``False`` is returned. This also applies to the ``NONE`` input. Otherwise, ``argument`` is called, with ``inpt`` as the instance and the value is compared to the ``operator`` and the Value is returned. If the condition is ``negative``, then then ``not`` the value is returned. Keyword Arguments: inpt -- An instance of the ``Input`` class. """
if inpt is Manager.NONE_INPUT: return False # Call (construct) the argument with the input object argument_instance = self.argument(inpt) if not argument_instance.applies: return False application = self.__apply(argument_instance, inpt) if self.negative: application = not application return application
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switches(self): """ List of all switches currently registered. """
results = [ switch for name, switch in self.storage.iteritems() if name.startswith(self.__joined_namespace) ] return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch(self, name): """ Returns the switch with the provided ``name``. If ``autocreate`` is set to ``True`` and no switch with that name exists, a ``DISABLED`` switch will be with that name. Keyword Arguments: name -- A name of a switch. """
try: switch = self.storage[self.__namespaced(name)] except KeyError: if not self.autocreate: raise ValueError("No switch named '%s' registered in '%s'" % (name, self.namespace)) switch = self.__create_and_register_disabled_switch(name) switch.manager = self return switch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def register(self, switch, signal=signals.switch_registered): ''' Register a switch and persist it to the storage. ''' if not switch.name: raise ValueError('Switch name cannot be blank') switch.manager = self self.__persist(switch) signal.call(switch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(obj, times=1, atleast=None, atmost=None, between=None, inorder=False): """Central interface to verify interactions. `verify` uses a fluent interface:: verify(<obj>, times=2).<method_name>(<args>) `args` can be as concrete as necessary. Often a catch-all is enough, especially if you're working with strict mocks, bc they throw at call time on unwanted, unconfigured arguments:: from mockito import ANY, ARGS, KWARGS when(manager).add_tasks(1, 2, 3) # no need to duplicate the specification; every other argument pattern # would have raised anyway. verify(manager).add_tasks(1, 2, 3) # duplicates `when`call verify(manager).add_tasks(*ARGS) verify(manager).add_tasks(Ellipsis) # Py2 """
if isinstance(obj, str): obj = get_obj(obj) verification_fn = _get_wanted_verification( times=times, atleast=atleast, atmost=atmost, between=between) if inorder: verification_fn = verification.InOrder(verification_fn) # FIXME?: Catch error if obj is neither a Mock nor a known stubbed obj theMock = _get_mock_or_raise(obj) class Verify(object): def __getattr__(self, method_name): return invocation.VerifiableInvocation( theMock, method_name, verification_fn) return Verify()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def when(obj, strict=None): """Central interface to stub functions on a given `obj` `obj` should be a module, a class or an instance of a class; it can be a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface where you configure a stub in three steps:: when(<obj>).<method_name>(<args>).thenReturn(<value>) Compared to simple *patching*, stubbing in mockito requires you to specify conrete `args` for which the stub will answer with a concrete `<value>`. All invocations that do not match this specific call signature will be rejected. They usually throw at call time. Stubbing in mockito's sense thus means not only to get rid of unwanted side effects, but effectively to turn function calls into constants. E.g.:: # Given ``dog`` is an instance of a ``Dog`` when(dog).bark('Grrr').thenReturn('Wuff') when(dog).bark('Miau').thenRaise(TypeError()) # With this configuration set up: assert dog.bark('Grrr') == 'Wuff' dog.bark('Miau') # will throw TypeError dog.bark('Wuff') # will throw unwanted interaction Stubbing can effectively be used as monkeypatching; usage shown with the `with` context managing:: with when(os.path).exists('/foo').thenReturn(True): Most of the time verifying your interactions is not necessary, because your code under tests implicitly verifies the return value by evaluating it. See :func:`verify` if you need to, see also :func:`expect` to setup expected call counts up front. If your function is pure side effect and does not return something, you can omit the specific answer. The default then is `None`:: when(manager).do_work() `when` verifies the method name, the expected argument signature, and the actual, factual arguments your code under test uses against the original object and its function so its easier to spot changing interfaces. Sometimes it's tedious to spell out all arguments:: from mockito import ANY, ARGS, KWARGS when(os.path).exists(ANY) when(os.path).exists(ANY(str)) .. note:: You must :func:`unstub` after stubbing, or use `with` statement. Set ``strict=False`` to bypass the function signature checks. See related :func:`when2` which has a more pythonic interface. """
if isinstance(obj, str): obj = get_obj(obj) if strict is None: strict = True theMock = _get_mock(obj, strict=strict) class When(object): def __getattr__(self, method_name): return invocation.StubbedInvocation( theMock, method_name, strict=strict) return When()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def when2(fn, *args, **kwargs): """Stub a function call with the given arguments Exposes a more pythonic interface than :func:`when`. See :func:`when` for more documentation. Returns `AnswerSelector` interface which exposes `thenReturn`, `thenRaise`, and `thenAnswer` as usual. Always `strict`. Usage:: # Given `dog` is an instance of a `Dog` when2(dog.bark, 'Miau').thenReturn('Wuff') .. note:: You must :func:`unstub` after stubbing, or use `with` statement. """
obj, name = get_obj_attr_tuple(fn) theMock = _get_mock(obj, strict=True) return invocation.StubbedInvocation(theMock, name)(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expect(obj, strict=None, times=None, atleast=None, atmost=None, between=None): """Stub a function call, and set up an expected call count. Usage:: # Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') dog.bark('Wuff') # will throw at call time: too many invocations # maybe if you need to ensure that `dog.bark()` was called at all verifyNoUnwantedInteractions() .. note:: You must :func:`unstub` after stubbing, or use `with` statement. See :func:`when`, :func:`when2`, :func:`verifyNoUnwantedInteractions` """
if strict is None: strict = True theMock = _get_mock(obj, strict=strict) verification_fn = _get_wanted_verification( times=times, atleast=atleast, atmost=atmost, between=between) class Expect(object): def __getattr__(self, method_name): return invocation.StubbedInvocation( theMock, method_name, verification=verification_fn, strict=strict) return Expect()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unstub(*objs): """Unstubs all stubbed methods and functions If you don't pass in any argument, *all* registered mocks and patched modules, classes etc. will be unstubbed. Note that additionally, the underlying registry will be cleaned. After an `unstub` you can't :func:`verify` anymore because all interactions will be forgotten. """
if objs: for obj in objs: mock_registry.unstub(obj) else: mock_registry.unstub_all()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verifyZeroInteractions(*objs): """Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks ('monkeypatched' objects or modules) do not support this functionality at all, bc only for the stubbed invocations the actual usage gets recorded. So this function is of limited use, nowadays. """
for obj in objs: theMock = _get_mock_or_raise(obj) if len(theMock.invocations) > 0: raise VerificationError( "\nUnwanted interaction: %s" % theMock.invocations[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verifyNoUnwantedInteractions(*objs): """Verifies that expectations set via `expect` are met E.g.:: os.path('/foo') verifyNoUnwantedInteractions(os.path) # ok, called once If you leave out the argument *all* registered objects will be checked. .. note:: **DANGERZONE**: If you did not :func:`unstub` correctly, it is possible that old registered mocks, from other tests leak. See related :func:`expect` """
if objs: theMocks = map(_get_mock_or_raise, objs) else: theMocks = mock_registry.get_registered_mocks() for mock in theMocks: for i in mock.stubbed_invocations: i.verify()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verifyStubbedInvocationsAreUsed(*objs): """Ensure stubs are actually used. This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changes after refactorings. It is meant to be invoked usually without arguments just before :func:`unstub`. """
if objs: theMocks = map(_get_mock_or_raise, objs) else: theMocks = mock_registry.get_registered_mocks() for mock in theMocks: for i in mock.stubbed_invocations: if not i.allow_zero_invocations and i.used < len(i.answers): raise VerificationError("\nUnused stub: %s" % i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_function_host(fn): """Destructure a given function into its host and its name. The 'host' of a function is a module, for methods it is usually its instance or its class. This is safe only for methods, for module wide, globally declared names it must be considered experimental. For all reasonable fn: ``getattr(*get_function_host(fn)) == fn`` Returns tuple (host, fn-name) Otherwise should raise TypeError """
obj = None try: name = fn.__name__ obj = fn.__self__ except AttributeError: pass if obj is None: # Due to how python imports work, everything that is global on a module # level must be regarded as not safe here. For now, we go for the extra # mile, TBC, because just specifying `os.path.exists` would be 'cool'. # # TLDR;: # E.g. `inspect.getmodule(os.path.exists)` returns `genericpath` bc # that's where `exists` is defined and comes from. But from the point # of view of the user `exists` always comes and is used from `os.path` # which points e.g. to `ntpath`. We thus must patch `ntpath`. # But that's the same for most imports:: # # # b.py # from a import foo # # Now asking `getmodule(b.foo)` it tells you `a`, but we access and use # `b.foo` and we therefore must patch `b`. obj, name = find_invoking_frame_and_try_parse() # safety check! assert getattr(obj, name) == fn return obj, name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_obj(path): """Return obj for given dotted path. Typical inputs for `path` are 'os' or 'os.path' in which case you get a module; or 'os.path.exists' in which case you get a function from that module. Just returns the given input in case it is not a str. Note: Relative imports not supported. Raises ImportError or AttributeError as appropriate. """
# Since we usually pass in mocks here; duck typing is not appropriate # (mocks respond to every attribute). if not isinstance(path, str): return path if path.startswith('.'): raise TypeError('relative imports are not supported') parts = path.split('.') head, tail = parts[0], parts[1:] obj = importlib.import_module(head) # Normally a simple reduce, but we go the extra mile # for good exception messages. for i, name in enumerate(tail): try: obj = getattr(obj, name) except AttributeError: # Note the [:i] instead of [:i+1], so we get the path just # *before* the AttributeError, t.i. the part of it that went ok. module = '.'.join([head] + tail[:i]) try: importlib.import_module(module) except ImportError: raise AttributeError( "object '%s' has no attribute '%s'" % (module, name)) else: raise AttributeError( "module '%s' has no attribute '%s'" % (module, name)) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spy(object): """Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under test; after that all interactions can be verified as usual. T.i. the original object **will not be patched**, and has no further knowledge as before. E.g.:: import time time = spy(time) # inject time verify(time).time() """
if inspect.isclass(object) or inspect.ismodule(object): class_ = None else: class_ = object.__class__ class Spy(_Dummy): if class_: __class__ = class_ def __getattr__(self, method_name): return RememberedProxyInvocation(theMock, method_name) def __repr__(self): name = 'Spied' if class_: name += class_.__name__ return "<%s id=%s>" % (name, id(self)) obj = Spy() theMock = Mock(obj, strict=True, spec=object) mock_registry.register(obj, theMock) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """Spy usage of given `fn`. Patches the module, class or object `fn` lives in, so that all interactions can be recorded; otherwise executes `fn` as before, so that all side effects happen as before. E.g.:: import time spy(time.time) verify(time).time() Note that builtins often cannot be patched because they're read-only. """
if isinstance(fn, str): answer = get_obj(fn) else: answer = fn when2(fn, Ellipsis).thenAnswer(answer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def importPuppetClasses(self, smartProxyId): """ Function importPuppetClasses Force the reload of puppet classes @param smartProxyId: smartProxy Id @return RETURN: the API result """
return self.api.create('{}/{}/import_puppetclasses' .format(self.objName, smartProxyId), '{}')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_templates(model): """ Return a list of templates usable by a model. """
for template_name, template in templates.items(): if issubclass(template.model, model): yield (template_name, template.layout._meta.verbose_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_api_envs(): """Get required API keys from environment variables."""
client_id = os.environ.get('CLIENT_ID') user_id = os.environ.get('USER_ID') if not client_id or not user_id: raise ValueError('API keys are not found in the environment') return client_id, user_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkAndCreate(self, key, payload, domainId): """ Function checkAndCreate Check if a subnet exists and create it if not @param key: The targeted subnet @param payload: The targeted subnet description @param domainId: The domainId to be attached wiuth the subnet @return RETURN: The id of the subnet """
if key not in self: self[key] = payload oid = self[key]['id'] if not oid: return False #~ Ensure subnet contains the domain subnetDomainIds = [] for domain in self[key]['domains']: subnetDomainIds.append(domain['id']) if domainId not in subnetDomainIds: subnetDomainIds.append(domainId) self[key]["domain_ids"] = subnetDomainIds if len(self[key]["domains"]) is not len(subnetDomainIds): return False return oid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeDomain(self, subnetId, domainId): """ Function removeDomain Delete a domain from a subnet @param subnetId: The subnet Id @param domainId: The domainId to be attached wiuth the subnet @return RETURN: boolean """
subnetDomainIds = [] for domain in self[subnetId]['domains']: subnetDomainIds.append(domain['id']) subnetDomainIds.remove(domainId) self[subnetId]["domain_ids"] = subnetDomainIds return len(self[subnetId]["domains"]) is len(subnetDomainIds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exclusive(via=threading.Lock): """ Mark a callable as exclusive :param via: factory for a Lock to guard the callable Guards the callable against being entered again before completion. Explicitly raises a :py:exc:`RuntimeError` on violation. :note: If applied to a method, it is exclusive across all instances. """
def make_exclusive(fnc): fnc_guard = via() @functools.wraps(fnc) def exclusive_call(*args, **kwargs): if fnc_guard.acquire(blocking=False): try: return fnc(*args, **kwargs) finally: fnc_guard.release() else: raise RuntimeError('exclusive call to %s violated') return exclusive_call return make_exclusive
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def service(flavour): r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless * the Service has been garbage collected, or * the ServiceUnit has been :py:meth:`~.ServiceUnit.cancel`\ ed. For each service instance, its :py:class:`~.ServiceUnit` is available at ``service_instance.__service_unit__``. """
def service_unit_decorator(raw_cls): __new__ = raw_cls.__new__ def __new_service__(cls, *args, **kwargs): if __new__ is object.__new__: self = __new__(cls) else: self = __new__(cls, *args, **kwargs) service_unit = ServiceUnit(self, flavour) self.__service_unit__ = service_unit return self raw_cls.__new__ = __new_service__ if raw_cls.run.__doc__ is None: raw_cls.run.__doc__ = "Service entry point" return raw_cls return service_unit_decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, payload, *args, flavour: ModuleType, **kwargs): """ Synchronously run ``payload`` and provide its output If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. """
if args or kwargs: payload = functools.partial(payload, *args, **kwargs) return self._meta_runner.run_payload(payload, flavour=flavour)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adopt(self, payload, *args, flavour: ModuleType, **kwargs): """ Concurrently run ``payload`` in the background If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. """
if args or kwargs: payload = functools.partial(payload, *args, **kwargs) self._meta_runner.register_payload(payload, flavour=flavour)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self): """ Start accepting synchronous, asynchronous and service payloads Since services are globally defined, only one :py:class:`ServiceRunner` may :py:meth:`accept` payloads at any time. """
if self._meta_runner: raise RuntimeError('payloads scheduled for %s before being started' % self) self._must_shutdown = False self._logger.info('%s starting', self.__class__.__name__) # force collecting objects so that defunct, migrated and overwritten services are destroyed now gc.collect() self._adopt_services() self.adopt(self._accept_services, flavour=trio) self._meta_runner.run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shutdown(self): """Shutdown the accept loop and stop running payloads"""
self._must_shutdown = True self._is_shutdown.wait() self._meta_runner.stop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def start_console(local_vars={}): '''Starts a console; modified from code.interact''' transforms.CONSOLE_ACTIVE = True transforms.remove_not_allowed_in_console() sys.ps1 = prompt console = ExperimentalInteractiveConsole(locals=local_vars) console.interact(banner=banner)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, line): """Transform and push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()). """
if transforms.FROM_EXPERIMENTAL.match(line): transforms.add_transformers(line) self.buffer.append("\n") else: self.buffer.append(line) add_pass = False if line.rstrip(' ').endswith(":"): add_pass = True source = "\n".join(self.buffer) if add_pass: source += "pass" source = transforms.transform(source) if add_pass: source = source.rstrip(' ') if source.endswith("pass"): source = source[:-4] # some transformations may strip an empty line meant to end a block if not self.buffer[-1]: source += "\n" try: more = self.runsource(source, self.filename) except SystemExit: os._exit(1) if not more: self.resetbuffer() return more
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(obj, f, preserve=False): """Write dict object into file :param obj: the object to be dumped into toml :param f: the file object :param preserve: optional flag to preserve the inline table in result """
if not f.write: raise TypeError('You can only dump an object into a file object') encoder = Encoder(f, preserve=preserve) return encoder.write_dict(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dumps(obj, preserve=False): """Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline table in result """
f = StringIO() dump(obj, f, preserve) return f.getvalue()