_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q51100 | Spatial.emit | train | def emit(self, sound, exclude=set()):
"""Send text to entities nearby this one."""
nearby = self.nearby()
try:
exclude = set(exclude)
except TypeError:
exclude = set([exclude])
exclude.add(self.entity)
listeners = nearby - exclude
for liste... | python | {
"resource": ""
} |
q51101 | get_version_rank | train | def get_version_rank(version):
"""
Converts a version string to it's rank.
Usage::
>>> get_version_rank("4.2.8")
4002008000000
>>> get_version_rank("4.0")
4000000000000
>>> get_version_rank("4.2.8").__class__
<type 'int'>
:param version: Current version... | python | {
"resource": ""
} |
q51102 | get_splitext_basename | train | def get_splitext_basename(path):
"""
Gets the basename of a path without its extension.
Usage::
>>> get_splitext_basename("/Users/JohnDoe/Documents/Test.txt")
u'Test'
:param path: Path to extract the basename without extension.
:type path: unicode
:return: Splitext basename.
... | python | {
"resource": ""
} |
q51103 | get_common_ancestor | train | def get_common_ancestor(*args):
"""
Gets common ancestor of given iterables.
Usage::
>>> get_common_ancestor(("1", "2", "3"), ("1", "2", "0"), ("1", "2", "3", "4"))
(u'1', u'2')
>>> get_common_ancestor("azerty", "azetty", "azello")
u'aze'
:param \*args: Iterables to re... | python | {
"resource": ""
} |
q51104 | get_common_paths_ancestor | train | def get_common_paths_ancestor(*args):
"""
Gets common paths ancestor of given paths.
Usage::
>>> get_common_paths_ancestor("/Users/JohnDoe/Documents", "/Users/JohnDoe/Documents/Test.txt")
u'/Users/JohnDoe/Documents'
:param \*args: Paths to retrieve common ancestor from.
:type \*ar... | python | {
"resource": ""
} |
q51105 | get_words | train | def get_words(data):
"""
Extracts the words from given string.
Usage::
>>> get_words("Users are: John Doe, Jane Doe, Z6PO.")
[u'Users', u'are', u'John', u'Doe', u'Jane', u'Doe', u'Z6PO']
:param data: Data to extract words from.
:type data: unicode
:return: Words.
:rtype: l... | python | {
"resource": ""
} |
q51106 | filter_words | train | def filter_words(words, filters_in=None, filters_out=None, flags=0):
"""
Filters the words using the given filters.
Usage::
>>> filter_words(["Users", "are", "John", "Doe", "Jane", "Doe", "Z6PO"], filters_in=("John", "Doe"))
[u'John', u'Doe', u'Doe']
>>> filter_words(["Users", "are... | python | {
"resource": ""
} |
q51107 | replace | train | def replace(string, data):
"""
Replaces the data occurrences in the string.
Usage::
>>> replace("Users are: John Doe, Jane Doe, Z6PO.", {"John" : "Luke", "Jane" : "Anakin", "Doe" : "Skywalker",
"Z6PO" : "R2D2"})
u'Users are: Luke Skywalker, Anakin Skywalker, R2D2.'
:param str... | python | {
"resource": ""
} |
q51108 | to_forward_slashes | train | def to_forward_slashes(data):
"""
Converts backward slashes to forward slashes.
Usage::
>>> to_forward_slashes("To\Forward\Slashes")
u'To/Forward/Slashes'
:param data: Data to convert.
:type data: unicode
:return: Converted path.
:rtype: unicode
"""
data = data.re... | python | {
"resource": ""
} |
q51109 | to_backward_slashes | train | def to_backward_slashes(data):
"""
Converts forward slashes to backward slashes.
Usage::
>>> to_backward_slashes("/Users/JohnDoe/Documents")
u'\\Users\\JohnDoe\\Documents'
:param data: Data to convert.
:type data: unicode
:return: Converted path.
:rtype: unicode
"""
... | python | {
"resource": ""
} |
q51110 | to_posix_path | train | def to_posix_path(path):
"""
Converts Windows path to Posix path while stripping drives letters and network server slashes.
Usage::
>>> to_posix_path("c:\\Users\\JohnDoe\\Documents")
u'/Users/JohnDoe/Documents'
:param path: Windows path.
:type path: unicode
:return: Path conve... | python | {
"resource": ""
} |
q51111 | get_normalized_path | train | def get_normalized_path(path):
"""
Normalizes a path, escaping slashes if needed on Windows.
Usage::
>>> get_normalized_path("C:\\Users/johnDoe\\Documents")
u'C:\\Users\\JohnDoe\\Documents'
:param path: Path to normalize.
:type path: unicode
:return: Normalized path.
:rtyp... | python | {
"resource": ""
} |
q51112 | is_email | train | def is_email(data):
"""
Check if given data string is an email.
Usage::
>>> is_email("john.doe@domain.com")
True
>>> is_email("john.doe:domain.com")
False
:param data: Data to check.
:type data: unicode
:return: Is email.
:rtype: bool
"""
if re.mat... | python | {
"resource": ""
} |
q51113 | is_website | train | def is_website(url):
"""
Check if given url string is a website.
Usage::
>>> is_website("http://www.domain.com")
True
>>> is_website("domain.com")
False
:param data: Data to check.
:type data: unicode
:return: Is website.
:rtype: bool
"""
if re.mat... | python | {
"resource": ""
} |
q51114 | Estimator.observe | train | def observe(self, value):
"""Samples an observation's value.
Args:
value: A numeric value signifying the value to be sampled.
"""
self._buffer.append(value)
if len(self._buffer) == _BUFFER_SIZE:
self._flush() | python | {
"resource": ""
} |
q51115 | Estimator.query | train | def query(self, rank):
"""Retrieves the value estimate for the requested quantile rank.
The requested quantile rank must be registered in the estimator's
invariants a priori!
Args:
rank: A floating point quantile rank along the interval [0, 1].
Returns:
... | python | {
"resource": ""
} |
q51116 | Estimator._flush | train | def _flush(self):
"""Purges the buffer and commits all pending values into the estimator."""
self._buffer.sort()
self._replace_batch()
self._buffer = []
self._compress() | python | {
"resource": ""
} |
q51117 | Estimator._replace_batch | train | def _replace_batch(self):
"""Incorporates all pending values into the estimator."""
if not self._head:
self._head, self._buffer = self._record(self._buffer[0], 1, 0, None), self._buffer[1:]
rank = 0.0
current = self._head
for b in self._buffer:
if b < self... | python | {
"resource": ""
} |
q51118 | Estimator._record | train | def _record(self, value, rank, delta, successor):
"""Catalogs a sample."""
self._observations += 1
self._items += 1
return _Sample(value, rank, delta, successor) | python | {
"resource": ""
} |
q51119 | Estimator._invariant | train | def _invariant(self, rank, n):
"""Computes the delta value for the sample."""
minimum = n + 1
for i in self._invariants:
delta = i._delta(rank, n)
if delta < minimum:
minimum = delta
return math.floor(minimum) | python | {
"resource": ""
} |
q51120 | Estimator._compress | train | def _compress(self):
"""Prunes the cataloged observations."""
rank = 0.0
current = self._head
while current and current._successor:
if current._rank + current._successor._rank + current._successor._delta <= self._invariant(rank, self._observations):
removed =... | python | {
"resource": ""
} |
q51121 | _is_path | train | def _is_path(instance, attribute, s, exists=True):
"Validator for path-yness"
if not s:
# allow False as a default
return
if exists:
if os.path.exists(s):
return
else:
raise OSError("path does not exist")
else:
# how do we tell if it's a pa... | python | {
"resource": ""
} |
q51122 | get_attribute_compound | train | def get_attribute_compound(attribute, value=None, splitter="|", binding_identifier="@"):
"""
Returns an attribute compound.
Usage::
>>> data = "@Link | Value | Boolean | Link Parameter"
>>> attribute_compound = foundations.parsers.get_attribute_compound("Attribute Compound", data)
... | python | {
"resource": ""
} |
q51123 | SectionsFileParser.section_exists | train | def section_exists(self, section):
"""
Checks if given section exists.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser(... | python | {
"resource": ""
} |
q51124 | SectionsFileParser.attribute_exists | train | def attribute_exists(self, attribute, section):
"""
Checks if given attribute exists.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = Sect... | python | {
"resource": ""
} |
q51125 | SectionsFileParser.get_attributes | train | def get_attributes(self, section, strip_namespaces=False):
"""
Returns given section attributes.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_pa... | python | {
"resource": ""
} |
q51126 | SectionsFileParser.get_all_attributes | train | def get_all_attributes(self):
"""
Returns all sections attributes.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
... | python | {
"resource": ""
} |
q51127 | SectionsFileParser.get_value | train | def get_value(self, attribute, section, default=""):
"""
Returns requested attribute value.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser ... | python | {
"resource": ""
} |
q51128 | SectionsFileParser.set_value | train | def set_value(self, attribute, section, value):
"""
Sets requested attribute value.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = Sectio... | python | {
"resource": ""
} |
q51129 | PlistFileParser.parse | train | def parse(self, raise_parsing_errors=True):
"""
Process the file content.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.elements.keys()
[u'Dictionary A', u'N... | python | {
"resource": ""
} |
q51130 | PlistFileParser.element_exists | train | def element_exists(self, element):
"""
Checks if given element exists.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.element_exists("String A")
True
... | python | {
"resource": ""
} |
q51131 | PlistFileParser.get_value | train | def get_value(self, element):
"""
| Returns the given element value.
| If multiple elements with the same name exists, only the first encountered will be returned.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
... | python | {
"resource": ""
} |
q51132 | IncrementalMmWriter.add_vector | train | def add_vector(self, vector):
"""\
Writes the provided vector to the matrix.
`vector`
An iterable of ``(word-id, word-frequency)`` tuples
"""
self._num_docs+=1
max_id, veclen = self._mmw.write_vector(self._num_docs, vector)
self._num_terms = max(self.... | python | {
"resource": ""
} |
q51133 | IncrementalMmWriter.close | train | def close(self):
"""\
Closes the writer.
This method MUST be called once all vectors are added.
"""
self._mmw.fake_headers(self._num_docs+1, self._num_terms, self._num_nnz)
self._mmw.close() | python | {
"resource": ""
} |
q51134 | psycopg2_wait_callback | train | def psycopg2_wait_callback(conn):
"""A wait callback to allow greenlet to work with Psycopg.
The caller must be from a greenlet other than the main one.
:param conn: psycopg2 connection or file number
This function must be invoked from a coroutine with parent, therefore
invoking it from the main g... | python | {
"resource": ""
} |
q51135 | _wait_fd | train | def _wait_fd(conn, read=True):
'''Wait for an event on file descriptor ``fd``.
:param conn: file descriptor
:param read: wait for a read event if ``True``, otherwise a wait
for write event.
This function must be invoked from a coroutine with parent, therefore
invoking it from the main gree... | python | {
"resource": ""
} |
q51136 | Reactor.shutdown | train | def shutdown(self, message=None):
"""Disconnect all servers with a message.
Args:
message (str): Quit message to use on each connection.
"""
for name, server in self.servers.items():
server.quit(message) | python | {
"resource": ""
} |
q51137 | Reactor.create_server | train | def create_server(self, server_name, *args, **kwargs):
"""Create an IRC server connection slot.
The server will actually be connected to when
:meth:`girc.client.ServerConnection.connect` is called later.
Args:
server_name (str): Name of the server, to be used for functions ... | python | {
"resource": ""
} |
q51138 | Reactor._destroy_server | train | def _destroy_server(self, server_name):
"""Destroys the given server, called internally."""
try:
del self.servers[server_name]
except KeyError:
pass
if self.auto_close and not self.servers:
loop.stop() | python | {
"resource": ""
} |
q51139 | Reactor.handler | train | def handler(self, direction, verb, priority=10):
"""Register this function as an event handler.
Args:
direction (str): ``in``, ``out``, ``both``, ``raw``.
verb (str): Event name.
priority (int): Handler priority (lower priority executes first).
Example:
... | python | {
"resource": ""
} |
q51140 | parse_uk_postcode | train | def parse_uk_postcode(postcode, strict=True, incode_mandatory=True):
'''Split UK postcode into outcode and incode portions.
Arguments:
postcode The postcode to be split.
strict If true, the postcode will be validated according to
the rules as specified at... | python | {
"resource": ""
} |
q51141 | now_time | train | def now_time(str=False):
"""Get the current time."""
if str:
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return datetime.datetime.now() | python | {
"resource": ""
} |
q51142 | now_date | train | def now_date(str=False):
"""Get the current date."""
if str:
return datetime.datetime.now().strftime("%Y-%m-%d")
return datetime.date.today() | python | {
"resource": ""
} |
q51143 | timedelta2millisecond | train | def timedelta2millisecond(td):
"""Get milliseconds from a timedelta."""
milliseconds = td.days * 24 * 60 * 60 * 1000
milliseconds += td.seconds * 1000
milliseconds += td.microseconds / 1000
return milliseconds | python | {
"resource": ""
} |
q51144 | timedelta2period | train | def timedelta2period(duration):
"""Convert timedelta to different formats."""
seconds = duration.seconds
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return '{0:0>2}:{1:0>2}'.format(minutes, seconds) | python | {
"resource": ""
} |
q51145 | ControlProcess._generate_config | train | def _generate_config(self):
"""Generate a configuration that can be sent to the Hottop roaster.
Configuration settings need to be represented inside of a byte array
that is then written to the serial interface. Much of the configuration
is static, but control settings are also included ... | python | {
"resource": ""
} |
q51146 | ControlProcess._send_config | train | def _send_config(self):
"""Send configuration data to the hottop.
:returns: bool
:raises: Generic exceptions if an error is identified.
"""
serialized = self._generate_config()
self._log.debug("Configuration has been serialized")
try:
self._conn.flush... | python | {
"resource": ""
} |
q51147 | ControlProcess._validate_checksum | train | def _validate_checksum(self, buffer):
"""Validate the buffer response against the checksum.
When reading the serial interface, data will come back in a raw format
with an included checksum process.
:returns: bool
"""
self._log.debug("Validating the buffer")
if l... | python | {
"resource": ""
} |
q51148 | ControlProcess._read_settings | train | def _read_settings(self, retry=True):
"""Read the information from the Hottop.
Read the settings from the serial interface and convert them into a
human-readable format that can be shared back to the end-user. Reading
from the serial interface will occasionally produce strange results o... | python | {
"resource": ""
} |
q51149 | ControlProcess._valid_config | train | def _valid_config(self, settings):
"""Scan through the returned settings to ensure they appear sane.
There are time when the returned buffer has the proper information, but
the reading is inaccurate. When this happens, temperatures will swing
or system values will be set to improper val... | python | {
"resource": ""
} |
q51150 | ControlProcess.run | train | def run(self):
"""Run the core loop of reading and writing configurations.
This is where all the roaster magic occurs. On the initial run, we
prime the roaster with some data to wake it up. Once awoke, we check
our shared queue to identify if the user has passed any updated
conf... | python | {
"resource": ""
} |
q51151 | Hottop._autodiscover_usb | train | def _autodiscover_usb(self):
"""Attempt to find the serial adapter for the hottop.
This will loop over the USB serial interfaces looking for a connection
that appears to match the naming convention of the Hottop roaster.
:returns: string
"""
if sys.platform.startswith('... | python | {
"resource": ""
} |
q51152 | Hottop.connect | train | def connect(self, interface=None):
"""Connect to the USB for the hottop.
Attempt to discover the USB port used for the Hottop and then form a
connection using the serial library.
:returns: bool
:raises SerialConnectionError:
"""
if self._simulate:
re... | python | {
"resource": ""
} |
q51153 | Hottop._init_controls | train | def _init_controls(self):
"""Establish a set of base controls the user can influence.
:returns: None
"""
self._config['heater'] = 0
self._config['fan'] = 0
self._config['main_fan'] = 0
self._config['drum_motor'] = 1
self._config['solenoid'] = 0
se... | python | {
"resource": ""
} |
q51154 | Hottop._callback | train | def _callback(self, data):
"""Processor callback to clean-up stream data.
This function provides a hook into the output stream of data from the
controller processing thread. Hottop readings are saved into a local
class variable for later saving. If the user has defined a callback, it
... | python | {
"resource": ""
} |
q51155 | Hottop._derive_charge | train | def _derive_charge(self, config):
"""Use a temperature window to identify the roast charge.
The charge will manifest as a sudden downward trend on the temperature.
Once found, we save it and avoid overwriting. The charge is needed in
order to derive the turning point.
:param co... | python | {
"resource": ""
} |
q51156 | Hottop.start | train | def start(self, func=None):
"""Start the roaster control process.
This function will kick off the processing thread for the Hottop and
register any user-defined callback function. By default, it will not
begin collecting any reading information or saving it. In order to do
that ... | python | {
"resource": ""
} |
q51157 | Hottop.end | train | def end(self):
"""End the roaster control process via thread signal.
This simply sends an exit signal to the thread, and shuts it down. In
order to stop monitoring, call the `set_monitor` method with false.
:returns: None
"""
self._process.shutdown()
self._roast... | python | {
"resource": ""
} |
q51158 | Hottop.reset | train | def reset(self):
"""Reset the internal roast properties.
:returns: None
"""
self._roasting = False
self._roast_start = None
self._roast_end = None
self._roast = dict()
self._window = deque(list(), 5)
self._init_controls() | python | {
"resource": ""
} |
q51159 | Hottop.add_roast_event | train | def add_roast_event(self, event):
"""Add an event to the roast log.
This method should be used for registering events that may be worth
tracking like first crack, second crack and the dropping of coffee.
Similar to the standard reading output from the roaster, manually
created e... | python | {
"resource": ""
} |
q51160 | Hottop.set_interval | train | def set_interval(self, interval):
"""Set the polling interval for the process thread.
:param interval: How often to poll the Hottop
:type interval: int or float
:returns: None
:raises: InvalidInput
"""
if type(interval) != float or type(interval) != int:
... | python | {
"resource": ""
} |
q51161 | Hottop.set_roast_properties | train | def set_roast_properties(self, settings):
"""Set the properties of the roast.
:param settings: General settings for the roast setup
:type settings: dict
:returns: None
:raises: InvalidInput
"""
if type(settings) != dict:
raise InvalidInput("Properties... | python | {
"resource": ""
} |
q51162 | Hottop.set_monitor | train | def set_monitor(self, monitor):
"""Set the monitor config.
This module assumes that users will connect to the roaster and get
reading information _before_ they want to begin collecting roast
details. This method is critical to enabling the collection of roast
information and ens... | python | {
"resource": ""
} |
q51163 | Hottop.set_heater | train | def set_heater(self, heater):
"""Set the heater config.
:param heater: Value to set the heater
:type heater: int [0-100]
:returns: None
:raises: InvalidInput
"""
if type(heater) != int and heater not in range(0, 101):
raise InvalidInput("Heater value ... | python | {
"resource": ""
} |
q51164 | Hottop.set_fan | train | def set_fan(self, fan):
"""Set the fan config.
:param fan: Value to set the fan
:type fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(fan) != int and fan not in range(0, 11):
raise InvalidInput("Fan value must be int between 0-10")
... | python | {
"resource": ""
} |
q51165 | Hottop.set_main_fan | train | def set_main_fan(self, main_fan):
"""Set the main fan config.
:param main_fan: Value to set the main fan
:type main_fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(main_fan) != int and main_fan not in range(0, 11):
raise InvalidInput(... | python | {
"resource": ""
} |
q51166 | Hottop.set_drum_motor | train | def set_drum_motor(self, drum_motor):
"""Set the drum motor config.
:param drum_motor: Value to set the drum motor
:type drum_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(drum_motor) != bool:
raise InvalidInput("Drum motor value must b... | python | {
"resource": ""
} |
q51167 | Hottop.set_solenoid | train | def set_solenoid(self, solenoid):
"""Set the solenoid config.
:param solenoid: Value to set the solenoid
:type solenoid: bool
:returns: None
:raises: InvalidInput
"""
if type(solenoid) != bool:
raise InvalidInput("Solenoid value must be bool")
... | python | {
"resource": ""
} |
q51168 | Hottop.set_cooling_motor | train | def set_cooling_motor(self, cooling_motor):
"""Set the cooling motor config.
:param cooling_motor: Value to set the cooling motor
:type cooling_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(cooling_motor) != bool:
raise InvalidInput("Co... | python | {
"resource": ""
} |
q51169 | Hottop.set_simulate | train | def set_simulate(self, status):
"""Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput
"""
if type(status) != bool:
raise InvalidInput("Status value must be bool")
self.... | python | {
"resource": ""
} |
q51170 | QuerySet.make_filter | train | def make_filter(self, fieldname, query_func, expct_value):
''' makes a filter that will be appliead to an object's property based
on query_func '''
def actual_filter(item):
value = getattr(item, fieldname)
if query_func in NULL_AFFECTED_FILTERS and value is None:
... | python | {
"resource": ""
} |
q51171 | notChainStr | train | def notChainStr (states, s):
"""XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub-NFA's.
"""
assert len(s)... | python | {
"resource": ""
} |
q51172 | notGroup | train | def notGroup (states, *stateIndexPairs):
"""Like group, but will add a DEFAULT transition to a new end state,
causing anything in the group to not match by going to a dead state.
XXX I think this is right...
"""
start, dead = group(states, *stateIndexPairs)
finish = len(states)
states.append... | python | {
"resource": ""
} |
q51173 | PrawOAuth2Mini.refresh | train | def refresh(self, force=False):
"""Refreshes the `access_token` and sets the praw instance `reddit_client`
with a valid one.
:param force: Boolean. Refresh will be done only when last refresh was
done before `EXPIRY_DURATION`, which is 3500 seconds. However
passing `forc... | python | {
"resource": ""
} |
q51174 | Engine.render_impl | train | def render_impl(self, template, context, **options):
"""
Inherited class must implement this!
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param options: Same options as :meth:`renders_impl`
... | python | {
"resource": ""
} |
q51175 | _int_to_key | train | def _int_to_key(keys, index):
'Convert int ``index`` to the corresponding key in ``keys``'
if isinstance(index, int):
try:
return keys[index]
except IndexError:
# use KeyError rather than IndexError for compatibility
raise KeyError('Index out of range of keys:... | python | {
"resource": ""
} |
q51176 | mget_list | train | def mget_list(item, index):
'get mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
return item[index]
else:
return map(item.__getitem__, index) | python | {
"resource": ""
} |
q51177 | mset_list | train | def mset_list(item, index, value):
'set mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
item[index] = value
else:
map(item.__setitem__, index, value) | python | {
"resource": ""
} |
q51178 | MI_get_item | train | def MI_get_item(self, key, index=0):
'return list of item'
index = _key_to_index_single(force_list(self.indices.keys()), index)
if index != 0:
key = self.indices[index][key] # always use first index key
# key must exist
value = super(MIMapping, self).__getitem__(key)
N = len(self.indice... | python | {
"resource": ""
} |
q51179 | od_reorder_keys | train | def od_reorder_keys(od, keys_in_new_order): # not used
'''
Reorder the keys in an OrderedDict ``od`` in-place.
'''
if set(od.keys()) != set(keys_in_new_order):
raise KeyError('Keys in the new order do not match existing keys')
for key in keys_in_new_order:
od[key] = od.pop(key)
r... | python | {
"resource": ""
} |
q51180 | MI_method_PY3 | train | def MI_method_PY3(cls):
'''class decorator to change MIMapping method names for PY3 compatibility'''
nmspc = cls.__dict__.copy()
for m in ['__cmp__', 'has_key']:
nmspc.pop(m)
methods = ['keys', 'values', 'items']
for m in methods:
nmspc[m] = nmspc.pop('view' + m)
return type(cls... | python | {
"resource": ""
} |
q51181 | MIMapping.fromkeys | train | def fromkeys(cls, keys, value=None, names=None):
'''
Create a new dictionary with keys from ``keys`` and values set to ``value``.
fromkeys() is a class method that returns a new dictionary. ``value`` defaults to None.
Length of ``keys`` must not exceed one because no duplicate values a... | python | {
"resource": ""
} |
q51182 | MIDict.clear | train | def clear(self, clear_indices=False):
'Remove all items. index names are removed if ``clear_indices==True``.'
super(MIMapping, self).clear()
if clear_indices:
self.indices.clear()
else:
for index_d in self.indices[1:]:
index_d.clear() | python | {
"resource": ""
} |
q51183 | MIDict.reorder_indices | train | def reorder_indices(self, indices_order):
'reorder all the indices'
# allow mixed index syntax like int
indices_order, single = convert_index_to_keys(self.indices, indices_order)
old_indices = force_list(self.indices.keys())
if indices_order == old_indices: # no changes
... | python | {
"resource": ""
} |
q51184 | MIDict.add_index | train | def add_index(self, values, name=None):
'add an index of ``name`` with the list of ``values``'
if len(values) != len(set(values)):
raise ValueError('Values in the new index are not unique')
d = self.indices
if len(values) != len(self) and len(values) and d:
raise... | python | {
"resource": ""
} |
q51185 | MIDict.remove_index | train | def remove_index(self, index):
'remove one or more indices'
index_rm, single = convert_key_to_index(force_list(self.indices.keys()), index)
if single:
index_rm = [index_rm]
index_new = [i for i in range(len(self.indices)) if i not in index_rm]
if not index_new: # no... | python | {
"resource": ""
} |
q51186 | exit | train | def exit(exit_code=0):
"""
Shuts down current process logging, associated handlers and then exits to system.
:param exit_code: System exit code.
:type exit_code: Integer or String or Object
:note: **exit_code** argument is passed to Python :func:`sys.exit` definition.
"""
LOGGER.debug("> ... | python | {
"resource": ""
} |
q51187 | wait | train | def wait(wait_time):
"""
Halts current process exection for an user defined time.
:param wait_time: Current sleep time in seconds.
:type wait_time: float
:return: Definition success.
:rtype: bool
"""
LOGGER.debug("> Waiting '{0}' seconds!".format(wait_time))
time.sleep(wait_time)
... | python | {
"resource": ""
} |
q51188 | spawn_daemon | train | def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'):
'causes run to be executed in a newly spawned daemon process'
global LAST_PGRP_PATH
fork = fork or os.fork
open(outfile, 'a').close() # TODO: configurable output file
if pgrpfile and os.path.exists(pgrpfile):
try:
cu... | python | {
"resource": ""
} |
q51189 | wsgiref_thread_arbiter | train | def wsgiref_thread_arbiter(wsgi, host, port):
'probably not suitable for production use; example of threaded server'
import wsgiref.simple_server
httpd = wsgiref.simple_server.make_server(host, port, wsgi)
httpd.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def start_server():
... | python | {
"resource": ""
} |
q51190 | Arbiter.spawn_thread | train | def spawn_thread(self):
'causes run to be executed in a thread'
self.thread = threading.Thread(target=self.run, args=(False,))
self.thread.daemon = True
self.thread.start() | python | {
"resource": ""
} |
q51191 | Arbiter._ensure_pgrp | train | def _ensure_pgrp(self):
"""Ensures that the pgrp file is present and up to date. There have
been production cases where the file was lost or not
immediately emitted due to disk space issues.
"""
if not LAST_PGRP_PATH: # global
return
try:
with ope... | python | {
"resource": ""
} |
q51192 | VarianceDecomposition.addRandomEffect | train | def addRandomEffect(self,K=None,covar_type='freeform',is_noise=False,normalize=True,Ks=None,offset=1e-4,rank=1,covar_K0=None):
"""
Add random effect Term
depending on self.P=1 or >1 add single trait or multi trait random effect term
"""
if self.P==1: self.addSingleTraitTerm(K=K,i... | python | {
"resource": ""
} |
q51193 | VarianceDecomposition.addFixedEffect | train | def addFixedEffect(self,F=None,A=None):
"""
add fixed effect to the model
Args:
F: fixed effect matrix [N,1]
A: design matrix [K,P] (e.g. SP.ones((1,P)) common effect; SP.eye(P) any effect)
"""
if A==None:
A = SP.eye(self.P)
if F==None... | python | {
"resource": ""
} |
q51194 | VarianceDecomposition._getScalesRand | train | def _getScalesRand(self):
"""
Return a vector of random scales
"""
if self.P>1:
scales = []
for term_i in range(self.n_terms):
_scales = SP.randn(self.diag[term_i].shape[0])
if self.offset[term_i]>0:
_scales = SP... | python | {
"resource": ""
} |
q51195 | VarianceDecomposition._perturbation | train | def _perturbation(self):
"""
Returns Gaussian perturbation
"""
if self.P>1:
scales = []
for term_i in range(self.n_terms):
_scales = SP.randn(self.diag[term_i].shape[0])
if self.offset[term_i]>0:
_scales = SP.co... | python | {
"resource": ""
} |
q51196 | VarianceDecomposition.setScales | train | def setScales(self,scales=None,term_num=None):
"""
get random initialization of variances based on the empirical trait variance
Args:
scales: if scales==None: set them randomly,
else: set scales to term_num (if term_num==None: set to all terms)
... | python | {
"resource": ""
} |
q51197 | VarianceDecomposition.getEstTraitCovar | train | def getEstTraitCovar(self,term_i=None):
"""
Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in
"""
assert self.P>1, 'Trait covars not defined for single trait analysis'
if term_i==None:
... | python | {
"resource": ""
} |
q51198 | VarianceDecomposition.getEstTraitCorrCoef | train | def getEstTraitCorrCoef(self,term_i=None):
"""
Returns the estimated trait correlation matrix
Args:
term_i: index of the term we are interested in
"""
cov = self.getEstTraitCovar(term_i)
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/std... | python | {
"resource": ""
} |
q51199 | VarianceDecomposition.getVariances | train | def getVariances(self):
"""
Returns the estimated variances as a n_terms x P matrix
each row of the output represents a term and its P values represent the variance corresponding variance in each trait
"""
if self.P>1:
RV=SP.zeros((self.n_terms,self.P))
fo... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.