repo
stringlengths 1
29
| path
stringlengths 24
332
| code
stringlengths 39
579k
|
---|---|---|
texterra | texterra//feature/disambiguation.pyfile:/feature/disambiguation.py:function:process/process | def process(document, rtype=None, api=None):
""" Receives a texterra-annotated annotated_text and returns its terms' list."""
result = []
if 'disambiguated-phrase' in document['annotations']:
terms, ids, kbnames = [], [], []
for term in document['annotations']['disambiguated-phrase']:
term_id = term['value']['id']
kb_name = term['value']['kb-name']
ids.append(term_id)
kbnames.append(kb_name)
terms.append((term['start'], term['end'], document['text'][term
['start']:term['end']], '{0}:{1}'.format(term_id, kb_name)))
if len(ids) > 0:
atrs = api._get_attributes(ids, kbnames, ['url'])
for term in terms:
result.append((term[0], term[1], term[2], atrs[term[3]]['url'])
)
return result
|
zof | zof//controller.pyfile:/controller.py:function:_negative_signal_number/_negative_signal_number | def _negative_signal_number(signame):
"""Return negative number to represent signal named `signame`.
If signame is unknown, return -99.
"""
try:
import signal
return -getattr(signal, signame)
except AttributeError:
return -99
|
sharedcloud_cli | sharedcloud_cli//mappers.pyfile:/mappers.py:function:_map_boolean_to_human_readable/_map_boolean_to_human_readable | def _map_boolean_to_human_readable(boolean, resource, token):
"""
Map a boolean into a human readable representation (Yes/No).
:param boolean: boolean with the value that we want to transform
:param resource: resource containing all the values and keys
:param token: user token
"""
if boolean:
return 'Yes'
else:
return 'No'
|
metrdsutil-0.1.9 | metrdsutil-0.1.9//metrdsutil/jupyter/jupyter.pyfile:/metrdsutil/jupyter/jupyter.py:function:notebook_config/notebook_config | def notebook_config(notebook_width=75, hide_lines='collapse'):
"""
configures viewing options of the jupyter notebook
parameters:
-----------
notebook_width : int
how wide (in %) the notebook should be
hide_lines : str
'collapse' for hiding line in/out, 'show' for showing
"""
statements = [
"""
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Show Code"></form>''')
"""
,
"display(HTML('<style>.prompt{width: 0px; min-width: 0px; visibility: "
+ hide_lines + "}</style>'))",
'display(HTML("<style>.container { width:' + str(notebook_width) +
'% !important; }</style>"))',
"pd.set_option('display.max_columns', 500)",
"pd.set_option('display.width', 250)"]
string = ''
for i in statements:
string += i + '\n'
return string
|
scss | scss//types.pyclass:String/unquoted | @classmethod
def unquoted(cls, value, literal=False):
"""Helper to create a string with no quotes."""
return cls(value, quotes=None, literal=literal)
|
givemebib | givemebib//functions.pyfile:/functions.py:function:savenonamebib/savenonamebib | def savenonamebib(bib, dirpath):
"""Given a target directory and a bib string with no filename to save it into, tries the following filenames until one is not taken :
_ nameinbib.bib (nameinbib = the entry name in the bib, e.g. @article{author_year=nameinbib)
_ JACS_nameinbib.bib (JACS is replaced by the initials of the journal name)
_ JACS_nameinbib_2.bib
_ JACS_nameinbib_3.bib
..."""
from pathlib import Path
openbib = bib.strip().split('\n')
for line in openbib:
if line.strip().startswith('@'):
name = line.split('{')[-1].replace(',', '').replace("'", '')
elif line.strip().startswith('year'):
year = int(line.split('=')[-1].replace('{', '').replace('}', ''
).replace(',', '').strip())
elif line.strip().startswith('journal'):
journame = line.split('=')[-1].replace('{', '').replace('}', ''
).lower().replace('the', '').replace('of', '').strip()
while ' ' in journame:
journame = journame.replace(' ', ' ')
journame = journame.split(' ')
temp = ''
if len(journame) == 1:
temp = journame[0]
else:
for word in journame:
temp += word[0].upper()
journame = temp
filename = name + '.bib'
if Path(filename).is_file():
filename = journame + '_' + filename
while Path(filename).is_file():
filename = filename.replace('.bib', '')
if filename.split('_')[-1].isdigit and int(filename.
split('_')[-1]) != year:
filename = filename[:-1] + str(int(filename[-1]) + 1
) + '.bib'
else:
filename = filename + '_2.bib'
with Path(dirpath / filename).open(mode='w') as outputfile:
outputfile.write(bib)
return filename
|
zxbasic-1.9.2 | zxbasic-1.9.2//zxbpp.pyfile:/zxbpp.py:function:p_exprge/p_exprge | def p_exprge(p):
""" expr : expr GE expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a >= b else '0'
|
xccdfparser | xccdfparser//lib.pyfile:/lib.py:function:unify_lookup/unify_lookup | def unify_lookup(lookup, results):
""" Create a unified serializable list from lookup and results. """
unified_list = []
for key in results.keys():
if key not in ('score', 'max_score'):
created_testbench = {'title': lookup[key][0], 'rule-id': key,
'x_fixtext': lookup[key][1]}
unified_list.append(created_testbench)
return unified_list
|
eclcli | eclcli//monitoring/monitoringclient/base.pyfile:/monitoring/monitoringclient/base.py:function:getid/getid | def getid(obj):
"""Extracts object ID.
Abstracts the common pattern of allowing both an object or an
object's ID (UUID) as a parameter when dealing with relationships.
"""
try:
return obj.id
except AttributeError:
return obj
|
django_linux | django_linux//core/files/base.pyfile:/core/files/base.py:function:endswith_lf/endswith_lf | def endswith_lf(line):
"""Return True if line (a text or byte string) ends with '
'."""
return line.endswith('\n' if isinstance(line, str) else b'\n')
|
yggdrasil-framework-1.1.1 | yggdrasil-framework-1.1.1//yggdrasil/command_line.pyfile:/yggdrasil/command_line.py:function:yggtime_py/yggtime_py | def yggtime_py():
"""Plot timing statistics comparing the different versions of Python."""
from yggdrasil import timing
timing.plot_scalings(compare='python')
|
xdict-1.1.11 | xdict-1.1.11//xdict/utils.pyfile:/xdict/utils.py:function:list_comprise/list_comprise | def list_comprise(list1, list2, **kwargs):
"""
list_comprise([1,2,3,4,5],[2,3,4],strict=0)
list_comprise([1,2,3,4,5],[2,3,4])
list_comprise([1,2,3,4,5],[2,3,4],strict=1)
list_comprise([1,2,3,4,5],[1,2,3,4],strict=1)
"""
if 'strict' in kwargs:
strict = kwargs['strict']
else:
strict = 0
len_1 = list1.__len__()
len_2 = list2.__len__()
if len_2 > len_1:
return False
elif strict:
if list2 == list1[:len_2]:
return True
else:
return False
else:
end = len_1 - len_2
for i in range(0, end + 1):
if list2 == list1[i:i + len_2]:
return True
else:
pass
return False
|
bars | bars//std.pyclass:bars/_decr_instances | @classmethod
def _decr_instances(cls, instance):
"""
Remove from list and reposition other bars
so that newer bars won't overlap previous bars
"""
with cls._lock:
try:
cls._instances.remove(instance)
except KeyError:
pass
if not instance.gui:
for inst in cls._instances:
if hasattr(inst, 'pos') and inst.pos > abs(instance.pos):
inst.clear(nolock=True)
inst.pos -= 1
if not cls._instances and cls.monitor:
try:
cls.monitor.exit()
del cls.monitor
except AttributeError:
pass
else:
cls.monitor = None
|
uwsgiconf-0.20.1 | uwsgiconf-0.20.1//uwsgiconf/uwsgi_stub.pyfile:/uwsgiconf/uwsgi_stub.py:function:metric_div/metric_div | def metric_div(key, value=1):
"""Divides the specified metric key value by the specified value.
:param str|unicode key:
:param int value:
:rtype: bool
"""
return False
|
javelin-0.1.0 | javelin-0.1.0//javelin/utils.pyfile:/javelin/utils.py:function:is_structure/is_structure | def is_structure(structure):
"""Check if an object is a stucture that javelin can understand.
ase.atoms with have cell, get_scaled_positions and get_atomic_numbers attributes
diffpy.structure with have lattice, xyz, and element attributes
"""
return (hasattr(structure, 'cell') or hasattr(structure, 'unitcell')
) and hasattr(structure, 'get_scaled_positions') and hasattr(structure,
'get_atomic_numbers') or hasattr(structure, 'lattice') and hasattr(
structure, 'xyz') and hasattr(structure, 'element')
|
bpy | bpy//ops/view3d.pyfile:/ops/view3d.py:function:ndof_orbit_zoom/ndof_orbit_zoom | def ndof_orbit_zoom():
"""Orbit and zoom the view using the 3D mouse
"""
pass
|
sila2lib | sila2lib//proto_builder/proto_builder.pyfile:/proto_builder/proto_builder.py:function:hook_comment/hook_comment | def hook_comment(input_string: str, comment_char: str='# ') ->str:
"""
Comment the given string
:param input_string: The string to comment. Multi-line strings will receive a comment on each line
:param comment_char: The character(s) to add at the beginning of each line
:return: The commented string
.. note:: Block-comments are not supported at the moment
"""
return comment_char + input_string.replace('\n', '\n' + comment_char)
|
mercurial | mercurial//scmutil.pyfile:/scmutil.py:function:bookmarkrevs/bookmarkrevs | def bookmarkrevs(repo, mark):
"""
Select revisions reachable by a given bookmark
"""
return repo.revs(
b'ancestors(bookmark(%s)) - ancestors(head() and not bookmark(%s)) - ancestors(bookmark() and not bookmark(%s))'
, mark, mark, mark)
|
atomium | atomium//mmcif.pyfile:/mmcif.py:function:atom_dict_to_atom_dict/atom_dict_to_atom_dict | def atom_dict_to_atom_dict(d, aniso_dict):
"""Turns an .mmcif atom dictionary into an atomium atom data dictionary.
:param dict d: the .mmcif atom dictionary.
:param dict d: the mapping of atom IDs to anisotropy.
:rtype: ``dict``"""
charge = 'pdbx_formal_charge'
atom = {'x': d['Cartn_x'], 'y': d['Cartn_y'], 'z': d['Cartn_z'],
'element': d['type_symbol'], 'name': d.get('label_atom_id'),
'occupancy': d.get('occupancy', 1), 'bvalue': d.get(
'B_iso_or_equiv'), 'charge': d.get(charge, 0) if d.get(charge) !=
'?' else 0, 'alt_loc': d.get('label_alt_id') if d.get(
'label_alt_id') != '.' else None, 'anisotropy': aniso_dict.get(int(
d['id']), [0, 0, 0, 0, 0, 0])}
for key in ['x', 'y', 'z', 'charge', 'bvalue', 'occupancy']:
if atom[key] is not None:
atom[key] = float(atom[key])
return atom
|
artemis-ml-2.0.0 | artemis-ml-2.0.0//artemis/general/should_be_builtins.pyfile:/artemis/general/should_be_builtins.py:function:reducemap/reducemap | def reducemap(func, sequence, initial=None, include_zeroth=False):
"""
A version of reduce that also returns the intermediate values.
:param func: A function of the form x_i_plus_1 = f(x_i, params_i)
Where:
x_i is the value passed through the reduce.
params_i is the i'th element of sequence
x_i_plus_i is the value that will be passed to the next step
:param sequence: A list of parameters to feed at each step of the reduce.
:param initial: Optionally, an initial value (else the first element of the sequence will be taken as the initial)
:param include_zeroth: Include the initial value in the returned list.
:return: A list of length: len(sequence), (or len(sequence)+1 if include_zeroth is True) containing the computed result of each iteration.
"""
if initial is None:
val = sequence[0]
sequence = sequence[1:]
else:
val = initial
results = [val] if include_zeroth else []
for s in sequence:
val = func(val, s)
results.append(val)
return results
|
dask-2.15.0 | dask-2.15.0//dask/bag/core.pyfile:/dask/bag/core.py:function:dictitems/dictitems | def dictitems(d):
""" A pickleable version of dict.items
>>> dictitems({'x': 1})
[('x', 1)]
"""
return list(d.items())
|
ruffruffs-0.0.2 | ruffruffs-0.0.2//ruffruffs/packages/urllib3/util/url.pyfile:/ruffruffs/packages/urllib3/util/url.py:function:split_first/split_first | def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims.
"""
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0:
return s, '', None
return s[:min_idx], s[min_idx + 1:], min_delim
|
lighter | lighter//functional/metric.pyfile:/functional/metric.py:function:FP/FP | def FP(target, prediction):
"""
False positives.
:param target: target value
:param prediction: prediction value
:return:
"""
return ((target == 0).float() * prediction.float().round()).sum()
|
CatLearn-0.6.2 | CatLearn-0.6.2//catlearn/regression/gpfunctions/kernel_scaling.pyfile:/catlearn/regression/gpfunctions/kernel_scaling.py:function:_laplacian_kernel_scale/_laplacian_kernel_scale | def _laplacian_kernel_scale(kernel, mean, std, rescale):
"""Scale Gaussian kernel hyperparameters.
Parameters
----------
kernel : dict
Dictionary containing all information for a single kernel.
mean : array
An array of mean values for all features.
std : array
An array of standard deviation values for all features.
rescale : boolean
Flag for whether to scale or rescale the data.
"""
print('{} kernel hyperparameters left unscaled'.format(kernel['type']))
return kernel
|
discord | discord//colour.pyclass:Colour/dark_purple | @classmethod
def dark_purple(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x71368a``."""
return cls(7419530)
|
ddtrace-0.37.0 | ddtrace-0.37.0//ddtrace/vendor/attr/_config.pyfile:/ddtrace/vendor/attr/_config.py:function:set_run_validators/set_run_validators | def set_run_validators(run):
"""
Set whether or not validators are run. By default, they are run.
"""
if not isinstance(run, bool):
raise TypeError("'run' must be bool.")
global _run_validators
_run_validators = run
|
polaris | polaris//batch/batch.pyfile:/batch/batch.py:function:build_viz_args/build_viz_args | def build_viz_args(config):
"""Build arguments for viz command when invoked from batch
:param config: polaris configuration for satellite
"""
output_graph_file = config.output_graph_file
return '--graph_file {}'.format(output_graph_file)
|
rnalysis | rnalysis//filtering.pyclass:Filter/_from_string | @staticmethod
def _from_string(msg: str='', delimiter: str='\n'):
"""
Takes a manual string input from the user, and then splits it using a delimiter into a list of values. Called when an FeatureSet instance is created without input, or when FeatureSet.enrich_randomization is called without input.
:param msg: a promprt to be printed to the user
:param delimiter: the delimiter used to separate the values. Default is '
'
:return:
A list of the comma-seperated values the user inserted.
"""
string = input(msg)
split = string.split(sep=delimiter)
if split[-1] == '':
split = split[:-1]
return split
|
ocean | ocean//modules/mixin_misccmds.pyclass:MixIn/requirements | @classmethod
def requirements(cls, srv, include_ip=False, indent='', format='text'):
"""
Describe the requirements of a server by providing a tree view of the requirements
:param srv:
:param indent:
:return:
"""
res = []
try:
requires = cls._ocean._get(srv).get('requires', [])
ip = ''
if include_ip:
ip = cls._ocean.get_ip(srv)
if format == 'text' and ip in [None, '']:
ip = 'not running'
if format == 'text':
others = ''
if include_ip:
others = ' (%s)' % (ip,)
res.append(indent + srv + others)
else:
res.append((srv, ip))
for x in sorted(requires):
res += cls.requirements(x, include_ip=include_ip, indent=indent +
' ' * 4)
except BaseException:
res.append(indent + srv + '[Not found !]')
if not len(indent) and format == 'text':
res = '\n'.join(res)
return res
|
pyverm | pyverm//_utils.pyfile:/_utils.py:function:input_decimal/input_decimal | def input_decimal(value):
"""
Function to make sure a value to a decimal value.
:param value: numeric value or ``None``
:return: value as ``Decimal`` or ``None``
"""
if value is None:
return None
else:
try:
return float(value)
except:
raise TypeError
|
sharedpy-0.0.106 | sharedpy-0.0.106//sharedpy/collection/utils.pyfile:/sharedpy/collection/utils.py:function:tag_last/tag_last | def tag_last(iterable):
"""
Given some iterable, returns (last, item), where last is only true if you are on the final iteration.
Slightly modified version of https://stackoverflow.com/a/22995806
"""
iterator = iter(iterable)
gotone = False
try:
lookback = next(iterator)
gotone = True
while True:
cur = next(iterator)
yield False, lookback
lookback = cur
except StopIteration:
if gotone:
yield True, lookback
|
matplotlib | matplotlib//_layoutbox.pyfile:/_layoutbox.py:function:hpack/hpack | def hpack(boxes, padding=0, strength='strong'):
"""
Stack LayoutBox instances from left to right.
"""
for i in range(1, len(boxes)):
c = boxes[i - 1].right + padding == boxes[i].left
boxes[i].solver.addConstraint(c | strength)
|
pyboto3-1.4.4 | pyboto3-1.4.4//pyboto3/waf.pyfile:/pyboto3/waf.py:function:update_sql_injection_match_set/update_sql_injection_match_set | def update_sql_injection_match_set(SqlInjectionMatchSetId=None, ChangeToken
=None, Updates=None):
"""
Inserts or deletes SqlInjectionMatchTuple objects (filters) in a SqlInjectionMatchSet . For each SqlInjectionMatchTuple object, you specify the following values:
You use SqlInjectionMatchSet objects to specify which CloudFront requests you want to allow, block, or count. For example, if you're receiving requests that contain snippets of SQL code in the query string and you want to block the requests, you can create a SqlInjectionMatchSet with the applicable settings, and then configure AWS WAF to block the requests.
To create and configure a SqlInjectionMatchSet , perform the following steps:
For more information about how to use the AWS WAF API to allow or block HTTP requests, see the AWS WAF Developer Guide .
See also: AWS API Documentation
Examples
The following example deletes a SqlInjectionMatchTuple object (filters) in a SQL injection match set with the ID example1ds3t-46da-4fdb-b8d5-abc321j569j5.
Expected Output:
:example: response = client.update_sql_injection_match_set(
SqlInjectionMatchSetId='string',
ChangeToken='string',
Updates=[
{
'Action': 'INSERT'|'DELETE',
'SqlInjectionMatchTuple': {
'FieldToMatch': {
'Type': 'URI'|'QUERY_STRING'|'HEADER'|'METHOD'|'BODY',
'Data': 'string'
},
'TextTransformation': 'NONE'|'COMPRESS_WHITE_SPACE'|'HTML_ENTITY_DECODE'|'LOWERCASE'|'CMD_LINE'|'URL_DECODE'
}
},
]
)
:type SqlInjectionMatchSetId: string
:param SqlInjectionMatchSetId: [REQUIRED]
The SqlInjectionMatchSetId of the SqlInjectionMatchSet that you want to update. SqlInjectionMatchSetId is returned by CreateSqlInjectionMatchSet and by ListSqlInjectionMatchSets .
:type ChangeToken: string
:param ChangeToken: [REQUIRED]
The value returned by the most recent call to GetChangeToken .
:type Updates: list
:param Updates: [REQUIRED]
An array of SqlInjectionMatchSetUpdate objects that you want to insert into or delete from a SqlInjectionMatchSet . For more information, see the applicable data types:
SqlInjectionMatchSetUpdate : Contains Action and SqlInjectionMatchTuple
SqlInjectionMatchTuple : Contains FieldToMatch and TextTransformation
FieldToMatch : Contains Data and Type
(dict) --Specifies the part of a web request that you want to inspect for snippets of malicious SQL code and indicates whether you want to add the specification to a SqlInjectionMatchSet or delete it from a SqlInjectionMatchSet .
Action (string) -- [REQUIRED]Specify INSERT to add a SqlInjectionMatchSetUpdate to a SqlInjectionMatchSet . Use DELETE to remove a SqlInjectionMatchSetUpdate from a SqlInjectionMatchSet .
SqlInjectionMatchTuple (dict) -- [REQUIRED]Specifies the part of a web request that you want AWS WAF to inspect for snippets of malicious SQL code and, if you want AWS WAF to inspect a header, the name of the header.
FieldToMatch (dict) -- [REQUIRED]Specifies where in a web request to look for snippets of malicious SQL code.
Type (string) -- [REQUIRED]The part of the web request that you want AWS WAF to search for a specified string. Parts of a request that you can search include the following:
HEADER : A specified request header, for example, the value of the User-Agent or Referer header. If you choose HEADER for the type, specify the name of the header in Data .
METHOD : The HTTP method, which indicated the type of operation that the request is asking the origin to perform. Amazon CloudFront supports the following methods: DELETE , GET , HEAD , OPTIONS , PATCH , POST , and PUT .
QUERY_STRING : A query string, which is the part of a URL that appears after a ? character, if any.
URI : The part of a web request that identifies a resource, for example, /images/daily-ad.jpg .
BODY : The part of a request that contains any additional data that you want to send to your web server as the HTTP request body, such as data from a form. The request body immediately follows the request headers. Note that only the first 8192 bytes of the request body are forwarded to AWS WAF for inspection. To allow or block requests based on the length of the body, you can create a size constraint set. For more information, see CreateSizeConstraintSet .
Data (string) --When the value of Type is HEADER , enter the name of the header that you want AWS WAF to search, for example, User-Agent or Referer . If the value of Type is any other value, omit Data .
The name of the header is not case sensitive.
TextTransformation (string) -- [REQUIRED]Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass AWS WAF. If you specify a transformation, AWS WAF performs the transformation on FieldToMatch before inspecting a request for a match.
CMD_LINE
When you're concerned that attackers are injecting an operating system commandline command and using unusual formatting to disguise some or all of the command, use this option to perform the following transformations:
Delete the following characters: ' ' ^
Delete spaces before the following characters: / (
Replace the following characters with a space: , ;
Replace multiple spaces with one space
Convert uppercase letters (A-Z) to lowercase (a-z)
COMPRESS_WHITE_SPACE
Use this option to replace the following characters with a space character (decimal 32):
f, formfeed, decimal 12
t, tab, decimal 9
n, newline, decimal 10
r, carriage return, decimal 13
v, vertical tab, decimal 11
non-breaking space, decimal 160
COMPRESS_WHITE_SPACE also replaces multiple spaces with one space.HTML_ENTITY_DECODE
Use this option to replace HTML-encoded characters with unencoded characters. HTML_ENTITY_DECODE performs the following operations:
Replaces (ampersand)quot; with '
Replaces (ampersand)nbsp; with a non-breaking space, decimal 160
Replaces (ampersand)lt; with a 'less than' symbol
Replaces (ampersand)gt; with ````
Replaces characters that are represented in hexadecimal format, (ampersand)#xhhhh; , with the corresponding characters
Replaces characters that are represented in decimal format, (ampersand)#nnnn; , with the corresponding characters
LOWERCASE
Use this option to convert uppercase letters (A-Z) to lowercase (a-z).
URL_DECODE
Use this option to decode a URL-encoded value.
NONE
Specify NONE if you don't want to perform any text transformations.
:rtype: dict
:return: {
'ChangeToken': 'string'
}
:returns:
Submit a CreateSqlInjectionMatchSet request.
Use GetChangeToken to get the change token that you provide in the ChangeToken parameter of an UpdateIPSet request.
Submit an UpdateSqlInjectionMatchSet request to specify the parts of web requests that you want AWS WAF to inspect for snippets of SQL code.
"""
pass
|
paasta-tools-0.92.1 | paasta-tools-0.92.1//paasta_tools/frameworks/constraints.pyfile:/paasta_tools/frameworks/constraints.py:function:nested_inc/nested_inc | def nested_inc(op, _, attr_val, attr_name, state, step=1):
"""Increments relevant counter by step from args array"""
oph = state.setdefault(op, {})
nameh = oph.setdefault(attr_name, {})
nameh.setdefault(attr_val, 0)
nameh[attr_val] += step
return state
|
chester | chester//tournament.pyfile:/tournament.py:function:_get_match_id/_get_match_id | def _get_match_id(p1, p2, round_id):
"""Return a unique integer for each pair of p1 and p2 for every value of round_id.
Property:
_get_match_id(p1, p2, r) == _get_match_id(p2, p1, r) for all p1, p2, r
"""
return hash(''.join(sorted(str(p1) + str(p2) + str(round_id))))
|
wotpy | wotpy//protocols/mqtt/handlers/action.pyclass:ActionMQTTHandler/to_result_topic | @classmethod
def to_result_topic(cls, invocation_topic):
"""Takes an Action invocation MQTT topic and returns the related result topic."""
topic_split = invocation_topic.split('/')
servient_id, thing_name, action_name = topic_split[-5], topic_split[-2
], topic_split[-1]
return '{}/action/result/{}/{}'.format(servient_id, thing_name, action_name
)
|
ipython-7.14.0 | ipython-7.14.0//IPython/core/inputtransformer2.pyfile:/IPython/core/inputtransformer2.py:function:_tr_quote2/_tr_quote2 | def _tr_quote2(content):
"""Translate lines escaped with a semicolon: ;"""
name, _, args = content.partition(' ')
return '%s("%s")' % (name, args)
|
toMaKe-0.6.3 | toMaKe-0.6.3//toMaKe/util.pyfile:/toMaKe/util.py:function:boolify/boolify | def boolify(v):
"""
return a boolean from a string
yes, y, true, True, t, 1 -> True
otherwise -> False
"""
return v.lower() in ['yes', 'y', 'true', 't', '1']
|
yujin_tools-0.4.54 | yujin_tools-0.4.54//src/catkin_make/terminal_color.pyfile:/src/catkin_make/terminal_color.py:function:enable_ANSI_colors/enable_ANSI_colors | def enable_ANSI_colors():
"""
Populates the global module dictionary `ansi` with ANSI escape sequences.
"""
global _ansi
color_order = ['black', 'red', 'green', 'yellow', 'blue', 'purple',
'cyan', 'white']
short_colors = {'black': 'k', 'red': 'r', 'green': 'g', 'yellow': 'y',
'blue': 'b', 'purple': 'p', 'cyan': 'c', 'white': 'w'}
_ansi = {'escape': '\x1b', 'reset': 0, '|': 0, 'boldon': 1, '!': 1,
'italicson': 3, '/': 3, 'ulon': 4, '_': 4, 'invon': 7, 'boldoff':
22, 'italicsoff': 23, 'uloff': 24, 'invoff': 27}
for key in _ansi:
if key != 'escape':
_ansi[key] = '{0}[{1}m'.format(_ansi['escape'], _ansi[key])
for index, color in enumerate(color_order):
_ansi[color] = '{0}[{1}m'.format(_ansi['escape'], 30 + index)
_ansi[color + 'f'] = _ansi[color]
_ansi[short_colors[color] + 'f'] = _ansi[color + 'f']
for index, color in enumerate(color_order):
_ansi[color + 'b'] = '{0}[{1}m'.format(_ansi['escape'], 40 + index)
_ansi[short_colors[color] + 'b'] = _ansi[color + 'b']
_ansi['atexclimation'] = '@!'
_ansi['atfwdslash'] = '@/'
_ansi['atunderscore'] = '@_'
_ansi['atbar'] = '@|'
|
pyplis-1.4.4 | pyplis-1.4.4//pyplis/helpers.pyfile:/pyplis/helpers.py:function:_roi_coordinates/_roi_coordinates | def _roi_coordinates(roi):
"""Convert roi coordinates into start point, height and width.
:param list roi: region of interest, i.e. ``[x0, y0, x1, y1]``
"""
return roi[0], roi[1], roi[2] - roi[0], roi[3] - roi[1]
|
smsframework_pswin | smsframework_pswin//receiver.pyfile:/receiver.py:function:_merge_request/_merge_request | def _merge_request(request):
""" Merge query string and form body """
data = {}
data.update(request.form.to_dict())
data.update(request.args.to_dict())
return data
|
byte-0.3.1 | byte-0.3.1//byte/model.pyclass:ModelOptions/parse | @classmethod
def parse(cls, value):
"""
Parse model options from dictionary or object.
:param value: Options
:type value: dict or object
"""
if not value:
return cls()
if type(value) is dict:
return cls(value)
options = {}
for key in dir(value):
if key.startswith('_'):
continue
options[key] = getattr(value, key)
return cls(options)
|
SimCADO-0.7.dev1 | SimCADO-0.7.dev1//simcado/utils.pyfile:/simcado/utils.py:function:deriv_polynomial2d/deriv_polynomial2d | def deriv_polynomial2d(poly):
"""Derivatives (gradient) of a Polynomial2D model
Parameters
----------
poly : astropy.modeling.models.Polynomial2D
Output
------
gradient : tuple of Polynomial2d
"""
import re
from astropy.modeling.models import Polynomial2D
degree = poly.degree
dpoly_dx = Polynomial2D(degree=degree - 1)
dpoly_dy = Polynomial2D(degree=degree - 1)
regexp = re.compile('c(\\d+)_(\\d+)')
for pname in poly.param_names:
match = regexp.match(pname)
i = int(match.group(1))
j = int(match.group(2))
cij = getattr(poly, pname)
pname_x = 'c%d_%d' % (i - 1, j)
pname_y = 'c%d_%d' % (i, j - 1)
setattr(dpoly_dx, pname_x, i * cij)
setattr(dpoly_dy, pname_y, j * cij)
return dpoly_dx, dpoly_dy
|
burp-ui-agent-0.6.6 | burp-ui-agent-0.6.6//burpui_agent/misc/backend/burp2.pyclass:Burp/_is_warning | @staticmethod
def _is_warning(jso):
"""Returns True if the document is a warning"""
if not jso:
return False
return 'warning' in jso
|
wrangle-0.6.7 | wrangle-0.6.7//wrangle/col/col_corr_category.pyfile:/wrangle/col/col_corr_category.py:function:col_corr_category/col_corr_category | def col_corr_category(data, col, outcome, rounding=2, warning_threshold=40):
"""Compute likeliness of a given
outcome against a set of class
attributes.
USE: wr.col_corr_cut(first, 'BUN_groups', 'hospital_mortality')
data : pandas DataFrame
col : str
A column with multilabel values
outcome : str
A column with binary class values
rounding : int
Number of decimals to be used for rounding.
warning_threshold : int
Number of samples required to avoid warning.
Warning is expressed as ** following the class
name.
"""
import pandas as pd
a = data[[outcome, col]].groupby(col).sum()
b = pd.DataFrame(data[[outcome, col]][col].value_counts())
out = a.merge(b, left_index=True, right_index=True)
out = round(out[outcome] / out[col] * 100, rounding)
out = pd.DataFrame(out)
out.columns = [outcome]
return out
|
picraft-1.0 | picraft-1.0//picraft/block.pyclass:Block/from_name | @classmethod
def from_name(cls, name, data=0):
"""
Construct a :class:`Block` instance from a *name*, as returned by the
:attr:`name` property. This may be used to construct blocks in a more
"friendly" way within code. For example::
>>> from picraft import *
>>> Block.from_name('stone')
<Block "stone" id=1 data=0>
>>> Block.from_name('wool', data=2)
<Block "wool" id=35 data=2>
The optional *data* parameter can be used to specify the data component
of the new :class:`Block` instance; it defaults to 0. Note that calling
the default constructor with a string that doesn't start with "#" is
equivalent to calling this method::
>>> Block('stone')
<Block "stone" id=1 data=0>
"""
if isinstance(name, bytes):
name = name.decode('utf-8')
try:
id_ = cls._BLOCKS_BY_NAME[name]
except KeyError:
raise ValueError('unknown name %s' % name)
return cls(id_, data)
|
keyring | keyring//cli.pyclass:CommandLineTool/strip_last_newline | @staticmethod
def strip_last_newline(str):
"""Strip one last newline, if present."""
return str[:-str.endswith('\n')]
|
instaboostfast-0.1.2 | instaboostfast-0.1.2//instaboostfast/get_instance_group.pyfile:/instaboostfast/get_instance_group.py:function:overlap/overlap | def overlap(bbox1, bbox2):
"""
Given two bboxes, return whether the two bboxes overlap
"""
x1, y1, w1, h1 = bbox1
x2, y2, w2, h2 = bbox2
return x1 < x2 + w2 and y1 < y2 + h2 and x2 < x1 + w1 and y2 < y1 + h1
|
p4a-django-1.9.1 | p4a-django-1.9.1//django/contrib/gis/db/backends/spatialite/models.pyclass:SpatialiteGeometryColumns/geom_col_name | @classmethod
def geom_col_name(cls):
"""
Returns the name of the metadata column used to store the feature
geometry column.
"""
return 'f_geometry_column'
|
PyTrack | PyTrack//etDataReader.pyfile:/etDataReader.py:function:replace_missing/replace_missing | def replace_missing(value, missing=0.0):
"""Returns missing code if passed value is missing, or the passed value if it is not missing; a missing value in the EDF contains only a period, no numbers; NOTE: this function is for gaze position values only, NOT for pupil size, as missing pupil size data is coded '0.0'
Parameters
----------
value : str
Either an X or a Y gaze position value (NOT pupil size! This is coded '0.0')
missing : float
The missing code to replace missing data with (default = 0.0)
Returns
-------
float
Either a missing code, or a float value of the gaze position
"""
if value.replace(' ', '') == '.':
return missing
else:
return float(value)
|
sequana-0.8.3 | sequana-0.8.3//sequana/cpg_islands.pyfile:/sequana/cpg_islands.py:function:CpG/CpG | def CpG(sequence, size=200):
"""
The Sequence Manipulation Suite: CpG Islands
Results for 1200 residue sequence "sample sequence" starting "taacatactt".
CpG islands search using window size of 200.
Range, value
32 to 231, the y-value is 1.75 and the %GC content is 50.5
33 to 232, the y-value is 1.75 and the %GC content is 50.5
Gardiner-Garden M, Frommer M. J Mol Biol. 1987 Jul 20;196(2):261-82.
"""
pass
|
ibmsecurity | ibmsecurity//isam/base/system_alerts/email.pyfile:/isam/base/system_alerts/email.py:function:get/get | def get(isamAppliance, uuid, check_mode=False, force=False):
"""
Get a specific email object
"""
return isamAppliance.invoke_get('Get a specific email object',
'/core/rsp_email_objs/{0}'.format(uuid))
|
asteroid | asteroid//utils.pyfile:/utils.py:function:isfloat/isfloat | def isfloat(value):
""" Computes whether `value` can be cast to a float.
Args:
value (str): Value to check.
Returns:
bool: Whether `value` can be cast to a float.
"""
try:
float(value)
return True
except ValueError:
return False
|
filesystems-0.25.0 | filesystems-0.25.0//filesystems/interfaces.pyclass:Path/relative_to | def relative_to(path):
"""
Resolve a path relative to this one.
"""
|
orator | orator//orm/model.pyclass:Model/updating | @classmethod
def updating(cls, callback):
"""
Register a updating model event with the dispatcher.
:type callback: callable
"""
cls._register_model_event('updating', callback)
|
SPARQLToSQL | SPARQLToSQL//sql_helper.pyfile:/sql_helper.py:function:find_common_cond_attrs/find_common_cond_attrs | def find_common_cond_attrs(sql_obj1, sql_obj2):
"""
Find common attributes for SQL join condition
:param sql_obj1:
:param sql_obj2:
:return:
"""
commonpr_list = []
for project1 in sql_obj1.pr_list:
for project2 in sql_obj2.pr_list:
if project1.alias == project2.alias:
commonpr_list.append(project1)
return commonpr_list
|
Methanal-0.9.0 | Methanal-0.9.0//methanal/imethanal.pyclass:IColumn/extractValue | def extractValue(model, item):
"""
Extract a value for the column from an Item.
@type model: L{methanal.widgets.Table}
@type item: L{axiom.item.Item}
@param item: Item from which to extract a value
@return: Underlying value for this column
"""
|
txkoji-0.10.0 | txkoji-0.10.0//txkoji/task_states.pyfile:/txkoji/task_states.py:function:to_str/to_str | def to_str(number):
"""
Convert a task state ID number to a string.
:param int number: task state ID, eg. 1
:returns: state name like eg. "OPEN", or "(unknown)" if we don't know the
name of this task state ID number.
"""
states = globals()
for name, value in states.items():
if number == value and name.isalpha() and name.isupper():
return name
return '(unknown state %d)' % number
|
pydelaunator-0.0.15 | pydelaunator-0.0.15//pydelaunator/geometry.pyfile:/pydelaunator/geometry.py:function:clockwise_signed_polygon_area/clockwise_signed_polygon_area | def clockwise_signed_polygon_area(signed_area: float) ->bool:
"""True iff given signed area is 0 or a signed area of a
clockwise ordered polygon.
signed_area -- the signed area of any polygon
Consider that Y axis IS NOT inverted. Else, returned value is false.
See http://stackoverflow.com/a/1165943/3077939
"""
return signed_area >= 0.0
|
powerline-status-2.7 | powerline-status-2.7//powerline/lib/dict.pyfile:/powerline/lib/dict.py:function:updated/updated | def updated(d, *args, **kwargs):
"""Copy dictionary and update it with provided arguments
"""
d = d.copy()
d.update(*args, **kwargs)
return d
|
Products | Products//ZopeTree/IZopeTree.pyclass:INode/hasChildren | def hasChildren():
"""
Return true if we have children.
"""
|
Cachual-0.2.2 | Cachual-0.2.2//cachual.pyfile:/cachual.py:function:unpack_bytes/unpack_bytes | def unpack_bytes(value):
"""Unpack the given Python 3 bytes by loading them as a Python 3 unicode
string, assuming UTF-8 encoding.
:type value: bytes
:param value: The bytes to unpack.
:returns: The bytes as a Python 3 unicode string, assuming UTF-8 encoding.
"""
return value.decode('utf-8')
|
openfisca_france | openfisca_france//model/mesures.pyclass:plus_values_base_large/formula_2014_01_01 | def formula_2014_01_01(foyer_fiscal, period):
"""
Cf. docstring période précédente
"""
v1_assiette_csg_plus_values = foyer_fiscal('assiette_csg_plus_values',
period)
v2_rfr_plus_values_hors_rni = foyer_fiscal('rfr_plus_values_hors_rni',
period)
f3we = foyer_fiscal('f3we', period)
f3vz = foyer_fiscal('f3vz', period)
f3sb = foyer_fiscal('f3sb', period)
f3wb = foyer_fiscal('f3wb', period)
intersection_v1_v2 = f3we + f3vz
ajouts_de_rev_cat_pv = f3sb + f3wb
return (v1_assiette_csg_plus_values + v2_rfr_plus_values_hors_rni -
intersection_v1_v2 + ajouts_de_rev_cat_pv)
|
mercurial-5.4 | mercurial-5.4//mercurial/interfaces/repository.pyclass:imanifestdict/walk | def walk(match):
"""Generator of paths in manifest satisfying a matcher.
If the matcher has explicit files listed and they don't exist in
the manifest, ``match.bad()`` is called for each missing file.
"""
|
watson-developer-cloud-2.10.1 | watson-developer-cloud-2.10.1//watson_developer_cloud/discovery_v1.pyclass:TrainingExample/_from_dict | @classmethod
def _from_dict(cls, _dict):
"""Initialize a TrainingExample object from a json dictionary."""
args = {}
if 'document_id' in _dict:
args['document_id'] = _dict.get('document_id')
if 'cross_reference' in _dict:
args['cross_reference'] = _dict.get('cross_reference')
if 'relevance' in _dict:
args['relevance'] = _dict.get('relevance')
return cls(**args)
|
cloudpulse-2016.1.1 | cloudpulse-2016.1.1//cloudpulse/openstack/common/cliutils.pyfile:/cloudpulse/openstack/common/cliutils.py:function:isunauthenticated/isunauthenticated | def isunauthenticated(func):
"""Checks if the function does not require authentication.
Mark such functions with the `@unauthenticated` decorator.
:returns: bool
"""
return getattr(func, 'unauthenticated', False)
|
hdf5_matlab_reader-0.1.2 | hdf5_matlab_reader-0.1.2//hdf5_matlab_reader/matlab_reader.pyfile:/hdf5_matlab_reader/matlab_reader.py:function:indexarg/indexarg | def indexarg(f, arg):
"""
clearly it is more important to be pythonic than straightforward
"""
return f[arg]
|
plone.server-1.0a16 | plone.server-1.0a16//src/plone.server/plone/server/interfaces/security.pyclass:IPrincipalPermissionManager/deny_permission_to_principal | def deny_permission_to_principal(permission_id, principal_id):
"""Assert that the permission is denied to the principal.
"""
|
garlicsim_py3-0.6.3 | garlicsim_py3-0.6.3//garlicsim/misc/simpack_grokker/step_type.pyclass:StepType/__call__ | def __call__(cls, step_function):
"""
Create a step function.
Only necessary for step functions that don't have a valid name
identifier (like "step") in their name.
Usually used as a decorator.
"""
step_function._BaseStepType__step_type = cls
return step_function
|
aeidon | aeidon//position.pyfile:/position.py:function:as_frame/as_frame | def as_frame(pos):
"""Return `pos` as type frame."""
return int(pos)
|
bpy | bpy//ops/view3d.pyfile:/ops/view3d.py:function:walk/walk | def walk():
"""Interactively walk around the scene
"""
pass
|
openpyxl-3.0.3 | openpyxl-3.0.3//openpyxl/formula/translate.pyclass:Translator/strip_ws_name | @staticmethod
def strip_ws_name(range_str):
"""Splits out the worksheet reference, if any, from a range reference."""
if '!' in range_str:
sheet, range_str = range_str.rsplit('!', 1)
return sheet + '!', range_str
return '', range_str
|
quimb | quimb//tensor/tensor_core.pyfile:/tensor/tensor_core.py:function:set_tensor_linop_backend/set_tensor_linop_backend | def set_tensor_linop_backend(backend):
"""Set the default backend used for tensor network linear operators, via
'opt_einsum'. This is different from the default contraction backend as
the contractions are likely repeatedly called many times.
See Also
--------
get_tensor_linop_backend, set_contract_backend, get_contract_backend,
TNLinearOperator
"""
global _TENSOR_LINOP_BACKEND
_TENSOR_LINOP_BACKEND = backend
|
pdf417gen | pdf417gen//rendering.pyfile:/rendering.py:function:modules/modules | def modules(codes):
"""Iterates over codes and yields barcode moudles as (y, x) tuples."""
for row_id, row in enumerate(codes):
col_id = 0
for value in row:
for digit in format(value, 'b'):
if digit == '1':
yield col_id, row_id
col_id += 1
|
opengrid-0.5.10 | opengrid-0.5.10//opengrid/library/regression.pyclass:MultiVarLinReg/find_best_rsquared | @staticmethod
def find_best_rsquared(list_of_fits):
"""Return the best fit, based on rsquared"""
res = sorted(list_of_fits, key=lambda x: x.rsquared)
return res[-1]
|
snappy | snappy//snap/fundamental_polyhedron.pyfile:/snap/fundamental_polyhedron.py:function:_diff_to_snappea/_diff_to_snappea | def _diff_to_snappea(value, snappeaValue):
"""
The SnapPea kernel will always give us a number, but we might deal
with a number or an interval.
Cast to our numeric type so that we can compare.
"""
NumericField = value.parent()
return value - NumericField(snappeaValue)
|
fake-bpy-module-2.80-20200428 | fake-bpy-module-2.80-20200428//bpy/ops/sound.pyfile:/bpy/ops/sound.py:function:update_animation_flags/update_animation_flags | def update_animation_flags():
"""Update animation flags
"""
pass
|
spotdl-1.2.6 | spotdl-1.2.6//spotdl/internals.pyfile:/spotdl/internals.py:function:extract_spotify_id/extract_spotify_id | def extract_spotify_id(raw_string):
"""
Returns a Spotify ID of a playlist, album, etc. after extracting
it from a given HTTP URL or Spotify URI.
"""
if '/' in raw_string:
if raw_string.endswith('/'):
raw_string = raw_string[:-1]
to_trim = raw_string.find('?')
if not to_trim == -1:
raw_string = raw_string[:to_trim]
splits = raw_string.split('/')
else:
splits = raw_string.split(':')
spotify_id = splits[-1]
return spotify_id
|
regulations | regulations//generator/html_builder.pyclass:HTMLBuilder/human_label | @staticmethod
def human_label(node):
"""Derive a human-readable description for this node"""
return '-'.join(node['label'])
|
intek | intek//application/etl.pyfile:/application/etl.py:function:get_email_subject/get_email_subject | def get_email_subject(content):
"""
Return the subject of the HTML email taken from the title of the HTML
template.
:return: the subject of the HTML email template.
:raise AssertError: If the content of the HTML email template has not
been read, of if this HTML has no title defined.
"""
start_offset = content.find('<title>')
assert start_offset > 0, 'The HTML template has no title defined'
start_offset = content.find('>', start_offset) + 1
end_offset = content.find('</title>', start_offset)
assert end_offset > 0, 'The HTML template has no title end tag.'
return content[start_offset:end_offset]
|
pytzer | pytzer//parameters.pyfile:/parameters.py:function:psi_H_NH4_Cl_PK74/psi_H_NH4_Cl_PK74 | def psi_H_NH4_Cl_PK74(T, P):
"""c-c'-a: hydrogen ammonium chloride [PK74]."""
psi = 0.0
valid = T == 298.15
return psi, valid
|
winremote-1.1.4 | winremote-1.1.4//winremote/modules/files.pyfile:/winremote/modules/files.py:function:copy_local/copy_local | def copy_local(session, src_path, dest_path):
"""
Copy file/directory
:param session: instance of Windows, which hold session to win machine
:type session: winremote.Windows
:param src_path: source path of file/directory
:type src_path: str
:param dest_path: destination path of file/directory
:type dest_path: str
:returns: result of command, status_code, std_out, std_err
:rtype: tuple
"""
return session.run_cmd('copy /Y "%s" "%s"' % (src_path, dest_path))
|
opem-1.2 | opem-1.2//opem/Functions.pyfile:/opem/Functions.py:function:filter_alpha/filter_alpha | def filter_alpha(Input_Dict):
"""
Filter alpha parameter.
:param Input_Dict: input parameters dictionary
:type Input_Dict : dict
:return: modified dictionary
"""
try:
if Input_Dict['alpha'] > 1:
Input_Dict['alpha'] = 1
print(
'[Warning] Opem Automatically Set Alpha To Maximum Value (1) ')
elif Input_Dict['alpha'] < 0:
Input_Dict['alpha'] = 0
print(
'[Warning] Opem Automatically Set Alpha To Maximum Value (0) ')
return Input_Dict
except Exception:
return Input_Dict
|
ptdc | ptdc//support.pyfile:/support.py:function:get_retweeted_status/get_retweeted_status | def get_retweeted_status(status):
"""
Retrieve the id of the retweeted status
:param status: Tweet object
:return: status id or None
"""
try:
return status.retweeted_status.id
except AttributeError:
return None
|
mxnet-1.6.0.data | mxnet-1.6.0.data//purelib/mxnet/ndarray/gen_sparse.pyfile:/purelib/mxnet/ndarray/gen_sparse.py:function:floor/floor | def floor(data=None, out=None, name=None, **kwargs):
"""Returns element-wise floor of the input.
The floor of the scalar x is the largest integer i, such that i <= x.
Example::
floor([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-3., -2., 1., 1., 2.]
The storage type of ``floor`` output depends upon the input storage type:
- floor(default) = default
- floor(row_sparse) = row_sparse
- floor(csr) = csr
Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L837
Parameters
----------
data : NDArray
The input array.
out : NDArray, optional
The output NDArray to hold the result.
Returns
-------
out : NDArray or list of NDArrays
The output of this function.
"""
return 0,
|
vmn-scikit-image-0.17.dev0 | vmn-scikit-image-0.17.dev0//skimage/morphology/extrema.pyfile:/skimage/morphology/extrema.py:function:_set_edge_values_inplace/_set_edge_values_inplace | def _set_edge_values_inplace(image, value):
"""Set edge values along all axes to a constant value.
Parameters
----------
image : ndarray
The array to modify inplace.
value : scalar
The value to use. Should be compatible with `image`'s dtype.
Examples
--------
>>> image = np.zeros((4, 5), dtype=int)
>>> _set_edge_values_inplace(image, 1)
>>> image
array([[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]])
"""
for axis in range(image.ndim):
sl = [slice(None)] * image.ndim
sl[axis] = 0
image[tuple(sl)] = value
sl[axis] = -1
image[tuple(sl)] = value
|
LaueTools | LaueTools//LaueSimulatorGUI.pyfile:/LaueSimulatorGUI.py:function:Edit_String_SimulData/Edit_String_SimulData | def Edit_String_SimulData(data):
"""
return string object made of lines which contains laue spots properties
Called to be Edited in LaueToolsframe.control
params:
data tuple of spots properties
data =(list_twicetheta, list_chi, list_energy, list_Miller, list_posX, list_posY,
ListName, nb of(parent) grains,
calibration parameters list, total nb of grains)
"""
nb_total_grains = data[9]
lines = 'Simulation Data from LAUE Pattern Program v1.0 2009 \n'
lines += 'Total number of grains : %s\n' % int(nb_total_grains)
lines += 'spot# h k l E 2theta chi X Y\n'
nb = data[7]
if type(nb) == type(5):
nb_grains = data[7]
TWT, CHI, ENE, MIL, XX, YY = data[:6]
NAME = data[6]
calib = data[8]
for index_grain in range(nb_grains):
nb_of_simulspots = len(TWT[index_grain])
startgrain = '#G %d\t%s\t%d\n' % (index_grain, NAME[index_grain
], nb_of_simulspots)
lines += startgrain
for data_index in range(nb_of_simulspots):
linedata = '%d\t%d\t%d\t%d\t%.5f\t%.4f\t%.4f\t%.4f\t%.4f\n' % (
data_index, MIL[index_grain][data_index][0], MIL[
index_grain][data_index][1], MIL[index_grain][
data_index][2], ENE[index_grain][data_index], TWT[
index_grain][data_index], CHI[index_grain][data_index],
XX[index_grain][data_index], YY[index_grain][data_index])
lines += linedata
lines += '#calibration parameters\n'
for param in calib:
lines += '# %s\n' % param
return lines
if isinstance(nb, list):
print('nb in Edit_String_SimulData', nb)
gen_i = 0
TWT, CHI, ENE, MIL, XX, YY = data[:6]
NAME = data[6]
calib = data[8]
for grain_ind in range(len(nb)):
for tt in range(nb[grain_ind][1]):
nb_of_simulspots = len(TWT[gen_i])
startgrain = '#G %d\t%s\t%d\t%d\n' % (grain_ind, NAME[
grain_ind], tt, nb_of_simulspots)
lines += startgrain
for data_index in range(nb_of_simulspots):
linedata = (
'%d\t%d\t%d\t%d\t%.5f\t%.4f\t%.4f\t%.4f\t%.4f\n' %
(data_index, MIL[gen_i][data_index][0], MIL[gen_i][
data_index][1], MIL[gen_i][data_index][2], ENE[
gen_i][data_index], TWT[gen_i][data_index], CHI[
gen_i][data_index], XX[gen_i][data_index], YY[gen_i
][data_index]))
lines += linedata
gen_i += 1
lines += '#calibration parameters\n'
for param in calib:
lines += '# %s\n' % param
return lines
|
sylib | sylib//calculator/plugins.pyclass:ICalcPlugin/gui_dict | @staticmethod
def gui_dict():
"""
Return a dictionary with functions that will be shown in the
configuration gui for the calculator node.
Each dictionary in the globals_dict represents another level of
subcategories in the tree view. The keys of the dict is used as labels
for the subcategories. A list represents a list of functions.
Each function in the list should be a tuple of three elements: label,
code, tooltip/documentation.
For example:
{'My functions': [
('My function 1', 'myplugin.func1()',
"My function 1 is awesome..."),
('My function 2', 'myplugin.func2()',
"My function 1 is also awesome...")]}
This should result in a top level category called "My functions"
containing the two functions "My function 1" and "My function 2".
"""
return {}
|
pystrometry-0.0.dev75 | pystrometry-0.0.dev75//astropy_helpers/astropy_helpers/utils.pyfile:/astropy_helpers/astropy_helpers/utils.py:function:resolve_name/resolve_name | def resolve_name(name):
"""Resolve a name like ``module.object`` to an object and return it.
Raise `ImportError` if the module or name is not found.
"""
parts = name.split('.')
cursor = len(parts) - 1
module_name = parts[:cursor]
attr_name = parts[-1]
while cursor > 0:
try:
ret = __import__('.'.join(module_name), fromlist=[attr_name])
break
except ImportError:
if cursor == 0:
raise
cursor -= 1
module_name = parts[:cursor]
attr_name = parts[cursor]
ret = ''
for part in parts[cursor:]:
try:
ret = getattr(ret, part)
except AttributeError:
raise ImportError(name)
return ret
|
tpb | tpb//utils.pyclass:Segments/_segment | @classmethod
def _segment(cls, segment):
"""
Returns a property capable of setting and getting a segment.
"""
return property(fget=lambda x: cls._get_segment(x, segment), fset=lambda
x, v: cls._set_segment(x, segment, v))
|
django | django//contrib/admin/templatetags/admin_list.pyfile:/contrib/admin/templatetags/admin_list.py:function:_coerce_field_name/_coerce_field_name | def _coerce_field_name(field_name, field_index):
"""
Coerce a field_name (which may be a callable) to a string.
"""
if callable(field_name):
if field_name.__name__ == '<lambda>':
return 'lambda' + str(field_index)
else:
return field_name.__name__
return field_name
|
pytzer | pytzer//parameters.pyfile:/parameters.py:function:psi_H_Na_CO3_HMW84/psi_H_Na_CO3_HMW84 | def psi_H_Na_CO3_HMW84(T, P):
"""c-c'-a: hydrogen sodium carbonate [HMW84]."""
psi = 0.0
valid = T == 298.15
return psi, valid
|
palettable | palettable//utils.pyfile:/utils.py:function:split_name_length/split_name_length | def split_name_length(name):
"""Split name and length from a name like CubeYF_8"""
split = name.split('_')
return split[0], int(split[1])
|
handi-0.10.4.1 | handi-0.10.4.1//versioneer.pyfile:/versioneer.py:function:plus_or_dot/plus_or_dot | def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if '+' in pieces.get('closest-tag', ''):
return '.'
return '+'
|
suitcase-utils-0.5.3 | suitcase-utils-0.5.3//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
|
TracWatchlistPlugin-3.0.0 | TracWatchlistPlugin-3.0.0//tracwatchlist/util.pyfile:/tracwatchlist/util.py:function:ensure_iter/ensure_iter | def ensure_iter(var):
"""Ensures that variable is iterable. If it's not by itself, return it
as an element of a tuple"""
if getattr(var, '__iter__', False):
return var
return var,
|
trollimage-1.12.0 | trollimage-1.12.0//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
|
_pytest | _pytest//hookspec.pyfile:/hookspec.py:function:pytest_report_header/pytest_report_header | def pytest_report_header(config, startdir):
""" return a string or list of strings to be displayed as header info for terminal reporting.
:param _pytest.config.Config config: pytest config object
:param startdir: py.path object with the starting dir
.. note::
This function should be implemented only in plugins or ``conftest.py``
files situated at the tests root directory due to how pytest
:ref:`discovers plugins during startup <pluginorder>`.
"""
|
aiida-core-1.2.1 | aiida-core-1.2.1//aiida/cmdline/commands/cmd_computer.pyfile:/aiida/cmdline/commands/cmd_computer.py:function:_computer_get_remote_username/_computer_get_remote_username | def _computer_get_remote_username(transport, scheduler, authinfo):
"""Internal test to check if it is possible to determine the username on the remote.
:param transport: an open transport
:param scheduler: the corresponding scheduler class
:param authinfo: the AuthInfo object
:return: tuple of boolean indicating success or failure and an optional string message
"""
remote_user = transport.whoami()
return True, remote_user
|
appenlight | appenlight//validators.pyfile:/validators.py:function:rewrite_type/rewrite_type | def rewrite_type(input_data):
"""
Fix for legacy appenlight clients
"""
if input_data == 'remote_call':
return 'remote'
return input_data
|