_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q54900
PickleProxy.notify
train
def notify(self, method, *args, **kwargs): """Perform a synchronous remote call where value no return value is desired. While faster than call it still blocks until the remote callback has been sent. This may block for sometime in certain situations. If it takes more than the Proxies s...
python
{ "resource": "" }
q54901
PickleProxy.response
train
def response(self, msgid, response): """Handle a response message.""" self.requests[msgid].callback(response) del self.requests[msgid]
python
{ "resource": "" }
q54902
PickleProxy.error
train
def error(self, msgid, error): """Handle a error message.""" self.requests[msgid].errback(error) del self.requests[msgid]
python
{ "resource": "" }
q54903
PickleProtocol.connection_made
train
def connection_made(self, address): """When a connection is made the proxy is available.""" self._proxy = PickleProxy(self.loop, self) for d in self._proxy_deferreds: d.callback(self._proxy)
python
{ "resource": "" }
q54904
PickleProtocol.data
train
def data(self, data): """Use a length prefixed protocol to give the length of a pickled message. """ self._buffer = self._buffer + data while self._data_handler(): pass
python
{ "resource": "" }
q54905
PickleProtocol.handle_notification
train
def handle_notification(self, msgtype, method, args, kwargs): """Handle a notification.""" self.dispatch.call(method, args, kwargs)
python
{ "resource": "" }
q54906
PickleProtocol.handle_response
train
def handle_response(self, msgtype, msgid, response): """Handle a response.""" self._proxy.response(msgid, response)
python
{ "resource": "" }
q54907
PickleProtocol.handle_error
train
def handle_error(self, msgtype, msgid, error): """Handle an error.""" self._proxy.error(msgid, error)
python
{ "resource": "" }
q54908
PickleProtocol.send_request
train
def send_request(self, msgid, method, args, kwargs): """Send a request.""" msg = dumps([0, msgid, method, args, kwargs]) self.send(msg)
python
{ "resource": "" }
q54909
PickleProtocol.send_notification
train
def send_notification(self, method, args, kwargs): """Send a notification.""" msg = dumps([1, method, args, kwargs]) self.send(msg)
python
{ "resource": "" }
q54910
PickleProtocol.send_response
train
def send_response(self, msgid, response): """Send a response.""" msg = dumps([2, msgid, response]) self.send(msg)
python
{ "resource": "" }
q54911
PickleProtocol.send_error
train
def send_error(self, msgid, error): """Send an error.""" msg = dumps([3, msgid, error]) self.send(msg)
python
{ "resource": "" }
q54912
TCPServerUi.start_tcp_server
train
def start_tcp_server(self, port): """ Starts the TCP server using given port. :param port: Port. :type port: int :return: Method success. :rtype: bool """ self.__tcp_server.port = port if not self.__tcp_server.online: if self.__tcp_se...
python
{ "resource": "" }
q54913
TCPClientUi.send_data_to_server
train
def send_data_to_server(self, data, time_out=5): """ Sends given data to the Server. :param data: Data to send. :type data: unicode :param time_out: Connection timeout in seconds. :type time_out: float :return: Method success. :rtype: bool """ ...
python
{ "resource": "" }
q54914
ContextMiddleware.get_url
train
def get_url(self, environ): """Return the base URL.""" if self.override_url: url = self.override_url else: # PEP333: wsgi.url_scheme, HTTP_HOST, SERVER_NAME, and SERVER_PORT # can be used to reconstruct a request's complete URL # Much of the follo...
python
{ "resource": "" }
q54915
ContextMiddleware.populate_context
train
def populate_context(self, context, environ): """Set initial context values.""" url = self.get_url(environ) context['base_url'] = url transaction_id = uuid.uuid4().hex context['transaction_id'] = transaction_id LOG.debug("Context created: base_url=%s, tid=%s", url, transa...
python
{ "resource": "" }
q54916
vd
train
def vd(inc, sd): """ Calculate vertical distance. :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units """ return abs(sd * math.sin(math.radians(inc)))
python
{ "resource": "" }
q54917
Client.call
train
def call(self, method, *args, **kw): """ In context of a batch we return the request's ID else we return the actual json """ if args and kw: raise ValueError("JSON-RPC method calls allow only either named or positional arguments.") if not method: r...
python
{ "resource": "" }
q54918
SplitableFASTA.status
train
def status(self): """Has the splitting been done already ?""" if all(os.path.exists(p.path) for p in self.parts): return 'splitted' return False
python
{ "resource": "" }
q54919
DirHashCache.clear
train
def clear(self): """ Remove all cache entries. """ db = sqlite3.connect(self.path) c = db.cursor() c.execute("DELETE FROM dirhashcache") db.commit() db.close()
python
{ "resource": "" }
q54920
DirHashCache.dirhash
train
def dirhash(self, path, **dirhash_opts): """ Compute the hash of a directory. Arguments: path: Directory. **dirhash_opts: Additional options to checksumdir.dirhash(). Returns: str: Checksum of directory. """ path = fs.path(path) ...
python
{ "resource": "" }
q54921
Table.read_contents
train
def read_contents(self, schema, name, conn): '''Read table columns''' sql = ''' with schemas as (select n.oid, n.nspname as name from pg_catalog.pg_namespace n), tables as (select c.oid, c.relnamespace as schema_oid, c.relname as name from pg_catalog.pg_class c where c.relkin...
python
{ "resource": "" }
q54922
Charger.sendCommand
train
def sendCommand(self, command): """Sends a command through the web interface of the charger and parses the response""" data = { 'rapi' : command } full_url = self.url + urllib.parse.urlencode(data) data = urllib.request.urlopen(full_url) response = re.search('\<p>&gt;\$(.+)\<script', data.read().dec...
python
{ "resource": "" }
q54923
Charger.getStatus
train
def getStatus(self): """Returns the charger's charge status, as a string""" command = '$GS' status = self.sendCommand(command) return states[int(status[1])]
python
{ "resource": "" }
q54924
Charger.getServiceLevel
train
def getServiceLevel(self): """Returns the service level""" command = '$GE' settings = self.sendCommand(command) flags = int(settings[2], 16) return (flags & 0x0001) + 1
python
{ "resource": "" }
q54925
Charger.getLCDType
train
def getLCDType(self): """Returns LCD type as a string, either monochrome or rgb""" command = '$GE' settings = self.sendCommand(command) flags = int(settings[2], 16) if flags & 0x0100: lcdtype = 'monochrome' else: lcdtype = 'rgb' return lcdtype
python
{ "resource": "" }
q54926
Charger.getChargingCurrent
train
def getChargingCurrent(self): """Returns the charging current, in amps, or 0.0 of not charging""" command = '$GG' currentAndVoltage = self.sendCommand(command) amps = float(currentAndVoltage[1])/1000 return amps
python
{ "resource": "" }
q54927
Charger.getChargingVoltage
train
def getChargingVoltage(self): """Returns the charging voltage, in volts, or 0.0 of not charging""" command = '$GG' currentAndVoltage = self.sendCommand(command) volts = float(currentAndVoltage[2])/1000 return volts
python
{ "resource": "" }
q54928
Charger.getAmbientThreshold
train
def getAmbientThreshold(self): """Returns the ambient temperature threshold in degrees Celcius, or 0 if no Threshold is set""" command = '$GO' threshold = self.sendCommand(command) if threshold[0] == 'NK': return 0 else: return float(threshold[1])/10
python
{ "resource": "" }
q54929
Charger.getIRThreshold
train
def getIRThreshold(self): """Returns the IR temperature threshold in degrees Celcius, or 0 if no Threshold is set""" command = '$GO' threshold = self.sendCommand(command) if threshold[0] == 'NK': return 0 else: return float(threshold[2])/10
python
{ "resource": "" }
q54930
Charger.getTime
train
def getTime(self): """Get the RTC time. Returns a datetime object, or NULL if the clock is not set""" command = '$GT' time = self.sendCommand(command) if time == ['OK','165', '165', '165', '165', '165', '85']: return NULL else: return datetime.datetime(year = int(time[1])+2000, ...
python
{ "resource": "" }
q54931
Connector.start
train
def start(self): """Start the connector state machine.""" if self.started: raise ConnectorStartedError() self.started = True try: self.connect_watcher.start() self.timeout_watcher.start() self.sock.connect(self.addr) except IOErro...
python
{ "resource": "" }
q54932
Connector.cancel
train
def cancel(self): """Cancel a connector from completing.""" if self.started and not self.connected and not self.timedout: self.connect_watcher.stop() self.timeout_watcher.stop()
python
{ "resource": "" }
q54933
Connector._connected
train
def _connected(self, watcher, events): """Connector is successful, return the socket.""" self.connected = True self._finish() self.deferred.callback(self.sock)
python
{ "resource": "" }
q54934
Connector._timeout
train
def _timeout(self, watcher, events): """Connector timed out, raise a timeout error.""" self.timedout = True self._finish() self.deferred.errback(TimeoutError())
python
{ "resource": "" }
q54935
SocketClient._connect
train
def _connect(self, sock, addr, timeout): """Start watching the socket for it to be writtable.""" if self.connection: raise SocketClientConnectedError() if self.connector: raise SocketClientConnectingError() self.connect_deferred = Deferred(self.loop) sel...
python
{ "resource": "" }
q54936
SocketClient._connected
train
def _connected(self, sock): """When the socket is writtable, the socket is ready to be used.""" logger.debug('socket connected, building protocol') self.protocol = self.factory.build(self.loop) self.connection = Connection(self.loop, self.sock, self.addr, self.protocol, self)...
python
{ "resource": "" }
q54937
get_week_start_end_day
train
def get_week_start_end_day(): """ Get the week start date and end date """ t = date.today() wd = t.weekday() return (t - timedelta(wd), t + timedelta(6 - wd))
python
{ "resource": "" }
q54938
get_month_start_end_day
train
def get_month_start_end_day(): """ Get the month start date a nd end date """ t = date.today() n = mdays[t.month] return (date(t.year, t.month, 1), date(t.year, t.month, n))
python
{ "resource": "" }
q54939
transformation_matrix
train
def transformation_matrix(x_vector, y_vector, translation, spacing): """ Creates a transformation matrix which will convert from a specified coordinate system to the scanner frame of reference. :param x_vector: The unit vector along the space X axis in scanner coordinates :param y_vector: The unit ...
python
{ "resource": "" }
q54940
always
train
def always(func: Callable[[], Generator]) -> AlwaysFixture: """Decorator that registers an 'always' fixture, which is always run before all provider state fixtures and faasport call. """ global user_always if user_always is not None: raise RuntimeError('Multiple definitions of @always fixtu...
python
{ "resource": "" }
q54941
parse_args
train
def parse_args(args=None): """ Parse arguments provided as a list of strings, and return a namespace with parameter names matching the arguments :param args: List of strings to be parsed as command-line arguments. If none, reads in sys.argv as the values. :return: a namespace containing arg...
python
{ "resource": "" }
q54942
Base._conv
train
def _conv(self,v): """Convert Python values to MySQL values""" if isinstance(v,str): return '"%s"' %v.replace("'","''") elif isinstance(v,datetime.datetime): if v.tzinfo is not None: raise ValueError,\ "datetime instances with tz...
python
{ "resource": "" }
q54943
sort_dependencies
train
def sort_dependencies(objects): """ Sort a list of instances by their model dependancy graph. This is very similar to Django's sort_dependencies method except for two big differences: 1. We graph dependencies unrelated to natural_key. 2. We take a list of objects, and return a sorted list of o...
python
{ "resource": "" }
q54944
ProjectsModel.__initialize_model
train
def __initialize_model(self): """ Initializes the Model. """ LOGGER.debug("> Initializing model.") self.beginResetModel() self.root_node = umbra.ui.nodes.DefaultNode(name="InvisibleRootNode") self.__default_project_node = ProjectNode(name=self.__default_project,...
python
{ "resource": "" }
q54945
ProjectsModel.list_editors
train
def list_editors(self, node=None): """ Returns the Model editors. :param node: Node to start walking from. :type node: AbstractNode or AbstractCompositeNode or Object :return: Editors. :rtype: list """ return [editor_node.editor for editor_node in self.l...
python
{ "resource": "" }
q54946
ProjectsModel.list_files
train
def list_files(self, node=None): """ Returns the Model files. :param node: Node to start walking from. :type node: AbstractNode or AbstractCompositeNode or Object :return: FileNode nodes. :rtype: list """ return [file_node.path for file_node in self.list...
python
{ "resource": "" }
q54947
ProjectsModel.list_projects
train
def list_projects(self, ignore_default_project_node=True): """ Returns the Model projects. :param ignore_default_project_node: Default ProjectNode will be ignored. :type ignore_default_project_node: bool :return: ProjectNode nodes. :rtype: list """ retur...
python
{ "resource": "" }
q54948
ProjectsModel.move_node
train
def move_node(self, parent, from_index, to_index): """ Moves given parent child to given index. :param to_index: Index to. :type to_index: int :param from_index: Index from. :type from_index: int :return: Method success. :rtype: bool """ ...
python
{ "resource": "" }
q54949
ProjectsModel.register_file
train
def register_file(self, file, parent, ensure_uniqueness=False): """ Registers given file in the Model. :param file: File to register. :type file: unicode :param parent: FileNode parent. :type parent: GraphModelNode :param ensure_uniqueness: Ensure registrar uniqu...
python
{ "resource": "" }
q54950
ProjectsModel.register_directory
train
def register_directory(self, directory, parent, ensure_uniqueness=False): """ Registers given directory in the Model. :param directory: Directory to register. :type directory: unicode :param parent: DirectoryNode parent. :type parent: GraphModelNode :param ensure...
python
{ "resource": "" }
q54951
ProjectsModel.register_project
train
def register_project(self, path, ensure_uniqueness=False): """ Registers given path in the Model as a project. :param path: Project path to register. :type path: unicode :param ensure_uniqueness: Ensure registrar uniqueness. :type ensure_uniqueness: bool :return:...
python
{ "resource": "" }
q54952
ProjectsModel.is_authoring_node
train
def is_authoring_node(self, node): """ Returns if given Node is an authoring node. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Is authoring node. :rtype: bool """ for parent_node in foundations.walkers.nodes_walker(no...
python
{ "resource": "" }
q54953
ProjectsModel.set_authoring_nodes
train
def set_authoring_nodes(self, editor): """ Sets the Model authoring Nodes using given editor. :param editor: Editor to set. :type editor: Editor :return: Method success. :rtype: bool """ project_node = self.default_project_node file_node = self.r...
python
{ "resource": "" }
q54954
ProjectsModel.delete_authoring_nodes
train
def delete_authoring_nodes(self, editor): """ Deletes the Model authoring Nodes associated with given editor. :param editor: Editor. :type editor: Editor :return: Method success. :rtype: bool """ editor_node = foundations.common.get_first_item(self.get_e...
python
{ "resource": "" }
q54955
ProjectsModel.update_authoring_nodes
train
def update_authoring_nodes(self, editor): """ Updates given editor Model authoring nodes. :param editor: Editor. :type editor: Editor :return: Method success. :rtype: bool """ editor_node = foundations.common.get_first_item(self.get_editor_nodes(editor))...
python
{ "resource": "" }
q54956
ProjectsModel.set_project_nodes
train
def set_project_nodes(self, root_node, maximum_depth=1): """ Sets the project Model children Nodes using given root node. :param root_node: Root node. :type root_node: ProjectNode or DirectoryNode :param maximum_depth: Maximum nodes nesting depth. :type maximum_depth: in...
python
{ "resource": "" }
q54957
ProjectsModel.unregister_project_nodes
train
def unregister_project_nodes(self, node): """ Unregisters given Node children. :param node: Node. :type node: ProjectNode or DirectoryNode """ for node in reversed(list(foundations.walkers.nodes_walker(node))): if node.family == "Directory": ...
python
{ "resource": "" }
q54958
LanguagesModel.sort_languages
train
def sort_languages(self, order=Qt.AscendingOrder): """ Sorts the Model languages. :param order: Order. ( Qt.SortOrder ) """ self.beginResetModel() self.__languages = sorted(self.__languages, key=lambda x: (x.name), reverse=order) self.endResetModel()
python
{ "resource": "" }
q54959
LanguagesModel.get_language
train
def get_language(self, name): """ Returns the language with given name. :param name: Language name. :type name: unicode :return: File language. :rtype: Language """ for language in self.__languages: if language.name == name: L...
python
{ "resource": "" }
q54960
LanguagesModel.get_file_language
train
def get_file_language(self, file): """ Returns the language of given file. :param file: File to get language of. :type file: unicode :return: File language. :rtype: Language """ for language in self.__languages: if re.search(language.extensio...
python
{ "resource": "" }
q54961
PatternsModel.insert_pattern
train
def insert_pattern(self, pattern, index): """ Inserts given pattern into the Model. :param pattern: Pattern. :type pattern: unicode :param index: Insertion index. :type index: int :return: Method success. :rtype: bool """ LOGGER.debug("> ...
python
{ "resource": "" }
q54962
PatternsModel.remove_pattern
train
def remove_pattern(self, pattern): """ Removes given pattern from the Model. :param pattern: Pattern. :type pattern: unicode :return: Method success. :rtype: bool """ for index, node in enumerate(self.root_node.children): if node.name != patt...
python
{ "resource": "" }
q54963
SearchResultsModel.get_metrics
train
def get_metrics(self): """ Returns the Model metrics. :return: Nodes metrics. :rtype: dict """ search_file_nodes_count = search_occurence_nodesCount = 0 for node in foundations.walkers.nodes_walker(self.root_node): if node.family == "SearchFile": ...
python
{ "resource": "" }
q54964
Form._init_fields
train
def _init_fields(self): """Creates the `_fields`, `_forms` asn `_sets` dicts. Any properties which begin with an underscore or are not `Field`, `Form` or `FormSet` **instances** are ignored by this method. """ fields = {} forms = {} sets = {} for name in...
python
{ "resource": "" }
q54965
Form._init_data
train
def _init_data(self, data, obj, files): """Load the data into the form. """ data = self.prepare(data) # Initialize sub-forms for name, subform in self._forms.items(): obj_value = get_obj_value(obj, name) if inspect.isclass(subform): fclass...
python
{ "resource": "" }
q54966
Form.is_valid
train
def is_valid(self): """Return whether the current values of the form fields are all valid. """ self.cleaned_data = {} self.changed_fields = [] self.validated = False self._errors = {} self._named_errors = {} cleaned_data = {} changed_fields = [] ...
python
{ "resource": "" }
q54967
Form.save_to
train
def save_to(self, obj): """Save the cleaned data to an object. """ if isinstance(obj, dict): obj = dict(obj) for key in self.changed_fields: if key in self.cleaned_data: val = self.cleaned_data.get(key) set_obj_value(obj, key, val)...
python
{ "resource": "" }
q54968
clean
train
def clean(): """remove build artifacts""" shutil.rmtree('{PROJECT_NAME}.egg-info'.format(PROJECT_NAME=PROJECT_NAME), ignore_errors=True) shutil.rmtree('build', ignore_errors=True) shutil.rmtree('dist', ignore_errors=True) shutil.rmtree('htmlcov', ignore_errors=True) shutil.rmtree('__pycache__', ...
python
{ "resource": "" }
q54969
coverage
train
def coverage(): """check code coverage quickly with the default Python""" run("coverage run --source {PROJECT_NAME} -m py.test".format(PROJECT_NAME=PROJECT_NAME)) run("coverage report -m") run("coverage html") webbrowser.open('file://' + os.path.realpath("htmlcov/index.html"), new=2)
python
{ "resource": "" }
q54970
Manifest._parse_version
train
def _parse_version(self, line): """ There's a magic suffix to the release version, currently it's -03, but it increments seemingly randomly. """ version_string = line.split(' ')[1] version_list = version_string.split('.') major_version = ''.join([version_list[0], ...
python
{ "resource": "" }
q54971
Manifest._parse_manifest
train
def _parse_manifest(self): """ Read the defined file, parse and set Version line, and return generator of filenames. """ with open(self.manifest_file, 'r') as f: for line in f: if line.startswith("Version"): self.mver, self.relnum = self._p...
python
{ "resource": "" }
q54972
attach_parser
train
def attach_parser(subparser): """Given a subparser, build and return the server parser.""" return subparser.add_parser( 'server', help='Run a bottle based server', parents=[ CONFIG.build_parser( add_help=False, # might need conflict_handler ...
python
{ "resource": "" }
q54973
fmt_pairs
train
def fmt_pairs(obj, indent=4, sort_key=None): """Format and sort a list of pairs, usually for printing. If sort_key is provided, the value will be passed as the 'key' keyword argument of the sorted() function when sorting the items. This allows for the input such as [('A', 3), ('B', 5), ('Z', 1)] to...
python
{ "resource": "" }
q54974
fmt_routes
train
def fmt_routes(bottle_app): """Return a pretty formatted string of the list of routes.""" routes = [(r.method, r.rule) for r in bottle_app.routes] if not routes: return string = 'Routes:\n' string += fmt_pairs(routes, sort_key=operator.itemgetter(1)) return string
python
{ "resource": "" }
q54975
build_application
train
def build_application(conf): """Do some setup and return the wsgi app.""" if isinstance(conf.adapter_options, list): conf['adapter_options'] = {key: val for _dict in conf.adapter_options for key, val in _dict.items()} elif conf.adapter_options is None: conf...
python
{ "resource": "" }
q54976
run
train
def run(conf, build_app=True): """Run server based on this configuration. If build_app is True, simpl will use your config to build and configure your wsgi application. If you have built and configured your application (conf.app) already, set build_app to false. Expects configuration options d...
python
{ "resource": "" }
q54977
EventletLogFilter.write
train
def write(self, text): """Write to appropriate target.""" if text: if text[0] in '(w': # write thread and wsgi messages to debug only self.log.debug(text[:-1]) return if self.access_log: self.access_log.write(text) ...
python
{ "resource": "" }
q54978
XEventletServer.get_socket
train
def get_socket(self): """Create listener socket based on bottle server parameters.""" import eventlet # Separate out socket.listen arguments socket_args = {} for arg in ('backlog', 'family'): try: socket_args[arg] = self.options.pop(arg) e...
python
{ "resource": "" }
q54979
XEventletServer.run
train
def run(self, handler): """Start bottle server.""" import eventlet.patcher if not eventlet.patcher.is_monkey_patched(os): msg = ("%s requires eventlet.monkey_patch() (before " "import)" % self.__class__.__name__) raise RuntimeError(msg) # Separ...
python
{ "resource": "" }
q54980
Generic_Code.get_cse_code
train
def get_cse_code(self, exprs, basename=None, dummy_groups=(), arrayify_groups=()): """ Get arrayified code for common subexpression. Parameters ---------- exprs : list of sympy expressions basename : str Stem of variable names (default: cse). ...
python
{ "resource": "" }
q54981
Generic_Code.mod
train
def mod(self): """ Cached compiled binary of the Generic_Code class. To clear cache invoke :meth:`clear_mod_cache`. """ if self._mod is None: self._mod = self.compile_and_import_binary() return self._mod
python
{ "resource": "" }
q54982
Stack.get_files
train
def get_files(self): """ Read and parse files from a directory, return a dictionary of path => post """ files = {} for filename in os.listdir(self.source): path = os.path.join(self.source, filename) files[filename] = frontmatter.load(path, ...
python
{ "resource": "" }
q54983
Stack.run
train
def run(self): "Run each middleware function on files" # load files from source directory files = self.get_files() # loop through each middleware for func in self.middleware: # call each one, ignoring return value func(files, self) # store and r...
python
{ "resource": "" }
q54984
Stack.iter
train
def iter(self, reset=False, reverse=False): """ Yield processed files one at a time, in natural order. """ files = os.listdir(self.source) files.sort(reverse=reverse) for filename in files: try: yield self.get(filename, reset) exce...
python
{ "resource": "" }
q54985
Stack.get
train
def get(self, filename, reset=False): """ Get a single processed file. Uses a cached version if `run` has already been called, unless `reset` is True. """ if filename in self.files and not reset: return self.files[filename] # load a single file, and process ...
python
{ "resource": "" }
q54986
Stack.serialize
train
def serialize(self, as_dict=False, sort=None): """ Dump built files as a list or dictionary, for JSON or other serialization. sort: a key function to sort a list, or simply True """ files = getattr(self, 'files', self.run()) if as_dict: return dict((fn, ...
python
{ "resource": "" }
q54987
Connection._process_attachments
train
def _process_attachments(self, attachments): """ Create attachments suitable for delivery to Hectane from the provided list of attachments. Each attachment may be either a local filename, a file object, or a dict describing the content (in the same format as Hectane). Note that ...
python
{ "resource": "" }
q54988
Connection.raw
train
def raw(self, from_, to, body): """ Send a raw MIME message. """ if isinstance(to, string_types): raise TypeError('"to" parameter must be enumerable') return self._session.post('{}/raw'.format(self._url), json={ 'from': from_, 'to': to, ...
python
{ "resource": "" }
q54989
Macros._static
train
def _static(self, target, value): """PHP's "static" """ return 'static ' + self.__p(ast.Assign(targets=[target],value=value))
python
{ "resource": "" }
q54990
_pad
train
def _pad(input_signal, length, average=10): """ Helper function which increases the length of an input signal. The original is inserted at the centre of the new signal and the extra values are set to the average of the first and last parts of the original, respectively. :param input_signal: the sig...
python
{ "resource": "" }
q54991
ContextFactory.getContext
train
def getContext(self): """Get the parent context but disable SSLv3.""" ctx = ClientContextFactory.getContext(self) ctx.set_options(OP_NO_SSLv3) return ctx
python
{ "resource": "" }
q54992
complex_to_real
train
def complex_to_real(complex_fid): """ Standard optimization routines as used in lmfit require real data. This function takes a complex FID and constructs a real version by concatenating the imaginary part to the complex part. The imaginary part is also reversed to keep the maxima at each end of the ...
python
{ "resource": "" }
q54993
real_to_complex
train
def real_to_complex(real_fid): """ Standard optimization routines as used in lmfit require real data. This function takes a real FID generated from the optimization routine and converts it back into a true complex form. :param real_fid: the real FID to be converted to complex. :return: the comp...
python
{ "resource": "" }
q54994
render_q
train
def render_q(q, qn, connection): """ Renders the Q object into SQL for the WHEN clause. Uses as much as possible the Django ORM machinery for SQL generation, handling table aliases, field quoting, parameter escaping etc. :param q: Q object representing the filter condition :param qn: db specif...
python
{ "resource": "" }
q54995
FASTA.first
train
def first(self): """Just the first sequence""" self.open() seq = SeqIO.parse(self.handle, self.format).next() self.close() return seq
python
{ "resource": "" }
q54996
FASTA.create
train
def create(self): """Create the file on the file system.""" self.buffer = [] self.buf_count = 0 if not self.directory.exists: self.directory.create() self.open('w') return self
python
{ "resource": "" }
q54997
FASTA.add_seq
train
def add_seq(self, seq): """Use this method to add a SeqRecord object to this fasta.""" self.buffer.append(seq) self.buf_count += 1 if self.buf_count % self.buffer_size == 0: self.flush()
python
{ "resource": "" }
q54998
FASTA.add_str
train
def add_str(self, seq, name=None, description=""): """Use this method to add a sequence as a string to this fasta.""" self.add_seq(SeqRecord(Seq(seq), id=name, description=description))
python
{ "resource": "" }
q54999
FASTA.flush
train
def flush(self): """Empty the buffer.""" for seq in self.buffer: SeqIO.write(seq, self.handle, self.format) self.buffer = []
python
{ "resource": "" }