text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _create_producer(self, settings):
"""Tries to establish a Kafka consumer connection"""
try:
brokers = settings['KAFKA_HOSTS']
self.logger.debug("Creating new kafka producer using brokers: " +
str(brokers))
return KafkaProducer(boots... | 0.008256 |
def create(model_config, model, vec_env, storage, takes, parallel_envs, action_noise=None, sample_args=None):
""" Vel factory function """
return EvaluateEnvCommand(
model_config=model_config,
model_factory=model,
env_factory=vec_env,
parallel_envs=parallel_envs,
action_n... | 0.004739 |
def last(args, dbtype=None):
"""
%prog database.fasta query.fasta
Run LAST by calling LASTDB and LASTAL. LAST program available:
<http://last.cbrc.jp>
Works with LAST-719.
"""
p = OptionParser(last.__doc__)
p.add_option("--dbtype", default="nucl",
choices=("nucl", "pro... | 0.002911 |
def _decompress_nist256(pubkey):
"""
Load public key from the serialized blob.
The leading byte least-significant bit is used to decide how to recreate
the y-coordinate from the specified x-coordinate. See bitcoin/main.py#L198
(from https://github.com/vbuterin/pybitcointools/) for details.
"""
... | 0.001047 |
def get_template_names(self):
"""
Dispatch template according to the kind of request: ajax or normal.
"""
if self.request.is_ajax():
return [self.list_template_name]
else:
return super(Search, self).get_template_names() | 0.007067 |
def find_files(self):
""" Gets modules routes.py and converts to module imports """
modules = self.evernode_app.get_modules()
root_path = sys.path[0] if self.evernode_app.root_path is None \
else self.evernode_app.root_path
dirs = [dict(
dir=os.path.join(roo... | 0.00103 |
def transformations(self, relationship="all"):
"""Get all the transformations of this info.
Return a list of transformations involving this info. ``relationship``
can be "parent" (in which case only transformations where the info is
the ``info_in`` are returned), "child" (in which case ... | 0.002717 |
def copy_file(
source_path,
target_path,
allow_undo=True,
no_confirm=False,
rename_on_collision=True,
silent=False,
extra_flags=0,
hWnd=None
):
"""Perform a shell-based file copy. Copying in
this way allows the possibility of undo, auto-renaming,
and showing the "flying file"... | 0.001368 |
def first(self, cascadeFetch=False):
'''
First - Returns the oldest record (lowerst primary key) with current filters.
This makes an efficient queue, as it only fetches a single object.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetche... | 0.030457 |
def get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None):
""" A utility function to get a subset of data from a Table, Query, Pandas dataframe or List.
Args:
source: the source of the data. Can be a Table, Pandas DataFrame, List of dictionaries or
lists, or a string, in which case... | 0.012505 |
def mahalanobis_norm(self, dx):
"""compute the Mahalanobis norm that is induced by the adapted
sample distribution, covariance matrix ``C`` times ``sigma**2``,
including ``sigma_vec``. The expected Mahalanobis distance to
the sample mean is about ``sqrt(dimension)``.
Argument
... | 0.002876 |
def get_units_property(self, *, unit_ids=None, property_name):
'''Returns a list of values stored under the property name corresponding
to a list of units
Parameters
----------
unit_ids: list
The unit ids for which the property will be returned
Defaults t... | 0.005772 |
def uploadDeviceConfig(self):
"""Upload the device configuration of the fake device
selected in the __init__ methodi to the google account."""
upload = googleplay_pb2.UploadDeviceConfigRequest()
upload.deviceConfiguration.CopyFrom(self.deviceBuilder.getDeviceConfig())
headers = ... | 0.004686 |
def lookup_friendships(self, user_ids=None, screen_names=None):
""" Perform bulk look up of friendships from user ID or screenname """
return self._lookup_friendships(list_to_csv(user_ids), list_to_csv(screen_names)) | 0.012931 |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | 0.001813 |
def raise_for_missing_name(self, line: str, position: int, namespace: str, name: str) -> None:
"""Raise an exception if the namespace is not defined or if it does not validate the given name."""
self.raise_for_missing_namespace(line, position, namespace, name)
if self.has_enumerated_namespace(n... | 0.011412 |
def _updateMinDutyCyclesGlobal(self):
"""
Updates the minimum duty cycles in a global fashion. Sets the minimum duty
cycles for the overlap all columns to be a percent of the maximum in the
region, specified by minPctOverlapDutyCycle. Functionality it is equivalent
to _updateMinDutyCyclesLocal, but ... | 0.001786 |
def get_seh_chain(self):
"""
@rtype: list of tuple( int, int )
@return: List of structured exception handlers.
Each SEH is represented as a tuple of two addresses:
- Address of this SEH block
- Address of the SEH callback function
Do not c... | 0.01001 |
def remove(name, local):
'''Remove a module named NAME. Will remove the first resolved module named NAME. You can also specify a full path to a module. Use the --local option
to ensure removal of modules local to the currently active environment.'''
click.echo()
if not local: # Use resolver to find mod... | 0.002827 |
def get_strategy(name_or_cls):
"""Return the strategy identified by its name. If ``name_or_class`` is a class,
it will be simply returned.
"""
if isinstance(name_or_cls, six.string_types):
if name_or_cls not in STRATS:
raise MutationError("strat is not defined")
return STRATS... | 0.00554 |
def reqScannerData(
self, subscription: ScannerSubscription,
scannerSubscriptionOptions: List[TagValue] = None,
scannerSubscriptionFilterOptions:
List[TagValue] = None) -> ScanDataList:
"""
Do a blocking market scan by starting a subscription and canceling... | 0.00237 |
def p_with_statement(self, p):
"""with_statement : WITH LPAREN expr RPAREN statement"""
p[0] = self.asttypes.With(expr=p[3], statement=p[5])
p[0].setpos(p) | 0.011173 |
def _enhance_bass(self):
"""Update best span choices with bass enhancement as requested by user (Eq. 11)."""
if not self._bass_enhancement:
# like in supsmu, skip if alpha=0
return
bass_span = DEFAULT_SPANS[BASS_INDEX]
enhanced_spans = []
for i, best_span_... | 0.003835 |
def _fn_with_custom_grad(fn, inputs, grad_fn, use_global_vars=False):
"""Create a subgraph with a custom gradient.
Args:
fn: function that takes inputs as arguments and produces 1 or more Tensors.
inputs: list<Tensor>, will be passed as fn(*inputs).
grad_fn: function with signature
(inputs, vars,... | 0.010943 |
def _check_directory_arguments(self):
"""
Validates arguments for loading from directories, including static image and time series directories.
"""
if not os.path.isdir(self.datapath):
raise (NotADirectoryError('Directory does not exist: %s' % self.datapath))
if self.... | 0.00936 |
def Y_ampl(self, new_y_scale):
"""Make scaling on Y axis using predefined values"""
self.parent.value('y_scale', new_y_scale)
self.parent.traces.display() | 0.011236 |
def _safe_get(mapping, key, default=None):
"""Helper for accessing style values.
It exists to avoid checking whether `mapping` is indeed a mapping before
trying to get a key. In the context of style dicts, this eliminates "is
this a mapping" checks in two common situations: 1) a style argument is
... | 0.001923 |
def Nusselt_laminar(Tsat, Tw, rhog, rhol, kl, mul, Hvap, L, angle=90.):
r'''Calculates heat transfer coefficient for laminar film condensation
of a pure chemical on a flat plate, as presented in [1]_ according to an
analysis performed by Nusselt in 1916.
.. math::
h=0.943\left[\frac{g\sin(\thet... | 0.001738 |
def import_context(cls, context):
""" Import context to corresponding WContextProto object (:meth:`WContext.export_context` reverse operation)
:param context: context to import
:return: WContext
"""
if context is None or len(context) == 0:
return
result = WContext(context[0][0], context[0][1])
for it... | 0.030837 |
def _type_repr(obj):
"""Return the repr() of an object, special-casing types (internal helper).
If obj is a type, we return a shorter version than the default
type.__repr__, based on the module and qualified name, which is
typically enough to uniquely identify a type. For everything
else, we fall ... | 0.001471 |
def _create_app(self, color_depth, term='xterm'):
"""
Create CommandLineInterface for this client.
Called when the client wants to attach the UI to the server.
"""
output = Vt100_Output(_SocketStdout(self._send_packet),
lambda: self.size,
... | 0.003501 |
def update_board(self, query_params=None):
'''
Update this board's information. Returns a new board.
'''
board_json = self.fetch_json(
uri_path=self.base_uri,
http_method='PUT',
query_params=query_params or {}
)
return self.create_boar... | 0.006006 |
def ReadSignedBinaryReferences(
self, binary_id,
cursor=None):
"""Reads blob references for the signed binary with the given id."""
cursor.execute(
"""
SELECT blob_references, UNIX_TIMESTAMP(timestamp)
FROM signed_binary_references
WHERE binary_type = %s AND binary_path_has... | 0.007709 |
def MultiNotifyQueue(self, notifications, mutation_pool=None):
"""This is the same as NotifyQueue but for several session_ids at once.
Args:
notifications: A list of notifications.
mutation_pool: A MutationPool object to schedule Notifications on.
Raises:
RuntimeError: An invalid session... | 0.006711 |
def create_directory(self):
"""
Creates a directory under the selected directory (if the selected item
is a file, the parent directory is used).
"""
src = self.get_current_path()
name, status = QtWidgets.QInputDialog.getText(
self.tree_view, _('Create director... | 0.002747 |
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
... | 0.000653 |
def preview(self, argv):
"""Retrieve the preview for the specified search jobs."""
opts = cmdline(argv, FLAGS_RESULTS)
self.foreach(opts.args, lambda job:
output(job.preview(**opts.kwargs))) | 0.017621 |
def __getFormat(self, format):
"""
Defaults to JSON [ps: 'RDF' is the native rdflib representation]
"""
if format == "XML":
self.sparql.setReturnFormat(XML)
self.format = "XML"
elif format == "RDF":
self.sparql.setReturnFormat(RDF)
self.format = "RDF"
else:
self.sparql.setReturnFormat(JSON)
... | 0.040816 |
def _build_user_environment(self, envs, inputs, outputs, mounts):
"""Returns a dictionary of for the user container environment."""
envs = {env.name: env.value for env in envs}
envs.update(providers_util.get_file_environment_variables(inputs))
envs.update(providers_util.get_file_environment_variables(ou... | 0.002415 |
def add_string_pairs_from_button_element(xib_file, results, button, special_ui_components_prefix):
""" Adds strings pairs from a button xib element.
Args:
xib_file (str): Path to the xib file.
results (list): The list to add the results to.
button(element): The button element from the x... | 0.005882 |
def load_model():
"""
Load a n-gram language model for mathematics in ARPA format which gets
shipped with hwrt.
Returns
-------
A NgramLanguageModel object
"""
logging.info("Load language model...")
ngram_arpa_t = pkg_resources.resource_filename('hwrt',
... | 0.001383 |
def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(HostedGraphiteHandler, self).get_default_config()
config.update({
'apikey': '',
'host': 'carbon.hostedgraphite.com',
'port': 2003,
'prot... | 0.004016 |
def set_wrap_mode(self, mode=None):
"""
Set wrap mode
Valid *mode* values: None, 'word', 'character'
"""
if mode == 'word':
wrap_mode = QTextOption.WrapAtWordBoundaryOrAnywhere
elif mode == 'character':
wrap_mode = QTextOption.WrapAnywhere
... | 0.004773 |
def fundamental_arguments(t):
"""Compute the fundamental arguments (mean elements) of Sun and Moon.
`t` - TDB time in Julian centuries since J2000.0, as float or NumPy array
Outputs fundamental arguments, in radians:
a[0] = l (mean anomaly of the Moon)
a[1] = l' (mean anomaly of the S... | 0.002387 |
def _read_input_urls(cls, session: AppSession, default_scheme='http'):
'''Read the URLs provided by the user.'''
url_string_iter = session.args.urls or ()
# FIXME: url rewriter isn't created yet
url_rewriter = session.factory.get('URLRewriter')
if session.args.input_file:
... | 0.001471 |
def get_datarect(self):
"""Get the approximate bounding box of the displayed image.
Returns
-------
rect : tuple
Bounding box in data coordinates in the form of
``(x1, y1, x2, y2)``.
"""
x1, y1, x2, y2 = self._org_x1, self._org_y1, self._org_x2, ... | 0.005495 |
def total(self):
"""Total cost of the order
"""
total = 0
for item in self.items.all():
total += item.total
return total | 0.011628 |
def did_composer_install(dir):
'''
Test to see if the vendor directory exists in this directory
dir
Directory location of the composer.json file
CLI Example:
.. code-block:: bash
salt '*' composer.did_composer_install /var/www/application
'''
lockFile = "{0}/vendor".forma... | 0.002525 |
def write_to_file(self, path, filename, footer=True):
"""
Class method responsible for generating a file containing the notebook object data.
----------
Parameters
----------
path : str
OpenSignalsTools Root folder path (where the notebook will be stored).
... | 0.008169 |
def match_hail_sizes(model_tracks, obs_tracks, track_pairings):
"""
Given forecast and observed track pairings, maximum hail sizes are associated with each paired forecast storm
track timestep. If the duration of the forecast and observed tracks differ, then interpolation is used for the
... | 0.005231 |
def scan(self) -> ['File']:
""" Scan
Scan the directory for files and folders and update the file dictionary.
@return: List of files
"""
self._files = {}
output = self._listFilesWin() if isWindows else self._listFilesPosix()
output = [line for line in output if... | 0.004601 |
def print_ec2_info(region,
instance_id,
access_key_id,
secret_access_key,
username):
""" outputs information about our EC2 instance """
data = get_ec2_info(instance_id=instance_id,
region=region,
... | 0.001029 |
def display(level='DEBUG'):
"""display(level='DEBUG') forwards logs to stdout"""
logger = get_logger()
sh = logging.StreamHandler()
sh.setLevel(getattr(logging, level))
sh.setFormatter(DEFAULT_LOG_FORMAT)
logger.addHandler(sh) | 0.004 |
async def sendmail(
self,
sender: str,
recipients: RecipientsType,
message: Union[str, bytes],
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
"""
This comma... | 0.000662 |
def get_service_ips(
service_name,
task_name=None,
inactive=False,
completed=False
):
""" Get a set of the IPs associated with a service
:param service_name: the service name
:type service_name: str
:param task_name: the task name
:type task_name: str
... | 0.002679 |
def __parseResponse(self, result):
"""Parses the server response."""
response = []
for data in result['data'] :
result_dict={}
for k,v in data.items() :
column = self.getOutputColumn(k)
if column != None:
type = column.g... | 0.016794 |
def fill_document(self):
"""Add a section, a subsection and some text to the document."""
with self.create(Section('A section')):
self.append('Some regular text and some ')
self.append(italic('italic text. '))
with self.create(Subsection('A subsection')):
... | 0.005362 |
def getBumper(self):
'''
Returns last Bumper.
@return last JdeRobotTypes Bumper saved
'''
if self.hasproxy():
self.lock.acquire()
bumper = self.bumper
self.lock.release()
return bumper
return None | 0.010135 |
def filter(table, predicates):
"""
Select rows from table based on boolean expressions
Parameters
----------
predicates : boolean array expressions, or list thereof
Returns
-------
filtered_expr : TableExpr
"""
resolved_predicates = _resolve_predicates(table, predicates)
re... | 0.002717 |
def reset(self):
'''
Resets this agent type to prepare it for a new simulation run. This
includes resetting the random number generator and initializing the style
of each agent of this type.
'''
self.resetRNG()
sNow = np.zeros(self.pop_size)
Shk = self.R... | 0.009926 |
def _send_register_payload(self, websocket):
"""Send the register payload."""
file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME)
data = codecs.open(file, 'r', 'utf-8')
raw_handshake = data.read()
handshake = json.loads(raw_handshake)
handshake['payload'... | 0.003394 |
def op_extract(op_name, data, senders, inputs, outputs, block_id, vtxindex, txid):
"""
Extract an operation from transaction data.
Return the extracted fields as a dict.
"""
global EXTRACT_METHODS
if op_name not in EXTRACT_METHODS.keys():
raise Exception("No such operation '%s'" % op_na... | 0.010823 |
def loadRecords(self, records):
"""
Loads the inputed records as children to this item.
:param records | [<orb.Table>, ..] || {<str> sub: <variant>, .. }
"""
self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless)
self._loaded = True
... | 0.006363 |
def analyze(self, scratch, **kwargs):
"""Run and return the results of the VariableInitialization plugin."""
variables = dict((x, self.variable_state(x.scripts, x.variables))
for x in scratch.sprites)
variables['global'] = self.variable_state(self.iter_scripts(scratch),
... | 0.003891 |
def parse_wd_json(self, wd_json):
"""
Parses a WD entity json and generates the datatype objects, sets self.wd_json_representation
:param wd_json: the json of a WD entity
:type wd_json: A Python Json representation of a WD item
:return: returns the json representation containing ... | 0.005682 |
def get_mime(self, path, isdir):
'''猜测文件类型, 根据它的文件扩展名'''
if isdir:
file_type = FOLDER
else:
file_type = mimetypes.guess_type(path)[0]
if not file_type:
file_type = UNKNOWN
return file_type | 0.007353 |
def start_worker_thread(
self,
sleep_interval=1.0):
"""start_worker_thread
Start the helper worker thread to publish queued messages
to Splunk
:param sleep_interval: sleep in seconds before reading from
the queue again
"""
... | 0.002878 |
def create_post_execute(task_params, parameter_map):
"""
Builds the code block for the GPTool Execute method after the job is
submitted based on the input task_params.
:param task_params: A list of task parameters from the task info structure.
:return: A string representing the code block to the GP... | 0.002532 |
def get_phi_ss(imt, mag, params):
"""
Returns the single station phi (or it's variance) for a given magnitude
and intensity measure type according to equation 5.14 of Al Atik (2015)
"""
C = params[imt]
if mag <= 5.0:
phi = C["a"]
elif mag > 6.5:
phi = C["b"]
else:
... | 0.002564 |
def jaccard_similarity(self,s1,s2):
"""
Calculate jaccard index of inferred associations of two subjects
|ancs(s1) /\ ancs(s2)|
---
|ancs(s1) \/ ancs(s2)|
"""
a1 = self.inferred_types(s1)
a2 = self.inferred_types(s2)
num_union = len(a1.union(a2))... | 0.014218 |
def shutdown(self):
"""Shutdown the accept loop and stop running payloads"""
self._must_shutdown = True
self._is_shutdown.wait()
self._meta_runner.stop() | 0.010811 |
def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True):
"""Remove from target annotations which inherit from cls.
:param target: target from where remove annotations which inherits from
cls.
:param tuple/type exclude: annotation types to exclude from selection.
... | 0.001298 |
def get(self, key, lang=None):
""" Returns triple related to this node. Can filter on lang
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if lang is not None:
for o in self.graph.ob... | 0.003906 |
def masked_relative_local_attention_1d(q,
k,
v,
block_length=128,
make_image_summary=False,
dropout_rate=0.,
... | 0.003403 |
def finite_pixels(self):
""" Return an array of the finite pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the finite pixels
"""
finite_px = np.where(np.isfinite(self.data))
finite_px = np.c_[finite_px[0], finite_px[1]]
return finit... | 0.006173 |
def _iterate_managers(connection, skip):
"""Iterate over instantiated managers."""
for idx, name, manager_cls in _iterate_manage_classes(skip):
if name in skip:
continue
try:
manager = manager_cls(connection=connection)
except TypeError as e:
click.se... | 0.00237 |
def iter_chunks(self, start_count=0):
"""
Iterate over the chunks of the file according to their length prefixes.
yields: index <int>, encrypted chunks without length prefixes <bytes>, lastchunk <bool>
"""
ciphertext = self.chunks_block
chunknum = start_count
idx ... | 0.005828 |
def ls(self, glob_str):
"""
Return just the filenames that match `glob_str` inside the store directory.
:param str glob_str: A glob string, i.e. 'state_*'
:return: list of matched keys
"""
path = os.path.join(self.uri, glob_str)
return [os.path.split(s)[1] for s ... | 0.00885 |
def update_app_icon(self):
"""
Update the app icon if the user is not trying to resize the window.
"""
if os.name == 'nt' or not hasattr(self, '_last_window_size'): # pragma: no cover
# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS
return
cur_time = time.... | 0.002882 |
def get_all_reserved_instances_offerings(self, reserved_instances_id=None,
instance_type=None,
availability_zone=None,
product_description=None,
... | 0.002903 |
def process_args():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser(description="A script for plotting files containing spike time data")
parser.add_argument('spiketimeFiles',
type=str,
metavar='<spiketime file>',
... | 0.013351 |
def update_state(world):
"""
Increment the world state, determining which cells live, die, or appear.
Args:
world (list[list]): A square matrix of cells
Returns: None
"""
world_size = len(world)
def wrap(index):
"""Wrap an index around the other end of the array"""
... | 0.000625 |
def login_with(cls, platform, third_party_auth_data):
'''
把第三方平台号绑定到 User 上
:param platform: 第三方平台名称 base string
'''
user = User()
return user.link_with(platform, third_party_auth_data) | 0.008547 |
def is_in_range(self, values, unit=None, raise_exception=True):
"""Check if a list of values is within physically/mathematically possible range.
Args:
values: A list of values.
unit: The unit of the values. If not specified, the default metric
unit will be assum... | 0.002059 |
def attach_intf_router(self, tenant_id, tenant_name, router_id):
"""Routine to attach the interface to the router. """
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
# Modify Hard coded Name fixme
subnet_lst = set()
subnet_lst.add(in... | 0.004237 |
def delete_directory(self, dirname):
"""Delete a directory (and contents) from the bucket.
Parameters
----------
dirname : `str`
Name of the directory, relative to ``bucket_root/``.
Raises
------
RuntimeError
Raised when there are no obje... | 0.001742 |
def fetch(force=False):
"""Fetch and extract latest Life-Line version of Fiji is just ImageJ
to *~/.bin*.
Parameters
----------
force : bool
Force overwrite of existing Fiji in *~/.bin*.
"""
try:
# python 2
from urllib2 import urlopen, HTTPError, URLError
except... | 0.001064 |
def make_generic_validator(validator: AnyCallable) -> 'ValidatorCallable':
"""
Make a generic function which calls a validator with the right arguments.
Unfortunately other approaches (eg. return a partial of a function that builds the arguments) is slow,
hence this laborious way of doing things.
... | 0.005771 |
def start_recording(self, file='mingus_dump.wav'):
"""Initialize a new wave file for recording."""
w = wave.open(file, 'wb')
w.setnchannels(2)
w.setsampwidth(2)
w.setframerate(44100)
self.wav = w | 0.00823 |
def validate(self):
"""Validate that the BinaryComposition is correctly representable."""
_validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS)
if not isinstance(self.left, Expression):
raise TypeError(u'Expected Expression left, got: {} {} {}'.format(
... | 0.005376 |
def open_dataset(self, service):
"""Opens and returns the NetCDF dataset associated with a service, or returns a previously-opened dataset"""
if not self.dataset:
path = os.path.join(SERVICE_DATA_ROOT, service.data_path)
self.dataset = netCDF4.Dataset(path, 'r')
return s... | 0.009063 |
def is_correct(self):
"""Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool
"""
state = True
# Inter... | 0.004704 |
def pos(self, element = None):
''' Tries to decide about the part of speech. '''
tags = []
if element:
if element.startswith(('de ', 'het ', 'het/de', 'de/het')) and not re.search('\[[\w|\s][\w|\s]+\]', element.split('\r\n')[0], re.U):
tags.append('NN')
if re.search('[\w|\s|/]+ \| [\w|\s|/]+ - [\w|\s|/... | 0.065767 |
def get_relationships_for_destination(self, destination_id=None):
"""Gets a ``RelationshipList`` corresponding to the given peer ``Id``.
arg: destination_id (osid.id.Id): a peer ``Id``
return: (osid.relationship.RelationshipList) - the relationships
raise: NullArgument - ``destinati... | 0.002347 |
def remove_namespace(doc, namespace):
'''Remove namespace in the passed document in place.'''
ns = u'{%s}' % namespace
nsl = len(ns)
for elem in doc.getiterator():
if elem.tag.startswith(ns):
elem.tag = elem.tag[nsl:]
elem.attrib['oxmlns'] = namespace | 0.025455 |
def main():
'''
This is called when we're executed from the commandline.
The current usage from the command-line is described below::
usage: hatlc [-h] [--describe] hatlcfile
read a HAT LC of any format and output to stdout
positional arguments:
hatlcfile path to the ... | 0.001645 |
def login(method):
"""Require user to login."""
def wrapper(*args, **kwargs):
crawler = args[0].crawler # args[0] is a NetEase object
try:
if os.path.isfile(cookie_path):
with open(cookie_path, 'r') as cookie_file:
cookie = cookie_file.read()
... | 0.001138 |
def dump_nodes(self):
"""Dump current screen UI to list
Returns:
List of UINode object, For
example:
[UINode(
bounds=Bounds(left=0, top=0, right=480, bottom=168),
checkable=False,
class_name='android.view.View',
... | 0.002611 |
def _solve_msm_eigensystem(transmat, k):
"""Find the dominant eigenpairs of an MSM transition matrix
Parameters
----------
transmat : np.ndarray, shape=(n_states, n_states)
The transition matrix
k : int
The number of eigenpairs to find.
Notes
-----
Normalize the left (:... | 0.010653 |
def random_lattice_box(mol_list, mol_number, size,
spacing=np.array([0.3, 0.3, 0.3])):
'''Make a box by placing the molecules specified in *mol_list* on
random points of an evenly spaced lattice.
Using a lattice automatically ensures that no two molecules are
overlapping.
**... | 0.007855 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.