_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q53600
Zyre.whispers
train
def whispers(self, peer, format, *args): """ Send formatted string to a single peer specified as UUID string """ return lib.zyre_whispers(self._as_parameter_, peer, format, *args)
python
{ "resource": "" }
q53601
Zyre.shouts
train
def shouts(self, group, format, *args): """ Send formatted string to a named group """ return lib.zyre_shouts(self._as_parameter_, group, format, *args)
python
{ "resource": "" }
q53602
Zyre.peers_by_group
train
def peers_by_group(self, name): """ Return zlist of current peers of this group. """ return czmq.Zlist(lib.zyre_peers_by_group(self._as_parameter_, name), True)
python
{ "resource": "" }
q53603
Zyre.peer_header_value
train
def peer_header_value(self, peer, name): """ Return the value of a header of a conected peer. Returns null if peer or key doesn't exits. """ return return_fresh_string(lib.zyre_peer_header_value(self._as_parameter_, peer, name))
python
{ "resource": "" }
q53604
Zyre.require_peer
train
def require_peer(self, uuid, endpoint, public_key): """ Explicitly connect to a peer """ return lib.zyre_require_peer(self._as_parameter_, uuid, endpoint, public_key)
python
{ "resource": "" }
q53605
DomainAPI.info
train
def info(self, domain_id=None, domain=None): '''Get information for a specific domain Specify a domain by either ``domain_id`` or ``domain``, if both are specified, then ``domain_id`` is used. :param str domain_id: Domain ID :param str domain: Domain :return: Do...
python
{ "resource": "" }
q53606
NodeVisitor.visit
train
def visit(self, node): """Visit the right method of the child class according to the node.""" method = 'visit_' + type(node).__name__ return getattr(self, method, self.fallback)(node)
python
{ "resource": "" }
q53607
postprocess_periodical
train
def postprocess_periodical(marc_xml, mods, uuid, counter, url): """ Some basic postprocessing of the periodical publications. Args: marc_xml (str): Original Aleph record. mods (str): XML string generated by XSLT template. uuid (str): UUID of the package. counter (int): Numbe...
python
{ "resource": "" }
q53608
DefaultCompleter.__set_cache
train
def __set_cache(self, tokens): """ Sets the tokens cache. :param tokens: Completer tokens list. :type tokens: tuple or list """ if DefaultCompleter._DefaultCompleter__tokens.get(self.__language): return DefaultCompleter._DefaultCompleter__tokens[sel...
python
{ "resource": "" }
q53609
DefaultCompleter.update_model
train
def update_model(self, words): """ Updates the completer model. :param words: Words to update the completer with. :type words: tuple or list :return: Method success. :rtype: bool """ extended_words = DefaultCompleter._DefaultCompleter__tokens[self.__lang...
python
{ "resource": "" }
q53610
CommanderProtocol.signedOn
train
def signedOn(self): """Called after successfully signing on to the server.""" log.info("Signed on as %s.", self.nickname) if not self.password: # We aren't wating for auth, join all the channels self.joinChannels() else: self.msg("NickServ", "IDENTIFY ...
python
{ "resource": "" }
q53611
CommanderProtocol.process_action
train
def process_action(self, raw_user, channel, raw_message): """Called when a message is received from a channel or user.""" log.info("%s %s %s", channel, raw_user, raw_message) if not raw_user: # ignore server messages return # This monster of a regex extracts msg...
python
{ "resource": "" }
q53612
CommanderProtocol.connectionLost
train
def connectionLost(self, reason): """Called when the connection is lost to the server.""" self.factory.loader.db.session.commit() if reactor.running: reactor.stop()
python
{ "resource": "" }
q53613
CommanderProtocol.userKicked
train
def userKicked(self, kickee, channel, kicker, message): """Called when I see another user get kicked.""" self.dispatch('population', 'userKicked', kickee, channel, kicker, message)
python
{ "resource": "" }
q53614
CommanderProtocol.dispatch
train
def dispatch(self, category, func, *args): """Dispatch an event to all listening plugins.""" self.factory.loader.runPlugins(category, func, self, *args)
python
{ "resource": "" }
q53615
PluginLoader.dependencies_satisfied
train
def dependencies_satisfied(self, plugin): """ Checks whether a plugin's dependencies are satisfied. Logs an error if there is an unsatisfied dependencies Returns: Bool """ for depends in plugin.dependencies: if depends not in self.config['plugins']: ...
python
{ "resource": "" }
q53616
PluginLoader.runPlugins
train
def runPlugins(self, category, func, protocol, *args): """ Run the specified set of plugins against a given protocol. """ # Plugins are already sorted by priority for plugin in self.plugins: # If a plugin throws an exception, we should catch it gracefully. ...
python
{ "resource": "" }
q53617
PreferencesManager.set_logging_formatter
train
def set_logging_formatter(self): """ Sets the logging formatter. """ for handler in (RuntimeGlobals.logging_console_handler, RuntimeGlobals.logging_file_handler, RuntimeGlobals.logging_session_handler): handler and handler.setF...
python
{ "resource": "" }
q53618
envvar_profile_cls
train
def envvar_profile_cls(profile_cls=None, **profile_cls_options) -> typing.Type[EnvvarProfile]: """ A class decorator that makes the decorated class a sub-class of EnvvarProfile and transforms its type annotations into envvar profile properties. """ def decorator(profile_cls): profile_option...
python
{ "resource": "" }
q53619
envvar_profile
train
def envvar_profile( profile_root: str, profile_properties: typing.Dict[str, typing.Optional[str]] = None, **profile_properties_as_kwargs, ) -> EnvvarProfile: """ Creates an EnvvarProfile instance without the need for an explicit declaration of the envvar profile class. """ if profile_propert...
python
{ "resource": "" }
q53620
EnvvarProfile.load
train
def load( cls, name=None, parent_name=None, profile_is_live=False, values=None, defaults=None ) -> "EnvvarProfile": """ Get a loaded frozen instance of a specific profile. """ instance = cls( name=name, parent_name=parent_name, profile_is_l...
python
{ "resource": "" }
q53621
EnvvarProfile.has_prop_value
train
def has_prop_value(self, prop: typing.Union[str, EnvvarProfileProperty]) -> bool: """ Returns True if the property has a concrete value set either via environment variables or on the froze profile instance. If a property only has a default value set, this returns False. """ ...
python
{ "resource": "" }
q53622
EnvvarProfile.to_envvars
train
def to_envvars(self): """ Export property values to a dictionary with environment variable names as keys. """ export = {} for prop_name in self.profile_properties: prop = self._get_prop(prop_name) value = self[prop_name] if value is not None: ...
python
{ "resource": "" }
q53623
EnvvarProfile.create_env
train
def create_env(self, include_activation=True, **props) -> "Environment": """ Create a custom dictionary of environment variables representing an environment by passing values of properties as keyword arguments. Values of properties not mentioned in the env will be taken from the ...
python
{ "resource": "" }
q53624
Environment.applied
train
def applied( self, context: typing.Any = None, setenv: typing.Callable = operator.setitem, delenv: typing.Callable = None, getenv: typing.Callable = operator.getitem, ): """ Apply this environment to the context. If no context is supplied, os.environ ...
python
{ "resource": "" }
q53625
gower_normalization
train
def gower_normalization(K, out=None): """Perform Gower normalizion on covariance matrix K. The rescaled covariance matrix has sample variance of 1. """ c = (K.shape[0] - 1) / (K.trace() - K.mean(0).sum()) if out is None: return c * K copyto(out, K) out *= c
python
{ "resource": "" }
q53626
Search_worker.__search
train
def __search(self): """ Performs the search. """ self.__search_results = [] editorsFiles = self.__container.default_target in self.__location.targets and \ [editor.file for editor in self.__container.script_editor.list_editors()] or [] self.__sear...
python
{ "resource": "" }
q53627
Search_worker.__search_files
train
def __search_files(self, files): """ Searches in given files. :param files: Files. :type files: list """ for file in files: if self.__interrupt: return if not foundations.common.path_exists(file): continue ...
python
{ "resource": "" }
q53628
Search_worker.__search_document
train
def __search_document(self, document, pattern, settings): """ Searches for given pattern occurrences in given document using given settings. :param document: Document. :type document: QTextDocument :param pattern: Pattern. :type pattern: unicode :param settings: ...
python
{ "resource": "" }
q53629
run
train
def run(command, num_retries=1, timeout=-1, **kwargs): """ Run a command with optional timeout and retries. Provides a convenience method for executing a subprocess with additional error handling. Arguments: command (list of str): The command to execute. num_retries (int, optional)...
python
{ "resource": "" }
q53630
sed
train
def sed(match, replacement, path, modifiers=""): """ Perform sed text substitution. """ cmd = "sed -r -i 's/%s/%s/%s' %s" % (match, replacement, modifiers, path) process = Subprocess(cmd, shell=True) ret, out, err = process.run(timeout=60) if ret: raise SubprocessError("Sed command ...
python
{ "resource": "" }
q53631
echo
train
def echo(*args, **kwargs): """ Write a message to a file. Arguments: args A list of arguments which make up the message. The last argument is the path to the file to write to. """ msg = args[:-1] path = fs.path(args[-1]) append = kwargs.pop("append", False) if appen...
python
{ "resource": "" }
q53632
which
train
def which(program, path=None): """ Returns the full path of shell commands. Replicates the functionality of system which (1) command. Looks for the named program in the directories indicated in the $PATH environment variable, and returns the full path if found. Examples: >>> system.wh...
python
{ "resource": "" }
q53633
scp
train
def scp(host, src, dst, user=None, path=None): """ Copy a file or directory from a remote location. A thin wrapper around the scp (1) system command. If the destination already exists, this will attempt to overwrite it. Arguments: host (str): name of the host src (str): path ...
python
{ "resource": "" }
q53634
isprocess
train
def isprocess(pid, error=False): """ Check that a process is running. Arguments: pid (int): Process ID to check. Returns: True if the process is running, else false. """ try: # Don't worry folks, no processes are harmed in the making of # this system call: ...
python
{ "resource": "" }
q53635
Subprocess.run
train
def run(self, timeout=-1): """ Run the subprocess. Arguments: timeout (optional) If a positive real value, then timout after the given number of seconds. Raises: SubprocessError If subprocess has not completed after "timeout" seco...
python
{ "resource": "" }
q53636
todjango
train
def todjango(table, model, update=True, create=True, use_bulk_create=True, *args, **kwargs): ''' Given a table with appropriate headings create Django models. ''' assert issubclass(model, Model), 'Must be supplied a valid Django model class' table_iterator = iter(table) table_headers = tab...
python
{ "resource": "" }
q53637
_get_django_objects
train
def _get_django_objects(model): ''' Given a Django model class get all of the current records that match. This is better than django's bulk methods and has no upper limit. ''' model_name = model.__class__.__name__ model_objects = [i for i in model.objects.all()] logger.debug('Found {}...
python
{ "resource": "" }
q53638
_chunked_bulk_create
train
def _chunked_bulk_create(django_model_object, unsaved_models, chunk_size=None): '''Create new models using bulk_create in batches of `chunk_size`. This is designed to overcome a query size limitation in some databases''' if chunk_size is None: chunk_size = getattr(settings, 'BULK_CREATE_CHUNK_SI...
python
{ "resource": "" }
q53639
parse_primers
train
def parse_primers(self, primers=None, mismatches=0, revcompl=False): """This functions starts with self because it's meant as an extension to the FASTA class.""" # Default primers # if primers is None: primers = self.primers # Case straight # if not revcompl: fwd_regex = regex.compile("...
python
{ "resource": "" }
q53640
VehicleDomain.remove
train
def remove(self, vehID, reason=tc.REMOVE_VAPORIZED): '''Remove vehicle with the given ID for the give reason. Reasons are defined in module constants and start with REMOVE_''' self._connection._sendByteCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.REMOVE, vehID, reason)
python
{ "resource": "" }
q53641
Manifest.initialize
train
def initialize(self, version, force=False): """ Initialize the manifest document in the given datamodel :param version: Actual version of the datamodel :param force: Replace manifest if it already exists """ _check_version_format(version) if not force and self.co...
python
{ "resource": "" }
q53642
Manifest.update
train
def update(self, version, reason=None): """ Modify the datamodel's manifest :param version: New version of the manifest :param reason: Optional reason of the update (i.g. "Update from x.y.z") """ _check_version_format(version) return self.collection.update({'_id'...
python
{ "resource": "" }
q53643
MongoPatcher.discover_and_apply
train
def discover_and_apply(self, directory=None, dry_run=False): """ Retrieve the patches and try to apply them against the datamodel :param directory: Directory to search the patch in (default: patches_dir) :param dry_run: Don't actually apply the patches """ directory = di...
python
{ "resource": "" }
q53644
Patch.can_be_applied
train
def can_be_applied(self, manifest, db): """ Check the current datamodel state fulfill the requirements to run this patch """ if manifest.version != self.base_version: raise DatamodelManifestError( "Datamodel's manifest shows incompatible version to " ...
python
{ "resource": "" }
q53645
Patch.apply
train
def apply(self, manifest, db, force=False): """ Run the given patch to update the datamodel :return: the list of post-scriptum returned by the fixes """ fixes_pss = [] if not force: self.can_be_applied(manifest, db) for fix in self.fixes: ...
python
{ "resource": "" }
q53646
Project.__updateDataItem
train
def __updateDataItem(self): """Updates dataItem.""" uri = self.getUri() self.__dataItem = self.__parseResponseServer(uri)
python
{ "resource": "" }
q53647
Project.__parseDatasets
train
def __parseDatasets(self): """Returns the list of Dataset related to the project.""" datasets = [] if self.__dataItem.has_key('dataSets'): for dataset in self.__dataItem['dataSets']: datasets.append(DataSet(Sitools2Abstract.getBaseUrl(self), dataset)) return d...
python
{ "resource": "" }
q53648
Project.getImage
train
def getImage(self): """Returns the project image when available.""" value = self.__getNone(self.__dataItem['image']['url']) if value == None: return None else: return Sitools2Abstract.getBaseUrl(self) + self.__dataItem['image']['url']
python
{ "resource": "" }
q53649
DataSet.__parseColumns
train
def __parseColumns(self): """Returns the list of columns related to the dataset.""" columns = [] if self.__dataItem.has_key('columnModel'): for column in self.__dataItem['columnModel']: columns.append(Column(column)) return columns
python
{ "resource": "" }
q53650
DataSet.updateDataset
train
def updateDataset(self): """Updates the dataset.""" self.__updateDataItem() self.__countNbRecords() self.__columns = self.__parseColumns()
python
{ "resource": "" }
q53651
DataSet.getSearch
train
def getSearch(self): """Returns the search capability.""" return Search(self.getColumns(), Sitools2Abstract.getBaseUrl(self) + self.getUri())
python
{ "resource": "" }
q53652
mapTrace
train
def mapTrace(trace, net, delta, verbose=False): """ matching a list of 2D positions to consecutive edges in a network """ result = [] paths = {} if verbose: print("mapping trace with %s points" % len(trace)) for pos in trace: newPaths = {} candidates = net.getNeighbor...
python
{ "resource": "" }
q53653
path
train
def path(*components): """ Get a file path. Concatenate all components into a path. """ _path = os.path.join(*components) _path = os.path.expanduser(_path) return _path
python
{ "resource": "" }
q53654
must_exist
train
def must_exist(*components): """ Ensure path exists. Arguments: *components (str[]): Path components. Returns: str: File path. Raises: File404: If path does not exist. """ _path = path(*components) if not exists(_path): raise File404(_path) return _...
python
{ "resource": "" }
q53655
is_subdir
train
def is_subdir(child, parent): """ Determine if "child" is a subdirectory of "parent". If child == parent, returns True. """ child_path = os.path.realpath(child) parent_path = os.path.realpath(parent) if len(child_path) < len(parent_path): return False for i in range(len(parent...
python
{ "resource": "" }
q53656
cdpop
train
def cdpop(): """ Return the last directory. Returns absolute path to new working directory. """ if len(_cdhist) >= 1: old = _cdhist.pop() # Pop from history. os.chdir(old) return old else: return pwd()
python
{ "resource": "" }
q53657
isexe
train
def isexe(*components): """ Return whether a path is an executable file. Arguments: path (str): Path of the file to check. Examples: >>> fs.isexe("/bin/ls") True >>> fs.isexe("/home") False >>> fs.isexe("/not/a/real/path") False Returns:...
python
{ "resource": "" }
q53658
ls
train
def ls(root=".", abspaths=False, recursive=False): """ Return a list of files in directory. Directory listings are sorted alphabetically. If the named directory is a file, return it's path. Examples: >>> fs.ls("foo") ["a", "b", "c"] >>> fs.ls("foo/a") ["foo/a"] ...
python
{ "resource": "" }
q53659
lsdirs
train
def lsdirs(root=".", **kwargs): """ Return only subdirectories from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of directory paths. Raise...
python
{ "resource": "" }
q53660
lsfiles
train
def lsfiles(root=".", **kwargs): """ Return only files from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of file paths. Raises: O...
python
{ "resource": "" }
q53661
cp
train
def cp(src, dst): """ Copy a file or directory. If source is a directory, this recursively copies the directory and its contents. If the destination is a directory, then this creates a copy of the source in the destination directory with the same basename. If the destination already exists...
python
{ "resource": "" }
q53662
mv
train
def mv(src, dst): """ Move a file or directory. If the destination already exists, this will attempt to overwrite it. Arguments: src (string): path to the source file or directory. dst (string): path to the destination file or directory. Raises: File404: if source do...
python
{ "resource": "" }
q53663
mkdir
train
def mkdir(*components, **kwargs): """ Make directory "path", including any required parents. If directory already exists, do nothing. """ _path = path(*components) if not isdir(_path): os.makedirs(_path, **kwargs) return _path
python
{ "resource": "" }
q53664
read
train
def read(*components, **kwargs): """ Read file and return a list of lines. If comment_char is set, ignore the contents of lines following the comment_char. Raises: IOError: if reading path fails """ rstrip = kwargs.get("rstrip", True) comment_char = kwargs.get("comment_char", None)...
python
{ "resource": "" }
q53665
du
train
def du(*components, **kwargs): """ Get the size of a file in bytes or as a human-readable string. Arguments: *components (str[]): Path to file. **kwargs: If "human_readable" is True, return a formatted string, e.g. "976.6 KiB" (default True) Returns: int or str: If "...
python
{ "resource": "" }
q53666
read_file
train
def read_file(path): """ Read file to string. Arguments: path (str): Source. """ with open(must_exist(path)) as infile: r = infile.read() return r
python
{ "resource": "" }
q53667
files_from_list
train
def files_from_list(*paths): """ Return a list of all file paths from a list of files or directories. For each path in the input: if it is a file, return it; if it is a directory, return a list of files in the directory. Arguments: paths (list of str): List of file and directory paths. ...
python
{ "resource": "" }
q53668
pdf
train
def pdf(options): """Generate PDF output. Use Sphinx to produce LaTeX, then use external tools such as TeXLive to convert the .tex file to a PDF. This task uses the following options, searching first in the "pdf" then "sphinx" section of the options. docroot the root under which Sphinx ...
python
{ "resource": "" }
q53669
run_sphinx
train
def run_sphinx(options, *option_sets): """Helper function to run sphinx with common options. Pass the names of namespaces to be used in the search path for options. The "sphinx" namespace is automatically added to the end of the list, so passing (options, 'html') causes the options to be configure...
python
{ "resource": "" }
q53670
_get_and_create_paths
train
def _get_and_create_paths(options): """Retrieves and creates paths needed to run sphinx. Returns a Bundle with the required values filled in. """ paths = _get_paths(options) paths.builddir.mkdir_p() paths.outdir.mkdir_p() paths.doctrees.mkdir_p() return paths
python
{ "resource": "" }
q53671
_get_paths
train
def _get_paths(options): """Retrieves paths needed to run sphinx. Returns a Bundle with the required values filled in. """ opts = options docroot = path(opts.get('docroot', 'docs')) if not docroot.exists(): raise BuildFailure("Sphinx documentation root (%s) does not exist." ...
python
{ "resource": "" }
q53672
run_script
train
def run_script(input_file, script_name, interpreter='python', include_prefix=True, ignore_error=False, trailing_newlines=True, break_lines_at=0, line_break_mode='break', adjust_python_for_version=True, ...
python
{ "resource": "" }
q53673
_runcog
train
def _runcog(options, files, uncog=False): """Common function for the cog and runcog tasks.""" options.order('cog', 'sphinx', add_rest=True) c = Cog() if uncog: c.options.bNoGenerate = True c.options.bReplace = True c.options.bDeleteCode = options.get("delete_code", False) includedir ...
python
{ "resource": "" }
q53674
cog
train
def cog(options): """Run cog against all or a subset of the input source files. Examples:: $ paver cog PyMOTW/atexit $ paver cog PyMOTW/atexit/index.rst $ paver cog See help on paver.doctools.cog for details on the standard options. """ options.order('cog', 'sphinx', add_res...
python
{ "resource": "" }
q53675
require_server
train
def require_server(fn): """ Checks if the user has called the task with a server name. Fabric tasks decorated with this decorator must be called like so:: fab <server name> <task name> If no server name is given, the task will not be executed. """ @wraps(fn) def wrapper(*args, **...
python
{ "resource": "" }
q53676
init_patcher
train
def init_patcher(app, db): """ Init mongopatcher for the application :param app: :class:`flask.Flask` app to initialize :param db: :class:`pymongo.MongoClient` to work on .. note: This function must be called before using ``patcher_manager`` """ app.config.setdefault('MONGOPATCHER_PATCHES_...
python
{ "resource": "" }
q53677
upgrade
train
def upgrade(yes, dry_run, patches): """ Upgrade the datamodel by applying recusively the patches available """ patcher = _get_mongopatcher() if dry_run: patcher.discover_and_apply(directory=patches, dry_run=dry_run) else: if (yes or prompt_bool("Are you sure you want to alter %s"...
python
{ "resource": "" }
q53678
discover
train
def discover(patches, verbose, name): """List the patches available in the given patches directory""" patches = _get_mongopatcher().discover(directory=patches) if name: import re patches = [p for p in patches if re.match(name, p.target_version)] if not patches: print('No patches ...
python
{ "resource": "" }
q53679
init
train
def init(version, force): """Initialize mongopatcher on the database by setting it manifest""" version = version or current_app.config['MONGOPATCHER_DATAMODEL_VERSION'] _get_mongopatcher().manifest.initialize(version, force) print('Datamodel initialized to version %s' % version)
python
{ "resource": "" }
q53680
info
train
def info(verbose): """Show version of the datamodel""" if _get_mongopatcher().manifest.is_initialized(): print('Datamodel version: %s' % _get_mongopatcher().manifest.version) if verbose: print('\nUpdate history:') for update in reversed(_get_mongopatcher().manifest.histor...
python
{ "resource": "" }
q53681
statsd_middleware_factory
train
def statsd_middleware_factory(app, handler): """Send the application stats to statsd.""" @coroutine def middleware(request): """Send stats to statsd.""" timer = Timer() timer.start() statsd = yield from app.ps.metrics.client() pipe = statsd.pipe() pipe.incr('...
python
{ "resource": "" }
q53682
Plugin.setup
train
def setup(self, app): """Parse and prepare the plugin's configuration.""" super().setup(app) self.enabled = len(self.cfg.backends) self.default = self.cfg.default if not self.default and self.enabled: self.default = self.cfg.backends[0][0] self.backends_has...
python
{ "resource": "" }
q53683
Plugin.client
train
def client(self, name=None): """Initialize a backend's client with given name or default.""" name = name or self.default if not name: return NullClient(self, None, None) params = self.backends_hash[name] ccls = self.backends_schemas.get(params.scheme, TCPClient) ...
python
{ "resource": "" }
q53684
Plugin.send
train
def send(self, stat, value, backend=None): """Send stat to backend.""" client = yield from self.client(backend) if not client: return False client.send(stat, value) client.disconnect()
python
{ "resource": "" }
q53685
AbstractClient.build_message
train
def build_message(self, stat, value): """Build a metric in Graphite format.""" return ' '.join((self.prefix + str(stat), str(value), str(round(time()))))
python
{ "resource": "" }
q53686
UDPClient._send
train
def _send(self, *messages): """Send message.""" if not self.transport: return False messages = [message.encode('ascii') for message in messages] data = b'' while messages: message = messages.pop(0) if len(data + message) + 1 > self.parent.cfg....
python
{ "resource": "" }
q53687
StatsDMixin.timing
train
def timing(self, stat, delta, rate=1): """Send new timing information. `delta` is in milliseconds.""" return self.send(stat, "%d|ms" % delta, rate)
python
{ "resource": "" }
q53688
load_config
train
def load_config(settings): '''Load settings from configfile''' config = ConfigParser() section = 'pgdocgen' try: config.read(settings['configfile']) except Exception as e: sys.stderr.write('Failed to read config: ' + str(e)) sys.exit(1) for option in config.options(sectio...
python
{ "resource": "" }
q53689
server_main
train
def server_main(loop, path): """Run in the client after the fork.""" loop.fork() logger.debug('forked function') sigintwatcher = pyev.Signal(signal.SIGINT, loop, lambda watcher, events: logger.info('interrupt ignored')) sigintwatcher.start() sigtermwatcher = pyev.Signal(signal.SIGTERM, loop, ser...
python
{ "resource": "" }
q53690
_set_package_directory
train
def _set_package_directory(): """ Sets the Application package directory in the path. """ package_directory = os.path.normpath(os.path.join(os.path.dirname(__file__), "../")) package_directory not in sys.path and sys.path.append(package_directory)
python
{ "resource": "" }
q53691
define_options
train
def define_options(default_conf): """ Define the options from default.conf dynamically """ default = {} with open(default_conf, 'rb') as f: exec_in(native_str(f.read()), {}, default) for name, value in default.iteritems(): # if the option is already defined by tornado # ...
python
{ "resource": "" }
q53692
log_config
train
def log_config(): """Logs the config used to start the application""" conf = '\n'.join( ['{}="{}"'.format(k, v) for k, v in sorted(options.as_dict().iteritems())]) logging.info('Service started with the following settings:\n' + conf)
python
{ "resource": "" }
q53693
ssl_server_options
train
def ssl_server_options(): """ ssl options for tornado https server these options are defined in each application's default.conf file if left empty, use the self generated keys and certificates included in this package. this function is backward compatible with python version lower than 2.7.9...
python
{ "resource": "" }
q53694
log_formatter
train
def log_formatter(request=None): """ Log formatter used in our syslog :param request: a request object :returns: logging.Formatter """ if request: format_str = ('%(asctime)s {ip} {name}: ENV={env} ' 'REMOTE_IP=%(remote_ip)s REQUEST_ID=%(request_id)s ' ...
python
{ "resource": "" }
q53695
configure_syslog
train
def configure_syslog(request=None, logger=None, exceptions=False): """ Configure syslog logging channel. It is turned on by setting `syslog_host` in the config file. The port default to 514 can be overridden by setting `syslog_port`. :param request: tornado.httputil.HTTPServerRequest instance :...
python
{ "resource": "" }
q53696
make_application
train
def make_application(version, app_name, app_urls, kwargs=None): """ Loads the routes and starts the server :param version: the application version :param app_name: the application name :param app_urls: a list of application endpoints :param kwargs: dictionary of options :returns: tornado.we...
python
{ "resource": "" }
q53697
make_server
train
def make_server(application, conf_dir=None): """ Configure the server return the server instance """ if conf_dir: load_config(conf_dir) configure_syslog() log_config() if options.use_ssl: ssl_options = ssl_server_options() server = tornado.httpserver.HTTPServer( ...
python
{ "resource": "" }
q53698
highlight_matching_symbols_pairs
train
def highlight_matching_symbols_pairs(editor): """ Highlights given editor matching pairs. :param editor: Document editor. :type editor: QWidget :return: Method success. :rtype: bool """ format = editor.language.theme.get("accelerator.pair") if not format: return False ...
python
{ "resource": "" }
q53699
transform_to_mods_mono
train
def transform_to_mods_mono(marc_xml, uuid, url): """ Convert `marc_xml` to MODS data format. Args: marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. uuid (str): UUID string giving the package ID. url (str): URL of the publication ...
python
{ "resource": "" }