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 split_adhoc_filters_into_base_filters(fd): """ Mutates form data to restructure the adhoc filters in the form of the four base filters, `where`, `having`, `f...
adhoc_filters = fd.get('adhoc_filters') if isinstance(adhoc_filters, list): simple_where_filters = [] simple_having_filters = [] sql_where_filters = [] sql_having_filters = [] for adhoc_filter in adhoc_filters: expression_type = adhoc_filter.get('expressionTy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_energy(): """Loads an energy related dataset to use with sankey and graphs"""
tbl_name = 'energy_usage' data = get_example_data('energy.json.gz') pdf = pd.read_json(data) pdf.to_sql( tbl_name, db.engine, if_exists='replace', chunksize=500, dtype={ 'source': String(255), 'target': String(255), 'value': Fl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runserver(debug, console_log, use_reloader, address, port, timeout, workers, socket): """Starts a Superset web server."""
debug = debug or config.get('DEBUG') or console_log if debug: print(Fore.BLUE + '-=' * 20) print( Fore.YELLOW + 'Starting Superset server in ' + Fore.RED + 'DEBUG' + Fore.YELLOW + ' mode') print(Fore.BLUE + '-=' * 20) print(Style.RESET_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 version(verbose): """Prints the current version number"""
print(Fore.BLUE + '-=' * 15) print(Fore.YELLOW + 'Superset ' + Fore.CYAN + '{version}'.format( version=config.get('VERSION_STRING'))) print(Fore.BLUE + '-=' * 15) if verbose: print('[DB] : ' + '{}'.format(db.engine)) print(Style.RESET_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 refresh_druid(datasource, merge): """Refresh druid datasources"""
session = db.session() from superset.connectors.druid.models import DruidCluster for cluster in session.query(DruidCluster).all(): try: cluster.refresh_datasources(datasource_name=datasource, merge_flag=merge) except Exception as e: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_dashboards(path, recursive): """Import dashboards from JSON"""
p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.json')) elif p.exists() and recursive: files.extend(p.rglob('*.json')) for f in files: logging.info('Importing dashboard from file %s', f) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_dashboards(print_stdout, dashboard_file): """Export dashboards to JSON"""
data = dashboard_import_export.export_dashboards(db.session) if print_stdout or not dashboard_file: print(data) if dashboard_file: logging.info('Exporting dashboards to %s', dashboard_file) with open(dashboard_file, 'w') as data_stream: data_stream.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_datasources(path, sync, recursive): """Import datasources from YAML"""
sync_array = sync.split(',') p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.yaml')) files.extend(p.glob('*.yml')) elif p.exists() and recursive: files.extend(p.rglob('*.yaml')) files.ext...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_datasources(print_stdout, datasource_file, back_references, include_defaults): """Export datasources to YAML"""
data = dict_import_export.export_to_dict( session=db.session, recursive=True, back_references=back_references, include_defaults=include_defaults) if print_stdout or not datasource_file: yaml.safe_dump(data, stdout, default_flow_style=False) if datasource_file: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_datasource_schema(back_references): """Export datasource YAML schema to stdout"""
data = dict_import_export.export_schema_to_dict( back_references=back_references) yaml.safe_dump(data, stdout, default_flow_style=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 update_datasources_cache(): """Refresh sqllab datasources cache"""
from superset.models.core import Database for database in db.session.query(Database).all(): if database.allow_multi_schema_metadata_fetch: print('Fetching {} datasources ...'.format(database.name)) try: database.all_table_names_in_database( fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def worker(workers): """Starts a Superset worker for async SQL query execution."""
logging.info( "The 'superset worker' command is deprecated. Please use the 'celery " "worker' command instead.") if workers: celery_app.conf.update(CELERYD_CONCURRENCY=workers) elif config.get('SUPERSET_CELERY_WORKERS'): celery_app.conf.update( CELERYD_CONCURRENC...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flower(port, address): """Runs a Celery Flower web server Celery Flower is a UI to monitor the Celery operation on a given broker"""
BROKER_URL = celery_app.conf.BROKER_URL cmd = ( 'celery flower ' f'--broker={BROKER_URL} ' f'--port={port} ' f'--address={address} ' ) logging.info( "The 'superset flower' command is deprecated. Please use the 'celery " "flower' command instead.") pri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_datasources(self, refreshAll=True): """endpoint that refreshes druid datasources metadata"""
session = db.session() DruidCluster = ConnectorRegistry.sources['druid'].cluster_class for cluster in session.query(DruidCluster).all(): cluster_name = cluster.cluster_name valid_cluster = True try: cluster.refresh_datasources(refreshAll=refre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_str(l: Node) -> str: """ converts the non-negative number list into a string. """
result = "" while l: result += str(l.val) l = l.next 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 cocktail_shaker_sort(arr): """ Cocktail_shaker_sort Sorting a given array mutation of bubble sort reference: https://en.wikipedia.org/wiki/Cocktail_shaker_so...
def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swapped = True while swapped: swapped = False for i in range(1, n): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = True if swapped == False: return ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def common_prefix(s1, s2): "Return prefix common of 2 strings" if not s1 or not s2: return "" k = 0 while s1[k] == s2[k]: k = k + 1 if k >= len(s1) or k >= len(s2): return s1[0:k] return s1[0:k]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lcs(s1, s2, i, j): """ The length of longest common subsequence among the two given strings s1 and s2 """
if i == 0 or j == 0: return 0 elif s1[i - 1] == s2[j - 1]: return 1 + lcs(s1, s2, i - 1, j - 1) else: return max(lcs(s1, s2, i - 1, j), lcs(s1, s2, i, j - 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 find_nth_digit(n): """find the nth digit of given number. 1. find the length of the number where the nth digit is from. 2. find the actual number where the n...
length = 1 count = 9 start = 1 while n > length * count: n -= length * count length += 1 count *= 10 start *= 10 start += (n-1) / length s = str(start) return int(s[(n-1) % length])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prime_check(n): """Return True if n is a prime number Else return False. """
if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: return False j += 6 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 longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """
if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) dict[string[i]] = i + 1 max_length = max(max_length, i - j + 1) return max_length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. """
if string is None: return 0 start, max_len = 0, 0 used_char = {} for index, char in enumerate(string): if char in used_char and start <= used_char[char]: start = used_char[char] + 1 else: max_len = max(max_len, index - start + 1) used_char[char] =...
<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_longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. Return max_len and the substring as a tuple """
if string is None: return 0, '' sub_string = '' dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) dict[string[i]] = i + 1 if i - j + 1 > max_length: max_length = i - j + 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 get_longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return max_len and ...
if string is None: return 0, '' sub_string = '' start, max_len = 0, 0 used_char = {} for index, char in enumerate(string): if char in used_char and start <= used_char[char]: start = used_char[char] + 1 else: if index - start + 1 > max_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 push(self, item, priority=None): """Push the item in the priority queue. if priority is not given, priority is set to the value of item. """
priority = item if priority is None else priority node = PriorityQueueNode(item, priority) for index, current in enumerate(self.priority_queue_list): if current.priority < node.priority: self.priority_queue_list.insert(index, node) return # wh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_iter(iterable): """ Takes as input multi dimensional iterable and returns generator which produces one dimensional output. """
for element in iterable: if isinstance(element, Iterable): yield from flatten_iter(element) else: yield element
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convolved(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """Iterable to get every convolution window per loop iteration. For example: `co...
# Input validation and error messages if not hasattr(iterable, '__iter__'): raise ValueError( "Can't iterate on object.".format( iterable)) if stride < 1: raise ValueError( "Stride must be of at least one. Got `stride={}`.".format( str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convolved_1d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """1D Iterable to get every convolution window per loop iteration. For more i...
return convolved(iterable, kernel_size, stride, padding, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convolved_2d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """2D Iterable to get every convolution window per loop iteration. For more i...
kernel_size = dimensionize(kernel_size, nd=2) stride = dimensionize(stride, nd=2) padding = dimensionize(padding, nd=2) for row_packet in convolved(iterable, kernel_size[0], stride[0], padding[0], default_value): transposed_inner = [] for col in tuple(row_packet): transpose...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dimensionize(maybe_a_list, nd=2): """Convert integers to a list of integers to fit the number of dimensions if the argument is not already a list. For exampl...
if not hasattr(maybe_a_list, '__iter__'): # Argument is probably an integer so we map it to a list of size `nd`. now_a_list = [maybe_a_list] * nd return now_a_list else: # Argument is probably an `nd`-sized list. return maybe_a_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_intervals(intervals): """ Merge intervals in the form of a list. """
if intervals is None: return None intervals.sort(key=lambda i: i[0]) out = [intervals.pop(0)] for i in intervals: if out[-1][-1] >= i[0]: out[-1][-1] = max(out[-1][-1], i[-1]) else: out.append(i) return 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 merge(intervals): """ Merge two intervals into one. """
out = [] for i in sorted(intervals, key=lambda i: i.start): if out and i.start <= out[-1].end: out[-1].end = max(out[-1].end, i.end) else: out += i, return 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 print_intervals(intervals): """ Print out the intervals. """
res = [] for i in intervals: res.append(repr(i)) print("".join(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 max_heapify(arr, end, simulation, iteration): """ Max heapify helper for max_heap_sort """
last_parent = (end - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from current_parent to last_parent while current_parent <= last_parent: # Find greatest child of current_parent chil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min_heapify(arr, start, simulation, iteration): """ Min heapify helper for min_heap_sort """
# Offset last_parent by the start (last_parent calculated as if start index was 0) # All array accesses need to be offset by start end = len(arr) - 1 last_parent = (end - start - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = pare...
<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_key(k, seed=None): """ the RSA key generating algorithm k is the number of bits in n """
def modinv(a, m): """calculate the inverse of a mod m that is, find b such that (a * b) % m == 1""" b = 1 while not (a * b) % m == 1: b += 1 return b def gen_prime(k, seed=None): """generate a prime with k bits""" def is_prime(num): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def square_root(n, epsilon=0.001): """Return square root of n, with maximum absolute error epsilon"""
guess = n / 2 while abs(guess * guess - n) > epsilon: guess = (guess + (n / guess)) / 2 return 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 powerset(iterable): """Calculate the powerset of any iterable. For a range of integers up to the length of the given list, make all possible combinations and...
"list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s) + 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 greedy_set_cover(universe, subsets, costs): """Approximate greedy algorithm for set-covering. Can be used on large inputs - though not an optimal solution. A...
elements = set(e for s in subsets.keys() for e in subsets[s]) # elements don't cover universe -> invalid input for set cover if elements != universe: return None # track elements of universe covered covered = set() cover_sets = [] while covered != universe: min_cost_elem_r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, key): """ Insert new key into node """
# Create new node n = TreeNode(key) if not self.node: self.node = n self.node.left = AvlTree() self.node.right = AvlTree() elif key < self.node.val: self.node.left.insert(key) elif key > self.node.val: self.node.right.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 re_balance(self): """ Re balance tree. After inserting or deleting a node, """
self.update_heights(recursive=False) self.update_balances(False) while self.balance < -1 or self.balance > 1: if self.balance > 1: if self.node.left.balance < 0: self.node.left.rotate_left() self.update_heights() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_heights(self, recursive=True): """ Update tree height """
if self.node: if recursive: if self.node.left: self.node.left.update_heights() if self.node.right: self.node.right.update_heights() self.height = 1 + max(self.node.left.height, self.node.right.height) else:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_balances(self, recursive=True): """ Calculate tree balance factor """
if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: self.node.right.update_balances() self.balance = self.node.left.height - self.node.right.height else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_order_traverse(self): """ In-order traversal of the tree """
result = [] if not self.node: return result result.extend(self.node.left.in_order_traverse()) result.append(self.node.key) result.extend(self.node.right.in_order_traverse()) 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 kth_to_last_dict(head, k): """ This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is n...
if not (head and k > -1): return False d = dict() count = 0 while head: d[count] = head head = head.next count += 1 return len(d)-k in d and d[len(d)-k]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kth_to_last(head, k): """ This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hits th...
if not (head or k > -1): return False p1 = head p2 = head for i in range(1, k+1): if p1 is None: # Went too far, k is not valid raise IndexError p1 = p1.next while p1: p1 = p1.next p2 = p2.next return p2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combination(n, r): """This function calculates nCr."""
if n == r or r == 0: return 1 else: return combination(n-1, r-1) + combination(n-1, r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combination_memo(n, r): """This function calculates nCr using memoization method."""
memo = {} def recur(n, r): if n == r or r == 0: return 1 if (n, r) not in memo: memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r) return memo[(n, r)] return recur(n, r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pancake_sort(arr): """ Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time c...
len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1): #Finding index of maximum number in arr index_max = arr.index(max(arr[0:cur])) if index_max+1 != cur: #Needs moving if index_max != 0: #reverse from 0 t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def scc(graph): ''' Computes the strongly connected components of a graph ''' order = [] vis = {vertex: False for vertex in graph} graph_transposed = {vertex: [] for vertex in graph} for (v, neighbours) in graph.iteritems(): for u in neighbours: add_edge(graph_transposed, u, v)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def build_graph(formula): ''' Builds the implication graph from the formula ''' graph = {} for clause in formula: for (lit, _) in clause: for neg in [False, True]: graph[(lit, neg)] = [] for ((a_lit, a_neg), (b_lit, b_neg)) in formula: add_edge(graph, (a_lit...
<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_depth(root): """ return 0 if unbalanced else depth + 1 """
if root is None: return 0 left = __get_depth(root.left) right = __get_depth(root.right) if abs(left-right) > 1 or -1 in [left, right]: return -1 return 1 + max(left, right)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def palindromic_substrings_iter(s): """ A slightly more Pythonic approach with a recursive generator """
if not s: yield [] return for i in range(len(s), 0, -1): sub = s[:i] if sub == sub[::-1]: for rest in palindromic_substrings_iter(s[i:]): yield [sub] + rest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ simple user-interface """
print("\t\tCalculator\n\n") while True: user_input = input("expression or exit: ") if user_input == "exit": break try: print("The result is {0}".format(evaluate(user_input))) except Exception: print("invalid syntax!") use...
<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_primes(n): """Return list of all primes less than n, Using sieve of Eratosthenes. """
if n <= 0: raise ValueError("'n' must be a positive integer.") # If x is even, exclude x from list (-1): sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2) sieve = [True for _ in range(sieve_size)] # Sieve primes = [] # List of Primes if n >= 2: primes.append(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 permute(elements): """ returns a list with the permuations. """
if len(elements) <= 1: return [elements] else: tmp = [] for perm in permute(elements[1:]): for i in range(len(elements)): tmp.append(perm[:i] + elements[0:1] + perm[i:]) return tmp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_rabit(): """internal library initializer."""
if _LIB is not None: _LIB.RabitGetRank.restype = ctypes.c_int _LIB.RabitGetWorldSize.restype = ctypes.c_int _LIB.RabitIsDistributed.restype = ctypes.c_int _LIB.RabitVersionNumber.restype = ctypes.c_int
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(args=None): """Initialize the rabit library with arguments"""
if args is None: args = [] arr = (ctypes.c_char_p * len(args))() arr[:] = args _LIB.RabitInit(len(arr), 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 get_processor_name(): """Get the processor name. Returns ------- name : str the name of processor(host) """
mxlen = 256 length = ctypes.c_ulong() buf = ctypes.create_string_buffer(mxlen) _LIB.RabitGetProcessorName(buf, ctypes.byref(length), mxlen) return buf.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast(data, root): """Broadcast object from one node to all other nodes. Parameters data : any type that can be pickled Input data, if current rank does ...
rank = get_rank() length = ctypes.c_ulong() if root == rank: assert data is not None, 'need to pass in data when broadcasting' s = pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL) length.value = len(s) # run first broadcast _LIB.RabitBroadcast(ctypes.byref(length), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normpath(path): """Normalize UNIX path to a native path."""
normalized = os.path.join(*path.split("/")) if os.path.isabs(path): return os.path.abspath("/") + normalized else: return normalized
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, iteration, fobj): """"Update the boosters for one iteration"""
self.bst.update(self.dtrain, iteration, fobj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval(self, iteration, feval): """"Evaluate the CVPack for one iteration."""
return self.bst.eval_set(self.watchlist, iteration, feval)
<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_callback_context(env): """return whether the current callback context is cv or train"""
if env.model is not None and env.cvfolds is None: context = 'train' elif env.model is None and env.cvfolds is not None: context = 'cv' return context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fmt_metric(value, show_stdv=True): """format metric string"""
if len(value) == 2: return '%s:%g' % (value[0], value[1]) if len(value) == 3: if show_stdv: return '%s:%g+%g' % (value[0], value[1], value[2]) return '%s:%g' % (value[0], value[1]) raise ValueError("wrong metric value")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_evaluation(period=1, show_stdv=True): """Create a callback that print evaluation result. We print the evaluation results every **period** iterations an...
def callback(env): """internal function""" if env.rank != 0 or (not env.evaluation_result_list) or period is False or period == 0: return i = env.iteration if i % period == 0 or i + 1 == env.begin_iteration or i + 1 == env.end_iteration: msg = '\t'.join([_fmt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_learning_rate(learning_rates): """Reset learning rate after iteration 1 NOTE: the initial learning rate will still take in-effect on first iteration. P...
def get_learning_rate(i, n, learning_rates): """helper providing the learning rate""" if isinstance(learning_rates, list): if len(learning_rates) != n: raise ValueError("Length of list 'learning_rates' has to equal 'num_boost_round'.") new_learning_rate = lea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _objective_decorator(func): """Decorate an objective function Converts an objective function using the typical sklearn metrics signature so that it is usable...
def inner(preds, dmatrix): """internal function""" labels = dmatrix.get_label() return func(labels, preds) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, X, ntree_limit=0): """Return the predicted leaf every tree for each sample. Parameters X : array_like, shape=[n_samples, n_features] Input featur...
test_dmatrix = DMatrix(X, missing=self.missing, nthread=self.n_jobs) return self.get_booster().predict(test_dmatrix, pred_leaf=True, ntree_limit=ntree_limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def feature_importances_(self): """ Feature importances property .. note:: Feature importance is defined only for tree boosters Feature importance is only define...
if getattr(self, 'booster', None) is not None and self.booster != 'gbtree': raise AttributeError('Feature importance is not defined for Booster type {}' .format(self.booster)) b = self.get_booster() score = b.get_score(importance_type=self.importance...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict_proba(self, data, ntree_limit=None, validate_features=True): """ Predict the probability of each `data` example being of a given class. .. note:: Thi...
test_dmatrix = DMatrix(data, missing=self.missing, nthread=self.n_jobs) if ntree_limit is None: ntree_limit = getattr(self, "best_ntree_limit", 0) class_probs = self.get_booster().predict(test_dmatrix, ntree_limit=ntree_limit, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_pystr_to_cstr(data): """Convert a list of Python str to C pointer Parameters data : list list of str """
if not isinstance(data, list): raise NotImplementedError pointers = (ctypes.c_char_p * len(data))() if PY3: data = [bytes(d, 'utf-8') for d in data] else: data = [d.encode('utf-8') if isinstance(d, unicode) else d # pylint: disable=undefined-variable for d in d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_cstr_to_pystr(data, length): """Revert C pointer to Python str Parameters data : ctypes pointer pointer to data length : ctypes pointer pointer to lengt...
if PY3: res = [] for i in range(length.value): try: res.append(str(data[i].decode('ascii'))) except UnicodeDecodeError: res.append(str(data[i].decode('utf-8'))) else: res = [] for i in range(length.value): try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_lib(): """Load xgboost Library."""
lib_paths = find_lib_path() if not lib_paths: return None try: pathBackup = os.environ['PATH'].split(os.pathsep) except KeyError: pathBackup = [] lib_success = False os_error_list = [] for lib_path in lib_paths: try: # needed when the lib is linke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctypes2buffer(cptr, length): """Convert ctypes pointer to buffer type."""
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)): raise RuntimeError('expected char pointer') res = bytearray(length) rptr = (ctypes.c_char * length).from_buffer(res) if not ctypes.memmove(rptr, cptr, length): raise RuntimeError('memmove failed') 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 c_array(ctype, values): """Convert a python string to c array."""
if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype): return (ctype * len(values)).from_buffer_copy(values) return (ctype * len(values))(*values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_dt_array(array): """ Extract numpy array from single column data table """
if not isinstance(array, DataTable) or array is None: return array if array.shape[1] > 1: raise ValueError('DataTable for label or weight cannot have multiple columns') # below requires new dt version # extract first column array = array.to_numpy()[:, 0].astype('float') retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_from_dt(self, data, nthread): """ Initialize data from a datatable Frame. """
ptrs = (ctypes.c_void_p * data.ncols)() if hasattr(data, "internal") and hasattr(data.internal, "column"): # datatable>0.8.0 for icol in range(data.ncols): col = data.internal.column(icol) ptr = col.data_pointer ptrs[icol] = ctypes...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_float_info_npy2d(self, field, data): """Set float type property into the DMatrix for numpy 2d array input Parameters field: str The field name of the inf...
if getattr(data, 'base', None) is not None and \ data.base is not None and isinstance(data, np.ndarray) \ and isinstance(data.base, np.ndarray) and (not data.flags.c_contiguous): warnings.warn("Use subset (sliced data) of np.ndarray is not recommended " + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_rabit_checkpoint(self): """Initialize the model by load from rabit checkpoint. Returns ------- version: integer The version number of the model. """
version = ctypes.c_int() _check_call(_LIB.XGBoosterLoadRabitCheckpoint( self.handle, ctypes.byref(version))) return version.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attr(self, key): """Get attribute string from the Booster. Parameters key : str The key to get attribute from. Returns ------- value : str The attribute valu...
ret = ctypes.c_char_p() success = ctypes.c_int() _check_call(_LIB.XGBoosterGetAttr( self.handle, c_str(key), ctypes.byref(ret), ctypes.byref(success))) if success.value != 0: return py_str(ret.value) return 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 attributes(self): """Get attributes stored in the Booster as a dictionary. Returns ------- result : dictionary of attribute_name: attribute_value pairs of st...
length = c_bst_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() _check_call(_LIB.XGBoosterGetAttrNames(self.handle, ctypes.byref(length), ctypes.byref(sarr))) attr_names = from_cstr_to_pystr(sa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attr(self, **kwargs): """Set the attribute of the Booster. Parameters **kwargs The attributes to set. Setting a value to None deletes an attribute. """
for key, value in kwargs.items(): if value is not None: if not isinstance(value, STRING_TYPES): raise ValueError("Set Attr only accepts string values") value = c_str(str(value)) _check_call(_LIB.XGBoosterSetAttr( self.h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_param(self, params, value=None): """Set parameters into the Booster. Parameters params: dict/list/str list of key,value pairs, dict of key to value or si...
if isinstance(params, Mapping): params = params.items() elif isinstance(params, STRING_TYPES) and value is not None: params = [(params, value)] for key, val in params: _check_call(_LIB.XGBoosterSetParam(self.handle, c_str(key), c_str(str(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 eval(self, data, name='eval', iteration=0): """Evaluate the model on mat. Parameters data : DMatrix The dmatrix storing the input. name : str, optional The n...
self._validate_features(data) return self.eval_set([(data, name)], iteration)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_model(self, fname): """ Save the model to a file. The model is saved in an XGBoost internal binary format which is universal among the various XGBoost i...
if isinstance(fname, STRING_TYPES): # assume file name _check_call(_LIB.XGBoosterSaveModel(self.handle, c_str(fname))) else: raise TypeError("fname must be a string")
<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_model(self, fout, fmap='', with_stats=False, dump_format="text"): """ Dump model into a text or JSON file. Parameters fout : string Output file name. fm...
if isinstance(fout, STRING_TYPES): fout = open(fout, 'w') need_close = True else: need_close = False ret = self.get_dump(fmap, with_stats, dump_format) if dump_format == 'json': fout.write('[\n') for i, _ in enumerate(ret): ...
<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_dump(self, fmap='', with_stats=False, dump_format="text"): """ Returns the model dump as a list of strings. Parameters fmap : string, optional Name of th...
length = c_bst_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() if self.feature_names is not None and fmap == '': flen = len(self.feature_names) fname = from_pystr_to_cstr(self.feature_names) if self.feature_types is None: # use quantitative...
<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_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): """Get split value histogram of a feature Parameters feature: str The name of t...
xgdump = self.get_dump(fmap=fmap) values = [] regexp = re.compile(r"\[{0}<([\d.Ee+-]+)\]".format(feature)) for i, _ in enumerate(xgdump): m = re.findall(regexp, xgdump[i]) values.extend([float(x) for x in m]) n_unique = len(np.unique(values)) bin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', importance_type='weight',...
try: import matplotlib.pyplot as plt except ImportError: raise ImportError('You must install matplotlib to plot importance') if isinstance(booster, XGBModel): importance = booster.get_booster().get_score(importance_type=importance_type) elif isinstance(booster, Booster): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_edge(graph, node, text, yes_color='#0000FF', no_color='#FF0000'): """parse dumped edge"""
try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, label='yes, missing', color=yes_color) graph.edge(node, no, label='no', color=no_color) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True): """Create a new action and assign callbacks, shortcuts...
a = QAction(text, parent) if icon is not None: a.setIcon(newIcon(icon)) if shortcut is not None: if isinstance(shortcut, (list, tuple)): a.setShortcuts(shortcut) else: a.setShortcut(shortcut) if tip is not None: a.setToolTip(tip) a.setStat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """
def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_func(key) list.sort(key=sort_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selectShapePoint(self, point): """Select the first shape created which contains this point."""
self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape shape.highlightVertex(index, shape.MOVE_VERTEX) self.selectShape(shape) return for shape in reversed(self.shapes): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toggleDrawingSensitive(self, drawing=True): """In the middle of drawing, toggling between modes should be disabled."""
self.actions.editMode.setEnabled(not drawing) if not drawing and self.beginner(): # Cancel creation. print('Cancel creation.') self.canvas.setEditing(True) self.canvas.restoreCursor() self.actions.create.setEnabled(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 btnstate(self, item= None): """ Function to handle difficult examples Update on each object """
if not self.canvas.editing(): return item = self.currentItem() if not item: # If not selected Item, take the first one item = self.labelList.item(self.labelList.count()-1) difficult = self.diffcButton.isChecked() try: shape = self.itemsToSh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newShape(self): """Pop-up and give focus to the label editor. position MUST be in global coordinates. """
if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.text(): if len(self.labelHist) > 0: self.labelDialog = LabelDialog( parent=self, listItem=self.labelHist) # Sync single class mode from PR#106 if self.single...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scaleFitWindow(self): """Figure out the size of the pixmap in order to fit the main widget."""
e = 2.0 # So that no scrollbars are generated. w1 = self.centralWidget().width() - e h1 = self.centralWidget().height() - e a1 = w1 / h1 # Calculate a new scale value based on the pixmap's aspect ratio. w2 = self.canvas.pixmap.width() - 0.0 h2 = self.canvas.pixm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genXML(self): """ Return XML root """
# Check conditions if self.filename is None or \ self.foldername is None or \ self.imgSize is None: return None top = Element('annotation') if self.verified: top.set('verified', 'yes') folder = SubElement(top, 'folder') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing"""
if self.enableRateLimit: self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method, params, headers, body) return self.fetch(request['url'], request['method'], request['headers'], request['body'])