code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def _apply_base_theme(app):
if QT_VERSION < (5,):
app.setStyle('plastique')
else:
app.setStyle('Fusion')
with open(_STYLESHEET) as stylesheet:
app.setStyleSheet(stylesheet.read()) | Apply base theme to the application.
Args:
app (QApplication): QApplication instance. | juraj-google-style |
def switch(condition, then_expression, else_expression):
if condition.dtype != dtypes_module.bool:
condition = math_ops.cast(condition, 'bool')
cond_ndim = ndim(condition)
if not cond_ndim:
if not callable(then_expression):
def then_expression_fn():
return then_e... | Switches between two operations depending on a scalar value.
Note that both `then_expression` and `else_expression`
should be symbolic tensors of the *same shape*.
Args:
condition: tensor (`int` or `bool`).
then_expression: either a tensor, or a callable that returns a tensor.
else_expression: either a tensor, or a c... | github-repos |
def put_async(self, path, value):
request = Put(self._get_next_id(), path, value)
request.set_callback(self._q.put)
future = self._dispatch_request(request)
return future | Puts a value to a path and returns immediately
Args:
path (list): The path to put to
value (object): The value to set
Returns:
Future: A single Future which will resolve to the result | juraj-google-style |
def show_tricky_tasks(self, verbose=0):
nids, tasks = [], []
for task in self.iflat_tasks():
if task.num_launches > 1 or any(n > 0 for n in (task.num_restarts, task.num_corrections)):
nids.append(task.node_id)
tasks.append(task)
if not nids:
... | Print list of tricky tasks i.e. tasks that have been restarted or
launched more than once or tasks with corrections.
Args:
verbose: Verbosity level. If > 0, task history and corrections (if any) are printed. | juraj-google-style |
def add_args(self, args):
for key, value in vars(args).items():
if value is not None:
setattr(self, key.upper(), value) | Add the args
Args:
args (namespace): The commandline args | juraj-google-style |
def getRow(self, key):
return Row(self._impl.getRow(Tuple(key)._impl)) | Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row. | codesearchnet |
def get_inlined_extension_url(field: descriptor.FieldDescriptor) -> str:
options = annotation_utils.get_options(field)
if options.HasExtension(annotations_pb2.fhir_inlined_extension_url):
return options.Extensions[annotations_pb2.fhir_inlined_extension_url]
return field.camelcase_name | Returns the FHIR inlined extension URL for a field.
Args:
field: The FieldDescriptor to examine.
Returns:
The FHIR inlined extension URL, if one exists, otherwise returns the camel-
case name of the FieldDescriptor. | github-repos |
def __init__(self, binary_line_reader, delimiter):
super(BinaryDSVReader, self).__init__()
self._line_reader = binary_line_reader
self._delimiter = delimiter | Initializes the delimited separated values reader.
Args:
binary_line_reader (BinaryLineReader): a binary file reader
delimiter (bytes): field delimiter. | juraj-google-style |
def query(self, rank):
self._flush()
current = self._head
if (not current):
return 0
mid_rank = math.floor((rank * self._observations))
max_rank = (mid_rank + math.floor((self._invariant(mid_rank, self._observations) / 2)))
rank = 0.0
while current._successor:
rank += current... | Retrieves the value estimate for the requested quantile rank.
The requested quantile rank must be registered in the estimator's
invariants a priori!
Args:
rank: A floating point quantile rank along the interval [0, 1].
Returns:
A numeric value for the quantile estimate. | codesearchnet |
def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None):
return self.__StreamMedia(callback=callback, finish_callback=finish_callback, additional_headers=additional_headers, use_chunks=False) | Send this resumable upload in a single request.
Args:
callback: Progress callback function with inputs
(http_wrapper.Response, transfer.Upload)
finish_callback: Final callback function with inputs
(http_wrapper.Response, transfer.Upload)
additional_headers: Dict of headers to include with the upload
http_wrapper.Reque... | codesearchnet |
def contains(self, sub):
sub = sub.lower()
found_words = set()
res = cgaddag.gdg_contains(self.gdg, sub.encode(encoding='ascii'))
tmp = res
while tmp:
word = tmp.contents.str.decode('ascii')
found_words.add(word)
tmp = tmp.contents.next
cgaddag.gdg_destroy_result(res)
... | Find all words containing a substring.
Args:
sub: A substring to be searched for.
Returns:
A list of all words found. | codesearchnet |
def _TypeCompatibilityCheck(self, type_params):
type_params = {t for t in type_params if not isinstance(t, pytd.AnythingType)}
if not all((isinstance(t, pytd.ClassType) for t in type_params)):
return False
mro_list = [set(mro.GetBasesInMRO(t.cls)) for t in type_params]
mro_list.sort(key=len)
... | Check if the types are compatible.
It is used to handle the case:
class A(Sequence[A]): pass
class B(A, Sequence[B]): pass
class C(B, Sequence[C]): pass
In class `C`, the type parameter `_T` of Sequence could be `A`, `B` or `C`.
Next we will check they have a linear inheritance relationship:
`A` -> `B` -> `C`.
Args:
... | github-repos |
def __init__(self, options={}):
settings = {
'currency': {
'symbol': "$",
'format': "%s%v",
'decimal': ".",
'thousand': ",",
'precision': 2,
'grouping': 3
},
'number': {
... | Summary.
Args:
options (dict, optional): settings configuration object. | juraj-google-style |
def set_inheritance(obj_name, enabled, obj_type='file', clear=False):
if (obj_type not in ['file', 'registry', 'registry32']):
raise SaltInvocationError('obj_type called with incorrect parameter: {0}'.format(obj_name))
if clear:
obj_dacl = dacl(obj_type=obj_type)
else:
obj_dacl = dac... | Enable or disable an objects inheritance.
Args:
obj_name (str):
The name of the object
enabled (bool):
True to enable inheritance, False to disable
obj_type (Optional[str]):
The type of object. Only three objects allow inheritance. Valid
objects are:
- file (default): This is a file or directory
- registry
- regis... | codesearchnet |
def is_int(string):
try:
a = float(string)
b = int(a)
except ValueError:
return False
else:
return a == b | Checks if a string is an integer. If the string value is an integer
return True, otherwise return False.
Args:
string: a string to test.
Returns:
boolean | juraj-google-style |
def sign(mv):
md5 = hashlib.md5()
update_hash(md5, mv)
return md5.digest() | Obtains a signature for a `MetricValue`
Args:
mv (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricValue`): a
MetricValue that's part of an operation
Returns:
string: a unique signature for that operation | codesearchnet |
def __rmfile(path):
logger.info("rmfile: %s" % path)
try:
os.remove(path)
return True
except Exception as e:
logger.error("rmfile: %s failed! Error: %s" % (path, e))
return False | Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise. | juraj-google-style |
def get_messages(module):
answer = collections.OrderedDict()
for name in dir(module):
candidate = getattr(module, name)
if (inspect.isclass(candidate) and issubclass(candidate, message.Message)):
answer[name] = candidate
return answer | Discovers all protobuf Message classes in a given import module.
Args:
module (module): A Python module; :func:`dir` will be run against this
module to find Message subclasses.
Returns:
dict[str, google.protobuf.message.Message]: A dictionary with the
Message class names as keys, and the Message subclasses themselves... | codesearchnet |
def deserialize_function(serial, function_type):
if (function_type == 'function'):
function = tf.keras.utils.deserialize_keras_object(serial)
elif (function_type == 'lambda'):
function = generic_utils.func_load(serial)
else:
raise TypeError('Unknown function type:', function_type)
... | Deserializes the Keras-serialized function.
(De)serializing Python functions from/to bytecode is unsafe. Therefore we
also use the function's type as an anonymous function ('lambda') or named
function in the Python environment ('function'). In the latter case, this lets
us use the Python scope to obtain the function r... | codesearchnet |
def UpdateNumberOfEventSources(self, number_of_consumed_sources, number_of_produced_sources):
consumed_sources_delta = 0
if (number_of_consumed_sources is not None):
if (number_of_consumed_sources < self.number_of_consumed_sources):
raise ValueError('Number of consumed sources smaller than p... | Updates the number of event sources.
Args:
number_of_consumed_sources (int): total number of event sources consumed
by the process.
number_of_produced_sources (int): total number of event sources produced
by the process.
Returns:
bool: True if either number of event sources has increased.
Raises:
ValueError: if the ... | codesearchnet |
def conv(self, conv_input: core.Tensor) -> Mapping[str, core.Tensor]:
out = nn_ops.conv2d(conv_input, self.conv_filters, strides=[1, 1, 2, 1], dilations=[1, 1, 1, 1], padding='SAME', data_format='NHWC')
return {'output': out} | Performs a 2D convolution operation.
Args:
conv_input: Input tensor to perform convolution on.
Returns:
A map of: output key -> output result. | github-repos |
def get_pmg_structure(phonopy_structure):
lattice = phonopy_structure.get_cell()
frac_coords = phonopy_structure.get_scaled_positions()
symbols = phonopy_structure.get_chemical_symbols()
masses = phonopy_structure.get_masses()
mms = phonopy_structure.get_magnetic_moments()
mms = (mms or ([0] * l... | Convert a PhonopyAtoms object to pymatgen Structure object.
Args:
phonopy_structure (PhonopyAtoms): A phonopy structure object. | codesearchnet |
def set_name(self, name):
if not self._campfire.get_user().admin:
return False
result = self._connection.put("room/%s" % self.id, {"room": {"name": name}})
if result["success"]:
self._load()
return result["success"] | Set the room name.
Args:
name (str): Name
Returns:
bool. Success | juraj-google-style |
def __init__(self, application_namespace=None, application_data=None):
super(ApplicationSpecificInformation, self).__init__(
Tags.APPLICATION_SPECIFIC_INFORMATION)
if application_namespace is None:
self.application_namespace = ApplicationNamespace()
else:
... | Construct an ApplicationSpecificInformation object.
Args:
application_namespace (ApplicationNamespace): The name of a
namespace supported by the server. Optional, defaults to None.
application_data (ApplicationData): String data relevant to the
specified namespace. Optional, defaults to None. | juraj-google-style |
def get_config_bool_option(parser: ConfigParser, section: str, option: str, default: bool=None) -> bool:
if (not parser.has_section(section)):
raise ValueError(('config missing section: ' + section))
return parser.getboolean(section, option, fallback=default) | Retrieves a boolean value from a parser.
Args:
parser: instance of :class:`ConfigParser`
section: section name within config file
option: option (variable) name within that section
default: value to return if option is absent
Returns:
string value
Raises:
ValueError: if the section is absent | codesearchnet |
def initial_value(self):
raise NotImplementedError | Returns the Tensor used as the initial value for the variable.
Note that this is different from `initialized_value()` which runs
the op that initializes the variable before returning its value.
This method returns the tensor that is used by the op that initializes
the variable.
Returns:
A `Tensor`. | github-repos |
def kill_pid(self, pid):
try:
p = psutil.Process(pid)
p.terminate()
self.info_log('Killed [pid:%s][name:%s]' % (p.pid, p.name()))
except psutil.NoSuchProcess:
self.error_log('No such process: [pid:%s]' % pid) | Kill process by pid
Args:
pid (int) | juraj-google-style |
def _generate_shape(word: str) -> str:
def counting_stars(w) -> List[int]:
count = [1]
for i in range(1, len(w)):
if w[i - 1] == w[i]:
count[-1] += 1
else:
count.append(1)
return count
... | Recreate shape from a token input by user
Args:
word: str
Returns: str | juraj-google-style |
def qr(x, mode='reduced'):
if any_symbolic_tensors((x,)):
return Qr(mode=mode).symbolic_call(x)
x = backend.convert_to_tensor(x)
return backend.linalg.qr(x, mode=mode) | Computes the QR decomposition of a tensor.
Args:
x: Input tensor of shape `(..., M, N)`.
mode: A string specifying the mode of the QR decomposition.
- 'reduced': Returns the reduced QR decomposition. (default)
- 'complete': Returns the complete QR decomposition.
Returns:
A tuple containing two tensors. The first tens... | github-repos |
def set_expected_update_frequency(self, update_frequency):
try:
int(update_frequency)
except ValueError:
update_frequency = Dataset.transform_update_frequency(update_frequency)
if not update_frequency:
raise HDXError('Invalid update frequency... | Set expected update frequency
Args:
update_frequency (str): Update frequency
Returns:
None | juraj-google-style |
def compare_profiles(profile1, profile2):
length = len(profile1)
profile1 = np.array(list(profile1))
profile2 = np.array(list(profile2))
similarity_array = profile1 == profile2
matches = np.sum(similarity_array)
similarity_ratio = matches/length
return similarity_ratio | Given two profiles, determine the ratio of similarity, i.e.
the hamming distance between the strings.
Args:
profile1/2 (str): profile string
Returns:
similarity_ratio (float): the ratio of similiarity (0-1) | juraj-google-style |
def plot(self, data):
import IPython
if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()):
raise ValueError('Expect a dictionary where the values are all dataframes.')
gfsg = GenericFeatureStatisticsGenerator()
data = [{'name': k, 'table': self._remo... | Plots an overview in a list of dataframes
Args:
data: a dictionary with key the name, and value the dataframe. | juraj-google-style |
def fail_request(self, orig_request, message, start_response):
cors_handler = self._create_cors_handler(orig_request)
return util.send_wsgi_error_response(
message, start_response, cors_handler=cors_handler) | Write an immediate failure response to outfile, no redirect.
This calls start_response and returns the error body.
Args:
orig_request: An ApiRequest, the original request from the user.
message: A string containing the error message to be displayed to user.
start_response: A function with semantics defined in PEP-333... | juraj-google-style |
def _decode_doubles(message):
binary = base64.b64decode(message)
return struct.unpack(('<' + ('d' * (len(binary) | Helper for decode_qp, decodes a double array.
The double array is stored as little endian 64 bit doubles.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse.
Args:
message: the double array
Returns:
decoded double array | codesearchnet |
def unitary(val: Any, default: TDefault=RaiseTypeErrorIfNotProvided) -> Union[(np.ndarray, TDefault)]:
from cirq import Gate, Operation
getter = getattr(val, '_unitary_', None)
result = (NotImplemented if (getter is None) else getter())
if (result is not NotImplemented):
return result
if isi... | Returns a unitary matrix describing the given value.
Args:
val: The value to describe with a unitary matrix.
default: Determines the fallback behavior when `val` doesn't have
a unitary matrix. If `default` is not set, a TypeError is raised. If
default is set to a value, that value is returned.
Returns:
If `val` has a... | codesearchnet |
class RunThresholdCriterion(beam.PTransform[beam.PCollection[NestedKeyedOutputT], beam.PCollection[NestedKeyedOutputT]]):
def __init__(self, threshold_criterion: ThresholdFn):
self._threshold_fn = threshold_criterion
def expand(self, input: beam.PCollection[NestedKeyedOutputT]) -> beam.PCollection[Nes... | Applies a threshold criterion to anomaly detection results.
This PTransform applies a `ThresholdFn` to the anomaly scores in
`AnomalyResult` objects, updating the prediction labels. It handles both
stateful and stateless `ThresholdFn` implementations.
Args:
threshold_criterion: The `ThresholdFn` to apply. | github-repos |
def get_visualizations():
if (not hasattr(g, 'visualizations')):
g.visualizations = {}
for VisClass in _get_visualization_classes():
vis = VisClass(get_model())
g.visualizations[vis.__class__.__name__] = vis
return g.visualizations | Get the available visualizations from the request context. Put the
visualizations in the request context if they are not yet there.
Returns:
:obj:`list` of instances of :class:`.BaseVisualization` or
derived class | codesearchnet |
def from_text(cls, text, lexicon, required=None, first_only=True):
component = lexicon.get_component(text, first_only=first_only)
if (required and (required not in component)):
return None
else:
return cls(component) | Generate a Component from a text string, using a Lexicon.
Args:
text (str): The text string to parse.
lexicon (Lexicon): The dictionary to use for the
categories and lexemes.
required (str): An attribute that we must have. If a required
attribute is missing from the component, then None is returned.
first_only (bool):... | codesearchnet |
def validlocations(configuration=None):
if Locations._validlocations is None:
if configuration is None:
configuration = Configuration.read()
Locations._validlocations = configuration.call_remoteckan('group_list', {'all_fields': True})
return Loca... | Read valid locations from HDX
Args:
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.
Returns:
List[Dict]: A list of valid locations | juraj-google-style |
def handle_arguments(self, string, root, opening, closing):
args = string[(opening + 1):closing].replace(' ', '')
if ((opening > 0) or (not self.arguments.match(args))):
if (opening == 0):
raise errors.ParseError('Invalid argument sequence!')
(string, meta) = self.escape_meta(string,... | Handles phrase-arguments.
Sets the override and increment flags if found. Also makes
sure that the argument sequence is at the start of the phrase
and else warns about the unescaped meta characters. If the
arguments are indeed at the start but do not match the arguments
regular expression, an error is raised.
Argumen... | codesearchnet |
def retrieve_review(self, reviewer, product):
if not isinstance(reviewer, self._reviewer_cls):
raise TypeError(
"Type of given reviewer isn't acceptable:", reviewer,
", expected:", self._reviewer_cls)
elif not isinstance(product, self._product_cls):
... | Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given reviewer and product aren't instance of
specified reviewer and product class when this graph is constructed.
KeyError: When ... | juraj-google-style |
def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
vision_data = {}
if image_sizes is not None:
images_kwargs = Qwen2_5_VLProcessorKwargs._defaults.get('images_kwargs', {})
images_kwargs.update(kwargs)
merge_size = images_kwargs.get('merge_size', None) or... | Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
Args:
image_sizes (`List[List[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.
video_sizes (`List[List[int]]`, *optional*):
The input sizes formatted as (num_frames, height, width) per each vide... | github-repos |
def sackin(self, normalize='leaves'):
num_nodes_from_root = dict()
sackin = 0
num_leaves = 0
for node in self.traverse_preorder():
num_nodes_from_root[node] = 1
if (not node.is_root()):
num_nodes_from_root[node] += num_nodes_from_root[node.parent]
if node.is_leaf():
... | Compute the Sackin balance index of this ``Tree``
Args:
``normalize`` (``str``): How to normalize the Sackin index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
* ``"yule"`` to normalize to the Yule model
* ``"pda"`` to normalize to the Proportional to Distinguishable ... | codesearchnet |
def Collect(self, knowledge_base, artifact_definition, searcher):
for source in artifact_definition.sources:
if (source.type_indicator not in (artifact_definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_KEY, artifact_definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_VALUE)):
continue
if (source.type_... | Collects values using a Windows Registry value artifact definition.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
artifact_definition (artifacts.ArtifactDefinition): artifact definition.
searcher (dfwinreg.WinRegistrySearcher): Windows Registry searcher to
preprocess the Windows Registr... | codesearchnet |
def save_headers(cls, filename: str, response: HTTPResponse):
new_filename = filename + '-new'
with open('wb') as new_file:
new_file.write(response.header())
with wpull.util.reset_file_offset(response.body):
response.body.seek(0)
shutil.... | Prepend the HTTP response header to the file.
Args:
filename: The path of the file
response: Response | juraj-google-style |
def insort_event_right(self, event, lo=0, hi=None):
if (lo < 0):
raise ValueError('lo must be non-negative')
if (hi is None):
hi = len(self.queue)
while (lo < hi):
mid = ((lo + hi)
if (event[0] < self.queue[mid][0]):
hi = mid
else:
lo = (mid +... | Insert event in queue, and keep it sorted assuming queue is sorted.
If event is already in queue, insert it to the right of the rightmost
event (to keep FIFO order).
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
Args:
event: a (time in sec since unix epoch, callback, args,... | codesearchnet |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
super(MACSignatureKeyInformation, self).read(input_stream, kmip_version=kmip_version)
local_stream = BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
self._unique_id... | Read the data encoding the MACSignatureKeyInformation struct and
decode it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which t... | codesearchnet |
def retrieve_artifacts(self, compose_data, output_data_config, job_name):
artifacts = os.path.join(self.container_root, 'artifacts')
compressed_artifacts = os.path.join(self.container_root, 'compressed_artifacts')
os.mkdir(artifacts)
model_artifacts = os.path.join(artifacts, 'model')
output_artifact... | Get the model artifacts from all the container nodes.
Used after training completes to gather the data from all the individual containers. As the
official SageMaker Training Service, it will override duplicate files if multiple containers have
the same file names.
Args:
compose_data(dict): Docker-Compose configuratio... | codesearchnet |
def victim_asset_associations(
self, main_type, sub_type, unique_id, branch_type, owner=None, params=None
):
params = params or {}
if owner:
params['owner'] = owner
if not sub_type:
url = '/v2/{}/{}/victimAssets/{}'.format(main_type, unique_id, bran... | Args:
owner:
main_type:
sub_type:
unique_id:
branch_type:
params:
Return: | juraj-google-style |
def get_scan_plot(self, coords=None):
from pymatgen.util.plotting import pretty_plot
plt = pretty_plot(12, 8)
d = self.read_scan()
if coords and coords in d["coords"]:
x = d["coords"][coords]
plt.xlabel(coords)
else:
x = range(len(d... | Get a matplotlib plot of the potential energy surface.
Args:
coords: internal coordinate name to use as abcissa. | juraj-google-style |
def _add_genotypes(self, variant_obj, gemini_variant, case_id, individual_objs):
for ind in individual_objs:
index = ind.ind_index
variant_obj.add_individual(Genotype(sample_id=ind.ind_id, genotype=gemini_variant['gts'][index], case_id=case_id, phenotype=ind.phenotype, ref_depth=gemini_variant['gt_r... | Add the genotypes for a variant for all individuals
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow): The gemini variant
case_id (str): related case id
individual_objs (list(dict)): A list of Individuals | codesearchnet |
def get_descriptor_defaults(self, api_info, hostname=None, x_google_api_name=False):
hostname = (hostname or util.get_app_hostname() or
api_info.hostname)
protocol = 'http' if ((hostname and hostname.startswith('localhost')) or
util.is_running_on_devserver()) else ... | Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary with the default configuration. | juraj-google-style |
def get_text_features(self, input_ids: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None) -> torch.FloatTensor:
output_attentions = output_attentions if output_attenti... | Returns:
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
applying the projection layer to the pooled output of [`CLIPTextModel`].
Examples:
```python
>>> from transformers import AutoTokenizer, CLIPModel
>>> model = CLIPModel.from_pretrained("openai/clip-vit-ba... | github-repos |
def get_config(self):
config = {}
for (_, curriculum) in self.brains_to_curriculums.items():
curr_config = curriculum.get_config()
config.update(curr_config)
return config | Get the combined configuration of all curriculums in this
MetaCurriculum.
Returns:
A dict from parameter to value. | codesearchnet |
def getOption(self, name):
try:
value = lock_and_call(
lambda: self._impl.getOption(name).value(),
self._lock
)
except RuntimeError:
return None
else:
try:
return int(value)
excep... | Get the current value of the specified option. If the option does not
exist, returns None.
Args:
name: Option name.
Returns:
Value of the option.
Raises:
InvalidArgumet: if the option name is not valid. | juraj-google-style |
def download_file(bucket_name, path, target, sagemaker_session):
path = path.lstrip('/')
boto_session = sagemaker_session.boto_session
s3 = boto_session.resource('s3')
bucket = s3.Bucket(bucket_name)
bucket.download_file(path, target) | Download a Single File from S3 into a local path
Args:
bucket_name (str): S3 bucket name
path (str): file path within the bucket
target (str): destination directory for the downloaded file.
sagemaker_session (:class:`sagemaker.session.Session`): a sagemaker session to interact with S3. | juraj-google-style |
def add_file(self, path, compress):
if (not os.path.isfile(path)):
raise ValueError('{} is not a file'.format(path))
self.fileobj.seek(self.last_offset)
with open(path, 'rb') as f:
flags = (os.stat(path).st_mode & 511)
self.add_fileobj(f, path, compress, flags) | Add a single file to the MAR file.
Args:
path (str): path to a file to add to this MAR file.
compress (str): One of 'xz', 'bz2', or None. Defaults to None. | codesearchnet |
def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],
name: str = None) -> Schedule:
if name is None and schedules:
sched = schedules[0]
if isinstance(sched, (list, tuple)):
name = sched[1].name
else:
name = sched.name
... | Create a union (and also shift if desired) of all input `Schedule`s.
Args:
*schedules: Schedules to take the union of
name: Name of the new schedule. Defaults to first element of `schedules` | juraj-google-style |
def __init__(self, location=None, parent=None, store_index=None, **kwargs):
if not parent:
raise ValueError('Missing parent value.')
super(VShadowPathSpec, self).__init__(parent=parent, **kwargs)
self.location = location
self.store_index = store_index | Initializes a path specification.
Note that the VSS path specification must have a parent.
Args:
location (Optional[str]): location.
parent (Optional[PathSpec]): parent path specification.
store_index (Optional[int]): store index.
Raises:
ValueError: when parent is not set. | juraj-google-style |
def tritonast2arybo(e, use_exprs=True, use_esf=False, context=None):
children_ = e.getChildren()
children = (tritonast2arybo(c,use_exprs,use_esf,context) for c in children_)
reversed_children = (tritonast2arybo(c,use_exprs,use_esf,context) for c in reversed(children_))
Ty = e.getType()
if Ty ... | Convert a subset of Triton's AST into Arybo's representation
Args:
e: Triton AST
use_esf: use ESFs when creating the final expression
context: dictionnary that associates Triton expression ID to arybo expressions
Returns:
An :class:`arybo.lib.MBAVariable` object | juraj-google-style |
def _copy_delpoy_scripts(self, scripts):
if not os.path.exists(self.paths.scripts()):
os.makedirs(self.paths.scripts())
new_scripts = []
for script in scripts:
script = os.path.expandvars(script)
if not os.path.exists(script):
raise R... | Copy the given deploy scripts to the scripts dir in the prefix
Args:
scripts(list of str): list of paths of the scripts to copy to the
prefix
Returns:
list of str: list with the paths to the copied scripts, with a
prefixed with $LAGO_PREFIX_PATH so the full path is not
hardcoded | juraj-google-style |
def reconstruct_non_debug_graph_def(debug_graph_def):
return DebugGraph(debug_graph_def).non_debug_graph_def | Reconstruct original (non-debugger-decorated) partition GraphDef.
This method strips the input `tf.compat.v1.GraphDef` of the Copy* and
Debug*-type nodes inserted by the debugger.
The reconstructed partition graph is identical to the original (i.e.,
non-debugger-decorated) partition graph except in the following resp... | github-repos |
def _connect_to_device(self, uuid, key, client):
slug = self._build_device_slug(uuid)
message = {'client': client, 'type': 'response', 'operation': 'connect'}
self._logger.info("Connection attempt for device %d", uuid)
if uuid in self._connections:
messag... | Connect to a device given its uuid
Args:
uuid (int): The unique id of the device
key (string): A 64 byte string used to secure this connection
client (string): The client id for who is trying to connect
to the device. | juraj-google-style |
def cxx(project, detect_project=False):
from benchbuild.utils import cmd
cxx_name = str(CFG['compiler']['cxx'])
wrap_cc(cxx_name, compiler(cxx_name), project, detect_project=detect_project)
return cmd['./{name}'.format(name=cxx_name)] | Return a clang++ that hides CFLAGS and LDFLAGS.
This will generate a wrapper script in the current directory
and return a complete plumbum command to it.
Args:
cflags: The CFLAGS we want to hide.
ldflags: The LDFLAGS we want to hide.
func (optional): A function that will be pickled alongside the compiler.
It will be ... | codesearchnet |
def compose_full_url(pub, uuid_url=False):
url = compose_path(pub, uuid_url)
if (WEB_PORT == 80):
return ('%s:
return ('%s: | Compose full url for given `pub`, with protocol, server's address and port.
Args:
pub (obj): :class:`.DBPublication` instance.
uuid_url (bool, default False): Compose URL using UUID.
Returns:
str: Absolute url of the publication.
Raises:
PrivatePublicationError: When the `pub` is private publication. | codesearchnet |
def _GetISO8601String(self, structure):
fraction_of_second_length = len(structure.fraction_of_second)
if (fraction_of_second_length not in (3, 6, 7)):
raise ValueError('unsupported time fraction of second length: {0:d}'.format(fraction_of_second_length))
try:
fraction_of_second = int(structu... | Retrieves an ISO8601 date time string from the structure.
The date and time values in the SCCM log are formatted as:
time="19:33:19.766-330" date="11-28-2014"
Args:
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file.
Returns:
str: ISO 8601 date time string.
Raises:
ValueError... | codesearchnet |
def __init__(self, initial_structure, final_structure):
if final_structure.formula != initial_structure.formula:
raise ValueError("Initial and final structures have different " +
"formulas!")
self.initial = initial_structure
self.final = final_st... | Please note that the input and final structures should have the same
ordering of sites. This is typically the case for most computational
codes.
Args:
initial_structure (Structure): Initial input structure to
calculation.
final_structure (Structure): Final output structure from
calculation. | juraj-google-style |
def add(self, rid, data, raise_on_error=True):
return self.post(rid, data, raise_on_error) | Write data to the DataStore. Alias for post() method.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response. | juraj-google-style |
def ParseFileObject(self, parser_mediator, file_object):
file_header_map = self._GetDataTypeMap('java_idx_file_header')
try:
file_header, file_offset = self._ReadStructureFromFileObject(
file_object, 0, file_header_map)
except (ValueError, errors.ParseError) as exception:
raise e... | Parses a Java WebStart Cache IDX file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dvfvs.FileIO): a file-like object to parse.
Raises:
UnableToParseFile: when the file cannot be parsed. | juraj-google-style |
def pose2mat(pose):
homo_pose_mat = np.zeros((4, 4), dtype=np.float32)
homo_pose_mat[(:3, :3)] = quat2mat(pose[1])
homo_pose_mat[(:3, 3)] = np.array(pose[0], dtype=np.float32)
homo_pose_mat[(3, 3)] = 1.0
return homo_pose_mat | Converts pose to homogeneous matrix.
Args:
pose: a (pos, orn) tuple where pos is vec3 float cartesian, and
orn is vec4 float quaternion.
Returns:
4x4 homogeneous matrix | codesearchnet |
def from_api_repr(cls, resource):
config = cls(resource["sourceFormat"])
for optcls in _OPTION_CLASSES:
opts = resource.get(optcls._RESOURCE_NAME)
if opts is not None:
config._options = optcls.from_api_repr(opts)
break
config._prop... | Factory: construct an :class:`~.external_config.ExternalConfig`
instance given its API representation.
Args:
resource (Dict[str, Any]):
Definition of an :class:`~.external_config.ExternalConfig`
instance in the same representation as is returned from the
API.
Returns:
:class:`~.external_config.ExternalConfig`:
Config... | juraj-google-style |
def __init__(self, low, high, output_shape):
self.__low = low
self.__high = high
self.__output_shape = output_shape | Init.
Args:
low: Lower boundary of the output interval.
All values generated will be greater than or equal to low.
high: Upper boundary of the output interval.
All values generated will be less than high.
output_shape: Output shape.
the shape is `(batch size, d1, d2, d3, ...)`. | juraj-google-style |
def verify(self, obj):
if not isinstance(obj, int):
raise ValidationError("Object is not a int", reason='object is not a int', object=obj,
type=type(obj), int_type=int)
return obj | Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reason key set indicating
the reason for the lack of validation. | juraj-google-style |
def list_autoscale_settings(access_token, subscription_id):
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/providers/microsoft.insights/',
'/autoscaleSettings?api-version=', INSIGHTS_API])
return do_get(en... | List the autoscale settings in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of autoscale settings. | juraj-google-style |
def normalize(code):
if len(code) == 3:
return code
normalized = translate(code)
if normalized:
return normalized
country = countries.get(code, None)
if country:
return country.alpha3.lower()
return code | Normalize language codes to ISO 639-2. If all conversions fails, return the
`code` as it was given.
Args:
code (str): Language / country code.
Returns:
str: ISO 639-2 country code. | juraj-google-style |
def get_log_id(cls, id):
conn = Qubole.agent()
r = conn.get_raw(cls.element_path(id) + "/logs")
return r.text | Fetches log for the command represented by this id
Args:
`id`: command id | juraj-google-style |
def __call__(self, environ, start_response):
start_time = datetime.datetime.utcnow()
name = environ.get('PATH_INFO') or '/'
closure = {'status': '200 OK'}
http_method = environ.get('REQUEST_METHOD', 'GET')
self.client.context.operation.id = str(uuid.uuid4())
... | Callable implementation for WSGI middleware.
Args:
environ (dict). a dictionary containing all WSGI environment properties for this request.\n
start_response (func). a function used to store the status, HTTP headers to be sent to the client and optional exception information.
Returns:
(obj). the response to send back... | juraj-google-style |
def outer_definition_name(cls):
outer_definition = cls.message_definition()
if (not outer_definition):
return util.get_package_for_module(cls.__module__)
return outer_definition.definition_name() | Helper method for creating outer definition name.
Returns:
If definition is nested, will return the outer definitions
name, else the package name. | codesearchnet |
def get_student_current_grade(self, username, course_id):
resp = self.requester.get(urljoin(self.base_url, '/api/grades/v1/courses/{course_key}/?username={username}'.format(username=username, course_key=course_id)))
resp.raise_for_status()
return CurrentGrade(resp.json()[0]) | Returns an CurrentGrade object for the user in a course
Args:
username (str): an edx user's username
course_id (str): an edX course id.
Returns:
CurrentGrade: object representing the student current grade for a course | codesearchnet |
def _strict_match(self, struct1, struct2, fu, s1_supercell=True,
use_rms=False, break_on_match=False):
if fu < 1:
raise ValueError("fu cannot be less than 1")
mask, s1_t_inds, s2_t_ind = self._get_mask(struct1, struct2,
... | Matches struct2 onto struct1 (which should contain all sites in
struct2).
Args:
struct1, struct2 (Structure): structures to be matched
fu (int): size of supercell to create
s1_supercell (bool): whether to create the supercell of
struct1 (vs struct2)
use_rms (bool): whether to minimize the rms of the matching
break_on_... | juraj-google-style |
def is_param_method(obj, has_deps=False):
parameterized = (inspect.ismethod(obj) and isinstance(get_method_owner(obj), param.Parameterized))
if (parameterized and has_deps):
return getattr(obj, '_dinfo', {}).get('dependencies')
return parameterized | Whether the object is a method on a parameterized object.
Args:
obj: Object to check
has_deps (boolean, optional): Check for dependencies
Whether to also check whether the method has been annotated
with param.depends
Returns:
A boolean value indicating whether the object is a method
on a Parameterized object and if e... | codesearchnet |
def gcd_float(numbers, tol=1e-08):
def pair_gcd_tol(a, b):
'Calculate the Greatest Common Divisor of a and b.\n\n Unless b==0, the result will have the same sign as b (so that when\n b is divided by it, the result comes out positive).\n '
while (b > tol):
(a, b) = (... | Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers. | codesearchnet |
def remove_import_statements(code):
new_code = []
for line in code.splitlines():
if ((not line.lstrip().startswith('import ')) and (not line.lstrip().startswith('from '))):
new_code.append(line)
while (new_code and (new_code[0] == '')):
new_code.pop(0)
while (new_code and (ne... | Removes lines with import statements from the code.
Args:
code: The code to be stripped.
Returns:
The code without import statements. | codesearchnet |
def GetCacheSize(self):
if ((not self._cache_start_offset) or (not self._cache_end_offset)):
return 0
return (self._cache_end_offset - self._cache_start_offset) | Determines the size of the uncompressed cached data.
Returns:
int: number of cached bytes. | codesearchnet |
def get_config_status():
cmd = 'Get-DscConfigurationStatus | Select-Object -Property HostName, Status, MetaData, @{Name="StartDate";Expression={Get-Date ($_.StartDate) -Format g}}, Type, Mode, RebootRequested, NumberofResources'
try:
return _pshell(cmd, ignore_retcode=True)
except CommandExecutionEr... | Get the status of the current DSC Configuration
Returns:
dict: A dictionary representing the status of the current DSC
Configuration on the machine
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config_status | codesearchnet |
def _parse_price(html_chunk):
price = get_first_content(
html_chunk.find("div", {"class": "prices"})
)
if not price:
return None
price = dhtmlparser.removeTags(price)
price = price.split("\n")[-1]
return price | Parse price of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Price as string with currency or None if not found. | juraj-google-style |
def default_output_fn(prediction, accept):
return _worker.Response(response=_encoders.encode(prediction, accept), mimetype=accept) | Function responsible to serialize the prediction for the response.
Args:
prediction (obj): prediction returned by predict_fn .
accept (str): accept content-type expected by the client.
Returns:
(worker.Response): a Flask response object with the following args:
* Args:
response: the serialized data to return
accept:... | juraj-google-style |
def _GetScanner(self, specification_store, signature_identifiers):
if (not specification_store):
return None
scanner_object = pysigscan.scanner()
for format_specification in specification_store.specifications:
if (format_specification.identifier not in signature_identifiers):
con... | Initializes the scanner form the specification store.
Args:
specification_store (FormatSpecificationStore): a specification store.
signature_identifiers (list[str]): signature identifiers.
Returns:
pysigscan.scanner: signature scanner or None. | codesearchnet |
def encode_field(self, field, value):
for encoder in _GetFieldCodecs(field, 'encoder'):
result = encoder(field, value)
value = result.value
if result.complete:
return value
if isinstance(field, messages.EnumField):
if field.repeated:
remapped_value = [(Get... | Encode the given value as JSON.
Args:
field: a messages.Field for the field we're encoding.
value: a value for field.
Returns:
A python value suitable for json.dumps. | codesearchnet |
def destroy_elb(app='', env='dev', region='us-east-1', **_):
task_json = get_template(
template_file='destroy/destroy_elb.json.j2',
app=app,
env=env,
region=region,
vpc=get_vpc_id(account=env, region=region))
wait_for_task(task_json)
return True | Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion. | juraj-google-style |
def add_gene_info(self, variant_obj, gene_panels=None):
gene_panels = gene_panels or []
variant_obj['has_refseq'] = False
extra_info = {}
for panel_obj in gene_panels:
for gene_info in panel_obj['genes']:
hgnc_id... | Add extra information about genes from gene panels
Args:
variant_obj(dict): A variant from the database
gene_panels(list(dict)): List of panels from database | juraj-google-style |
def stop_condition(self, condition):
for cond_format in self._known_conditions:
try:
cond = cond_format.FromString(condition)
self.stop_conditions.append(cond)
return
except ArgumentError:
continu... | Add a stop condition to this simulation.
Stop conditions are specified as strings and parsed into
the appropriate internal structures.
Args:
condition (str): a string description of the stop condition | juraj-google-style |
def _get_path_params(match):
result = {}
for var_name, value in match.groupdict().iteritems():
actual_var_name = ApiConfigManager._from_safe_path_param_name(var_name)
result[actual_var_name] = urllib.unquote_plus(value)
return result | Gets path parameters from a regular expression match.
Args:
match: A regular expression Match object for a path.
Returns:
A dictionary containing the variable names converted from base64. | juraj-google-style |
def predict_proba(self, x, y=None, **kwargs):
if self.clf is None:
raise ValueError("Model has to be trained before making predictions.")
if x is pandas.Series:
input_ = self.featurize_row(x.iloc[0], x.iloc[1]).reshape((1, -1))
elif x is pandas.DataFrame:
... | Predict the causal score using a trained RCC model
Args:
x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.
args (numpy.array): second variable (optional depending on the 1st argument).
Returns:
float: Causation score (Value : 1 if a->b and -1 if b->a) | juraj-google-style |
def stop_apppool(name):
ps_cmd = ['Stop-WebAppPool', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return (cmd_ret['retcode'] == 0) | Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool' | codesearchnet |
def cycle_find(key, width=4):
key_len = len(key)
buf = ''
it = deBruijn(width, 26)
for i in range(key_len):
buf += chr((ord('A') + next(it)))
if (buf == key):
return 0
for (i, c) in enumerate(it):
buf = (buf[1:] + chr((ord('A') + c)))
if (buf == key):
... | Given an element of a de Bruijn sequence, find its index in that sequence.
Args:
key(str): The piece of the de Bruijn sequence to find.
width(int): The width of each element in the sequence.
Returns:
int: The index of ``key`` in the de Bruijn sequence. | codesearchnet |
def get_client_kwargs(self, path):
bucket_name, key = self.split_locator(path)
kwargs = dict(Bucket=bucket_name)
if key:
kwargs['Key'] = key
return kwargs | Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args | juraj-google-style |
def GetVolumeSystemTypeIndicators(cls, path_spec, resolver_context=None):
if (cls._volume_system_remainder_list is None or
cls._volume_system_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_VOLUME_SYSTEM)
cls._volume_sy... | Determines if a file contains a supported volume system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators. | juraj-google-style |
def unpackStruct(self, data, def_buf):
struct_str = "="
for fld in def_buf:
if not def_buf[fld][MeterData.CalculatedFlag]:
struct_str = struct_str + str(def_buf[fld][MeterData.SizeValue]) + "s"
if len(data) == 255:
contents = struct.unpack(struct_... | Wrapper for struct.unpack with SerialBlock buffer definitionns.
Args:
data (str): Implicit cast bytes to str, serial port return.
def_buf (SerialBlock): Block object holding field lengths.
Returns:
tuple: parsed result of struct.unpack() with field definitions. | juraj-google-style |
def replace_batch_norm(model):
for name, module in model.named_children():
if isinstance(module, nn.BatchNorm2d):
new_module = DetrFrozenBatchNorm2d(module.num_features)
if not module.weight.device == torch.device('meta'):
new_module.weight.data.copy_(module.weight)
... | Recursively replace all `torch.nn.BatchNorm2d` with `DetrFrozenBatchNorm2d`.
Args:
model (torch.nn.Module):
input model | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.