_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q40000 | validate_nonce | train | def validate_nonce(nonce, secret):
'''
Is the nonce one that was generated by this library using the provided secret?
'''
nonce_components = nonce.split(':', 2)
if not len(nonce_components) == 3:
return False
timestamp = nonce_components[0]
salt = nonce_components[1]
nonce_signat... | python | {
"resource": ""
} |
q40001 | calculate_partial_digest | train | def calculate_partial_digest(username, realm, password):
'''
Calculate a partial digest that may be stored and used to authenticate future
HTTP Digest sessions.
'''
return md5.md5("%s:%s:%s" % (username.encode('utf-8'), realm, password.encode('utf-8'))).hexdigest() | python | {
"resource": ""
} |
q40002 | build_digest_challenge | train | def build_digest_challenge(timestamp, secret, realm, opaque, stale):
'''
Builds a Digest challenge that may be sent as the value of the 'WWW-Authenticate' header
in a 401 or 403 response.
'opaque' may be any value - it will be returned by the client.
'timestamp' will be incorporated and signed in ... | python | {
"resource": ""
} |
q40003 | calculate_request_digest | train | def calculate_request_digest(method, partial_digest, digest_response=None,
uri=None, nonce=None, nonce_count=None, client_nonce=None):
'''
Calculates a value for the 'response' value of the client authentication request.
Requires the 'partial_digest' calculated from the realm, u... | python | {
"resource": ""
} |
q40004 | build_authorization_request | train | def build_authorization_request(username, method, uri, nonce_count, digest_challenge=None,
realm=None, nonce=None, opaque=None, password=None,
request_digest=None, client_nonce=None):
'''
Builds an authorization request that may be sent as the valu... | python | {
"resource": ""
} |
q40005 | parse_digest_challenge | train | def parse_digest_challenge(authentication_header):
'''
Parses the value of a 'WWW-Authenticate' header. Returns an object with properties
corresponding to each of the recognized parameters in the header.
'''
if not is_digest_challenge(authentication_header):
return None
parts = parse_pa... | python | {
"resource": ""
} |
q40006 | BreakpointGraph.__get_vertex_by_name | train | def __get_vertex_by_name(self, vertex_name):
""" Obtains a vertex object by supplied label
Returns a :class:`bg.vertex.BGVertex` or its subclass instance
:param vertex_name: a vertex label it is identified by.
:type vertex_name: any hashable python object. ``str`` expected.
:re... | python | {
"resource": ""
} |
q40007 | BreakpointGraph.to_json | train | def to_json(self, schema_info=True):
""" JSON serialization method that account for all information-wise important part of breakpoint graph
"""
genomes = set()
result = {}
result["edges"] = []
for bgedge in self.edges():
genomes |= bgedge.multicolor.colors
... | python | {
"resource": ""
} |
q40008 | BreakpointGraph.from_json | train | def from_json(cls, data, genomes_data=None, genomes_deserialization_required=True, merge=False):
""" A JSON deserialization operation, that recovers a breakpoint graph from its JSON representation
as information about genomes, that are encoded in breakpoint graph might be available somewhere else, bu... | python | {
"resource": ""
} |
q40009 | get | train | def get(request, obj_id=None):
"""Lists all tags
:returns: json
"""
res = Result()
if obj_id:
if obj_id == '0':
obj = {
'id': 0,
'name': 'TAGLESS',
'artist': False,
}
else:
obj = get_object_or_404(Ta... | python | {
"resource": ""
} |
q40010 | post | train | def post(request):
"""Creates a tag object
:param name: Name for tag
:type name: str
:returns: json
"""
res = Result()
data = request.POST or json.loads(request.body)['body']
name = data.get('name', None)
if not name:
res.isError = True
res.message = "No name given"... | python | {
"resource": ""
} |
q40011 | put | train | def put(request, obj_id=None):
"""Adds tags from objects resolved from guids
:param tags: Tags to add
:type tags: list
:param guids: Guids to add tags from
:type guids: list
:returns: json
"""
res = Result()
data = request.PUT or json.loads(request.body)['body']
if obj_id:
... | python | {
"resource": ""
} |
q40012 | delete | train | def delete(request, obj_id=None):
"""Removes tags from objects resolved from guids
:param tags: Tags to remove
:type tags: list
:param guids: Guids to remove tags from
:type guids: list
:returns: json
"""
res = Result()
if obj_id:
# -- Delete the tag itself
tag = Ta... | python | {
"resource": ""
} |
q40013 | search | train | def search(request):
"""
Search for Tag objects and returns a Result object with a list of searialize Tag
objects.
:param search: Append a "Search for" tag
:type search: bool
:param zero: Exclude Tags with no items
:type zero: bool
:param artist: Exclude artist tags
:type artist: bo... | python | {
"resource": ""
} |
q40014 | merge | train | def merge(request, obj_id):
"""Merges multiple tags into a single tag and all related objects are reassigned"""
res = Result()
if request.POST:
tags = json.loads(request.POST['tags'])
else:
tags = json.loads(request.body)['body']['tags']
guids = []
images = Image.objects.filter(... | python | {
"resource": ""
} |
q40015 | _manageTags | train | def _manageTags(tagList, guids, add=True):
""" Adds or Removes Guids from Tags """
objects = getObjectsFromGuids(guids)
tags = []
for tag in tagList:
try:
t = Tag.objects.get(pk=int(tag))
except ValueError:
t = Tag.objects.get_or_create(name=tag.lower())[0]
... | python | {
"resource": ""
} |
q40016 | _addTags | train | def _addTags(tags, objects):
""" Adds tags to objects """
for t in tags:
for o in objects:
o.tags.add(t)
return True | python | {
"resource": ""
} |
q40017 | _removeTags | train | def _removeTags(tags, objects):
""" Removes tags from objects """
for t in tags:
for o in objects:
o.tags.remove(t)
return True | python | {
"resource": ""
} |
q40018 | _short_ts_regexp | train | def _short_ts_regexp():
'''Generates regexp for parsing of
shortened relative timestamps, as shown in the table.'''
ts_re = ['^']
for k in it.chain(_short_ts_days, _short_ts_s):
ts_re.append(r'(?P<{0}>\d+{0}\s*)?'.format(k))
return re.compile(''.join(ts_re), re.I | re.U) | python | {
"resource": ""
} |
q40019 | CuttlePool._get | train | def _get(self, timeout):
"""
Get a resource from the pool. If timeout is ``None`` waits
indefinitely.
:param timeout: Time in seconds to wait for a resource.
:type timeout: int
:return: A resource.
:rtype: :class:`_ResourceTracker`
:raises PoolEmptyError... | python | {
"resource": ""
} |
q40020 | CuttlePool._get_tracker | train | def _get_tracker(self, resource):
"""
Return the resource tracker that is tracking ``resource``.
:param resource: A resource.
:return: A resource tracker.
:rtype: :class:`_ResourceTracker`
"""
with self._lock:
for rt in self._reference_queue:
... | python | {
"resource": ""
} |
q40021 | CuttlePool._harvest_lost_resources | train | def _harvest_lost_resources(self):
"""Return lost resources to pool."""
with self._lock:
for i in self._unavailable_range():
rtracker = self._reference_queue[i]
if rtracker is not None and rtracker.available():
self.put_resource(rtracker.re... | python | {
"resource": ""
} |
q40022 | CuttlePool._make_resource | train | def _make_resource(self):
"""
Returns a resource instance.
"""
with self._lock:
for i in self._unavailable_range():
if self._reference_queue[i] is None:
rtracker = _ResourceTracker(
self._factory(**self._factory_argu... | python | {
"resource": ""
} |
q40023 | CuttlePool._put | train | def _put(self, rtracker):
"""
Put a resource back in the queue.
:param rtracker: A resource.
:type rtracker: :class:`_ResourceTracker`
:raises PoolFullError: If pool is full.
:raises UnknownResourceError: If resource can't be found.
"""
with self._lock:
... | python | {
"resource": ""
} |
q40024 | CuttlePool._remove | train | def _remove(self, rtracker):
"""
Remove a resource from the pool.
:param rtracker: A resource.
:type rtracker: :class:`_ResourceTracker`
"""
with self._lock:
i = self._reference_queue.index(rtracker)
self._reference_queue[i] = None
sel... | python | {
"resource": ""
} |
q40025 | CuttlePool._unavailable_range | train | def _unavailable_range(self):
"""
Return a generator for the indices of the unavailable region of
``_reference_queue``.
"""
with self._lock:
i = self._resource_end
j = self._resource_start
if j < i or self.empty():
j += self.max... | python | {
"resource": ""
} |
q40026 | CuttlePool.get_resource | train | def get_resource(self, resource_wrapper=None):
"""
Returns a ``Resource`` instance.
:param resource_wrapper: A Resource subclass.
:return: A ``Resource`` instance.
:raises PoolEmptyError: If attempt to get resource fails or times
out.
"""
rtracker = ... | python | {
"resource": ""
} |
q40027 | CuttlePool.put_resource | train | def put_resource(self, resource):
"""
Adds a resource back to the pool or discards it if the pool is full.
:param resource: A resource object.
:raises UnknownResourceError: If resource was not made by the
pool.
"""
rtracker = self... | python | {
"resource": ""
} |
q40028 | _ResourceTracker.wrap_resource | train | def wrap_resource(self, pool, resource_wrapper):
"""
Return a resource wrapped in ``resource_wrapper``.
:param pool: A pool instance.
:type pool: :class:`CuttlePool`
:param resource_wrapper: A wrapper class for the resource.
:type resource_wrapper: :class:`Resource`
... | python | {
"resource": ""
} |
q40029 | Resource.close | train | def close(self):
"""
Returns the resource to the resource pool.
"""
if self._resource is not None:
self._pool.put_resource(self._resource)
self._resource = None
self._pool = None | python | {
"resource": ""
} |
q40030 | Connection.send | train | def send(self, message, fragment_size=None, mask=False):
"""
Send a message. If `fragment_size` is specified, the message is
fragmented into multiple frames whose payload size does not extend
`fragment_size`.
"""
for frame in self.message_to_frames(message, fragment_size,... | python | {
"resource": ""
} |
q40031 | Connection.handle_control_frame | train | def handle_control_frame(self, frame):
"""
Handle a control frame as defined by RFC 6455.
"""
if frame.opcode == OPCODE_CLOSE:
self.close_frame_received = True
code, reason = frame.unpack_close()
if self.close_frame_sent:
self.onclose(... | python | {
"resource": ""
} |
q40032 | Connection.send_ping | train | def send_ping(self, payload=''):
"""
Send a PING control frame with an optional payload.
"""
self.send_frame(ControlFrame(OPCODE_PING, payload),
lambda: self.onping(payload))
self.ping_payload = payload
self.ping_sent = True | python | {
"resource": ""
} |
q40033 | ProcessingThing.handler | train | def handler(self):
'Parametrized handler function'
return ft.partial(self.base.handler, parameter=self.parameter)\
if self.parameter else self.base.handler | python | {
"resource": ""
} |
q40034 | _Connection.connect | train | def connect(self):
"""Connect to the Redis server if necessary.
:rtype: :class:`~tornado.concurrent.Future`
:raises: :class:`~tredis.exceptions.ConnectError`
:class:`~tredis.exceptinos.RedisError`
"""
future = concurrent.Future()
if self.connected:
... | python | {
"resource": ""
} |
q40035 | _Connection.execute | train | def execute(self, command, future):
"""Execute a command after connecting if necessary.
:param bytes command: command to execute after the connection
is established
:param tornado.concurrent.Future future: future to resolve
when the command's response is received.
... | python | {
"resource": ""
} |
q40036 | _Connection._on_closed | train | def _on_closed(self):
"""Invoked when the connection is closed"""
LOGGER.error('Redis connection closed')
self.connected = False
self._on_close()
self._stream = None | python | {
"resource": ""
} |
q40037 | _Connection._on_connected | train | def _on_connected(self, stream_future, connect_future):
"""Invoked when the socket stream has connected, setting up the
stream callbacks and invoking the on connect callback if set.
:param stream_future: The connection socket future
:type stream_future: :class:`~tornado.concurrent.Futur... | python | {
"resource": ""
} |
q40038 | _Connection._write | train | def _write(self, command, future):
"""Write a command to the socket
:param Command command: the Command data structure
"""
def on_written():
self._on_written(command, future)
try:
self._stream.write(command.command, callback=on_written)
except ... | python | {
"resource": ""
} |
q40039 | Client.connect | train | def connect(self):
"""Connect to the Redis server or Cluster.
:rtype: tornado.concurrent.Future
"""
LOGGER.debug('Creating a%s connection to %s:%s (db %s)',
' cluster node'
if self._clustering else '', self._hosts[0]['host'],
... | python | {
"resource": ""
} |
q40040 | Client.close | train | def close(self):
"""Close any open connections to Redis.
:raises: :exc:`tredis.exceptions.ConnectionError`
"""
if not self._connected.is_set():
raise exceptions.ConnectionError('not connected')
self._closing = True
if self._clustering:
for host i... | python | {
"resource": ""
} |
q40041 | Client.ready | train | def ready(self):
"""Indicates that the client is connected to the Redis server or
cluster and is ready for use.
:rtype: bool
"""
if self._clustering:
return (all([c.connected for c in self._cluster.values()])
and len(self._cluster))
retur... | python | {
"resource": ""
} |
q40042 | Client._create_cluster_connection | train | def _create_cluster_connection(self, node):
"""Create a connection to a Redis server.
:param node: The node to connect to
:type node: tredis.cluster.ClusterNode
"""
LOGGER.debug('Creating a cluster connection to %s:%s', node.ip,
node.port)
conn = _C... | python | {
"resource": ""
} |
q40043 | Client._encode_resp | train | def _encode_resp(self, value):
"""Dynamically build the RESP payload based upon the list provided.
:param mixed value: The list of command parts to encode
:rtype: bytes
"""
if isinstance(value, bytes):
return b''.join(
[b'$',
ascii(l... | python | {
"resource": ""
} |
q40044 | Client._eval_expectation | train | def _eval_expectation(command, response, future):
"""Evaluate the response from Redis to see if it matches the expected
response.
:param command: The command that is being evaluated
:type command: tredis.client.Command
:param bytes response: The response value to check
:... | python | {
"resource": ""
} |
q40045 | Client._execute | train | def _execute(self, parts, expectation=None, format_callback=None):
"""Really execute a redis command
:param list parts: The list of command parts
:param mixed expectation: Optional response expectation
:rtype: :class:`~tornado.concurrent.Future`
:raises: :exc:`~tredis.exception... | python | {
"resource": ""
} |
q40046 | Client._on_cluster_discovery | train | def _on_cluster_discovery(self, future):
"""Invoked when the Redis server has responded to the ``CLUSTER_NODES``
command.
:param future: The future containing the response from Redis
:type future: tornado.concurrent.Future
"""
LOGGER.debug('_on_cluster_discovery(%r)', f... | python | {
"resource": ""
} |
q40047 | Client._on_closed | train | def _on_closed(self):
"""Invoked by connections when they are closed."""
self._connected.clear()
if not self._closing:
if self._on_close_callback:
self._on_close_callback()
else:
raise exceptions.ConnectionError('closed') | python | {
"resource": ""
} |
q40048 | Client._on_cluster_data_moved | train | def _on_cluster_data_moved(self, response, command, future):
"""Process the ``MOVED`` response from a Redis cluster node.
:param bytes response: The response from the Redis server
:param command: The command that was being executed
:type command: tredis.client.Command
:param fut... | python | {
"resource": ""
} |
q40049 | Client._on_connected | train | def _on_connected(self, future):
"""Invoked when connections have been established. If the client is
in clustering mode, it will kick of the discovery step if needed. If
not, it will select the configured database.
:param future: The connection future
:type future: tornado.concu... | python | {
"resource": ""
} |
q40050 | Client._on_read_only_error | train | def _on_read_only_error(self, command, future):
"""Invoked when a Redis node returns an error indicating it's in
read-only mode. It will use the ``INFO REPLICATION`` command to
attempt to find the master server and failover to that, reissuing
the command to that server.
:param c... | python | {
"resource": ""
} |
q40051 | Client._read | train | def _read(self, command, future):
"""Invoked when a command is executed to read and parse its results.
It will loop on the IOLoop until the response is complete and then
set the value of the response in the execution future.
:param command: The command that was being executed
:t... | python | {
"resource": ""
} |
q40052 | Client._pick_cluster_host | train | def _pick_cluster_host(self, value):
"""Selects the Redis cluster host for the specified value.
:param mixed value: The value to use when looking for the host
:rtype: tredis.client._Connection
"""
crc = crc16.crc16(self._encode_resp(value[1])) % HASH_SLOTS
for host in s... | python | {
"resource": ""
} |
q40053 | parse_lines | train | def parse_lines(stream, separator=None):
"""
Takes each line of a stream, creating a generator that yields
tuples of line, row - where row is the line split by separator
(or by whitespace if separator is None.
:param stream:
:param separator: (optional)
:return: generator
"""
separa... | python | {
"resource": ""
} |
q40054 | safe_evaluate | train | def safe_evaluate(command, glob, local):
"""
Continue to attempt to execute the given command, importing objects which
cause a NameError in the command
:param command: command for eval
:param glob: globals dict for eval
:param local: locals dict for eval
:return: command result
"""
... | python | {
"resource": ""
} |
q40055 | int_to_gematria | train | def int_to_gematria(num, gershayim=True):
"""convert integers between 1 an 999 to Hebrew numerals.
- set gershayim flag to False to ommit gershayim
"""
# 1. Lookup in specials
if num in specialnumbers['specials']:
retval = specialnumbers['specials'][num]
return _add_gershayim... | python | {
"resource": ""
} |
q40056 | get_urls_from_onetab | train | def get_urls_from_onetab(onetab):
"""
Get video urls from a link to the onetab shared page.
Args:
onetab (str): Link to a onetab shared page.
Returns:
list: List of links to the videos.
"""
html = requests.get(onetab).text
soup = BeautifulSoup(html, 'lxml')
divs = sou... | python | {
"resource": ""
} |
q40057 | cProfileFuncStat.from_dict | train | def from_dict(cls, d):
"""Used to create an instance of this class from a pstats dict item"""
stats = []
for (filename, lineno, name), stat_values in d.iteritems():
if len(stat_values) == 5:
ncalls, ncall_nr, total_time, cum_time, subcall_stats = stat_values
... | python | {
"resource": ""
} |
q40058 | cProfileParser.exclude_functions | train | def exclude_functions(self, *funcs):
"""
Excludes the contributions from the following functions.
"""
for f in funcs:
f.exclude = True
run_time_s = sum(0 if s.exclude else s.own_time_s for s in self.stats)
cProfileFuncStat.run_time_s = run_time_s | python | {
"resource": ""
} |
q40059 | cProfileParser.get_top | train | def get_top(self, stat, n):
"""Return the top n values when sorting by 'stat'"""
return sorted(self.stats, key=lambda x: getattr(x, stat), reverse=True)[:n] | python | {
"resource": ""
} |
q40060 | cProfileParser.save_pstat | train | def save_pstat(self, path):
"""
Save the modified pstats file
"""
stats = {}
for s in self.stats:
if not s.exclude:
stats.update(s.to_dict())
with open(path, 'wb') as f:
marshal.dump(stats, f) | python | {
"resource": ""
} |
q40061 | safe_int | train | def safe_int(value):
"""
Tries to convert a value to int; returns 0 if conversion failed
"""
try:
result = int(value)
if result < 0:
raise NegativeDurationError(
'Negative values in duration strings are not allowed!'
)
except NegativeDurationEr... | python | {
"resource": ""
} |
q40062 | _parse | train | def _parse(value, strict=True):
"""
Preliminary duration value parser
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
pattern = r'(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)'
match = re.match(pattern, ... | python | {
"resource": ""
} |
q40063 | to_seconds | train | def to_seconds(value, strict=True, force_int=True):
"""
converts duration value to integer seconds
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
if isinstance(value, int):
return value # assuming it's sec... | python | {
"resource": ""
} |
q40064 | to_timedelta | train | def to_timedelta(value, strict=True):
"""
converts duration string to timedelta
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration string exceed allowed values
"""
if isinstance(value, int):
return timedelta(seconds=value) # assuming it's se... | python | {
"resource": ""
} |
q40065 | to_tuple | train | def to_tuple(value, strict=True, force_int=True):
"""
converts duration value to tuple of integers
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
if isinstance(value, int):
seconds = value
minutes, ... | python | {
"resource": ""
} |
q40066 | name_url | train | def name_url(provider, cloud, method_name):
"""
Get a URL for a method in a driver
"""
snake_parts = method_name.split('_')
if len(snake_parts) <= 1:
return False
# Convention for libcloud is ex_ are extended methods
if snake_parts[0] == 'ex':
extra = True
method_nam... | python | {
"resource": ""
} |
q40067 | contains_frame | train | def contains_frame(data):
"""
Read the frame length from the start of `data` and check if the data is
long enough to contain the entire frame.
"""
if len(data) < 2:
return False
b2 = struct.unpack('!B', data[1])[0]
payload_len = b2 & 0x7F
payload_start = 2
if payload_len ==... | python | {
"resource": ""
} |
q40068 | ControlFrame.unpack_close | train | def unpack_close(self):
"""
Unpack a close message into a status code and a reason. If no payload
is given, the code is None and the reason is an empty string.
"""
if self.payload:
code = struct.unpack('!H', str(self.payload[:2]))[0]
reason = str(self.payl... | python | {
"resource": ""
} |
q40069 | SocketReader.readn | train | def readn(self, n):
"""
Keep receiving data until exactly `n` bytes have been read.
"""
data = ''
while len(data) < n:
received = self.sock.recv(n - len(data))
if not len(received):
raise socket.error('no data read from socket')
... | python | {
"resource": ""
} |
q40070 | Wp.quality_comparator | train | def quality_comparator(video_data):
"""Custom comparator used to choose the right format based on the resolution."""
def parse_resolution(res: str) -> Tuple[int, ...]:
return tuple(map(int, res.split('x')))
raw_resolution = video_data['resolution']
resolution = parse_resolut... | python | {
"resource": ""
} |
q40071 | read_noise_curve | train | def read_noise_curve(noise_curve, noise_type_in='ASD', noise_type_out='ASD',
add_wd_noise=False, wd_noise='HB_wd_noise', wd_noise_type_in='ASD'):
"""Simple auxillary function that can read noise curves in.
This function can read in noise curves from a provided file or those that are preins... | python | {
"resource": ""
} |
q40072 | combine_with_wd_noise | train | def combine_with_wd_noise(f_n, amp_n, f_n_wd, amp_n_wd):
"""Combine noise with wd noise.
Combines noise and white dwarf background noise based on greater
amplitude value at each noise curve step.
Args:
f_n (float array): Frequencies of noise curve.
amp_n (float array): Amplitude values... | python | {
"resource": ""
} |
q40073 | show_available_noise_curves | train | def show_available_noise_curves(return_curves=True, print_curves=False):
"""List available sensitivity curves
This function lists the available sensitivity curve strings in noise_curves folder.
Args:
return_curves (bool, optional): If True, return a list of curve options.
print_curves (boo... | python | {
"resource": ""
} |
q40074 | _split_out_of_braces | train | def _split_out_of_braces(s):
"""Generator to split comma seperated string, but not split commas inside
curly braces.
>>> list(_split_out_of_braces("py{26, 27}-django{15, 16}, py32"))
>>>['py{26, 27}-django{15, 16}, py32']
"""
prev = 0
for m in re.finditer(r"{[^{}]*}|\s*,\s*", s):
i... | python | {
"resource": ""
} |
q40075 | expand_factor_conditions | train | def expand_factor_conditions(s, env):
"""If env matches the expanded factor then return value else return ''.
Example
-------
>>> s = 'py{33,34}: docformatter'
>>> expand_factor_conditions(s, Env(name="py34", ...))
"docformatter"
>>> expand_factor_conditions(s, Env(name="py26", ...))
""... | python | {
"resource": ""
} |
q40076 | replace_braces | train | def replace_braces(s, env):
"""Makes tox substitutions to s, with respect to environment env.
Example
-------
>>> replace_braces("echo {posargs:{env:USER:} passed no posargs}")
"echo andy passed no posargs"
Note: first "{env:USER:}" is replaced with os.environ.get("USER", ""),
the "{posarg... | python | {
"resource": ""
} |
q40077 | _replace_match | train | def _replace_match(m, env):
"""Given a match object, having matched something inside curly braces,
replace the contents if matches one of the supported tox-substitutions."""
# ditch the curly braces
s = m.group()[1:-1].strip()
try:
# get the env attributes e.g. envpython or toxinidir.
... | python | {
"resource": ""
} |
q40078 | csnr | train | def csnr(freqs, hc, hn, fmrg, fpeak, prefactor=1.0):
"""Calculate the SNR of a frequency domain waveform.
SNRCalculation is a function that takes waveforms (frequencies and hcs)
and a noise curve, and returns SNRs for all binary phases and the whole waveform.
Arguments:
freqs (1D or 2D array o... | python | {
"resource": ""
} |
q40079 | Linear.Areml_eigh | train | def Areml_eigh(self):
"""compute the eigenvalue decomposition of Astar"""
s,U = LA.eigh(self.Areml(),lower=True)
i_pos = (s>1e-10)
s = s[i_pos]
U = U[:,i_pos]
return s,U | python | {
"resource": ""
} |
q40080 | Linear.getGradient | train | def getGradient(self,j):
""" get rotated gradient for fixed effect i """
i = int(self.indicator['term'][j])
r = int(self.indicator['row'][j])
c = int(self.indicator['col'][j])
rv = -np.kron(self.Fstar()[i][:,[r]],self.Astar()[i][[c],:])
return rv | python | {
"resource": ""
} |
q40081 | Linear.XstarT_dot | train | def XstarT_dot(self,M):
""" get dot product of Xhat and M """
if 0:
#TODO: implement this properly
pass
else:
RV = np.dot(self.Xstar().T,M)
return RV | python | {
"resource": ""
} |
q40082 | Linear.getResiduals | train | def getResiduals(self):
""" regress out fixed effects and results residuals """
X = np.zeros((self.N*self.P,self.n_fixed_effs))
ip = 0
for i in range(self.n_terms):
Ki = self.A[i].shape[0]*self.F[i].shape[1]
X[:,ip:ip+Ki] = np.kron(self.A[i].T,self.F[i])
... | python | {
"resource": ""
} |
q40083 | Linear._set_toChange | train | def _set_toChange(x):
""" set variables in list x toChange """
for key in list(x.keys()):
self.toChange[key] = True | python | {
"resource": ""
} |
q40084 | bread | train | def bread(stream):
""" Decode a file or stream to an object.
"""
if hasattr(stream, "read"):
return bdecode(stream.read())
else:
handle = open(stream, "rb")
try:
return bdecode(handle.read())
finally:
handle.close() | python | {
"resource": ""
} |
q40085 | bwrite | train | def bwrite(stream, obj):
""" Encode a given object to a file or stream.
"""
handle = None
if not hasattr(stream, "write"):
stream = handle = open(stream, "wb")
try:
stream.write(bencode(obj))
finally:
if handle:
handle.close() | python | {
"resource": ""
} |
q40086 | Encoder.encode | train | def encode(self, obj):
""" Add the given object to the result.
"""
if isinstance(obj, int_like_types):
self.result.append("i%de" % obj)
elif isinstance(obj, string_types):
self.result.extend([str(len(obj)), ':', str(obj)])
elif hasattr(obj, "__bencode__"):... | python | {
"resource": ""
} |
q40087 | calc_delta_c | train | def calc_delta_c(c200):
"""Calculate characteristic overdensity from concentration.
Parameters
----------
c200 : ndarray or float
Cluster concentration parameter.
Returns
----------
ndarray or float
Cluster characteristic overdensity, of same type as c200.
"""
top =... | python | {
"resource": ""
} |
q40088 | ClusterEnsemble.show | train | def show(self, notebook=notebook_display):
"""Display cluster properties and scaling relation parameters."""
print("\nCluster Ensemble:")
if notebook is True:
display(self._df)
elif notebook is False:
print(self._df)
self.massrich_parameters() | python | {
"resource": ""
} |
q40089 | ClusterEnsemble.calc_nfw | train | def calc_nfw(self, rbins, offsets=None, numTh=200, numRoff=200,
numRinner=20, factorRouter=3):
"""Calculates Sigma and DeltaSigma profiles.
Generates the surface mass density (sigma_nfw attribute of parent
object) and differential surface mass density (deltasigma_nfw
at... | python | {
"resource": ""
} |
q40090 | delaunay_graph | train | def delaunay_graph(X, weighted=False):
'''Delaunay triangulation graph.
'''
e1, e2 = _delaunay_edges(X)
pairs = np.column_stack((e1, e2))
w = paired_distances(X[e1], X[e2]) if weighted else None
return Graph.from_edge_pairs(pairs, num_vertices=X.shape[0], symmetric=True,
... | python | {
"resource": ""
} |
q40091 | FileReadOut.hdf5_read_out | train | def hdf5_read_out(self):
"""Read out an hdf5 file.
Takes the output of :class:`gwsnrcalc.genconutils.genprocess.GenProcess`
and reads it out to an HDF5 file.
"""
with h5py.File(self.WORKING_DIRECTORY + '/' + self.output_file_name, 'w') as f:
header = f.create_group... | python | {
"resource": ""
} |
q40092 | FileReadOut.txt_read_out | train | def txt_read_out(self):
"""Read out txt file.
Takes the output of :class:`gwsnrcalc.genconutils.genprocess.GenProcess`
and reads it out to a txt file.
"""
header = '#Generated SNR Out\n'
header += '#Generator by: Michael Katz\n'
header += '#Date/Time: {}\n'.for... | python | {
"resource": ""
} |
q40093 | trigger_function_installed | train | def trigger_function_installed(connection: connection):
"""Test whether or not the psycopg2-pgevents trigger function is installed.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
Returns
-------
bool
True if the ... | python | {
"resource": ""
} |
q40094 | trigger_installed | train | def trigger_installed(connection: connection, table: str, schema: str='public'):
"""Test whether or not a psycopg2-pgevents trigger is installed for a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table... | python | {
"resource": ""
} |
q40095 | install_trigger_function | train | def install_trigger_function(connection: connection, overwrite: bool=False) -> None:
"""Install the psycopg2-pgevents trigger function against the database.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
overwrite: bool
W... | python | {
"resource": ""
} |
q40096 | uninstall_trigger_function | train | def uninstall_trigger_function(connection: connection, force: bool=False) -> None:
"""Uninstall the psycopg2-pgevents trigger function from the database.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
force: bool
If True,... | python | {
"resource": ""
} |
q40097 | install_trigger | train | def install_trigger(connection: connection, table: str, schema: str='public', overwrite: bool=False) -> None:
"""Install a psycopg2-pgevents trigger against a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
... | python | {
"resource": ""
} |
q40098 | uninstall_trigger | train | def uninstall_trigger(connection: connection, table: str, schema: str='public') -> None:
"""Uninstall a psycopg2-pgevents trigger from a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table for which the... | python | {
"resource": ""
} |
q40099 | absolutify | train | def absolutify(url):
"""Takes a URL and prepends the SITE_URL"""
site_url = getattr(settings, 'SITE_URL', False)
# If we don't define it explicitly
if not site_url:
protocol = settings.PROTOCOL
hostname = settings.DOMAIN
port = settings.PORT
if (protocol, port) in (('htt... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.