code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def create_statement_inspection_table(sts: List[Influence]):
columns = [
"un_groundings",
"subj_polarity",
"obj_polarity",
"Sentence",
"Source API",
]
polarity_to_str = lambda x: "+" if x == 1 else "-" if x == -1 else "None"
l = []
for s in sts:
... | Display an HTML representation of a table with INDRA statements to
manually inspect for validity.
Args:
sts: A list of INDRA statements to be manually inspected for validity. | juraj-google-style |
def notify_owner(func):
def wrapper(self, *args, **kwargs):
old = self._saved_copy()
result = func(self, *args, **kwargs)
self._notify_owners(old)
return result
wrapper.__doc__ = ('Container method ``%s`` instrumented to notify property owners' % func.__name__)
return wrappe... | A decorator for mutating methods of property container classes
that notifies owners of the property container about mutating changes.
Args:
func (callable) : the container method to wrap in a notification
Returns:
wrapped method
Examples:
A ``__setitem__`` could be wrapped like this:
.. code-block:: python
# x[i]... | codesearchnet |
def write_to_file(src, dst):
n = 0
for block in src:
dst.write(block)
n += len(block)
return n | Write data from `src` into `dst`.
Args:
src (iterable): iterable that yields blocks of data to write
dst (file-like object): file-like object that must support
.write(block)
Returns:
number of bytes written to `dst` | juraj-google-style |
def get_user(self, user_id):
try:
return self._user_dict[user_id]
except KeyError:
logger.warning('UserList returning unknown User for UserID %s',
user_id)
return User(user_id, None, None, None, [], False) | Get a user by its ID.
Args:
user_id (~hangups.user.UserID): The ID of the user.
Raises:
KeyError: If no such user is known.
Returns:
:class:`~hangups.user.User` with the given ID. | juraj-google-style |
def _sign_operation(op):
md5 = hashlib.md5()
md5.update(op.consumerId.encode('utf-8'))
md5.update(b'\x00')
md5.update(op.operationName.encode('utf-8'))
if op.labels:
signing.add_dict_to_hash(md5, encoding.MessageToPyValue(op.labels))
return md5.digest() | Obtains a signature for an operation in a ReportRequest.
Args:
op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an
operation used in a `ReportRequest`
Returns:
string: a unique signature for that operation | juraj-google-style |
def handler_for_name(fq_name):
resolved_name = for_name(fq_name)
if isinstance(resolved_name, (type, types.ClassType)):
return resolved_name()
elif isinstance(resolved_name, types.MethodType):
return getattr(resolved_name.im_class(), resolved_name.__name__)
else:
return resolved_... | Resolves and instantiates handler by fully qualified name.
First resolves the name using for_name call. Then if it resolves to a class,
instantiates a class, if it resolves to a method - instantiates the class and
binds method to the instance.
Args:
fq_name: fully qualified name of something to find.
Returns:
handle... | codesearchnet |
def htmlcolor_to_rgb(str_color):
if not (str_color.startswith('
raise ValueError("Bad html color format. Expected: '
result = [1.0 * int(n, 16) / 255 for n in (str_color[1:3], str_color[3:5], str_color[5:])]
return result | function to convert HTML-styly color string to RGB values
Args:
s: Color in HTML format
Returns:
list of three RGB color components | juraj-google-style |
def trim_wav_ms(in_path: Path, out_path: Path, start_time: int, end_time: int) -> None:
try:
trim_wav_sox(in_path, out_path, start_time, end_time)
except FileNotFoundError:
trim_wav_pydub(in_path, out_path, start_time, end_time)
except subprocess.CalledProcessError:
trim_wav_pydub(in... | Extracts part of a WAV File.
First attempts to call sox. If sox is unavailable, it backs off to
pydub+ffmpeg.
Args:
in_path: A path to the source file to extract a portion of
out_path: A path describing the to-be-created WAV file.
start_time: The point in the source WAV file at which to begin
extraction.
end_time: Th... | codesearchnet |
def UnlockScanNode(self, path_spec):
if not self.HasScanNode(path_spec):
raise KeyError('Scan node does not exist.')
if path_spec not in self._locked_scan_nodes:
raise KeyError('Scan node is not locked.')
del self._locked_scan_nodes[path_spec]
self._scan_nodes[path_spec].scanned... | Marks a scan node as unlocked.
Args:
path_spec (PathSpec): path specification.
Raises:
KeyError: if the scan node does not exists or is not locked. | juraj-google-style |
def get_tensor_file_paths(self, node_name, output_slot, debug_op, device_name=None):
device_name = self._infer_device_name(device_name, node_name)
watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op)
if watch_key not in self._watch_key_to_datum[device_name]:
raise WatchKeyDoesNotExist... | Get the file paths from a debug-dumped tensor.
Args:
node_name: (`str`) name of the node that the tensor is produced by.
output_slot: (`int`) output slot index of tensor.
debug_op: (`str`) name of the debug op.
device_name: (`str`) name of the device. If there is only one device or if
the specified debug_watch_key exi... | github-repos |
def load_actor_class(self, driver_id, function_descriptor):
function_id = function_descriptor.function_id
actor_class = self._loaded_actor_classes.get(function_id, None)
if (actor_class is None):
if self._worker.load_code_from_local:
driver_id = ray.DriverID.nil()
actor_class... | Load the actor class.
Args:
driver_id: Driver ID of the actor.
function_descriptor: Function descriptor of the actor constructor.
Returns:
The actor class. | codesearchnet |
def SetFlushInterval(self, flush_interval):
self._flush_interval = flush_interval
logger.debug('Elasticsearch flush interval: {0:d}'.format(flush_interval)) | Set the flush interval.
Args:
flush_interval (int): number of events to buffer before doing a bulk
insert. | codesearchnet |
def intersection_update(self, *others):
for other in map(self._as_mapping, others):
for (element, current_count) in list(self.items()):
multiplicity = other.get(element, 0)
if (multiplicity < current_count):
self[element] = multiplicity | r"""Update the multiset, keeping only elements found in it and all others.
>>> ms = Multiset('aab')
>>> ms.intersection_update('bc')
>>> sorted(ms)
['b']
You can also use the ``&=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.... | codesearchnet |
def proc_val(key, val):
list_keys = ("LDAUU", "LDAUL", "LDAUJ", "MAGMOM", "DIPOL",
"LANGEVIN_GAMMA", "QUAD_EFG", "EINT")
bool_keys = ("LDAU", "LWAVE", "LSCALU", "LCHARG", "LPLANE", "LUSE_VDW",
"LHFCALC", "ADDGRID", "LSORBIT", "LNONCOLLINEAR")
fl... | Static helper method to convert INCAR parameters to proper types, e.g.,
integers, floats, lists, etc.
Args:
key: INCAR parameter key
val: Actual value of INCAR parameter. | juraj-google-style |
def api_request(self, method_name, params):
url = self._method_url(method_name)
data = json.dumps(params)
return self._make_request(url=url, method='post', data=data) | Execute an arbitrary method.
Args:
method_name (str): include the controller name: 'devices/search'
params (dict): the method parameters
Returns:
A dict with the response
Raises:
requests.exceptions.HTTPError | codesearchnet |
def ensure_app_data_dir(appname, *args):
from ubelt import util_path
dpath = get_app_data_dir(appname, *args)
util_path.ensuredir(dpath)
return dpath | Calls `get_app_data_dir` but ensures the directory exists.
Args:
appname (str): the name of the application
*args: any other subdirectories may be specified
SeeAlso:
get_app_data_dir
Example:
>>> import ubelt as ub
>>> dpath = ub.ensure_app_data_dir('ubelt')
>>> assert exists(dpath) | juraj-google-style |
def _get_schema(cls, schema):
if isinstance(schema, string_types):
schema = cls._get_object_from_python_path(schema)
if isclass(schema):
schema = schema()
if (not isinstance(schema, Schema)):
raise TypeError('The schema must be a path to a Marshmallow schema or a Marshmallow schema.'... | Method that will fetch a Marshmallow schema flexibly.
Args:
schema (marshmallow.Schema|str): Either the schema class, an
instance of a schema, or a Python path to a schema.
Returns:
marshmallow.Schema: The desired schema.
Raises:
TypeError: This is raised if the provided object isn't
a Marshmallow schema. | codesearchnet |
def fwd(self, x_data):
x_data = numpy.asfarray(x_data)
shape = x_data.shape
x_data = x_data.reshape(len(self), (- 1))
(lower, upper) = evaluation.evaluate_bound(self, x_data)
q_data = numpy.zeros(x_data.shape)
indices = (x_data > upper)
q_data[indices] = 1
indices = ((~ indices) & (x_dat... | Forward Rosenblatt transformation.
Args:
x_data (numpy.ndarray):
Location for the distribution function. ``x_data.shape`` must
be compatible with distribution shape.
Returns:
(numpy.ndarray):
Evaluated distribution function values, where
``out.shape==x_data.shape``. | codesearchnet |
def delete_asset(self, asset_id, asset_type):
return self.asset(asset_id, asset_type=asset_type, action='DELETE') | Delete the asset with the provided asset_id.
Args:
asset_id: The id of the asset.
asset_type: The asset type.
Returns: | codesearchnet |
def translate_node_id(self, ni: PrefName, sctx: SchemaContext) -> QualName:
p, s, loc = ni.partition(":")
if not s:
return (ni, sctx.default_ns)
try:
mdata = self.modules[sctx.text_mid]
except KeyError:
raise ModuleNotRegistered(*sctx.text_mid... | Translate node identifier to a qualified name.
Args:
ni: Node identifier (with optional prefix).
sctx: SchemaContext.
Raises:
ModuleNotRegistered: If `mid` is not registered in the data model.
UnknownPrefix: If the prefix specified in `ni` is not declared. | juraj-google-style |
def generate(self, descriptors):
model_ids = self.search_tree.adj_list.keys()
target_graph = None
father_id = None
descriptors = deepcopy(descriptors)
elem_class = Elem
if self.optimizemode is OptimizeMode.Maximize:
elem_class = ReverseElem
... | Generate new architecture.
Args:
descriptors: All the searched neural architectures.
Returns:
graph: An instance of Graph. A morphed neural network with weights.
father_id: The father node ID in the search tree. | juraj-google-style |
def read_as_base64(fn):
with open(fn) as unpacked_file:
with tempfile.TemporaryFile() as b64_file:
base64.encode(unpacked_file, b64_file)
b64_file.flush()
b64_file.seek(0)
return b64_file.read() | Convert given `fn` to base64 and return it. This method does the process
in not-so-much memory consuming way.
Args:
fn (str): Path to the file which should be converted.
Returns:
str: File encoded as base64. | codesearchnet |
def __init__(self, cumulative=IGNORED, name=IGNORED, scalar=IGNORED, kind=IGNORED):
if name != IGNORED and (not isinstance(name, MetricStructuredNameMatcher)):
raise ValueError('name must be a MetricStructuredNameMatcher.')
self.cumulative = cumulative
self.name = name
self.scalar = scalar
s... | Creates a MetricUpdateMatcher.
Any property not passed in to the constructor will be ignored when matching.
Args:
cumulative: A boolean.
name: A MetricStructuredNameMatcher object that matches the name.
scalar: An integer with the metric update.
kind: A string defining the kind of counter. | github-repos |
def get_config(self):
all_args = tf_inspect.getfullargspec(self.__init__).args
config = {'name': self.name, 'trainable': self.trainable}
if hasattr(self, '_batch_input_shape'):
config['batch_input_shape'] = self._batch_input_shape
config['dtype'] = policy.serialize(self._dtype_policy)
if has... | Returns the config of the layer.
A layer config is a Python dictionary (serializable)
containing the configuration of a layer.
The same layer can be reinstantiated later
(without its trained weights) from this configuration.
The config of a layer does not include connectivity
information, nor the layer class name. Th... | github-repos |
def _apply_credentials(auto_refresh=True, credentials=None, headers=None):
token = credentials.get_credentials().access_token
if (auto_refresh is True):
if (token is None):
token = credentials.refresh(access_token=None, timeout=10)
elif credentials.jwt_is_expired():
token... | Update Authorization header.
Update request headers with latest `access_token`. Perform token
`refresh` if token is ``None``.
Args:
auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``.
credentials (class): Read-only credentials.
headers (class): Requests `CaseInsens... | codesearchnet |
def set_large_file_size(self, st_size):
self._check_positive_int(st_size)
if self.st_size:
self.size = 0
if self.filesystem:
self.filesystem.change_disk_usage(st_size, self.name, self.st_dev)
self.st_size = st_size
self._byte_contents = None | Sets the self.st_size attribute and replaces self.content with None.
Provided specifically to simulate very large files without regards
to their content (which wouldn't fit in memory).
Note that read/write operations with such a file raise
:py:class:`FakeLargeFileIoException`.
Args:
st_size: (int) The desired file si... | codesearchnet |
def _attach_debugger_logic(model, debug_path: Optional[str]='.', do_prune_layers: Optional[bool]=True, use_repr: bool=True):
class_name = model.__class__.__name__
model._call_tree = {'module_path': class_name, 'inputs': None, 'outputs': None, 'children': []}
model._debugger_model_call_stack = []
model._... | Attaches a debugging wrapper to every module in the model.
This records structured inputs and outputs during the forward pass into a call tree.
Args:
model (`PreTrainedModel`, `nn.Module`): Model to wrap.
debug_path (`str`): Optional directory to dump debug JSON files.
do_prune_layers (`bool`, *optional*, defaults to... | github-repos |
def save(self, clean=True):
ret = {}
if clean:
self._dirty = False
else:
ret['_dirty'] = self._dirty
return ret | Serialize into raw representation. Clears the dirty bit by default.
Args:
clean (bool): Whether to clear the dirty bit.
Returns:
dict: Raw. | codesearchnet |
def evaluate(self, node: InstanceNode) -> XPathValue:
return self._eval(XPathContext(node, node, 1, 1)) | Evaluate the receiver and return the result.
Args:
node: Context node for XPath evaluation.
Raises:
XPathTypeError: If a subexpression of the receiver is of a wrong
type. | juraj-google-style |
def _rewrite_input_as_indexed_slices(body_grad_graph, grad_output_slices, forward_input, loop_vars):
init_slices = _create_grad_indexed_slices_init(grad_output_slices, forward_input)
with body_grad_graph.as_default():
input_slices = indexed_slices.IndexedSlices(values=body_grad_graph.capture(init_slices... | Rewrites grad_output_slices's corresponding input to be an IndexedSlices.
This rewrite requires that forward_input was captured in the forward loop,
i.e. is not a user-specified loop variable. This is important because the
rewrite assumes that forward_input is passed through to its corresponding
output unchanged. This... | github-repos |
def chat(self, id):
json = self.skype.conn("GET", "{0}/users/ME/conversations/{1}".format(self.skype.conn.msgsHost, id),
auth=SkypeConnection.Auth.RegToken, params={"view": "msnp24Equivalent"}).json()
cls = SkypeSingleChat
if "threadProperties" in json:
... | Get a single conversation by identifier.
Args:
id (str): single or group chat identifier | juraj-google-style |
def get_sequence_sliding_window_properties(self, scale, window, representative_only=True):
if representative_only:
if (not self.representative_sequence):
log.warning('{}: no representative sequence set, cannot get sequence properties'.format(self.id))
return
if (not self.repr... | Run Biopython ProteinAnalysis with a sliding window to calculate a given property.
Results are stored in the protein's respective SeqProp objects at ``.letter_annotations``
Args:
scale (str): Scale name
window (int): Sliding window size
representative_only (bool): If analysis should only be run on the representative s... | codesearchnet |
def range_dimension_tensor(self, name='range_dimension_tensor'):
with self._name_scope(name):
return self._range_dimension_tensor() | Dimension (in the sense of vector spaces) of the range of this operator.
Determined at runtime.
If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns `M`.
Args:
name: A name for this `Op`.
Returns:
`int32` `Tensor` | github-repos |
def create_trial_from_spec(spec, output_path, parser, **trial_kwargs):
try:
args = parser.parse_args(to_argv(spec))
except SystemExit:
raise TuneError('Error parsing args, see above message', spec)
if ('resources_per_trial' in spec):
trial_kwargs['resources'] = json_to_resources(spec... | Creates a Trial object from parsing the spec.
Arguments:
spec (dict): A resolved experiment specification. Arguments should
The args here should correspond to the command line flags
in ray.tune.config_parser.
output_path (str); A specific output path within the local_dir.
Typically the name of the experiment.
parser (... | codesearchnet |
def from_text_files(cls, path, field, train, validation, test=None, bs=64, bptt=70, **kwargs):
(trn_ds, val_ds, test_ds) = ConcatTextDataset.splits(path, text_field=field, train=train, validation=validation, test=test)
return cls(path, field, trn_ds, val_ds, test_ds, bs, bptt, **kwargs) | Method used to instantiate a LanguageModelData object that can be used for a
supported nlp task.
Args:
path (str): the absolute path in which temporary model data will be saved
field (Field): torchtext field
train (str): file location of the training data
validation (str): file location of the validation data
test (st... | codesearchnet |
def remove_file(profile, branch, file_path, commit_message=None):
branch_sha = get_branch_sha(profile, branch)
tree = get_files_in_branch(profile, branch_sha)
new_tree = remove_file_from_tree(tree, file_path)
data = trees.create_tree(profile, new_tree)
sha = data.get('sha')
if (not commit_messag... | Remove a file from a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
branch
The name of a branch.
file_path
The path of the file to delete.
commit_message
A commit message ... | codesearchnet |
def resolve_topic(topic):
try:
(module_name, _, class_name) = topic.partition('
module = importlib.import_module(module_name)
except ImportError as e:
raise TopicResolutionError('{}: {}'.format(topic, e))
try:
cls = resolve_attr(module, class_name)
except AttributeError a... | Return class described by given topic.
Args:
topic: A string describing a class.
Returns:
A class.
Raises:
TopicResolutionError: If there is no such class. | codesearchnet |
def copy_function(func, name=None):
code = func.__code__
newname = name or func.__name__
newcode = CodeType(
code.co_argcount,
code.co_kwonlyargcount,
code.co_nlocals,
code.co_stacksize,
code.co_flags,
code.co_code,
code.co_consts,
code.co... | Copy a function object with different name.
Args:
func (function): Function to be copied.
name (string, optional): Name of the new function.
If not spacified, the same name of `func` will be used.
Returns:
newfunc (function): New function with different name. | juraj-google-style |
def __init__(self, experimenter=None, exp_type=None):
super().__init__()
self.experimenter = experimenter
self.exp_type = exp_type | Create a ExperimenterMultipartHeader with the parameters below.
Args:
experimenter: Experimenter ID which takes the same form as in
struct ofp_experimenter_header (
:class:`~pyof.v0x04.symmetric.experimenter.ExperimenterHeader`)
exp_type: Experimenter defined. | juraj-google-style |
def get_symmetry_operations(self, cartesian=False):
(rotation, translation) = self._get_symmetry()
symmops = []
mat = self._structure.lattice.matrix.T
invmat = np.linalg.inv(mat)
for (rot, trans) in zip(rotation, translation):
if cartesian:
rot = np.dot(mat, np.dot(rot, invmat))
... | Return symmetry operations as a list of SymmOp objects.
By default returns fractional coord symmops.
But cartesian can be returned too.
Returns:
([SymmOp]): List of symmetry operations. | codesearchnet |
def bloom_gelu_forward(x: torch.Tensor) -> torch.Tensor:
return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))) | Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
make the model jitable.
Args:
x (`torch.tensor`):
input hidden states | github-repos |
def add_listener(self, callback, event_type=None):
listener_uid = uuid4()
self.listeners.append(
{
'uid': listener_uid,
'callback': callback,
'event_type': event_type
}
)
return li... | Add a listener that will send a callback when the client recieves
an event.
Args:
callback (func(roomchunk)): Callback called when an event arrives.
event_type (str): The event_type to filter for.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener. | juraj-google-style |
def find_certs() -> str:
bundle = path.realpath(path.dirname(httplib2.CA_CERTS))
if (not bundle.startswith(path.dirname(httplib2.__file__))):
return bundle
for (platform, files) in PLATFORM_FILES.items():
if sys.platform.startswith(platform):
for cert_file in files:
... | Find suitable certificates for ``httplib2``.
Warning:
The default behaviour is to fall back to the bundled certificates when
no system certificates can be found. If you're packaging ``jnrbase``
*please* set ``ALLOW_FALLBACK`` to ``False`` to disable this very much
unwanted behaviour, but please maintain the option so... | codesearchnet |
def find_wells_without_curve(self, mnemonic, alias=None):
return Project([w for w in self if (w.get_curve(mnemonic, alias=alias) is None)]) | Returns a new Project with only the wells which DO NOT have the named curve.
Args:
menmonic (str): the name of the curve to look for.
alias (dict): a welly alias dictionary.
Returns:
project. | codesearchnet |
def __init__(self, path, auto_reboot_args=None, keep_explorer=False, add_all_devices=False):
super(SimpleTestResult, self).__init__()
self.path = path
self.auto_reboot_args = auto_reboot_args
self.result = json.load(open(self.path, 'r'))
self.log_handler = None
s... | Record test results in json file
Args:
path (str): File path to record the results
auto_reboot (bool): Whether reboot when harness die | juraj-google-style |
def group_sub_entities(self, entities: List[dict]) -> dict:
entity = entities[0]['entity'].split('-', 1)[-1]
scores = np.nanmean([entity['score'] for entity in entities])
tokens = [entity['word'] for entity in entities]
entity_group = {'entity_group': entity, 'score': np.mean(scores), 'word': self.token... | Group together the adjacent tokens with the same entity predicted.
Args:
entities (`dict`): The entities predicted by the pipeline. | github-repos |
def assertRaisesWithPredicateMatch(self, exception_type, expected_err_re_or_predicate):
if callable(expected_err_re_or_predicate):
predicate = expected_err_re_or_predicate
else:
def predicate(e):
if isinstance(e, errors.OpError):
e = cast(errors.OpError, e)
... | Returns a context manager to enclose code expected to raise an exception.
If the exception is an OpError, the op stack is also included in the message
predicate search.
Args:
exception_type: The expected type of exception that should be raised.
expected_err_re_or_predicate: If this is callable, it should be a functio... | github-repos |
def __call__(self, request: Union[Chunk, List[Chunk]], *args, **kwargs) -> List[Tuple[Chunk, Dict[str, Any]]]:
requests = request if isinstance(request, list) else [request]
query = self.vector_search_parameters.format_query(requests)
if self.log_query:
_LOGGER.info('Executing query %s', query)
... | Process request(s) using BigQuery vector search.
Args:
request: Single Chunk with embedding or list of Chunk's with
embeddings to process
Returns:
Chunk(s) where chunk.metadata['enrichment_output'] contains the
data retrieved via BigQuery VECTOR_SEARCH. | github-repos |
def min_count(self, n=1):
word_count = {w:c for w,c in iteritems(self.word_count) if c >= n}
return CountedVocabulary(word_count=word_count) | Returns a vocabulary after eliminating the words that appear < `n`.
Args:
n (integer): specifies the minimum word frequency allowed. | juraj-google-style |
def rename(self, source_file_names, destination_file_names):
raise NotImplementedError | Rename the files at the source list to the destination list.
Source and destination lists should be of the same size.
Args:
source_file_names: List of file paths that need to be moved
destination_file_names: List of destination_file_names for the files
Raises:
``BeamIOError``: if any of the rename operations fail | github-repos |
def _init_metadata_service(self, version):
metadata_cfg = self._load_config_section(CONFIG_METADATA_SECTION)
self._token_metadata = metadata_cfg[CONFIG_TOKEN]
proto = metadata_cfg[CONFIG_PROTOCOL]
host = metadata_cfg[CONFIG_HOST]
self._metadata = MetadataService(host, v... | Method to initialize the Metadata Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version. | juraj-google-style |
def get_op_name(tensor_name):
if not tensor_name:
raise ValueError(f'Tensor name cannot be empty or None. Received: {tensor_name}.')
if tensor_name.startswith('^'):
tensor_name = tensor_name[1:]
if ':' in tensor_name:
op_name, _ = tensor_name.split(':')
return op_name
ret... | Extract the Op name from a Tensor name.
The Op name is everything before a colon, if present,
not including any ^ prefix denoting a control dependency.
Args:
tensor_name: the full name of a Tensor in the graph.
Returns:
The name of the Op of which the given Tensor is an output.
Raises:
ValueError: if tensor_name is N... | github-repos |
def job_history(backend):
year = widgets.Output(layout=widgets.Layout(display='flex-inline',
align_items='center',
min_height='400px'))
month = widgets.Output(layout=widgets.Layout(display='flex-inline',
... | Widget for displaying job history
Args:
backend (IBMQbackend): The backend.
Returns:
Tab: A tab widget for history images. | juraj-google-style |
def create(cls, **kwargs):
try:
return cls.add(cls.new(**kwargs))
except:
cls.session.rollback()
raise | Initializes a new instance, adds it to the db and commits
the transaction.
Args:
**kwargs: The keyword arguments for the init constructor.
Examples:
>>> user = User.create(name="Vicky", email="vicky@h.com")
>>> user.id
35 | juraj-google-style |
def getSwarmModelParams(modelID):
cjDAO = ClientJobsDAO.get()
(jobID, description) = cjDAO.modelsGetFields(modelID, ['jobId', 'genDescription'])
(baseDescription,) = cjDAO.jobGetFields(jobID, ['genBaseDescription'])
descriptionDirectory = tempfile.mkdtemp()
try:
baseDescriptionFilePath = os.... | Retrieve the Engine-level model params from a Swarm model
Args:
modelID - Engine-level model ID of the Swarm model
Returns:
JSON-encoded string containing Model Params | codesearchnet |
def close(self):
if self._session and (not self._closed):
self._closed = True
tf_session.TF_CloseSession(self._session) | Closes this session.
Calling this method frees all resources associated with the session.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
closing the TensorFlow session. | github-repos |
def y_score(estimator, X):
try:
y = estimator.predict_proba(X)
return y[:, 1]
except(AttributeError):
return estimator.decision_function(X) | Score examples from a new matrix X
Args:
estimator: an sklearn estimator object
X: design matrix with the same features that the estimator was trained on
Returns: a vector of scores of the same length as X
Note that estimator.predict_proba is preferred but when unavailable
(e.g. SVM without probability calibration) d... | juraj-google-style |
def has_inf_or_nan(datum, tensor):
_ = datum
if isinstance(tensor, InconvertibleTensorProto):
return False
elif np.issubdtype(tensor.dtype, np.floating) or np.issubdtype(tensor.dtype, np.complexfloating) or np.issubdtype(tensor.dtype, np.integer):
return np.any(np.isnan(tensor)) or np.any(np... | A predicate for whether a tensor consists of any bad numerical values.
This predicate is common enough to merit definition in this module.
Bad numerical values include `nan`s and `inf`s.
The signature of this function follows the requirement of the method
`DebugDumpDir.find()`.
Args:
datum: (`DebugTensorDatum`) Datum... | github-repos |
def _handle_port_request(self, client_data, writer):
try:
pid = int(client_data)
except ValueError as error:
self._client_request_errors += 1
log.warning('Could not parse request: %s', error)
return
log.info('Request on behalf of pid %d.'... | Given a port request body, parse it and respond appropriately.
Args:
client_data: The request bytes from the client.
writer: The asyncio Writer for the response to be written to. | juraj-google-style |
def GetShadowMap(self, since=None):
return ShadowUpdateGetter().GetUpdates(self._GetClient(), self.conf['bucket'], self.conf['shadow_object'], since) | Return the shadow map from this source.
Args:
since: Get data only changed since this timestamp (inclusive) or None
for all data.
Returns:
instance of shadow.ShadowMap | github-repos |
def _write_session(self):
base_name = ('%ssession' % self._product_accronym.lower())
filename = ('%s%s.py' % (self._class_prefix.lower(), base_name))
override_content = self._extract_override_content(base_name)
self.write(destination=self.output_directory, filename=filename, template_name='session.py.tp... | Write SDK session file
Args:
version (str): the version of the server | codesearchnet |
def input_waiting(self):
buf = array.array('I', [0])
try:
fcntl.ioctl(self._fd, termios.TIOCINQ, buf, True)
except OSError as e:
raise SerialError(e.errno, ('Querying input waiting: ' + e.strerror))
return buf[0] | Query the number of bytes waiting to be read from the serial port.
Returns:
int: number of bytes waiting to be read.
Raises:
SerialError: if an I/O or OS error occurs. | codesearchnet |
def loss(logits, labels):
labels = tf.to_int64(labels)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels, name='xentropy')
return tf.reduce_mean(cross_entropy, name='xentropy_mean') | Calculates the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor of type float. | juraj-google-style |
def path(self, goal):
if goal == self.name:
return [self]
if goal not in self.routes:
raise ValueError("Unknown '{0}'".format(goal))
obj = self
path = [obj]
while True:
obj = obj.routes[goal].direction
path.append(obj)
... | Get the shortest way between two nodes of the graph
Args:
goal (str): Name of the targeted node
Return:
list of Node | juraj-google-style |
def _lookup_model(cls, kind, default_model=None):
modelclass = cls._kind_map.get(kind, default_model)
if modelclass is None:
raise KindError(
"No model class found for kind '%s'. Did you forget to import it?" %
kind)
return modelclass | Get the model class for the kind.
Args:
kind: A string representing the name of the kind to lookup.
default_model: The model class to use if the kind can't be found.
Returns:
The model class for the requested kind.
Raises:
KindError: The kind was not found and no default_model was provided. | juraj-google-style |
def vectorize(density_matrix, method='col'):
density_matrix = np.array(density_matrix)
if (method == 'col'):
return density_matrix.flatten(order='F')
elif (method == 'row'):
return density_matrix.flatten(order='C')
elif (method in ['pauli', 'pauli_weights']):
num = int(np.log2(le... | Flatten an operator to a vector in a specified basis.
Args:
density_matrix (ndarray): a density matrix.
method (str): the method of vectorization. Allowed values are
- 'col' (default) flattens to column-major vector.
- 'row' flattens to row-major vector.
- 'pauli'flattens in the n-qubit Pauli basis.
- 'pauli-weights':... | codesearchnet |
def has_request(self, request):
queue_item = QueueItem(request, Response(request.url))
key = queue_item.get_hash()
for status in QueueItem.STATUSES:
if (key in self.__get_var(('items_' + status)).keys()):
return True
return False | Check if the given request already exists in the queue.
Args:
request (:class:`nyawc.http.Request`): The request to check.
Returns:
bool: True if already exists, False otherwise. | codesearchnet |
def command(self, cmd_name, callback, *args):
cmd = JLinkCommand(cmd_name, args, callback)
self._commands.put(cmd) | Run an asynchronous command.
Args:
cmd_name (int): The unique code for the command to execute.
callback (callable): The optional callback to run when the command finishes.
The signature should be callback(cmd_name, result, exception)
*args: Any arguments that are passed to the underlying command handler | codesearchnet |
def get_model(self, opt_fn, emb_sz, n_hid, n_layers, **kwargs):
m = get_language_model(self.nt, emb_sz, n_hid, n_layers, self.pad_idx, **kwargs)
model = SingleModel(to_gpu(m))
return RNN_Learner(self, model, opt_fn=opt_fn) | Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module.
Args:
opt_fn (Optimizer): the torch optimizer function to use
emb_sz (int): embedding size
n_hid (int): number of hidden inputs
n_layers (int): number of hidden layers
kwargs: other arguments
Returns:
An instance of the RNN_Learner... | codesearchnet |
def prefetch_users(persistent_course_grades):
users = User.objects.filter(
id__in=[grade.user_id for grade in persistent_course_grades]
)
return {
user.id: user for user in users
} | Prefetch Users from the list of user_ids present in the persistent_course_grades.
Arguments:
persistent_course_grades (list): A list of PersistentCourseGrade.
Returns:
(dict): A dictionary containing user_id to user mapping. | juraj-google-style |
def Deserialize(self, reader):
self.name = reader.ReadVarString().decode('utf-8')
self.symbol = reader.ReadVarString().decode('utf-8')
self.decimals = reader.ReadUInt8() | Read serialized data from byte stream
Args:
reader (neocore.IO.BinaryReader): reader to read byte data from | juraj-google-style |
def from_file(cls, filename, directory=None,
format=None, engine=None, encoding=File._encoding):
filepath = os.path.join(directory or '', filename)
if encoding is None:
encoding = locale.getpreferredencoding()
with io.open(filepath, encoding=encoding) as fd... | Return an instance with the source string read from the given file.
Args:
filename: Filename for loading/saving the source.
directory: (Sub)directory for source loading/saving and rendering.
format: Rendering output format (``'pdf'``, ``'png'``, ...).
engine: Layout command used (``'dot'``, ``'neato'``, ...).
encoding... | juraj-google-style |
def train(self, X_train, Y_train, X_test, Y_test):
while True:
print(1)
time.sleep(1)
if (random.randint(0, 9) >= 5):
break | Train and validate the LR on a train and test dataset
Args:
X_train (np.array): Training data
Y_train (np.array): Training labels
X_test (np.array): Test data
Y_test (np.array): Test labels | codesearchnet |
def stitch_map(tiles, width, height, bbox, dpi):
size = (int((width * dpi_to_dpmm(dpi))), int((height * dpi_to_dpmm(dpi))))
background = Image.new('RGBA', size, (255, 255, 255))
for layer in tiles:
layer_img = Image.new('RGBA', size)
for ((x, y), tile_path) in layer.items():
tile... | Merge tiles together into one image.
Args:
tiles (list of dict of file): tiles for each layer
width (float): page width in mm
height (height): page height in mm
dpi (dpi): resolution in dots per inch
Returns:
PIL.Image: merged map. | codesearchnet |
def subproc_call(cmd, timeout=None):
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout)
return (output, 0)
except subprocess.TimeoutExpired as e:
logger.warn("Command '{}' timeout!".format(cmd))
logger.warn(e.output.decode('utf-8'))
... | Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1. | codesearchnet |
def get_variant_type(variant_source):
file_type = get_file_type(variant_source)
variant_type = 'sv'
if file_type == 'vcf':
variants = VCF(variant_source)
elif file_type == 'gemini':
variants = GeminiQuery(variant_source)
gemini_query = "SELECT * from variants"
varian... | Try to find out what type of variants that exists in a variant source
Args:
variant_source (str): Path to variant source
source_mode (str): 'vcf' or 'gemini'
Returns:
variant_type (str): 'sv' or 'snv' | juraj-google-style |
async def client_event_handler(self, client_id, event_tuple, user_data):
(conn_string, event_name, event) = event_tuple
if (event_name == 'report'):
report = event.serialize()
report['encoded_report'] = base64.b64encode(report['encoded_report'])
msg_payload = dict(connection_string=conn_... | Forward an event on behalf of a client.
This method is called by StandardDeviceServer when it has an event that
should be sent to a client.
Args:
client_id (str): The client that we should send this event to
event_tuple (tuple): The conn_string, event_name and event
object passed from the call to notify_event.
user_d... | codesearchnet |
def _write_session(self):
base_name = "%ssession" % self._product_accronym.lower()
filename = "%s%s.py" % (self._class_prefix.lower(), base_name)
override_content = self._extract_override_content(base_name)
self.write(destination=self.output_directory, filename=filename, templa... | Write SDK session file
Args:
version (str): the version of the server | juraj-google-style |
def get_port_from_port_server(portserver_address, pid=None):
if (not portserver_address):
return None
if (portserver_address[0] == '@'):
portserver_address = ('\x00' + portserver_address[1:])
if (pid is None):
pid = os.getpid()
try:
if hasattr(socket, 'AF_UNIX'):
... | Request a free a port from a system-wide portserver.
This follows a very simple portserver protocol:
The request consists of our pid (in ASCII) followed by a newline.
The response is a port number and a newline, 0 on failure.
This function is an implementation detail of pick_unused_port().
It should not normally be c... | codesearchnet |
def __init__(self, interface, logger, base_configs=None):
raise NotImplementedError('Base class should not be called directly!') | The constructor for the Sniffer. It constructs a sniffer and
configures it to be ready for capture.
Args:
interface: A string specifying the interface used to configure the
sniffer.
logger: Mobly logger object.
base_configs: A dictionary containing baseline configurations of the
sniffer. These can be overridden when s... | github-repos |
def flatten_per_replica_values(distribution_strategy, per_replica_values):
return [e for flattened in nest.flatten(per_replica_values) for e in distribution_strategy.unwrap(flattened)] | Unwraps and flattens a nest of PerReplica parameters.
PerReplica values have one value associated with each device. Each entry in
the PerReplica dict has a device `key` and the corresponding value on the
device as the `value`. In this function we take a PerReplica value or a list
of PerReplica values and return all th... | github-repos |
def rename_style(self, old_name, new_name):
if (old_name not in self.styles):
raise KeyError(('Style %r not found' % old_name))
if (new_name in self.styles):
raise ValueError(('There is already a style called %r' % new_name))
if (not is_valid_field_content(new_name)):
raise ValueErro... | Rename a style, including references to it.
Arguments:
old_name (str): Style to be renamed.
new_name (str): New name for the style (must be unused).
Raises:
KeyError: No style named old_name.
ValueError: new_name is not a legal name (cannot use commas)
or new_name is taken. | codesearchnet |
def ssh(cmd=''):
with settings(warn_only=True):
local('ssh -A -o StrictHostKeyChecking=no -i "%s" %s@%s "%s"' % (
env.key_filename, env.user, env.host, cmd)) | SSH into the server(s) (sequentially if more than one)
Args:
cmd (str) ='': Command to run on the server | juraj-google-style |
def encode_corpus(self, corpus, output_path):
out_container = containers.Container(output_path)
out_container.open()
for utterance in corpus.utterances.values():
data = self.encode_utterance(utterance, corpus=corpus)
out_container.set(utterance.idx, data)
... | Encode all utterances of the given corpus and store them in a :class:`audiomate.container.Container`.
Args:
corpus (Corpus): The corpus to process.
output_path (str): The path to store the container with the encoded data.
Returns:
Container: The container with the encoded data. | juraj-google-style |
def intersect(df, other, index=False, keep='first'):
validate_set_ops(df, other)
if index:
df_reset_index = df.reset_index()
other_reset_index = other.reset_index()
index_cols = [col for col in df_reset_index.columns if col not in df.columns]
df_index_names = df.index.names... | Returns rows that appear in both DataFrames.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): Boolean indicating whether to consider the pandas index
as part of the set operation (default `False`).
ke... | juraj-google-style |
def add_implem(self, transition, attribute, function, **kwargs):
implem = ImplementationProperty(field_name=self.state_field, transition=transition, workflow=self.workflow, implementation=function, **kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
... | Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty. | codesearchnet |
def set_image(self, text):
if exercises.CONTENT_STORAGE_PLACEHOLDER in text:
return text, []
stripped_text = text.strip().replace('\\n', '')
graphie_regex = re.compile(WEB_GRAPHIE_URL_REGEX, flags=re.IGNORECASE)
graphie_match = graphie_rege... | Save image resource at `text` (path or url) to storage, then return the
replacement string and the necessary exercicse image file object.
Args:
- text (str): path or url to parse as an exercise image resource
Returns: (new_text, files)
- `new_text` (str): replacement string for the original `text` string
- `files` (lis... | juraj-google-style |
def texture3d(self, size, components, data=None, *, alignment=1, dtype='f1') -> 'Texture3D':
res = Texture3D.__new__(Texture3D)
res.mglo, res._glo = self.mglo.texture3d(size, components, data, alignment, dtype)
res.ctx = self
res.extra = None
return res | Create a :py:class:`Texture3D` object.
Args:
size (tuple): The width, height and depth of the texture.
components (int): The number of components 1, 2, 3 or 4.
data (bytes): Content of the texture.
Keyword Args:
alignment (int): The byte alignment 1, 2, 4 or 8.
dtype (str): Data type.
Returns:
:py:class:`Texture3D` ... | juraj-google-style |
def _SetExtractionPreferredTimeZone(self, knowledge_base):
if self._preferred_time_zone:
try:
knowledge_base.SetTimeZone(self._preferred_time_zone)
except ValueError:
logger.warning('Unsupported time zone: {0:s}, defaulting to {1:s}'.format(self._preferred_time_zone, knowledg... | Sets the preferred time zone before extraction.
Args:
knowledge_base (KnowledgeBase): contains information from the source
data needed for parsing. | codesearchnet |
def filter_devices(ads, func):
results = []
for ad in ads:
if func(ad):
results.append(ad)
return results | Finds the AndroidDevice instances from a list that match certain
conditions.
Args:
ads: A list of AndroidDevice instances.
func: A function that takes an AndroidDevice object and returns True
if the device satisfies the filter condition.
Returns:
A list of AndroidDevice instances that satisfy the filter condition. | codesearchnet |
def _prune_heads(self, heads_to_prune):
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads) | Prunes heads of the model.
Args:
heads_to_prune:
dict of {layer_num: list of heads to prune in this layer} | github-repos |
def design_stat_extremes(self, value="Extremes"):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError(
'value {} need to be of type str '
'for field `design_stat_extremes`'.form... | Corresponds to IDD Field `design_stat_extremes`
Args:
value (str): value for IDD Field `design_stat_extremes`
Accepted values are:
- Extremes
Default value: Extremes
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid v... | juraj-google-style |
def get_block(self, height_or_hash, id=None, endpoint=None):
return self._call_endpoint(GET_BLOCK, params=[height_or_hash, 1], id=id, endpoint=endpoint) | Look up a block by the height or hash of the block.
Args:
height_or_hash: (int or str) either the height of the desired block or its hash in the form '1e67372c158a4cfbb17b9ad3aaae77001a4247a00318e354c62e53b56af4006f'
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to speci... | juraj-google-style |
def _Matches(path, pattern_list):
return any(fnmatch.fnmatchcase(path, pattern) for pattern in pattern_list) | Returns true if path matches any patten found in pattern_list.
Args:
path: A dot separated path to a package, class, method or variable
pattern_list: A list of wildcard patterns
Returns:
True if path matches any wildcard found in pattern_list. | juraj-google-style |
def parse_rule(cls, txt):
types = {'glob': GlobRule, 'regex': RegexRule, 'range': RangeRule, 'before': TimestampRule, 'after': TimestampRule}
(label, txt) = Rule._parse_label(txt)
if (label is None):
if ('*' in txt):
label = 'glob'
else:
label = 'range'
elif (labe... | Parse a rule from a string.
See rezconfig.package_filter for an overview of valid strings.
Args:
txt (str): String to parse.
Returns:
`Rule` instance. | codesearchnet |
def update(self, other):
if isinstance(other, NdMapping):
dims = [d for d in other.kdims if d not in self.kdims]
if len(dims) == other.ndims:
raise KeyError("Cannot update with NdMapping that has"
" a different set of key dimensions... | Merges other item with this object
Args:
other: Object containing items to merge into this object
Must be a dictionary or NdMapping type | juraj-google-style |
def create_graph_from_data(self, data):
self.arguments['{SCORE}'] = self.scores[self.score]
self.arguments['{VERBOSE}'] = str(self.verbose).upper()
results = self._run_gies(data, verbose=self.verbose)
return nx.relabel_nodes(nx.DiGraph(results),
... | Run the GIES algorithm.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by the GIES algorithm. | juraj-google-style |
def has_register(self, register):
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
... | Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit. | juraj-google-style |
def get(self, key, state_manager, training=None):
if key in self._feature_tensors:
return self._feature_tensors[key]
if key in self._features:
feature_tensor = self._get_raw_feature_as_tensor(key)
self._feature_tensors[key] = feature_tensor
return feature_tensor
if isinstance... | Returns a `Tensor` for the given key.
A `str` key is used to access a base feature (not-transformed). When a
`FeatureColumn` is passed, the transformed feature is returned if it
already exists, otherwise the given `FeatureColumn` is asked to provide its
transformed output, which is then cached.
Args:
key: a `str` or ... | github-repos |
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_buffer = utils.BytearrayStream()
if self._object_type:
self._object_type.write(local_buffer, kmip_version=kmip_version)
else:
raise exceptions.InvalidField('The Create response payload is missing the object type f... | Write the data encoding the Create response payload to a buffer.
Args:
output_buffer (stream): A data buffer in which to encode object
data, supporting a write method.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
In... | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.