_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q54600
Table.conv
train
def conv(self,field_name,conv_func): """When a record is returned by a SELECT, ask conversion of specified field value with the specified function""" if field_name not in self.fields: raise NameError,"Unknown field %s" %field_name self.conv_func[field_name] = conv_func
python
{ "resource": "" }
q54601
Table.update
train
def update(self,record,**kw): """Update the record with new keys and values""" vals = self._make_sql_params(kw) sql = "UPDATE %s SET %s WHERE rowid=?" %(self.name, ",".join(vals)) self.cursor.execute(sql,kw.values()+[record['__id__']])
python
{ "resource": "" }
q54602
faasport
train
def faasport(func: Faasport) -> Faasport: """Decorator that registers the user's faasport function.""" global user_faasport if user_faasport is not None: raise RuntimeError('Multiple definitions of faasport.') user_faasport = func return func
python
{ "resource": "" }
q54603
NoSqlBase._find_parameter
train
def _find_parameter(cls, dct): '''Search for the 'key=True' case, and confirm no more than one parameter has that property.''' num_found = 0 field = None for key, val in dct.iteritems(): if isinstance(val, DataType) and val.is_key: field = key ...
python
{ "resource": "" }
q54604
URI.uri
train
def uri(self): """Cache to prevent recalculating URI unless necessary""" if self.__modified: self.__uri = self.__parse_uri() return self.__uri
python
{ "resource": "" }
q54605
URI.uri
train
def uri(self, value): """Attempt to validate URI and split into individual values""" if value == self.__uri: return match = URI_REGEX.match(value) if match is None: raise ValueError('Unable to match URI from `{}`'.format(value)) for key, value in match.g...
python
{ "resource": "" }
q54606
URI.__parse_uri
train
def __parse_uri(self): """Parse complete URI from all values""" if self.scheme: scheme = '{}://'.format(self.scheme) else: scheme = '' credentials = self.username or '' password = self.password or '' if credentials and password: crede...
python
{ "resource": "" }
q54607
write_path
train
def write_path(target, path, value, separator='/'): """Write a value deep into a dict building any intermediate keys. :param target: a dict to write data to :param path: a key or path to a key (path is delimited by `separator`) :param value: the value to write to the key :keyword separator: the sep...
python
{ "resource": "" }
q54608
read_path
train
def read_path(source, path, separator='/'): """Read a value from a dict supporting a deep path as a key. :param source: a dict to read data from :param path: a key or path to a key (path is delimited by `separator`) :keyword separator: the separator used in the path (ex. Could be "." for a json...
python
{ "resource": "" }
q54609
path_exists
train
def path_exists(source, path, separator='/'): """Check a dict for the existence of a value given a path to it. :param source: a dict to read data from :param path: a key or path to a key (path is delimited by `separator`) :keyword separator: the separator used in the path (ex. Could be "." for a ...
python
{ "resource": "" }
q54610
split_dict
train
def split_dict(data, filter_keys=None): # flake8: noqa """Deep extract matching keys into separate dict. Extracted data is placed into another dict. The function returns two dicts; one without the filtered data and one with only the filtered data. The dicts are structured so that they can be recombine...
python
{ "resource": "" }
q54611
merge_dictionary
train
def merge_dictionary(dst, src, extend_lists=False): """Recursively merge two dicts. Hashes at the root level are NOT overwritten. This can be used to merge two dicts using deep key evaluation (with support for merging lists as well). There is also logic to handle placeholders (`None`) in lists as docu...
python
{ "resource": "" }
q54612
merge_lists
train
def merge_lists(dest, source, extend_lists=False): """Recursively merge two lists. :keyword extend_lists: if true, just extends lists instead of merging them. This applies merge_dictionary if any of the entries are dicts. Note: This updates dest and returns it. """ if not source: retur...
python
{ "resource": "" }
q54613
kwarg
train
def kwarg(string, separator='='): """Return a dict from a delimited string.""" if separator not in string: raise ValueError("Separator '%s' not in value '%s'" % (separator, string)) if string.strip().startswith(separator): raise ValueError("Value '%s' starts with sep...
python
{ "resource": "" }
q54614
HelpfulParser.error
train
def error(self, message, print_help=False): """Provide a more helpful message if there are too few arguments.""" if 'too few arguments' in message.lower(): target = sys.argv.pop(0) sys.argv.insert( 0, os.path.basename(target) or os.path.relpath(target)) ...
python
{ "resource": "" }
q54615
finishOpenID
train
def finishOpenID(request): """ Finish the OpenID authentication process. Invoke the OpenID library with the response from the OpenID server and render a page detailing the result. """ result = {} # Because the object containing the query parameters is a # MultiValueDict and the OpenID ...
python
{ "resource": "" }
q54616
Collector.collect
train
def collect(self, file_paths): """ Takes in a list of string file_paths, and parses through them using the converter, strategies, and switches defined at object initialization. It returns two dictionaries- the first maps from file_path strings to inner dictionaries, and ...
python
{ "resource": "" }
q54617
Collector.collect_single_file
train
def collect_single_file(self, file_path): """ Takes in a list of strings, usually the lines in a text file, and collects the AnchorHub tags and auto-generated anchors for the file according to the Collector's converter, strategies, and switches :param file_path: string file pat...
python
{ "resource": "" }
q54618
Collector._try_switches
train
def _try_switches(self, lines, index): """ For each switch in the Collector object, pass a list of string, representing lines of text in a file, and an index to the current line to try to flip the switch. A switch will only flip on if the line passes its 'test_on' method, and wil...
python
{ "resource": "" }
q54619
install_gitflow
train
def install_gitflow(): """Install git-flow if not found""" if not run('which git-flow', hide=True, warn=True).ok: run('wget --no-check-certificate -q -O /tmp/gitflow-installer.sh https://raw.github.com/petervanderdoes/gitflow/develop/contrib/gitflow-installer.sh') run('sudo bash /tmp/gitflow-in...
python
{ "resource": "" }
q54620
finish_rel_branch
train
def finish_rel_branch(relver): """Finish release branch""" print('finish release branch', relver) run('git flow release finish --keepremote -F -p -m "version {ver}" {ver}'.format(ver=relver), hide=True)
python
{ "resource": "" }
q54621
_iter_changelog
train
def _iter_changelog(changelog): """Convert a oneline log iterator to formatted strings. :param changelog: An iterator of one line log entries like that given by _iter_log_oneline. :return: An iterator over (release, formatted changelog) tuples. """ first_line = True current_release = No...
python
{ "resource": "" }
q54622
write_changelog
train
def write_changelog(debug=False): """Write a changelog based on the git changelog.""" changelog = _iter_log_oneline(debug) if changelog: changelog = _iter_changelog(changelog) if not changelog: return if debug: print('Writing ChangeLog') new_changelog = os.path.join(os.pa...
python
{ "resource": "" }
q54623
prepare_release
train
def prepare_release(ver=None): """Prepare release artifacts""" write_changelog(True) if ver is None: ver = next_release() print('saving updates to ChangeLog') run('git commit ChangeLog -m "[RELEASE] Update to version v{}"'.format(ver), hide=True) sha = run('git log -1 --pretty=format:"%h...
python
{ "resource": "" }
q54624
publish
train
def publish(idx=None): """Publish packaged distributions to pypi index""" if idx is None: idx = '' else: idx = '-r ' + idx run('python setup.py register {}'.format(idx)) run('twine upload {} dist/*.whl dist/*.egg dist/*.tar.gz'.format(idx))
python
{ "resource": "" }
q54625
release
train
def release(major=False, minor=False, patch=True, pypi_index=None): """Overall process flow for performing a release""" relver = next_release(major, minor, patch) start_rel_branch(relver) prepare_release(relver) finish_rel_branch(relver) publish(pypi_index)
python
{ "resource": "" }
q54626
clean
train
def clean(all=False, docs=False, dist=False, extra=None): """Clean up build files""" run('find . -type f -name "*.py[co]" -delete') run('find . -type d -name "__pycache__" -delete') patterns = ['build', '*.egg-info/'] if all or docs: patterns.append('doc/build/*') if all or dist: ...
python
{ "resource": "" }
q54627
LinesNumbers_QWidget.get_width
train
def get_width(self): """ Returns the Widget target width. :return: Widget target width. :rtype: int """ return self.__margin + \ self.__editor.fontMetrics().width(foundations.strings.to_string(max(1, self.__editor.blockCount())))
python
{ "resource": "" }
q54628
LinesNumbers_QWidget.update_rectangle
train
def update_rectangle(self, rectangle, scroll_y): """ Updates the given Widget rectangle. :param rectangle: Rectangle to update. :type rectangle: QRect :param scroll_y: Amount of pixels the viewport was scrolled. :type scroll_y: int :return: Method success. ...
python
{ "resource": "" }
q54629
LinesNumbers_QWidget.update_geometry
train
def update_geometry(self): """ Updates the Widget geometry. :return: Method success. :rtype: bool """ self.setGeometry(self.__editor.contentsRect().left(), self.__editor.contentsRect().top(), self.get_width(), ...
python
{ "resource": "" }
q54630
CodeEditor_QPlainTextEdit.__insert_completion
train
def __insert_completion(self, completion): """ Inserts the completion text in the current document. :param completion: Completion text. :type completion: QString """ LOGGER.debug("> Inserting '{0}' completion.".format(completion)) text_cursor = self.textCursor(...
python
{ "resource": "" }
q54631
CodeEditor_QPlainTextEdit.__set_language_description
train
def __set_language_description(self): """ Sets the language accelerators. """ LOGGER.debug("> Setting language description.") if not self.__language: return if self.__language.highlighter: self.set_highlighter(self.__language.highlighter(self.do...
python
{ "resource": "" }
q54632
CodeEditor_QPlainTextEdit.set_language
train
def set_language(self, language): """ Sets the language. :param language: Language to set. :type language: Language :return: Method success. :rtype: bool """ LOGGER.debug("> Setting editor language to '{0}'.".format(language.name)) self.__languag...
python
{ "resource": "" }
q54633
CodeEditor_QPlainTextEdit.set_highlighter
train
def set_highlighter(self, highlighter): """ Sets given highlighter as the current document highlighter. :param highlighter: Highlighter. :type highlighter: QSyntaxHighlighter :return: Method success. :rtype: bool """ if not issubclass(highlighter.__class...
python
{ "resource": "" }
q54634
CodeEditor_QPlainTextEdit.remove_highlighter
train
def remove_highlighter(self): """ Removes current highlighter. :return: Method success. :rtype: bool """ if self.__highlighter: LOGGER.debug("> Removing '{0}' highlighter.".format(self.__highlighter)) self.__highlighter.deleteLater() ...
python
{ "resource": "" }
q54635
CodeEditor_QPlainTextEdit.set_completer
train
def set_completer(self, completer): """ Sets given completer as the current completer. :param completer: Completer. :type completer: QCompleter :return: Method success. :rtype: bool """ if not issubclass(completer.__class__, QCompleter): rais...
python
{ "resource": "" }
q54636
CodeEditor_QPlainTextEdit.remove_completer
train
def remove_completer(self): """ Removes current completer. :return: Method success. :rtype: bool """ if self.__completer: LOGGER.debug("> Removing '{0}' completer.".format(self.__completer)) # Signals / Slots. self.__completer.activat...
python
{ "resource": "" }
q54637
CodeEditor_QPlainTextEdit.get_matching_symbols_pairs
train
def get_matching_symbols_pairs(self, cursor, opening_symbol, closing_symbol, backward=False): """ Returns the cursor for matching given symbols pairs. :param cursor: Cursor to match from. :type cursor: QTextCursor :param opening_symbol: Opening symbol. :type opening_symb...
python
{ "resource": "" }
q54638
CodeEditor_QPlainTextEdit.indent
train
def indent(self): """ Indents the document text under cursor. :return: Method success. :rtype: bool """ cursor = self.textCursor() if not cursor.hasSelection(): cursor.insertText(self.__indent_marker) else: block = self.document()...
python
{ "resource": "" }
q54639
CodeEditor_QPlainTextEdit.unindent
train
def unindent(self): """ Unindents the document text under cursor. :return: Method success. :rtype: bool """ cursor = self.textCursor() if not cursor.hasSelection(): cursor.movePosition(QTextCursor.StartOfBlock) line = foundations.strings....
python
{ "resource": "" }
q54640
CodeEditor_QPlainTextEdit.toggle_comments
train
def toggle_comments(self): """ Toggles comments on the document selected lines. :return: Method success. :rtype: bool """ if not self.__comment_marker: return True cursor = self.textCursor() if not cursor.hasSelection(): cursor.m...
python
{ "resource": "" }
q54641
CodeEditor_QPlainTextEdit.remove_trailing_white_spaces
train
def remove_trailing_white_spaces(self): """ Removes document trailing white spaces. :return: Method success. :rtype: bool """ cursor = self.textCursor() block = self.document().findBlockByLineNumber(0) while block.isValid(): cursor.setPositi...
python
{ "resource": "" }
q54642
CodeEditor_QPlainTextEdit.convert_indentation_to_tabs
train
def convert_indentation_to_tabs(self): """ Converts document indentation to tabs. :return: Method success. :rtype: bool """ cursor = self.textCursor() block = self.document().findBlockByLineNumber(0) while block.isValid(): cursor.setPosition...
python
{ "resource": "" }
q54643
modified_environ
train
def modified_environ(added=None, absent=()): """ Temporarily updates the os.environ dictionary in-place. Can be used as a context manager or a decorator. The os.environ dictionary is updated in-place so that the modification is sure to work in all situations. :param added: Dictionary of enviro...
python
{ "resource": "" }
q54644
itervalues
train
def itervalues(d, **kw): """Return an iterator over the values of a dictionary.""" if not PY2: return iter(d.values(**kw)) return d.itervalues(**kw)
python
{ "resource": "" }
q54645
Tokenizer.__get_tokens
train
def __get_tokens(self, row): """Row should be a single string""" row_tokenizer = RowTokenizer(row, self.config) line = row_tokenizer.next() while line: # print("RETURN line", line[0:100]) yield line line = row_tokenizer.next()
python
{ "resource": "" }
q54646
cursor
train
def cursor(): """Database cursor generator. Commit on context exit.""" try: cur = conn.cursor() yield cur except (db.Error, Exception) as e: cur.close() if conn: conn.rollback() print(e.message) raise else: conn.commit() cur.clo...
python
{ "resource": "" }
q54647
Grapple.download
train
def download(self): """ Walk from the current ledger index to the genesis ledger index, and download transactions from rippled. """ self.housekeeping() self.rippled_history() if self.resampling_frequencies is not None: self.find_markets() s...
python
{ "resource": "" }
q54648
get_clear_pin
train
def get_clear_pin(pinblock, account_number): """ Calculate the clear PIN from provided PIN block and account_number, which is the 12 right-most digits of card account number, excluding check digit """ raw_pinblock = bytes.fromhex(pinblock.decode('utf-8')) raw_acct_num = bytes.fromhex((b'0000' + acco...
python
{ "resource": "" }
q54649
parityOf
train
def parityOf(int_type): """ Calculates the parity of an integer, returning 0 if there are an even number of set bits, and -1 if there are an odd number. """ parity = 0 while (int_type): parity = ~parity int_type = int_type & (int_type - 1) return(parity)
python
{ "resource": "" }
q54650
modify_key_parity
train
def modify_key_parity(key): """ The prior use of the function is to return the parity-validated key. The incoming key is expected to be hex data binary representation, e.g. b'E7A3C8B1' """ validated_key = b'' for byte in key: if parityOf(int(byte)) == -1: byte_candidate = in...
python
{ "resource": "" }
q54651
Notification_QLabel.__raise
train
def __raise(self, *args): """ Ensures that the Widget stays on top of the parent stack forcing the redraw. :param \*args: Arguments. :type \*args: \* """ children = self.parent().children().remove(self) if children: self.stackUnder(children[-1]) ...
python
{ "resource": "" }
q54652
Notification_QLabel.__set_position
train
def __set_position(self): """ Sets the Widget position relatively to its parent. """ rectangle = hasattr(self.parent(), "viewport") and self.parent().viewport().rect() or self.parent().rect() if not rectangle: return self.adjustSize() if self.__anch...
python
{ "resource": "" }
q54653
Notification_QLabel.__fade_in
train
def __fade_in(self): """ Starts the Widget fade in. """ self.__timer.stop() self.__vector = self.__fade_speed self.__timer.start()
python
{ "resource": "" }
q54654
Notification_QLabel.__fade_out
train
def __fade_out(self): """ Starts the Widget fade out. """ self.__timer.stop() self.__vector = -self.__fade_speed self.__timer.start()
python
{ "resource": "" }
q54655
Notification_QLabel.__set_opacity
train
def __set_opacity(self): """ Sets the Widget opacity. """ if self.__vector > 0: if self.isHidden(): self.show() if self.opacity <= self.__target_opacity: self.opacity += self.__vector else: self.__timer....
python
{ "resource": "" }
q54656
Notification_QLabel.show_message
train
def show_message(self, message, duration=2500): """ Shows given message. :param message: Message. :type message: unicode :param duration: Notification duration in milliseconds. :type duration: int :return: Method success. :rtype: bool """ ...
python
{ "resource": "" }
q54657
execute_git_command
train
def execute_git_command(command, repo_dir=None): """Execute a git command and return the output. Catches CalledProcessErrors and OSErrors, wrapping them in a more useful :class:`~simpl.exceptions.SimplGitCommandError`. Raises :class:`~simpl.exceptions.SimplGitCommandError` if the command fails. Re...
python
{ "resource": "" }
q54658
check_git_version
train
def check_git_version(): """Check the installed git version against a known-stable version. If the git version is less then ``MIN_GIT_VERSION``, a warning is raised. If git is not installed at all on this system, we also raise a warning for that. The original reason why this check was introduced ...
python
{ "resource": "" }
q54659
git_clone
train
def git_clone(target_dir, repo_location, branch_or_tag=None, verbose=True): """Clone repo at repo_location to target_dir and checkout branch_or_tag. If branch_or_tag is not specified, the HEAD of the primary branch of the cloned repo is checked out. """ target_dir = pipes.quote(target_dir) comm...
python
{ "resource": "" }
q54660
git_tag
train
def git_tag(repo_dir, tagname, message=None, force=True): """Create an annotated tag at the current head.""" message = message or "%s" % tagname command = ['git', 'tag', '--annotate', '--message', message] if force: command.append('--force') # append the tag as the final arg command.appe...
python
{ "resource": "" }
q54661
git_list_config
train
def git_list_config(repo_dir): """Return a list of the git configuration.""" command = ['git', 'config', '--list'] raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = {key: val for key, val in [cfg.split('=', 1) for cfg in raw]} # TODO(sam): maybe turn this into...
python
{ "resource": "" }
q54662
git_list_tags
train
def git_list_tags(repo_dir, with_messages=False): """Return a list of git tags for the git repo in `repo_dir`.""" command = ['git', 'tag', '-l'] if with_messages: command.append('-n1') raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = [l.strip() for l in raw if l.st...
python
{ "resource": "" }
q54663
git_list_branches
train
def git_list_branches(repo_dir): """Return a list of git branches for the git repo in 'repo_dir'. .. code-block:: python [ {'branch': <branchname>, 'commit': <commit_hash>, 'message': <commit message>}, {...}, ] """ command = ['git', 'b...
python
{ "resource": "" }
q54664
git_list_remotes
train
def git_list_remotes(repo_dir): """Return a listing of configured remotes.""" command = ['git', 'remote', '--verbose', 'show'] raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = [l.strip() for l in raw if l.strip()] # <name> <location> (<cmd>) # make a list of lists with...
python
{ "resource": "" }
q54665
git_list_refs
train
def git_list_refs(repo_dir): """List references available in the local repo with commit ids. This is similar to ls-remote, but shows the *local* refs. Return format: .. code-block:: python {<ref1>: <commit_hash1>, <ref2>: <commit_hash2>, ..., <refN>: <commit_hashN>...
python
{ "resource": "" }
q54666
git_ls_remote
train
def git_ls_remote(repo_dir, remote='origin', refs=None): """Run git ls-remote. 'remote' can be a remote ref in a local repo, e.g. origin, or url of a remote repository. Return format: .. code-block:: python {<ref1>: <commit_hash1>, <ref2>: <commit_hash2>, ..., ...
python
{ "resource": "" }
q54667
git_checkout
train
def git_checkout(repo_dir, ref, branch=None): """Do a git checkout of `ref` in `repo_dir`. If branch is specified it should be the name of the new branch. """ command = ['git', 'checkout', '--force'] if branch: command.extend(['-B', '{}'.format(branch)]) command.append(ref) return e...
python
{ "resource": "" }
q54668
git_fetch
train
def git_fetch(repo_dir, remote=None, refspec=None, verbose=False, tags=True): """Do a git fetch of `refspec` in `repo_dir`. If 'remote' is None, all remotes will be fetched. """ command = ['git', 'fetch'] if not remote: command.append('--all') else: remote = pipes.quote(remote) ...
python
{ "resource": "" }
q54669
git_ls_tree
train
def git_ls_tree(repo_dir, treeish='HEAD'): """Run git ls-tree.""" command = ['git', 'ls-tree', '-r', '--full-tree', treeish] raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = [l.strip() for l in raw if l.strip()] # <mode> <type> <object> <file> # make a list of lists wi...
python
{ "resource": "" }
q54670
is_git_repo
train
def is_git_repo(repo_dir): """Return True if the directory is inside a git repo.""" command = ['git', 'rev-parse'] try: execute_git_command(command, repo_dir=repo_dir) except exceptions.SimplGitCommandError: return False else: return True
python
{ "resource": "" }
q54671
_cleanup_tempdir
train
def _cleanup_tempdir(tempdir): """Clean up temp directory ignoring ENOENT errors.""" try: shutil.rmtree(tempdir) except OSError as err: if err.errno != errno.ENOENT: raise
python
{ "resource": "" }
q54672
create_tempdir
train
def create_tempdir(suffix='', prefix='tmp', directory=None, delete=True): """Create a tempdir and return the path. This function registers the new temporary directory for deletion with the atexit module. """ tempd = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=directory) if delete: ...
python
{ "resource": "" }
q54673
GitRepo.clone
train
def clone(cls, repo_location, repo_dir=None, branch_or_tag=None, temp=False): """Clone repo at repo_location into repo_dir and checkout branch_or_tag. Defaults into current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for...
python
{ "resource": "" }
q54674
GitRepo.init
train
def init(cls, repo_dir=None, temp=False, initial_commit=False): """Run `git init` in the repo_dir. Defaults to current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be initialized. The tempdir is ...
python
{ "resource": "" }
q54675
GitRepo.origin
train
def origin(self): """Show where the 'origin' remote ref points. Returns None if the 'origin' remote ref does not exist. If 'origin' has different locations for different commands, the result is ambiguous and None is returned. Notes: A repo does not necessarily have...
python
{ "resource": "" }
q54676
GitRepo.tag
train
def tag(self, tagname, message=None, force=True): """Create an annotated tag.""" return git_tag(self.repo_dir, tagname, message=message, force=force)
python
{ "resource": "" }
q54677
GitRepo.ls_remote
train
def ls_remote(self, remote='origin', refs=None): """Return a mapping of refs to commit ids for the given remote. 'remote' can be a remote ref in a local repo, e.g. origin, or url of a remote repository. Returns:: {<ref1>: <commit_hash1>, <ref2>: <commit_hash2>...
python
{ "resource": "" }
q54678
GitRepo.checkout
train
def checkout(self, ref, branch=None): """Do a git checkout of `ref`.""" return git_checkout(self.repo_dir, ref, branch=branch)
python
{ "resource": "" }
q54679
GitRepo.fetch
train
def fetch(self, remote=None, refspec=None, verbose=False, tags=True): """Do a git fetch of `refspec`.""" return git_fetch(self.repo_dir, remote=remote, refspec=refspec, verbose=verbose, tags=tags)
python
{ "resource": "" }
q54680
GitRepo.remote_resolve_reference
train
def remote_resolve_reference(self, ref, remote='origin'): """Resolve a reference to a remote revision.""" return git_remote_resolve_reference(self.repo_dir, ref, remote=remote)
python
{ "resource": "" }
q54681
_get_config
train
def _get_config(): ''' Get user docker configuration Return: dict ''' cfg = os.path.expanduser('~/.dockercfg') try: fic = open(cfg) try: config = json.loads(fic.read()) finally: fic.close() except Exception: config = {'rootPath': '/dev...
python
{ "resource": "" }
q54682
_set_id
train
def _set_id(infos): ''' ID compatibility hack return: dict ''' if infos: cid = None if infos.get("Id"): cid = infos["Id"] elif infos.get("ID"): cid = infos["ID"] elif infos.get("id"): cid = infos["id"] if "Id" not in infos: infos["Id"] = cid ...
python
{ "resource": "" }
q54683
_get_container_infos
train
def _get_container_infos(config, container): ''' Get container infos container Image Id / grain name return: dict ''' client = _get_client(config) infos = None try: infos = _set_id(client.inspect_container(container)) except Exception: pass return infos
python
{ "resource": "" }
q54684
is_running
train
def is_running(config, container, *args, **kwargs): ''' Is this container running container Container id Return container ''' try: infos = _get_container_infos(config, container) return (infos if infos.get('State', {}).get('Running') else None) except Exception: ...
python
{ "resource": "" }
q54685
_parse_image_multilogs_string
train
def _parse_image_multilogs_string(config, ret, repo): ''' Parse image log strings into grokable data ''' image_logs, infos = [], None if ret and ret.strip().startswith('{') and ret.strip().endswith('}'): pushd = 0 buf = '' for char in ret: buf += char ...
python
{ "resource": "" }
q54686
stop
train
def stop(config, container, timeout=10, *args, **kwargs): ''' Stop a running container :type container: string :param container: The container id to stop :type timeout: int :param timeout: Wait for a timeout to let the container exit gracefully before killing it :rtype: dict :...
python
{ "resource": "" }
q54687
kill
train
def kill(config, container, *args, **kwargs): ''' Kill a running container :type container: string :param container: The container id to kill :rtype: dict :returns: boolean ''' err = "Unknown" client = _get_client(config) try: dcontainer = _get_container_infos(config, c...
python
{ "resource": "" }
q54688
remove_container
train
def remove_container(config, container=None, force=True, v=False, *args, **kwargs): ''' Removes a container from a docker installation container Container id to remove force By default, remove a running container, set this to notremove it unconditionally v verbose mo...
python
{ "resource": "" }
q54689
restart
train
def restart(config, container, timeout=10, *args, **kwargs): ''' Restart a running container :type container: string :param container: The container id to restart :type timout: int :param timeout: Wait for a timeout to let the container exit gracefully before killing it :rtype: di...
python
{ "resource": "" }
q54690
start
train
def start(config, container, binds=None, ports=None, port_bindings=None, lxc_conf=None, publish_all_ports=None, links=None, privileged=False, *args, **kwargs): ''' Start the specified container container Container id Returns boolean ''' if not binds: ...
python
{ "resource": "" }
q54691
get_images
train
def get_images(config, name=None, quiet=False, all=True, *args, **kwargs): ''' List docker images :type name: string :param name: A repository name to filter on :type quiet: boolean :param quiet: Only show image ids :type all: boolean :param all: Show all images :rtype: dict ...
python
{ "resource": "" }
q54692
get_containers
train
def get_containers(config, all=True, trunc=False, since=None, before=None, limit=-1, *args, **kwargs): ''' Get a list of mappings representing all containers all Retu...
python
{ "resource": "" }
q54693
login
train
def login(config, username=None, password=None, email=None, url=None, client=None, *args, **kwargs): ''' Wrapper to the docker.py login method ''' try: c = (_get_client(config) if not client else client) lg = c.login(username, password, email, url) print "%s logged to %s"%(userna...
python
{ "resource": "" }
q54694
pull
train
def pull(config, repo, tag=None, username=None, password=None, email=None, *args, **kwargs): ''' Pulls an repo from any registry. See above documentation for how to configure authenticated access. :type repo: string :param repo: The repository to pull. \ [registryurl://]REPOSITORY_NAME ...
python
{ "resource": "" }
q54695
ProjectsExplorer.__raise_file_system_exception
train
def __raise_file_system_exception(self, item, directory): """ Raises a common fileSystem exception. :param item: Name of the item generating the exception. :type item: unicode :param directory: Name of the target directory. :type directory: unicode """ p...
python
{ "resource": "" }
q54696
ProjectsExplorer.__set_authoring_nodes
train
def __set_authoring_nodes(self, source, target): """ Sets given editor authoring nodes. :param source: Source file. :type source: unicode :param target: Target file. :type target: unicode """ editor = self.__script_editor.get_editor(source) edito...
python
{ "resource": "" }
q54697
ProjectsExplorer.__rename_path
train
def __rename_path(self, source, target): """ Renames given source with given target name. :param source: Source file. :type source: unicode :param target: Target file. :type target: unicode """ if not foundations.common.path_exists(source): r...
python
{ "resource": "" }
q54698
ProjectsExplorer.__delete_path
train
def __delete_path(self, path): """ Deletes given path. :param path: Path to delete. :type path: unicode """ if not foundations.common.path_exists(path): return parent_directory = os.path.dirname(path) is_path_registered = self.__engine.file_...
python
{ "resource": "" }
q54699
ProjectsExplorer.__rename_file
train
def __rename_file(self, source, target): """ Renames a file using given source and target names. :param source: Source file. :type source: unicode :param target: Target file. :type target: unicode """ for file_node in self.__script_editor.model.get_file_...
python
{ "resource": "" }