repo
stringlengths 1
29
| path
stringlengths 24
332
| code
stringlengths 39
579k
|
---|---|---|
dsgutils-0.2.0
|
dsgutils-0.2.0//dsgutils/pd/munging.pyfile:/dsgutils/pd/munging.py:function:order_df/order_df
|
def order_df(df, first=None, last=None):
"""
Order a dataframe that the 'first' columns are first and 'last' are last. It is not necessary to provide
all the columns, if a subset of the columns is supplied, the columns not supplied columns will stay inplace.
:param df: Dataframe to order
:type df: pd.DataFrame
:param first: List of columns to put first
:type first: list
:param last: List of columns to put last
:type last: list
:return: Ordered dataframe
:rtype pd.DataFrame
"""
if not first:
first = []
if not last:
last = []
first.extend(list(set(df.columns) - set(first) - set(last)))
if last:
first.extend(last)
return df[first]
|
limix_legacy
|
limix_legacy//utils/util_functions.pyfile:/utils/util_functions.py:function:smartSum/smartSum
|
def smartSum(x, key, value):
""" create a new page in x if key is not a page of x
otherwise add value to x[key] """
if key not in list(x.keys()):
x[key] = value
else:
x[key] += value
|
userv-0.7.1
|
userv-0.7.1//userv/swagger.pyfile:/userv/swagger.py:function:_convert_to_swagger_type/_convert_to_swagger_type
|
def _convert_to_swagger_type(value):
"""
Every type has a swagger type
:rtype: str
"""
if isinstance(value, (str,)) or value is None:
return 'string'
if isinstance(value, (float,)):
return 'number'
if isinstance(value, (int,)):
return 'integer'
if isinstance(value, (bool,)):
return 'boolean'
if isinstance(value, (set, tuple, list)):
return 'array'
if isinstance(value, (dict,)):
return 'object'
return 'string'
|
agogosml
|
agogosml//common/kafka_streaming_client.pyclass:KafkaStreamingClient/create_kafka_config
|
@staticmethod
def create_kafka_config(user_config: dict) ->dict:
"""Creates the kafka configuration"""
config = {'bootstrap.servers': user_config.get('KAFKA_ADDRESS'),
'enable.auto.commit': False, 'auto.offset.reset': 'earliest',
'default.topic.config': {'auto.offset.reset': 'smallest'}}
if user_config.get('EVENTHUB_KAFKA_CONNECTION_STRING'):
ssl_location = user_config.get('SSL_CERT_LOCATION'
) or '/etc/ssl/certs/ca-certificates.crt'
eventhub_config = {'security.protocol': 'SASL_SSL',
'sasl.mechanism': 'PLAIN', 'ssl.ca.location': ssl_location,
'sasl.username': '$ConnectionString', 'sasl.password':
user_config.get('EVENTHUB_KAFKA_CONNECTION_STRING'),
'client.id': 'agogosml'}
config = {**config, **eventhub_config}
if user_config.get('KAFKA_CONSUMER_GROUP') is not None:
config['group.id'] = user_config['KAFKA_CONSUMER_GROUP']
return config
|
gaphor
|
gaphor//UML/modelfactory.pyfile:/UML/modelfactory.py:function:get_applied_stereotypes/get_applied_stereotypes
|
def get_applied_stereotypes(element):
"""
Get collection of applied stereotypes to an element.
"""
return element.appliedStereotype[:].classifier
|
itk
|
itk//itkSpatialObjectToVTKPolyDataFilterPython.pyfile:/itkSpatialObjectToVTKPolyDataFilterPython.py:function:spatial_object_to_vtk_poly_data_filter/spatial_object_to_vtk_poly_data_filter
|
def spatial_object_to_vtk_poly_data_filter(*args, **kwargs):
"""Procedural interface for SpatialObjectToVTKPolyDataFilter"""
import itk
instance = itk.SpatialObjectToVTKPolyDataFilter.New(*args, **kwargs)
return instance.__internal_call__()
|
fast_arrow-1.0.3
|
fast_arrow-1.0.3//fast_arrow/resources/stock_marketdata.pyclass:StockMarketdata/quotes_by_instrument_urls
|
@classmethod
def quotes_by_instrument_urls(cls, client, urls):
"""
fetch and return results
"""
instruments = ','.join(urls)
params = {'instruments': instruments}
url = 'https://api.robinhood.com/marketdata/quotes/'
data = client.get(url, params=params)
results = data['results']
while 'next' in data and data['next']:
data = client.get(data['next'])
results.extend(data['results'])
return results
|
DateTime-4.3
|
DateTime-4.3//src/DateTime/interfaces.pyclass:IDateTime/isCurrentMonth
|
def isCurrentMonth():
"""Return true if this object represents a date/time that
falls within the current month, in the context of this
object's timezone representation"""
|
transphire-1.4.28
|
transphire-1.4.28//transphire/transphire_content.pyfile:/transphire/transphire_content.py:function:default_cryolo_v1_2_1/default_cryolo_v1_2_1
|
def default_cryolo_v1_2_1():
"""
Content of crYOLO version 1.2.1
Arguments:
None
Return:
Content items as list
"""
items = [['WIDGETS MAIN', '5', int, '', 'PLAIN', '', ''], [
'WIDGETS ADVANCED', '5', int, '', 'PLAIN', '', ''], ['WIDGETS RARE',
'5', int, '', 'PLAIN', '', ''], ['--conf', '', str, '', 'FILE',
'Main', '', 'Path to configuration file.'], ['--weights', '', str,
'', 'FILE', 'Main', 'Path to pretrained weights.'], ['--threshold',
'0.3', float, '', 'PLAIN', 'Main',
'Confidence threshold. Have to be between 0 and 1. As higher, as more conservative.'
], ['Pixel size (A/px)', '1', float, 'Filter micrographs:True',
'PLAIN', 'Main',
'NOT A CRYOLO OPTION. Pixel size value. Only used for visual representation.'
], ['Box size', '200', int, '', 'PLAIN', 'Main',
'NOT A CRYOLO OPTION. Box size value. Only used for visual representation.'
], ['--filament', ['False', 'True'], bool, '', 'COMBO', 'Main',
'Activate filament mode'], ['--filament_width', '0', float,
'--filament:True', 'PLAIN', 'Main',
'(FILAMENT MODE) Filament width (in pixel)'], ['--box_distance',
'0', int, '--filament:True', 'PLAIN', 'Main',
'(FILAMENT MODE) Distance between two boxes(in pixel)'], [
'--minimum_number_boxes', '0', int, '--filament:True', 'PLAIN',
'Main', '(FILAMENT MODE) Distance between two boxes(in pixel)'], [
'Filter micrographs', ['True', 'False'], bool, '', 'COMBO',
'Advanced',
'NOT A CRYOLO OPTION. Box size value. Only used for visual representation.'
], ['Filter value high pass (A)', '9999', float,
'Filter micrographs:True', 'PLAIN', 'Advanced',
'NOT A CRYOLO OPTION. High-pass filter value in angstrom before running crYOLO.'
], ['Filter value low pass (A)', '10', float,
'Filter micrographs:True', 'PLAIN', 'Advanced',
'NOT A CRYOLO OPTION. Low-pass filter value in angstrom before running crYOLO.'
], ['--patch', '-1', int, '', 'PLAIN', 'Advanced',
'Number of patches. (-1 uses the patch size specified in the configuration file.)'
], ['--gpu', '0', [int] * 99, '', 'PLAIN', 'Advanced',
"Specifiy which gpu's should be used."], ['Split Gpu?', ['True',
'False'], bool, '', 'COMBO', 'Advanced',
'NOT A CRYOLO OPTION. Split the gpu values specified in --gpu to be able to run mutliple crYOLO jobs in parallel.'
]]
return items
|
search_in_files-0.0.6
|
search_in_files-0.0.6//search_in_files/search.pyfile:/search_in_files/search.py:function:wait_for_workers/wait_for_workers
|
def wait_for_workers(workers, task_queue):
"""
Waits for all workers to finish
"""
for w in workers:
task_queue.put(None)
for w in workers:
w.join()
task_queue.close()
|
sls-0.5.0
|
sls-0.5.0//sls/parser/stack.pyclass:Stack/extract
|
@staticmethod
def extract(stack, value, before=None):
"""
Returns the respective stack nodes of a rule 'value' seen
by looking backwards at the stack. An optional 'before' rule
can be required to be seen first.
"""
seen = before is None
for node in reversed(stack):
from_rule = node.dfa.from_rule
if not seen:
if from_rule == before:
seen = True
elif from_rule == value:
return node.nodes
assert 0, stack
|
wlc-1.3
|
wlc-1.3//wlc/main.pyclass:ObjectCommand/add_parser
|
@classmethod
def add_parser(cls, subparser):
"""Create parser for command line."""
parser = super().add_parser(subparser)
parser.add_argument('object', nargs='*', help=
'Object on which we should operate (project, component or translation)'
)
return parser
|
dropbox-10.1.2
|
dropbox-10.1.2//dropbox/team_log.pyclass:EventDetails/shared_link_settings_remove_password_details
|
@classmethod
def shared_link_settings_remove_password_details(cls, val):
"""
Create an instance of this class set to the
``shared_link_settings_remove_password_details`` tag with value ``val``.
:param SharedLinkSettingsRemovePasswordDetails val:
:rtype: EventDetails
"""
return cls('shared_link_settings_remove_password_details', val)
|
siskin-0.85.3
|
siskin-0.85.3//siskin/configuration.pyclass:Config/add_config_path
|
@classmethod
def add_config_path(cls, path):
""" Append config path. """
cls._config_paths.append(path)
cls._instance.reload()
|
dropbox
|
dropbox//team_log.pyclass:EventType/file_requests_emails_restricted_to_team_only
|
@classmethod
def file_requests_emails_restricted_to_team_only(cls, val):
"""
Create an instance of this class set to the
``file_requests_emails_restricted_to_team_only`` tag with value ``val``.
:param FileRequestsEmailsRestrictedToTeamOnlyType val:
:rtype: EventType
"""
return cls('file_requests_emails_restricted_to_team_only', val)
|
lenstronomy-1.5.0
|
lenstronomy-1.5.0//lenstronomy/Util/sampling_util.pyfile:/lenstronomy/Util/sampling_util.py:function:uniform2unit/uniform2unit
|
def uniform2unit(theta, vmin, vmax):
"""
mapping from uniform distribution on unit hypercube
to uniform distribution on parameter space
"""
return (theta - vmin) / (vmax - vmin)
|
yaml-structureddata-5.0.2
|
yaml-structureddata-5.0.2//StructuredData/internal/rst_load.pyfile:/StructuredData/internal/rst_load.py:function:read_file/read_file
|
def read_file(filename):
"""read a file and return the lines."""
f = open(filename, 'r')
lines = f.readlines()
f.close()
return lines
|
twisted-hl7-0.2.2
|
twisted-hl7-0.2.2//twistedhl7/receiver.pyclass:IHL7Receiver/parseMessage
|
def parseMessage(raw_message):
"""Clients should parse the message and return an instance of :py:class:`twistedhl7.receiver.MessageContainer` or subclass.
:rtype: :py:class:`twistedhl7.receiver.MessageContainer`
"""
pass
|
dropbox
|
dropbox//team_log.pyclass:EventDetails/emm_add_exception_details
|
@classmethod
def emm_add_exception_details(cls, val):
"""
Create an instance of this class set to the
``emm_add_exception_details`` tag with value ``val``.
:param EmmAddExceptionDetails val:
:rtype: EventDetails
"""
return cls('emm_add_exception_details', val)
|
python-tuskarclient-0.1.18
|
python-tuskarclient-0.1.18//tuskarclient/openstack/common/apiclient/base.pyfile:/tuskarclient/openstack/common/apiclient/base.py:function:getid/getid
|
def getid(obj):
"""Return id if argument is a Resource.
Abstracts the common pattern of allowing both an object or an object's ID
(UUID) as a parameter when dealing with relationships.
"""
try:
if obj.uuid:
return obj.uuid
except AttributeError:
pass
try:
return obj.id
except AttributeError:
return obj
|
chibi-0.8.2
|
chibi-0.8.2//chibi/snippet/is_type.pyfile:/chibi/snippet/is_type.py:function:is_like_list/is_like_list
|
def is_like_list(obj):
"""
evaluate if the object is like a list
Arguments
---------
obj: object
Returns
-------
bool
"""
return isinstance(obj, (list, tuple, set))
|
fontlib
|
fontlib//css.pyfile:/css.py:function:split_tokens/split_tokens
|
def split_tokens(rule_tokens, t_type='literal', t_value=';'):
"""Split list of tokens into a list of token lists.
By a delimiter, the ``rule_tokens`` list is splitted into groups.
Delimiters are tokens with type ``t_type`` and value ``t_value``.
Delimiter tokens and ``whitespace`` tokens are stripped from the
returned lists.
The default ``t_type`` and ``t_value`` are good to consume a list of
declarations:
- https://drafts.csswg.org/css-syntax-3/#consume-a-list-of-declarations
:param rule_tokens:
A list of :class:`tinycss.ast.Node`
:param t_type:
String with the type of the delimiter token (default=``literal``)
:param t_value:
String with the value of the delimiter token (default=``;``)
:returns: a list of lists with token in (:class:`tinycss.ast.Node`)
:return: list
"""
decl_tokens = []
current = []
for token in rule_tokens:
if token.type in ['whitespace']:
continue
elif token.type == t_type and token.value == t_value:
decl_tokens.append(current)
current = []
else:
current.append(token)
return decl_tokens
|
chado-tools-0.2.14
|
chado-tools-0.2.14//pychado/queries.pyfile:/pychado/queries.py:function:set_organism_condition/set_organism_condition
|
def set_organism_condition(query: str, organism: str) ->str:
"""Replaces a placeholder in a query with a condition restricting results to a certain organism"""
if not organism:
modified_query = query.replace(':ORGANISM_CONDITION', 'TRUE')
else:
modified_query = query.replace(':ORGANISM_CONDITION',
'abbreviation = :organism')
return modified_query
|
mercurial-5.4
|
mercurial-5.4//mercurial/thirdparty/zope/interface/common/idatetime.pyclass:IDateTime/dst
|
def dst():
"""Return 0 if DST is not in effect, or the DST offset (in minutes
eastward) if DST is in effect.
"""
|
reproman-0.2.1
|
reproman-0.2.1//reproman/interface/retrace.pyfile:/reproman/interface/retrace.py:function:get_tracer_classes/get_tracer_classes
|
def get_tracer_classes():
"""A helper which returns a list of all available Tracers
The order should not but does matter and ATM is magically provided
"""
from reproman.distributions.debian import DebTracer
from reproman.distributions.redhat import RPMTracer
from reproman.distributions.conda import CondaTracer
from reproman.distributions.venv import VenvTracer
from reproman.distributions.vcs import VCSTracer
from reproman.distributions.docker import DockerTracer
from reproman.distributions.singularity import SingularityTracer
Tracers = [DebTracer, RPMTracer, CondaTracer, VenvTracer, VCSTracer,
DockerTracer, SingularityTracer]
return Tracers
|
pycoin-0.90.20200322
|
pycoin-0.90.20200322//pycoin/satoshi/intops.pyfile:/pycoin/satoshi/intops.py:function:do_OP_RIGHT/do_OP_RIGHT
|
def do_OP_RIGHT(vm):
"""
>>> s = [b'abcdef', b'\\3']
>>> do_OP_RIGHT(s, require_minimal=True)
>>> print(s==[b'def'])
True
>>> s = [b'abcdef', b'\\0']
>>> do_OP_RIGHT(s, require_minimal=False)
>>> print(s==[b''])
True
"""
pos = vm.pop_nonnegative()
if pos > 0:
vm.append(vm.pop()[-pos:])
else:
vm.pop()
vm.append(b'')
|
service_framework-0.0.8
|
service_framework-0.0.8//src/service_framework/states/in/full_update_in.pyclass:FullUpdateIn/get_state_type
|
@staticmethod
def get_state_type():
"""
This is needed so the service framework knows the
state type of the current state.
return::str The state and update type of this state.
"""
return 'full_update_in'
|
avwx
|
avwx//current/metar.pyfile:/current/metar.py:function:get_runway_visibility/get_runway_visibility
|
def get_runway_visibility(wxdata: [str]) ->([str], [str]):
"""
Returns the report list and the remove runway visibility list
"""
runway_vis = []
for i, item in reversed(list(enumerate(wxdata))):
if len(item) > 4 and item[0] == 'R' and (item[3] == '/' or item[4] ==
'/') and item[1:3].isdigit():
runway_vis.append(wxdata.pop(i))
runway_vis.sort()
return wxdata, runway_vis
|
fake-bpy-module-2.78-20200428
|
fake-bpy-module-2.78-20200428//bpy/ops/object.pyfile:/bpy/ops/object.py:function:material_slot_assign/material_slot_assign
|
def material_slot_assign():
"""Assign active material slot to selection
"""
pass
|
cricket-0.2.5
|
cricket-0.2.5//cricket/executor.pyfile:/cricket/executor.py:function:enqueue_output/enqueue_output
|
def enqueue_output(out, queue):
"""A utility method for consuming piped output from a subprocess.
Reads content from `out` one line at a time, and puts it onto
queue for consumption in a separate thread.
"""
for line in iter(out.readline, b''):
queue.put(line.strip().decode('utf-8'))
out.close()
|
pymavlink-ws-2.4.5
|
pymavlink-ws-2.4.5//generator/mavgen_wlua.pyfile:/generator/mavgen_wlua.py:function:mavfmt/mavfmt
|
def mavfmt(field):
"""work out the struct format for a type"""
map = {'float': 'f', 'double': 'd', 'char': 'c', 'int8_t': 'b',
'uint8_t': 'B', 'uint8_t_mavlink_version': 'B', 'int16_t': 'h',
'uint16_t': 'H', 'int32_t': 'i', 'uint32_t': 'I', 'int64_t': 'q',
'uint64_t': 'Q'}
if field.array_length:
if field.type in ['char', 'int8_t', 'uint8_t']:
return str(field.array_length) + 's'
return str(field.array_length) + map[field.type]
return map[field.type]
|
foreman_yml
|
foreman_yml//voluptuous.pyfile:/voluptuous.py:function:Lower/Lower
|
def Lower(v):
"""Transform a string to lower case.
>>> s = Schema(Lower)
>>> s('HI')
'hi'
"""
return str(v).lower()
|
gandi.cli-1.5
|
gandi.cli-1.5//gandi/cli/core/base.pyclass:GandiModule/json_put
|
@classmethod
def json_put(cls, url, **kwargs):
""" Helper for PUT json request """
return cls.json_call('PUT', url, **kwargs)
|
itk
|
itk//rtkConstantImageSourcePython.pyfile:/rtkConstantImageSourcePython.py:function:constant_image_source/constant_image_source
|
def constant_image_source(*args, **kwargs):
"""Procedural interface for ConstantImageSource"""
import itk
instance = itk.ConstantImageSource.New(*args, **kwargs)
return instance.__internal_call__()
|
trafficintelligence
|
trafficintelligence//utils.pyfile:/utils.py:function:sortByLength/sortByLength
|
def sortByLength(instances, reverse=False):
"""Returns a new list with the instances sorted by length (method __len__)
reverse is passed to sorted"""
return sorted(instances, key=len, reverse=reverse)
|
Kivy-1.11.1
|
Kivy-1.11.1//kivy/tools/pep8checker/pep8.pyfile:/kivy/tools/pep8checker/pep8.py:function:indentation/indentation
|
def indentation(logical_line, previous_logical, indent_char, indent_level,
previous_indent_level):
"""Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to
use 8-space tabs.
Okay: a = 1
Okay: if a == 0:\\n a = 1
E111: a = 1
E114: # a = 1
Okay: for item in items:\\n pass
E112: for item in items:\\npass
E115: for item in items:\\n# Hi\\n pass
Okay: a = 1\\nb = 2
E113: a = 1\\n b = 2
E116: a = 1\\n # b = 2
"""
c = 0 if logical_line else 3
tmpl = 'E11%d %s' if logical_line else 'E11%d %s (comment)'
if indent_level % 4:
yield 0, tmpl % (1 + c, 'indentation is not a multiple of four')
indent_expect = previous_logical.endswith(':')
if indent_expect and indent_level <= previous_indent_level:
yield 0, tmpl % (2 + c, 'expected an indented block')
elif not indent_expect and indent_level > previous_indent_level:
yield 0, tmpl % (3 + c, 'unexpected indentation')
|
mingdongtextsim
|
mingdongtextsim//algorithm/distance.pyfile:/algorithm/distance.py:function:try_divide/try_divide
|
def try_divide(x, y, val=0.0):
"""
try to divide two numbers
"""
if y != 0.0:
val = float(x) / y
return val
|
Pytzer-0.4.3
|
Pytzer-0.4.3//pytzer/model.pyfile:/pytzer/model.py:function:ln_acf2ln_acf_MX/ln_acf2ln_acf_MX
|
def ln_acf2ln_acf_MX(ln_acfM, ln_acfX, nM, nX):
"""Calculate the mean activity coefficient for an electrolyte."""
return (nM * ln_acfM + nX * ln_acfX) / (nM + nX)
|
nionswift-eels-analysis-0.4.4
|
nionswift-eels-analysis-0.4.4//nion/eels_analysis/EELS_EdgeIdentification.pyfile:/nion/eels_analysis/EELS_EdgeIdentification.py:function:candidate_edges/candidate_edges
|
def candidate_edges(edge_onset_eV: float, max_offset_eV: float,
primary_subshells_only: bool) ->list:
"""Return a list of edges near the specified edge onset energy.
"""
pass
|
zag-0.2.12
|
zag-0.2.12//zag/engines/action_engine/compiler.pyfile:/zag/engines/action_engine/compiler.py:function:_add_update_edges/_add_update_edges
|
def _add_update_edges(graph, nodes_from, nodes_to, attr_dict=None):
"""Adds/updates edges from nodes to other nodes in the specified graph.
It will connect the 'nodes_from' to the 'nodes_to' if an edge currently
does *not* exist (if it does already exist then the edges attributes
are just updated instead). When an edge is created the provided edge
attributes dictionary will be applied to the new edge between these two
nodes.
"""
for u in nodes_from:
for v in nodes_to:
if not graph.has_edge(u, v):
if attr_dict:
graph.add_edge(u, v, attr_dict=attr_dict.copy())
else:
graph.add_edge(u, v)
elif attr_dict:
graph.add_edge(u, v, attr_dict=attr_dict.copy())
|
exdir-0.4.1
|
exdir-0.4.1//versioneer.pyfile:/versioneer.py:function:render_git_describe_long/render_git_describe_long
|
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
mynewspaper-4.0
|
mynewspaper-4.0//misc/bottle.pyfile:/misc/bottle.py:function:path_shift/path_shift
|
def path_shift(script_name, path_info, shift=1):
""" Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:return: The modified paths.
:param script_name: The SCRIPT_NAME path.
:param script_name: The PATH_INFO path.
:param shift: The number of path fragments to shift. May be negative to
change the shift direction. (default: 1)
"""
if shift == 0:
return script_name, path_info
pathlist = path_info.strip('/').split('/')
scriptlist = script_name.strip('/').split('/')
if pathlist and pathlist[0] == '':
pathlist = []
if scriptlist and scriptlist[0] == '':
scriptlist = []
if shift > 0 and shift <= len(pathlist):
moved = pathlist[:shift]
scriptlist = scriptlist + moved
pathlist = pathlist[shift:]
elif shift < 0 and shift >= -len(scriptlist):
moved = scriptlist[shift:]
pathlist = moved + pathlist
scriptlist = scriptlist[:shift]
else:
empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
raise AssertionError('Cannot shift. Nothing left from %s' % empty)
new_script_name = '/' + '/'.join(scriptlist)
new_path_info = '/' + '/'.join(pathlist)
if path_info.endswith('/') and pathlist:
new_path_info += '/'
return new_script_name, new_path_info
|
gwf
|
gwf//core.pyclass:Graph/from_config
|
@classmethod
def from_config(cls, config):
"""Return graph for the workflow specified by `config`.
See :func:`graph_from_path` for further information.
"""
return cls.from_path(config['file'])
|
mnemonicode-1.4.5
|
mnemonicode-1.4.5//mnemonicode/_utils.pyfile:/mnemonicode/_utils.py:function:chunk_sequence/chunk_sequence
|
def chunk_sequence(data, size):
"""Split an iterator at ``size`` item intervals
"""
for offset in range(0, len(data), size):
yield data[offset:offset + size]
|
PyDojoML-0.4.5
|
PyDojoML-0.4.5//dojo/tree/utils/impurity_measurements.pyfile:/dojo/tree/utils/impurity_measurements.py:function:prop/prop
|
def prop(x, s):
"""Returns the proportion of `x` in `s`.
"""
return list(s).count(x) / len(s)
|
virtuinbridge
|
virtuinbridge//virtuinglobalstubs.pyfile:/virtuinglobalstubs.py:function:RefreshGuiTraveler/RefreshGuiTraveler
|
def RefreshGuiTraveler(*args, **kwargs):
""" Stub Anduin function."""
print('RefreshGuiTraveler', args, kwargs)
|
nPYc
|
nPYc//utilities/_internal.pyfile:/utilities/_internal.py:function:_vcorrcoef/_vcorrcoef
|
def _vcorrcoef(X, Y, method='pearson', sampleMask=None, featureMask=None):
"""
Calculate correlation between each column in *X* and the vector *Y*. Correlations may be calculated either as Pearson's *r* [#]_ or Spearman's rho [#]_ .
[#] Karl Pearson (20 June 1895) "Notes on regression and inheritance in the case of two parents," *Proceedings of the Royal Society of London*, 58 : 240–242.
[#] Myers, Jerome L.; Well, Arnold D. (2003). *Research Design and Statistical Analysis (2nd ed.)*. Lawrence Erlbaum. p. 508. ISBN 0-8058-4037-0.
:param numpy.ndarray X:
:param numpy.ndarray Y:
:param str method: Correlation method to use, may be 'pearson', or 'spearman'
:param sampleMask: If ``None`` calculate correlations based on all samples, otherwise use *sampleMask* as a boolean mask
:type sampleMask: None or numpy.ndarray of bool
:param featureMask: If ``None`` calculate correlations for all features
:type featureMask: None or numpy.ndarray of bool
"""
import numpy
import scipy
if sampleMask is None:
pass
else:
Y = Y[sampleMask]
X = X[(sampleMask), :]
if featureMask is None:
pass
else:
X = X[:, (featureMask)]
if method == 'spearman':
rankedMat = numpy.zeros_like(X)
for col in range(X.shape[1]):
rankedMat[:, (col)] = scipy.stats.rankdata(X[:, (col)])
X = rankedMat
Y = scipy.stats.rankdata(Y)
X = X.T
Xm = numpy.reshape(numpy.mean(X, axis=1), (X.shape[0], 1))
ym = numpy.mean(Y)
r_num = numpy.sum((X - Xm) * (Y - ym), axis=1)
r_den = numpy.sqrt(numpy.sum(numpy.power(X - Xm, 2), axis=1) * numpy.
sum(numpy.power(Y - ym, 2)))
r = r_num / r_den
r[numpy.isnan(r)] = 0
return r
|
HAP-python-2.8.3
|
HAP-python-2.8.3//pyhap/util.pyfile:/pyhap/util.py:function:long_to_bytes/long_to_bytes
|
def long_to_bytes(n):
"""
Convert a ``long int`` to ``bytes``
:param n: Long Integer
:type n: int
:return: ``long int`` in ``bytes`` format.
:rtype: bytes
"""
byteList = list()
x = 0
off = 0
while x != n:
b = n >> off & 255
byteList.append(b)
x = x | b << off
off += 8
byteList.reverse()
return bytes(byteList)
|
PyOpenGL-3.1.5
|
PyOpenGL-3.1.5//OpenGL/plugins.pyclass:Plugin/all
|
@classmethod
def all(cls):
"""Iterate over all registered plugins"""
return cls.registry[:]
|
promo
|
promo//duration_morph.pyfile:/duration_morph.py:function:_getTimeDiff/_getTimeDiff
|
def _getTimeDiff(start, stop, ratio):
"""Returns the time difference between interval and interval*ratio"""
return (ratio - 1) * (stop - start)
|
deltascope-1.0.0
|
deltascope-1.0.0//deltascope/alignment.pyfile:/deltascope/alignment.py:function:scatter_df/scatter_df
|
def scatter_df(ax, i, df):
"""
Scatter plot of df with projections in all 3 axes
:param plt.subplots ax: Subplot array with minimum dimension [2,3]
:param int i: Index of row that should be labeled
:param pd.DataFrame df: Dataframe containing 'x','y','z' columns preferably downsampled for faster plotting
"""
ax[i, 0].scatter(df.x, df.y, s=10)
ax[i, 1].scatter(df.x, df.z, s=10)
ax[i, 2].scatter(df.z, df.y, s=10)
|
creamas
|
creamas//domains/image/gp/primitives.pyfile:/domains/image/gp/primitives.py:function:mdist/mdist
|
def mdist(a, b):
"""Absolute distance between a and b.
"""
return abs(a - b)
|
emmet
|
emmet//list_utils.pyfile:/list_utils.py:function:some/some
|
def some(fn: callable, items: list):
"""Tests whether at least one element in the array passes the test implemented by the provided function. It returns a `bool` value."""
for item in items:
if fn(item):
return True
return False
|
pkgcore
|
pkgcore//merge/engine.pyclass:MergeEngine/get_pkg_contents
|
@staticmethod
def get_pkg_contents(engine, csets, pkg):
"""Generate the cset of what files shall be merged to the livefs."""
return pkg.contents.clone()
|
smqtk-0.13.0
|
smqtk-0.13.0//python/smqtk/utils/bits.pyfile:/python/smqtk/utils/bits.py:function:next_perm/next_perm
|
def next_perm(v):
"""
Compute the lexicographically next bit permutation
Generates next permutation with a given amount of set bits,
given the previous lexicographical value.
Taken from http://graphics.stanford.edu/~seander/bithacks.html
"""
t = (v | v - 1) + 1
w = t | ((t & -t) / (v & -v) >> 1) - 1
return w
|
dtale-1.8.11
|
dtale-1.8.11//dtale/utils.pyfile:/dtale/utils.py:function:find_selected_column/find_selected_column
|
def find_selected_column(data, col):
"""
In case we come across a series which after reset_index()
it's columns are [date, security_id, values]
in which case we want the last column
:param data: dataframe
:type data: :class:`pandas:pandas.DataFrame`
:param col: column name
:type col: str
:return: column name if it exists within the dataframe's columns, the last column within the dataframe otherwise
:rtype: str
"""
return col if col in data.columns else data.columns[-1]
|
oslo.i18n-4.0.1
|
oslo.i18n-4.0.1//oslo_i18n/_locale.pyfile:/oslo_i18n/_locale.py:function:get_locale_dir_variable_name/get_locale_dir_variable_name
|
def get_locale_dir_variable_name(domain):
"""Build environment variable name for local dir.
Convert a translation domain name to a variable for specifying
a separate locale dir.
"""
return domain.upper().replace('.', '_').replace('-', '_') + '_LOCALEDIR'
|
relstorage
|
relstorage//adapters/interfaces.pyclass:ITransactionControl/commit_phase1
|
def commit_phase1(store_connection, tid):
"""
Begin a commit. Returns the transaction name.
The transaction name must not be None.
This method should guarantee that :meth:`commit_phase2` will
succeed, meaning that if commit_phase2() would raise any
error, the error should be raised in :meth:`commit_phase1`
instead.
:param store_connection: An :class:`IManagedStoreConnection`
"""
|
calico
|
calico//parse.pyfile:/parse.py:function:get_comment_value/get_comment_value
|
def get_comment_value(node, name, field):
"""Get the value of a comment field.
:sig: (SpecNode, str, str) -> str
:param node: Node to get the comment from.
:param name: Name of setting in the node.
:param field: Name of comment field.
:return: Value of comment field.
"""
try:
comment = node.ca.items[name][2].value[1:].strip()
except KeyError:
comment = None
if comment is not None:
delim = field + ':'
if comment.startswith(delim):
return comment[len(delim):].strip()
return None
|
zope
|
zope//file/event.pyfile:/file/event.py:function:updateMimeType/updateMimeType
|
def updateMimeType(file, event):
"""Update the file's mimeType on a change.
If the current mimeType value is known to be legal for the new
content type, leave it alone. If not, set the mimeType attribute
to the first value from the list of known MIME types for the
content type.
"""
if event.newContentType is not None:
types = event.newContentType.getTaggedValue('mimeTypes')
if file.mimeType not in types:
file.mimeType = types[0]
|
utils
|
utils//lists.pyfile:/lists.py:function:unlist/unlist
|
def unlist(list_thing, complain=True):
"""transforms [Something] -> Something. By default, raises a ValueError for
any other list values."""
if complain and len(list_thing) > 1:
raise ValueError('More than one element in {}'.format(list_thing))
elif len(list_thing) == 1:
return list_thing[0]
if complain:
raise ValueError('Nothing in {}'.format(list_thing))
return None
|
silva.core.interfaces-3.0.4
|
silva.core.interfaces-3.0.4//src/silva/core/interfaces/content.pyclass:IPublication/get_publication
|
def get_publication():
"""Return the nearest publication by acquisition.
"""
|
eric6
|
eric6//ThirdParty/Jasy/jasy/core/Console.pyfile:/ThirdParty/Jasy/jasy/core/Console.py:function:outdent/outdent
|
def outdent(all=False):
"""
Decrements global indenting level.
Should be called whenever leaving a structural logging section.
"""
global __level
if all:
__level = 0
else:
__level -= 1
|
nibabel
|
nibabel//cifti2/cifti2_axes.pyclass:SeriesAxis/from_index_mapping
|
@classmethod
def from_index_mapping(cls, mim):
"""
Creates a new SeriesAxis axis based on a CIFTI-2 dataset
Parameters
----------
mim : :class:`.cifti2.Cifti2MatrixIndicesMap`
Returns
-------
SeriesAxis
"""
start = mim.series_start * 10 ** mim.series_exponent
step = mim.series_step * 10 ** mim.series_exponent
return cls(start, step, mim.number_of_series_points, mim.series_unit)
|
os_vm_expire
|
os_vm_expire//cmd/expire_manage.pyfile:/cmd/expire_manage.py:function:methods_of/methods_of
|
def methods_of(obj):
"""Get all callable methods of an object that don't start with underscore
returns a list of tuples of the form (method_name, method)
"""
result = []
for fn in dir(obj):
if callable(getattr(obj, fn)) and not fn.startswith('_'):
result.append((fn, getattr(obj, fn), getattr(obj, fn +
'_description', None)))
return result
|
kidx_core
|
kidx_core//utils.pyfile:/utils.py:function:cap_length/cap_length
|
def cap_length(s, char_limit=20, append_ellipsis=True):
"""Makes sure the string doesn't exceed the passed char limit.
Appends an ellipsis if the string is to long."""
if len(s) > char_limit:
if append_ellipsis:
return s[:char_limit - 3] + '...'
else:
return s[:char_limit]
else:
return s
|
crawler_utils
|
crawler_utils//utils.pyfile:/utils.py:function:url2path/url2path
|
def url2path(url):
"""
replace '/' to '_' to transfer url to file_path
:param url: string
:return:
"""
return url.strip().replace('/', '_')
|
django-servee-0.7a1.dev1
|
django-servee-0.7a1.dev1//servee/utils.pyfile:/servee/utils.py:function:space_out_camel_case/space_out_camel_case
|
def space_out_camel_case(camel):
"""
Converts a "CamelCasedName" to "Camel Case Name".
"""
chars = []
for char in camel:
if len(chars) >= 2 and chars[-1] != ' ':
if char.isupper() and chars[-1].islower():
chars.append(' ')
elif char.islower() and chars[-1].isupper() and chars[-2].isupper(
):
chars.insert(len(chars) - 1, ' ')
chars.append(char)
return ''.join(chars)
|
cflib
|
cflib//main.pyfile:/main.py:function:a/a
|
def a(n):
"""Calculate the Watterson's Theta coefficient."""
ret = 0
for i in range(n - 1):
ret += float(1.0) / (i + 1)
return ret
|
nmrstarlib-2.1.1
|
nmrstarlib-2.1.1//nmrstarlib/nmrstarlib.pyclass:StarFile/_is_cif
|
@staticmethod
def _is_cif(string):
"""Test if input string is in CIF format.
:param string: Input string.
:type string: :py:class:`str` or :py:class:`bytes`
:return: Input string if in CIF format or False otherwise.
:rtype: :py:class:`str` or :py:obj:`False`
"""
if string[0:5] == u'data_' and u'_entry.id' in string or string[0:5
] == b'data_' and b'_entry.id' in string:
return string
return False
|
chemics-20.4
|
chemics-20.4//chemics/emulsion.pyfile:/chemics/emulsion.py:function:solidsDistribution/solidsDistribution
|
def solidsDistribution(delta, emf, umf, ub, fw):
"""
Calculates the distribution of solids in the bubble, cloud/wake, and
emulsion phases using K/L eqs. 6.35-6.37.
Parameters
----------
delta : float
Volume fraction of gas in the bubbles [-]
emf : float
Void fraction at minimum fluidization [-]
umf : float
Minimum fluidization velocity [m/s]
ub : float
Bubble rise velocity [m/s]
fw : float
Ratio of the wake volume to the bubble volume [-]
Note
----
gamma_b is for the moment a hard-coded constant. See K/L eq. 6.37.
Returns
-------
gamma_b : float
Volume of solids in the bubble divided by the bubble volume
gamma_c : float
Volume of solids in the cloud/wake divided by the bubble volume
gamma_e : float
Volume of solids in the emulsion divided by the bubble volume
"""
gamma_b = 0.005
gamma_c = (1.0 - emf) * (3.0 / (ub * float(emf) / umf - 1.0) + fw)
gamma_e = (1.0 - emf) * (1.0 - delta) / delta - gamma_b - gamma_c
return gamma_b, gamma_c, gamma_e
|
moya
|
moya//serve.pyfile:/serve.py:function:file_chunker/file_chunker
|
def file_chunker(file, size=65536):
"""An iterator that reads a file in chunks."""
read = file.read
try:
chunk = read(size)
while chunk:
yield chunk
chunk = read(size)
finally:
file.close()
|
OFS
|
OFS//interfaces.pyclass:IOrderedContainer/moveObjectsDown
|
def moveObjectsDown(ids, delta=1, subset_ids=None):
""" Move specified sub-objects down by delta in container.
If no delta is specified, delta is 1. See moveObjectsByDelta for more
details.
Permission -- Manage properties
Returns -- Number of moved sub-objects
"""
|
panoptes_aggregation-3.4.3
|
panoptes_aggregation-3.4.3//panoptes_aggregation/reducers/text_utils.pyfile:/panoptes_aggregation/reducers/text_utils.py:function:angle_metric/angle_metric
|
def angle_metric(t1, t2):
"""A metric for the distance between angles in the [-180, 180] range
Parameters
----------
t1 : float
Theta one in degrees
t2 : float
Theta two in degrees
Returns
-------
distance : float
The distance between the two input angles in degrees
"""
d = abs(t1 - t2)
if d > 180:
d = 360 - d
return d
|
confpy-0.11.0
|
confpy-0.11.0//confpy/core/compat.pyfile:/confpy/core/compat.py:function:iteritems/iteritems
|
def iteritems(dictionary):
"""Replacement to account for iteritems/items switch in Py3."""
if hasattr(dictionary, 'iteritems'):
return dictionary.iteritems()
return dictionary.items()
|
cx-pyqtgraph-0.12.1
|
cx-pyqtgraph-0.12.1//cx_pyqtgraph/exceptionHandling.pyfile:/cx_pyqtgraph/exceptionHandling.py:function:setTracebackClearing/setTracebackClearing
|
def setTracebackClearing(clear=True):
"""
Enable or disable traceback clearing.
By default, clearing is disabled and Python will indefinitely store unhandled exception stack traces.
This function is provided since Python's default behavior can cause unexpected retention of
large memory-consuming objects.
"""
global clear_tracebacks
clear_tracebacks = clear
|
snipsskillscore
|
snipsskillscore//intent_parser.pyclass:IntentParser/get_dict_value
|
@staticmethod
def get_dict_value(dictionary, path):
""" Safely get the value of a dictionary given a key path. For
instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at
key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at
key path ['a', 'b', 'c'] is None.
:param dictionary: a dictionary.
:param path: the key path.
:return: The value of d at the given key path, or None if the key
path does not exist.
"""
if len(path) == 0:
return None
temp_dictionary = dictionary
try:
for k in path:
temp_dictionary = temp_dictionary[k]
return temp_dictionary
except (KeyError, TypeError):
pass
return None
|
zc
|
zc//relationship/interfaces.pyclass:IIndex/tokenizeRelationship
|
def tokenizeRelationship(rel):
"""Returns a token for the given relationship"""
|
ibapi
|
ibapi//comm.pyfile:/comm.py:function:make_field/make_field
|
def make_field(val) ->str:
""" adds the NULL string terminator """
if val is None:
raise ValueError('Cannot send None to TWS')
if type(val) is bool:
val = int(val)
field = str(val) + '\x00'
return field
|
dropbox
|
dropbox//team_log.pyclass:EventDetails/no_password_link_view_report_failed_details
|
@classmethod
def no_password_link_view_report_failed_details(cls, val):
"""
Create an instance of this class set to the
``no_password_link_view_report_failed_details`` tag with value ``val``.
:param NoPasswordLinkViewReportFailedDetails val:
:rtype: EventDetails
"""
return cls('no_password_link_view_report_failed_details', val)
|
fake-bpy-module-2.80-20200428
|
fake-bpy-module-2.80-20200428//bmesh/utils.pyfile:/bmesh/utils.py:function:vert_separate/vert_separate
|
def vert_separate(vert: 'bmesh.types.BMVert', edges: 'bmesh.types.BMEdge'
) ->'bmesh.types.BMVert':
"""Separate this vertex at every edge.
:param vert: The vert to be separated.
:type vert: 'bmesh.types.BMVert'
:param edges: The edges to separated.
:type edges: 'bmesh.types.BMEdge'
:return: The newly separated verts (including the vertex passed).
"""
pass
|
sylib
|
sylib//atfparser/parser.pyfile:/atfparser/parser.py:function:p_dval_undefined/p_dval_undefined
|
def p_dval_undefined(p):
"""dval : UNDEFINED SEMICOLON"""
p[0] = None
|
pyxdf-1.16.2
|
pyxdf-1.16.2//pyxdf/pyxdf.pyfile:/pyxdf/pyxdf.py:function:parse_chunks/parse_chunks
|
def parse_chunks(chunks):
"""Parse chunks and extract information on individual streams."""
streams = []
for chunk in chunks:
if chunk['tag'] == 2:
streams.append(dict(stream_id=chunk['stream_id'], name=chunk.
get('name'), type=chunk.get('type'), source_id=chunk.get(
'source_id'), created_at=chunk.get('created_at'), uid=chunk
.get('uid'), session_id=chunk.get('session_id'), hostname=
chunk.get('hostname'), channel_count=int(chunk[
'channel_count']), channel_format=chunk['channel_format'],
nominal_srate=int(chunk['nominal_srate'])))
return streams
|
dropbox
|
dropbox//team_log.pyclass:EventDetails/paper_default_folder_policy_changed_details
|
@classmethod
def paper_default_folder_policy_changed_details(cls, val):
"""
Create an instance of this class set to the
``paper_default_folder_policy_changed_details`` tag with value ``val``.
:param PaperDefaultFolderPolicyChangedDetails val:
:rtype: EventDetails
"""
return cls('paper_default_folder_policy_changed_details', val)
|
dsin100daysv19-6.0.0.dev0
|
dsin100daysv19-6.0.0.dev0//notebook/_tz.pyfile:/notebook/_tz.py:function:isoformat/isoformat
|
def isoformat(dt):
"""Return iso-formatted timestamp
Like .isoformat(), but uses Z for UTC instead of +00:00
"""
return dt.isoformat().replace('+00:00', 'Z')
|
manifestparser-2.1.0
|
manifestparser-2.1.0//manifestparser/filters.pyfile:/manifestparser/filters.py:function:enabled/enabled
|
def enabled(tests, values):
"""
Removes all tests containing the `disabled` key. This filter can be
added by passing `disabled=False` into `active_tests`.
"""
for test in tests:
if 'disabled' not in test:
yield test
|
imagesplit
|
imagesplit//file/metaio_reader.pyfile:/file/metaio_reader.py:function:anatomical_to_cosine/anatomical_to_cosine
|
def anatomical_to_cosine(anatomical_orientation_char):
"""Get Dicom direction cosine for this orientation string"""
if anatomical_orientation_char == 'R':
return [1, 0, 0]
elif anatomical_orientation_char == 'L':
return [-1, 0, 0]
elif anatomical_orientation_char == 'A':
return [0, 1, 0]
elif anatomical_orientation_char == 'P':
return [0, -1, 0]
elif anatomical_orientation_char == 'I':
return [0, 0, 1]
elif anatomical_orientation_char == 'S':
return [0, 0, -1]
else:
raise ValueError(
'No implementation yet for anatomical orientation ' +
anatomical_orientation_char + '.')
|
Pytzer-0.4.3
|
Pytzer-0.4.3//pytzer/dissociation.pyfile:/pytzer/dissociation.py:function:rhow_K75/rhow_K75
|
def rhow_K75(tempK):
"""Water density in g/cm**3 following Kell (1975) J. Chem. Eng. Data 20(1),
97-105.
"""
tempC = tempK - 273.15
return (0.99983952 + 0.016945176 * tempC - 7.9870401e-06 * tempC ** 2 -
4.6170461e-08 * tempC ** 3 + 1.0556302e-10 * tempC ** 4 -
2.8054253e-13 * tempC ** 5) / (1 + 0.01687985 * tempC)
|
sodapclient
|
sodapclient//VariableLoader.pyclass:VariableLoader/check_dim_sels
|
@staticmethod
def check_dim_sels(var_dims, dim_sels, num_dims):
"""
Extract dimension selections and check they're valid.
args...
var_dims: variable dimensions
dim_sels: dimension selections (see get_request_url)
num_dims: number of dimensions
"""
dims_ok = True
for idim in range(num_dims):
if dim_sels[idim, 0] < 0 or dim_sels[idim, 1] < 0 or dim_sels[idim, 2
] < 0:
dims_ok = False
if dim_sels[idim, 0] > var_dims[idim] - 1 or dim_sels[idim, 2
] > var_dims[idim] - 1:
dims_ok = False
if dim_sels[idim, 2] < dim_sels[idim, 0]:
dims_ok = False
if dim_sels[idim, 0] != dim_sels[idim, 2] and dim_sels[idim, 1
] > dim_sels[idim, 2]:
dims_ok = False
return dims_ok
|
dp
|
dp//pygui/Demo_Matplotlib_Browser_Paned.pyfile:/pygui/Demo_Matplotlib_Browser_Paned.py:function:PyplotArtistBoxPlots/PyplotArtistBoxPlots
|
def PyplotArtistBoxPlots():
"""
=========================================
Demo of artist customization in box plots
=========================================
This example demonstrates how to use the various kwargs
to fully customize box plots. The first figure demonstrates
how to remove and add individual components (note that the
mean is the only value not shown by default). The second
figure demonstrates how the styles of the artists can
be customized. It also demonstrates how to set the limit
of the whiskers to specific percentiles (lower right axes)
A good general reference on boxplots and their history can be found
here: http://vita.had.co.nz/papers/boxplots.pdf
"""
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(937)
data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75)
labels = list('ABCD')
fs = 10
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True)
axes[0, 0].boxplot(data, labels=labels)
axes[0, 0].set_title('Default', fontsize=fs)
axes[0, 1].boxplot(data, labels=labels, showmeans=True)
axes[0, 1].set_title('showmeans=True', fontsize=fs)
axes[0, 2].boxplot(data, labels=labels, showmeans=True, meanline=True)
axes[0, 2].set_title('showmeans=True,\nmeanline=True', fontsize=fs)
axes[1, 0].boxplot(data, labels=labels, showbox=False, showcaps=False)
tufte_title = 'Tufte Style \n(showbox=False,\nshowcaps=False)'
axes[1, 0].set_title(tufte_title, fontsize=fs)
axes[1, 1].boxplot(data, labels=labels, notch=True, bootstrap=10000)
axes[1, 1].set_title('notch=True,\nbootstrap=10000', fontsize=fs)
axes[1, 2].boxplot(data, labels=labels, showfliers=False)
axes[1, 2].set_title('showfliers=False', fontsize=fs)
for ax in axes.flatten():
ax.set_yscale('log')
ax.set_yticklabels([])
fig.subplots_adjust(hspace=0.4)
return fig
|
ulog_tools-0.0.9
|
ulog_tools-0.0.9//versioneer.pyfile:/versioneer.py:function:render_git_describe/render_git_describe
|
def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if pieces['distance']:
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
serial
|
serial//serialutil.pyfile:/serialutil.py:function:iterbytes/iterbytes
|
def iterbytes(b):
"""Iterate over bytes, returning bytes instead of ints (python3)"""
if isinstance(b, memoryview):
b = b.tobytes()
i = 0
while True:
a = b[i:i + 1]
i += 1
if a:
yield a
else:
break
|
pywidl-0.1
|
pywidl-0.1//pywidl/grammar.pyfile:/pywidl/grammar.py:function:p_Default/p_Default
|
def p_Default(p):
"""Default : "=" DefaultValue"""
p[0] = p[2]
|
mrjob-0.7.2
|
mrjob-0.7.2//mrjob/logs/ids.pyfile:/mrjob/logs/ids.py:function:_id_part/_id_part
|
def _id_part(id, i):
"""Get the ith part of some container ID, e.g.
container_1567013493699_0003_01_000002. If *id* is None
or too short, return ''"""
parts = (id or '').split('_')
if i >= len(parts):
return ''
else:
return parts[i]
|
navegador5-0.60
|
navegador5-0.60//navegador5/cookie/rfc6265.pyfile:/navegador5/cookie/rfc6265.py:function:_all_cookie_octets_str/_all_cookie_octets_str
|
def _all_cookie_octets_str():
"""
%x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E;
US-ASCII characters excluding CTLs,
whitespace DQUOTE, comma, semicolon,
and backslash
"""
all_cookie_octets_str = '!'
for i in range(35, 44):
all_cookie_octets_str = all_cookie_octets_str + chr(i)
for i in range(45, 58):
all_cookie_octets_str = all_cookie_octets_str + chr(i)
for i in range(60, 92):
all_cookie_octets_str = all_cookie_octets_str + chr(i)
for i in range(93, 126):
all_cookie_octets_str = all_cookie_octets_str + chr(i)
return all_cookie_octets_str
|
explorator-0.0.15
|
explorator-0.0.15//explorator/functions.pyfile:/explorator/functions.py:function:filtered_string_DEPRECATED/filtered_string_DEPRECATED
|
def filtered_string_DEPRECATED(content, delete_words=None):
"""
Эта функция делает следующие преобразования со строкой:
- Удаляет пробелы по краям строки
- Удаляет подстроки из списка delete_words
- Удаляет пробелы подряд в строке, оставляя один
Parameters
----------
content: (str) - целевая строка
delete_words: (list of str) - подстроки, которые надо удалить из целевой строки
Returns
-------
(str) - обработанная строка
"""
if delete_words is None:
delete_words = []
if content != float('nan'):
content = str(content)
if delete_words:
for word in delete_words:
content = content.replace(word, '')
content = content.strip()
tmp = ''
i = 0
while i < len(content):
if i < len(content) - 1 and content[i] + content[i + 1] != ' ':
tmp += content[i]
elif i == len(content) - 1:
tmp += content[i]
i += 1
content = tmp
return content
|
aboleth
|
aboleth//distributions.pyfile:/distributions.py:function:_add_suffix/_add_suffix
|
def _add_suffix(name, suffix):
"""Add a suffix to a name, do nothing if suffix is None."""
suffix = '' if suffix is None else '_' + suffix
new_name = name + suffix
return new_name
|
rhasspy-hermes-0.2.0
|
rhasspy-hermes-0.2.0//rhasspyhermes/nlu.pyclass:NluIntentParsed/topic
|
@classmethod
def topic(cls, **kwargs) ->str:
"""Get topic for message."""
return 'hermes/nlu/intentParsed'
|
urlstring-2.4.0
|
urlstring-2.4.0//urlstring/path.pyclass:URLPath/join_segments
|
@classmethod
def join_segments(cls, segments, absolute=True):
"""Create a :class:`URLPath` from an iterable of segments."""
if absolute:
path = cls('/')
else:
path = cls('')
for segment in segments:
path = path.add_segment(segment)
return path
|
CNFgen-0.8.4.1
|
CNFgen-0.8.4.1//cnfformula/cmdline.pyclass:GraphHelper/setup_command_line
|
@staticmethod
def setup_command_line(parser):
"""Setup command line options for getting graphs"""
raise NotImplementedError('Graph Input helper must be subclassed')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.