text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_file_language(filename, text=None):
"""Get file language from filename"""
ext = osp.splitext(filename)[1]
if ext.startswith('.'):
ext = ext[1:] # file extension with leading dot
language = ext
if not ext:
if text is None:
text, _enc = encoding.read(filenam... | 0.007825 |
def transform(self, X, y=None, sample_weight=None):
'''
Transforms the time series data with linear direct value interpolation
If y is a time series and passed, it will be transformed as well
The time dimension is removed from the data
Parameters
----------
X : a... | 0.003252 |
def filter_errors(errors, select=None, ignore=None, **params):
"""Filter errors by select and ignore options.
:return bool:
"""
select = select or []
ignore = ignore or []
for e in errors:
for s in select:
if e.number.startswith(s):
yield e
... | 0.002088 |
def set(self, x, y):
"""Set a pixel of the :class:`Canvas` object.
:param x: x coordinate of the pixel
:param y: y coordinate of the pixel
"""
x = normalize(x)
y = normalize(y)
col, row = get_pos(x, y)
if type(self.chars[row][col]) != int:
re... | 0.005249 |
def find_bookmark_file ():
"""Return the bookmark file of the Opera profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found.
"""
try:
dirname = get_profile_dir()
if os.path.isdir(dirname):
for name in OperaBookmarkFiles:
... | 0.004124 |
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]:
"""Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messa... | 0.001809 |
def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True,
username=None, password=None, **kwargs):
"""Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of t... | 0.003747 |
def lp(**kwargs):
"""
Create parameters for a new line profile dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.... | 0.004785 |
def rotation_at_time(t, timestamps, rotation_sequence):
"""Get the gyro rotation at time t using SLERP.
Parameters
-----------
t : float
The query timestamp.
timestamps : array_like float
List of all timestamps
rotation_sequence : ... | 0.006757 |
def _instructions_changed(self, change):
"""Call when there is a change in the instructions."""
if change.adds():
for index, instruction in change.items():
if isinstance(instruction, dict):
in_row = self._parser.instruction_in_row(self, instruction)
... | 0.004515 |
def DeserializeTX(buffer):
"""
Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction:
"""
mstream = MemoryStream(buffer)
reader = BinaryReade... | 0.005013 |
def shift(self, top=None, right=None, bottom=None, left=None):
"""
Shift the bounding box from one or more image sides, i.e. move it on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift the bounding box from the top.
... | 0.003448 |
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
... | 0.004866 |
def ask(self, number=None, xmean=None, sigma_fac=1,
gradf=None, args=()):
"""get new candidate solutions, sampled from a multi-variate
normal distribution and transformed to f-representation
(phenotype) to be evaluated.
Arguments
---------
`number`
... | 0.002797 |
def validate_repo_url(self, repo: str):
""" Validates repo URL - if it's a valid git URL and if Arca can handle that type of repo URL
:raise ValueError: If the URL is not valid
"""
# that should match valid git repos
if not isinstance(repo, str) or not re.match(r"^(https?|file):... | 0.011312 |
def on_message(self, ws, reply, *args):
""" This method is called by the websocket connection on every
message that is received. If we receive a ``notice``, we
hand over post-processing and signalling of events to
``process_notice``.
"""
log.debug("Received me... | 0.002405 |
def get_likes(self, likable_type, likable_id):
"""
likable_type: 'Comment', 'Press', 'Review', 'StartupRole', 'StatusUpdate'
likable_id: id of the object that the likes of it you are interested
"""
return _get_request(_LIKES.format(c_api=_C_API_BEGINNING,
... | 0.009398 |
def lookup_class(fully_qualified_name):
"""
Given its fully qualified name, finds the desired class and imports it.
Returns the Class object if found.
"""
module_name, class_name = str(fully_qualified_name).rsplit(".", 1)
module = __import__(module_name, globals(), locals(), [class_name], 0)
... | 0.001976 |
def Network_setCacheDisabled(self, cacheDisabled):
"""
Function path: Network.setCacheDisabled
Domain: Network
Method name: setCacheDisabled
Parameters:
Required arguments:
'cacheDisabled' (type: boolean) -> Cache disabled state.
No return value.
Description: Toggles ignoring cache for... | 0.043348 |
def get_child_value(parent, name, allow_missing=0):
""" return the value of the child element with name in the parent Element """
if not parent.hasElement(name):
if allow_missing:
return np.nan
else:
raise Exception('failed to find child element %s... | 0.009615 |
def evaluate(dataloader):
"""Evaluate network on the specified dataset"""
total_L = 0.0
total_sample_num = 0
total_correct_num = 0
start_log_interval_time = time.time()
print('Begin Testing...')
for i, ((data, valid_length), label) in enumerate(dataloader):
data = mx.nd.transpose(dat... | 0.000922 |
def explain_tabular(self, trainset, labels, instance, num_features=5, kernel_width=3):
"""Explain categorical and numeric features for a prediction.
It analyze the prediction by LIME, and returns a report of the most impactful tabular
features contributing to certain labels.
Args:
... | 0.005128 |
def frombits(cls, bits='0'):
"""Create a set from binary string."""
if len(bits) > cls._len:
raise ValueError('too many bits %r' % (bits,))
return cls.fromint(bits[::-1], 2) | 0.009569 |
def _req(self, path, method='get', json=True, assert_status=200, **kw):
"""Make a request to the API of an cdstar instance.
:param path: HTTP path.
:param method: HTTP method.
:param json: Flag signalling whether the response should be treated as JSON.
:param assert_status: Expe... | 0.00569 |
def _prepend_row_index(rows, index):
"""Add a left-most index column."""
if index is None or index is False:
return rows
if len(index) != len(rows):
print('index=', index)
print('rows=', rows)
raise ValueError('index must be as long as the number of data rows')
rows = [[v... | 0.002625 |
def _parse(string):
"""
Parses given XML document content.
Returns the resulting root XML element node or None if the given XML
content is empty.
@param string: XML document content to parse.
@type string: I{bytes}
@return: Resulting root XML element node or None.
@rtype: L{Element}|I{... | 0.002439 |
def get_ipv6_neighbors_table(self):
"""
Get IPv6 neighbors table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float) in seconds
* state (string)
... | 0.00154 |
def zip_and_upload(app_dir, bucket, key, session=None):
"""Zip built static site and upload to S3."""
if session:
s3_client = session.client('s3')
else:
s3_client = boto3.client('s3')
transfer = S3Transfer(s3_client)
filedes, temp_file = tempfile.mkstemp()
os.close(filedes)
... | 0.001171 |
def metadata(self, name):
"""Return value and metadata associated with the named value
Parameters
----------
name : str
name to retrieve. If the name contains '.'s it will be retrieved recursively
Raises
------
KeyError
if name is not def... | 0.004552 |
def merge(self, ds, inplace=False, axis=1):
"""Merge two datasets.
Parameters
----------
axis : {0,1}
ds : `Dataset`
inplace : bool, default False
Returns
-------
`Dataset`
"""
if not isinstance(ds, Dataset):
raise Va... | 0.001837 |
def create_endpoint(service_name: str, *,
ipv4: OptStr = None,
ipv6: OptStr = None,
port: OptInt = None) -> Endpoint:
"""Factory function to create Endpoint object.
"""
return Endpoint(service_name, ipv4, ipv6, port) | 0.003472 |
def _load_key(key_object):
"""
Common code to load public and private keys into PublicKey and PrivateKey
objects
:param key_object:
An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo
object
:raises:
ValueError - when any of the parameters contain an invalid ... | 0.001533 |
def load(js_url='', css_url='', version='5.2.0'):
"""Load Dropzone resources with given version and init dropzone configuration.
.. versionchanged:: 1.4.3
Added ``js_url`` and ``css_url`` parameters to pass custom resource URL.
.. versionchanged:: 1.4.4
This method was ... | 0.003215 |
def list_data(self):
"""
Return all the data stored in the autocomplete index. If the data was
stored as serialized JSON, then it will be de-serialized before being
returned.
:rtype: list
"""
fn = (lambda v: json.loads(decode(v))) if self._use_json else decode
... | 0.00554 |
def prune(containers=False, networks=False, images=False,
build=False, volumes=False, system=None, **filters):
'''
.. versionadded:: 2019.2.0
Prune Docker's various subsystems
.. note::
This requires docker-py version 2.1.0 or later.
containers : False
If ``True``, prune... | 0.001411 |
def is_redirecting(path):
'''Returns True if path contains a .cpenv file'''
candidate = unipath(path, '.cpenv')
return os.path.exists(candidate) and os.path.isfile(candidate) | 0.005348 |
def sign(self, payload, signing_key_or_keys):
"""
Create a JWT with one or more keys.
Returns a compact-form serialized JWT if there is only one key to sign with
Returns a JSON-structured serialized JWT if there are multiple keys to sign with
"""
if isinstance(signing_key... | 0.008264 |
def create_account(self, email_address, password=None, client_id=None, client_secret=None):
''' Create a new account.
If the account is created via an app, then Account.oauth will contain the
OAuth data that can be used to execute actions on behalf of the newly created account.
Args:
... | 0.007673 |
def load_candidate(self, filename=None, config=None):
"""
Loads a candidate configuration on the device.
In case the load fails at any point, will automatically rollback to last working configuration.
:param filename: Specifies the name of the file with the configuration content.
... | 0.006452 |
def load_params_from_file(self, fname: str, allow_missing_params: bool = False):
"""
Loads parameters from a file and sets the parameters of the underlying module and this model instance.
:param fname: File name to load parameters from.
:param allow_missing_params: If set, the given par... | 0.009146 |
async def send_message(
self,
message: Message,
sender: str = None,
recipients: RecipientsType = None,
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
r"""
S... | 0.002665 |
def highlight_block(self, text, block):
"""
Highlights the block using a pygments lexer.
:param text: text of the block to highlith
:param block: block to highlight
"""
if self.color_scheme.name != self._pygments_style:
self._pygments_style = self.color_schem... | 0.000926 |
def get_tileset_from_gid(self, gid):
""" Return tileset that owns the gid
Note: this is a slow operation, so if you are expecting to do this
often, it would be worthwhile to cache the results of this.
:param gid: gid of tile image
:rtype: TiledTileset if found, otherwise ... | 0.002954 |
def invalidate_value(
cls,
value: Any,
exc: Type[Exception]=EncodingTypeError,
msg: Optional[str]=None,
) -> None:
"""
Throws a standard exception for when a value is not encodable by an
encoder.
"""
raise exc(
"Value `{rep}` of typ... | 0.014572 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
opt = "db_url"
... | 0.002517 |
def _get_valid_endpoint(resp, name, entry_type):
"""
Parse the service catalog returned by the Identity API for an endpoint matching
the Nova service with the requested version
Sends a CRITICAL service check when no viable candidates are found in the Catalog
"""
catalog =... | 0.004363 |
def function_selector(method_name_and_signature):
"""
Makes a function hash id from a method signature
"""
s = sha3.keccak_256()
s.update(method_name_and_signature.encode())
return bytes(s.digest()[:4]) | 0.008 |
def rebuild(self, image):
"""
Rebuild the droplet with the specified image
A rebuild action functions just like a new create. [APIDocs]_
:param image: an image ID, an image slug, or an `Image` object
representing the image the droplet should use as a base
:type ... | 0.002972 |
def appliance_device_snmp_v1_trap_destinations(self):
"""
Gets the ApplianceDeviceSNMPv1TrapDestinations API client.
Returns:
ApplianceDeviceSNMPv1TrapDestinations:
"""
if not self.__appliance_device_snmp_v1_trap_destinations:
self.__appliance_device_snmp... | 0.006452 |
def get_model_list(class_list):
"""
Receives a list of strings with app_name.model_name format
and turns them into classes. If an item is already a class
it ignores it.
"""
for idx, item in enumerate(class_list):
if isinstance(item, six.string_types):
model_class = apps.get_m... | 0.002688 |
def pretty_date(the_datetime):
"""Attempt to return a human-readable time delta string."""
# Source modified from
# http://stackoverflow.com/a/5164027/176978
diff = datetime.utcnow() - the_datetime
if diff.days > 7 or diff.days < 0:
return the_datetime.strftime('%A %B %d, %Y')
elif diff.... | 0.001157 |
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(ke... | 0.002985 |
def get_object(self, resource_url):
"""Get remote resource information. Creates a local directory for the
resource if this is the first access to the resource. Downloads the
resource Json representation and writes it into a .json file in the
cache directory.
Raises ValueError if... | 0.00153 |
def _clamp_value(value, minimum, maximum):
"""
Clamp a value to fit between a minimum and a maximum.
* If ``value`` is between ``minimum`` and ``maximum``, return ``value``
* If ``value`` is below ``minimum``, return ``minimum``
* If ``value is above ``maximum``, return ``maximum``
Args:
... | 0.001066 |
def mime_type(self, category=None):
"""
:param category: application|audio|image|message|model|multipart|text|video
"""
category = category if category else self.random_element(
list(self.mime_types.keys()))
return self.random_element(self.mime_types[category]) | 0.009585 |
def search(self, buf):
"""Search the provided buffer for matching text.
Search the provided buffer for matching text. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`Sequenc... | 0.002941 |
def __update_stats(self, server):
"""
Update stats for the given server (picked from the server list)
"""
# Get the server URI
uri = self.__get_uri(server)
# Try to connect to the server
t = GlancesClientTransport()
t.set_timeout(3)
# Get common ... | 0.001873 |
def get():
"""Subarray list.
This method will list all sub-arrays known to SDP.
"""
_url = get_root_url()
LOG.debug('GET Sub array list')
sub_array_ids = sorted(DB.get_sub_array_ids())
response = dict(sub_arrays=[])
for array_id in sub_array_ids:
array_summary = dict(sub_arrar... | 0.001244 |
def getATSTemplateMgtURL(self, CorpNum, UserID):
"""
์๋ฆผํก ํ
ํ๋ฆฟ๊ด๋ฆฌ ํ์
URL
:param CorpNum: ํ๋นํ์ ์ฌ์
์๋ฒํธ
:param UserID: ํ๋นํ์ ์์ด๋
:return: ํ๋น URL
"""
result = self._httpget('/KakaoTalk/?TG=TEMPLATE', CorpNum, UserID)
return result.url | 0.00692 |
def get_planes(im, squeeze=True):
r"""
Extracts three planar images from the volumetric image, one for each
principle axis. The planes are taken from the middle of the domain.
Parameters
----------
im : ND-array
The volumetric image from which the 3 planar images are to be obtained
... | 0.000979 |
def bench(client, n):
""" Benchmark n requests """
items = list(range(n))
# Time client publish operations
# ------------------------------
started = time.time()
for i in items:
client.publish('test', i)
duration = time.time() - started
print('Publisher client stats:')
util... | 0.002899 |
def get_head_node_ip(config_file, override_cluster_name):
"""Returns head node IP for given configuration file if exists."""
config = yaml.load(open(config_file).read())
if override_cluster_name is not None:
config["cluster_name"] = override_cluster_name
provider = get_node_provider(config["pr... | 0.001397 |
def reshuffle_batches(self, indices, rng):
"""
Permutes global batches
:param indices: torch.tensor with batch indices
:param rng: instance of torch.Generator
"""
indices = indices.view(-1, self.global_batch_size)
num_batches = indices.shape[0]
order = to... | 0.004405 |
def get_files_to_check(self):
"""Generate files and error codes to check on each one.
Walk dir trees under `self._arguments` and yield file names
that `match` under each directory that `match_dir`.
The method locates the configuration for each file name and yields a
tuple of (fi... | 0.000998 |
def has_space(self, length=1, offset=0):
"""Returns boolean if self.pos + length < working string length."""
return self.pos + (length + offset) - 1 < self.length | 0.011236 |
def _get_main_language():
"""
returns the main language
:return:
"""
try:
main_language = TransLanguage.objects.filter(main_language=True).get()
return main_language.code
except TransLanguage.DoesNotExist:
return 'es' | 0.009967 |
def get_mr_filters(data_shape, opt='', coarse=False): # pragma: no cover
"""Get mr_transform filters
This method obtains wavelet filters by calling mr_transform
Parameters
----------
data_shape : tuple
2D data shape
opt : list, optional
List of additonal mr_transform options
... | 0.001121 |
def call_somatic(tumor_name, normal_name):
"""Call SOMATIC variants from tumor/normal calls, adding REJECT filters and SOMATIC flag.
Works from stdin and writes to stdout, finding positions of tumor and normal samples.
Uses MuTect like somatic filter based on implementation in speedseq:
https://github... | 0.005908 |
def search_string_filter(i):
"""
Input: {
repo_uoa - repo UOA
module_uoa - module UOA
data_uoa - data UOA
path - path
(search_string) - search with expressions *?
}
O... | 0.034597 |
def get_route_io_data_types(self):
# type: () -> typing.List[UserDefined]
"""
Returns a list of all user-defined data types that are referenced as
either an argument, result, or error of a route. If a List or Nullable
data type is referenced, then the contained data type is retur... | 0.004983 |
def get_ast_obj(belstr, bel_version, component_type: str = ""):
"""Convert AST partialparse dict to BELAst"""
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_specification.get_specification(bel_version)
subj = ast_dict["subject"]
subj_ast = add_ast_fn(subj, spec)
relation ... | 0.000902 |
def from_dict(values):
'''
Instantiate a BlockadeConfig instance based on
a given dictionary of configuration values
'''
try:
containers = values['containers']
parsed_containers = {}
for name, container_dict in containers.items():
... | 0.002726 |
def get_router_for_floatingip(self, context, internal_port,
internal_subnet, external_network_id):
"""We need to over-load this function so that we only return the
user visible router and never its redundancy routers (as they never
have floatingips associated wi... | 0.00137 |
def set_parallel_value_for_key(self, key, value):
"""
Set a globally available key and value that can be accessed
from all the pabot processes.
"""
if self._remotelib:
self._remotelib.run_keyword('set_parallel_value_for_key',
[k... | 0.004808 |
def __initialize_ui(self):
"""
Initializes the View ui.
"""
self.viewport().installEventFilter(ReadOnlyFilter(self))
if issubclass(type(self), QListView):
super(type(self), self).setUniformItemSizes(True)
elif issubclass(type(self), QTreeView):
s... | 0.00542 |
def get_connection_params(self):
"""
Default method to acquire database connection parameters.
Sets connection parameters to match settings.py, and sets
default values to blank fields.
"""
valid_settings = {
'NAME': 'name',
'HOST': 'host',
... | 0.001686 |
def messaging(self):
"""
Access the Messaging Twilio Domain
:returns: Messaging Twilio Domain
:rtype: twilio.rest.messaging.Messaging
"""
if self._messaging is None:
from twilio.rest.messaging import Messaging
self._messaging = Messaging(self)
... | 0.005764 |
def _login(session):
"""Login."""
_LOGGER.info("logging in (no valid cookie found)")
session.cookies.clear()
resp = session.post(SSO_URL, {
'USER': session.auth.username,
'PASSWORD': session.auth.password,
'TARGET': TARGET_URL
})
parsed = BeautifulSoup(resp.text, HTML_PAR... | 0.001471 |
def get_device_offset(self):
"""Returns the previous device offset set by :meth:`set_device_offset`.
:returns: ``(x_offset, y_offset)``
"""
offsets = ffi.new('double[2]')
cairo.cairo_surface_get_device_offset(
self._pointer, offsets + 0, offsets + 1)
return ... | 0.005988 |
def destinations(self, cluster='main'):
"""Return a list of destinations for a cluster."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
destinations = self.config.get(cluster, 'd... | 0.005141 |
def print_summary(graph, tails, node_id_map):
"""Print out summary and per-node comparison data."""
# Get comparison data
heads = get_heads(tails)
heights = get_heights(tails)
max_height = max(heights)
common_height, block_ids_at_common_height = get_common_height(tails)
lags = get_lags(heigh... | 0.000578 |
def list_view_row_clicked(self, list_view, path, view_column):
"""
Function opens the firefox window with relevant link
"""
model = list_view.get_model()
text = model[path][0]
match = URL_FINDER.search(text)
if match is not None:
url = match.group(1)
... | 0.005236 |
def bubble_sizes_ref(self, series):
"""
The Excel worksheet reference to the range containing the bubble
sizes for *series* (not including the column heading cell).
"""
top_row = self.series_table_row_offset(series) + 2
bottom_row = top_row + len(series) - 1
retur... | 0.005464 |
def unregister_service(self, name):
"""
Implementation of :meth:`twitcher.api.IRegistry.unregister_service`.
"""
try:
self.store.delete_service(name=name)
except Exception:
LOGGER.exception('unregister failed')
return False
else:
... | 0.005935 |
def get_child_account(self, account_name):
"""
Retrieves a child account.
This could be a descendant nested at any level.
:param account_name: The name of the account to retrieve.
:returns: The child account, if found, else None.
"""
if r'/' in account_name:
... | 0.003273 |
def add_local_node(self, child_node, name=None):
"""Append a child that should alter the locals of this scope node.
:param child_node: The child node that will alter locals.
:type child_node: NodeNG
:param name: The name of the local that will be altered by
the given child ... | 0.005137 |
def pfunc_multi(self, strands, permutation=None, temp=37.0, pseudo=False,
material=None, dangles='some', sodium=1.0, magnesium=0.0):
'''Compute the partition function for an ordered complex of strands.
Runs the \'pfunc\' command.
:param strands: List of strands to use as inp... | 0.001058 |
def command(func):
"""Command line interface decorator.
Decorate a function for building a Bowtie
application and turn it into a command line interface.
"""
# pylint: disable=protected-access,unused-variable
nargs = numargs(func)
if nargs > 0:
raise WrongNumberOfArguments(
... | 0.00113 |
def _simulate(self, nreps, admix=None, Ns=500000, gen=20):
"""
Enter a baba.Tree object in which the 'tree' attribute (newick
derived tree) has edge lengths in units of generations. You can
use the 'gen' parameter to multiply branch lengths by a constant.
Parameters:
-----------
nreps: ... | 0.011455 |
def setOutputNode(self, node):
"""
Sets the node that will be generating the output information for \
this connection.
:param node | <XNode>
"""
# if the output node matches the current, ignore
if node == self._outputNode:
return
... | 0.004975 |
def process(self, data):
"""Process the results from episode processing.
:param list data: result instances
"""
fields = []
for res in data:
for epname, out in six.iteritems(res.status):
fields.append(
[out.get('state'),
... | 0.004065 |
def more_like_this(self, model_instance, additional_query=None,
start_offset=0, end_offset=None,
limit_to_registered_models=True, result_class=None, **kwargs):
"""
Given a model instance, returns a result set of similar documents.
Required arguments... | 0.004045 |
def get_locations():
'''
Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``... | 0.000869 |
def register_signals(self):
"""Register signals."""
from .receivers import OAIServerUpdater
# Register Record signals to update OAI informations
self.update_function = OAIServerUpdater()
records_signals.before_record_insert.connect(self.update_function,
... | 0.003317 |
def _affine_inv_mult(c, m):
"Applies the inverse affine transform described in `m` to `c`."
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
a = torch.inverse(m[:2,:2].t())
c.flow = torch.mm(c.flow - m[:2,2], a).view(size)
return c | 0.022801 |
def persist(self):
"""
Banana banana
"""
if self.app.dry:
return
for proj in self.subprojects.values():
proj.persist() | 0.01087 |
def default_validity_start():
"""
Sets validity_start field to 1 day before the current date
(avoids "certificate not valid yet" edge case).
In some cases, because of timezone differences, when certificates
were just created they were considered valid in a timezone (eg: Europe)
but not yet vali... | 0.001616 |
def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
'Cannot... | 0.001929 |
def get_last_update_of_model(self, model, **kwargs):
"""
Return the last time a given model's items were updated. Returns the
epoch if the items were never updated.
"""
qs = self.get_for_model(model)
if kwargs:
qs = qs.filter(**kwargs)
try:
... | 0.004474 |
def _add_baseline_to_exclude_files(args):
"""
Modifies args.exclude_files in-place.
"""
baseline_name_regex = r'^{}$'.format(args.import_filename[0])
if not args.exclude_files:
args.exclude_files = baseline_name_regex
elif baseline_name_regex not in args.exclude_files:
args.excl... | 0.002725 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.