code
stringlengths 20
4.93k
| docstring
stringlengths 33
1.27k
| source
stringclasses 3
values |
---|---|---|
def expected_rs(n):
front = (n - 0.5) / n
i = np.arange(1,n)
back = np.sum(np.sqrt((n - i) / i))
if n <= 340:
middle = math.gamma((n-1) * 0.5) / math.sqrt(math.pi) / math.gamma(n * 0.5)
else:
middle = 1.0 / math.sqrt(n * math.pi * 0.5)
return front * middle * back
|
Calculates the expected (R/S)_n for white noise for a given n.
This is used as a correction factor in the function hurst_rs. It uses the
formula of Anis-Lloyd-Peters (see [h_3]_).
Args:
n (int):
the value of n for which the expected (R/S)_n should be calculated
Returns:
float:
expected (R/S)_n for white noise
|
juraj-google-style
|
def sample_variants(self, variants, sample_name, category='snv'):
LOG.info('Retrieving variants for subject : {0}'.format(sample_name))
has_allele = re.compile('1|2')
query = {'$and': [{'_id': {'$in': variants}}, {'category': category}, {'samples': {'$elemMatch': {'display_name': sample_name, 'genotype_call': {'$regex': has_allele}}}}]}
result = self.variant_collection.find(query)
return result
|
Given a list of variants get variant objects found in a specific patient
Args:
variants(list): a list of variant ids
sample_name(str): a sample display name
category(str): 'snv', 'sv' ..
Returns:
result(iterable(Variant))
|
codesearchnet
|
def AddrStrToScriptHash(address):
data = b58decode(address)
if (len(data) != 25):
raise ValueError('Not correct Address, wrong length.')
if (data[0] != settings.ADDRESS_VERSION):
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if (checksum != data[21:]):
raise Exception('Address format error')
return UInt160(data=data[1:21])
|
Convert a public address to a script hash.
Args:
address (str): base 58 check encoded public address.
Raises:
ValueError: if the address length of address version is incorrect.
Exception: if the address checksum fails.
Returns:
UInt160:
|
codesearchnet
|
def query(self, s):
s1 = np.sort([self.order[token] for token in s if (token in self.order)])
logging.debug('{} original tokens and {} tokens after applying frequency order.'.format(len(s), len(s1)))
prefix = self._get_prefix(s1)
candidates = set([i for (p1, token) in enumerate(prefix) for (i, p2) in self.index[token] if self.position_filter_func(s1, self.sets[i], p1, p2, self.similarity_threshold)])
logging.debug('{} candidates found.'.format(len(candidates)))
results = deque([])
for i in candidates:
s2 = self.sets[i]
sim = self.similarity_func(s1, s2)
if (sim < self.similarity_threshold):
continue
results.append((i, sim))
logging.debug('{} verified sets found.'.format(len(results)))
return list(results)
|
Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets.
|
codesearchnet
|
def inv(a):
amean = gvar.mean(a)
if ((amean.ndim != 2) or (amean.shape[0] != amean.shape[1])):
raise ValueError(('bad matrix shape: ' + str(a.shape)))
da = (a - amean)
ainv = numpy.linalg.inv(amean)
return (ainv - ainv.dot(da.dot(ainv)))
|
Inverse of matrix ``a``.
Args:
a: Two-dimensional, square matrix/array of numbers
and/or :class:`gvar.GVar`\s.
Returns:
The inverse of matrix ``a``.
Raises:
ValueError: If matrix is not square and two-dimensional.
|
codesearchnet
|
def mimic_adam_with_adafactor(hparams):
assert "adam" in hparams.optimizer
hparams.optimizer = "adafactor"
hparams.optimizer_adafactor_beta1 = hparams.optimizer_adam_beta1
hparams.optimizer_adafactor_beta2 = hparams.optimizer_adam_beta2
hparams.optimizer_adafactor_multiply_by_parameter_scale = False
hparams.optimizer_adafactor_factored = False
hparams.optimizer_adafactor_clipping_threshold = None
hparams.optimizer_adafactor_decay_type = "adam"
|
Switch from Adam to Adafactor, approximating the behavior of Adam.
Some minor things may be different, like epsilon and beta1 correction.
Args:
hparams: model hyperparameters where "adam" in hparams.optimizer
|
juraj-google-style
|
def __init__(self, artifacts_registry, knowledge_base):
super(ArtifactDefinitionsFilterHelper, self).__init__()
self._artifacts_registry = artifacts_registry
self._knowledge_base = knowledge_base
self.file_system_artifact_names = set()
self.file_system_find_specs = []
self.registry_artifact_names = set()
self.registry_find_specs = []
|
Initializes an artifact definitions filter helper.
Args:
artifacts_registry (artifacts.ArtifactDefinitionsRegistry): artifact
definitions registry.
knowledge_base (KnowledgeBase): contains information from the source
data needed for filtering.
|
juraj-google-style
|
def __init__(self, select2attrs=None, *args, **kwargs):
self.select2attrs = select2attrs or {}
assert_msg = "select2attrs attribute must be dict, not {}"
assert isinstance(self.select2attrs, dict), assert_msg.format(
self.select2attrs.__class__.__name__
)
if 'width' not in self.select2attrs:
self.select2attrs.update({'width': '250px'})
super(Select2Mixin, self).__init__(*args, **kwargs)
|
Initialize default select2 attributes.
If width is not provided, sets Select2 width to 250px.
Args:
select2attrs: a dictionary, which then passed to
Select2 constructor function as options.
|
juraj-google-style
|
def __init__(self, columns: list[str], name: Optional[str]=None):
self.name = name
super().__init__(columns)
|
Deduplicates each row (0th dimension) of the provided tensor.
Args:
columns: A list of the columns to apply the transformation on.
name: optional. A name for this operation.
|
github-repos
|
def add_resource(self, feature_column, resource_name, resource):
self._cols_to_resources_map[feature_column][resource_name] = resource
if self._layer is not None and isinstance(resource, trackable.Trackable):
if feature_column.name not in self._layer._resources:
self._layer._resources[feature_column.name] = data_structures.Mapping()
if resource_name not in self._layer._resources[feature_column.name]:
self._layer._resources[feature_column.name][resource_name] = resource
|
Creates a new resource.
Resources can be things such as tables, variables, trackables, etc.
Args:
feature_column: A `FeatureColumn` object this resource corresponds to.
resource_name: Name of the resource.
resource: The resource.
Returns:
The created resource.
|
github-repos
|
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
version_value = registry_key.GetValueByName('Version')
count_subkey = registry_key.GetSubkeyByName('Count')
if not version_value:
parser_mediator.ProduceExtractionWarning('missing version value')
return
if not version_value.DataIsInteger():
parser_mediator.ProduceExtractionWarning(
'unsupported version value data type')
return
format_version = version_value.GetDataAsObject()
if format_version not in (3, 5):
parser_mediator.ProduceExtractionWarning(
'unsupported format version: {0:d}'.format(format_version))
return
if not count_subkey:
parser_mediator.ProduceExtractionWarning('missing count subkey')
return
userassist_entry_index = 0
for registry_value in count_subkey.GetValues():
try:
value_name = codecs.decode(registry_value.name, 'rot-13')
except UnicodeEncodeError as exception:
logger.debug((
'Unable to decode UserAssist string: {0:s} with error: {1!s}.\n'
'Attempting piecewise decoding.').format(
registry_value.name, exception))
characters = []
for char in registry_value.name:
if ord(char) < 128:
try:
characters.append(char.decode('rot-13'))
except UnicodeEncodeError:
characters.append(char)
else:
characters.append(char)
value_name = ''.join(characters)
if format_version == 5:
path_segments = value_name.split('\\')
for segment_index, path_segment in enumerate(path_segments):
guid = path_segments[segment_index][1:-1]
path_segments[segment_index] = known_folder_ids.PATHS.get(
guid, path_segment)
value_name = '\\'.join(path_segments)
if '%' in value_name:
environment_variables = self._knowledge_base.GetEnvironmentVariables()
value_name = path_helper.PathHelper.ExpandWindowsPath(
value_name, environment_variables)
if value_name == 'UEME_CTLSESSION':
continue
if format_version == 3:
entry_map = self._GetDataTypeMap('user_assist_entry_v3')
elif format_version == 5:
entry_map = self._GetDataTypeMap('user_assist_entry_v5')
else:
parser_mediator.ProduceExtractionWarning(
'unsupported format version: {0:d}'.format(format_version))
continue
if not registry_value.DataIsBinaryData():
parser_mediator.ProduceExtractionWarning(
'unsupported value data type: {0:s}'.format(
registry_value.data_type_string))
continue
entry_data_size = entry_map.GetByteSize()
value_data_size = len(registry_value.data)
if entry_data_size != value_data_size:
parser_mediator.ProduceExtractionWarning(
'unsupported value data size: {0:d}'.format(value_data_size))
continue
try:
user_assist_entry = self._ReadStructureFromByteStream(
registry_value.data, 0, entry_map)
except (ValueError, errors.ParseError) as exception:
parser_mediator.ProduceExtractionWarning(
'unable to parse UserAssist entry value with error: {0!s}'.format(
exception))
continue
event_data = UserAssistWindowsRegistryEventData()
event_data.key_path = count_subkey.path
event_data.number_of_executions = user_assist_entry.number_of_executions
event_data.value_name = value_name
if format_version == 3:
if event_data.number_of_executions > 5:
event_data.number_of_executions -= 5
elif format_version == 5:
userassist_entry_index += 1
event_data.application_focus_count = (
user_assist_entry.application_focus_count)
event_data.application_focus_duration = (
user_assist_entry.application_focus_duration)
event_data.entry_index = userassist_entry_index
timestamp = user_assist_entry.last_execution_time
if not timestamp:
date_time = dfdatetime_semantic_time.SemanticTime('Not set')
else:
date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
event = time_events.DateTimeValuesEvent(
date_time, definitions.TIME_DESCRIPTION_LAST_RUN)
parser_mediator.ProduceEventWithEventData(event, event_data)
|
Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
|
juraj-google-style
|
def add_state(self, name: str, state: State, initial: bool=False):
if (not issubclass(state.__class__, State)):
raise AttributeError('state must be subclass of spade.behaviour.State')
self._states[name] = state
if initial:
self.current_state = name
|
Adds a new state to the FSM.
Args:
name (str): the name of the state, which is used as its identifier.
state (spade.behaviour.State): The state class
initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False)
|
codesearchnet
|
def plot_internal_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs):
temperatures = np.linspace(tmin, tmax, ntemp)
if self.structure:
ylabel = r"$\Delta E$ (kJ/mol)"
else:
ylabel = r"$\Delta E$ (kJ/mol-c)"
fig = self._plot_thermo(self.dos.internal_energy, temperatures, ylabel=ylabel, ylim=ylim,
factor=1e-3, **kwargs)
return fig
|
Plots the vibrational internal energy in a temperature range.
Args:
tmin: minimum temperature
tmax: maximum temperature
ntemp: number of steps
ylim: tuple specifying the y-axis limits.
kwargs: kwargs passed to the matplotlib function 'plot'.
Returns:
matplotlib figure
|
juraj-google-style
|
def _checkResponseRegisterAddress(payload, registeraddress):
_checkString(payload, minlength=2, description='payload')
_checkRegisteraddress(registeraddress)
BYTERANGE_FOR_STARTADDRESS = slice(0, 2)
bytesForStartAddress = payload[BYTERANGE_FOR_STARTADDRESS]
receivedStartAddress = _twoByteStringToNum(bytesForStartAddress)
if receivedStartAddress != registeraddress:
raise ValueError('Wrong given write start adress: {0}, but commanded is {1}. The data payload is: {2!r}'.format( \
receivedStartAddress, registeraddress, payload))
|
Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal numbers, not hex).
Raises:
TypeError, ValueError
|
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), {idx: i for (idx, i) in enumerate(data.columns)})
|
Run the GIES algorithm.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by the GIES algorithm.
|
codesearchnet
|
def add_perm(self, subj_str, perm_str):
self._assert_valid_permission(perm_str)
self._perm_dict.setdefault(perm_str, set()).add(subj_str)
|
Add a permission for a subject.
Args:
subj_str : str
Subject for which to add permission(s)
perm_str : str
Permission to add. Implicitly adds all lower permissions. E.g., ``write``
will also add ``read``.
|
juraj-google-style
|
def scan(self, folder, sub=None, next_=None):
if (not sub):
sub = ''
assert isinstance(sub, string_types)
assert (isinstance(next_, int) or (next_ is None))
return self.post('scan', params={'folder': folder, 'sub': sub, 'next': next_})
|
Request immediate rescan of a folder, or a specific path within a
folder.
Args:
folder (str): Folder ID.
sub (str): Path relative to the folder root. If sub is omitted
the entire folder is scanned for changes, otherwise only
the given path children are scanned.
next_ (int): Delays Syncthing's automated rescan interval for
a given amount of seconds.
Returns:
str
|
codesearchnet
|
def load_yaml(path):
with open(path, 'rt') as f:
yamldict = yaml.load(f.read(), Loader=yamlloader.ordereddict.CSafeLoader)
if (not yamldict):
raise LoadError(('YAML file: %s is empty!' % path))
return yamldict
|
Load YAML file into an ordered dictionary
Args:
path (str): Path to YAML file
Returns:
OrderedDict: Ordered dictionary containing loaded YAML file
|
codesearchnet
|
def create_slot(primary, val, name, colocate_with_primary=True, *, copy_xla_sharding=False):
validate_shape = val.get_shape().is_fully_defined()
if isinstance(primary, variables.Variable):
prefix = primary._shared_name
else:
prefix = primary.op.name
with variable_scope.variable_scope(None, prefix + '/' + name):
if colocate_with_primary:
distribution_strategy = distribute_lib.get_strategy()
with distribution_strategy.extended.colocate_vars_with(primary):
return _create_slot_var(primary, val, '', validate_shape, None, None, copy_xla_sharding=copy_xla_sharding)
else:
return _create_slot_var(primary, val, '', validate_shape, None, None, copy_xla_sharding=copy_xla_sharding)
|
Create a slot initialized to the given value.
The type of the slot is determined by the given value.
Args:
primary: The primary `Variable` or `Tensor`.
val: A `Tensor` specifying the initial value of the slot.
name: Name to use for the slot variable.
colocate_with_primary: Boolean. If True the slot is located
on the same device as `primary`.
copy_xla_sharding: Boolean. If True also copies XLA sharding
from primary.
Returns:
A `Variable` object.
|
github-repos
|
def annotate(label, since, current, extra_message, custom_message=None):
warning_message = _WarningMessage(label=label, since=since, current=current, extra_message=extra_message, custom_message=custom_message)
def _annotate(fnc):
if inspect.isclass(fnc):
old_new = fnc.__new__
def wrapped_new(cls, *args, **kwargs):
warning_message.emit_warning(fnc.__name__)
if old_new is object.__new__:
return old_new(cls)
return old_new(cls, *args, **kwargs)
fnc.__new__ = staticmethod(wrapped_new)
if label == 'deprecated':
fnc.__doc__ = _add_deprecation_notice_to_docstring(fnc.__doc__, warning_message.message.replace('%name%', fnc.__name__))
return fnc
else:
@wraps(fnc)
def inner(*args, **kwargs):
warning_message.emit_warning(fnc.__name__)
return fnc(*args, **kwargs)
if label == 'deprecated':
inner.__doc__ = _add_deprecation_notice_to_docstring(fnc.__doc__, warning_message.message.replace('%name%', fnc.__name__))
return inner
return _annotate
|
Decorates an API with a deprecated or experimental annotation.
Args:
label: the kind of annotation ('deprecated' or 'experimental').
since: the version that causes the annotation.
current: the suggested replacement function.
extra_message: an optional additional message.
custom_message: if the default message does not suffice, the message
can be changed using this argument. A string
whit replacement tokens.
A replecement string is were the previus args will
be located on the custom message.
The following replacement strings can be used:
%name% -> API.__name__
%since% -> since (Mandatory for the decapreted annotation)
%current% -> current
%extra% -> extra_message
Returns:
The decorator for the API.
|
github-repos
|
def resources(self, absolute_url=None):
if absolute_url:
return Resources(mode="server", root_url=absolute_url + self._prefix, path_versioner=StaticHandler.append_version)
return Resources(mode="server", root_url=self._prefix, path_versioner=StaticHandler.append_version)
|
Provide a :class:`~bokeh.resources.Resources` that specifies where
Bokeh application sessions should load BokehJS resources from.
Args:
absolute_url (bool):
An absolute URL prefix to use for locating resources. If None,
relative URLs are used (default: None)
|
juraj-google-style
|
def __is_function_action(self, action_function):
is_function_action = True
if not hasattr(action_function, '__call__'):
return False
try:
for end_string, context in action_function():
if not isinstance(end_string, basestring):
self.log_error("Action function must return end of filename as a string as first argument")
if not isinstance(context, dict):
self.log_error("Action function must return context as a dict as second argument")
break
except Exception:
is_function_action = False
return is_function_action
|
Detect if given function is really an action function.
Args:
action_function: Function to test.
Note:
We don't care if the variable refer to a function but rather if it is callable or not.
|
juraj-google-style
|
def _get_status_code(self, http_status):
try:
return int(http_status.split(' ', 1)[0])
except TypeError:
_logger.warning('Unable to find status code in HTTP status %r.', http_status)
return 500
|
Get the HTTP status code from an HTTP status string.
Args:
http_status: A string containing a HTTP status code and reason.
Returns:
An integer with the status code number from http_status.
|
codesearchnet
|
def __init__(self, project, query, checksum, timeout_secs=0):
if bigquery is None:
raise ImportError('Bigquery dependencies are not installed.')
if not query or not isinstance(query, str):
raise ValueError('Invalid argument: query. Please use non-empty string')
if not checksum or not isinstance(checksum, str):
raise ValueError('Invalid argument: checksum. Please use non-empty string')
self.project = project
self.query = query
self.expected_checksum = checksum
self.checksum = None
self.timeout_secs = timeout_secs
|
Initialize BigQueryMatcher object.
Args:
project: The name (string) of the project.
query: The query (string) to perform.
checksum: SHA-1 hash generated from a sorted list of lines
read from expected output.
timeout_secs: Duration to retry query until checksum matches. This
is useful for DF streaming pipelines or BQ streaming inserts. The
default (0) never retries.
|
github-repos
|
def reshape_data(tensor, per_example_length=1):
dims = [1, 0]
for i in xrange(2, tensor.get_shape().ndims):
dims.append(i)
return pt.wrap(tf.transpose(tensor, dims)).reshape([(- 1), per_example_length])
|
Reshapes input so that it is appropriate for sequence_lstm..
The expected format for sequence lstms is
[timesteps * batch, per_example_length] and the data produced by the utilities
is [batch, timestep, *optional* expected_length]. The result can be cleaved
so that there is a Tensor per timestep.
Args:
tensor: The tensor to reshape.
per_example_length: The number of examples at each timestep.
Returns:
A Pretty Tensor that is compatible with cleave and then sequence_lstm.
|
codesearchnet
|
def _Scroll(self, lines=None):
if lines is None:
lines = self._cli_lines
if lines < 0:
self._displayed -= self._cli_lines
self._displayed += lines
if self._displayed < 0:
self._displayed = 0
self._lines_to_show = self._cli_lines
else:
self._lines_to_show = lines
self._lastscroll = lines
|
Set attributes to scroll the buffer correctly.
Args:
lines: An int, number of lines to scroll. If None, scrolls
by the terminal length.
|
juraj-google-style
|
def __init__(self, config, http_client_session=None):
self.verify = config.get("verify", True)
self.output = config.get("output", [])
self.validation_results = []
config_variables = config.get("variables", {})
testcase_setup_hooks = config.get("setup_hooks", [])
self.testcase_teardown_hooks = config.get("teardown_hooks", [])
self.http_client_session = http_client_session or HttpSession()
self.session_context = SessionContext(config_variables)
if testcase_setup_hooks:
self.do_hook_actions(testcase_setup_hooks, "setup")
|
run testcase or testsuite.
Args:
config (dict): testcase/testsuite config dict
{
"name": "ABC",
"variables": {},
"setup_hooks", [],
"teardown_hooks", []
}
http_client_session (instance): requests.Session(), or locust.client.Session() instance.
|
juraj-google-style
|
def parse_commit_message(commit_message: str) -> Dict[str, bool]:
if commit_message is None:
return {'skip': False, 'no_filter': False, 'test_all': False}
command_search = re.search('\\[([^\\]]*)\\]', commit_message)
if command_search is not None:
command = command_search.groups()[0]
command = command.lower().replace('-', ' ').replace('_', ' ')
skip = command in ['ci skip', 'skip ci', 'circleci skip', 'skip circleci']
no_filter = set(command.split(' ')) == {'no', 'filter'}
test_all = set(command.split(' ')) == {'test', 'all'}
return {'skip': skip, 'no_filter': no_filter, 'test_all': test_all}
else:
return {'skip': False, 'no_filter': False, 'test_all': False}
|
Parses the commit message to detect if a command is there to skip, force all or part of the CI.
Args:
commit_message (`str`): The commit message of the current commit.
Returns:
`Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`,
`"test_all_models"` and `"test_all"`.
|
github-repos
|
def html2text(__html: str, *, width: int = 80,
ascii_replacements: bool = False) -> str:
html2.BODY_WIDTH = width
html2.UNICODE_SNOB = ascii_replacements
return html2.html2text(__html).strip()
|
HTML to plain text renderer.
See also: :pypi:`html2text`
Args:
__html: Text to process
width: Paragraph width
ascii_replacements: Use pseudo-ASCII replacements for Unicode
Returns:
Rendered text
|
juraj-google-style
|
def get_parent(self, tree, alt=None):
parent = self.parent_db.get(tree.path)
if not parent:
return alt
return list(parent)[0]
|
Get parent for given `tree` or `alt` if not found.
Args:
tree (obj): :class:`.Tree` instance, which is already stored in DB.
alt (obj, default None): Alternative value returned when `tree` is
not found.
Returns:
obj: :class:`.Tree` parent to given `tree`.
|
juraj-google-style
|
def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn):
x = tf.nn.l2_normalize(x)
for _ in range(num_steps):
x = eig_one_step(x, learning_rate, vector_prod_fn)
return x
|
Computes eigenvector which corresponds to minimum eigenvalue.
Args:
x: initial value of eigenvector.
num_steps: number of optimization steps.
learning_rate: learning rate.
vector_prod_fn: function which takes x and returns product H*x.
Returns:
approximate value of eigenvector.
This function finds approximate value of eigenvector of matrix H which
corresponds to smallest (by absolute value) eigenvalue of H.
It works by solving optimization problem x^{T}*H*x -> min.
|
codesearchnet
|
def _parse_ospf_process_id(self, config):
match = re.search(r'^router ospf (\d+)', config)
return dict(ospf_process_id=int(match.group(1)))
|
Parses config file for the OSPF proc ID
Args:
config(str): Running configuration
Returns:
dict: key: ospf_process_id (int)
|
juraj-google-style
|
def apply_formatting_dict(obj: Any, formatting: Dict[(str, Any)]) -> Any:
new_obj = obj
if isinstance(obj, str):
if ('$' not in obj):
new_obj = string.Formatter().vformat(obj, (), formatting_dict(**formatting))
elif isinstance(obj, dict):
new_obj = {}
for (k, v) in obj.items():
new_obj[k] = apply_formatting_dict(v, formatting)
elif isinstance(obj, list):
new_obj = []
for (i, el) in enumerate(obj):
new_obj.append(apply_formatting_dict(el, formatting))
elif (isinstance(obj, int) or isinstance(obj, float) or (obj is None)):
pass
elif isinstance(obj, enum.Enum):
pass
else:
logger.debug(f"Unrecognized obj '{obj}' of type '{type(obj)}'")
return new_obj
|
Recursively apply a formatting dict to all strings in a configuration.
Note that it skips applying the formatting if the string appears to contain latex (specifically,
if it contains an "$"), since the formatting fails on nested brackets.
Args:
obj: Some configuration object to recursively applying the formatting to.
formatting (dict): String formatting options to apply to each configuration field.
Returns:
dict: Configuration with formatting applied to every field.
|
codesearchnet
|
def apply_cut(self, cut):
return Subsystem(self.network, self.state, self.node_indices,
cut=cut, mice_cache=self._mice_cache)
|
Return a cut version of this |Subsystem|.
Args:
cut (Cut): The cut to apply to this |Subsystem|.
Returns:
Subsystem: The cut subsystem.
|
juraj-google-style
|
def filter_dict(d, exclude):
ret = {}
for (key, value) in d.items():
if (key not in exclude):
ret.update({key: value})
return ret
|
Return a new dict with specified keys excluded from the origional dict
Args:
d (dict): origional dict
exclude (list): The keys that are excluded
|
codesearchnet
|
def ParseFileObject(self, parser_mediator, file_object):
esedb_file = pyesedb.file()
try:
esedb_file.open_file_object(file_object)
except IOError as exception:
parser_mediator.ProduceExtractionWarning('unable to open file with error: {0!s}'.format(exception))
return
cache = ESEDBCache()
try:
table_names = frozenset(self._GetTableNames(esedb_file))
for plugin in self._plugins:
if parser_mediator.abort:
break
if (not plugin.required_tables.issubset(table_names)):
continue
try:
plugin.UpdateChainAndProcess(parser_mediator, cache=cache, database=esedb_file)
except Exception as exception:
parser_mediator.ProduceExtractionWarning('plugin: {0:s} unable to parse ESE database with error: {1!s}'.format(plugin.NAME, exception))
finally:
esedb_file.close()
|
Parses an ESE database file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
|
codesearchnet
|
def prepare_run_debug_urls(self, fetches, feed_dict):
self._run_counter_lock.acquire()
run_dir = os.path.join(self._session_root, 'run_%d_%d' % (int(time.time() * 1000000.0), self._run_counter))
self._run_counter += 1
self._run_counter_lock.release()
gfile.MkDir(run_dir)
fetches_event = event_pb2.Event()
fetches_event.log_message.message = repr(fetches)
fetches_path = os.path.join(run_dir, debug_data.METADATA_FILE_PREFIX + debug_data.FETCHES_INFO_FILE_TAG)
with gfile.Open(os.path.join(fetches_path), 'wb') as f:
f.write(fetches_event.SerializeToString())
feed_keys_event = event_pb2.Event()
feed_keys_event.log_message.message = repr(feed_dict.keys()) if feed_dict else repr(feed_dict)
feed_keys_path = os.path.join(run_dir, debug_data.METADATA_FILE_PREFIX + debug_data.FEED_KEYS_INFO_FILE_TAG)
with gfile.Open(os.path.join(feed_keys_path), 'wb') as f:
f.write(feed_keys_event.SerializeToString())
return ['file:
|
Implementation of abstract method in superclass.
See doc of `NonInteractiveDebugWrapperSession.prepare_run_debug_urls()`
for details. This implementation creates a run-specific subdirectory under
self._session_root and stores information regarding run `fetches` and
`feed_dict.keys()` in the subdirectory.
Args:
fetches: Same as the `fetches` argument to `Session.run()`
feed_dict: Same as the `feed_dict` argument to `Session.run()`
Returns:
debug_urls: (`str` or `list` of `str`) file:// debug URLs to be used in
this `Session.run()` call.
|
github-repos
|
def get_class_weights(y, smooth_factor=0):
from collections import Counter
counter = Counter(y)
if (smooth_factor > 0):
p = (max(counter.values()) * smooth_factor)
for k in counter.keys():
counter[k] += p
majority = max(counter.values())
return {cls: float((majority / count)) for (cls, count) in counter.items()}
|
Returns the weights for each class based on the frequencies of the samples.
Args:
y: A list of true labels (the labels must be hashable).
smooth_factor: A factor that smooths extremely uneven weights.
Returns:
A dictionary with the weight for each class.
|
codesearchnet
|
def BuildFilterFindSpecs(self, artifact_definitions_path, custom_artifacts_path, knowledge_base_object, artifact_filter_names=None, filter_file_path=None):
environment_variables = knowledge_base_object.GetEnvironmentVariables()
find_specs = None
if artifact_filter_names:
logger.debug('building find specification based on artifacts: {0:s}'.format(', '.join(artifact_filter_names)))
artifacts_registry_object = BaseEngine.BuildArtifactsRegistry(artifact_definitions_path, custom_artifacts_path)
self._artifacts_filter_helper = artifact_filters.ArtifactDefinitionsFilterHelper(artifacts_registry_object, knowledge_base_object)
self._artifacts_filter_helper.BuildFindSpecs(artifact_filter_names, environment_variables=environment_variables)
if self._artifacts_filter_helper.registry_find_specs:
self._artifacts_filter_helper.BuildFindSpecs(self._WINDOWS_REGISTRY_FILES_ARTIFACT_NAMES, environment_variables=environment_variables)
find_specs = self._artifacts_filter_helper.file_system_find_specs
if (not find_specs):
raise errors.InvalidFilter('No valid file system find specifications were built from artifacts.')
elif filter_file_path:
logger.debug('building find specification based on filter file: {0:s}'.format(filter_file_path))
filter_file_object = filter_file.FilterFile(filter_file_path)
find_specs = filter_file_object.BuildFindSpecs(environment_variables=environment_variables)
if (not find_specs):
raise errors.InvalidFilter('No valid file system find specifications were built from filter file.')
return find_specs
|
Builds find specifications from artifacts or filter file if available.
Args:
artifact_definitions_path (str): path to artifact definitions file.
custom_artifacts_path (str): path to custom artifact definitions file.
knowledge_base_object (KnowledgeBase): knowledge base.
artifact_filter_names (Optional[list[str]]): names of artifact
definitions that are used for filtering file system and Windows
Registry key paths.
filter_file_path (Optional[str]): path of filter file.
Returns:
list[dfvfs.FindSpec]: find specifications for the file source type.
Raises:
InvalidFilter: if no valid FindSpecs are built.
|
codesearchnet
|
def convert_dt_time(duration, return_iter=False):
try:
days, hours, minutes, seconds = convert_timedelta(duration)
if return_iter:
return days, hours, minutes, seconds
if days > 0:
format_string = (
'{} day{}, {} hour{}'.format(
days, 's' if days != 1 else '', hours, 's' if hours != 1 else ''))
elif hours > 1:
format_string = (
'{} hour{}, {} minute{}'.format(
hours, 's' if hours != 1 else '', minutes, 's' if minutes != 1 else ''))
else:
format_string = (
'{} minute{}, {} sec{}'.format(
minutes, 's' if minutes != 1 else '', seconds, 's' if seconds != 1 else ''))
except AttributeError as e:
logger.exception(
'%s: Type mismatch when converting timedelta objects (Code: %s)' %
(inspect.stack()[0][3], str(e)))
except Exception as e:
logger.exception(
'%s: Unknown error when converting datetime objects (Code: %s)' %
(inspect.stack()[0][3], str(e)))
return format_string
|
Summary:
convert timedelta objects to human readable output
Args:
:duration (datetime.timedelta): time duration to convert
:return_iter (tuple): tuple containing time sequence
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers), OR
human readable, notated units | TYPE: string
|
juraj-google-style
|
def preds(self, nodeids=None):
if nodeids is None: nodeids = self._nodeids
_eps = self._eps
return [_eps[nid][1] for nid in nodeids]
|
Return the Pred objects for *nodeids*, or all Preds.
Args:
nodeids: an iterable of nodeids of predications to return
Preds from; if `None`, return all Preds
|
juraj-google-style
|
def dataflow_to_dataset(df, types):
assert isinstance(df, DataFlow), df
assert isinstance(types, (list, tuple)), types
df = MapData(df, (lambda dp: tuple(dp)))
df.reset_state()
ds = tf.data.Dataset.from_generator(df.get_data, tuple(types))
return ds
|
Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
dataset.
Args:
df (DataFlow): a dataflow which produces lists
types([tf.DType]): list of types
Returns:
(tf.data.Dataset)
|
codesearchnet
|
def get_entry_type(self, tag):
if tag.findParent().get('kind') in ['class', 'struct']:
return u'Method'
return super(functionTagProcessor, self).get_entry_type(tag)
|
Override that returns u'Method' for class/struct methods.
Override as necessary.
Args:
tag: A BeautifulSoup Tag for a function.
Returns:
If this is a class/struct method, returns u'Method', otherwise
returns the value from the inherited implementation of
get_entry_type (which should be u'Function').
|
juraj-google-style
|
def fill_memory_slot(memory, value, index):
mask = tf.to_float(tf.one_hot(index, tf.shape(memory)[0])[(:, None, None, None)])
fill_memory = (((1 - mask) * memory) + (mask * value[(None, ...)]))
return fill_memory
|
Fills the memory slot at a particular index with the given value.
Args:
memory: a 4-d tensor [memory_size, batch, length, channel] containing
the state of all steps
value: a 3-d tensor [batch, length, channel] as the sate
index: integer in [0, memory_size)
Returns:
filled memory
|
codesearchnet
|
def evalAsync(self, amplstatements, callback, **kwargs):
if self._langext is not None:
amplstatements = self._langext.translate(amplstatements, **kwargs)
def async_call():
self._lock.acquire()
try:
self._impl.eval(amplstatements)
self._errorhandler_wrapper.check()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback.run()
Thread(target=async_call).start()
|
Interpret the given AMPL statement asynchronously.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
callback: Callback to be executed when the statement has been
interpreted.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running.
|
juraj-google-style
|
def set(self, key, value):
data = self._load_file()
data[key] = value
self._save_file(data)
|
Set the value of a key
Args:
key (string): The key used to store this value
value (string): The value to store
|
juraj-google-style
|
def RegisterPlugin(cls, plugin_class):
plugin_name = plugin_class.NAME.lower()
if (plugin_name in cls._plugin_classes):
raise KeyError('Plugin class already set for name: {0:s}.'.format(plugin_class.NAME))
cls._plugin_classes[plugin_name] = plugin_class
|
Registers a plugin class.
The plugin classes are identified based on their lower case name.
Args:
plugin_class (type): class of the plugin.
Raises:
KeyError: if plugin class is already set for the corresponding name.
|
codesearchnet
|
def precipitable_water(self, value=999.0):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
'value {} need to be of type float '
'for field `precipitable_water`'.format(value))
self._precipitable_water = value
|
Corresponds to IDD Field `precipitable_water`
Args:
value (float): value for IDD Field `precipitable_water`
Unit: mm
Missing value: 999.0
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 value
|
juraj-google-style
|
def case(self, case_id=None):
cases = self.cases()
if case_id:
for case in cases:
if case.case_id == case_id:
return case
else:
if cases:
return cases[0]
return None
|
Return a Case object
If no case_id is given return one case
Args:
case_id (str): A case id
Returns:
case(Case): A Case object
|
juraj-google-style
|
def class_logit(layer, label):
def inner(T):
if isinstance(label, int):
class_n = label
else:
class_n = T('labels').index(label)
logits = T(layer)
logit = tf.reduce_sum(logits[(:, class_n)])
return logit
return inner
|
Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit.
|
codesearchnet
|
def configure_attributes(self, json_data):
env = boto3.session.Session(profile_name=self.env, region_name=self.region)
elbclient = env.client('elb')
elb_settings = self.properties['elb']
LOG.debug('Block ELB Settings Pre Configure Load Balancer Attributes:\n%s', pformat(elb_settings))
for job in json.loads(json_data)['job']:
load_balancer_attributes = {
'CrossZoneLoadBalancing': {
'Enabled': True
},
'AccessLog': {
'Enabled': False,
},
'ConnectionDraining': {
'Enabled': False,
},
'ConnectionSettings': {
'IdleTimeout': 60
}
}
if elb_settings.get('connection_draining_timeout'):
connection_draining_timeout = int(elb_settings['connection_draining_timeout'])
LOG.info('Applying Custom Load Balancer Connection Draining Timeout: %d', connection_draining_timeout)
load_balancer_attributes['ConnectionDraining'] = {
'Enabled': True,
'Timeout': connection_draining_timeout
}
if elb_settings.get('idle_timeout'):
idle_timeout = int(elb_settings['idle_timeout'])
LOG.info('Applying Custom Load Balancer Idle Timeout: %d', idle_timeout)
load_balancer_attributes['ConnectionSettings'] = {'IdleTimeout': idle_timeout}
if elb_settings.get('access_log'):
access_log_bucket_name = elb_settings['access_log']['bucket_name']
access_log_bucket_prefix = elb_settings['access_log']['bucket_prefix']
access_log_emit_interval = int(elb_settings['access_log']['emit_interval'])
LOG.info('Applying Custom Load Balancer Access Log: %s/%s every %d minutes', access_log_bucket_name,
access_log_bucket_prefix, access_log_emit_interval)
load_balancer_attributes['AccessLog'] = {
'Enabled': True,
'S3BucketName': access_log_bucket_name,
'EmitInterval': access_log_emit_interval,
'S3BucketPrefix': access_log_bucket_prefix
}
LOG.info('Applying Load Balancer Attributes')
LOG.debug('Load Balancer Attributes:\n%s', pformat(load_balancer_attributes))
elbclient.modify_load_balancer_attributes(
LoadBalancerName=self.app, LoadBalancerAttributes=load_balancer_attributes)
|
Configure load balancer attributes such as idle timeout, connection draining, etc
Args:
json_data (json): return data from ELB upsert
|
juraj-google-style
|
def get_features(self, tokenizer, max_length=None, pad_on_left=False, pad_token=0, mask_padding_with_zero=True, return_tensors=None):
if max_length is None:
max_length = tokenizer.max_len
label_map = {label: i for i, label in enumerate(self.labels)}
all_input_ids = []
for ex_index, example in enumerate(self.examples):
if ex_index % 10000 == 0:
logger.info(f'Tokenizing example {ex_index}')
input_ids = tokenizer.encode(example.text_a, add_special_tokens=True, max_length=min(max_length, tokenizer.max_len))
all_input_ids.append(input_ids)
batch_length = max((len(input_ids) for input_ids in all_input_ids))
features = []
for ex_index, (input_ids, example) in enumerate(zip(all_input_ids, self.examples)):
if ex_index % 10000 == 0:
logger.info(f'Writing example {ex_index}/{len(self.examples)}')
attention_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
padding_length = batch_length - len(input_ids)
if pad_on_left:
input_ids = [pad_token] * padding_length + input_ids
attention_mask = [0 if mask_padding_with_zero else 1] * padding_length + attention_mask
else:
input_ids = input_ids + [pad_token] * padding_length
attention_mask = attention_mask + [0 if mask_padding_with_zero else 1] * padding_length
if len(input_ids) != batch_length:
raise ValueError(f'Error with input length {len(input_ids)} vs {batch_length}')
if len(attention_mask) != batch_length:
raise ValueError(f'Error with input length {len(attention_mask)} vs {batch_length}')
if self.mode == 'classification':
label = label_map[example.label]
elif self.mode == 'regression':
label = float(example.label)
else:
raise ValueError(self.mode)
if ex_index < 5 and self.verbose:
logger.info('*** Example ***')
logger.info(f'guid: {example.guid}')
logger.info(f'input_ids: {' '.join([str(x) for x in input_ids])}')
logger.info(f'attention_mask: {' '.join([str(x) for x in attention_mask])}')
logger.info(f'label: {example.label} (id = {label})')
features.append(InputFeatures(input_ids=input_ids, attention_mask=attention_mask, label=label))
if return_tensors is None:
return features
elif return_tensors == 'tf':
if not is_tf_available():
raise RuntimeError("return_tensors set to 'tf' but TensorFlow 2.0 can't be imported")
import tensorflow as tf
def gen():
for ex in features:
yield ({'input_ids': ex.input_ids, 'attention_mask': ex.attention_mask}, ex.label)
dataset = tf.data.Dataset.from_generator(gen, ({'input_ids': tf.int32, 'attention_mask': tf.int32}, tf.int64), ({'input_ids': tf.TensorShape([None]), 'attention_mask': tf.TensorShape([None])}, tf.TensorShape([])))
return dataset
elif return_tensors == 'pt':
if not is_torch_available():
raise RuntimeError("return_tensors set to 'pt' but PyTorch can't be imported")
import torch
from torch.utils.data import TensorDataset
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
if self.mode == 'classification':
all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
elif self.mode == 'regression':
all_labels = torch.tensor([f.label for f in features], dtype=torch.float)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_labels)
return dataset
else:
raise ValueError("return_tensors should be one of 'tf' or 'pt'")
|
Convert examples in a list of `InputFeatures`
Args:
tokenizer: Instance of a tokenizer that will tokenize the examples
max_length: Maximum example length
pad_on_left: If set to `True`, the examples will be padded on the left rather than on the right (default)
pad_token: Padding token
mask_padding_with_zero: If set to `True`, the attention mask will be filled by `1` for actual values
and by `0` for padded values. If set to `False`, inverts it (`1` for padded values, `0` for actual
values)
Returns:
If the `examples` input is a `tf.data.Dataset`, will return a `tf.data.Dataset` containing the
task-specific features. If the input is a list of `InputExamples`, will return a list of task-specific
`InputFeatures` which can be fed to the model.
|
github-repos
|
def display_task_progress(self, instance, project, region, request_id=None, user=None, poll_interval=60):
total_completed = 0
while True:
task_results = self.client.get_task_data(instance, project, region, request_id=request_id, user=user)
tasks = {task['id']: task for task in task_results}
completed_tasks = set()
pending_tasks = set()
for task in tasks.values():
if (task.get('successful') is not None):
completed_tasks.add(task['id'])
else:
pending_tasks.add(task['id'])
if ((len(completed_tasks) > total_completed) or (not completed_tasks)):
total_completed = len(completed_tasks)
print('Task status update (completed: {0:d} | pending: {1:d})'.format(len(completed_tasks), len(pending_tasks)))
print('Completed tasks:')
for task_id in completed_tasks:
self._print_task_data(tasks[task_id])
print('Pending tasks:')
for task_id in pending_tasks:
self._print_task_data(tasks[task_id])
if ((len(completed_tasks) == len(task_results)) and completed_tasks):
print('All {0:d} Tasks completed'.format(len(task_results)))
return
time.sleep(poll_interval)
|
Displays the overall progress of tasks in a Turbinia job.
Args:
instance (string): The name of the Turbinia instance
project (string): The project containing the disk to process
region (string): Region where turbinia is configured.
request_id (string): The request ID provided by Turbinia.
user (string): The username to filter tasks by.
poll_interval (int): The interval at which to poll for new results.
|
codesearchnet
|
def VerifyStructure(self, parser_mediator, line):
try:
structure = self._LINE.parseString(line)
except pyparsing.ParseException:
logger.debug('Not a SkyDrive old log file')
return False
(day_of_month, month, year, hours, minutes, seconds, milliseconds) = structure.date_time
time_elements_tuple = (year, month, day_of_month, hours, minutes, seconds, milliseconds)
try:
dfdatetime_time_elements.TimeElementsInMilliseconds(time_elements_tuple=time_elements_tuple)
except ValueError:
logger.debug('Not a SkyDrive old log file, invalid date and time: {0!s}'.format(structure.date_time))
return False
return True
|
Verify that this file is a SkyDrive old log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not.
|
codesearchnet
|
def for_executor(cls, executor: Optional[Executor]) -> 'Subsystem':
if isinstance(executor, ThreadPoolExecutor):
return _ThreadingSubsystem(executor)
elif executor is None:
return _AsyncioSubsystem()
else:
raise TypeError(executor)
|
Return a subsystem based on the given executor. If ``executor`` is
None, use :mod:`asyncio`. If ``executor`` is a
:class:`concurrent.futures.ThreadPoolExecutor`, use :mod:`threading`.
Args:
executor: The executor in use, if any.
|
juraj-google-style
|
def start(self, hostname=None, port=None, templates_path=None):
self.hostname = hostname if hostname else "localhost"
if port:
self.port = port
elif not self.port:
self.port = unused_port(self.hostname)
if templates_path:
self.loaders.insert(0, jinja2.FileSystemLoader(templates_path))
self._set_loaders()
self.setup_routes()
self.runner = aioweb.AppRunner(self.app)
return self.agent.submit(start_server_in_loop(self.runner, self.hostname, self.port, self.agent))
|
Starts the web interface.
Args:
hostname (str, optional): host name to listen from. (Default value = None)
port (int, optional): port to listen from. (Default value = None)
templates_path (str, optional): path to look for templates. (Default value = None)
|
juraj-google-style
|
def _call_and_return_none_on_error(func: Callable[[], NotNoneT], error_msg: str) -> Optional[NotNoneT]:
try:
return func()
except Exception as ex:
traceback.print_exception(ex)
logging.error(error_msg)
return None
|
Calls `func` and returns `None` on error.
This is used to gracefully return the 'error status' represented as `None`, as
raising exceptions from `PyFunctionLibrary` methods crashes the program.
Args:
func: The function to run. The function should be a callable returning a
non-None value.
error_msg: The error message to log upon error. Used for debugging purposes.
Returns:
`None` if the function raises an exception. The return value of `func`
otherwise.
|
github-repos
|
def get_next_as_optional(iterator):
return iterator.get_next_as_optional()
|
Returns a `tf.experimental.Optional` with the next element of the iterator.
If the iterator has reached the end of the sequence, the returned
`tf.experimental.Optional` will have no value.
Args:
iterator: A `tf.data.Iterator`.
Returns:
A `tf.experimental.Optional` object which either contains the next element
of the iterator (if it exists) or no value.
|
github-repos
|
def segs(self, word):
return [m.group('all') for m in self.seg_regex.finditer(word)]
|
Returns a list of segments from a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
list: list of strings corresponding to segments found in `word`
|
codesearchnet
|
def alt40fms(msg):
d = hex2bin(data(msg))
if d[13] == '0':
return None
alt = bin2int(d[14:26]) * 16
return alt
|
Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
|
juraj-google-style
|
def __init__(self, regularizer=None, activity_regularizer=None, use_operator=False, var_name='v', **kwargs):
self._regularizer = regularizer
if isinstance(regularizer, dict):
self._regularizer = regularizers.deserialize(regularizer, custom_objects=globals())
self._activity_regularizer = activity_regularizer
if isinstance(activity_regularizer, dict):
self._activity_regularizer = regularizers.deserialize(activity_regularizer, custom_objects=globals())
self._use_operator = use_operator
self._var_name = var_name
super(MultiplyLayer, self).__init__(activity_regularizer=self._activity_regularizer, **kwargs)
|
Initializes the MultiplyLayer.
Args:
regularizer: The weight regularizer on the scalar variable.
activity_regularizer: The activity regularizer.
use_operator: If True, add using the * operator. If False, add using
tf.multiply.
var_name: The name of the variable. It can be useful to pass a name other
than 'v', to test having the attribute name (self.v) being different
from the variable name.
**kwargs: Passed to AssertTypeLayer constructor.
|
github-repos
|
def create(self, params):
sh_id = params.get('id', str(uuid4()))
if sh_id in self:
raise ShardedClusterError(
"Sharded cluster with id %s already exists." % sh_id)
params['id'] = sh_id
cluster = ShardedCluster(params)
self[cluster.id] = cluster
return cluster.id
|
create new ShardedCluster
Args:
params - dictionary with specific params for instance
Return cluster_id
where cluster_id - id which can use to take the cluster from servers collection
|
juraj-google-style
|
def set_hook_data(self, key, data):
if (not isinstance(data, collections.Mapping)):
raise ValueError(('Hook (key: %s) data must be an instance of collections.Mapping (a dictionary for example).' % key))
if (key in self.hook_data):
raise KeyError('Hook data for key %s already exists, each hook must have a unique data_key.', key)
self.hook_data[key] = data
|
Set hook data for the given key.
Args:
key(str): The key to store the hook data in.
data(:class:`collections.Mapping`): A dictionary of data to store,
as returned from a hook.
|
codesearchnet
|
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None, globalmacroids=None, globalmacro=False, **kwargs):
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {'output': 'extend', 'filter': {}}
if macro:
if isinstance(macro, dict):
macro = (('{' + six.text_type(macro.keys()[0])) + '}')
if ((not macro.startswith('{')) and (not macro.endswith('}'))):
macro = (('{' + macro) + '}')
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return (ret['result'] if ret['result'] else False)
else:
raise KeyError
except KeyError:
return ret
|
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
|
codesearchnet
|
def dump(self, format='ttl'):
return self.rdf.graph.serialize(format=format).decode('utf-8')
|
Convenience method to return RDF data for resource,
optionally selecting serialization format.
Inspired by .dump from Samvera.
Args:
format (str): expecting serialization formats accepted by rdflib.serialization(format=)
|
codesearchnet
|
def realtime(widget, url_name=None, url_regex=None, time_interval=None):
if not hasattr(widget, 'get_updated_content'):
raise AttributeError('Widget %s must implement get_updated_content '
'method.' % widget)
elif not callable(widget.get_updated_content):
raise ValueError('get_updated_content in widget %s is not callable'
% widget)
if url_name is None:
if getattr(widget, 'url_name', None) is not None:
url_name = widget.url_name
else:
url_name = widget.__class__.__name__
if url_name in [w.url_name for w in REALTIME_WIDGETS]:
raise ValueError('URL name %s is already used by another '
'real time widget.' % url_name)
if url_regex is None:
if getattr(widget, 'url_regex', None) is not None:
url_regex = widget.url_regex
else:
url_regex = sha256(url_name.encode('utf-8'))
url_regex = url_regex.hexdigest()[:32]
url_regex = 'realtime/' + url_regex
if url_regex in [w.url_regex for w in REALTIME_WIDGETS]:
raise ValueError('URL regex %s is already used by another '
'real time widget.' % url_regex)
if time_interval is None:
if getattr(widget, 'time_interval', None) is not None:
time_interval = widget.time_interval
else:
time_interval = app_settings.default_time_interval
from django.views.generic import View
from braces.views import AjaxResponseMixin, JSONResponseMixin
class PartialResponse(JSONResponseMixin, AjaxResponseMixin, View):
def get_data(self):
return widget.get_updated_content()
def get(self, request, *args, **kwargs):
return self.get_ajax(request, *args, **kwargs)
def get_ajax(self, request, *args, **kwargs):
return self.render_json_response(self.get_data())
PartialResponse.url_name = url_name
PartialResponse.url_regex = url_regex
PartialResponse.time_interval = time_interval
REALTIME_WIDGETS.append(PartialResponse)
if not hasattr(widget, 'url_name'):
widget.url_name = url_name
if not hasattr(widget, 'url_regex'):
widget.url_regex = url_regex
if not hasattr(widget, 'time_interval'):
widget.time_interval = time_interval
return widget
|
Return a widget as real-time.
Args:
widget (Widget): the widget to register and return as real-time.
url_name (str): the URL name to call to get updated content.
url_regex (regex): the URL regex to be matched.
time_interval (int): the interval of refreshment in milliseconds.
Returns:
Widget: the "real-timed" widget.
|
juraj-google-style
|
def discount_rate(self, date: Optional[types.DateTensor]=None, time: Optional[types.FloatTensor]=None, context=None) -> tf.Tensor:
pass
|
Returns the discount rates to a specified set of dates.
Args:
date: A `DateTensor` specifying the dates at which to evaluate the
discount rates. The function expects either `date` or `time` to be
specified.
time: A real `Tensor` specifying the times at which to evaluate the
discount rates. The function expects either `date` or `time` to be
specified.
context: The context object, e.g., curve_type.
Returns:
A `Tensor` of the same shape as `dates` with the corresponding discount
rates.
|
github-repos
|
def seek(self, offset, whence=os.SEEK_SET):
if not self._is_open:
raise IOError('Not opened.')
if self._current_offset < 0:
raise IOError(
'Invalid current offset: {0:d} value less than zero.'.format(
self._current_offset))
if whence == os.SEEK_CUR:
offset += self._current_offset
elif whence == os.SEEK_END:
if self._decoded_stream_size is None:
self._decoded_stream_size = self._GetDecodedStreamSize()
if self._decoded_stream_size is None:
raise IOError('Invalid decoded stream size.')
offset += self._decoded_stream_size
elif whence != os.SEEK_SET:
raise IOError('Unsupported whence.')
if offset < 0:
raise IOError('Invalid offset value less than zero.')
if offset != self._current_offset:
self._current_offset = offset
self._realign_offset = True
|
Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek to.
whence (Optional(int)): value that indicates whether offset is an absolute
or relative position within the file.
Raises:
IOError: if the seek failed.
OSError: if the seek failed.
|
juraj-google-style
|
def _CanSkipContentExtraction(self, file_entry):
location = getattr(file_entry.path_spec, 'location', None)
if not location:
return False
data_stream_name = getattr(file_entry.path_spec, 'data_stream', None)
if data_stream_name:
return False
file_system = file_entry.GetFileSystem()
path_segments = file_system.SplitPath(location)
if not path_segments:
return False
if self._CHROME_CACHE_DATA_FILE_RE.match(path_segments[-1]):
location_segments = path_segments[:-1]
location_segments.append('index')
location = file_system.JoinPath(location_segments)
index_path_spec = path_spec_factory.Factory.NewPathSpec(
file_entry.type_indicator, location=location,
parent=file_entry.path_spec.parent)
if file_system.FileEntryExistsByPathSpec(index_path_spec):
return True
elif self._FIREFOX_CACHE_DATA_FILE_RE.match(path_segments[-1]):
location_segments = path_segments[:-4]
location_segments.append('_CACHE_MAP_')
location = file_system.JoinPath(location_segments)
cache_map_path_spec = path_spec_factory.Factory.NewPathSpec(
file_entry.type_indicator, location=location,
parent=file_entry.path_spec.parent)
if file_system.FileEntryExistsByPathSpec(cache_map_path_spec):
return True
elif self._FIREFOX_CACHE2_DATA_FILE_RE.match(path_segments[-1]):
location_segments = path_segments[:-2]
location_segments.append('index')
location = file_system.JoinPath(location_segments)
index_path_spec = path_spec_factory.Factory.NewPathSpec(
file_entry.type_indicator, location=location,
parent=file_entry.path_spec.parent)
if file_system.FileEntryExistsByPathSpec(index_path_spec):
return True
elif len(path_segments) == 1 and path_segments[0].lower() in (
'hiberfil.sys', 'pagefile.sys', 'swapfile.sys'):
return True
return False
|
Determines if content extraction of a file entry can be skipped.
Args:
file_entry (dfvfs.FileEntry): file entry of which to determine content
extraction can be skipped.
Returns:
bool: True if content extraction can be skipped.
|
juraj-google-style
|
def _filter_var(self, node, var):
bindings = var.Bindings(node) if len(var.bindings) > 1 else var.bindings
if not bindings:
return None
if len(bindings) == len(var.bindings) and (not any((isinstance(b.data, abstract.TypeParameterInstance) for b in bindings))):
return var
ret = self.ctx.program.NewVariable()
for binding in bindings:
val = binding.data
if isinstance(val, abstract.TypeParameterInstance):
var = val.instance.get_instance_type_parameter(val.name)
var_bindings = var.Bindings(node)
if var_bindings:
bindings.extend(var_bindings)
elif val.param.constraints or val.param.bound:
ret.PasteVariable(val.param.instantiate(node))
else:
ret.AddBinding(self.ctx.convert.empty, [], node)
else:
ret.AddBinding(val, {binding}, node)
if ret.bindings:
return ret
else:
return None
|
Filter the variable by the node.
Filters the variable data, including recursively expanded type parameter
instances, by visibility at the node. A type parameter instance needs to be
filtered at the moment of access because its value may change later.
Args:
node: The current node.
var: A variable to filter.
Returns:
The filtered variable.
|
github-repos
|
def _resolve_path(obj, path=None):
if path:
for attr_name in path.split('__'):
obj = getattr(obj, attr_name)
return obj
|
Resolve django-like path eg. object2__object3 for object
Args:
obj: The object the view is displaying.
path (str, optional): Description
Returns:
A oject at end of resolved path
|
juraj-google-style
|
def replace_nones(list_, repl=(- 1)):
repl_list = [(repl if (item is None) else (replace_nones(item, repl) if isinstance(item, list) else item)) for item in list_]
return repl_list
|
r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> list_ = [None, 0, 1, 2]
>>> repl = -1
>>> # execute function
>>> repl_list = replace_nones(list_, repl)
>>> # verify results
>>> result = str(repl_list)
>>> print(result)
[-1, 0, 1, 2]
|
codesearchnet
|
def __init__(self, replicaset=None, ssl=None, login=None, password=None,
ca_cert=None, certfile=None, keyfile=None,
keyfile_passphrase=None, crlfile=None, **kwargs):
super().__init__(**kwargs)
self.replicaset = replicaset or bigchaindb.config['database'].get('replicaset')
self.ssl = ssl if ssl is not None else bigchaindb.config['database'].get('ssl', False)
self.login = login or bigchaindb.config['database'].get('login')
self.password = password or bigchaindb.config['database'].get('password')
self.ca_cert = ca_cert or bigchaindb.config['database'].get('ca_cert', None)
self.certfile = certfile or bigchaindb.config['database'].get('certfile', None)
self.keyfile = keyfile or bigchaindb.config['database'].get('keyfile', None)
self.keyfile_passphrase = keyfile_passphrase or bigchaindb.config['database'].get('keyfile_passphrase', None)
self.crlfile = crlfile or bigchaindb.config['database'].get('crlfile', None)
|
Create a new Connection instance.
Args:
replicaset (str, optional): the name of the replica set to
connect to.
**kwargs: arbitrary keyword arguments provided by the
configuration's ``database`` settings
|
juraj-google-style
|
def report_sink_lineage(path):
FileSystems.get_filesystem(path).report_lineage(path, Lineage.sinks())
|
Report sink :class:`~apache_beam.metrics.metric.Lineage`.
Args:
path: string path to be reported.
|
github-repos
|
def _ParseEntry(self, key, val):
if (key in self._repeated):
setting = self.section.setdefault(key, [])
setting.extend(val)
else:
self.section.setdefault(key, val)
|
Adds an entry for a configuration setting.
Args:
key: The name of the setting.
val: The value of the setting.
|
codesearchnet
|
def cumulative_distribution(self, X, U=0):
self.check_fit()
low_bounds = self.model.dataset.mean() - (5 * self.model.dataset.std())
return self.model.integrate_box_1d(low_bounds, X) - U
|
Computes the integral of a 1-D pdf between two bounds
Args:
X(float): a datapoint.
U(float): cdf value in [0,1], only used in get_ppf
Returns:
float: estimated cumulative distribution.
|
juraj-google-style
|
def dense_shape_and_type(matrix):
if not isinstance(matrix, tensor_lib.Tensor):
raise TypeError('matrix should be a tensor, but saw: %s' % (matrix,))
if matrix.dtype != dtypes.variant:
raise TypeError('expected matrix to be type tf.variant, but saw: %s' % (matrix.dtype,))
handle_data = _get_handle_data(matrix)
if not handle_data or not handle_data.is_set:
raise ValueError('matrix has missing handle data: %s' % (matrix,))
if len(handle_data.shape_and_type) != 1:
raise ValueError("len(matrix.handle_data.shape_and_type) != 1: '%s'" % (handle_data.shape_and_type,))
return DenseShapeAndType(tensor_shape.TensorShape(handle_data.shape_and_type[0].shape), dtypes.DType(handle_data.shape_and_type[0].dtype))
|
Get dense shape and dtype of the tf.Tensor containing the matrix.
Args:
matrix: A `tf.Tensor` of type `tf.variant` storing a sparse matrix.
Returns:
An instance of `ShapeAndType` with properties `shape` (a `tf.TensorShape`)
and `dtype` (a `tf.DType`).
Raises:
TypeError: if `matrix` is not a tensor or its dtype is not variant.
ValueError: if `matrix` lacks static handle data containing the dense
shape and dtype.
|
github-repos
|
def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting lrelu ...')
if (names == 'short'):
tf_name = ('lRELU' + random_string(3))
elif (names == 'keep'):
tf_name = w_name
else:
tf_name = (w_name + str(random.random()))
leakyrelu = keras.layers.LeakyReLU(alpha=params['alpha'], name=tf_name)
layers[scope_name] = leakyrelu(layers[inputs[0]])
|
Convert leaky relu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
|
codesearchnet
|
def main(params=None):
if params == None:
parser = getParser()
args = parser.parse_args(params)
else:
args = params
print(general.title(banner.text))
extraWords = args.extra_words
try:
if args.name == None and args.surname1 == None and args.surname2 == None and args.city == None and args.country == None and args.year == None:
print("\nCollecting information about the profile")
print("----------------------------------------\n")
args.name = raw_input(general.emphasis("Insert a name: ".ljust(35, " "))).replace(' ','')
args.surname1 = raw_input(general.emphasis("Insert the first surname: ".ljust(35, " "))).replace(' ','')
args.surname2 = raw_input(general.emphasis("Insert the second surname: ".ljust(35, " "))).replace(' ','')
args.year = raw_input(general.emphasis("Insert a year (e. g.: birthyear): ".ljust(35, " "))).replace(' ','')
args.city = raw_input(general.emphasis("Insert a city: ".ljust(35, " "))).replace(' ','')
args.country = raw_input(general.emphasis("Insert a country: ".ljust(35, " "))).replace(' ','')
if args.extra_words == []:
print("\nAdditional transformations to be added")
print("--------------------------------------\n")
inputText = raw_input(general.emphasis("Extra words to add (',' separated): ".ljust(35, " "))).replace(' ','')
extraWords += inputText.lower().split(',')
except KeyboardInterrupt:
print("\n\nThe user manually aborted the program. Exiting...")
sys.exit(2)
lista=[]
print("\nInput data:")
print("-----------\n")
if args.name != "":
print("Name: ".ljust(20, " ") + args.name)
if args.surname1 != "":
print("First Surname: ".ljust(20, " ") + args.surname1)
if args.surname2 != "":
print("Second Surname: ".ljust(20, " ") + args.surname2)
if args.year != "":
print("Year: ".ljust(20, " ") + args.year)
if args.city != "":
print("City: ".ljust(20, " ") + args.city)
if args.country != "":
print("Country: ".ljust(20, " ") + args.country)
aliases = generate(
name=args.name,
surname1=args.surname1,
surname2=args.surname2,
city=args.city,
country=args.country,
year=args.year,
useNumbers=args.numbers,
useCommonWords=args.common_words,
useLeet=args.leet,
useLocales=args.locales,
extraWords=extraWords
)
print("Writing the results onto the file:\n\t" + general.emphasis(args.outputFile))
oF=open(args.outputFile, "w")
for l in aliases:
oF.write(l+"\n")
oF.close()
print(banner.footer)
|
Main function to launch alias_generator.
Args:
-----
params: A list with the parameters as grabbed by the terminal. It is
None when this is called by an entry_point. If it is called by osrf
the data is already parsed.
|
juraj-google-style
|
def diff_text2(self, diffs):
text = []
for (op, data) in diffs:
if op != self.DIFF_DELETE:
text.append(data)
return "".join(text)
|
Compute and return the destination text (all equalities and insertions).
Args:
diffs: Array of diff tuples.
Returns:
Destination text.
|
juraj-google-style
|
def datetimeobj_YmdHMS(value):
i = int(value)
S = i
M = S
H = M
d = H
m = d
Y = m
return datetime.datetime(
Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, tzinfo=TZ_GMT
)
|
Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime object.
Raises:
ValueError: If timestamp is invalid.
Note: The timezone is assumed to be UTC/GMT.
|
juraj-google-style
|
def zip_ll(data, means, M):
genes, cells = data.shape
clusters = means.shape[1]
ll = np.zeros((cells, clusters))
d0 = (data==0)
d1 = (data>0)
for i in range(clusters):
means_i = np.tile(means[:,i], (cells, 1))
means_i = means_i.transpose()
L_i = np.tile(M[:,i], (cells, 1))
L_i = L_i.transpose()
ll_0 = np.log(L_i + (1 - L_i)*np.exp(-means_i))
ll_0 = np.where((L_i==0) & (means_i==0), -means_i, ll_0)
ll_1 = np.log(1 - L_i) + xlogy(data, means_i) - means_i
ll_0 = np.where(d0, ll_0, 0.0)
ll_1 = np.where(d1, ll_1, 0.0)
ll[:,i] = np.sum(ll_0 + ll_1, 0)
return ll
|
Calculates the zero-inflated Poisson log-likelihood.
Args:
data (array): genes x cells
means (array): genes x k
M (array): genes x k - this is the zero-inflation parameter.
Returns:
cells x k array of log-likelihood for each cell/cluster pair.
|
juraj-google-style
|
def text(self, x, y, text):
for i, char in enumerate(text):
self.point(x + i, y, char)
|
Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed.
|
juraj-google-style
|
def git_ls_remote(self, uri, ref):
logger.debug('Invoking git to retrieve commit id for repo %s...', uri)
lsremote_output = subprocess.check_output(['git', 'ls-remote', uri, ref])
if (b'\t' in lsremote_output):
commit_id = lsremote_output.split(b'\t')[0]
logger.debug('Matching commit id found: %s', commit_id)
return commit_id
else:
raise ValueError(('Ref "%s" not found for repo %s.' % (ref, uri)))
|
Determine the latest commit id for a given ref.
Args:
uri (string): git URI
ref (string): git ref
Returns:
str: A commit id
|
codesearchnet
|
def value_splitter(self, reference, prop, value, mode):
items = []
if (mode == 'json-list'):
try:
items = json.loads(value)
except json.JSONDecodeError as e:
print(value)
msg = "Reference '{ref}' raised JSON decoder error when splitting values from '{prop}': {err}'"
raise SerializerError(msg.format(ref=reference, prop=prop, err=e))
elif (len(value) > 0):
items = value.split(' ')
return items
|
Split a string into a list items.
Default behavior is to split on white spaces.
Arguments:
reference (string): Reference name used when raising possible
error.
prop (string): Property name used when raising possible error.
value (string): Property value to split.
mode (string): Splitter mode. Default should come from
``ManifestSerializer._DEFAULT_SPLITTER``.
Available splitter are:
* ``white-space``: Simply split a string on white spaces;
* ``json-list``: Assume the string is a JSON list to parse;
Returns:
list:
|
codesearchnet
|
def append_transformation(self, transformation, return_alternatives=False, clear_redo=True):
if clear_redo:
self._undone = []
if (return_alternatives and transformation.is_one_to_many):
ranked_list = transformation.apply_transformation(self.final_structure, return_ranked_list=return_alternatives)
input_structure = self.final_structure.as_dict()
alts = []
for x in ranked_list[1:]:
s = x.pop('structure')
actual_transformation = x.pop('transformation', transformation)
hdict = actual_transformation.as_dict()
hdict['input_structure'] = input_structure
hdict['output_parameters'] = x
self.final_structure = s
d = self.as_dict()
d['history'].append(hdict)
d['final_structure'] = s.as_dict()
alts.append(TransformedStructure.from_dict(d))
x = ranked_list[0]
s = x.pop('structure')
actual_transformation = x.pop('transformation', transformation)
hdict = actual_transformation.as_dict()
hdict['input_structure'] = self.final_structure.as_dict()
hdict['output_parameters'] = x
self.history.append(hdict)
self.final_structure = s
return alts
else:
s = transformation.apply_transformation(self.final_structure)
hdict = transformation.as_dict()
hdict['input_structure'] = self.final_structure.as_dict()
hdict['output_parameters'] = {}
self.history.append(hdict)
self.final_structure = s
|
Appends a transformation to the TransformedStructure.
Args:
transformation: Transformation to append
return_alternatives: Whether to return alternative
TransformedStructures for one-to-many transformations.
return_alternatives can be a number, which stipulates the
total number of structures to return.
clear_redo: Boolean indicating whether to clear the redo list.
By default, this is True, meaning any appends clears the
history of undoing. However, when using append_transformation
to do a redo, the redo list should not be cleared to allow
multiple redos.
|
codesearchnet
|
def concatenate(self, other):
other = as_shape(other)
if self.dims is None or other.dims is None:
return unknown_shape()
else:
return TensorShape(self.dims + other.dims)
|
Returns the concatenation of the dimension in `self` and `other`.
*N.B.* If either `self` or `other` is completely unknown,
concatenation will discard information about the other shape. In
future, we might support concatenation that preserves this
information for use with slicing.
Args:
other: Another `TensorShape`.
Returns:
A `TensorShape` whose dimensions are the concatenation of the
dimensions in `self` and `other`.
|
github-repos
|
def _bbox(nodes):
(left, bottom) = np.min(nodes, axis=1)
(right, top) = np.max(nodes, axis=1)
return (left, right, bottom, top)
|
Get the bounding box for set of points.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): A set of points.
Returns:
Tuple[float, float, float, float]: The left, right,
bottom and top bounds for the box.
|
codesearchnet
|
def _assert_same_base_type(items, expected_type=None):
original_expected_type = expected_type
mismatch = False
for item in items:
if (item is not None):
item_type = base_dtype(item.dtype)
if (not expected_type):
expected_type = item_type
elif (expected_type != item_type):
mismatch = True
break
if mismatch:
expected_type = original_expected_type
original_item_str = None
get_name = (lambda x: (x.name if hasattr(x, 'name') else str(x)))
for item in items:
if (item is not None):
item_type = base_dtype(item.dtype)
if (not expected_type):
expected_type = item_type
original_item_str = get_name(item)
elif (expected_type != item_type):
raise ValueError('{}, type={}, must be of the same type ({}){}.'.format(get_name(item), item_type, expected_type, (' as {}'.format(original_item_str) if original_item_str else '')))
return expected_type
else:
return expected_type
|
r"""Asserts all items are of the same base type.
Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected type. If not specified, assert all items are
of the same base type.
Returns:
Validated type, or none if neither expected_type nor items provided.
Raises:
ValueError: If any types do not match.
|
codesearchnet
|
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
return_df = pd.merge(df_reset_index, other_reset_index, how='inner', left_on=df_reset_index.columns.values.tolist(), right_on=df_reset_index.columns.values.tolist()).set_index(index_cols)
return_df.index.names = df_index_names
return_df = return_df.drop_duplicates(keep=keep)
return return_df
else:
return_df = pd.merge(df, other, how='inner', left_on=df.columns.values.tolist(), right_on=df.columns.values.tolist())
return_df = return_df.drop_duplicates(keep=keep)
return return_df
|
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`).
keep (str): Indicates which duplicate should be kept. Options are `'first'`
and `'last'`.
|
codesearchnet
|
def wait(timeout=None, flush=True):
if (timeout is not None):
timeout = (timeout + _time.clock())
while True:
if _eventQueue:
return _eventQueue.pop(0)
if flush:
_tdl.flush()
if (timeout and (_time.clock() >= timeout)):
return None
_time.sleep(0.001)
_processEvents()
|
Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`tdl.flush` will be made before
listening for events.
Returns: Type[Event]: An event, or None if the function
has timed out.
Anything added via :any:`push` will also be returned.
|
codesearchnet
|
def rescale(self, image: 'torch.Tensor', scale: float, offset: Optional[bool]=True, **kwargs) -> 'torch.Tensor':
rescaled_image = image * scale
if offset:
rescaled_image -= 1
return rescaled_image
|
Rescale an image by a scale factor.
If `offset` is `True`, the image has its values rescaled by `scale` and then offset by 1. If `scale` is
1/127.5, the image is rescaled between [-1, 1].
image = image * scale - 1
If `offset` is `False`, and `scale` is 1/255, the image is rescaled between [0, 1].
image = image * scale
Args:
image (`torch.Tensor`):
Image to rescale.
scale (`float`):
The scaling factor to rescale pixel values by.
offset (`bool`, *optional*):
Whether to scale the image in both negative and positive directions.
Returns:
`torch.Tensor`: The rescaled image.
|
github-repos
|
def get_variable(mesh, name, shape, dtype=tf.float32, master_dtype=None, slice_dtype=None, activation_dtype=None, initializer=None, trainable=True, **kwargs):
if (dtype is None):
dtype = VariableDType(master_dtype, slice_dtype, activation_dtype)
elif isinstance(dtype, tf.DType):
dtype = VariableDType((master_dtype or dtype), (slice_dtype or dtype), (activation_dtype or dtype))
elif (not isinstance(dtype, VariableDType)):
raise ValueError('dtype should be a tf.dtype or a mtf.VariableDType')
scope_name = tf.get_variable_scope().name
if scope_name:
full_name = ((scope_name + '/') + name)
else:
full_name = name
if (full_name in mesh.graph.name_to_variable):
var = mesh.graph.name_to_variable[full_name]
else:
var = Variable(mesh, name, convert_to_shape(shape), dtype, initializer, trainable, **kwargs)
if (var.name != full_name):
raise ValueError(('Expected var.name == full_name. %s vs %s' % (var.name, full_name)))
mesh.graph.name_to_variable[full_name] = var
return var.outputs[0]
|
Create a new variable or retrieve an already-created one.
Args:
mesh: a Mesh
name: a string (uses the existing tf.variable_scope())
shape: a Shape
dtype: a VariableDType or a tf.DType
master_dtype: an optional tf.DType (deprecated - use dtype arg)
slice_dtype: an optional tf.DType (deprecated - use dtype arg)
activation_dtype: an optional tf.DType (deprecated - use dtype arg)
initializer: an optional tf initializer function
trainable: a boolean
**kwargs: additional keyword arguments to tf.get_variable
Returns:
a Tensor with the given shape and dtype equal to dtype.activation_dtype
|
codesearchnet
|
def incrementKeySequenceCounter(self, iIncrementValue=1):
print '%s call incrementKeySequenceCounter' % self.port
print iIncrementValue
currentKeySeq = ''
try:
currentKeySeq = self.getKeySequenceCounter()
keySequence = int(currentKeySeq, 10) + iIncrementValue
print keySequence
return self.setKeySequenceCounter(keySequence)
except Exception, e:
ModuleHelper.WriteIntoDebugLogger('incrementKeySequenceCounter() Error: ' + str(e))
|
increment the key sequence with a given value
Args:
iIncrementValue: specific increment value to be added
Returns:
True: successful to increment the key sequence with a given value
False: fail to increment the key sequence with a given value
|
juraj-google-style
|
def __init__(self, rs_params):
self.server_map = {}
self.auth_key = rs_params.get('auth_key', None)
self.login = rs_params.get('login', '')
self.auth_source = rs_params.get('authSource', 'admin')
self.password = rs_params.get('password', '')
self.admin_added = False
self.repl_id = rs_params.get('id', None) or str(uuid4())
self._version = rs_params.get('version')
self.sslParams = rs_params.get('sslParams', {})
self.kwargs = {}
self.restart_required = self.login or self.auth_key
self.x509_extra_user = False
if self.sslParams:
self.kwargs.update(DEFAULT_SSL_OPTIONS)
members = rs_params.get('members', [])
self.enable_ipv6 = ipv6_enabled_repl(rs_params)
config = {"_id": self.repl_id, "members": [
self.member_create(member, index)
for index, member in enumerate(members)
]}
if 'rsSettings' in rs_params:
config['settings'] = rs_params['rsSettings']
self._write_concern = len(
[m for m in members
if not m.get('rsParams', {}).get('arbiterOnly')]
)
logger.debug("replica config: {config}".format(**locals()))
if not self.repl_init(config):
self.cleanup()
raise ReplicaSetError("Could not create replica set.")
if not self.waiting_config_state():
raise ReplicaSetError(
"Could not actualize replica set configuration.")
if self.login:
for member in members:
proc_params = member.get('procParams', {})
set_params = proc_params.get('setParameter', {})
auth_mechs = set_params.get('authenticationMechanisms', '')
auth_mechs = auth_mechs.split(',')
if len(auth_mechs) == 1 and auth_mechs[0] == 'MONGODB-X509':
self.x509_extra_user = True
break
if config["members"]:
server_id = self._servers.host_to_server_id(
self.member_id_to_host(0))
version = self._servers.version(server_id)
else:
version = (2, 4, 0)
self._add_users(self.connection()[self.auth_source], version)
if self.restart_required:
for idx, member in enumerate(members):
server_id = self._servers.host_to_server_id(
self.member_id_to_host(idx))
server = self._servers._storage[server_id]
if not member.get('rsParams', {}).get('arbiterOnly'):
server.x509_extra_user = self.x509_extra_user
server.auth_source = self.auth_source
server.login = self.login
server.password = self.password
def add_auth(config):
if self.auth_key:
config['keyFile'] = self.key_file
config.update(member.get('procParams', {}))
return config
server.restart(config_callback=add_auth)
self.restart_required = False
if not self.waiting_member_state() and self.waiting_config_state():
raise ReplicaSetError(
"Could not actualize replica set configuration.")
for i in range(100):
if self.connection().primary:
break
time.sleep(0.1)
else:
raise ReplicaSetError("No primary was ever elected.")
|
create replica set according members config
Args:
rs_params - replica set configuration
|
juraj-google-style
|
def _generate_graph_update_dicts(self):
transform_dict = {}
pcoll_dict = {}
for transform_id, transform_proto in self._top_level_transforms():
transform_dict[transform_proto.unique_name] = {'required': transform_id in self._required_transforms}
for pcoll_id in transform_proto.outputs.values():
pcoll_dict[pcoll_id] = {'cached': pcoll_id in self._cached_pcollections, 'referenced': pcoll_id in self._referenced_pcollections}
def vertex_properties_to_attributes(vertex):
attrs = {}
if 'leaf' in vertex:
attrs['style'] = 'invis'
elif vertex.get('required'):
attrs['color'] = 'blue'
attrs['fontcolor'] = 'blue'
else:
attrs['color'] = 'grey'
return attrs
def edge_properties_to_attributes(edge):
attrs = {}
if edge.get('cached'):
attrs['color'] = 'red'
elif edge.get('referenced'):
attrs['color'] = 'black'
else:
attrs['color'] = 'grey'
return attrs
vertex_dict = {}
edge_dict = {}
for transform_name, transform_properties in transform_dict.items():
vertex_dict[transform_name] = vertex_properties_to_attributes(transform_properties)
for pcoll_id, pcoll_properties in pcoll_dict.items():
edge_dict[pcoll_id] = edge_properties_to_attributes(pcoll_properties)
return (vertex_dict, edge_dict)
|
Generate updates specific to interactive pipeline.
Returns:
vertex_dict: (Dict[str, Dict[str, str]]) maps vertex name to attributes
edge_dict: (Dict[str, Dict[str, str]]) maps vertex name to attributes
|
github-repos
|
def format_level_1_memory(memory):
formatted_memory = _list_to_complex_array(memory)
if (not (1 <= len(formatted_memory.shape) <= 2)):
raise QiskitError('Level one memory is not of correct shape.')
return formatted_memory
|
Format an experiment result memory object for measurement level 1.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 1 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
indicies.
|
codesearchnet
|
def __getattr__(self, item):
if item in self.METHOD_NO_PROXY:
return super(AuthProxy, self).__getattr__(item)
attr = getattr(self.proxy_class, item)
if callable(attr):
return self.auth_proxy(attr)
|
Override attribute getter to act as a proxy for``proxy_class``.
If ``item`` is contained in ``METHOD_NO_PROXY``, it will not be
proxied to the ``proxy_class`` and will instead return the attribute
on this object.
Args:
item (str): Name of attribute to get.
|
juraj-google-style
|
def get_el_amount(self, element):
return sum([self._all_comp[i][element] * abs(self._coeffs[i])
for i in range(len(self._all_comp))]) / 2
|
Returns the amount of the element in the reaction.
Args:
element (Element/Specie): Element in the reaction
Returns:
Amount of that element in the reaction.
|
juraj-google-style
|
def to_file(self, filename):
d = {'mass_info': self.mass_info, 'nonbond_coeffs': self.nonbond_coeffs, 'topo_coeffs': self.topo_coeffs}
yaml = YAML(typ='safe')
with open(filename, 'w') as f:
yaml.dump(d, f)
|
Saves object to a file in YAML format.
Args:
filename (str): Filename.
|
codesearchnet
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.