_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q10900
_construct_new_key
train
def _construct_new_key(name, units=None): """Construct an MDF safe key from the name and units""" to_replace = ["/", "\\", "*", "^", "#", " ", "\n", "\t", ",", ".", ")", "(", "'", "`", "-"] to_remove = ["$", "{", "}"] cat = name if units: cat = "_".join([name,
python
{ "resource": "" }
q10901
_extract_key_value
train
def _extract_key_value(obj): """Extract the value from the object and make a descriptive key""" key = None; value = None # Parse a Value object, which includes Properties if isinstance(obj, Value): key = _construct_new_key(obj.name, obj.units) value = [] if obj.scalars: value = [(val.value if isinstance(val, Scalar) else val) for val in obj.scalars] elif obj.vectors and len(obj.vectors) == 1: value = [(val.value if isinstance(val, Scalar) else val)
python
{ "resource": "" }
q10902
process_input_buffer
train
def process_input_buffer(): """Send the content of the input buffer to all remote processes, this must be called in the main thread""" from polysh.control_commands_helpers import handle_control_command data = the_stdin_thread.input_buffer.get() remote_dispatcher.log(b'> ' + data) if data.startswith(b':'): try: handle_control_command(data[1:-1].decode()) except UnicodeDecodeError as e: console_output(b'Could not decode command.') return if data.startswith(b'!'): try: retcode = subprocess.call(data[1:], shell=True) except OSError as e: if e.errno == errno.EINTR: console_output(b'Child was interrupted\n') retcode = 0 else: raise if retcode > 128 and retcode <= 192: retcode = 128 - retcode if retcode > 0: console_output('Child returned {:d}\n'.format(retcode).encode()) elif retcode < 0:
python
{ "resource": "" }
q10903
write_main_socket
train
def write_main_socket(c): """Synchronous write to the main socket, wait for ACK""" the_stdin_thread.socket_write.send(c) while True:
python
{ "resource": "" }
q10904
get_stdin_pid
train
def get_stdin_pid(cached_result=None): """Try to get the PID of the stdin thread, otherwise get the whole process ID""" if cached_result is None: try: tasks = os.listdir('/proc/self/task')
python
{ "resource": "" }
q10905
InputBuffer.add
train
def add(self, data): """Add data to the buffer"""
python
{ "resource": "" }
q10906
InputBuffer.get
train
def get(self): """Get the content of the buffer""" data = b'' with self.lock:
python
{ "resource": "" }
q10907
SocketNotificationReader.handle_read
train
def handle_read(self): """Handle all the available character commands in the socket""" while True: try: c = self.recv(1) except socket.error as e: if e.errno == errno.EWOULDBLOCK: return else:
python
{ "resource": "" }
q10908
knuth_sum
train
def knuth_sum(a, b): """Error-free transformation of the sum of two floating point numbers according to D.E. Knuth. The Art of Computer Programming: Seminumerical Algorithms, volume 2. Addison Wesley, Reading, Massachusetts, second edition, 1981. The underlying problem is that the exact sum a+b of two floating point number a and b is not necessarily a floating point number; for example if you add a very large and a very small number. It is
python
{ "resource": "" }
q10909
distill
train
def distill(p, K): """Algorithm 4.3. Error-free vector transformation for summation. The vector p is transformed without changing the sum, and p_n is replaced by float(sum(p)). Kahan [21] calls this a 'distillation algorithm.'
python
{ "resource": "" }
q10910
toggle_shells
train
def toggle_shells(command, enable): """Enable or disable the specified shells. If the command would have no effect, it changes all other shells to the inverse enable value.""" selection = list(selected_shells(command)) if command and command != '*' and selection: for i in selection:
python
{ "resource": "" }
q10911
selected_shells
train
def selected_shells(command): """Iterator over the shells with names matching the patterns. An empty patterns matches all the shells""" if not command or command == '*': for i in dispatchers.all_instances(): yield i return selected = set() instance_found = False for pattern in command.split(): found = False for expanded_pattern in expand_syntax(pattern): for i in dispatchers.all_instances(): instance_found = True
python
{ "resource": "" }
q10912
complete_shells
train
def complete_shells(line, text, predicate=lambda i: True): """Return the shell names to include in the completion""" res = [i.display_name + ' ' for i in dispatchers.all_instances() if
python
{ "resource": "" }
q10913
kill_all
train
def kill_all(): """When polysh quits, we kill all the remote shells we started""" for i in dispatchers.all_instances():
python
{ "resource": "" }
q10914
BufferedDispatcher._handle_read_chunk
train
def _handle_read_chunk(self): """Some data can be read""" new_data = b'' buffer_length = len(self.read_buffer) try: while buffer_length < self.MAX_BUFFER_SIZE: try: piece = self.recv(4096) except OSError as e: if e.errno == errno.EAGAIN: # End of the available data break elif e.errno == errno.EIO and new_data: # Hopefully we could read an error message before the # actual termination break else:
python
{ "resource": "" }
q10915
BufferedDispatcher.dispatch_write
train
def dispatch_write(self, buf): """Augment the buffer with stuff to write when possible""" self.write_buffer += buf if len(self.write_buffer) > self.MAX_BUFFER_SIZE: console_output('Buffer too big ({:d})
python
{ "resource": "" }
q10916
safe_write
train
def safe_write(buf): """We can get a SIGWINCH when printing, which will cause write to raise an EINTR. That's not a reason to stop printing.""" assert isinstance(buf, bytes) while True: try: os.write(1, buf)
python
{ "resource": "" }
q10917
console_output
train
def console_output(msg, logging_msg=None): """Use instead of print, to clear the status information before printing""" assert isinstance(msg, bytes) assert isinstance(logging_msg, bytes) or logging_msg is None from polysh import remote_dispatcher remote_dispatcher.log(logging_msg or msg) if remote_dispatcher.options.interactive: from polysh.stdin import the_stdin_thread the_stdin_thread.no_raw_input()
python
{ "resource": "" }
q10918
expand_syntax
train
def expand_syntax(string): """Iterator over all the strings in the expansion of the argument""" match = syntax_pattern.search(string) if match: prefix = string[:match.start()] suffix = string[match.end():] intervals = match.group(1).split(',') for interval in
python
{ "resource": "" }
q10919
all_instances
train
def all_instances(): """Iterator over all the remote_dispatcher instances""" return sorted([i for i in asyncore.socket_map.values() if
python
{ "resource": "" }
q10920
count_awaited_processes
train
def count_awaited_processes(): """Return a tuple with the number of awaited processes and the total number""" awaited = 0 total = 0 for i in all_instances(): if i.enabled:
python
{ "resource": "" }
q10921
all_terminated
train
def all_terminated(): """For each remote shell determine if its terminated""" instances_found = False for i in all_instances():
python
{ "resource": "" }
q10922
update_terminal_size
train
def update_terminal_size(): """Propagate the terminal size to the remote shells accounting for the place taken by the longest name""" w, h = terminal_size() w = max(w - display_names.max_display_name_length - 2, min(w, 10)) # python bug http://python.org/sf/1112949 on amd64 # from ajaxterm.py bug = struct.unpack('i',
python
{ "resource": "" }
q10923
format_info
train
def format_info(info_list): """Turn a 2-dimension list of bytes into a 1-dimension list of bytes with correct spacing""" max_lengths = [] if info_list: nr_columns = len(info_list[0]) else: nr_columns = 0 for i in range(nr_columns): max_lengths.append(max([len(info[i]) for info in info_list])) flattened_info_list = [] for info_id in range(len(info_list)): info = info_list[info_id] for str_id in range(len(info) - 1): # Don't justify the last column (i.e. the last printed line) # as it
python
{ "resource": "" }
q10924
generate_ill_conditioned_dot_product
train
def generate_ill_conditioned_dot_product(n, c, dps=100): """n ... length of vector c ... target condition number """ # Algorithm 6.1 from # # ACCURATE SUM AND DOT PRODUCT, # TAKESHI OGITA, SIEGFRIED M. RUMP, AND SHIN'ICHI OISHI. assert n >= 6 n2 = round(n / 2) x = numpy.zeros(n) y = numpy.zeros(n) b = math.log2(c) # vector of exponents between 0 and b/2: e = numpy.rint(numpy.random.rand(n2) * b / 2).astype(int) # make sure exponents b/2 and 0 actually occur in e # vectors x,y e[0] = round(b / 2) + 1 e[-1] = 0 # generate first half of vectors x, y rx, ry = numpy.random.rand(2, n2) x[:n2] = (2 * rx - 1) * 2
python
{ "resource": "" }
q10925
RemoteDispatcher.launch_ssh
train
def launch_ssh(self, name, port): """Launch the ssh command in the child process""" if options.user: name = '%s@%s' % (options.user, name) evaluated = options.ssh % {'host': name, 'port': port}
python
{ "resource": "" }
q10926
RemoteDispatcher.change_state
train
def change_state(self, state): """Change the state of the remote process, logging the change""" if state is not self.state: if self.debug: self.print_debug(b'state => ' + STATE_NAMES[state].encode())
python
{ "resource": "" }
q10927
RemoteDispatcher.disconnect
train
def disconnect(self): """We are no more interested in this remote process""" try: os.kill(-self.pid, signal.SIGKILL) except OSError: # The process was already dead, no problem pass self.read_buffer = b'' self.write_buffer = b'' self.set_enabled(False) if self.read_in_state_not_started:
python
{ "resource": "" }
q10928
RemoteDispatcher.configure_tty
train
def configure_tty(self): """We don't want \n to be replaced with \r\n, and we disable the echo""" attr = termios.tcgetattr(self.fd) attr[1] &= ~termios.ONLCR #
python
{ "resource": "" }
q10929
RemoteDispatcher.set_prompt
train
def set_prompt(self): """The prompt is important because we detect the readyness of a process by waiting for its prompt.""" # No right prompt command_line = b'PS2=;RPS1=;RPROMPT=;' command_line += b'PROMPT_COMMAND=;' command_line += b'TERM=ansi;' command_line += b'unset HISTFILE;'
python
{ "resource": "" }
q10930
RemoteDispatcher.handle_read_fast_case
train
def handle_read_fast_case(self, data): """If we are in a fast case we'll avoid the long processing of each line""" if self.state is not STATE_RUNNING or callbacks.any_in(data):
python
{ "resource": "" }
q10931
RemoteDispatcher.handle_read
train
def handle_read(self): """We got some output from a remote shell, this is one of the state machine""" if self.state == STATE_DEAD: return global nr_handle_read nr_handle_read += 1 new_data = self._handle_read_chunk() if self.debug: self.print_debug(b'==> ' + new_data) if self.handle_read_fast_case(self.read_buffer): return lf_pos = new_data.find(b'\n') if lf_pos >= 0: # Optimization: we knew there were no '\n' in the previous read # buffer, so we searched only in the new_data and we offset the # found index by the length of the previous buffer lf_pos += len(self.read_buffer) - len(new_data) elif self.state is STATE_NOT_STARTED and \ options.password is not None and \ b'password:' in self.read_buffer.lower(): self.dispatch_write('{}\n'.format(options.password).encode()) self.read_buffer = b''
python
{ "resource": "" }
q10932
RemoteDispatcher.print_unfinished_line
train
def print_unfinished_line(self): """The unfinished line stayed long enough in the buffer to be printed""" if self.state is STATE_RUNNING:
python
{ "resource": "" }
q10933
RemoteDispatcher.handle_write
train
def handle_write(self): """Let's write as much as we can""" num_sent = self.send(self.write_buffer) if self.debug: if self.state is not STATE_NOT_STARTED or options.password is None:
python
{ "resource": "" }
q10934
RemoteDispatcher.print_debug
train
def print_debug(self, msg): """Log some debugging information to the console""" assert isinstance(msg, bytes) state = STATE_NAMES[self.state].encode()
python
{ "resource": "" }
q10935
RemoteDispatcher.get_info
train
def get_info(self): """Return a list with all information available about this process""" return [self.display_name.encode(),
python
{ "resource": "" }
q10936
RemoteDispatcher.dispatch_write
train
def dispatch_write(self, buf): """There is new stuff to write when possible""" if self.state != STATE_DEAD and self.enabled:
python
{ "resource": "" }
q10937
RemoteDispatcher.change_name
train
def change_name(self, new_name): """Change the name of the shell, possibly updating the maximum name length""" if not new_name: name = self.hostname else:
python
{ "resource": "" }
q10938
RemoteDispatcher.rename
train
def rename(self, name): """Send to the remote shell, its new name to be shell expanded""" if name: # defug callback add? rename1, rename2 = callbacks.add( b'rename', self.change_name, False) self.dispatch_command(b'/bin/echo "' + rename1
python
{ "resource": "" }
q10939
complete
train
def complete(text, state): """On tab press, return the next possible completion""" global completion_results if state == 0: line = readline.get_line_buffer() if line.startswith(':'): # Control command completion completion_results = complete_control_command(line, text) else: if line.startswith('!') and text and line.startswith(text): dropped_exclam = True text = text[1:] else: dropped_exclam = False completion_results = [] # Complete local paths completion_results += complete_local_path(text) # Complete from history l = len(text) completion_results += [w + ' ' for w in history_words if len(w) > l and w.startswith(text)] if readline.get_begidx() == 0:
python
{ "resource": "" }
q10940
Popen
train
def Popen(*args, **kwargs): """ Executes a command using subprocess.Popen and redirects output to AETROS and stdout. Parses stdout as well for stdout API calls. Use read_line argument to read stdout of command's stdout line by line. Use returned process stdin to communicate with the command. :return: subprocess.Popen """ read_line = None
python
{ "resource": "" }
q10941
JobBackend.on_sigint
train
def on_sigint(self, sig, frame): """ We got SIGINT signal. """ if self.stop_requested or self.stop_requested_force: # signal has already been sent or we force a shutdown. # handles the keystroke 2x CTRL+C to force an exit. self.stop_requested_force = True self.logger.warning('Force stopped: ' + str(sig)) # just kill the process, we don't care about the results self.on_force_exit() os._exit(1) # with force_exit we really close the process, killing it in unknown state # self.fail('Force stopped', force_exit=True) # return if self.is_master_process(): self.logger.warning('Received signal '+str(sig)+'.
python
{ "resource": "" }
q10942
JobBackend.external_aborted
train
def external_aborted(self, params): """ Immediately abort the job by server. This runs in the Client:read() thread. """ self.ended = True self.running = False # When the server sends an abort signal, we really have to close immediately,
python
{ "resource": "" }
q10943
JobBackend.external_stop
train
def external_stop(self, force): """ Stop signal by server. """ # only the master processes handles the regular stop signal from the server, sending a SIGINT to # all its child (means to us, non-master process) if not self.is_master_process(): if force: # make sure even the subprocess dies really on force os._exit(1)
python
{ "resource": "" }
q10944
JobBackend.fail
train
def fail(self, message=None, force_exit=False): """ Marks the job as failed, saves the given error message and force exists the process when force_exit=True. """ global last_exit_code if not last_exit_code: last_exit_code = 1 with self.git.batch_commit('FAILED'): self.set_status('FAILED', add_section=False) self.git.commit_json_file('FAIL_MESSAGE', 'aetros/job/crash/error', str(message) if message else '') if isinstance(sys.stderr,
python
{ "resource": "" }
q10945
JobBackend.write_log
train
def write_log(self, message): """ Proxy method for GeneralLogger. """ if self.stream_log and not self.ended:
python
{ "resource": "" }
q10946
JobBackend.set_status
train
def set_status(self, status, add_section=True): """ Set an arbitrary status, visible in the big wheel of the
python
{ "resource": "" }
q10947
JobBackend.create
train
def create(self, create_info=None, hyperparameter=None, server='local', insights=False): """ Creates a new job in git and pushes it. :param create_info: from the api.create_job_info(id). Contains the config and job info (type, server) :param hyperparameter: simple nested dict with key->value, which overwrites stuff from aetros.yml :param server: if None, the the job will be assigned to a server. :param insights: whether you want to activate insights (for simple models) """ if not create_info: create_info = { 'server': server, 'config': { 'insights': insights, 'command': ' '.join(sys.argv) } } config = find_config(self.config_path, logger=self.logger) if not config['model']: raise Exception('AETROS config file (aetros.yml) not found.') # first transform simple format in the full definition with parameter types # (string, number, group, choice_group, etc) full_hyperparameters = lose_parameters_to_full(config['parameters']) # now extract hyperparameters from full definition, and overwrite stuff using # incoming_hyperparameter if available hyperparameter
python
{ "resource": "" }
q10948
JobBackend.get_parameter
train
def get_parameter(self, path, default=None, return_group=False): """ Reads hyperparameter from job configuration. If nothing found use given default. :param path: str :param default: * :param return_group: If true and path is a choice_group, we return the dict instead of the group name. :return:
python
{ "resource": "" }
q10949
JobBackend.load
train
def load(self, job_id): """ Loads job into index and work-tree, restart its ref and sets as current.
python
{ "resource": "" }
q10950
JobBackend.load_job_from_ref
train
def load_job_from_ref(self): """ Loads the job.json into self.job """ if not self.job_id: raise Exception('Job not loaded yet. Use load(id) first.') if not os.path.exists(self.git.work_tree + '/aetros/job.json'): raise Exception('Could not load aetros/job.json from git repository. Make sure you have created the job correctly.') with open(self.git.work_tree + '/aetros/job.json') as f:
python
{ "resource": "" }
q10951
JobBackend.file_list
train
def file_list(self): """ Lists all files in the working directory. """ blacklist = ['.git', 'aetros'] working_tree = self.git.work_tree def recursive(path='.'): if os.path.basename(path) in blacklist: return 0, 0 if os.path.isdir(path): files = [] for file in os.listdir(path): if path and path != '.': file = path + '/' + file added_files = recursive(file) files += added_files return files
python
{ "resource": "" }
q10952
ftpretty.get
train
def get(self, remote, local=None): """ Gets the file from FTP server local can be: a file: opened for writing, left open a string: path to output file None: contents are returned """ if isinstance(local, file_type): # open file, leave open local_file = local elif local is None: # return string local_file = buffer_type() else: # path to file, open, write/close return None local_file = open(local, 'wb')
python
{ "resource": "" }
q10953
ftpretty.upload_tree
train
def upload_tree(self, src, dst, ignore=None): """Recursively upload a directory tree. Although similar to shutil.copytree we don't follow symlinks. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() try: self.conn.mkd(dst) except error_perm: pass errors = [] for name in names: if name in ignored_names: continue src_name = os.path.join(src, name) dst_name = os.path.join(dst, name) try: if os.path.islink(src_name): pass
python
{ "resource": "" }
q10954
ftpretty.list
train
def list(self, remote='.', extra=False, remove_relative_paths=False): """ Return directory list """ if extra: self.tmp_output = [] self.conn.dir(remote, self._collector) directory_list = split_file_info(self.tmp_output) else:
python
{ "resource": "" }
q10955
ftpretty.descend
train
def descend(self, remote, force=False): """ Descend, possibly creating directories as needed """ remote_dirs = remote.split('/') for directory in remote_dirs:
python
{ "resource": "" }
q10956
ftpretty.delete
train
def delete(self, remote): """ Delete a file from server """ try: self.conn.delete(remote)
python
{ "resource": "" }
q10957
ftpretty.cd
train
def cd(self, remote): """ Change working directory on server """ try: self.conn.cwd(remote)
python
{ "resource": "" }
q10958
start
train
def start(logger, full_id, fetch=True, env=None, volumes=None, cpus=None, memory=None, gpu_devices=None, offline=False): """ Starts the job with all logging of a job_id """ owner, name, id = unpack_full_job_id(full_id) if isinstance(sys.stdout, GeneralLogger): # we don't want to have stuff written to stdout before in job's log sys.stdout.clear_buffer() job_backend = JobBackend(model_name=owner + '/' + name) if fetch: job_backend.fetch(id) job_backend.restart(id) job_backend.start(collect_system=False, offline=offline) job_backend.set_status('PREPARE', add_section=False) job = job_backend.get_job_model() if not cpus: cpus = job.get_cpu() if not memory:
python
{ "resource": "" }
q10959
fromimage
train
def fromimage(im, flatten=False, mode=None): """ Return a copy of a PIL image as a numpy array. Parameters ---------- im : PIL image Input image. flatten : bool If true, convert the output to grey-scale. mode : str, optional Mode to convert image to, e.g. ``'RGB'``. See the Notes of the `imread` docstring for more details. Returns ------- fromimage : ndarray The different colour bands/channels are stored in the third dimension, such that a grey-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4. """ if not Image.isImageType(im): raise TypeError("Input is not a PIL image.") if mode is not None: if mode != im.mode: im = im.convert(mode) elif im.mode == 'P': # Mode 'P' means there is an indexed "palette". If we leave the mode # as 'P', then when we do `a = array(im)` below, `a` will be a 2-D # containing the indices into the palette, and not a 3-D array # containing the RGB or RGBA values. if 'transparency' in im.info:
python
{ "resource": "" }
q10960
imresize
train
def imresize(arr, size, interp='bilinear', mode=None): """ Resize an image. Parameters ---------- arr : ndarray The array of image to be resized. size : int, float or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : str, optional Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear', 'bicubic' or 'cubic'). mode : str, optional The PIL image mode ('P', 'L', etc.) to convert `arr` before resizing. Returns ------- imresize : ndarray The resized array of image. See Also -------- toimage : Implicitly used to convert `arr` according to `mode`. scipy.ndimage.zoom : More generic
python
{ "resource": "" }
q10961
BackendClient._end_channel
train
def _end_channel(self, channel): """ Soft end of ssh channel. End the writing thread as soon as the message queue is empty. """ self.stop_on_empty_queue[channel] = True # by joining the we wait until its loop finishes. # it won't loop forever since we've
python
{ "resource": "" }
q10962
BackendClient.wait_sending_last_messages
train
def wait_sending_last_messages(self): """ Requests all channels to close and waits for it. """ if self.active and self.online is not False: self.logger.debug("client sends last %s messages ..." % ([str(i) + ':' + str(len(x)) for i, x in six.iteritems(self.queues)],)) for channel, messages in six.iteritems(self.queues): for idx, message in enumerate(messages): self.logger.debug("[%s] %d: %s" % (channel, idx, str(message)[0:120])) # send all missing messages
python
{ "resource": "" }
q10963
BackendClient.wait_until_queue_empty
train
def wait_until_queue_empty(self, channels, report=True, clear_end=True): """ Waits until all queues of channels are empty. """ state = {'message': ''} self.logger.debug("wait_until_queue_empty: report=%s %s" % (str(report), str([channel+':'+str(len(self.queues[channel])) for channel in channels]), )) queues = [] for channel in channels: queues += self.queues[channel][:] def print_progress(): if report: self.logger.debug("all_empty=%s" % (str(all_empty),)) sys.__stderr__.write('\b' * len(state['message'])) sys.__stderr__.write("\033[K") state['message'] = "%.2f kB/s // %.2fkB of %.2fkB // %.2f%%" \ % (self.bytes_speed / 1024, self.bytes_sent / 1024, self.bytes_total / 1024, (self.bytes_sent / self.bytes_total * 100) if self.bytes_total else 0)
python
{ "resource": "" }
q10964
BackendClient.send_message
train
def send_message(self, message, channel): """ Internal. Sends the actual message from a queue entry. """ if not self.is_connected(channel): return False message['_sending'] = True if '_data' in message: data = message['_data'] else: data = msgpack.packb(message, default=invalid_json_values) self.bytes_total += len(data) message['_bytes_sent'] = 0 message['_id'] = -1 if is_debug2(): sys.__stderr__.write("[%s] send message: %s\n" % (channel, str(msgpack.unpackb(data))[0:180])) try: while data: start = time.time() bytes_sent = self.ssh_channel[channel].send(data) data = data[bytes_sent:] message['_bytes_sent'] += bytes_sent self.bytes_sent += bytes_sent end = time.time()
python
{ "resource": "" }
q10965
BackendClient.wait_for_at_least_one_message
train
def wait_for_at_least_one_message(self, channel): """ Reads until we receive at least one message we can unpack. Return all found messages. """ unpacker = msgpack.Unpacker(encoding='utf-8') while True: try: start = time.time() chunk = self.ssh_channel[channel].recv(1024) end = time.time() self.read_speeds.append( len(chunk) / (end-start) ) if len(self.read_speeds) > 20: self.read_speeds = self.read_speeds[10:] if chunk == b'':
python
{ "resource": "" }
q10966
raise_sigint
train
def raise_sigint(): """ Raising the SIGINT signal in the current process and all sub-processes. os.kill() only issues a signal in the current process (without subprocesses). CTRL+C on the console sends the signal to the process group (which we need). """ if hasattr(signal, 'CTRL_C_EVENT'): # windows. Need CTRL_C_EVENT to raise the signal in the whole process group
python
{ "resource": "" }
q10967
Git.read_job
train
def read_job(self, job_id, checkout=False): """ Reads head and reads the tree into index, and checkout the work-tree when checkout=True. This does not fetch the job from the actual server. It needs to be in the local git already. """ self.job_id = job_id commit = self.get_head_commit() self.logger.debug('Job ref points to ' + commit) self.command_exec(['read-tree', self.ref_head]) if checkout: self.logger.debug('Working directory in ' + self.work_tree) # make sure we have checked out all files we have added until now. Important for simple models, # so we have the actual model.py and dataset scripts.
python
{ "resource": "" }
q10968
Git.start_push_sync
train
def start_push_sync(self): """ Starts the detection of unsynced Git data. """ self.active_thread = True self.active_push = True
python
{ "resource": "" }
q10969
Git.batch_commit
train
def batch_commit(self, message): """ Instead of committing a lot of small commits you can batch it together using this controller. Example: with git.batch_commit('BATCHED'): git.commit_file('my commit 1', 'path/to/file', 'content from file') git.commit_json_file('[1, 2, 3]', 'path/to/file2', 'json array') Withing the `with` block you can use group the method calls of `commit_file` and `commit_json_file`, and every other method calling this two methods. :type message: str :return: with controller to be used with Python's `with git.batch_commit():` """ class controlled_execution: def __init__(self, git, message): self.git = git self.message = message def __enter__(self): self.git.git_batch_commit = True if self.git.job_id: # make sure we're always on the tip tree
python
{ "resource": "" }
q10970
Git.add_file_path_in_work_tree
train
def add_file_path_in_work_tree(self, path, work_tree, verbose=True): """ Add a new file as blob in the storage and add its tree entry into the index. """ args = ['--work-tree', work_tree, 'add', '-f'] if verbose:
python
{ "resource": "" }
q10971
Git.commit_file
train
def commit_file(self, message, path, content): """ Add a new file as blob in the storage, add its tree entry into the index and commit the index. :param message: str :param path: str :param content: str :return:
python
{ "resource": "" }
q10972
Git.contents
train
def contents(self, path): """ Reads the given path of current ref_head and returns its content as utf-8 """ try:
python
{ "resource": "" }
q10973
get_ordered_devices
train
def get_ordered_devices(): """ Default CUDA_DEVICE_ORDER is not compatible with nvidia-docker. Nvidia-Docker is using CUDA_DEVICE_ORDER=PCI_BUS_ID. https://github.com/NVIDIA/nvidia-docker/wiki/nvidia-docker#gpu-isolation """ libcudart = get_libcudart() devices = {} for i in range(0, get_installed_devices()): gpu = get_device_properties(i) pciBusId = ctypes.create_string_buffer(64) libcudart.cudaDeviceGetPCIBusId(ctypes.byref(pciBusId), 64, i)
python
{ "resource": "" }
q10974
reduce_list_size
train
def reduce_list_size(li): """Return two lists - the last N items of li whose total size is less than MAX_SIZE - the rest of the original list li """ # sys.getsizeof is nearly useless. All our data is stringable so rather # use that as a measure of size. size = len(repr(li)) keep = li toss =
python
{ "resource": "" }
q10975
AnchorSmith.least_role
train
def least_role() -> Role: """ Return the TRUSTEE indy-sdk role for an anchor acting in an AnchorSmith capacity.
python
{ "resource": "" }
q10976
usage
train
def usage() -> None: """ Print usage advice. """ print() print('Usage: setnym.py <config-ini>') print() print('where <config-ini> represents the path to the configuration file.') print() print('The operation submits a nym to a trustee anchor to send to the ledger,') print('if the ledger does not have it already as configured.') print() print('The configuration file has sections and entries as follows:') print(' * section [Node Pool]:') print(' - name: the name of the node pool to which the operation applies') print(' - genesis.txn.path: the path to the genesis transaction file') print(' for the node pool (may omit if node pool already exists)') print(' * section [Trustee Anchor]:') print(" - name: the trustee anchor's (wallet) name") print(" - wallet.type: (default blank) the trustee anchor's wallet type") print(" - wallet.access: (default blank) the trustee anchor's") print(' wallet access credential (password) value') print(' * section [VON Anchor]:') print(' - role: the role to request in the send-nym transaction; specify:') print(' - (default) empty value for user with no additional write privileges') print(' - TRUST_ANCHOR for VON anchor with write privileges for indy artifacts') print(' - TRUSTEE for VON anchor sending further
python
{ "resource": "" }
q10977
_set_wallets
train
async def _set_wallets(an_data: dict) -> dict: """ Set wallets as configured for setnym operation. :param an_data: dict mapping profiles to anchor data :return: dict mapping anchor names to wallet objects """ w_mgr = WalletManager() rv = {} for profile in an_data: w_cfg = {'id': an_data[profile].name} if an_data[profile].wallet_type: w_cfg['storage_type'] = an_data[profile].wallet_type if an_data[profile].seed: w_cfg['seed'] = an_data[profile].seed if an_data[profile].did: w_cfg['did'] = an_data[profile].did
python
{ "resource": "" }
q10978
schema_id
train
def schema_id(origin_did: str, name: str, version: str) -> str: """ Return schema identifier for input origin DID, schema name, and schema version. :param origin_did: DID of schema originator :param name:
python
{ "resource": "" }
q10979
ok_did
train
def ok_did(token: str) -> bool: """ Whether input token looks like a valid distributed identifier. :param token:
python
{ "resource": "" }
q10980
cred_def_id2seq_no
train
def cred_def_id2seq_no(cd_id: str) -> int: """ Given a credential definition identifier, return its schema sequence number. Raise BadIdentifier on input that is not a credential definition identifier. :param cd_id: credential definition identifier :return: sequence number """ if ok_cred_def_id(cd_id):
python
{ "resource": "" }
q10981
rev_reg_id2cred_def_id
train
def rev_reg_id2cred_def_id(rr_id: str) -> str: """ Given a revocation registry identifier, return its corresponding credential definition identifier. Raise BadIdentifier if input is not a revocation registry identifier. :param rr_id: revocation registry identifier :return: credential definition identifier """ if ok_rev_reg_id(rr_id):
python
{ "resource": "" }
q10982
prune_creds_json
train
def prune_creds_json(creds: dict, cred_ids: set) -> str: """ Strip all creds out of the input json structure that do not match any of the input credential identifiers. :param creds: indy-sdk creds structure :param cred_ids: the set of credential identifiers of interest :return: the reduced creds json """ rv = deepcopy(creds) for key in ('attrs', 'predicates'): for attr_uuid,
python
{ "resource": "" }
q10983
proof_req2wql_all
train
def proof_req2wql_all(proof_req: dict, x_cd_ids: Union[str, Sequence[str]] = None) -> dict: """ Given a proof request and a list of cred def ids to omit, return an extra WQL query dict that will find all corresponding credentials in search. The proof request must have cred def id restrictions on all requested attribute specifications. At present, the utility does not support predicates. :param proof_req: proof request :param x_cd_ids: cred def identifier or sequence thereof to omit
python
{ "resource": "" }
q10984
proof_req_attr_referents
train
def proof_req_attr_referents(proof_req: dict) -> dict: """ Given a proof request with all requested attributes having cred def id restrictions, return its attribute referents by cred def id and attribute. The returned structure can be useful in populating the extra WQL query parameter in the credential search API. :param proof_req: proof request with all requested attribute specifications having cred def id restriction; e.g., :: { 'name": 'proof_req', 'version': '0.0', 'requested_attributes': { '18_greenLevel_uuid': { 'restrictions': [ { 'cred_def_id': 'WgWxqztrNooG92RXvxSTWv:3:CL:18:tag' } ], 'name': 'greenLevel', 'non_revoked': { 'to': 1532367957, 'from': 1532367957 } }, '18_legalName_uuid': { 'restrictions': [ { 'cred_def_id': 'WgWxqztrNooG92RXvxSTWv:3:CL:18:tag' } ], 'name': 'legalName', 'non_revoked': { 'to': 1532367957, 'from': 1532367957 } }, '15_id_uuid': { # this specification will not show up in response: no
python
{ "resource": "" }
q10985
proof_req_pred_referents
train
def proof_req_pred_referents(proof_req: dict) -> dict: """ Given a proof request with all requested predicates having cred def id restrictions, return its predicate referents by cred def id and attribute, mapping a predicate and a limit. The returned structure can be useful in downstream processing to filter cred-infos for predicates. :param proof_req: proof request with all requested predicate specifications having cred def id restriction; e.g., :: { 'name': 'proof_req', 'version': '0.0', 'requested_attributes': { ... } 'requested_predicates': { '194_highscore_GE_uuid': { 'name': 'highscore', 'p_type': '>=', 'p_value': '100000', 'restrictions': [ { 'cred_def_id': 'WgWxqztrNooG92RXvxSTWv:3:CL:194:tag' } ], 'non_revoked': { ... } }, '194_level_GE_uuid': { 'name': 'level', 'p_type': '>=', 'p_value': '10', 'restrictions': [ { 'cred_def_id': 'WgWxqztrNooG92RXvxSTWv:3:CL:194:tag' } ], 'non_revoked': { ... } }, '194_attempts_LE_uuid': { 'name': 'attempts', 'p_type': '<=', 'p_value': '3', 'restrictions': [ { 'cred_def_id': 'WgWxqztrNooG92RXvxSTWv:3:CL:194:tag' } ], 'non_revoked': { ... } }, '198_employees_LT_uuid': { 'name': 'employees', 'p_type': '<', 'p_value': '100', 'restrictions': [ { 'cred_def_id': 'WgWxqztrNooG92RXvxSTWv:3:CL:198:tag' } ], 'non_revoked': { ... } }, '198_employees_GE_uuid': { 'name': 'employees', 'p_type': '>=', 'p_value': '50',
python
{ "resource": "" }
q10986
Verifier._build_rr_state_json
train
async def _build_rr_state_json(self, rr_id: str, timestamp: int) -> (str, int): """ Build rev reg state json at a given requested timestamp. Return rev reg state json and its transaction time on the distributed ledger, with upper bound at input timestamp of interest. Raise AbsentRevReg if no revocation registry exists on input rev reg id, or BadRevStateTime if requested timestamp predates revocation registry creation. :param rr_id: rev reg id :param timestamp: timestamp of interest (epoch seconds) :return: rev reg state json and ledger timestamp (epoch seconds) """ LOGGER.debug('_Verifier._build_rr_state_json >>> rr_id: %s, timestamp: %s', rr_id, timestamp) if not ok_rev_reg_id(rr_id): LOGGER.debug('Verifier._build_rr_state_json <!< Bad rev reg id %s', rr_id) raise BadIdentifier('Bad rev reg id {}'.format(rr_id)) rr_json = None ledger_timestamp = None get_rr_req_json = await ledger.build_get_revoc_reg_request(self.did, rr_id, timestamp) resp_json = await self._submit(get_rr_req_json) resp = json.loads(resp_json) if resp.get('result', {}).get('data', None) and resp['result']['data'].get('value', None): # timestamp at or beyond rev reg creation, carry on try:
python
{ "resource": "" }
q10987
Verifier.build_proof_req_json
train
async def build_proof_req_json(self, cd_id2spec: dict) -> str: """ Build and return indy-sdk proof request for input attributes and non-revocation intervals by cred def id. :param cd_id2spec: dict mapping cred def ids to: - (optionally) 'attrs': lists of names of attributes of interest (omit for all, empty list or None for none) - (optionally) '>=': (pred) inclusive int lower-bounds of interest (omit, empty list, or None for none) - (optionally) '>': (pred) exclusive int lower-bounds of interest (omit, empty list, or None for none) - (optionally) '<=': (pred) inclusive int upper-bounds of interest (omit, empty list, or None for none) - (optionally) '<': (pred) exclusive int upper-bounds of interest (omit, empty list, or None for none) - (optionally), 'interval': either - (2-tuple) pair of epoch second counts marking 'from' and 'to' timestamps, or - | single epoch second count to set 'from' and 'to' the same; default | (now, now) for cred defs supporting revocation or None otherwise; e.g., :: { 'Vx4E82R17q...:3:CL:16:tag': { 'attrs': [ # request attrs 'name' and 'favouriteDrink' from this cred def's schema 'name', 'favouriteDrink' ], '>=': { # request predicate score>=80 from this cred def 'score': 80 } '<=': { # request ranking <=10 from this cred def 'ranking': 10 } 'interval': 1528116008 # same instant for all attrs and preds of corresponding schema }, 'R17v42T4pk...:3:CL:19:tag': None, # request all attrs, no preds, default intervals on all attrs 'e3vc5K168n...:3:CL:23:tag': {}, # request all attrs, no preds, default intervals on all attrs 'Z9ccax812j...:3:CL:27:tag': { # request all attrs, no preds, this interval on all attrs 'interval': (1528112408, 1528116008) }, '9cHbp54C8n...:3:CL:37:tag': { # request no attrs and some predicates; specify interval 'attrs': [], # or equivalently, 'attrs': None '>=': { 'employees': '50' # nicety: implementation converts to int for caller }, '>=': { 'revenue': '10000000' # nicety: implementation converts to int for caller 'ebidta': 0 } 'interval': (1528029608, 1528116008) }, '6caBcmLi33...:3:CL:41:tag': { # all attrs, one pred, default intervals to now on attrs & pred '>': { 'regEpoch': 1514782800 } }, ... } :return: indy-sdk proof request json """ LOGGER.debug('Verifier.build_proof_req_json >>> cd_id2spec: %s', cd_id2spec) cd_id2schema = {} now = int(time()) rv = { 'nonce': str(int(time())), 'name': 'proof_req', 'version': '0.0', 'requested_attributes': {}, 'requested_predicates': {} } for cd_id in cd_id2spec: if not ok_cred_def_id(cd_id): LOGGER.debug('Verifier.build_proof_req_json <!< Bad cred def id %s', cd_id) raise BadIdentifier('Bad cred def id {}'.format(cd_id)) interval = None cred_def = json.loads(await self.get_cred_def(cd_id))
python
{ "resource": "" }
q10988
Verifier.load_cache_for_verification
train
async def load_cache_for_verification(self, archive: bool = False) -> int: """ Load schema, cred def, revocation caches; optionally archive enough to go offline and be able to verify proof on content marked of interest in configuration. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :param archive: True to archive now or False to demur (subclasses may still need to augment archivable caches further) :return: cache load event timestamp (epoch seconds) """ LOGGER.debug('Verifier.load_cache_for_verification >>> archive: %s', archive) rv = int(time()) for s_id in self.config.get('archive-verifier-caches-on-close', {}).get('schema_id', {}): if ok_schema_id(s_id): with SCHEMA_CACHE.lock: await self.get_schema(s_id) else: LOGGER.info('Not archiving schema for specified bad id %s', s_id) for cd_id in self.config.get('archive-verifier-caches-on-close', {}).get('cred_def_id', {}): if ok_cred_def_id(cd_id): with CRED_DEF_CACHE.lock: await self.get_cred_def(cd_id) else: LOGGER.info('Not archiving cred def for specified bad id %s', cd_id) for rr_id in self.config.get('archive-verifier-caches-on-close', {}).get('rev_reg_id', {}): if ok_rev_reg_id(rr_id): await self.get_rev_reg_def(rr_id) with REVO_CACHE.lock: revo_cache_entry = REVO_CACHE.get(rr_id, None) if revo_cache_entry: try: await revo_cache_entry.get_state_json(self._build_rr_state_json, rv, rv) except ClosedPool:
python
{ "resource": "" }
q10989
Verifier.check_encoding
train
def check_encoding(proof_req: dict, proof: dict) -> bool: """ Return whether the proof's raw values correspond to their encodings as cross-referenced against proof request. :param proof request: proof request :param proof: corresponding proof to check :return: True if OK, False for encoding mismatch """ LOGGER.debug('Verifier.check_encoding <<< proof_req: %s, proof: %s', proof_req, proof) cd_id2proof_id = {} # invert proof['identifiers'] per cd_id p_preds = {} # cd_id and attr to bound for idx in range(len(proof['identifiers'])): cd_id = proof['identifiers'][idx]['cred_def_id'] cd_id2proof_id[cd_id] = idx # since at most 1 cred per cred def p_preds[cd_id] = { ge_proof['predicate']['attr_name']: ge_proof['predicate']['value'] for ge_proof in proof['proof']['proofs'][idx]['primary_proof']['ge_proofs'] } for (uuid, req_attr) in proof_req['requested_attributes'].items(): # proof req xref proof per revealed attr canon_attr = canon(req_attr['name']) proof_ident_idx = cd_id2proof_id[req_attr['restrictions'][0]['cred_def_id']] enco = proof['proof']['proofs'][proof_ident_idx]['primary_proof']['eq_proof']['revealed_attrs'].get( canon_attr) if not enco: continue # requested but declined from revelation in proof: must appear in a predicate
python
{ "resource": "" }
q10990
PublicKey.to_dict
train
def to_dict(self): """ Return dict representation of public key to embed in DID document. """ return { 'id': self.id, 'type': str(self.type.ver_type),
python
{ "resource": "" }
q10991
main
train
async def main(wallet_name: str) -> None: """ Main line for revocation registry builder operating in external process on behalf of issuer agent. :param wallet_name: wallet name - must match that of issuer with existing wallet """ logging.basicConfig(level=logging.WARN, format='%(levelname)-8s | %(name)-12s | %(message)s') logging.getLogger('indy').setLevel(logging.ERROR) path_start = join(RevRegBuilder.dir_tails_sentinel(wallet_name), '.start') with open(path_start, 'r') as fh_start: start_data = json.loads(fh_start.read()) remove(path_start) logging.getLogger(__name__).setLevel(start_data['logging']['level'])
python
{ "resource": "" }
q10992
RevRegBuilder._start_data_json
train
def _start_data_json(self) -> str: """ Output json with start data to write for external revocation registry builder process pickup. :return: logging and wallet init data json """ rv = { 'logging': { 'paths': [] }, 'wallet': { } } logger = LOGGER while not logger.level: logger = logger.parent if logger is None: break rv['logging']['level'] = logger.level logger = LOGGER log_paths = [realpath(h.baseFilename) for h in logger.handlers if hasattr(h, 'baseFilename')] while not log_paths:
python
{ "resource": "" }
q10993
RevRegBuilder._get_state
train
def _get_state(wallet_name: str) -> _STATE: """ Return current state of revocation registry builder process. :param wallet_name: name of wallet for corresponding Issuer :return: current process state as _STATE enum """ dir_sentinel = RevRegBuilder.dir_tails_sentinel(wallet_name) file_pid = join(dir_sentinel, '.pid') file_start = join(dir_sentinel, '.start')
python
{ "resource": "" }
q10994
RevRegBuilder.dir_tails_top
train
def dir_tails_top(self, rr_id) -> str: """ Return top of tails tree for input rev reg id. :param rr_id: revocation registry identifier :return: top of tails tree
python
{ "resource": "" }
q10995
RevRegBuilder.dir_tails_target
train
def dir_tails_target(self, rr_id) -> str: """ Return target directory for revocation registry and tails file production. :param rr_id: revocation registry identifier
python
{ "resource": "" }
q10996
RevRegBuilder.mark_in_progress
train
def mark_in_progress(self, rr_id: str, rr_size: int) -> None: """ Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build """ try: makedirs(join(self._dir_tails_sentinel, rr_id), exist_ok=False)
python
{ "resource": "" }
q10997
RevRegBuilder.serve
train
async def serve(self) -> None: """ Write pidfile to sentinel directory if need be, and wait for sentinels to shut down or build revocation registry and tails file. """ LOGGER.debug('RevRegBuilder.serve >>>') assert self.external file_pid = join(self._dir_tails_sentinel, '.pid') if isfile(file_pid): with open(file_pid, 'r') as fh_pid: pid = int(fh_pid.read()) try: kill(pid, 0) except ProcessLookupError: remove(file_pid) LOGGER.info('RevRegBuilder removed derelict .pid file') except PermissionError: LOGGER.info('RevRegBuilder process already running with pid %s: exiting', pid) LOGGER.debug('RevRegBuilder.serve <<<') return else: LOGGER.info('RevRegBuilder process already running with pid %s: exiting', pid) LOGGER.debug('RevRegBuilder.serve <<<') return pid = getpid() with open(file_pid, 'w') as pid_fh: print(str(pid), file=pid_fh) file_stop = join(self._dir_tails_sentinel, '.stop') while True:
python
{ "resource": "" }
q10998
RevRegBuilder.stop
train
async def stop(wallet_name: str) -> None: """ Gracefully stop an external revocation registry builder, waiting for its current. The indy-sdk toolkit uses a temporary directory for tails file mustration, and shutting down the toolkit removes the directory, crashing the external tails file write. This method allows a graceful stop to wait for completion of such tasks already in progress. :wallet_name: name external revocation registry builder to check :return: whether a task is pending. """ LOGGER.debug('RevRegBuilder.stop >>>')
python
{ "resource": "" }
q10999
do_ultracache
train
def do_ultracache(parser, token): """Based on Django's default cache template tag""" nodelist = parser.parse(("endultracache",)) parser.delete_first_token() tokens = token.split_contents() if len(tokens) < 3: raise TemplateSyntaxError(""%r" tag requires at least 2 arguments." % tokens[0]) return UltraCacheNode(nodelist,
python
{ "resource": "" }