_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q52700
generate_and_cache
train
def generate_and_cache(path=user_path): ''' Generate category ranges and save to userlevel cache file. :param path: path to userlevel cache file :type path: str :returns: category ranges dict :rtype: dict of RangeGroup ''' data = tools.generate() if not path: return data ...
python
{ "resource": "" }
q52701
ADGroup.group
train
def group(self, base_dn, samaccountname, attributes=(), explicit_membership_only=False): """Produces a single, populated ADGroup object through the object factory. Does not populate attributes for the caller instance. sAMAccountName may not be present in group objects in modern AD schemas. ...
python
{ "resource": "" }
q52702
ADGroup.groups
train
def groups(self, base_dn, samaccountnames=(), attributes=(), explicit_membership_only=False): """Gathers a list of ADGroup objects sAMAccountName may not be present in group objects in modern AD schemas. Searching by common name and object class (group) may be an alternative approach if...
python
{ "resource": "" }
q52703
DHLTracker.wait_till_page_load
train
def wait_till_page_load(self,driver,max_wait_time): ''' This method pauses execution until the page is loaded fully, including data delayed by JavaScript ''' sleepCount = max_wait_time # wait for a fixed max_wait_time only # A page that's fully loaded has the word 'Current Status' while self.trackin...
python
{ "resource": "" }
q52704
Gati_Tracker.Get_Page
train
def Get_Page(self): ''' Fetches raw XML data from the site for a given tracking_no ''' url = 'http://www.gati.com/webservices/gatiicedkttrack.jsp?dktno=' + self.tracking_no response = requests.get(url) self.page = response.text
python
{ "resource": "" }
q52705
_splash
train
def _splash(): """Print the splash""" splash_title = "{pkg} [{version}] - {url}".format(pkg=PKG_NAME, version=version, url=PKG_URL) log.to_stdout(splash_title, colorf=log.yellow, bold=True) log.to_stdout('-' * len(splash_title), colorf=log.yellow, bo...
python
{ "resource": "" }
q52706
init
train
def init(argv): """ Bootstrap the whole thing :param argv: list of command line arguments """ # Setting initial configuration values config.set_default({ # driver section "driver": {}, # fs section "fs": {}, # MongoDB section "mongodb": {}, })...
python
{ "resource": "" }
q52707
main
train
def main(argv=None): """ This is the main thread of execution :param argv: list of command line arguments """ # Exit code exit_code = 0 # First, we change main() to take an optional 'argv' # argument, which allows us to call it from the interactive # Python prompt if argv is No...
python
{ "resource": "" }
q52708
Registry.read
train
def read(self, document, iface, *args, **kwargs): """ Returns a Deferred that fire the read object. """ try: document = IReadableDocument(document) mime_type = document.mime_type reader = self.lookup_reader(mime_type, iface) if not reader: ...
python
{ "resource": "" }
q52709
Registry.write
train
def write(self, document, obj, *args, **kwargs): """ Returns a Deferred that fire the factory result that should be the document. """ try: document = IWritableDocument(document) mime_type = document.mime_type writer = self.lookup_writer(mime_ty...
python
{ "resource": "" }
q52710
delimiter_encodeseq
train
def delimiter_encodeseq(delimiter, encodeseq, charset): '''Coerce delimiter and encodeseq to unicode and verify that they are not the same''' delimiter = coerce_unicode(delimiter, charset) encodeseq = coerce_unicode(encodeseq, charset) if 1 != len(encodeseq): raise FSQEncodeError(errno.EI...
python
{ "resource": "" }
q52711
rationalize_file
train
def rationalize_file(item_f, charset, mode='rb', lock=False): '''FSQ attempts to treat all file-like things as line-buffered as an optimization to the average case. rationalize_file will handle file objects, buffers, raw file-descriptors, sockets, and string file-addresses, and will return a f...
python
{ "resource": "" }
q52712
wrap_io_os_err
train
def wrap_io_os_err(e): '''Formats IO and OS error messages for wrapping in FSQExceptions''' msg = '' if e.strerror: msg = e.strerror if e.message: msg = ' '.join([e.message, msg]) if e.filename: msg = ': '.join([msg, e.filename]) return msg
python
{ "resource": "" }
q52713
check_ttl_max_tries
train
def check_ttl_max_tries(tries, enqueued_at, max_tries, ttl): '''Check that the ttl for an item has not expired, and that the item has not exceeded it's maximum allotted tries''' if max_tries > 0 and tries >= max_tries: raise FSQMaxTriesError(errno.EINTR, u'Max tries exceded:'\ ...
python
{ "resource": "" }
q52714
camelcase_to_underscores
train
def camelcase_to_underscores(word): """Converts a CamelCase word into an under_score word. >>> camelcase_to_underscores("CamelCaseCase") 'camel_case_case' >>> camelcase_to_underscores("getHTTPResponseCode") 'get_http_response_code' """ s1 = _FIRST_CAP_RE.sub(r'\1_\2', word) ...
python
{ "resource": "" }
q52715
silent_popen
train
def silent_popen(args, **kwargs): """Wrapper for subprocess.Popen with suppressed output. STERR is redirected to STDOUT which is piped back to the calling process and returned as the result. """ return subprocess.Popen(args, stderr=subprocess.STDOUT, ...
python
{ "resource": "" }
q52716
datetime_from_iso8601
train
def datetime_from_iso8601(date): """Small helper that parses ISO-8601 date dates. >>> datetime_from_iso8601("2013-04-10T12:52:39") datetime.datetime(2013, 4, 10, 12, 52, 39) >>> datetime_from_iso8601("2013-01-07T12:55:19.257") datetime.datetime(2013, 1, 7, 12, 55, 19, 257000) ""...
python
{ "resource": "" }
q52717
Bin.create
train
def create(cls, service=Service(), private=False): """ create a bin instance on the server """ response = service.send(SRequest('POST', cls.path, data={'private': private})) return cls.from_response(response, service=service)
python
{ "resource": "" }
q52718
Bin.get
train
def get(cls, name, service=Service()): '''fetch given bin from the service''' path = pathjoin(cls.path, name) response = service.send(SRequest('GET', path)) return cls.from_response(response, service=service)
python
{ "resource": "" }
q52719
Bin.reload
train
def reload(self): '''reload self from self.service''' other = type(self).get(self.name, service=self.service) self.request_count = other.request_count
python
{ "resource": "" }
q52720
Bin.api_url
train
def api_url(self): '''return the api url of self''' return pathjoin(Bin.path, self.name, url=self.service.url)
python
{ "resource": "" }
q52721
Bin.requests
train
def requests(self): '''return accumulated requests to this bin''' path = pathjoin(self.path, self.name, Request.path) response = self.service.send(SRequest('GET', path)) # a bin behaves as a push-down store --- better to return the requests # in order of appearance return...
python
{ "resource": "" }
q52722
get
train
def get(url, last_modified=None): """Performs a get request to a given url. Returns an empty str on error. """ try: with closing(urllib2.urlopen(url)) as page: if last_modified is not None: last_mod = dateutil.parser.parse(dict(page.info())['last-modified']) ...
python
{ "resource": "" }
q52723
list_rocs_files
train
def list_rocs_files(url=ROCS_URL): """Gets the contents of the given url. """ soup = BeautifulSoup(get(url)) if not url.endswith('/'): url += '/' files = [] for elem in soup.findAll('a'): if elem['href'].startswith('?'): continue if elem.string.lower() == 'par...
python
{ "resource": "" }
q52724
XmlDogma._create_path
train
def _create_path(self,xpath): """ Started to write an xpath parser to create the specified path but there are many ways to specify a path in xpath - it is too expressive. This is not a sensible thing to do from inside a property function. Let it return an error unless the path ex...
python
{ "resource": "" }
q52725
XmlDogma._eval_xpath
train
def _eval_xpath(self, xpath): """ Evaluates xpath expressions. Either string or XPath object. """ if isinstance(xpath, etree.XPath): result = xpath(self._dataObject) else: result = self._dataObject.xpath(xpath,namespaces=self._namespaces) ...
python
{ "resource": "" }
q52726
XmlDogma._eval
train
def _eval(self, teaching): """ Returns the evaluation. """ # transform if someone called _get directly if isinstance(teaching, string_types): teaching = self._validate_teaching(None, teaching, namespaces=self._namespaces) return teaching(self._dataObject)
python
{ "resource": "" }
q52727
Averager.add
train
def add(self, value): """Add a value, and return current average.""" self._data.append(value) if len(self._data) > self._max_count: self._data.popleft() return sum(self._data)/len(self._data)
python
{ "resource": "" }
q52728
create_app
train
def create_app(): """Flask application factory function.""" app = Flask(__name__) app.config_from_envvar = app.config.from_envvar app.config_from_object = app.config.from_object configure_app(app) init_core(app) register_blueprints(app) return app
python
{ "resource": "" }
q52729
configure_sql
train
def configure_sql(engine): """Configure session and metadata with the database engine.""" Session.configure(bind=engine) Base.metadata.bind = engine
python
{ "resource": "" }
q52730
create_schema
train
def create_schema(alembic_config_ini=None): """Create the database schema. :param alembic_config_ini: When provided, stamp with the current revision version. """ Base.metadata.create_all() if alembic_config_ini: from alembic.config import Config from alembic import command ...
python
{ "resource": "" }
q52731
populate_database
train
def populate_database(): """Populate the database with some data useful for development.""" if User.fetch_by(username='admin'): return # Admin user admin = User(name='Administrator', password='password', username='admin', is_admin=True) # Class class_ = Class(name='CS32...
python
{ "resource": "" }
q52732
Class.can_edit
train
def can_edit(self, user): """Return whether or not `user` can make changes to the class.""" return user.is_admin or not self.is_locked and self in user.admin_for
python
{ "resource": "" }
q52733
File.can_view
train
def can_view(self, user): """Return true if the user can view the file.""" # Perform simplest checks first if user.is_admin or self in user.files: return True elif user.admin_for: # Begin more expensive comparisions # Single-indirect lookup classes = ...
python
{ "resource": "" }
q52734
Group.can_view
train
def can_view(self, user): """Return whether or not `user` can view info about the group.""" return user.is_admin or user in self.users \ or self.project.class_ in user.admin_for
python
{ "resource": "" }
q52735
Project.can_access
train
def can_access(self, user): """Return whether or not `user` can access a project. The project's is_ready field must be set for a user to access. """ return self.class_.is_admin(user) or \ self.is_ready and self.class_ in user.classes
python
{ "resource": "" }
q52736
Project.can_edit
train
def can_edit(self, user): """Return whether or not `user` can make changes to the project.""" return self.class_.can_edit(user) and self.status != u'locked'
python
{ "resource": "" }
q52737
Project.points_possible
train
def points_possible(self, include_hidden=False): """Return the total points possible for this project.""" return sum([test_case.points for testable in self.testables for test_case in testable.test_cases if include_hidden or not testable.is_hidden])
python
{ "resource": "" }
q52738
Project.recent_submissions
train
def recent_submissions(self): """Generate a list of the most recent submissions for each user. Only yields a submission for a user if they've made one. """ for group in self.groups: submission = Submission.most_recent_submission(self, group) if submission: ...
python
{ "resource": "" }
q52739
Project.submit_string
train
def submit_string(self): """Return a string specifying the files to submit for this project.""" required = [] optional = [] for file_verifier in self.file_verifiers: if file_verifier.optional: optional.append('[{0}]'.format(file_verifier.filename)) ...
python
{ "resource": "" }
q52740
Project.verify_submission
train
def verify_submission(self, base_path, submission, update): """Return list of testables that can be built.""" results = VerificationResults() valid_files = set() file_mapping = submission.file_mapping() # Create a list of in-use file verifiers file_verifiers = set(fv for...
python
{ "resource": "" }
q52741
Submission.most_recent_submission
train
def most_recent_submission(project, group): """Return the most recent submission for the user and project id.""" return (Submission.query_by(project=project, group=group) .order_by(Submission.created_at.desc()).first())
python
{ "resource": "" }
q52742
Submission.can_view
train
def can_view(self, user): """Return whether or not `user` can view the submission.""" return user in self.group.users or self.project.can_view(user)
python
{ "resource": "" }
q52743
Submission.get_delay
train
def get_delay(self, update): """Return the minutes to delay the viewing of submission results. Only store information into the datebase when `update` is set. """ if hasattr(self, '_delay'): return self._delay now = datetime.now(UTC()) zero = timedelta(0) ...
python
{ "resource": "" }
q52744
Submission.points
train
def points(self, include_hidden=False): """Return the number of points awarded to this submission.""" return sum(x.points for x in self.testable_results if include_hidden or not x.testable.is_hidden)
python
{ "resource": "" }
q52745
Submission.verify
train
def verify(self, base_path, update=False): """Verify the submission and return testables that can be executed.""" return self.project.verify_submission(base_path, self, update=update)
python
{ "resource": "" }
q52746
User.get_value
train
def get_value(cls, value): '''Takes the class of the item that we want to query, along with a potential instance of that class. If the value is an instance of int or basestring, then we will treat it like an id for that instance.''' if isinstance(value, (basestring, int)): ...
python
{ "resource": "" }
q52747
User.login
train
def login(username, password, development_mode=False): """Return the user if successful, None otherwise""" retval = None try: user = User.fetch_by(username=username) if user and (development_mode or user.verify_password(password)): retval = user ex...
python
{ "resource": "" }
q52748
User.can_join_group
train
def can_join_group(self, project): """Return whether or not user can join a group on `project`.""" if project.class_.is_locked or project.group_max < 2: return False u2g = self.fetch_group_assoc(project) if u2g: return len(list(u2g.group.users)) < project.group_ma...
python
{ "resource": "" }
q52749
User.can_view
train
def can_view(self, user): """Return whether or not `user` can view information about the user.""" return user.is_admin or self == user \ or set(self.classes).intersection(user.admin_for)
python
{ "resource": "" }
q52750
User.group_with
train
def group_with(self, to_user, project, bypass_limit=False): """Join the users in a group.""" from_user = self from_assoc = from_user.fetch_group_assoc(project) to_assoc = to_user.fetch_group_assoc(project) if from_user == to_user or from_assoc == to_assoc and from_assoc: ...
python
{ "resource": "" }
q52751
AgentMixin.allocation_used
train
def allocation_used(self, state, allocation_id): ''' Checks if allocation is used by any of the partners. If allocation does not exist returns False. @param allocation_id: ID of the allocation @returns: True/False ''' return len(filter(lambda x: x.allocation_id ==...
python
{ "resource": "" }
q52752
filter_macro
train
def filter_macro(func, *args, **kwargs): """ Promotes a function that returns a filter into its own filter type. Example:: @filter_macro def String(): return Unicode | Strip | NotEmpty # You can now use `String` anywhere you would use a regular Filter: (String ...
python
{ "resource": "" }
q52753
pathjoin
train
def pathjoin(*parts, **kvs): '''join path parts into a path; in case url is not none, use that, too''' url = kvs.pop('url', '/') url = url + '/' + '/'.join(parts) url = normalize_url(url) return url
python
{ "resource": "" }
q52754
compare_checksum
train
def compare_checksum(info, f): """Return True if the checksum values in the info dictionary match the computed checksum values of file content. """ pieces = info['pieces'] def getchunks(f, size): while True: chunk = f.read(size) if chunk == '': break ...
python
{ "resource": "" }
q52755
new_project
train
def new_project(): """New Project.""" form = NewProjectForm() if not form.validate_on_submit(): return jsonify(errors=form.errors), 400 data = form.data data['slug'] = slugify(data['name']) data['owner_id'] = get_current_user_id() id = add_instance('project', **data) if not id...
python
{ "resource": "" }
q52756
delete_project
train
def delete_project(project_id): """Delete Project.""" project = get_data_or_404('project', project_id) if project['owner_id'] != get_current_user_id(): return jsonify(message='forbidden'), 403 delete_instance('project', project_id) return jsonify({})
python
{ "resource": "" }
q52757
new_sender
train
def new_sender(project_id): """Add sender.""" project = get_data_or_404('project', project_id) if project['owner_id'] != get_current_user_id(): return jsonify(message='forbidden'), 403 form = NewSenderForm() if not form.validate_on_submit(): return jsonify(errors=form.errors), 400...
python
{ "resource": "" }
q52758
new_action
train
def new_action(project_id): """Add action.""" project = get_data_or_404('project', project_id) if project['owner_id'] != get_current_user_id(): return jsonify(message='forbidden'), 403 form = NewActionForm() if not form.validate_on_submit(): return jsonify(errors=form.errors), 400...
python
{ "resource": "" }
q52759
delete_action
train
def delete_action(action_id): """Delete action.""" action = get_data_or_404('action', action_id) project = get_data_or_404('project', action['project_id']) if project['owner_id'] != get_current_user_id(): return jsonify(message='forbidden'), 403 delete_instance('sender', action['id']) ...
python
{ "resource": "" }
q52760
delete_webhook
train
def delete_webhook(webhook_id): """Delete webhook.""" webhook = get_data_or_404('webhook', webhook_id) action = get_data_or_404('action', webhook['action_id']) project = get_data_or_404('project', action['project_id']) if project['owner_id'] != get_current_user_id(): return jsonify(message=...
python
{ "resource": "" }
q52761
remove
train
def remove(text, what, count=None, strip=False): ''' Like ``replace``, where ``new`` replacement is an empty string. ''' return replace(text, what, '', count=count, strip=strip)
python
{ "resource": "" }
q52762
remove_each
train
def remove_each(text, items, count=None, strip=False): ''' Like ``remove``, where each occurrence in ``items`` is ``what`` to remove. ''' for item in items: text = remove(text, item, count=count, strip=strip) return text
python
{ "resource": "" }
q52763
matches
train
def matches(text, what): ''' Check if ``what`` occurs in ``text`` ''' return text.find(what) > -1 if is_string(what) else what.match(text)
python
{ "resource": "" }
q52764
find_first
train
def find_first(data, what): ''' Search for ``what`` in the iterable ``data`` and return the index of the first match. Return ``None`` if no match found. ''' for i, line in enumerate(data): if contains(line, what): return i return None
python
{ "resource": "" }
q52765
splitter
train
def splitter(text, token=None, expected=2, default='', strip=False): ''' Split ``text`` by ``token`` into at least ``expected`` number of results. When ``token`` is ``None``, the default for Python ``str.split`` is used, which will split on all whitespace. ``token`` may also be a regex. ...
python
{ "resource": "" }
q52766
versioned_static
train
def versioned_static(file_path): """ Given the path for a static file Output a url path with a hex has query string for versioning """ full_path = find(file_path) url = static(file_path) if type(full_path) is list and len(full_path) > 0: full_path = full_path[0] if not full_pa...
python
{ "resource": "" }
q52767
progbar
train
def progbar(iterable, *a, verbose=True, **kw): """Prints a progress bar as the iterable is iterated over :param iterable: The iterator to iterate over :param a: Arguments to get passed to tqdm (or tqdm_notebook, if in a Jupyter notebook) :param verbose: Whether or not to print the progress bar at all ...
python
{ "resource": "" }
q52768
parallel_progbar
train
def parallel_progbar(mapper, iterable, nprocs=None, starmap=False, flatmap=False, shuffle=False, verbose=True, verbose_flatmap=None, **kwargs): """Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned :param mapper: The mapping function to apply...
python
{ "resource": "" }
q52769
iparallel_progbar
train
def iparallel_progbar(mapper, iterable, nprocs=None, starmap=False, flatmap=False, shuffle=False, verbose=True, verbose_flatmap=None, max_cache=-1, **kwargs): """Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned. Yields objects as soon as th...
python
{ "resource": "" }
q52770
from_isodate
train
def from_isodate(value, strict=False): """Convert an ISO formatted date into a Date object. :param value: The ISO formatted date. :param strict: If value is ``None``, then if strict is ``True`` it returns the Date object of today, otherwise it returns ``None``. (Default: ``False``) :ret...
python
{ "resource": "" }
q52771
from_isodatetime
train
def from_isodatetime(value, strict=False): """Convert an ISO formatted datetime into a Date object. :param value: The ISO formatted datetime. :param strict: If value is ``None``, then if strict is ``True`` it returns the Date object of today, otherwise it returns ``None``. (Default: ``False...
python
{ "resource": "" }
q52772
format_arrow
train
def format_arrow(value, format_string): """Format an arrow datetime object. :param value: The arrow datetime object. :param format_string: The date format string :returns: Returns a string representation of the given arrow datetime object, formatted according to the given format string. .....
python
{ "resource": "" }
q52773
PoreSurfaceParameters.output_files
train
def output_files(self): """Return list of output files to be retrieved""" output_list = [] pm_dict = self.get_dict() output_list.append(pm_dict['output_surface']) if pm_dict['target_volume'] != 0.0: output_list.append(pm_dict['output_surface'] + str(".cell")) ...
python
{ "resource": "" }
q52774
PoreSurfaceParameters.output_links
train
def output_links(self): """Return list of output link names""" output_links = [] pm_dict = self.get_dict() output_links.append('surface_sample') if pm_dict['target_volume'] != 0.0: output_links.append('cell') return output_links
python
{ "resource": "" }
q52775
maybeDeferred
train
def maybeDeferred(f, *args, **kw): """ Copied from twsited.internet.defer and add a check to detect fibers. """ try: result = f(*args, **kw) except Exception: return fail(failure.Failure()) if IFiber.providedBy(result): import traceback frames = traceback.extract...
python
{ "resource": "" }
q52776
ensure_async
train
def ensure_async(function_original): """ A function decorated with this will always return a defer.Deferred even when returning synchronous result or raise an exception. """ def wrapper(*args, **kwargs): try: result = function_original(*args, **kwargs) if isinstance(...
python
{ "resource": "" }
q52777
Tcd.append
train
def append(self, station): """ Append station to database. Returns the index of the appended station. """ rec = station._pack(self) with self: _libtcd.add_tide_record(rec, self._header) return self._header.number_of_records - 1
python
{ "resource": "" }
q52778
Porter2Stemmer.stem
train
def stem(self, word): """ Stem the word if it has more than two characters, otherwise return it as is. """ if len(word) <= 2: return word else: word = self.remove_initial_apostrophe(word) word = self.set_ys(word) self.find_...
python
{ "resource": "" }
q52779
Porter2Stemmer.set_ys
train
def set_ys(self, word): """ Identify Ys that are to be treated as consonants and make them uppercase. """ if word[0] == 'y': word = 'Y' + word[1:] for match in re.finditer("[aeiou]y", word): y_index = match.end() - 1 char_list = [x fo...
python
{ "resource": "" }
q52780
Porter2Stemmer.find_regions
train
def find_regions(self, word): """ Find regions R1 and R2. """ length = len(word) for index, match in enumerate(re.finditer("[aeiouy][^aeiouy]", word)): if index == 0: if match.end() < length: self.r1 = match.end() if in...
python
{ "resource": "" }
q52781
Porter2Stemmer.is_short
train
def is_short(self, word): """ Determine if the word is short. Short words are ones that end in a short syllable and have an empty R1 region. """ short = False length = len(word) if self.r1 >= length: if length > 2: ending = wo...
python
{ "resource": "" }
q52782
Porter2Stemmer.strip_possessives
train
def strip_possessives(self, word): """ Get rid of apostrophes indicating possession. """ if word.endswith("'s'"): return word[:-3] elif word.endswith("'s"): return word[:-2] elif word.endswith("'"): return word[:-1] else: ...
python
{ "resource": "" }
q52783
Porter2Stemmer.replace_ys
train
def replace_ys(self, word): """ Replace y or Y with i if preceded by a non-vowel which is not the first letter of the word .""" length = len(word) if word[length - 1] in 'Yy': if length > 2: if word[length - 2] not in self.vowels: ...
python
{ "resource": "" }
q52784
Porter2Stemmer.replace_suffixes_3
train
def replace_suffixes_3(self, word): """. Perform replacements on more common suffixes. """ length = len(word) replacements = {'tional': 'tion', 'enci': 'ence', 'anci': 'ance', 'abli': 'able', 'entli': 'ent', 'ization': 'ize', 'izer...
python
{ "resource": "" }
q52785
Porter2Stemmer.replace_suffixes_4
train
def replace_suffixes_4(self, word): """ Perform replacements on even more common suffixes. """ length = len(word) replacements = {'ational': 'ate', 'tional': 'tion', 'alize': 'al', 'icate': 'ic', 'iciti': 'ic', 'ical': 'ic', 'ful': ...
python
{ "resource": "" }
q52786
Porter2Stemmer.delete_suffixes
train
def delete_suffixes(self, word): """ Delete some very common suffixes. """ length = len(word) suffixes = ['al', 'ance', 'ence', 'er', 'ic', 'able', 'ible', 'ant', 'ement', 'ment', 'ent', 'ism', 'ate', 'iti', 'ous', 'ive', 'ize'] fo...
python
{ "resource": "" }
q52787
Porter2Stemmer.process_terminals
train
def process_terminals(self, word): """ Deal with terminal Es and Ls and convert any uppercase Ys back to lowercase. """ length = len(word) if word[length - 1] == 'e': if self.r2 <= (length - 1): word = word[:-1] elif self.r1 <= (l...
python
{ "resource": "" }
q52788
xdg_compose
train
def xdg_compose(to, subject, body=None, cc=None, bcc=None): """Use xdg-email to compose in an X environment. Needs xdg-utils and a running X session. Works with GNOME, KDE, MATE, XFCE, ... """ command = ["xdg-email", "--utf8", "--subject", subject] if body: command += ["--body", body] ...
python
{ "resource": "" }
q52789
safe_size_check
train
def safe_size_check(checked_path, error_detail, max_bytes=500000000): """Determines if a particular path is larger than expected. Useful before any recursive remove.""" actual_size = 0 for dirpath, dirnames, filenames in os.walk(checked_path): for f in filenames: fp = os.path.join(dirpat...
python
{ "resource": "" }
q52790
recursive_pattern_delete
train
def recursive_pattern_delete(root, file_patterns, directory_patterns, dry_run=False): """Recursively deletes files matching a list of patterns. Same for directories""" for root, dirs, files in os.walk(root): for pattern in file_patterns: for file_name in fnmatch.filter(files, pattern): ...
python
{ "resource": "" }
q52791
execute
train
def execute(*args, **kwargs): """A wrapper of pyntcontrib's execute that handles kwargs""" if kwargs: # TODO: Remove this when pyntcontrib's execute does this args = list(args) args.extend(_kwargs_to_execute_args(kwargs)) _execute(*args)
python
{ "resource": "" }
q52792
GitHeart.append_onto_file
train
def append_onto_file(self, file_name, msg): """ Appends msg onto the Given File """ with open(file_name, "a") as heart_file: heart_file.write(msg) heart_file.close()
python
{ "resource": "" }
q52793
GitHeart.do_commit_amends
train
def do_commit_amends(self): """ Amends the Commit to form the heart """ commit_cumalative_count = 0 for days in MARKED_DAYS: amend_date = ( self.end_date - datetime.timedelta(days)).strftime("%Y-%m-%d %H:%M:%S") for commit_number_in_a_d...
python
{ "resource": "" }
q52794
circles_pil
train
def circles_pil(width, height, color): """ Implementation of circle border with PIL. """ image = Image.new("RGBA", (width, height), color=None) draw = ImageDraw.Draw(image) draw.ellipse((0, 0, width - 1, height - 1), fill=color) image.save('circles.png')
python
{ "resource": "" }
q52795
circles_pycairo
train
def circles_pycairo(width, height, color): """ Implementation of circle border with PyCairo. """ cairo_color = color / rgb(255, 255, 255) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context(surface) # draw a circle in the center ctx.new_path() ctx.set_sour...
python
{ "resource": "" }
q52796
YeelightCommand.build_message
train
def build_message(self): """ Make the one string message sent to the bulb """ if self.params is None: inline_params = "" else: # Put all params in one string inline_params = "" if type(self.params) is list: for x...
python
{ "resource": "" }
q52797
YeelightResponse.check_id
train
def check_id(self): """ Raise an exception if the command and the response id does not match """ if self.response_id != self.command.get_command_id(): raise Exception( "Error decoding response : the response id {} doesn't match the command id {}".format(se...
python
{ "resource": "" }
q52798
discordian_calendar
train
def discordian_calendar(season=None, year=None, dtobj=None): """Prints a discordian calendar for a particular season and year. Args:: season: integer cardinal season from 1 to 5 year: integer discordian year from 1166 to MAXYEAR + 1166 dtobj: datetime object to instatiate the calendar ...
python
{ "resource": "" }
q52799
main
train
def main(): """Command line entry point for dcal.""" if "--help" in sys.argv or "-h" in sys.argv or len(sys.argv) > 3: raise SystemExit(__doc__) try: discordian_calendar(*sys.argv[1:]) except ValueError as error: raise SystemExit("Error: {}".format("\n".join(error.args)))
python
{ "resource": "" }