Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
9,700 | def paged_object_to_list(paged_object):
paged_return = []
while True:
try:
page = next(paged_object)
paged_return.append(page.as_dict())
except CloudError:
raise
except StopIteration:
break
return paged_return | Extract all pages within a paged object as a list of dictionaries |
9,701 | def replace_name(file_path, new_name):
if not file_path:
raise Exception("File path cannot be empty")
elif not new_name:
raise Exception("New name cannot be empty")
dirname = os.path.dirname(file_path)
ext = os.path.splitext(os.path.basename(file_path))[1... | Change the file name in a path but keep the extension |
9,702 | def proj4_to_epsg(projection):
def make_definition(value):
return {x.strip().lower() for x in value.split() if x}
match = EPSG_RE.search(projection.srs)
if match:
return int(match.group(1))
pyproj_data_dir = os.path.join(os.path.dirname(pyproj.__file__), )
pyproj_ep... | Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails |
9,703 | def call_action(self, service_name, action_name, **kwargs):
action = self.services[service_name].actions[action_name]
return action.execute(**kwargs) | Executes the given action. Raise a KeyError on unkown actions. |
9,704 | def unpack(self, buff, offset=0):
super().unpack(buff, offset)
try:
self.oxm_field = self._unpack_oxm_field()
except ValueError as exception:
raise UnpackException(exception)
self.oxm_hasmask = (self.oxm_field_and_mask & 1) == 1
... | Unpack the buffer into a OxmTLV.
Args:
buff (bytes): The binary data to be unpacked.
offset (int): If we need to shift the beginning of the data. |
9,705 | def _set_route_target_evpn(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("action target_community",route_target_evpn.route_target_evpn, yang_name="route-target-evpn", rest_name="route-target", parent=self, is_container=, user_ordered=Fa... | Setter method for route_target_evpn, mapped from YANG variable /vrf/address_family/ipv6/unicast/route_target_container_ipv6/route_target_evpn (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_route_target_evpn is considered as a private
method. Backends looking to popul... |
9,706 | def complete_reminder(self, reminder_id, complete_dict):
return self._create_put_request(
resource=REMINDERS,
billomat_id=reminder_id,
command=COMPLETE,
send_data=complete_dict
) | Completes a reminder
:param complete_dict: the complete dict with the template id
:param reminder_id: the reminder id
:return: Response |
9,707 | def _generate_new_address(self, creator=None) -> str:
if creator:
return "0x" + str(mk_contract_address(creator, 0).hex())
while True:
address = "0x" + "".join([str(hex(randint(0, 16)))[-1] for _ in range(40)])
if address not in self.accounts.key... | Generates a new address for the global state.
:return: |
9,708 | def insert(self, context):
module_file = open(context.resolve(self.__path), "rb")
data = {
"name": self.__name
}
if self.__context_root is not None:
data["contextroot"] = self.__context_root
status_code, msg = self.__endpoint.post(
"/applications/application",
data=data,
files={
"id... | Deploy application.
:param resort.engine.execution.Context context:
Current execution context. |
9,709 | def _resolve_api_id(self):
apis = __salt__[](name=self.rest_api_name,
description=_Swagger.AWS_API_DESCRIPTION,
**self._common_aws_args).get()
if apis:
if len(apis) == 1... | returns an Api Id that matches the given api_name and the hardcoded _Swagger.AWS_API_DESCRIPTION
as the api description |
9,710 | def share_network(network_id, usernames, read_only, share,**kwargs):
user_id = kwargs.get()
net_i = _get_network(network_id)
net_i.check_share_permission(user_id)
if read_only == :
write =
share =
else:
write =
if net_i.created_by != int(user_id) and share == :... | Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users |
9,711 | def add_mismatch(self, entity, *traits):
for trait in traits:
self.index[trait].add(entity) | Add a mismatching entity to the index.
We do this by simply adding the mismatch to the index.
:param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`
:param list traits: a list of hashable traits to index the entity with |
9,712 | def resume(self):
if self.get_state() != Target.TARGET_HALTED:
logging.debug()
return
self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_RESUME))
self._run_token += 1
self.clear_debug_cause_bits()
self.write_mem... | resume the execution |
9,713 | def set_context(self, data):
for key in data:
setattr(self.local_context, key, data[key]) | Load Context with data |
9,714 | def order_by(self, field, orientation=):
if isinstance(field, list):
self.raw_order_by.append(field)
else:
self.raw_order_by.append([field, orientation])
return self | Indica los campos y el criterio de ordenamiento |
9,715 | def QueueQueryAndOwn(self, queue, lease_seconds, limit, timestamp):
try:
lock = DB.LockRetryWrapper(queue, lease_time=lease_seconds)
return self._QueueQueryAndOwn(
lock.subject,
lease_seconds=lease_seconds,
limit=limit,
timestamp=timestamp)
except DB... | Returns a list of Tasks leased for a certain time.
Args:
queue: The queue to query from.
lease_seconds: The tasks will be leased for this long.
limit: Number of values to fetch.
timestamp: Range of times for consideration.
Returns:
A list of GrrMessage() objects leased. |
9,716 | def _raise_on_mode(self, mode):
valid_modes = [
,
,
,
,
,
,
]
if mode not in valid_modes:
raise ValueError(
.format(mode, valid_modes)
) | Checks that the provided query mode is one of the accepted values. If
not, raises a :obj:`ValueError`. |
9,717 | def getStats(self):
if self._stats == None:
assert self._mode == self._FILE_READ_MODE
inFile = open(self._filename, self._FILE_READ_MODE)
reader = csv.reader(inFile, dialect="excel")
names = [n.strip() for n in reader.next()]
types = [t.strip() for ... | Parse the file using dedicated reader and collect fields stats. Never
called if user of :class:`~.FileRecordStream` does not invoke
:meth:`~.FileRecordStream.getStats` method.
:returns:
a dictionary of stats. In the current implementation, min and max
fields are supported. Example of th... |
9,718 | def do_classdesc(self, parent=None, ident=0):
clazz = JavaClass()
log_debug("[classdesc]", ident)
class_name = self._readString()
clazz.name = class_nam... | Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object |
9,719 | def update_cursor(self, dc, grid, row, col):
old_row, old_col = self.old_cursor_row_col
bgcolor = get_color(config["background_color"])
self._draw_cursor(dc, grid, old_row, old_col,
pen=wx.Pen(bgcolor), brush=wx.Brush(bgcolor))
self._draw_cursor(dc, ... | Whites out the old cursor and draws the new one |
9,720 | def element_type(self):
if not self.is_pointer:
raise ValueError("Type {} is not a pointer".format(self))
return TypeRef(ffi.lib.LLVMPY_GetElementType(self)) | Returns the pointed-to type. When the type is not a pointer,
raises exception. |
9,721 | def Clamond(Re, eD, fast=False):
r
X1 = eD*Re*0.1239681863354175460160858261654858382699
X2 = log(Re) - 0.7793974884556819406441139701653776731705
F = X2 - 0.2
X1F = X1 + F
X1F1 = 1. + X1F
E = (log(X1F) - 0.2)/(X1F1)
F = F - (X1F1 + 0.5*E)*E*(X1F)/(X1F1 + E*(1. + E*0.3333333333333... | r'''Calculates Darcy friction factor using a solution accurate to almost
machine precision. Recommended very strongly. For details of the algorithm,
see [1]_.
Parameters
----------
Re : float
Reynolds number, [-]
eD : float
Relative roughness, [-]
fast : bool, optional
... |
9,722 | def _execute(self, api_command, *, timeout=None):
if api_command.observe:
self._observe(api_command)
return
method = api_command.method
path = api_command.path
data = api_command.data
parse_json = api_command.parse_json
url = api_command... | Execute the command. |
9,723 | def _init_unique_sets(self):
ks = dict()
for t in self._unique_checks:
key = t[0]
ks[key] = set()
return ks | Initialise sets used for uniqueness checking. |
9,724 | def update(self, _attributes=None, **attributes):
if _attributes is not None:
attributes.update(_attributes)
if self._related.uses_timestamps():
attributes[self.get_related_updated_at()] = self._related.fresh_timestamp()
return self._query.update(attributes) | Perform an update on all the related models.
:param attributes: The attributes
:type attributes: dict
:rtype: int |
9,725 | def read_history_file(self, filename=None):
u
if filename is None:
filename = self.history_filename
try:
for line in open(filename, u):
self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))
except IOError:
... | u'''Load a readline history file. |
9,726 | def get_documents(self, subtypes=None, refresh=False):
search = ScopusSearch(.format(self.identifier), refresh)
if subtypes:
return [p for p in search.results if p.subtype in subtypes]
else:
return search.results | Return list of author's publications using ScopusSearch, which
fit a specified set of document subtypes. |
9,727 | def create_styles(title,defaults=None,mappings=None,host=cytoscape_host,port=cytoscape_port):
if defaults:
defaults_=[]
for d in defaults:
if d:
defaults_.append(d)
defaults=defaults_
if mappings:
mappings_=[]
for m in mappings:
... | Creates a new visual style
:param title: title of the visual style
:param defaults: a list of dictionaries for each visualProperty
:param mappings: a list of dictionaries for each visualProperty
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=123... |
9,728 | def search_variant_sets(self, dataset_id):
request = protocol.SearchVariantSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "variantsets", protocol.SearchVariantSetsResponse) | Returns an iterator over the VariantSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the :class:`ga4gh.protocol.Dataset`
of interest.
:return: An iterator over the :class:`ga4gh.protocol.VariantSet`
objects defined by ... |
9,729 | def verify(self, obj):
if not isinstance(obj, int):
raise ValidationError("Object is not a int", reason=, 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
... |
9,730 | def _tls_auth_encrypt(self, s):
write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
self.tls_session.wcs.seq_num += 1
add_data = (write_seq_num +
pkcs_i2osp(self.type, 1) +
pkcs_i2osp(self.version, 2) +
pkcs_i2osp(l... | Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here. |
9,731 | def pvlan_host_association(self, **kwargs):
int_type = kwargs.pop().lower()
name = kwargs.pop()
pri_vlan = kwargs.pop()
sec_vlan = kwargs.pop()
callback = kwargs.pop(, self._callback)
int_types = [, ,
, ,
]
if i... | Set interface PVLAN association.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
pri_vlan (str): The primary PVLAN.
sec_vlan (str): The secondary PVLAN.
... |
9,732 | def _make_image_description(self, datasets, **kwargs):
translate_platform_name = {: ,
: ,
: ,
: ,
: ,
: ,
... | generate image description for mitiff.
Satellite: NOAA 18
Date and Time: 06:58 31/05-2016
SatDir: 0
Channels: 6 In this file: 1-VIS0.63 2-VIS0.86 3(3B)-IR3.7
4-IR10.8 5-IR11.5 6(3A)-VIS1.6
Xsize: 4720
Ysize: 5544
Map projection: Stereographic
... |
9,733 | def main(args):
grr_config.CONFIG.AddContext(contexts.CLIENT_BUILD_CONTEXT)
if args.subparser_name == "generate_client_config":
templates.append(template)
repack_configs = []
for repack_config in args.repack_configs:
if "*" in repack_config:
repack_configs.extend(gl... | Launch the appropriate builder. |
9,734 | def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None,
slicers=None, axes_are_reversed=False, build_axes=True,
ns=None, docs=None):
cls._AXIS_ORDERS = axes
cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)}
cls._AXIS_LEN = l... | Provide axes setup for the major PandasObjects.
Parameters
----------
axes : the names of the axes in order (lowest to highest)
info_axis_num : the axis of the selector dimension (int)
stat_axis_num : the number of axis for the default stats (int)
aliases : other names f... |
9,735 | def parent(self):
def parent_element():
return WebElementWrapper(self.driver_wrapper, self.locator, self.element.parent)
return self.execute_and_handle_webelement_exceptions(parent_element, ) | Get the parent of the element
@rtype: WebElementWrapper
@return: Parent of webelementwrapper on which this was invoked |
9,736 | def record(self):
while True:
frames = []
self.stream.start_stream()
for i in range(self.num_frames):
data = self.stream.read(self.config.FRAMES_PER_BUFFER)
frames.append(data)
self.output.seek(0)
w = wave.open... | Record PyAudio stream into StringIO output
This coroutine keeps stream open; the stream is closed in stop() |
9,737 | def argmin(self, axis=None, skipna=True, *args, **kwargs):
nv.validate_argmin(args, kwargs)
nv.validate_minmax_axis(axis)
i8 = self.asi8
if self.hasnans:
mask = self._isnan
if mask.all() or not skipna:
return -1
i8 = i8.copy()... | Returns the indices of the minimum values along an axis.
See `numpy.ndarray.argmin` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmin |
9,738 | def next_event(self):
if self._departures[0]._time < self._arrivals[0]._time:
new_depart = heappop(self._departures)
self._current_t = new_depart._time
self._num_total -= 1
self.num_system -= 1
self.num_departures += 1
if self.col... | Simulates the queue forward one event.
Use :meth:`.simulate` instead.
Returns
-------
out : :class:`.Agent` (sometimes)
If the next event is a departure then the departing agent
is returned, otherwise nothing is returned.
See Also
--------
... |
9,739 | def generate_bigip_uri(base_uri, partition, name, sub_path, suffix, **kwargs):
https://0.0.0.0/mgmt/tm/ltm/nat/CUSTOMER1nat52ahttps://0.0.0.0/mgmt/tm/ltm/nat/~CUSTOMER1~nat52https://0.0.0.0/mgmt/tm/ltm/nat/CUSTOMER1nat52a/wackyhttps://0.0.0.0/mgmt/tm/ltm/nat/~CUSTOMER1~nat52/wackyhttps://0.0.0.0/mgmt/tm/ltm/nat/a/t... | (str, str, str) --> str
This function checks the supplied elements to see if each conforms to
the specification for the appropriate part of the URI. These validations
are conducted by the helper function _validate_uri_parts.
After validation the parts are assembled into a valid BigIP REST URI
strin... |
9,740 | def makeUserLoginMethod(username, password, locale=None):
def _doLogin(soapStub):
si = vim.ServiceInstance("ServiceInstance", soapStub)
sm = si.content.sessionManager
if not sm.currentSession:
si.content.sessionManager.Login(username, password, locale)
return _... | Return a function that will call the vim.SessionManager.Login() method
with the given parameters. The result of this function can be passed as
the "loginMethod" to a SessionOrientedStub constructor. |
9,741 | def router_function(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if platform_is_windows():
raise RuntimeError(
"Router interface is not available on Win32 systems.\n"
"Configure AMS routes using the TwinCAT router service."
)... | Raise a runtime error if on Win32 systems.
Decorator.
Decorator for functions that interact with the router for the Linux
implementation of the ADS library.
Unlike the Windows implementation which uses a separate router daemon,
the Linux library manages AMS routing in-process. As such, routing mu... |
9,742 | def _get_content_type(self, file):
if file.mimetype:
return file.mimetype
_, extension = os.path.splitext(file.name)
extension = extension.strip()
return media_types[extension] if extension in media_types else | Return content type of file. If file does not
have a content type, make a guess. |
9,743 | def _encode_text(name, value, dummy0, dummy1):
value = _utf_8_encode(value)[0]
return b"\x02" + name + _PACK_INT(len(value) + 1) + value + b"\x00" | Encode a python unicode (python 2.x) / str (python 3.x). |
9,744 | def get_passenger_queue_stats(self):
queue_stats = {
"top_level_queue_size": 0.0,
"passenger_queue_size": 0.0,
}
command = [self.config["passenger_status_bin"]]
if str_to_bool(self.config["use_sudo"]):
command.insert(0, self.config["sudo_cmd"... | Execute passenger-stats, parse its output, returnand requests in queue |
9,745 | def SetProtocol(self, protocol):
protocol = protocol.lower().strip()
if protocol not in [, ]:
raise ValueError()
self._analyzer.SetProtocol(protocol) | Sets the protocol that will be used to query Viper.
Args:
protocol (str): protocol to use to query Viper. Either 'http' or 'https'.
Raises:
ValueError: If an invalid protocol is selected. |
9,746 | def reset(self, hard=False):
if hard:
self.sendcommand(Vendapin.RESET, 1, 0x01)
time.sleep(2)
else:
self.sendcommand(Vendapin.RESET)
time.sleep(2)
response = self.receivepacket()
print( + str(response)) | reset the card dispense, either soft or hard based on boolean 2nd arg |
9,747 | def _configure_key_pair(config):
if "ssh_private_key" in config["auth"]:
return config
ssh_user = config["auth"]["ssh_user"]
project = compute.projects().get(
project=config["provider"]["project_id"]).execute()
ssh_keys_str = next(
(item for item in project["co... | Configure SSH access, using an existing key pair if possible.
Creates a project-wide ssh key that can be used to access all the instances
unless explicitly prohibited by instance config.
The ssh-keys created by ray are of format:
[USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME]
where:
[USERNAM... |
9,748 | def _set_mpls_interface(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("interface_type interface_name",mpls_interface.mpls_interface, yang_name="mpls-interface", rest_name="mpls-interface", parent=self, is_container=, user_ordered=False,... | Setter method for mpls_interface, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_interface is considered as a private
method. Backends looking to populate this variable should
... |
9,749 | def render_document(template_name, data_name, output_name):
env = Environment(loader=PackageLoader())
with open(output_name, ) as output_file:
output = env.get_template(template_name).render(yaml.load(open(data_name)))
output_file.write(output) | Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file.
Parameters
==========
template_name : String
Exact name of the MarkDown template file from the aide_document/templates fold... |
9,750 | def create_asset(json):
result = Asset(json[])
file_dict = json[][]
result.fields = json[]
result.url = file_dict[]
result.mimeType = file_dict[]
return result | Create :class:`.resources.Asset` from JSON.
:param json: JSON dict.
:return: Asset instance. |
9,751 | def _field_sort_name(cls, name):
if isinstance(cls.__dict__[name], DateItemField):
name = re.sub(, , name)
name = re.sub(, , name)
name = re.sub(, , name)
return name | Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `date1`, and `date2`, respectively, to
m... |
9,752 | def parse_atoms(self):
atom_site_header_tag = self.main_tag.getElementsByTagName("PDBx:atom_siteCategory")
assert(len(atom_site_header_tag) == 1)
atom_site_header_tag = atom_site_header_tag[0]
atom_site_tags = atom_site_header_tag.getElementsByTagName("PDBx:atom_site")
... | All ATOM lines are parsed even though only one per residue needs to be parsed. The reason for parsing all the
lines is just to sanity-checks that the ATOMs within one residue are consistent with each other. |
9,753 | def t_whitespace(self, s):
r
self.add_token(, s)
self.pos += len(s)
pass | r'\s+ |
9,754 | def init_publisher(app):
@app.context_processor
def inject_links():
return {
: stack.top.websub_self_url,
: stack.top.websub_hub_url,
: stack.top.websub_self_link,
: stack.top.websub_hub_link,
} | Calling this with your flask app as argument is required for the
publisher decorator to work. |
9,755 | def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
if weights is not None:
W = np.array(weights)
if W.ndim == 1:
W = np.diag(W)
S = np.array([vectorize(m).conj()
for m in ops]).reshape(len(ops), ops[0].size)
if weights is not None:
... | Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to be used for weighted fitting.
trace (float or None): trace of re... |
9,756 | def find_branches(self, labels=False, unique=False):
branches = []
if labels is True:
identifier = [self.label]
else:
identifier = [self]
if self._children == []:
return identifier
else:
for child in self._... | Recursively constructs a list of pointers of the tree's structure
Args:
labels (bool): If True, returned lists consist of node labels.
If False (default), lists consist of node
pointers. This option is mostly intended for
... |
9,757 | def __update_html(self, html):
if platform.system() in ("Windows", "Microsoft"):
html = re.sub(r"((?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+)",
lambda x: foundations.strings.to_forward_slashes(x.group(1)),
html)
... | Updates the View with given html content.
:param html: Html content.
:type html: unicode |
9,758 | def _future_command_unlocked(self, cmd):
future = self._loop.create_future()
asyncio_loop = self._loop.get_loop()
def _done_callback(result):
retval = result[]
if not result[]:
future.set_exception(HardwareError("Error executing synchronous com... | Run command as a coroutine and return a future.
Args:
loop (BackgroundEventLoop): The loop that we should attach
the future too.
cmd (list): The command and arguments that we wish to call.
Returns:
asyncio.Future: An awaitable future with the result ... |
9,759 | def register (self, target):
assert isinstance(target, VirtualTarget)
if target.path():
signature = target.path() + "-" + target.name()
else:
signature = "-" + target.name()
result = None
if signature not in self.cache_:
self.cache_ [... | Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered.
Otherwise, 'target' is regi... |
9,760 | def _list_store_resources(self, request, head_id, filter_ids,
resource_fetcher, block_xform):
resources = []
if filter_ids and not request.head_id:
for resource_id in filter_ids:
try:
resources.append(resour... | Builds a list of blocks or resources derived from blocks,
handling multiple possible filter requests:
- filtered by a set of ids
- filtered by head block
- filtered by both id and head block
- not filtered (all current resources)
Note:
This me... |
9,761 | def post(self, action, data=None, headers=None):
return self.request(make_url(self.endpoint, action), method=, data=data,
headers=headers) | Makes a GET request |
9,762 | def setColor(self, key, value):
key = nativestring(key).capitalize()
self._colorSet.setColor(key, value)
if ( key == ):
palette = self.palette()
palette.setColor( palette.Base, value )
self.setPalette(palette) | Sets the color value for the inputed color.
:param key | <unicode>
value | <QtGui.QColor> |
9,763 | def matches(self, client, event_data):
for f in self.filters:
if not f(client, event_data):
return False
return True | True if all filters are matching. |
9,764 | def invalidate(self):
endpoint =
payload = {
: self.access_token,
: self.client_token,
}
self._ygg_req(endpoint, payload)
self.client_token =
self.access_token =
self.available_profiles = []
self.selected_profile = {}
... | Invalidate access tokens with a client/access token pair
Returns:
dict: Empty or error dict |
9,765 | def _update_camera_pos(self):
ch_em = self.events.transform_change
with ch_em.blocker(self._update_transform):
tr = self.transform
tr.reset()
up, forward, right = self._get_dim_vectors()
pp1 = np.array([(0, 0, 0),... | Set the camera position and orientation |
9,766 | def resolve_and_call(self, func, extra_env=None):
kwargs = self.resolve_parameters(func, extra_env=extra_env)
return func(**kwargs) | Resolve function arguments and call them, possibily filling from the environment |
9,767 | def _expand_numparse(disable_numparse, column_count):
if isinstance(disable_numparse, Iterable):
numparses = [True] * column_count
for index in disable_numparse:
numparses[index] = False
return numparses
else:
return [not disable_numparse] * column_count | Return a list of bools of length `column_count` which indicates whether
number parsing should be used on each column.
If `disable_numparse` is a list of indices, each of those indices are False,
and everything else is True.
If `disable_numparse` is a bool, then the returned list is all the same. |
9,768 | def byaxis(self):
space = self
class NpyTensorSpacebyaxis(object):
def __getitem__(self, indices):
try:
iter(indices)
except TypeError:
newshape = space.shape[indices]
... | Return the subspace defined along one or several dimensions.
Examples
--------
Indexing with integers or slices:
>>> space = odl.rn((2, 3, 4))
>>> space.byaxis[0]
rn(2)
>>> space.byaxis[1:]
rn((3, 4))
Lists can be used to stack spaces arbitraril... |
9,769 | def lock_status(self, resource_id, parent_id=None, account_id=None):
account_id = self.get_account_id(account_id)
params = parent_id and {: parent_id} or None
return self.http.get(
"%s/%s/locks/%s" % (self.endpoint, account_id, resource_id),
params=params, auth=s... | Get the lock status for a given resource.
for security groups, parent id is their vpc. |
9,770 | def find_children(self):
for i in range(len(self.vertices)):
self.vertices[i].children = []
for i in range(len(self.vertices)):
for parent in self.vertices[i].parents:
if i not in self.vertices[parent].children:
self.vertices[parent].c... | Take a tree and set the children according to the parents.
Takes a tree structure which lists the parents of each vertex
and computes the children for each vertex and places them in. |
9,771 | def remove(self, *members):
if self.serialized:
members = list(map(self._dumps, members))
return self._client.srem(self.key_prefix, *members) | Removes @members from the set
-> #int the number of members that were removed from the set |
9,772 | def eth_getBlockByNumber(self, block=BLOCK_TAG_LATEST, tx_objects=True):
block = validate_block(block)
return self._call("eth_getBlockByNumber", [block, tx_objects]) | TODO: documentation
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber
TESTED |
9,773 | def list(self, pattern=):
if self._descriptors is None:
self._descriptors = self._client.list_metric_descriptors(
filter_string=self._filter_string, type_prefix=self._type_prefix)
return [metric for metric in self._descriptors
if fnmatch.fnmatch(metric.type, pattern)] | Returns a list of metric descriptors that match the filters.
Args:
pattern: An optional pattern to further filter the descriptors. This can
include Unix shell-style wildcards. E.g. ``"compute*"``,
``"*cpu/load_??m"``.
Returns:
A list of MetricDescriptor objects that match the f... |
9,774 | def _raw(cls, vertices, edges, out_edges, in_edges, head, tail):
self = object.__new__(cls)
self._out_edges = out_edges
self._in_edges = in_edges
self._head = head
self._tail = tail
self._vertices = vertices
self._edges = edges
return self | Private constructor for direct construction
of an ObjectGraph from its attributes.
vertices is the collection of vertices
out_edges and in_edges map vertices to lists of edges
head and tail map edges to objects. |
9,775 | def i18n(msg, event=None, lang=, domain=):
if event is not None:
language = event.client.language
else:
language = lang
domain = Domain(domain)
return domain.get(language, msg) | Gettext function wrapper to return a message in a specified language by domain
To use internationalization (i18n) on your messages, import it as '_' and use as usual.
Do not forget to supply the client's language setting. |
9,776 | def ring_coding(array):
n = len(array)
codes = np.ones(n, dtype=Path.code_type) * Path.LINETO
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY
return codes | Produces matplotlib Path codes for exterior and interior rings
of a polygon geometry. |
9,777 | def write_utf(self, s):
utfstr = s.encode()
length = len(utfstr)
if length > 64:
raise NamePartTooLongException
self.write_byte(length)
self.write_string(utfstr, length) | Writes a UTF-8 string of a given length to the packet |
9,778 | def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud is None:
return _local.Local.preprocess(train_dataset, output_dir, eval_dataset, checkpoint)
if not isinstance(cloud, dict):
... | Preprocess data. Produce output that can be used by training efficiently.
Args:
train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If eval_dataset is None, the pipeline will randomly split train_dataset into
train/eval set with 7:3 ratio.
output_dir: The ... |
9,779 | def save_figures(block, block_vars, gallery_conf):
image_path_iterator = block_vars[]
all_rst = u
prev_count = len(image_path_iterator)
for scraper in gallery_conf[]:
rst = scraper(block, block_vars, gallery_conf)
if not isinstance(rst, basestring):
raise TypeError(
... | Save all open figures of the example code-block.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
... |
9,780 | def get_points_and_weights(w_func=lambda x : np.ones(x.shape),
left=-1.0, right=1.0, num_points=5, n=4096):
dx = (float(right)-left)/n
z = np.hstack(np.linspace(left+0.5*dx, right-0.5*dx, n))
w = dx*w_func(z)
(a, b) = discrete_gautschi(z, w, num_points)
alpha = a
beta = np.s... | Quadratude points and weights for a weighting function.
Points and weights for approximating the integral
I = \int_left^right f(x) w(x) dx
given the weighting function w(x) using the approximation
I ~ w_i f(x_i)
Args:
w_func: The weighting function w(x). Must be a function that ta... |
9,781 | def submit_form(self, form, submit=None, **kwargs):
method = form.method.upper()
url = self._build_url(form.action) or self.url
payload = form.serialize(submit=submit)
serialized = payload.to_requests(method)
send_args = self._build_send_args(**kwargs)... | Submit a form.
:param Form form: Filled-out form object
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:param kwargs: Keyword arguments to `Session::send` |
9,782 | def predict_proba(self, X):
y_probas = []
for yp in self.forward_iter(X, training=False):
yp = yp[0] if isinstance(yp, tuple) else yp
y_probas.append(to_numpy(yp))
y_proba = np.concatenate(y_probas, 0)
return y_proba | Return the output of the module's forward method as a numpy
array.
If the module's forward method returns multiple outputs as a
tuple, it is assumed that the first output contains the
relevant information and the other values are ignored. If all
values are relevant, consider usi... |
9,783 | def get_method_serializers(self, http_method):
if http_method == and not in self.method_serializers:
http_method =
return (
self.method_serializers.get(http_method, self.serializers),
self.default_method_media_type.get(
http_method, self.d... | Get request method serializers + default media type.
Grab serializers from ``method_serializers`` if defined, otherwise
returns the default serializers. Uses GET serializers for HEAD requests
if no HEAD serializers were specified.
The method also determines the default media type.
... |
9,784 | def get_protocol_version(protocol=None, target=None):
target = get_py_internals(target)
if protocol is None:
protocol = target[]
if protocol > cPickle.HIGHEST_PROTOCOL:
warnings.warn( % cPickle.HIGHEST_PROTOCOL)
protocol = cPickle.HIGHEST_PROTOCOL
target_highest_protocol... | Return a suitable pickle protocol version for a given target.
Arguments:
target: The internals description of the targeted python
version. If this is ``None`` the specification of the currently
running python version will be used.
protocol(None or int): The requested protoco... |
9,785 | def get_free_region(self, width, height):
best_height = best_width = np.inf
best_index = -1
for i in range(len(self._atlas_nodes)):
y = self._fit(i, width, height)
if y >= 0:
node = self._atlas_nodes[i]
if (y+height < best_height o... | Get a free region of given size and allocate it
Parameters
----------
width : int
Width of region to allocate
height : int
Height of region to allocate
Returns
-------
bounds : tuple | None
A newly allocated region as (x, y, w... |
9,786 | def parse_version(version: str) -> tuple:
if not version:
return None
parts = version.split()
missing = 3 - len(parts)
return tuple(int(i) for i in parts + ([0] * missing)) | Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0) |
9,787 | def prepare(self, cache):
if cache is not None:
np.copyto(self.qubits, cache)
else:
self.qubits.fill(0.0)
self.qubits[0] = 1.0
self.cregs = [0] * self.n_qubits | Prepare to run next shot. |
9,788 | def conditional_accept(self):
if self.ui.calfileRadio.isChecked() and str(self.ui.calChoiceCmbbx.currentText()) == :
self.ui.noneRadio.setChecked(True)
if self.ui.calfileRadio.isChecked():
try:
x, freqs = self.datafile.get_calibration(str(self.ui.calChoic... | Accepts the inputs if all values are valid and congruent.
i.e. Valid datafile and frequency range within the given calibration dataset. |
9,789 | def _set_fetcher_options(self, base):
ei_opts = self.distribution.get_option_dict().copy()
fetch_directives = (
, , , ,
, ,
)
fetch_options = {}
for key, val in ei_opts.iteritems():
if key not in fetch_directives: con... | When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well. |
9,790 | def validate_key(request, group=None, perm=None, keytype=None):
def update_last_access():
if KEY_LAST_USED_UPDATE:
request.key.save()
if request.user.is_authenticated() and is_valid_consumer(request):
if not group and not perm and not keytype:
return update_last... | Validate the given key |
9,791 | def receive(self, msg):
x = self.routing
while not isinstance(x, ActionList):
if not x or not msg:
return None, msg
if not isinstance(x, dict):
raise ValueError( % type(x))
_, value = msg.popitem(last=False)
x = x... | Returns a (receiver, msg) pair, where receiver is `None` if no route for
the message was found, or otherwise an object with a `receive` method
that can accept that `msg`. |
9,792 | def _ecc_encode_compressed_point(private_key):
byte_length = (private_key.curve.key_size + 7) // 8
public_numbers = private_key.public_key().public_numbers()
y_map = [b"\x02", b"\x03"]
if private_key.curve.name.startswith("secp"):
y_order = public_numbers.y % 2
y = y_map[y... | Encodes a compressed elliptic curve point
as described in SEC-1 v2 section 2.3.3
http://www.secg.org/sec1-v2.pdf
:param private_key: Private key from which to extract point data
:type private_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
:returns: Encoded compres... |
9,793 | def default_multivariate_normal_fn(dtype, shape, name, trainable,
add_variable_fn):
del name, trainable, add_variable_fn
dist = tfd.Normal(loc=tf.zeros(shape, dtype), scale=dtype.as_numpy_dtype(1))
batch_ndims = tf.size(input=dist.batch_shape_tensor())
return tfd.Indepen... | Creates multivariate standard `Normal` distribution.
Args:
dtype: Type of parameter's event.
shape: Python `list`-like representing the parameter's event shape.
name: Python `str` name prepended to any created (or existing)
`tf.Variable`s.
trainable: Python `bool` indicating all created `tf.Var... |
9,794 | def check_rights(self, resources, request=None):
if not self.auth:
return True
try:
if not self.auth.test_rights(resources, request=request):
raise AssertionError()
except AssertionError, e:
raise HttpError("Access forbiden. {0}".for... | Check rights for resources.
:return bool: True if operation is success else HTTP_403_FORBIDDEN |
9,795 | def get_task_summary(self, task_name):
params = {: , : task_name}
resp = self._client.get(self.resource(), params=params)
map_reduce = resp.json().get()
if map_reduce:
json_summary = map_reduce.get()
if json_summary:
summary = Instance.T... | Get a task's summary, mostly used for MapReduce.
:param task_name: task name
:return: summary as a dict parsed from JSON
:rtype: dict |
9,796 | def ekrced(handle, segno, recno, column, nelts=_SPICE_EK_EKRCEX_ROOM_DEFAULT):
handle = ctypes.c_int(handle)
segno = ctypes.c_int(segno)
recno = ctypes.c_int(recno)
column = stypes.stringToCharP(column)
nvals = ctypes.c_int(0)
dvals = stypes.emptyDoubleVector(nelts)
isnull = ctypes.c_in... | Read data from a double precision column in a specified EK record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrced_c.html
:param handle: Handle attached to EK file.
:type handle: int
:param segno: Index of segment containing record.
:type segno: int
:param recno: Record from whi... |
9,797 | def users_create_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users
api_path = "/api/v2/users/create_many.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/users#create-many-users |
9,798 | def set_zerg_client_params(self, server_sockets, use_fallback_socket=None):
self._set(, server_sockets, multi=True)
if use_fallback_socket is not None:
self._set(, use_fallback_socket, cast=bool)
for socket in listify(server_sockets):
self._section.netw... | Zerg mode. Zergs params.
:param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server.
:param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available |
9,799 | def listen(self, **kwargs: Any) -> Server:
loop = cast(asyncio.AbstractEventLoop, self._loop)
return (yield from loop.create_server(
lambda: self._protocol(
loop=loop,
handle=self._handle,
requset_charset=self.requset_charset,
... | bind host, port or sock |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.