_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q54400
SerializerContext.serialize
train
def serialize(self, tag): """Serialize tag and print it to the output.""" try: tag.serialize(self) except (AttributeError, TypeError): self.write(str(tag))
python
{ "resource": "" }
q54401
TagBase.set_children
train
def set_children(self, value, defined): """Set the children of the object.""" self.children = value self.children_defined = defined return self
python
{ "resource": "" }
q54402
_SpanTagImpl.set_children
train
def set_children(self, children): """Set children of the span block.""" if isinstance(children, tuple): self._children = list(children) else: self._children = [children] return self
python
{ "resource": "" }
q54403
Pushed.push_app
train
def push_app(self, content, content_url=None): '''Push a notification to a Pushed application. Param: content -> content of Pushed notification message content_url (optional) -> enrich message with URL Returns Shipment ID as string ''' parameters = { '...
python
{ "resource": "" }
q54404
Pushed.push_channel
train
def push_channel(self, content, channel, content_url=None): '''Push a notification to a Pushed channel. Param: content -> content of Pushed notification message channel -> string identifying a Pushed channel content_url (optional) -> enrich message with URL Returns...
python
{ "resource": "" }
q54405
Pushed.push_user
train
def push_user(self, content, access_token, content_url=None): '''Push a notification to a specific pushed user. Param: content -> content of Pushed notification message access_token -> OAuth access token content_url (optional) -> enrich message with URL Returns Shi...
python
{ "resource": "" }
q54406
Pushed.push_pushed_id
train
def push_pushed_id(self, content, pushed_id, content_url=None): '''Push a notification to a specific pushed user by Pushed ID. Param: content -> content of Pushed notification message pushed_id -> user's pushed ID content_url (optional) -> enrich message with URL R...
python
{ "resource": "" }
q54407
Pushed.access_token
train
def access_token(self, code): '''Exchange a temporary OAuth2 code for an access token. Param: code -> temporary OAuth2 code from a Pushed callback Returns access token as string ''' parameters = {"code": code} access_uri = "/".join([BASE_URL, API_VERSION, ACCESS_TOKEN]) ...
python
{ "resource": "" }
q54408
Pushed.authorization_link
train
def authorization_link(self, redirect_uri): '''Construct OAuth2 authorization link. Params: redirect_uri -> URI for receiving callback with token Returns authorization URL as string ''' args = '?client_id=%s&redirect_uri=%s' % ( self.app_key, redirect_...
python
{ "resource": "" }
q54409
get_admins_from_django
train
def get_admins_from_django(homedir): return ["root@localhost"] """ Get admin's emails from django settings """ path = homedir + "/settings/basic.py" if not os.path.exists(path): path = homedir + "/settings.py" if not os.path.exists(path): return mod = compiler.parseFile(path) ...
python
{ "resource": "" }
q54410
send_mail
train
def send_mail(subject, body, email_from, emails_to): """ Funxtion for sending email though gmail """ msg = MIMEText(body) msg['Subject'] = subject msg['From'] = email_from msg['To'] = ", ".join(emails_to) s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() # for tls add this line s.starttl...
python
{ "resource": "" }
q54411
format_argspec_plus
train
def format_argspec_plus(fn, grouped=True): """Returns a dictionary of formatted, introspected function arguments. A enhanced variant of inspect.formatargspec to support code generation. fn An inspectable callable or tuple of inspect getargspec() results. grouped Defaults to True; include ...
python
{ "resource": "" }
q54412
decorator
train
def decorator(target): """A signature-matching decorator factory.""" def decorate(fn): spec = inspect.getargspec(fn) names = tuple(spec[0]) + spec[1:3] + (fn.__name__,) targ_name, fn_name = unique_symbols(names, 'target', 'fn') metadata = dict(target=targ_name, fn=fn_name) ...
python
{ "resource": "" }
q54413
_num_required_args
train
def _num_required_args(func): """ Number of args for func >>> def foo(a, b, c=None): ... return a + b + c >>> _num_required_args(foo) 2 >>> def bar(*args): ... return sum(args) >>> print(_num_required_args(bar)) None borrowed from: https:/...
python
{ "resource": "" }
q54414
deprecate
train
def deprecate(message): """ Decorate a function to emit a deprecation warning with the given message. """ @decorator def decorate(fn, *args, **kw): warnings.warn(message, DeprecationWarning, 2) return fn(*args, **kw) return decorate
python
{ "resource": "" }
q54415
exc_emailer
train
def exc_emailer(send_mail_func, logger=None, catch=Exception, print_to_stderr=True): """ Catch exceptions and email them using `send_mail_func` which should accept a single string argument which will be the traceback to be emailed. Will re-raise original exception if calling `send_mail_func`...
python
{ "resource": "" }
q54416
memoize
train
def memoize(method_to_wrap): """ Currently only works on instance methods. Designed for use with SQLAlchemy entities. Could be updated in the future to be more flexible. class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) a...
python
{ "resource": "" }
q54417
edit_block
train
def edit_block(object): """ Handles edit blocks undo states. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def edit_block_wrapper(*args, **kwargs): """ Handles edit blocks undo states. :...
python
{ "resource": "" }
q54418
anchor_text_cursor
train
def anchor_text_cursor(object): """ Anchors the text cursor position. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def anchor_text_cursorWrapper(*args, **kwargs): """ Anchors the text cursor pos...
python
{ "resource": "" }
q54419
center_text_cursor
train
def center_text_cursor(object): """ Centers the text cursor position. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def center_text_cursor_wrapper(*args, **kwargs): """ Centers the text cursor po...
python
{ "resource": "" }
q54420
Basic_QPlainTextEdit.__select_text_under_cursor_blocks
train
def __select_text_under_cursor_blocks(self, cursor): """ Selects the document text under cursor blocks. :param cursor: Cursor. :type cursor: QTextCursor """ start_block = self.document().findBlock(cursor.selectionStart()).firstLineNumber() end_block = self.docum...
python
{ "resource": "" }
q54421
Basic_QPlainTextEdit.get_selected_text_metrics
train
def get_selected_text_metrics(self): """ Returns current document selected text metrics. :return: Selected text metrics. :rtype: tuple """ selected_text = self.get_selected_text() if not selected_text: return tuple() return (selected_text, s...
python
{ "resource": "" }
q54422
Basic_QPlainTextEdit.store_text_cursor_anchor
train
def store_text_cursor_anchor(self): """ Stores the document cursor anchor. :return: Method success. :rtype: bool """ self.__text_cursor_anchor = (self.textCursor(), self.horizontalScrollBar().sliderPosition(), ...
python
{ "resource": "" }
q54423
Basic_QPlainTextEdit.restore_text_cursor_anchor
train
def restore_text_cursor_anchor(self): """ Restores the document cursor anchor. :return: Method success. :rtype: bool """ if not self.__text_cursor_anchor: return False text_cursor, horizontal_scroll_bar_slider_position, vertical_scroll_bar_slider_po...
python
{ "resource": "" }
q54424
Basic_QPlainTextEdit.get_previous_character
train
def get_previous_character(self): """ Returns the character before the cursor. :return: Previous cursor character. :rtype: QString """ cursor = self.textCursor() cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor) return cursor.sel...
python
{ "resource": "" }
q54425
Basic_QPlainTextEdit.get_next_character
train
def get_next_character(self): """ Returns the character after the cursor. :return: Next cursor character. :rtype: QString """ cursor = self.textCursor() cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) return cursor.selectedText()
python
{ "resource": "" }
q54426
Basic_QPlainTextEdit.get_words
train
def get_words(self): """ Returns the document words. :return: Document words. :rtype: list """ words = [] block = self.document().findBlockByLineNumber(0) while block.isValid(): blockWords = foundations.strings.get_words(foundations.strings.t...
python
{ "resource": "" }
q54427
Basic_QPlainTextEdit.get_word_under_cursor
train
def get_word_under_cursor(self): """ Returns the document word under cursor. :return: Word under cursor. :rtype: QString """ if not re.match(r"^\w+$", foundations.strings.to_string(self.get_previous_character())): return QString() cursor = self.text...
python
{ "resource": "" }
q54428
Basic_QPlainTextEdit.set_content
train
def set_content(self, content): """ Sets document with given content while providing undo capability. :param content: Content to set. :type content: list :return: Method success. :rtype: bool """ cursor = self.textCursor() cursor.movePosition(QTe...
python
{ "resource": "" }
q54429
Basic_QPlainTextEdit.delete_lines
train
def delete_lines(self): """ Deletes the document lines under cursor. :return: Method success. :rtype: bool """ cursor = self.textCursor() self.__select_text_under_cursor_blocks(cursor) cursor.removeSelectedText() cursor.deleteChar() retur...
python
{ "resource": "" }
q54430
Basic_QPlainTextEdit.duplicate_lines
train
def duplicate_lines(self): """ Duplicates the document lines under cursor. :return: Method success. :rtype: bool """ cursor = self.textCursor() self.__select_text_under_cursor_blocks(cursor) text = cursor.selectedText() cursor.setPosition(cursor...
python
{ "resource": "" }
q54431
Basic_QPlainTextEdit.move_lines
train
def move_lines(self, direction=QTextCursor.Up): """ Moves the document lines under cursor. :param direction: Move direction ( QTextCursor.Down / QTextCursor.Up ). ( QTextCursor.MoveOperation ) :return: Method success. :rtype: bool """ cursor = self.textCursor() ...
python
{ "resource": "" }
q54432
Basic_QPlainTextEdit.search
train
def search(self, pattern, **kwargs): """ Searchs given pattern text in the document. Usage:: >>> script_editor = Umbra.components_manager.get_interface("factory.script_editor") True >>> codeEditor = script_editor.get_current_editor() True ...
python
{ "resource": "" }
q54433
Basic_QPlainTextEdit.search_next
train
def search_next(self): """ Searchs the next search pattern in the document. :return: Method success. :rtype: bool """ pattern = self.get_selected_text() or self.__search_pattern if not pattern: return False return self.search(pattern, **{"ca...
python
{ "resource": "" }
q54434
Basic_QPlainTextEdit.search_previous
train
def search_previous(self): """ Searchs the previous search pattern in the document. :return: Method success. :rtype: bool """ pattern = self.get_selected_text() or self.__search_pattern if not pattern: return False return self.search(pattern...
python
{ "resource": "" }
q54435
Basic_QPlainTextEdit.replace
train
def replace(self, pattern, replacement_pattern, **kwargs): """ Replaces current given pattern occurence in the document with the replacement pattern. Usage:: >>> script_editor = Umbra.components_manager.get_interface("factory.script_editor") True >>> codeEdi...
python
{ "resource": "" }
q54436
Basic_QPlainTextEdit.replace_all
train
def replace_all(self, pattern, replacement_pattern, **kwargs): """ | Replaces every given pattern occurrences in the document with the replacement pattern. .. warning:: Initializing **wrap_around** keyword to **True** leads to infinite recursion loop if the search patte...
python
{ "resource": "" }
q54437
Basic_QPlainTextEdit.go_to_line
train
def go_to_line(self, line): """ Moves the text cursor to given line. :param line: Line to go to. :type line: int :return: Method success. :rtype: bool """ cursor = self.textCursor() cursor.setPosition(self.document().findBlockByNumber(line - 1).p...
python
{ "resource": "" }
q54438
Basic_QPlainTextEdit.go_to_column
train
def go_to_column(self, column): """ Moves the text cursor to given column. :param column: Column to go to. :type column: int :return: Method success. :rtype: bool """ cursor = self.textCursor() cursor.setPosition(cursor.block().position() + colum...
python
{ "resource": "" }
q54439
Basic_QPlainTextEdit.go_to_position
train
def go_to_position(self, position): """ Moves the text cursor to given position. :param position: Position to go to. :type position: int :return: Method success. :rtype: bool """ cursor = self.textCursor() cursor.setPosition(position) sel...
python
{ "resource": "" }
q54440
Basic_QPlainTextEdit.toggle_word_wrap
train
def toggle_word_wrap(self): """ Toggles document word wrap. :return: Method success. :rtype: bool """ self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap) return True
python
{ "resource": "" }
q54441
Basic_QPlainTextEdit.toggle_white_spaces
train
def toggle_white_spaces(self): """ Toggles document white spaces display. :return: Method success. :rtype: bool """ text_option = self.get_default_text_option() if text_option.flags().__int__(): text_option = QTextOption() text_option.set...
python
{ "resource": "" }
q54442
Basic_QPlainTextEdit.set_font_increment
train
def set_font_increment(self, value): """ Increments the document font size. :param value: Font size increment. :type value: int :return: Method success. :rtype: bool """ font = self.font() point_size = font.pointSize() + value if point_si...
python
{ "resource": "" }
q54443
AlignedFASTA.build_tree
train
def build_tree(self, *args, **kwargs): """Dispatch a tree build call. Note that you need at least four taxa to express some evolutionary history on an unrooted tree.""" # Check length # assert len(self) > 3 # Default option # algorithm = kwargs.pop(kwargs, None) i...
python
{ "resource": "" }
q54444
AlignedFASTA.build_tree_raxml
train
def build_tree_raxml(self, new_path = None, seq_type = 'nucl' or 'prot', num_threads = None, free_cores = 2, keep_dir = False): """Make a tree with RAxML.""" # Check output # if new_path is N...
python
{ "resource": "" }
q54445
AlignedFASTA.build_tree_fast
train
def build_tree_fast(self, new_path=None, seq_type='nucl' or 'prot'): """Make a tree with FastTree. Names will be truncated however.""" # Check output # if new_path is None: new_path = self.prefix_path + '.tree' # Command # command_args = [] if seq_type == 'nucl': command_...
python
{ "resource": "" }
q54446
i18n_app
train
def i18n_app(providername): """ import this function at the top of each provider netshow component that has cli output functions. Example from netshow.netshow import i18n_app as _ """ install_location = pkg_resources.require('netshow-core-lib')[0].location translation_loc = os.path.join(in...
python
{ "resource": "" }
q54447
Editor.__set_document_signals
train
def __set_document_signals(self): """ Connects the editor document signals. """ # Signals / Slots. self.document().contentsChanged.connect(self.contents_changed.emit) self.document().contentsChanged.connect(self.__document__contents_changed) self.document().modif...
python
{ "resource": "" }
q54448
Editor.set_title
train
def set_title(self, title=None): """ Sets the editor title. :param title: Editor title. :type title: unicode :return: Method success. :rtype: bool """ if not title: # TODO: https://bugreports.qt-project.org/browse/QTBUG-27084 # ti...
python
{ "resource": "" }
q54449
Editor.set_file
train
def set_file(self, file=None, is_modified=False, is_untitled=False): """ Sets the editor file. :param File: File to set. :type File: unicode :param is_modified: File modified state. :type is_modified: bool :param is_untitled: File untitled state. :type is...
python
{ "resource": "" }
q54450
Editor.get_untitled_file_name
train
def get_untitled_file_name(self): """ Returns an untitled editor file name. :return: Untitled file name. :rtype: unicode """ name = "{0} {1}.{2}".format( self.__default_file_name, Editor._Editor__untitled_name_id, self.default_file_extension) Editor....
python
{ "resource": "" }
q54451
Editor.load_document
train
def load_document(self, document, file=None, language=None): """ Loads given document into the editor. :param document: Document to load. :type document: QTextDocument :param file: File. :type file: unicode :param language: Editor language. :type language...
python
{ "resource": "" }
q54452
Editor.new_file
train
def new_file(self): """ Creates a new editor file. :return: File name. :rtype: unicode """ file = self.get_untitled_file_name() LOGGER.debug("> Creating '{0}' file.".format(file)) self.set_file(file, is_modified=False, is_untitled=True) self.__se...
python
{ "resource": "" }
q54453
Editor.load_file
train
def load_file(self, file): """ Reads and loads given file into the editor. :param File: File to load. :type File: unicode :return: Method success. :rtype: bool """ if not foundations.common.path_exists(file): raise foundations.exceptions.File...
python
{ "resource": "" }
q54454
Editor.reload_file
train
def reload_file(self, is_modified=True): """ Reloads the current editor file. :param is_modified: File modified state. :type is_modified: bool :return: Method success. :rtype: bool """ if not foundations.common.path_exists(self.__file): raise...
python
{ "resource": "" }
q54455
Editor.save_file
train
def save_file(self): """ Saves the editor file content. :return: Method success. :rtype: bool """ if not self.__is_untitled and foundations.common.path_exists(self.__file): return self.write_file(self.__file) else: return self.save_fileAs...
python
{ "resource": "" }
q54456
Editor.save_fileAs
train
def save_fileAs(self, file=None): """ Saves the editor file content either using given file or user chosen file. :return: Method success. :rtype: bool :note: May require user interaction. """ file = file or umbra.ui.common.store_last_browsed_path( Q...
python
{ "resource": "" }
q54457
Editor.write_file
train
def write_file(self, file): """ Writes the editor file content into given file. :param file: File to write. :type file: unicode :return: Method success. :rtype: bool """ LOGGER.debug("> Writing '{0}' file.".format(file)) writer = foundations.io.F...
python
{ "resource": "" }
q54458
Editor.close_file
train
def close_file(self): """ Closes the editor file. :return: Method success. :rtype: bool """ if not self.is_modified(): LOGGER.debug("> Closing '{0}' file.".format(self.__file)) self.file_closed.emit() return True choice = me...
python
{ "resource": "" }
q54459
submit
train
def submit(script, workspace, **params): """Submit a job with the given parameters.""" from klab import cluster, process # Make sure the rosetta symlink has been created. if not os.path.exists(workspace.rosetta_dir): raise pipeline.RosettaNotFound(workspace) # Parse some job parameters fo...
python
{ "resource": "" }
q54460
initiate
train
def initiate(): """Return some relevant information about the currently running job.""" print_debug_header() workspace = pipeline.workspace_from_dir(sys.argv[1]) workspace.cd_to_root() job_info = read_job_info(workspace.job_info_path(os.environ['JOB_ID'])) job_info['job_id'] = int(os.environ['...
python
{ "resource": "" }
q54461
OAuth.auth_url
train
def auth_url(self, scope): """Gets the url a user needs to access to give up a user token""" params = { 'response_type': 'code', 'client_id': self.__client_id, 'redirect_uri': self.__redirect_uri, 'scope': scope } if self.__state is not No...
python
{ "resource": "" }
q54462
OAuth.get_user_token
train
def get_user_token(self, scope, code=None): """Gets the auth token from a user's response""" user_token = self.__get_user_token(scope) if user_token: return user_token if self.__cache is not None: token = self.__cache.get(self.__user_token_cache_key()) ...
python
{ "resource": "" }
q54463
OAuth.get_app_token
train
def get_app_token(self, scope): """Gets the app auth token""" app_token = self.__get_app_token(scope) if app_token: return app_token if self.__cache is not None: token = self.__cache.get(self.__app_token_cache_key(scope)) if token: r...
python
{ "resource": "" }
q54464
crypt
train
def crypt(password, cost=2): """ Hash a password result sample: $pbkdf2-256-1$8$FRakfnkgpMjnqs1Xxgjiwgycdf68be9b06451039cc\ 0f7075ec1c369fa36f055b1705ec7a The returned string is broken down into - The algorithm and version used - The cost factor, number of iterations ov...
python
{ "resource": "" }
q54465
verify
train
def verify(password, hash): """ Verify a password against a passed hash """ _, algorithm, cost, salt, password_hash = hash.split("$") password = pbkdf2.pbkdf2_hex(password, salt, int(cost) * 500) return _safe_str_cmp(password, password_hash)
python
{ "resource": "" }
q54466
_safe_str_cmp
train
def _safe_str_cmp(a, b): """ Internal function to efficiently iterate over the hashes Regular string compare will bail at the earliest opportunity which allows timing attacks """ if len(a) != len(b): return False rv = 0 for x, y in zip(a, b): rv |= ord(x) ^ ord(y) ...
python
{ "resource": "" }
q54467
find_validation_workspaces
train
def find_validation_workspaces(name, rounds=None): """ Find all the workspaces containing validated designs. """ workspaces = [] if rounds is not None: rounds = indices_from_str(rounds) else: rounds = itertools.count(1) for round in rounds: workspace = pipeline.Vali...
python
{ "resource": "" }
q54468
calculate_quality_metrics
train
def calculate_quality_metrics(metrics, designs, verbose=False): """ Have each metric calculate all the information it needs. """ for metric in metrics: if metric.progress_update: print metric.progress_update metric.load(designs, verbose)
python
{ "resource": "" }
q54469
report_quality_metrics
train
def report_quality_metrics(designs, metrics, path, clustering=False): """ Create a nicely formatted spreadsheet showing all the designs and metrics. """ import xlsxwriter print "Reporting quality metrics..." # Open a XLSX worksheet. workbook = xlsxwriter.Workbook(path) worksheet = work...
python
{ "resource": "" }
q54470
report_score_vs_rmsd_funnels
train
def report_score_vs_rmsd_funnels(designs, path): """ Create a PDF showing the score vs. RMSD funnels for all the reasonable designs. This method was copied from an old version of this script, and does not currently work. """ from matplotlib.backends.backend_pdf import PdfPages import matplo...
python
{ "resource": "" }
q54471
report_pymol_sessions
train
def report_pymol_sessions(designs, directory): """ Create pymol session for each reasonable design representative. This method was copied from an old version of this script, and does not currently work. """ print "Reporting pymol sessions..." if os.path.exists(directory): shutil.rmtree(dir...
python
{ "resource": "" }
q54472
annotate_designs
train
def annotate_designs(designs, symbol='+'): """ Automatically annotate the sequence and structure cluster for all the reasonable designs identified by this script. These annotations make it easier to quickly focus on interesting subsets of design in the "Show My Designs" GUI. """ max_seq_clu...
python
{ "resource": "" }
q54473
queryset_to_dict
train
def queryset_to_dict(qs, key='pk', singular=True): """ Given a queryset will transform it into a dictionary based on ``key``. """ if singular: result = {} for u in qs: result.setdefault(getattr(u, key), u) else: result = defaultdict(list) for u in qs: ...
python
{ "resource": "" }
q54474
attach_foreignkey
train
def attach_foreignkey(objects, field, related=[], database=None): """ Shortcut method which handles a pythonic LEFT OUTER JOIN. ``attach_foreignkey(posts, Post.thread)`` Works with both ForeignKey and OneToOne (reverse) lookups. """ if not objects: return if database is None: ...
python
{ "resource": "" }
q54475
add_abs_path_directories
train
def add_abs_path_directories(opts_dict): """ Adds 'abs_input' and 'abs_output' to opts_dict :param opts_dict: dictionary that will be modified """ assert_has_input_output(opts_dict) opts_dict['abs_input'] = path.abspath(opts_dict['input']) if opts_dict['is_dir']: # Only add path sep...
python
{ "resource": "" }
q54476
ensure_directories_end_in_separator
train
def ensure_directories_end_in_separator(opts_dict): """ Adds a path separator to the end of the input and output directories, if they don't already have them. :param opts_dict: dictionary that will be modified """ assert_has_input_output(opts_dict) assert 'is_dir' in opts_dict if opts_d...
python
{ "resource": "" }
q54477
add_wrapper_regex
train
def add_wrapper_regex(opts_dict): """ Adds the regular expression for the specified wrapper to opts_dict. It is assumed the dictionary has the keys 'open' and 'close' The regular expression will match the following, in order: 1. The wrapper 'open' pattern 2. Followed by any amount of white spa...
python
{ "resource": "" }
q54478
get_substring_idxs
train
def get_substring_idxs(substr, string): """ Return a list of indexes of substr. If substr not found, list is empty. Arguments: substr (str): Substring to match. string (str): String to match in. Returns: list of int: Start indices of substr. """ return [match.start(...
python
{ "resource": "" }
q54479
truncate
train
def truncate(string, maxchar): """ Truncate a string to a maximum number of characters. If the string is longer than maxchar, then remove excess characters and append an ellipses. Arguments: string (str): String to truncate. maxchar (int): Maximum length of string in characters. M...
python
{ "resource": "" }
q54480
diff
train
def diff(s1, s2): """ Return a normalised Levenshtein distance between two strings. Distance is normalised by dividing the Levenshtein distance of the two strings by the max(len(s1), len(s2)). Examples: >>> text.diff("foo", "foo") 0 >>> text.diff("foo", "fooo") 1 ...
python
{ "resource": "" }
q54481
PrivateInvestment.lock_up_period
train
def lock_up_period(self, lock_up_period): """ This lockup period is in months. This might change to a relative delta.""" try: if isinstance(lock_up_period, (str, int)): self._lock_up_period = int(lock_up_period) except Exception: raise ValueError('invalid...
python
{ "resource": "" }
q54482
PrivateInvestment.investment_term
train
def investment_term(self, investment_term): """ This investment term is in months. This might change to a relative delta.""" try: if isinstance(investment_term, (str, int)): self._investment_term = int(investment_term) except Exception: raise ValueError('...
python
{ "resource": "" }
q54483
local_machine
train
def local_machine(): """Option to do something on local machine.""" common_conf() env.machine = 'local' env.pg_admin_role = settings.LOCAL_PG_ADMIN_ROLE env.db_backup_dir = settings.DJANGO_PROJECT_ROOT env.media_backup_dir = settings.DJANGO_PROJECT_ROOT # Not sure what this is good for. Not...
python
{ "resource": "" }
q54484
dev
train
def dev(): """Option to do something on the development server.""" common_conf() env.user = settings.LOGIN_USER_DEV env.machine = 'dev' env.host_string = settings.HOST_DEV env.hosts = [env.host_string, ]
python
{ "resource": "" }
q54485
stage
train
def stage(): """Option to do something on the staging server.""" common_conf() env.user = settings.LOGIN_USER_STAGE env.machine = 'stage' env.host_string = settings.HOST_STAGE env.hosts = [env.host_string, ]
python
{ "resource": "" }
q54486
prod
train
def prod(): """Option to do something on the production server.""" common_conf() env.user = settings.LOGIN_USER_PROD env.machine = 'prod' env.host_string = settings.HOST_PROD env.hosts = [env.host_string, ]
python
{ "resource": "" }
q54487
add_dummy_scores
train
def add_dummy_scores(iteratable, score=0): """Add zero scores to all sequences""" for seq in iteratable: seq.letter_annotations["phred_quality"] = (score,)*len(seq) yield seq
python
{ "resource": "" }
q54488
schedule_job
train
def schedule_job(date, callable_name, content_object=None, expires='7d', args=(), kwargs={}): """Schedule a job. `date` may be a datetime.datetime or a datetime.timedelta. The callable to be executed may be specified in two ways: - set `callable_name` to an identifier ('mypackage.mya...
python
{ "resource": "" }
q54489
run_jobs
train
def run_jobs(delete_completed=False, ignore_errors=False, now=None): """Run scheduled jobs. You may specify a date to be treated as the current time. """ if ScheduledJob.objects.filter(status='running'): raise ValueError('jobs in progress found; aborting') if now is None: now = date...
python
{ "resource": "" }
q54490
Schema.read_contents
train
def read_contents(self, name, conn): '''Read schema tables''' sql = '''select c.relname, d.description, case c.relkind when 'r' then 'table' when 'v' then 'view' when 'm' then 'm...
python
{ "resource": "" }
q54491
main
train
def main(argv=None): """ Main entry method for AnchorHub. Takes in command-line arguments, finds files to parse within the specified input directory, and outputs parsed files to the specified output directory. :param argv: a list of string command line arguments """ # Get command line argum...
python
{ "resource": "" }
q54492
State.can
train
def can(self, event): """ returns a list of states that can result from processing this event """ return [t.new_state for t in self._transitions if t.event.equals(event)]
python
{ "resource": "" }
q54493
State.is_faulty
train
def is_faulty(self, event): """ returns a boolean if fault processing is handled for this event """ for each in self._faults: if each.name.upper() == event.name.upper(): return True return False
python
{ "resource": "" }
q54494
State.consume
train
def consume(self, event): """ process the current event, setup new state and teardown current state """ future_states = self.can(event) new_state = future_states[0] if len(future_states) > 1: new_state = self.choose(event) event.execute() self...
python
{ "resource": "" }
q54495
State.on
train
def on(self, event, new_state): """ add a valid transition to this state """ if self.name == new_state.name: raise RuntimeError("Use loop method to define {} -> {} -> {}".format(self.name, event.name, new_state.name)) self._register_transition(event, new_state)
python
{ "resource": "" }
q54496
State.faulty
train
def faulty(self, *args): """ add an event or list of events that produces a predefined error an event is only added if its not already there """ for each in args: if not self.is_faulty(each): self._faults.add(each)
python
{ "resource": "" }
q54497
Queue._ensure_counter
train
def _ensure_counter(self): """Ensure counter exists in Consul.""" if self._counter_path not in self._client.kv: self._client.kv[self._counter_path] = ''.zfill(self._COUNTER_FILL)
python
{ "resource": "" }
q54498
Queue._ensure_queue
train
def _ensure_queue(self): """Ensure queue exists in Consul.""" if self._queue_path not in self._client.kv: self._client.kv[self._queue_path] = None
python
{ "resource": "" }
q54499
Queue.get
train
def get(self): """Get a task from the queue.""" tasks = self._get_avaliable_tasks() if not tasks: return None name, data = tasks[0] self._client.kv.delete(name) return data
python
{ "resource": "" }