text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def from_apps(cls, apps):
"Takes in an Apps and returns a VersionedProjectState matching it"
app_models = {}
for model in apps.get_models(include_swapped=True):
model_state = VersionedModelState.from_model(model)
app_models[(model_state.app_label, model_state.name.lower()... | 0.008174 |
def construct_all(templates, **unbound_var_values):
"""Constructs all the given templates in a single pass without redundancy.
This is useful when the templates have a common substructure and you want the
smallest possible graph.
Args:
templates: A sequence of templates.
**unbound_var_values: The unbo... | 0.012212 |
def delete_folder(self, folder):
'''Delete a folder. It will recursively delete all the content.
Args:
folder_id (str): The UUID of the folder to be deleted.
Returns:
None
Raises:
StorageArgumentException: Invalid arguments
StorageForbid... | 0.002853 |
def _node_rating_count(self):
"""
Return node_rating_count record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.rating_count
"""
try:
return self.noderatingcount
except ObjectDoesNotExist:
node_rating_count = NodeRatingCount(node=self)
... | 0.002604 |
def gpu_a_trous():
"""
Simple convenience function so that the a trous kernels can be easily accessed by any function.
"""
ker1 = SourceModule("""
__global__ void gpu_a_trous_row_kernel(float *in1, float *in2, float *wfil, int *scale)
{
... | 0.004394 |
def _node_filter(self, node, ancestors, filtrates):
'''_node_filter
Low-level api: Remove unrelated nodes in config. This is a recursive
method.
Parameters
----------
node : `Element`
A node to be processed.
ancestors : `list`
A list of... | 0.001262 |
async def set_key_metadata(wallet_handle: int,
verkey: str,
metadata: str) -> None:
"""
Creates keys pair and stores in the wallet.
:param wallet_handle: Wallet handle (created by open_wallet).
:param verkey: the key (verkey, key id) to store metada... | 0.001693 |
def add_subscriber(self, connection_id, subscriptions,
last_known_block_id):
"""Register the subscriber for the given event subscriptions.
Raises:
InvalidFilterError
One of the filters in the subscriptions is invalid.
"""
with self._sub... | 0.005172 |
def set_file_to_upload(self, file_to_upload):
# type: (str) -> None
"""Delete any existing url and set the file uploaded to the local path provided
Args:
file_to_upload (str): Local path to file to upload
Returns:
None
"""
if 'url' in self.data:
... | 0.010076 |
def start_container(self, conf, tty=True, detach=False, is_dependency=False, no_intervention=False):
"""Start up a single container"""
# Make sure we can bind to our specified ports!
if not conf.harpoon.docker_api.base_url.startswith("http"):
self.find_bound_ports(conf.ports)
... | 0.006028 |
def indirectInitialMatrix(self, initialState):
"""
Given some initial state, this iteratively determines new states.
We repeatedly call the transition function on unvisited states in the frontier set.
Each newly visited state is put in a dictionary called 'mapping' and the rates are stor... | 0.018783 |
def checkMain():
"""
This script performs two checks. First it tries to import nupic.bindings
to check that it is correctly installed. Then it tries to import the C
extensions under nupic.bindings. Appropriate user-friendly status messages
are printed depend on the outcome.
"""
try:
checkImportBinding... | 0.011335 |
def convert_pro_to_hyp(pro):
"""Converts a pro residue to a hydroxypro residue.
All metadata associated with the original pro will be lost i.e. tags.
As a consequence, it is advisable to relabel all atoms in the structure
in order to make them contiguous.
Parameters
----------
pro: ampal.R... | 0.001113 |
def get_noise_level(cell):
""" Gets the noise level of a network / cell.
@param string cell
A network / cell from iwlist scan.
@return string
The noise level of the network.
"""
noise = matching_line(cell, "Noise level=")
if noise is None:
return ""
noise = noise.sp... | 0.002762 |
def _bisearch(ucs, table):
"""
Auxiliary function for binary search in interval table.
:arg int ucs: Ordinal value of unicode character.
:arg list table: List of starting and ending ranges of ordinal values,
in form of ``[(start, end), ...]``.
:rtype: int
:returns: 1 if ordinal value uc... | 0.001393 |
def bindings(self, entity_id, typ, service):
"""
Get me all the bindings that are registered for a service entity
:param entity_id:
:param service:
:return:
"""
return self.service(entity_id, typ, service) | 0.007634 |
def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None,
coverage_file=None, use_repeatable_ids=False):
"""Process the given HTML file stream with the css stream."""
html_doc = etree.parse(html_in)
oven = Oven(css_in, use_repeatable_ids)
oven.bake(html_doc, last_step)
... | 0.00149 |
def datetime_f(dttm):
"""Formats datetime to take less room when it is recent"""
if dttm:
dttm = dttm.isoformat()
now_iso = datetime.now().isoformat()
if now_iso[:10] == dttm[:10]:
dttm = dttm[11:]
elif now_iso[:4] == dttm[:4]:
dttm = dttm[5:]
return '... | 0.002865 |
def store_report_link(backend, user, response, *args, **kwargs):
'''
Part of the Python Social Auth Pipeline.
Stores the result service URL reported by the LMS / LTI tool consumer so that we can use it later.
'''
if backend.name is 'lti':
assignment_pk = response.get('assignment_pk', None)
... | 0.005708 |
def get_activations_stimulate(self):
"""Extract Activation INDRA Statements via stimulation."""
# TODO: extract to other patterns:
# - Stimulation by EGF activates ERK
# - Stimulation by EGF leads to ERK activation
# Search for stimulation event
stim_events = self.tree.fi... | 0.000569 |
def nub(it):
'''Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``.
'''
seen = set()
for v in it:
h = hash(v)
if h in seen:
continue
seen.add(h)
yield v | 0.003704 |
def pow(val: Any,
exponent: Any,
default: Any = RaiseTypeErrorIfNotProvided) -> Any:
"""Returns `val**factor` of the given value, if defined.
Values define an extrapolation by defining a __pow__(self, exponent) method.
Note that the method may return NotImplemented to indicate a particular
... | 0.001188 |
def detail(self, block_identifier: BlockSpecification) -> ChannelDetails:
""" Returns the channel details. """
return self.token_network.detail(
participant1=self.participant1,
participant2=self.participant2,
block_identifier=block_identifier,
channel_iden... | 0.00554 |
def get_queue_system_lock(self, queue):
"""
Get system lock timeout
Returns time system lock expires or None if lock does not exist
"""
key = self._key(LOCK_REDIS_KEY, queue)
return Semaphore.get_system_lock(self.connection, key) | 0.007168 |
def remove_neighbours(self):
"""
Remove all the pixels at max order located at the bound of the moc
"""
time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order))
intervals_arr = self._interval_set._intervals
intervals_arr[:, 0] = np.minimum(intervals_arr[:, 0] ... | 0.005291 |
def render_search(self, ctx, data):
"""
Render some UI for performing searches, if we know about a search
aggregator.
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
searchAggregator = translator.getPageComponen... | 0.00369 |
def parts(path):
# type: (Text) -> List[Text]
"""Split a path in to its component parts.
Arguments:
path (str): Path to split in to parts.
Returns:
list: List of components
Example:
>>> parts('/foo/bar/baz')
['/', 'foo', 'bar', 'baz']
"""
_path = normpath(... | 0.002037 |
def reload_module(
module: typing.Union[str, types.ModuleType],
recursive: bool,
force: bool
) -> bool:
"""
Reloads the specified module, which can either be a module object or
a string name of a module. Will not reload a module that has not been
imported
:param module:
... | 0.000657 |
def _minimal_common_integer_splitted(si_0, si_1):
"""
Calculates the minimal integer that appears in both StridedIntervals.
It's equivalent to finding an integral solution for equation `ax + b = cy + d` that makes `ax + b` minimal
si_0.stride, si_1.stride being a and c, and si_0.lower_bo... | 0.005516 |
def get_vasp_input(self, vasp_input_set=MPRelaxSet, **kwargs):
"""
Returns VASP input as a dict of vasp objects.
Args:
vasp_input_set (pymatgen.io.vaspio_set.VaspInputSet): input set
to create vasp input files from structures
"""
d = vasp_input_set(se... | 0.004484 |
def xsl_text(self, text, parent):
"""Construct an XSLT 'text' element containing `text`.
`parent` is this element's parent.
"""
res = ET.SubElement(parent, "text")
res.text = text
return res | 0.008368 |
def build(args):
"""
%prog build current.fasta Bacteria_Virus.fasta prefix
Build assembly files after a set of clean-ups:
1. Use cdhit (100%) to remove duplicate scaffolds
2. Screen against the bacteria and virus database (remove scaffolds 95% id, 50% cov)
3. Mask matches to UniVec_Core
4. ... | 0.001969 |
def update(self, new_routing_table):
""" Update the current routing table with new routing information
from a replacement table.
"""
self.routers.replace(new_routing_table.routers)
self.readers.replace(new_routing_table.readers)
self.writers.replace(new_routing_table.writ... | 0.004264 |
def _build(config_cls, dictionary, validate=False): # noqa
""" Builds an instance of ``config_cls`` using ``dictionary``.
:param type config_cls: The class to use for building
:param dict dictionary: The dictionary to use for building ``config_cls``
:param bool validate: Performs validation before bui... | 0.001255 |
def Grigoras(Tc=None, Pc=None, Vc=None):
r'''Relatively recent (1990) relationship for estimating critical
properties from each other. Two of the three properties are required.
This model uses the "critical surface", a general plot of Tc vs Pc vs Vc.
The model used 137 organic and inorganic compounds to... | 0.000459 |
def cell_thermal_mass(temperature, conductivity):
"""
Sample interval is measured in seconds.
Temperature in degrees.
CTM is calculated in S/m.
"""
alpha = 0.03 # Thermal anomaly amplitude.
beta = 1.0 / 7 # Thermal anomaly time constant (1/beta).
sample_interval = 1 / 15.0
a = 2... | 0.001835 |
def _parse_precinct_size(spcod):
"""Compute precinct size from SPcod or SPcoc."""
spcod = np.frombuffer(spcod, dtype=np.uint8)
precinct_size = []
for item in spcod:
ep2 = (item & 0xF0) >> 4
ep1 = item & 0x0F
precinct_size.append((2 ** ep1, 2 ** ep2))
return tuple(precinct_siz... | 0.003106 |
def __check_status(result, function, arguments):
"""
Check the result of a vcinpl function call and raise appropriate exception
in case of an error. Used as errcheck function when mapping C functions
with ctypes.
:param result:
Function call numeric result
:param callable fun... | 0.002433 |
def select_multi_items(self, select_name):
"""
Select multiple options from select with label (recommended), name, or
id. Pass a multiline string of options. e.g.
.. code-block:: gherkin
When I select the following from "Contact Methods":
\"\"\"
Email
Phone
... | 0.002022 |
def validate_srec_checksum(srec):
"""
Validate if the checksum of the supplied s-record is valid
Returns: True if valid, False if not
"""
checksum = srec[len(srec)-2:]
# Strip the original checksum and compare with the computed one
if compute_srec_checksum(srec[:len(srec) - 2]) == i... | 0.002577 |
def order_assets(self, asset_ids, composition_id):
"""Reorders a set of assets in a composition.
arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of
``Assets``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``comp... | 0.002551 |
def update_with(self, update_fn, *maps):
"""
Return a new PMap with the items in Mappings maps inserted. If the same key is present in multiple
maps the values will be merged using merge_fn going from left to right.
>>> from operator import add
>>> m1 = m(a=1, b=2)
>>> m... | 0.005995 |
def remove_vdir(name, site, app='/'):
'''
Remove an IIS virtual directory.
:param str name: The virtual directory name.
:param str site: The IIS site name.
:param str app: The IIS application.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-foo-vdir-... | 0.001415 |
def _adaptSynapses(self, inputVector, activeColumns, synPermActiveInc, synPermInactiveDec):
"""
The primary method in charge of learning. Adapts the permanence values of
the synapses based on the input vector, and the chosen columns after
inhibition round. Permanence values are increased for synapses co... | 0.004232 |
def _set_get_stp_brief_info(self, v, load=False):
"""
Setter method for get_stp_brief_info, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_stp_brief_info is considered as a private
method. ... | 0.005423 |
def mul_pdf(mean1, var1, mean2, var2):
"""
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the
results as a tuple (mean, var, scale_factor).
Strictly speaking the product of two Gaussian PDFs is a Gaussian
function, not Gaussian PDF. It is, however, proportional to a Gaussian
PDF.... | 0.001514 |
def defined_annotation_keywords(self) -> Set[str]:
"""Get the set of all keywords defined as annotations in this graph."""
return (
set(self.annotation_pattern) |
set(self.annotation_url) |
set(self.annotation_list)
) | 0.00722 |
def local_id(personal):
"""
Executor for `globus endpoint local-id`
"""
if personal:
try:
ep_id = LocalGlobusConnectPersonal().endpoint_id
except IOError as e:
safeprint(e, write_to_stderr=True)
click.get_current_context().exit(1)
if ep_id is ... | 0.002033 |
def _handle_system_status_event(self, event: SystemStatusEvent) -> None:
"""
DISARMED -> ARMED_AWAY -> EXIT_DELAY_START -> EXIT_DELAY_END
(trip): -> ALARM -> OUTPUT_ON -> ALARM_RESTORE
(disarm): -> DISARMED -> OUTPUT_OFF
(disarm): -> DISARMED
(disarm before EXIT_DE... | 0.001473 |
def register_master():
"""Register the SDP Master device."""
tango_db = Database()
device = "sip_sdp/elt/master"
device_info = DbDevInfo()
device_info._class = "SDPMasterDevice"
device_info.server = "sdp_master_ds/1"
device_info.name = device
devices = tango_db.get_device_name(device_inf... | 0.001842 |
def iter_generic_bases(type_):
"""Iterates over all generics `type_` derives from, including origins.
This function is only necessary because, in typing 3.5.0, a generic doesn't
get included in the list of bases when it constructs a parameterized version
of itself. This was fixed in aab2c59; now it wou... | 0.005172 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'system') and self.system is not None:
_dict['system'] = self.system._to_dict()
return _dict | 0.008333 |
def close(self):
""" Close TCP connection """
if self.device is not None:
self.device.shutdown(socket.SHUT_RDWR)
self.device.close() | 0.011628 |
def can_approve(self, user, **data):
"""
Only sys admins can approve an organisation, or a reseller sending pre_verified=true
:param user: a User
:param data: data that the user wants to update
"""
is_admin = user.is_admin()
is_reseller_preverifying = user.is_rese... | 0.009501 |
def log(args, kwargs):
"""Log to a file."""
logfile = os.path.join(args.logdir, 'log.tsv')
if 'log_created' not in globals():
if os.path.exists(logfile):
logging.error('Logfile %s already exists.', logfile)
sys.exit(1)
global log_created
log_created = sorte... | 0.001477 |
def exists(instance_id=None, name=None, tags=None, region=None, key=None,
keyid=None, profile=None, in_states=None, filters=None):
'''
Given an instance id, check to see if the given instance id exists.
Returns True if the given instance with the given id, name, or tags
exists; otherwise, Fa... | 0.002427 |
def _WebSafeComponent(c, alt=False):
'''Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value.
... | 0.012712 |
def is_armed(self):
"""Return True or False if the system is armed in any way"""
alarm_code = self.get_armed_status()
if alarm_code == YALE_STATE_ARM_FULL:
return True
if alarm_code == YALE_STATE_ARM_PARTIAL:
return True
return False | 0.006667 |
def get_outerframe_skip_importlib_frame(level):
"""
There's a bug in Python3.4+, see http://bugs.python.org/issue23773,
remove this and use sys._getframe(3) when bug is fixed
"""
if sys.version_info < (3, 4):
return sys._getframe(level)
else:
curre... | 0.004552 |
def get(self, name_or_id):
"""
Get alert by name or id
:param name_or_id: The alert's name or id
:type name_or_id: str
:return: A list of matching tags. An empty list is returned if there are
not any matches
:rtype: list of dict
:raises: This will r... | 0.004615 |
def _handle_exception(ignore_callback_errors, print_callback_errors, obj,
cb_event=None, node=None):
"""Helper for prining errors in callbacks
See EventEmitter._invoke_callback for a use example.
"""
if not hasattr(obj, '_vispy_err_registry'):
obj._vispy_err_registry = {}
... | 0.000454 |
def on_resized(self):
""" Update linked views """
d = self.declaration
if not self.is_root and d.parent.multi_axis:
if self.viewbox:
self.viewbox.setGeometry(self.widget.vb.sceneBoundingRect())
self.viewbox.linkedViewChanged(self.widget.vb,self.viewbox... | 0.012232 |
def as_dictionary(self, is_proof=True):
"""
Return the DDO as a JSON dict.
:param if is_proof: if False then do not include the 'proof' element.
:return: dict
"""
if self._created is None:
self._created = DDO._get_timestamp()
data = {
'@c... | 0.001794 |
def cli(env, identifier, path, name):
"""Adds an attachment to an existing ticket."""
mgr = SoftLayer.TicketManager(env.client)
ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
if path is None:
raise exceptions.ArgumentError("Missing argument --path")
if not os.path.e... | 0.001458 |
def register(self, kind, handler):
"""Register a handler for a given type, class, interface, or abstract base class.
View registration should happen within the `start` callback of an extension. For example, to register the
previous `json` view example:
class JSONExtension:
def start(self, context):
... | 0.033736 |
def request_ocsp(self):
"""
Called to request that the server sends stapled OCSP data, if
available. If this is not called on the client side then the server
will not send OCSP data. Should be used in conjunction with
:meth:`Context.set_ocsp_client_callback`.
"""
... | 0.004435 |
def rebuild(self):
"""
Rebuilds the widget based on the position and current size/location
of its parent.
"""
if not self.isVisible():
return
self.raise_()
max_size = self.maximumPixmapSize()
min_size = self.minimum... | 0.007463 |
def daily404summary(date, return_format=None):
"""Returns daily summary information of submitted 404 Error Page
Information.
:param date: string or datetime.date() (required)
"""
uri = 'daily404summary'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
e... | 0.002398 |
def fullscreen(self):
"""Return a context manager that enters fullscreen mode while inside it
and restores normal mode on leaving."""
self.stream.write(self.enter_fullscreen)
try:
yield
finally:
self.stream.write(self.exit_fullscreen) | 0.006711 |
def wait_for_lime(self, listen_port, listen_address="0.0.0.0",
max_tries=20, wait=1):
"""
Wait for lime to load unless max_retries is exceeded
:type listen_port: int
:param listen_port: port LiME is listening for connections on
:type listen_address: str
... | 0.003099 |
def print_report(self):
"""
Print Compare report.
:return: None
"""
report = compare_report_print(
self.sorted, self.scores, self.best_name)
print(report) | 0.009302 |
def emit(self, arg=None):
"""Emits the signal, passing the optional argument"""
for model,name in self.__get_models__():
model.notify_signal_emit(name, arg) | 0.016304 |
def do_hook_actions(self, actions, hook_type):
""" call hook actions.
Args:
actions (list): each action in actions list maybe in two format.
format1 (dict): assignment, the value returned by hook function will be assigned to variable.
{"var": "${func()}"... | 0.002845 |
def process_task_topic_list(app, doctree, fromdocname):
"""Process the ``task_topic_list`` node to generate a rendered listing of
Task, Configurable, or Config topics (as determined by the types
key of the ``task_topic_list`` node).
This is called during the "doctree-resolved" phase so that the
``l... | 0.000301 |
def cachier(stale_after=None, next_time=False, pickle_reload=True,
mongetter=None):
"""A persistent, stale-free memoization decorator.
The positional and keyword arguments to the wrapped function must be
hashable (i.e. Python's immutable built-in objects, not mutable
containers). Also, noti... | 0.000558 |
def synonym(name):
"""
Utility function mimicking the behavior of the old SA synonym function
with the new hybrid property semantics.
"""
return hybrid_property(lambda inst: getattr(inst, name),
lambda inst, value: setattr(inst, name, value),
exp... | 0.002833 |
def create_config_files(directory):
"""
Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return:
"""
# Some constant strings
config_zip_url = "https://s3-us-west-1.amazonaws.com/heartbleed/linux/linux-files.zip"
if not os.path.exists(di... | 0.001477 |
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> conf... | 0.001575 |
def find_near(lat, lon, *, n=10, session=None):
"""Return n results for a given latitude and longitude"""
search_params = {'npoints': n, 'clat': lat, 'clon': lon,
'Columns[]': ['Subregion', 'Notes', 'CollectionYear',
'ReservoirAge', 'ReservoirErr', 'C14a... | 0.007949 |
def basic_consume(self, queue='', consumer_tag='', no_local=False,
no_ack=False, exclusive=False, nowait=False,
callback=None, arguments=None, on_cancel=None):
"""Start a queue consumer
This method asks the server to start a "consumer", which is a
tra... | 0.000871 |
def find_partition_multiplex(graphs, partition_type, **kwargs):
""" Detect communities for multiplex graphs.
Each graph should be defined on the same set of vertices, only the edges may
differ for different graphs. See
:func:`Optimiser.optimise_partition_multiplex` for a more detailed
explanation.
Paramet... | 0.006877 |
def __get_stored_instances(self, factory_name):
# type: (str) -> List[StoredInstance]
"""
Retrieves the list of all stored instances objects corresponding to
the given factory name
:param factory_name: A factory name
:return: All components instantiated from the given fa... | 0.005272 |
def _create_filter_by(self):
"""Transform the json-server filter arguments to model-resource ones."""
filter_by = []
for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS:
column = _re_column_name.search... | 0.004452 |
def date(self):
"""
Return date object with same year, month and day.
:rtype: :py:class:`khayyam.JalaliDate`
"""
return khayyam.JalaliDate(self.year, self.month, self.day) | 0.009434 |
def credit_card_account_query(self, number, date):
"""CC Statement request"""
return self.authenticated_query(self._ccreq(number, date)) | 0.013158 |
def concretize(self, **kwargs):
"""
Return a concretization of the contents of the file, as a flat bytestring.
"""
size = self.state.solver.min(self._size, **kwargs)
data = self.load(0, size)
kwargs['cast_to'] = kwargs.get('cast_to', bytes)
kwargs['extra_constrai... | 0.008929 |
def from_birth_date(birth_date):
"""Take a person's birth date (datetime.date) and return a new DOB
object suitable for him."""
if birth_date > datetime.date.today():
raise ValueError('birth_date can\'t be in the future')
date_range = DateRange(birth_date, birth_date)
... | 0.00831 |
def parse_classi_or_classii_allele_name(name, infer_pair=True):
"""
Handle different forms of both single and alpha-beta allele names.
Alpha-beta alleles may look like:
DPA10105-DPB110001
HLA-DPA1*01:05-DPB1*100:01
hla-dpa1*0105-dpb1*10001
dpa1*0105-dpb1*10001
HLA-DPA1*01:05/DPB1*100:01... | 0.000808 |
async def _sasl_respond(self):
""" Respond to SASL challenge with response. """
# Formulate a response.
if self._sasl_client:
try:
response = self._sasl_client.process(self._sasl_challenge)
except puresasl.SASLError:
response = None
... | 0.003653 |
def _distribution_distance(simulated_trajectories, observed_trajectories_lookup, distribution):
"""
Returns the distance between the simulated and observed trajectory, w.r.t. the assumed distribution
:param simulated_trajectories: Simulated trajectories
:type simulated_trajectories: list[:class:`means.... | 0.005747 |
def update_json(self, fields=None):
"""Update the current entity.
Call :meth:`update_raw`. Check the response status code, decode JSON
and return the decoded JSON as a dict.
:param fields: See :meth:`update`.
:return: A dict consisting of the decoded JSON in the server's
... | 0.003096 |
def get_node_sum(self, age=None):
"""Get sum of all branches in the tree.
Returns:
int: The sum of all nodes grown until the age.
"""
if age is None:
age = self.age
return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) | 0.009524 |
def get_title(self, group=None):
"""Adds number of comments to title."""
title = super(CommentsPlugin, self).get_title()
if group is not None:
count = GroupComments.objects.filter(group=group).count()
else:
count = None
if count:
title = u'%s (... | 0.005525 |
def parse_repo_slug_from_url(github_url):
"""Get the slug, <owner>/<repo_name>, for a GitHub repository from
its URL.
Parameters
----------
github_url : `str`
URL of a GitHub repository.
Returns
-------
repo_slug : `RepoSlug`
Repository slug with fields ``full``, ``owne... | 0.00125 |
def add_splash_ids(splash_mapping_file_pth, conn, db_type='sqlite'):
""" Add splash ids to database (in case stored in a different file to the msp files like for MoNA)
Example:
>>> from msp2db.db import get_connection
>>> from msp2db.parse import add_splash_ids
>>> conn = get_connection... | 0.003978 |
def pool_function(p, nick, rutaDescarga, avoidProcessing=True, avoidDownload=True, verbosity=1):
"""
Wrapper for being able to launch all the threads of getPageWrapper.
We receive the parameters for getPageWrapper as a tuple.
Args:
-----
pName: Platform where the information is stored. It ... | 0.008929 |
def rotate_defaultbasis(self, C):
"""Rotate all parameters to the basis where the running down-type quark
and charged lepton mass matrices are diagonal and where the running
up-type quark mass matrix has the form V.S, with V unitary and S real
diagonal, and where the CKM and PMNS matrice... | 0.003604 |
def Compare(fromMo, toMo, diff):
""" Internal method to support CompareManagedObject functionality. """
from UcsBase import UcsUtils
if (fromMo.classId != toMo.classId):
return CompareStatus.TypesDifferent
for prop in UcsUtils.GetUcsPropertyMetaAttributeList(str(fromMo.classId)):
propMeta = UcsUtils.IsPropert... | 0.027027 |
def dskopn(fname, ifname, ncomch):
"""
Open a new DSK file for subsequent write operations.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskopn_c.html
:param fname: Name of a DSK file to be opened.
:type fname: str
:param ifname: Internal file name.
:type ifname: str
... | 0.008392 |
def role_show(self, role_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/roles#get-role"
api_path = "/api/v2/roles/{role_id}"
api_path = api_path.format(role_id=role_id)
return self.call(api_path, **kwargs) | 0.007843 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.