_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q52900
Commands.get_medium
train
def get_medium(self, agent_type, index=0): '''Returns the medium class for the given agent_type. Optional index tells which one to give.''' mediums = list(x for x in self.agency._agents if x.get_descriptor().type_name == agent_type) try: return mediums[...
python
{ "resource": "" }
q52901
Commands.restart_agent
train
def restart_agent(self, agent_id, **kwargs): '''tells the host agent running in this agency to restart the agent.''' host_medium = self.get_medium('host_agent') agent = host_medium.get_agent() d = host_medium.get_document(agent_id) # This is done like this on purpose, we want to ...
python
{ "resource": "" }
q52902
KeyChecker.checkKey
train
def checkKey(self, credentials): """ Retrieve the keys of the user specified by the credentials, and check if one matches the blob in the credentials. """ filename = self._keyfile if not os.path.exists(filename): return 0 lines = open(filename).xreadli...
python
{ "resource": "" }
q52903
source_call
train
def source_call(method_name, *args, **kwargs): """ Creates an effect that will drop the current effect value, call the source's method with specified name with the specified arguments and keywords. @param method_name: the name of method belonging to the source reference. @type method_name: str ...
python
{ "resource": "" }
q52904
source_filter
train
def source_filter(method_name, *args, **kwargs): """ Creates an effect that will call the source's method with the current value and specified arguments and keywords. @param method_name: the name of method belonging to the source reference. @type method_name: str """ def source_filter(value...
python
{ "resource": "" }
q52905
action_filter
train
def action_filter(method_name, *args, **kwargs): """ Creates an effect that will call the action's method with the current value and specified arguments and keywords. @param method_name: the name of method belonging to the action. @type method_name: str """ def action_filter(value, context,...
python
{ "resource": "" }
q52906
view_call
train
def view_call(method_name, *args, **kwargs): """ Creates an effect that will drop the current effect value, call the view's method with specified name with the specified arguments and keywords. @param method_name: the name of method belonging to the view. @type method_name: str """ def ...
python
{ "resource": "" }
q52907
value_call
train
def value_call(method_name, *args, **kwargs): """ Creates an effect that will call value's method with specified name with the specified arguments and keywords. @param method_name: the name of method belonging to the value. @type method_name: str """ def value_call(value, context, **_params...
python
{ "resource": "" }
q52908
Converter._is_null
train
def _is_null(self, value): """Check if an incoming value is ``None`` or the empty string.""" if isinstance(value, six.string_types): if not len(value.strip()): return True return value is None
python
{ "resource": "" }
q52909
Converter.cast
train
def cast(self, value, **opts): """Convert the given value to the target type. Return ``None`` if the value is empty. If an error occurs, raise a ``ConverterError``. """ if isinstance(value, self.result_type): return value if self._is_null(value): ...
python
{ "resource": "" }
q52910
Converter.stringify
train
def stringify(self, value, **opts): """Generate a string representation of the data. Inverse of conversion: generate a string representation of the data that is guaranteed to be parseable by this library. """ if self._is_null(value): return None try: ...
python
{ "resource": "" }
q52911
Purrer.is_purrlog
train
def is_purrlog(path): """Checks if path refers to a valid purrlog. Path must exist, and must contain either at least one directory called entry-YYYYMMDD-HHMMSS, or the file "dirconfig" """ if not os.path.isdir(path): return False if list(filter(os.path.isdir, glob.glo...
python
{ "resource": "" }
q52912
Purrer.addWatchedDirectory
train
def addWatchedDirectory(self, dirname, watching=Purr.WATCHED, save_config=True): """Starts watching the specified directories for changes""" # see if we're alredy watching this exact set of directories -- do nothing if so dirname = Purr.canonizePath(dirname) # do nothing if already watch...
python
{ "resource": "" }
q52913
Purrer.setLogEntries
train
def setLogEntries(self, entries, save=True, update_policies=True): """Sets list of log entries. If save=True, saves the log. If update_policies=True, also updates default policies based on these entries""" prev = None; # "previous" valid entry for "Prev" link uplink = os.path.join("..",...
python
{ "resource": "" }
q52914
Purrer._initIndexDir
train
def _initIndexDir(self): """makes sure purrlog directory is properly set up""" if not os.path.exists(self.logdir): os.mkdir(self.logdir) dprint(1, "created", self.logdir) Purr.RenderIndex.initIndexDir(self.logdir)
python
{ "resource": "" }
q52915
Purrer.save
train
def save(self, refresh=False): """Saves the log. If refresh is set to a timestamp, will regenerate everything from scratch. """ # create directory if it doesn't exist # error will be thrown if this is not possible _busy = Purr.BusyIndicator() Purr.progressMessage(...
python
{ "resource": "" }
q52916
Purrer.rescan
train
def rescan(self): """Checks files and directories on watchlist for updates, rescans them for new data products. If any are found, returns them. Skips those in directories whose watchingState is set to Purr.UNWATCHED. """ if not self.attached: return dprint(5, "startin...
python
{ "resource": "" }
q52917
LinkedDocuments.by_type
train
def by_type(self, type_name): ''' Return an iterator of doc_ids of the documents of the specified type. ''' if IRestorator.providedBy(type_name): type_name = type_name.type_name return (x[1] for x in self._links if x[0] == type_name)
python
{ "resource": "" }
q52918
GerritPlugin._ssh_cmd
train
def _ssh_cmd(self, *args): """Execute a gerrit command over SSH. """ command = "gerrit {0}".format(" ".join(args)) _, stdout, stderr = self._client.exec_command(command) return (stdout.readlines(), stderr.readlines())
python
{ "resource": "" }
q52919
factory
train
def factory(raw_data, request): """Class factory to create different types of shades depending on shade type.""" if ATTR_SHADE in raw_data: raw_data = raw_data.get(ATTR_SHADE) shade_type = raw_data.get(ATTR_TYPE) def find_type(shade): for tp in shade.shade_types: if tp....
python
{ "resource": "" }
q52920
BaseShade._create_shade_data
train
def _create_shade_data(self, position_data=None, room_id=None): """Create a shade data object to be sent to the hub""" base = {ATTR_SHADE: {ATTR_ID: self.id}} if position_data: base[ATTR_SHADE][ATTR_POSITION_DATA] = position_data if room_id: base[ATTR_SHADE][ATTR_...
python
{ "resource": "" }
q52921
BaseShade.refresh
train
async def refresh(self): """Query the hub and the actual shade to get the most recent shade data. Including current shade position.""" raw_data = await self.request.get(self._resource_path, {"refresh": "true"}) self._raw_data = raw_data[ATTR_SHADE]
python
{ "resource": "" }
q52922
BaseShade.get_current_position
train
async def get_current_position(self, refresh=True) -> dict: """Return the current shade position. :param refresh: If True it queries the hub for the latest info. :return: Dictionary with position data. """ if refresh: await self.refresh() position = self._raw...
python
{ "resource": "" }
q52923
HandleDeath.restart_complete
train
def restart_complete(self, state, new_address): ''' Called when we get notified that the restart has been completed by some agent who has volontureed to do so. ''' if state.timeout_call_id: state.agent.cancel_delayed_call(state.timeout_call_id) state.timeo...
python
{ "resource": "" }
q52924
HandleDeath._start_collective_solver
train
def _start_collective_solver(self, state): ''' Determines who from all the monitors monitoring this agent should resolve the issue. ''' own_address = state.agent.get_own_address() monitors = [IRecipient(x) for x in state.descriptor.partners if x.role =...
python
{ "resource": "" }
q52925
HandleDeath._retry
train
def _retry(self, state): ''' Starts a single try of the whole restart path. ''' state.attempt += 1 self.debug('Starting restart attempt: %d.', state.attempt) if self._cmp_strategy(RestartStrategy.buryme): self.debug('Agent %r is going to by buried according to...
python
{ "resource": "" }
q52926
HandleDeath._adopt_notifications
train
def _adopt_notifications(self, state): '''Part of the "monitor" restart strategy. The pending notifications from descriptor of dead agent are imported to our pending list.''' def iterator(): it = state.descriptor.pending_notifications.iteritems() for _, nots in it: ...
python
{ "resource": "" }
q52927
HandleDeath._iter_categorized_partners
train
def _iter_categorized_partners(self, state): ''' Iterator over the partners giving as extra param partners of the same category. ''' # categorize partners into the structure # partner_class -> list of its instances categorized = dict() for partner in state...
python
{ "resource": "" }
q52928
acquire_pidfile
train
def acquire_pidfile(rundir, process_type=PROCESS_TYPE, name=None): """ Open a PID file for writing, using the given process type and process name for the filename. The returned file can be then passed to writePidFile after forking. @rtype: str @returns: file object, open for writing """ ...
python
{ "resource": "" }
q52929
write_pidfile
train
def write_pidfile(rundir, process_type=PROCESS_TYPE, name=None, file=None): #@ReservedAssignment """ Write a pid file in the run directory, using the given process type and process name for the filename. @rtype: str @returns: full path to the pid file that was written """ ...
python
{ "resource": "" }
q52930
delete_pidfile
train
def delete_pidfile(rundir, process_type=PROCESS_TYPE, name=None, force=False): """ Delete the pid file in the run directory, using the given process type and process name for the filename. @param force: if errors due to the file not existing should be ignored @type force: bool @rtype: str ...
python
{ "resource": "" }
q52931
validate
train
def validate(idText, alpha, r, cert, caPubkey): """ A server can validate an implicit certificate response using identity string @idText, private value @alpha (used to generate cert request), and the certificate response @r (private key component) and implicit @cert. @raises Exception if the cer...
python
{ "resource": "" }
q52932
recoverPubkey
train
def recoverPubkey(idText, cert, caPubkey): """ A client can recover the server's pubkey using the identity string @idText, server's implicit @cert, and the trusted @caPubkey. """ # Verify types assertType(cert, ec1Element) assertType(caPubkey, ec1Element) # Compute the pubkey return...
python
{ "resource": "" }
q52933
ConfigurationSet.parse_xml_node
train
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a configuration set into this object. ''' self.id = node.getAttributeNS(RTS_NS, 'id') self._config_data = [] for d in node.getElementsByTagNameNS(RTS_NS, 'ConfigurationData'): self._...
python
{ "resource": "" }
q52934
ConfigurationSet.parse_yaml
train
def parse_yaml(self, y): '''Parse a YAML specification of a configuration set into this object. ''' self.id = y['id'] self._config_data = [] if 'configurationData' in y: for d in y.get('configurationData'): self._config_data.append(Configurati...
python
{ "resource": "" }
q52935
ConfigurationSet.save_xml
train
def save_xml(self, doc, element): '''Save this configuration set into an xml.dom.Element object.''' element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id) for c in self._config_data: new_element = doc.createElementNS(RTS_NS, RTS_NS_S + ...
python
{ "resource": "" }
q52936
ConfigurationSet.to_dict
train
def to_dict(self): '''Save this configuration set into a dictionary.''' d = {'id': self.id} data = [] for c in self._config_data: data.append(c.to_dict()) if data: d['configurationData'] = data return d
python
{ "resource": "" }
q52937
ConfigurationData.parse_xml_node
train
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a configuration data into this object. ''' self.name = node.getAttributeNS(RTS_NS, 'name') if node.hasAttributeNS(RTS_NS, 'data'): self.data = node.getAttributeNS(RTS_NS, 'data') els...
python
{ "resource": "" }
q52938
ConfigurationData.parse_yaml
train
def parse_yaml(self, y): '''Parse a YAML specification of a configuration data into this object. ''' self.name = y['name'] if 'data' in y: self.data = y['data'] else: self.data = '' return self
python
{ "resource": "" }
q52939
ConfigurationData.save_xml
train
def save_xml(self, doc, element): '''Save this configuration data into an xml.dom.Element object.''' element.setAttributeNS(RTS_NS, RTS_NS_S + 'name', self.name) if self.data: element.setAttributeNS(RTS_NS, RTS_NS_S + 'data', self.data)
python
{ "resource": "" }
q52940
ConfigurationData.to_dict
train
def to_dict(self): '''Save this configuration data into a dictionary.''' d = {'name': self.name} if self.data: d['data'] = self.data return d
python
{ "resource": "" }
q52941
mutable
train
def mutable(function): '''Combined decorator of guarded.mutable and journal.recorded. When called from outside a recording context, it returns a Deferred. When called from inside a recording context, it returns a L{fiber.Fiber} or any synchronous value. Same as using:: @journal.recorded() ...
python
{ "resource": "" }
q52942
SocketTalk.server
train
def server(addr): """Return a SocketTalk server.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(addr) sock.listen(1) conn, addr = sock.accept() talk = SocketTalk(conn) return...
python
{ "resource": "" }
q52943
SocketTalk.client
train
def client(addr): """Return a SocketTalk client.""" success = False while not success: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect(addr) ...
python
{ "resource": "" }
q52944
SocketTalk.get
train
def get(self): """Receive a message. Return the message upon successful reception, or None upon failure.""" # First retrieve all header bytes in order to extract # length of the message remainder. header = '' while len(header) < self.HEADER_LENGTH: chunk = se...
python
{ "resource": "" }
q52945
normalize
train
def normalize(code): """ Normalize language codes to ISO 639-2. If all conversions fails, return the `code` as it was given. Args: code (str): Language / country code. Returns: str: ISO 639-2 country code. """ if len(code) == 3: return code normalized = transla...
python
{ "resource": "" }
q52946
includeme
train
def includeme(config): """Include persona settings into a pyramid config. This function does the following: * Setup default authentication and authorization policies, and a default session factory. Keep in mind that the sessions are not encrypted, if you need to store secret information in i...
python
{ "resource": "" }
q52947
YeelightBulb.set_color_temperature
train
def set_color_temperature(self, temperature, effect=EFFECT_SUDDEN, transition_time=MIN_TRANSITION_TIME): """ Set the white color temperature. The bulb must be switched on. :param temperature: color temperature to set. It can be between 1700 and 6500 K :param effect: if the c...
python
{ "resource": "" }
q52948
YeelightBulb.set_rgb_color
train
def set_rgb_color(self, red, green, blue, effect=EFFECT_SUDDEN, transition_time=MIN_TRANSITION_TIME): """ Set the color of the bulb using rgb code. The bulb must be switched on. :param red: Red component of the color between 0 and 255 :param green: Green component of the col...
python
{ "resource": "" }
q52949
YeelightBulb.set_brightness
train
def set_brightness(self, brightness, effect=EFFECT_SUDDEN, transition_time=MIN_TRANSITION_TIME): """ This method is used to change the brightness of a smart LED :param brightness: is the target brightness. The type is integer and ranges from 1 to 100. The ...
python
{ "resource": "" }
q52950
YeelightBulb.adjust
train
def adjust(self, action, prop): """ This method is used to change brightness, CT or color of a smart LED without knowing the current value, it's main used by controllers. :param action: The direction of the adjustment. The valid value can be: ...
python
{ "resource": "" }
q52951
remove_elements_with_source
train
def remove_elements_with_source(source, field): """Remove all elements matching ``source`` in ``field``.""" return freeze( [element for element in field if element.get('source', '').lower() != source] )
python
{ "resource": "" }
q52952
keep_only_update_source_in_field
train
def keep_only_update_source_in_field(field, root, head, update): """Remove elements from root and head where ``source`` matches the update. This is useful if the update needs to overwrite all elements with the same source. .. note:: If the update doesn't contain exactly one source in ``field``...
python
{ "resource": "" }
q52953
filter_curated_references
train
def filter_curated_references(root, head, update): """Remove references from either ``head`` or ``update`` depending on curation. If references have been curated, then it removes all references from the update to keep the existing ones. Otherwise, it removes all references from the head to force replac...
python
{ "resource": "" }
q52954
filter_publisher_references
train
def filter_publisher_references(root, head, update): """Remove references from ``update`` if there are any in ``head``. This is useful when merging a record from a publisher with an update form arXiv, as arXiv should never overwrite references from the publisher. """ if 'references' in head: ...
python
{ "resource": "" }
q52955
button
train
def button(request): """If the user is logged in, returns the logout button, otherwise returns the login button""" if not authenticated_userid(request): return markupsafe.Markup(SIGNIN_HTML) else: return markupsafe.Markup(SIGNOUT_HTML)
python
{ "resource": "" }
q52956
js
train
def js(request): """Returns the javascript needed to run persona""" userid = authenticated_userid(request) user = markupsafe.Markup("'%s'")%userid if userid else "null" redirect_paramater = request.registry['persona.redirect_url_parameter'] came_from = '%s%s' % (request.host_url, ...
python
{ "resource": "" }
q52957
EpisodeWorker.run
train
def run(self): """ Run the task - compose full series + add to our results """ empty = False while not empty: try: s = self.series.get() result_dict = itunes.get_rss_feed_data_from_series(s) self.storer.store(result_dict) self.logger.info('Retrieved and stored %...
python
{ "resource": "" }
q52958
crosslisting_feature
train
def crosslisting_feature(catalog, soup): """Parses all the crosslistings. These refer to the similar CRNs, such as a grad & undergrad level course. """ listing = {} for elem in soup.coursedb.findAll('crosslisting'): seats = int(elem['seats']) crns = [safeInt(crn.string) for crn in el...
python
{ "resource": "" }
q52959
CardDb.from_file
train
def from_file(cls, db_file=ALL_SETS_PATH): """Reads card data from a JSON-file. :param db_file: A file-like object or a path. :return: A new :class:`~mtgjson.CardDb` instance. """ if callable(getattr(db_file, 'read', None)): return cls(json.load(db_file)) wi...
python
{ "resource": "" }
q52960
CardDb.from_url
train
def from_url(cls, db_url=ALL_SETS_ZIP_URL): """Load card data from a URL. Uses :func:`requests.get` to fetch card data. Also handles zipfiles. :param db_url: URL to fetch. :return: A new :class:`~mtgjson.CardDb` instance. """ r = requests.get(db_url) r.raise_for...
python
{ "resource": "" }
q52961
Cache.cleanup
train
def cleanup(self, ctime=None): ''' This method is called iteratively by the connection owning it. Its job is to control the size of cache and remove old entries. ''' ctime = ctime or time.time() if self.last_cleanup: self.average_cleanup_time.add_point(ctime -...
python
{ "resource": "" }
q52962
Submit.login
train
def login(self, email=None, password=None): """Login to establish a valid session.""" auth_url = self.url('auth') email = email or self._config.get('email') password = password or self._config.get('password') if password and not email: raise Exception('Email must be p...
python
{ "resource": "" }
q52963
validate_command
train
def validate_command(raw_command): """Validate the command input. Currently we only check the number of arguments according to the command type. Parameters ---------- raw_command: str The raw command input, e.g., `register xxxxxx yyyyyy`. Raises ------ ValueError If th...
python
{ "resource": "" }
q52964
print_tweets
train
def print_tweets(tweets): """Print a list of tweets one by one separated by "="s. Parameters ---------- tweets: list(dict) A list of tweets. Each tweet is a dict containing the username of the tweet's author, the post time, and the tweet body. """ print('=' * 60) for index, ...
python
{ "resource": "" }
q52965
pytwis_clt
train
def pytwis_clt(): """The main routine of this command-line tool.""" epilog = '''After launching `pytwis_clt.py`, you will be able to use the following commands: * Register a new user: 127.0.0.1:6379> register {username} {password} * Log into a user: 127.0.0.1:6379> login {username}...
python
{ "resource": "" }
q52966
synthesizeProperty
train
def synthesizeProperty(propertyName, default = None, contract = None, readOnly = False, privateMemberName = None): """ When applied to a class, this decorator adds a property to it and overrides the constructor in order ...
python
{ "resource": "" }
q52967
named_module
train
def named_module(name): """Returns a module given its name.""" module = __import__(name) packages = name.split(".")[1:] m = module for p in packages: m = getattr(m, p) return m
python
{ "resource": "" }
q52968
list_
train
def list_(): # pylint: disable=redefined-builtin """ Display all MultiplyParameters nodes """ load_dbenv_if_not_loaded( ) # Important to load the dbenv in the last moment from aiida.orm.querybuilder import QueryBuilder from aiida.orm import DataFactory MultiplyParameters = DataFactory...
python
{ "resource": "" }
q52969
export
train
def export(outfile, pk): """Export a MultiplyParameters node, identified by PK, to plain text""" load_dbenv_if_not_loaded( ) # Important to load the dbenv in the last moment from aiida.orm import load_node node = load_node(pk) string = str(node) if outfile: with open(outfile, 'w')...
python
{ "resource": "" }
q52970
BaseResource.query
train
def query(cls, **kwargs): """ Query multiple objects. :param kwargs: The query parameters. The key is the filter parameter and the value is the value to search for. :return: The list of matching objects :raises: A `ValueError` if at least one of the supplied parameters is not in...
python
{ "resource": "" }
q52971
load_psd
train
def load_psd(): """ Resamples advLIGO noise PSD to 4096 Hz """ # psd has freq resolution = 1/3 with 6145 samples psd = np.loadtxt("ZERO_DET_high_P_PSD.txt")[:,1] down_factor = 3 pad_size = int(np.ceil(float(psd.size)/down_factor)*down_factor - psd.size) psd_padded = np.append(psd, np.zeros(pad_s...
python
{ "resource": "" }
q52972
Catalog._fourier
train
def _fourier(self): """ 1 side Fourier transform and scale by dt all waveforms in catalog """ freq_bin_upper = 2000 freq_bin_lower = 40 fs = self._metadata['fs'] Y_transformed = {} for key in self.Y_dict.keys(): # normalize by fs, bins have units strain/Hz ...
python
{ "resource": "" }
q52973
ISS.current_location
train
def current_location(self): """Current location of the ISS. :return: A dict with latitude and longitude of ISS :rtype: dict """ data = requests.get('{}{}'.format( self.API_URL, self.API_CURRENT_LOCATION), timeout=5) if data.status_code is 200: re...
python
{ "resource": "" }
q52974
ISS.pass_times
train
def pass_times(self, latitude, longitude, altitude=None, number=None): """The next pass times of the ISS. :param latitude: latitude in degrees of location you want iss pass above :type latitude: float :param longitude: longitude in degrees of location you want iss pass a...
python
{ "resource": "" }
q52975
ISS.next_rise
train
def next_rise(self, latitude, longitude, altitude=None): """The next rise of the ISS. :param latitude: latitude in degrees of location you want iss pass above :type latitude: float :param longitude: longitude in degrees of location you want iss pass above :type l...
python
{ "resource": "" }
q52976
ISS.is_ISS_above
train
def is_ISS_above(self, latitude, longitude, altitude=None): """Location of the ISS regardin the current location. :param latitude: latitude in degrees of location you want iss pass above :type latitude: float :param longitude: longitude in degrees of location you want iss pass ...
python
{ "resource": "" }
q52977
File.grandparent_path
train
def grandparent_path(self): """ return grandparent's path string """ return os.path.basename(os.path.join(self.path, '../..'))
python
{ "resource": "" }
q52978
File.remove_blank_dirs
train
def remove_blank_dirs(self): """Remove blank dir and all blank subdirectories""" if self.is_blank(): try: os.rmdir(self.path) except OSError as e: print(e) else: remove_empty_dir(self.path)
python
{ "resource": "" }
q52979
arr_normalize
train
def arr_normalize(arr, *args, **kwargs): """ ARGS arr array to normalize **kargs scale = <f_scale> scale the normalized output by <f_scale> DESC Given an input array, <arr>, normalize all values to range between 0 and 1. If specifie...
python
{ "resource": "" }
q52980
shell
train
def shell(command, **kwargs): """ Runs 'command' on the underlying shell and keeps the stdout and stderr stream separate. Returns [stdout, stderr, exitCode] """ b_stdoutflush = False b_stderrflush = False b_waitForChild = True for key, val in kwargs.item...
python
{ "resource": "" }
q52981
touch
train
def touch(fname, times=None): ''' Emulates the UNIX touch command. ''' with io.open(fname, 'a'): os.utime(fname, times)
python
{ "resource": "" }
q52982
Cache.init_extension
train
def init_extension(self, app): """Initialize cache instance.""" app.config.setdefault('CACHE_VERSION', '0') app.config.setdefault('CACHE_PREFIX', 'r') app.config.setdefault('CACHE_BACKEND', 'rio.exts.flask_cache.NullBackend') app.config.setdefault('CACHE_BACKEND_OPTIONS', {})
python
{ "resource": "" }
q52983
Cache.make_key
train
def make_key(self, key, version=None): """RedisCache will set prefix+version as prefix for each key.""" return '{}:{}:{}'.format( self.prefix, version or self.version, key, )
python
{ "resource": "" }
q52984
Cache.get_client
train
def get_client(self): """Get cache client. """ backend_class = import_string(current_app.config.get('CACHE_BACKEND')) backend = backend_class(**current_app.config.get('CACHE_BACKEND_OPTIONS')) return backend
python
{ "resource": "" }
q52985
EmailBackend._only_safe_emails
train
def _only_safe_emails(self, emails): """"Given a list of emails, checks whether they are all in the white list.""" email_modified = False if any(not self._is_whitelisted(email) for email in emails): email_modified = True emails = [email for email in emails if sel...
python
{ "resource": "" }
q52986
EmailBackend._is_whitelisted
train
def _is_whitelisted(self, email): """Check if an email is in the whitelist. If there's no whitelist, it's assumed it's not whitelisted.""" return hasattr(settings, "SAFE_EMAIL_WHITELIST") and \ any(re.match(m, email) for m in settings.SAFE_EMAIL_WHITELIST)
python
{ "resource": "" }
q52987
call_webhook
train
def call_webhook(event, webhook, payload): """Build request from event,webhook,payoad and parse response.""" started_at = time() request = _build_request_for_calling_webhook(event, webhook, payload) logger.info('REQUEST %(uuid)s %(method)s %(url)s %(payload)s' % dict( uuid=str(event['uuid']), ...
python
{ "resource": "" }
q52988
merge_webhooks_runset
train
def merge_webhooks_runset(runset): """Make some statistics on the run set. """ min_started_at = min([w['started_at'] for w in runset]) max_ended_at = max([w['ended_at'] for w in runset]) ellapse = max_ended_at - min_started_at errors_count = sum(1 for w in runset if 'error' in w) total_coun...
python
{ "resource": "" }
q52989
exec_event
train
def exec_event(event, webhooks, payload): """Execute event. Merge webhooks run set to do some stats after all of the webhooks been responded successfully. +---------+ |webhook-1+--------------------+ +---------+ | | +---------+ ...
python
{ "resource": "" }
q52990
download
train
def download(url): """ Download `url` and return it as utf-8 encoded text. Args: url (str): What should be downloaded? Returns: str: Content of the page. """ headers = {"User-Agent": USER_AGENT} resp = requests.get( url, timeout=REQUEST_TIMEOUT, head...
python
{ "resource": "" }
q52991
StartAgent._update_descriptor
train
def _update_descriptor(self, state, allocation): '''Sometime creating the descriptor for new agent we cannot know in which shard it will endup. If it is None or set to lobby, the HA will update the field to match his own''' if state.descriptor.shard is None or state.descriptor.shard == '...
python
{ "resource": "" }
q52992
fail_perm
train
def fail_perm(item): '''Fail a work-item permanatly by mv'ing it to queue's fail directory''' # The only thing we require to fail is an item_id and a queue # as an item may fail permanently due to malformed item_id-ness item_id = item.id trg_queue = item.queue host = item.host try: o...
python
{ "resource": "" }
q52993
done
train
def done(item, done_type=None, max_tries=None, ttl=None): '''Wrapper for any type of finish, successful, permanant failure or temporary failure''' if done_type is None or done_type == _c.FSQ_SUCCESS: return success(item) return fail(item, fail_type=done_type, max_tries=max_tries, ttl=ttl)
python
{ "resource": "" }
q52994
fail
train
def fail(item, fail_type=None, max_tries=None, ttl=None): '''Fail a work item, either temporarily or permanently''' # default to fail_perm if fail_type is not None and fail_type == _c.FSQ_FAIL_TMP: return fail_tmp(item, max_tries=max_tries, ttl=ttl) return fail_perm(item)
python
{ "resource": "" }
q52995
Service.send
train
def send(self, request): '''send a request to self.url authenticated with self.auth''' return self.session.send(request(self.url, self.auth))
python
{ "resource": "" }
q52996
EpisodesDriver.eps_from_series
train
def eps_from_series(self): """ Workhorse function that handles grabbing series data from csvs and requesting episodal information from RSS feeds """ csvs = [] for _, _, filenames in os.walk('./{}'.format(self.directory)): csvs.extend(filenames) series_set = set() for c in csvs: ...
python
{ "resource": "" }
q52997
NotificationSender.notify
train
def notify(self, state, notifications): ''' Call this to schedule sending partner notification. ''' def do_append(desc, notifications): for notification in notifications: if not isinstance(notification, PendingNotification): raise ValueErr...
python
{ "resource": "" }
q52998
usage
train
def usage(asked_for=0): '''Exit with a usage string, used for bad argument or with -h''' exit = fsq.const('FSQ_SUCCESS') if asked_for else\ fsq.const('FSQ_FAIL_PERM') f = sys.stdout if asked_for else sys.stderr shout('{0} [opts] src_queue trg_queue host item_id [item_id [...]]'.format( ...
python
{ "resource": "" }
q52999
Renderer.create_software_renderer
train
def create_software_renderer(self, surface): """Create a 2D software rendering context for a surface. Args: surface (Surface): The surface where rendering is done. Returns: Renderer: A 2D software rendering context. Raises: SDLError: If there was an...
python
{ "resource": "" }