code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def remove_send_last_message(self, connection):
if (connection in self._send_last_message):
del self._send_last_message[connection]
LOGGER.debug('Removed send_last_message function for connection %s', connection)
else:
LOGGER.warning('Attempted to remove send_last_message function for co... | Removes a send_last_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages. | codesearchnet |
def repeat(self, caller: Caller[RequestT, ResponseT], request: RequestT, timeout: float, metrics_collector: Optional[_MetricsCollector]) -> ResponseT:
pass | Implements a repeater strategy for RequestResponseIO when a repeater
is enabled.
Args:
caller: a `~apache_beam.io.requestresponse.Caller` object that
calls the API.
request: input request to repeat.
timeout: time to wait for the request to complete.
metrics_collector: (Optional) a
`~apache_beam.io.requestresponse._Met... | github-repos |
def _GetTypeFromScope(self, package, type_name, scope):
if (type_name not in scope):
components = _PrefixWithDot(package).split('.')
while components:
possible_match = '.'.join((components + [type_name]))
if (possible_match in scope):
type_name = possible_matc... | Finds a given type name in the current scope.
Args:
package: The package the proto should be located in.
type_name: The name of the type to be found in the scope.
scope: Dict mapping short and full symbols to message and enum types.
Returns:
The descriptor for the requested type. | codesearchnet |
def author_name_contains_fullnames(author_name):
def _is_initial(name_part):
return ((len(name_part) == 1) or (u'.' in name_part))
parsed_name = ParsedName(author_name)
if (len(parsed_name) == 1):
return False
elif any([_is_initial(name_part) for name_part in parsed_name]):
retu... | Recognizes whether the name contains full name parts and not initials or only lastname.
Returns:
bool: True if name has only full name parts, e.g. 'Ellis John', False otherwise. So for example, False is
returned for 'Ellis, J.' or 'Ellis'. | codesearchnet |
def chip_as_adjacency_list(device: 'cirq.google.XmonDevice') -> Dict[(GridQubit, List[GridQubit])]:
c_set = set(device.qubits)
c_adj = {}
for n in device.qubits:
c_adj[n] = []
for m in [above(n), left_of(n), below(n), right_of(n)]:
if (m in c_set):
c_adj[n].append... | Gives adjacency list representation of a chip.
The adjacency list is constructed in order of above, left_of, below and
right_of consecutively.
Args:
device: Chip to be converted.
Returns:
Map from nodes to list of qubits which represent all the neighbours of
given qubit. | codesearchnet |
def param_static_shapes(cls, sample_shape):
if isinstance(sample_shape, tensor_shape.TensorShape):
if not sample_shape.is_fully_defined():
raise ValueError('TensorShape sample_shape must be fully defined')
sample_shape = sample_shape.as_list()
params = cls.param_shapes(sample_shape)
... | param_shapes with static (i.e. `TensorShape`) shapes.
This is a class method that describes what key/value arguments are required
to instantiate the given `Distribution` so that a particular shape is
returned for that instance's call to `sample()`. Assumes that the sample's
shape is known statically.
Subclasses shoul... | github-repos |
def StartsWithIgnoreCase(self, value):
self._awql = self._CreateSingleValueCondition(value, 'STARTS_WITH_IGNORE_CASE')
return self._query_builder | Sets the type of the WHERE clause as "starts with ignore case".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to. | codesearchnet |
def export_disks(self, standalone, dst_dir, compress, collect_only=False, with_threads=True, *args, **kwargs):
vm_export_mgr = export.VMExportManager(*args, disks=self.vm.disks, dst=dst_dir, compress=compress, with_threads=with_threads, standalone=standalone, **kwargs)
if collect_only:
return {self.vm.n... | Export all the disks of self.
Args:
standalone (bool): if true, merge the base images and the layered
image into a new file (Supported only in qcow2 format)
dst_dir (str): dir to place the exported disks
compress(bool): if true, compress each disk.
collect_only(bool): If true, return only a dict which maps between
the... | codesearchnet |
def assign_selective_dynamics(self, slab):
sd_list = []
sd_list = [[False, False, False] if site.properties['surface_properties'] == 'subsurface'
else [True, True, True] for site in slab.sites]
new_sp = slab.site_properties
new_sp['selective_dynamics'] = sd_li... | Helper function to assign selective dynamics site_properties
based on surface, subsurface site properties
Args:
slab (Slab): slab for which to assign selective dynamics | juraj-google-style |
def smash(self):
self._initialize_smash()
try:
stack_name = self._config.get('environment', {}).get('stack_name', None)
response = self._cloudFormation.describe_stacks(StackName=stack_name)
logging.debug('smash pre-flight returned: {}'.format(
... | Smash the given stack
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems. | juraj-google-style |
def connections(self):
if (not self.__connections):
self.__connections = Connections(self.__connection)
return self.__connections | Gets the Connections API client.
Returns:
Connections: | codesearchnet |
def data_it(db_data, user_type):
data_type = {
'array': (list),
'dict': (dict),
'entity': (dict),
'list': (list),
'str': (string_types),
'string': (string_types),
}
if use... | Validate data is type.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation. | juraj-google-style |
def get_actions(self, parent_environ=None):
interp = Python(target_environ={}, passive=True)
executor = self._create_executor(interp, parent_environ)
self._execute(executor)
return executor.actions | Get the list of rex.Action objects resulting from interpreting this
context. This is provided mainly for testing purposes.
Args:
parent_environ Environment to interpret the context within,
defaults to os.environ if None.
Returns:
A list of rex.Action subclass instances. | codesearchnet |
def ParseChat(self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
participants = self._GetRowValue(query_hash, row, 'participants')
author = self._GetRowValue(query_hash, row, 'author')
dialog_partner = self._GetRowValue(query_hash, row, 'dialog_partner')
from_display... | Parses a chat message.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row resulting from query. | juraj-google-style |
def create_customer(self, *, full_name, email):
payload = {
"fullName": full_name,
"email": email
}
return self.client._post(self.url + 'customers', json=payload, headers=self.get_headers()) | Creation of a customer in the system.
Args:
full_name: Customer's complete name.
Alphanumeric. Max: 255.
email: Customer's email address.
Alphanumeric. Max: 255.
Returns: | juraj-google-style |
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4,
'For C++11-compatibility, omit template arguments from make_pa... | Check that make_pair's template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of ... | juraj-google-style |
class TFDebertaV2StableDropout(keras.layers.Layer):
def __init__(self, drop_prob, **kwargs):
super().__init__(**kwargs)
self.drop_prob = drop_prob
@tf.custom_gradient
def xdropout(self, inputs):
mask = tf.cast(1 - tf.compat.v1.distributions.Bernoulli(probs=1.0 - self.drop_... | Optimized dropout module for stabilizing the training
Args:
drop_prob (float): the dropout probabilities | github-repos |
async def trio_open_connection(host, port, *, ssl=False, **kwargs):
import trio
if (not ssl):
sock = (await trio.open_tcp_stream(host, port))
else:
if isinstance(ssl, bool):
ssl_context = None
else:
ssl_context = ssl
sock = (await trio.open_ssl_over_tc... | Allows connections to be made that may or may not require ssl.
Somewhat surprisingly trio doesn't have an abstraction for this like
curio even though it's fairly trivial to write. Down the line hopefully.
Args:
host (str): Network location, either by domain or IP.
port (int): The requested port.
ssl (bool or SSLContex... | codesearchnet |
async def download_file(context, url, abs_filename, session=None, chunk_size=128):
session = (session or context.session)
loggable_url = get_loggable_url(url)
log.info('Downloading %s', loggable_url)
parent_dir = os.path.dirname(abs_filename)
async with session.get(url) as resp:
if (resp.sta... | Download a file, async.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to download
abs_filename (str): the path to download to
session (aiohttp.ClientSession, optional): the session to use. If
None, use context.session. Defaults to None.
chunk_size (int, optional): the chu... | codesearchnet |
def __init__(self, *args, **kwargs):
super(ContractTransaction, self).__init__(*args, **kwargs)
self.Type = TransactionType.ContractTransaction | Create an instance.
Args:
*args:
**kwargs: | juraj-google-style |
def raster_to_gtiff(tif, geotif, change_nodata=False, change_gdal_type=False):
rst_file = RasterUtilClass.read_raster(tif)
nodata = rst_file.noDataValue
if change_nodata:
if (not MathClass.floatequal(rst_file.noDataValue, DEFAULT_NODATA)):
nodata = DEFAULT_NODATA
rst_file.dat... | Converting Raster format to GeoTIFF.
Args:
tif: source raster file path.
geotif: output raster file path.
change_nodata: change NoDataValue to -9999 or not.
gdal_type (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default.
change_gdal_type: If True, output the Float32 data type. | codesearchnet |
def run_inference(self, batch: Sequence[pandas.DataFrame], model: Union[xgboost.Booster, xgboost.XGBModel], inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResult]:
return self._inference_fn(batch, model, inference_args) | Runs inferences on a batch of pandas dataframes.
Args:
batch: A sequence of examples as pandas dataframes. Each
row in a dataframe is a single example. The dimensions
must match the dimensions of the data used to train
the model.
model: XGBoost booster or XBGModel (sklearn interface). Must
implement predict(X). Where ... | github-repos |
def __init__(self, expected_methods):
if not expected_methods:
raise ValueError("There must be at least one expected method")
Error.__init__(self)
self._expected_methods = expected_methods | Init exception.
Args:
# expected_methods: A sequence of MockMethod objects that should have been
# called.
expected_methods: [MockMethod]
Raises:
ValueError: if expected_methods contains no methods. | juraj-google-style |
def verify(self, token, **kwargs):
path = '/runners/verify'
post_data = {'token': token}
self.gitlab.http_post(path, post_data=post_data, **kwargs) | Validates authentication credentials for a registered Runner.
Args:
token (str): The runner's authentication token
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabVerifyError: If the server failed to verify the token | codesearchnet |
def cmd_path(self, cmd):
for binscript in self.bin.files:
if binscript.path.endswith('/{0}'.format(cmd)):
return binscript.path
raise ValueError('The command {0} was not found.'.format(cmd)) | Get the path of a command in the virtual if it exists.
Args:
cmd (str): The command to look for.
Returns:
str: The full path to the command.
Raises:
ValueError: If the command is not present. | codesearchnet |
def archive(self, output_path):
if (self.path is None):
raise ArgumentError('Cannot archive a recipe yet without a reference to its original yaml file in self.path')
outfile = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
outfile.write(self.path, arcname='recipe_script.yaml')
written_f... | Archive this recipe and all associated files into a .ship archive.
Args:
output_path (str): The path where the .ship file should be saved. | codesearchnet |
def __rmod__(self, other):
other = as_dimension(other)
return other % self | Returns `other` modulo `self`.
Args:
other: Another Dimension, or a value accepted by `as_dimension`.
Returns:
A Dimension whose value is `other` modulo `self`. | github-repos |
def set_float(self, option, value):
if (not isinstance(value, float)):
raise TypeError('Value must be a float')
self.options[option] = value | Set a float option.
Args:
option (str): name of option.
value (float): value of the option.
Raises:
TypeError: Value must be a float. | codesearchnet |
def get_font(self, weight='medium', slant='upright', width='normal'):
def find_closest_style(style, styles, alternatives):
try:
return style, styles[style]
except KeyError:
for option in alternatives[style]:
try:
... | Return the font matching or closest to the given style
If a font with the given weight, slant and width is available, return
it. Otherwise, return the font that is closest in style.
Args:
weight (FontWeight): weight of the font
slant (FontSlant): slant of the font
width (FontWidth): width of the font
Returns:
Font: ... | juraj-google-style |
def rename(self, new_folder_name):
headers = self.headers
endpoint = ('https:
payload = (('{ "DisplayName": "' + new_folder_name) + '"}')
r = requests.patch(endpoint, headers=headers, data=payload)
if check_response(r):
return_folder = r.json()
return self._json_to_folder(self.accoun... | Renames the Folder to the provided name.
Args:
new_folder_name: A string of the replacement name.
Raises:
AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token.
Returns:
A new Folder representing the folder with the new name on Outlook. | codesearchnet |
def step1_get_device_and_user_codes(self, http=None):
if (self.device_uri is None):
raise ValueError('The value of device_uri must not be None.')
body = urllib.parse.urlencode({'client_id': self.client_id, 'scope': self.scope})
headers = {'content-type': 'application/x-www-form-urlencoded'}
if (... | Returns a user code and the verification URL where to enter it
Returns:
A user code as a string for the user to authorize the application
An URL as a string where the user has to enter the code | codesearchnet |
def get_country_name(self, callsign, timestamp=timestamp_now):
return self.get_all(callsign, timestamp)[const.COUNTRY] | Returns the country name where the callsign is located
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
str: name of the Country
Raises:
KeyError: No Country found for callsign
Note:
Don't rely on the country name when working with several insta... | codesearchnet |
def process_event(self, event_name: str, data: dict) -> None:
if event_name == "after_validation":
if data['impatience'] > self._learning_rate_last_impatience:
self._learning_rate_cur_impatience += 1
else:
self._learning_rate_cur_impatience = 0
... | Update learning rate and momentum variables after event (given by `event_name`)
Args:
event_name: name of event after which the method was called.
Set of values: `"after_validation"`, `"after_batch"`, `"after_epoch"`, `"after_train_log"`
data: dictionary with parameters values
Returns:
None | juraj-google-style |
def dark(app):
_apply_base_theme(app)
darkPalette = QPalette()
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Light, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Midligh... | Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance. | juraj-google-style |
def from_config(cls, config):
config = config.copy()
function_keys = ['kernel_posterior_fn', 'kernel_posterior_tensor_fn', 'kernel_prior_fn', 'kernel_divergence_fn', 'bias_posterior_fn', 'bias_posterior_tensor_fn', 'bias_prior_fn', 'bias_divergence_fn']
for function_key in function_keys:
serial = co... | Creates a layer from its config.
This method is the reverse of `get_config`, capable of instantiating the
same layer from the config dictionary.
Args:
config: A Python dictionary, typically the output of `get_config`.
Returns:
layer: A layer instance. | codesearchnet |
def can_api_key_access_build(param_name):
build_id = (request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name])
utils.jsonify_assert(build_id, 'build_id required')
if app.config.get('IGNORE_AUTH'):
api_key = models.ApiKey(id='anonymous_superuser', ... | Determines if the current API key can access the build in the request.
Args:
param_name: Parameter name to use for getting the build ID from the
request. Will fetch from GET or POST requests.
Returns:
(api_key, build) The API Key and the Build it has access to. | codesearchnet |
def agent_heartbeat(self, agent_id, metrics, run_states):
mutation = gql()
try:
response = self.gql(mutation, variable_values={
'id': agent_id,
'metrics': json.dumps(metrics),
'runState': json.dumps(run_states)})
except Excepti... | Notify server about agent state, receive commands.
Args:
agent_id (str): agent_id
metrics (dict): system metrics
run_states (dict): run_id: state mapping
Returns:
List of commands to execute. | juraj-google-style |
def _CreateFeedItems(client, feed_details, label_name):
feed_item_service = client.GetService('FeedItemService', version='v201809')
urls = ('http:
operations = [{'operand': {'feedId': feed_details.feed_id, 'attributeValues': [{'feedAttributeId': feed_details.url_attribute_id, 'stringValues': [url]}, {'feedA... | Creates the page URLs in the DSA page feed.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
label_name: a str containing the page feed URL label. | codesearchnet |
def _process_new(self, feed_item):
return {'name': feed_item.get(FieldMap.CAMPAIGN_LANDING_PAGE_NAME, None), 'url': feed_item.get(FieldMap.CAMPAIGN_LANDING_PAGE_URL, None), 'advertiserId': feed_item.get(FieldMap.ADVERTISER_ID, None)} | Creates a new landing page DCM object from a feed item representing a landing page from the Bulkdozer feed.
This function simply creates the object to be inserted later by the BaseDAO
object.
Args:
feed_item: Feed item representing the landing page from the Bulkdozer
feed.
Returns:
An landing page object ready to be... | github-repos |
def __init__(self, worker):
super(ClientStatsCollector, self).__init__()
self.daemon = True
self._worker = worker
self._process = psutil.Process()
self._cpu_samples = []
self._io_samples = []
self._last_send_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(0)
self._should_send =... | Initializes the stat collector.
Args:
worker: A `GRRClientWorker` instance that spawned this stat collector. | juraj-google-style |
def free(object_ids, local_only=False, delete_creating_tasks=False):
worker = ray.worker.get_global_worker()
if (ray.worker._mode() == ray.worker.LOCAL_MODE):
return
if isinstance(object_ids, ray.ObjectID):
object_ids = [object_ids]
if (not isinstance(object_ids, list)):
raise Ty... | Free a list of IDs from object stores.
This function is a low-level API which should be used in restricted
scenarios.
If local_only is false, the request will be send to all object stores.
This method will not return any value to indicate whether the deletion is
successful or not. This function is an instruction to ... | codesearchnet |
def forward(self, x):
if self.training and self.drop_prob > 0:
return XDropout.apply(x, self.get_context())
return x | Call the module
Args:
x (`torch.tensor`): The input tensor to apply dropout | github-repos |
def pull(handle, enumerate=False):
assert isinstance(handle, Handle), handle
return Pull(handle, enumerate) | Pulls next message for handle.
Args:
handle: A :class:`.stream.Handle` or GroupHandle.
enumerate (bool): boolean to indicate whether a tuple ``(idx, msg)``
should be returned, not unlike Python's enumerate().
Returns:
A :class:`Pull` task to be yielded. Marv will send the
corresponding message as soon as it is availa... | codesearchnet |
def __parameter_enum(self, final_subfield):
if isinstance(final_subfield, messages.EnumField):
enum_descriptor = {}
for enum_value in final_subfield.type.to_dict().keys():
enum_descriptor[enum_value] = {'backendValue': enum_value}
return enum_descriptor | Returns enum descriptor of final subfield if it is an enum.
An enum descriptor is a dictionary with keys as the names from the enum and
each value is a dictionary with a single key "backendValue" and value equal
to the same enum name used to stored it in the descriptor.
The key "description" can also be used next to ... | codesearchnet |
def create_reset_score(cls, student_item):
return cls.objects.create(
student_item=student_item,
submission=None,
points_earned=0,
points_possible=0,
reset=True,
) | Create a "reset" score (a score with a null submission).
Only scores created after the most recent "reset" score
should be used to determine a student's effective score.
Args:
student_item (StudentItem): The student item model.
Returns:
Score: The newly created "reset" score.
Raises:
DatabaseError: An error occurre... | juraj-google-style |
def __init__(self,
application,
project_id,
control_client,
next_operation_id=_next_operation_uuid,
timer=datetime.utcnow):
self._application = application
self._project_id = project_id
self._control_cl... | Initializes a new Middleware instance.
Args:
application: the wrapped wsgi application
project_id: the project_id thats providing service control support
control_client: the service control client instance
next_operation_id (func): produces the next operation
timer (func[[datetime.datetime]]): a func that obtains the ... | juraj-google-style |
def early_stop_by_value(step_values: List[Tuple[int, float]], metric: Union[str, Callable[[pg.tuning.Measurement], float]]='reward', maximize: bool=True):
assert isinstance(step_values, list), step_values
for v in step_values:
if not isinstance(v, tuple) or len(v) != 2 or (not isinstance(v[0], int)) or ... | Step-wise early stopping policy based on the value of reward/metric.
Example::
policy = early_stop_by_value([
# Stop at step 1 if trial reward is less than 0.2.
(1, 0.2),
# Stop at step 2 if trial reward is less than 0.8.
(2, 0.8),
])()
Args:
step_values: A list of tuple (gating step, value threshold).
gating step ... | github-repos |
def get_sequence_properties(self, clean_seq=False, representative_only=True):
if representative_only:
if not self.representative_sequence:
log.warning('{}: no representative sequence set, cannot get sequence properties'.format(self.id))
return
... | Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of the protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
representative_only (bool): If analysis should only be run on the representative sequence | juraj-google-style |
def addFixedEffect(self, F=None, A=None):
if (A == None):
A = SP.eye(self.P)
if (F == None):
F = SP.ones((self.N, 1))
assert (A.shape[1] == self.P), 'Incompatible shape'
assert (F.shape[0] == self.N), 'Incompatible shape'
if (F.shape[1] > 1):
for m in range(F.shape[1]):
... | add fixed effect to the model
Args:
F: fixed effect matrix [N,1]
A: design matrix [K,P] (e.g. SP.ones((1,P)) common effect; SP.eye(P) any effect) | codesearchnet |
def encrypt(self, message, public_key):
max_str_len = rsa.common.byte_size(public_key.n) - 11
if len(message) > max_str_len:
message = textwrap.wrap(message, width=max_str_len)
else:
message = [message]
enc_msg = []
... | Encrypts a string using a given rsa.PublicKey object. If the message
is larger than the key, it will split it up into a list and encrypt
each line in the list.
Args:
message (string): The string to encrypt.
public_key (rsa.PublicKey): The key object used to encrypt the
message. Only the paired private key can decrypt ... | juraj-google-style |
def readlink(path):
if (sys.getwindowsversion().major < 6):
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
try:
return salt.utils.path.readlink(path)
except OSError as exc:
if (exc.errno == errno.EINVAL):
raise CommandExecutionError('{... | Return the path that a symlink points to
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path is
not a symlink, however, the error raised will be a SaltInvocationError, not
an OSError.
Args:
path (str): The path to the symlink
Returns:
str: The p... | codesearchnet |
def gpio_set(self, pins, states):
if len(pins) != len(states):
raise ValueError('Length mismatch between pins and states.')
size = len(pins)
indices = (ctypes.c_uint8 * size)(*pins)
states = (ctypes.c_uint8 * size)(*states)
result_states = (ctypes.c_uint8 * ... | Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
states (list): list of states to set
Returns:
A list of updated states.
Raises:
JLinkException: on err... | juraj-google-style |
def references_json(references):
references_json = []
for r in references:
ref = r.ref
ref['attributes'] = r._to_json_like(include_defaults=False)
references_json.append(ref)
return references_json | Given a list of all models in a graph, return JSON representing
them and their properties.
Args:
references (seq[Model]) :
A list of models to convert to JSON
Returns:
list | juraj-google-style |
def run(self, dag):
if (self.initial_layout is None):
if self.property_set['layout']:
self.initial_layout = self.property_set['layout']
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if (len(dag.qubits()) != len(self.initial_layout)):
... | Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG | codesearchnet |
def search(self, files=None, defined_fields=None, **kwargs):
if (defined_fields is None):
defined_fields = []
all_keys = (set(defined_fields) | set(kwargs.keys()))
if (not all_keys):
raise ValueError('At least one field to search on must be passed.')
if (files is None):
files = s... | Search files in the layout by metadata fields.
Args:
files (list): Optional list of names of files to search. If None,
all files in the layout are scanned.
defined_fields (list): Optional list of names of fields that must
be defined in the JSON sidecar in order to consider the file a
match, but which don't need to mat... | codesearchnet |
def get_hostname(url):
if url not in URLHelper.__cache:
URLHelper.__cache[url] = urlparse(url)
parts = URLHelper.__cache[url].netloc.split(".")
if len(parts) == 1:
return parts[0]
else:
return ".".join(parts[-2:-1]) | Get the hostname of the given URL.
Args:
url (str): The URL to get the hostname from.
Returns:
str: The hostname | juraj-google-style |
def remove_server_data(server_id):
logger.debug('Removing server from serverdata')
data = datatools.get_data()
if (server_id in data['discord']['servers']):
data['discord']['servers'].pop(server_id)
datatools.write_data(data) | Remove a server from the server data
Args:
server_id (int): The server to remove from the server data | codesearchnet |
def name_from_scope_name(name) -> str:
return name[:-1] if name and name[-1] == '/' else name | Returns the name of an op given the name of its scope.
Args:
name: the name of the scope.
Returns:
the name of the op (equal to scope name minus any trailing slash). | github-repos |
def size(self, path: str) -> int:
raise NotImplementedError | Get size in bytes of a file on the FileSystem.
Args:
path: string filepath of file.
Returns: int size of file according to the FileSystem.
Raises:
``BeamIOError``: if path doesn't exist. | github-repos |
def epoch_to_log_line_timestamp(epoch_time, time_zone=None):
s, ms = divmod(epoch_time, 1000)
d = datetime.datetime.fromtimestamp(s, tz=time_zone)
return d.strftime('%m-%d %H:%M:%S.') + str(ms) | Converts an epoch timestamp in ms to log line timestamp format, which
is readible for humans.
Args:
epoch_time: integer, an epoch timestamp in ms.
time_zone: instance of tzinfo, time zone information.
Using pytz rather than python 3.2 time_zone implementation for
python 2 compatibility reasons.
Returns:
A string that... | juraj-google-style |
def heightmap_clamp(hm: np.ndarray, mi: float, ma: float) -> None:
hm.clip(mi, ma) | Clamp all values on this heightmap between ``mi`` and ``ma``
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
mi (float): The lower bound to clamp to.
ma (float): The upper bound to clamp to.
.. deprecated:: 2.0
Do ``hm.clip(mi, ma)`` instead. | juraj-google-style |
def create_forwarding_information_base(self, timeout=-1):
uri = "{}{}".format(self.data["uri"], self.FORWARDING_INFORMATION_PATH)
return self._helper.do_post(uri, None, timeout, None) | Generates the forwarding information base dump file for a logical interconnect.
Args:
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
OneView, just stops waiting for its completion.
Returns: Interconnect Forwarding Information Base DataInfo. | juraj-google-style |
def save_config(self):
if (not self.opts['dirty_config'][1]):
if logger.isEnabledFor(logging.INFO):
logger.info('Config not saved (not modified)')
return 1
txt = '
copyfile(self.config_file, (self.config_file + '.restore'))
if (self.opts['default_station'][1] is None):
... | Save config file
Creates config.restore (back up file)
Returns:
-1: Error saving config
0: Config saved successfully
1: Config not saved (not modified | codesearchnet |
def get_output_embeddings(self) -> Union[None, keras.layers.Layer]:
if self.get_lm_head() is not None:
lm_head = self.get_lm_head()
try:
return lm_head.get_output_embeddings()
except AttributeError:
logger.info('Building the model')
self.build_in_name_scop... | Returns the model's output embeddings
Returns:
`tf.Variable`: The new weights mapping vocabulary to hidden states. | github-repos |
def resolve_revision(self, dest, url, rev_options):
rev = rev_options.arg_rev
sha, is_branch = self.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return r... | Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object. | juraj-google-style |
def ricker(f, length, dt):
t = np.linspace(-int(length/2), int((length-dt)/2), int(length/dt))
y = (1. - 2.*(np.pi**2)*(f**2)*(t**2))*np.exp(-(np.pi**2)*(f**2)*(t**2))
return t, y | A Ricker wavelet.
Args:
f (float): frequency in Haz, e.g. 25 Hz.
length (float): Length in s, e.g. 0.128.
dt (float): sample interval in s, e.g. 0.001.
Returns:
tuple. time basis, amplitude values. | juraj-google-style |
def __init__(self, context):
self._credentials = context.credentials
self._project_id = context.project_id | Initializes the Storage helper with context information.
Args:
context: a Context object providing project_id and credentials. | juraj-google-style |
def _start_reader_thread(self, stream, chunks):
import io
import threading
def target():
while True:
chunk = stream.read(io.DEFAULT_BUFFER_SIZE)
if (not chunk):
break
chunks.append(chunk)
thread = threading.Thread(target=target)
thread.sta... | Starts a thread for reading output from FFMPEG.
The thread reads consecutive chunks from the stream and saves them in
the given list.
Args:
stream: output stream of the FFMPEG process.
chunks: list to save output chunks to.
Returns:
Thread | codesearchnet |
def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:
batch_size, height, width, channel = hidden_states.shape
pad_h = (window_size - height % window_size) % window_size
pad_w = (window_size - width % window_size) % window_size
hidden_states =... | Args:
Partition into non-overlapping windows with padding if needed.
hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
size.
Returns:
windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
(pad_height, pad_width): pad... | github-repos |
def set_extra_selections(self, key, extra_selections):
draw_order = DRAW_ORDERS.get(key)
if draw_order is None:
draw_order = DRAW_ORDERS.get('on_top')
for selection in extra_selections:
selection.draw_order = draw_order
self.clear_extra_selecti... | Set extra selections for a key.
Also assign draw orders to leave current_cell and current_line
in the backgrund (and avoid them to cover other decorations)
NOTE: This will remove previous decorations added to the same key.
Args:
key (str) name of the extra selections group.
extra_selections (list of sourcecode.api.... | juraj-google-style |
def get_keys_from_ldap(self, username=None):
result_dict = {}
filter = ['(sshPublicKey=*)']
if username is not None:
filter.append('(uid={})'.format(username))
attributes = ['uid', 'sshPublicKey']
results = self.client.search(filter, attributes)
for r... | Fetch keys from ldap.
Args:
username Username associated with keys to fetch (optional)
Returns:
Array of dictionaries in '{username: [public keys]}' format | juraj-google-style |
def _create_state_graph(self, name):
import_collections = [
tf_v1.GraphKeys.GLOBAL_VARIABLES,
tf_v1.GraphKeys.MODEL_VARIABLES,
tf_v1.GraphKeys.TABLE_INITIALIZERS,
tf_v1.GraphKeys.ASSET_FILEPATHS,
tf_v1.GraphKeys.COND_CONTEXT,
tf_v1.GraphKeys.WHILE_CONTEXT,
... | Creates the graph nodes that hold the state of the Module.
Args:
name: name scope to create the state graph in.
Returns:
A tuple consisting of:
variables_tensor_map: a map from tensor names in the original graph def
to the created Variables objects.
state_map: a map from tensors names in the original graph def to the... | juraj-google-style |
def __init__(self, port=None, max_length=UBINT16_MAX_VALUE):
super().__init__(action_type=ActionType.OFPAT_OUTPUT, length=8)
self.port = port
self.max_length = max_length | Create an ActionOutput with the optional parameters below.
Args:
port (:class:`~pyof.v0x01.common.phy_port.Port` or :class:`int`):
Output port.
max_length (int): Max length to send to controller. | juraj-google-style |
def get_trace(self, project_id, trace_id):
trace_pb = self._gapic_api.get_trace(project_id, trace_id)
trace_mapping = _parse_trace_pb(trace_pb)
return trace_mapping | Gets a single trace by its ID.
Args:
trace_id (str): ID of the trace to return.
project_id (str): Required. ID of the Cloud project where the trace
data is stored.
Returns:
A Trace dict. | juraj-google-style |
def init_app(self, app, client_id=None):
if not self.client_id:
if client_id:
self.client_id = client_id
else:
self.client_id = app.name | Initialize the Micropub extension if it was not given app
in the constructor.
Args:
app (flask.Flask): the flask application to extend.
client_id (string, optional): the IndieAuth client id, will be
displayed when the user is asked to authorize this client. If not
provided, the app name will be used. | juraj-google-style |
def delete(self, filename):
for repo in self._children:
if hasattr(repo, 'delete'):
repo.delete(filename) | Delete a file from all repositories which support it.
Individual repositories will determine correct location to
delete from (Scripts vs. Packages).
This will not remove the corresponding Package or Script object
from the JSS's database!
Args:
filename: The filename you wish to delete (do not include a
path). | codesearchnet |
def from_authorized_user_file(cls, filename, scopes=None):
with io.open(filename, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
return cls.from_authorized_user_info(data, scopes) | Creates a Credentials instance from an authorized user json file.
Args:
filename (str): The path to the authorized user json file.
scopes (Sequence[str]): Optional list of scopes to include in the
credentials.
Returns:
google.oauth2.credentials.Credentials: The constructed
credentials.
Raises:
ValueError: If the fil... | juraj-google-style |
def get_centered_molecule(self):
center = self.center_of_mass
new_coords = (np.array(self.cart_coords) - center)
return self.__class__(self.species_and_occu, new_coords, charge=self._charge, spin_multiplicity=self._spin_multiplicity, site_properties=self.site_properties) | Returns a Molecule centered at the center of mass.
Returns:
Molecule centered with center of mass at origin. | codesearchnet |
def singleprint(self) -> fingerprinting_pywrap.Singleprint:
try:
return fingerprinting_pywrap.Singleprint(self.graph_def_program_hash, self.signature_def_hash, self.saved_object_graph_hash, self.checkpoint_hash)
except (TypeError, fingerprinting_pywrap.FingerprintException) as e:
raise ValueErro... | Canonical fingerprinting ID for a SavedModel.
Uniquely identifies a SavedModel based on the regularized fingerprint
attributes. (saved_model_checksum is sensitive to immaterial changes and
thus non-deterministic.)
Returns:
The string concatenation of `graph_def_program_hash`,
`signature_def_hash`, `saved_object_graph... | github-repos |
def _ProcessGRRMessages(self, fs_client_id, grr_messages):
grr_client_id = fleetspeak_utils.FleetspeakIDToGRRID(fs_client_id)
for grr_message in grr_messages:
grr_message.source = grr_client_id
grr_message.auth_state = (
rdf_flows.GrrMessage.AuthorizationState.AUTHENTICATED)
clien... | Handles messages from GRR clients received via Fleetspeak.
This method updates the last-ping timestamp of the client before beginning
processing.
Args:
fs_client_id: The Fleetspeak client-id for the client.
grr_messages: An Iterable of GrrMessages. | juraj-google-style |
def handle(self, message):
opcode = message['op']
if opcode == 10:
self.on_hello(message)
elif opcode == 11:
self.on_heartbeat(message)
elif opcode == 0:
self.on_message(message)
else:
logger.debug("Not a message we handle... | Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection | juraj-google-style |
def save_subset_weights_to_hdf5_group(f, weights):
weight_values = [backend.convert_to_numpy(w) for w in weights]
weight_names = [str(w.path).encode('utf8') for w in weights]
save_attributes_to_hdf5_group(f, 'weight_names', weight_names)
for name, val in zip(weight_names, weight_values):
param_d... | Save top-level weights of a model to a HDF5 group.
Args:
f: HDF5 group.
weights: List of weight variables. | github-repos |
def _FormatTokenData(self, token_type, token_data):
token_data_format_function = self._TOKEN_DATA_FORMAT_FUNCTIONS.get(
token_type)
if token_data_format_function:
token_data_format_function = getattr(
self, token_data_format_function, None)
if not token_data_format_function:
... | Formats the token data as a dictionary of values.
Args:
token_type (int): token type.
token_data (object): token data.
Returns:
dict[str, str]: formatted token values or an empty dictionary if no
formatted token values could be determined. | juraj-google-style |
def build_pipeline_args(cls, project, script, job_params, task_params, reserved_labels, preemptible, logging_uri, scopes, keep_alive):
inputs = {}
inputs.update({SCRIPT_VARNAME: script})
inputs.update({var.name: var.value for var in (job_params['envs'] | task_params['envs']) if var.value})
inputs.update... | Builds pipeline args for execution.
Args:
project: string name of project.
script: Body of the script to execute.
job_params: dictionary of values for labels, envs, inputs, and outputs
for this job.
task_params: dictionary of values for labels, envs, inputs, and outputs
for this task.
reserved_labels: dictionary of re... | codesearchnet |
def _build_insert_compiler(self, rows: List[Dict]):
objs = []
field_count = len(rows[0])
for (index, row) in enumerate(rows):
if (field_count != len(row)):
raise SuspiciousOperation('In bulk upserts, you cannot have rows with different field configurations. Row {0} has a different field ... | Builds the SQL compiler for a insert query.
Arguments:
rows:
A list of dictionaries, where each entry
describes a record to insert.
Returns:
The SQL compiler for the insert. | codesearchnet |
def upload_benchmark_data(client, data):
test_result = json.loads(data)
test_name = str(test_result['name'])
start_time = datetime.datetime.utcfromtimestamp(float(test_result['startTime']))
batch = []
t_key = client.key('Test')
t_val = datastore.Entity(t_key, exclude_from_indexes=['info'])
t... | Parse benchmark data and use the client to upload it to the datastore.
Parse the given benchmark data from the serialized JSON-format used to write
the test results file. Create the different datastore Entities from that data
and upload them to the datastore in a batch using the client connection.
Args:
client: data... | github-repos |
def console_get_background_flag(con: tcod.console.Console) -> int:
return int(lib.TCOD_console_get_background_flag(_console(con))) | Return this consoles current blend mode.
Args:
con (Console): Any Console instance.
.. deprecated:: 8.5
Check :any:`Console.default_bg_blend` instead. | juraj-google-style |
def save_own_variables(self, store):
all_vars = self._trainable_variables + self._non_trainable_variables
for i, v in enumerate(all_vars):
store[f'{i}'] = v | Saves the state of the layer.
You can override this method to take full control of how the state of
the layer is saved upon calling `model.save()`.
Args:
store: Dict where the state of the model will be saved. | github-repos |
def date_added(self, date_added):
date_added = self._utils.format_datetime(date_added, date_format='%Y-%m-%dT%H:%M:%SZ')
self._data['dateAdded'] = date_added
request = self._base_request
request['dateAdded'] = date_added
return self._tc_requests.update(request, owner=self.owner) | Updates the security labels date_added
Args:
date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format | codesearchnet |
def __driver_completer(self, toks, text, state):
if state != 0:
return self.__completion_candidates[state]
if not toks or (len(toks) == 1 and text == toks[0]):
try:
self.__completion_candidates = self.__complete_cmds(text)
... | Driver level completer.
Arguments:
toks: A list of tokens, tokenized from the original input line.
text: A string, the text to be replaced if a completion candidate is
chosen.
state: An integer, the index of the candidate out of the list of
candidates.
Returns:
A string, the candidate. | juraj-google-style |
def _map_query_path_to_location_info(query_metadata_table):
query_path_to_location_info = {}
for location, location_info in query_metadata_table.registered_locations:
if not isinstance(location, Location):
continue
if location.query_path in query_path_to_location_info:
... | Create a map from each query path to a LocationInfo at that path.
Args:
query_metadata_table: QueryMetadataTable, object containing all metadata collected during
query processing, including location metadata (e.g. which locations
are folded or optional).
Returns:
Dict[Tuple[str], LocationInfo], dictionary mapping que... | juraj-google-style |
def __init__(self, message=None, parser_chain=None, path_spec=None):
super(ExtractionWarning, self).__init__()
self.message = message
self.parser_chain = parser_chain
self.path_spec = path_spec | Initializes an extraction warning.
Args:
message (Optional[str]): warning message.
parser_chain (Optional[str]): parser chain to which the warning applies.
path_spec (Optional[dfvfs.PathSpec]): path specification of the file entry
to which the warning applies. | juraj-google-style |
def mark_typed_map(self, name, type_object):
if (not hasattr(type_object, 'dump')):
raise ArgumentError(('The passed type object %s is missing required method: dump()' % type_object))
if (not hasattr(type_object, 'Restore')):
raise ArgumentError(('The passed type object %s is missing required me... | Mark a property as containing a map str to serializable object.
This convenience method allows you to avoid having to call
``mark_complex()`` whenever you need to serialize a dict of objects.
This method requires that all members of the given dict be of a single
class that contains a dump() method and a Restore() clas... | codesearchnet |
def process_node(layer, node_data):
input_tensors = []
for input_data in nest.flatten(node_data):
input_data = input_data.as_list()
inbound_layer_name = input_data[0]
inbound_node_index = input_data[1]
inbound_tensor_index = input_data[2]
if len(input_data) == 3:
... | Deserialize a node.
Args:
layer: layer instance.
node_data: Nested structure of `ListWrapper`.
Raises:
ValueError: In case of improperly formatted `node_data`. | github-repos |
def g_step(self, gen_frames, fake_logits_stop):
hparam_to_gen_loss = {
"least_squares": gan_losses.least_squares_generator_loss,
"cross_entropy": gan_losses.modified_generator_loss,
"wasserstein": gan_losses.wasserstein_generator_loss
}
fake_logits = self.discriminator(gen_fram... | Performs the generator step in computing the GAN loss.
Args:
gen_frames: Generated frames
fake_logits_stop: Logits corresponding to the generated frames as per
the discriminator. Assumed to have a stop-gradient term.
Returns:
gan_g_loss_pos_d: Loss.
gan_g_loss_neg_d: -gan_g_loss_pos_d but with a stop gradient on gener... | juraj-google-style |
def validate_file(fn, options=None):
file_results = FileValidationResults(filepath=fn)
output.info("Performing JSON schema validation on %s" % fn)
if not options:
options = ValidationOptions(files=fn)
try:
with open(fn) as instance_file:
file_results.object_results = v... | Validate the input document `fn` according to the options passed in.
If any exceptions are raised during validation, no further validation
will take place.
Args:
fn: The filename of the JSON file to be validated.
options: An instance of ``ValidationOptions``.
Returns:
An instance of FileValidationResults. | juraj-google-style |
def _get_stack_depth(package, fqdn, defdepth=_def_stackdepth):
global _stack_config
if (package not in _stack_config):
from acorn.config import settings
spack = settings(package)
_stack_config[package] = {}
secname = 'logging.depth'
if spack.has_section(secname):
... | Loads the stack depth settings from the config file for the specified
package.
Args:
package (str): name of the package to get stack depth info for.
fqdn (str): fully qualified domain name of the member in the package.
defdepth (int): default depth when one has not been configured. | codesearchnet |
def training_step(self, model: nn.Module, inputs: dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[torch.Tensor]=None) -> torch.Tensor:
model.train()
if hasattr(self.optimizer, 'train') and callable(self.optimizer.train):
self.optimizer.train()
inputs = self._prepare_inputs(inputs)
... | Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Args:
model (`nn.Module`):
The model to train.
inputs (`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targ... | github-repos |
def __spread__(y, yy, n, x, m):
nfac=[0,1,1,2,6,24,120,720,5040,40320,362880]
if m > 10. :
print('factorial table too small in spread')
return
ix=long(x)
if x == float(ix):
yy[ix]=yy[ix]+y
else:
ilo = long(x-0.5*float(m)+1.0)
ilo = min( max( ilo , 1 ), n-m+1 )
ihi = ilo+m-1
nde... | Given an array yy(0:n-1), extirpolate (spread) a value y into
m actual array elements that best approximate the "fictional"
(i.e., possible noninteger) array element number x. The weights
used are coefficients of the Lagrange interpolating polynomial
Arguments:
y :
yy :
n :
x :
m :
Returns: | juraj-google-style |
def is_applicable_python_file(rel_path: str) -> bool:
return (rel_path.endswith('.py') and
not any(re.search(pat, rel_path) for pat in IGNORED_FILE_PATTERNS)) | Determines if a file should be included in incremental coverage analysis.
Args:
rel_path: The repo-relative file path being considered.
Returns:
Whether to include the file. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.