Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
388,200 | def get_review_requests(self):
return (
github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/requested_reviewers",
None,
list_item=
),
github.Pagi... | :calls: `GET /repos/:owner/:repo/pulls/:number/requested_reviewers <https://developer.github.com/v3/pulls/review_requests/>`_
:rtype: tuple of :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` and of :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team` |
388,201 | def list_dfu_devices(*args, **kwargs):
devices = get_dfu_devices(*args, **kwargs)
if not devices:
print("No DFU capable devices found")
return
for device in devices:
print("Bus {} Device {:03d}: ID {:04x}:{:04x}"
.format(device.bus, device.address,
... | Prints a lits of devices detected in DFU mode. |
388,202 | def delete_resource(resource_name, key, identifier_fields, profile=, subdomain=None, api_key=None):
resource = get_resource(resource_name, key, identifier_fields, profile, subdomain, api_key)
if resource:
if __opts__[]:
return
else:
return True | delete any pagerduty resource
Helper method for absent()
example:
delete_resource("users", key, ["id","name","email"]) # delete by id or name or email |
388,203 | def __make_points(self, measurement, additional_tags, ts, fields):
tags = self.tags.copy()
tags.update(additional_tags)
return {
"measurement": measurement,
"tags": tags,
"time": int(ts),
"fields": fields,
} | Parameters
----------
measurement : string
measurement type (e.g. monitoring, overall_meta, net_codes, proto_codes, overall_quantiles)
additional_tags : dict
custom additional tags for this points
ts : integer
timestamp
fields : dict
... |
388,204 | def reset(self):
self.grid = [[0 for dummy_l in range(self.grid_width)] for dummy_l in range(self.grid_height)] | Reset the game so the grid is zeros (or default items) |
388,205 | def stabilize(self, test_func, error, timeoutSecs=10, retryDelaySecs=0.5):
timeTakenSecsnumberOfRetries
start = time.time()
numberOfRetries = 0
while h2o_args.no_timeout or (time.time() - start < timeoutSecs):
if test_func(self, tries=numberOfRetries, timeoutSecs=timeoutSecs)... | Repeatedly test a function waiting for it to return True.
Arguments:
test_func -- A function that will be run repeatedly
error -- A function that will be run to produce an error message
it will be called with (node, timeTakenSecs, numberOfRetries)
... |
388,206 | def confirm_authorization_request(self):
server = self.server
scope = request.values.get() or
scopes = scope.split()
credentials = dict(
client_id=request.values.get(),
redirect_uri=request.values.get(, None),
response_type=request.values.get... | When consumer confirm the authorization. |
388,207 | def serialize_operator_less_than(self, op):
elem = etree.Element()
return self.serialize_value_list(elem, op.args) | Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<less-than>
<value>text</value>
<value><attribute>foobar</attribute></value>
</less-than> |
388,208 | def GetRawDevice(path):
path = CanonicalPathToLocalPath(path)
try:
path = win32file.GetLongPathName(path)
except pywintypes.error:
pass
try:
mount_point = win32file.GetVolumePathName(path)
except pywintypes.error as details:
logging.info("path not found. %s", details)
raise IOError(... | Resolves the raw device that contains the path.
Args:
path: A path to examine.
Returns:
A pathspec to read the raw device as well as the modified path to read
within the raw device. This is usually the path without the mount point.
Raises:
IOError: if the path does not exist or some unexpected ... |
388,209 | def v1_label_negative_inference(request, response,
visid_to_dbid, dbid_to_visid,
label_store, cid):
``, the connected components of ``cid`` and
``cid
lab_to_json = partial(label_to_json, dbid_to_visid)
labs = imap(lab_to_json,
... | Return inferred negative labels.
The route for this endpoint is:
``/dossier/v1/label/<cid>/negative-inference``.
Negative labels are inferred by first getting all other content ids
connected to ``cid`` through a negative label. For each directly
adjacent ``cid'``, the connected components of ``cid... |
388,210 | def get_or_default(func=None, default=None):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except ObjectDoesNotExist:
if callable(default):
return default()
... | Wrapper around Django's ORM `get` functionality.
Wrap anything that raises ObjectDoesNotExist exception
and provide the default value if necessary.
`default` by default is None. `default` can be any callable,
if it is callable it will be called when ObjectDoesNotExist
exception will be raised. |
388,211 | def _get_os(osvi = None):
if not osvi:
osvi = GetVersionEx()
if osvi.dwPlatformId == VER_PLATFORM_WIN32_NT and osvi.dwMajorVersion > 4:
if osvi.dwMajorVersion == 6:
if osvi.dwMinorVersion == 0:
if osvi.wProductType == VER_NT_WORKSTATION:
... | Determines the current operating system.
This function allows you to quickly tell apart major OS differences.
For more detailed information call L{GetVersionEx} instead.
@note:
Wine reports itself as Windows XP 32 bits
(even if the Linux host is 64 bits).
ReactOS may report itself ... |
388,212 | def _get_event_cls(view_obj, events_map):
request = view_obj.request
view_method = getattr(view_obj, request.action)
event_action = (
getattr(view_method, , None) or
request.action)
return events_map[event_action] | Helper function to get event class.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Found event class. |
388,213 | def construct_message(self, email=None):
self.multipart[] = self.subject
self.multipart[] = self.config[]
self.multipart[] = formatdate(localtime=True)
if email is None and self.send_as_one:
self.multipart[] = ", ".join(self.addresses)
elif em... | construct the email message |
388,214 | def _is_paste(keys):
text_count = 0
newline_count = 0
for k in keys:
if isinstance(k.key, six.text_type):
text_count += 1
if k.key == Keys.ControlJ:
newline_count += 1
return newline_count >= 1 and text_... | Return `True` when we should consider this list of keys as a paste
event. Pasted text on windows will be turned into a
`Keys.BracketedPaste` event. (It's not 100% correct, but it is probably
the best possible way to detect pasting of text and handle that
correctly.) |
388,215 | def setVisible(self, state):
super(XLineEdit, self).setVisible(state)
self.adjustStyleSheet()
self.adjustTextMargins() | Sets the visible state for this line edit.
:param state | <bool> |
388,216 | def handle_failed_login(self, login_result):
error_code = login_result.get()
if in error_code:
utils.error_message()
self.trigger_two_step_login(login_result)
self.finish_two_step_login()
else:
utils.error_message_and_exit(, login_result) | If Two Factor Authentication (2FA/2SV) is enabled, the initial
login will fail with a predictable error. Catching this error allows us
to begin the authentication process.
Other types of errors can be treated in a similar way. |
388,217 | def right_click(self, x, y, n=1, pre_dl=None, post_dl=None):
self.delay(pre_dl)
self.m.click(x, y, 2, n)
self.delay(post_dl) | Right click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处右键单击 ``n`` 次。 |
388,218 | def check_selection(self):
if self.current_prompt_pos is None:
self.set_cursor_position()
else:
self.truncate_selection(self.current_prompt_pos) | Check if selected text is r/w,
otherwise remove read-only parts of selection |
388,219 | def get_composition_query_session_for_repository(self, repository_id, proxy):
if repository_id is None:
raise NullArgument()
if not self.supports_composition_query():
raise Unimplemented()
try:
from . import sessions
except ImportError:
... | Gets a composition query session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionQuerySession) - a
CompositionQuerySession
raise: NotFound - repository_i... |
388,220 | def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
if source_format not in {, }:
raise ValueError(
"Unknown source_format {}. Supported formats are: and ".format(source_format)
)
if source_format == :
x_min, y_min, width, height =... | Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`[x_min, y_min, x_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`.
Args:
bbox (list): bounding box
... |
388,221 | def unregister(self, token_to_remove):
for i, (_, token, _) in enumerate(self._filter_order):
if token == token_to_remove:
break
else:
raise ValueError("unregistered token: {!r}".format(
token_to_remove))
del self._filter_order[i] | Unregister a filter function.
:param token_to_remove: The token as returned by :meth:`register`.
Unregister a function from the filter chain using the token returned by
:meth:`register`. |
388,222 | def fromexportreg(cls, bundle, export_reg):
exc = export_reg.get_exception()
if exc:
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.EXPORT_ERROR,
bundle,
export_reg.get_export_container_id(),
export_re... | Creates a RemoteServiceAdminEvent object from an ExportRegistration |
388,223 | def delete_intent(self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
if not in self._inner_api_calls:
self._inner_api_ca... | Deletes the specified intent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.IntentsClient()
>>>
>>> name = client.intent_path('[PROJECT]', '[INTENT]')
>>>
>>> client.delete_intent(name)
Args:
... |
388,224 | def save_state(self, fname):
log.info("Saving state to %s", fname)
data = {
: self.ksize,
: self.alpha,
: self.node.id,
: self.bootstrappable_neighbors()
}
if not data[]:
log.warning("No known neighbors, so not writing ... | Save the state of this node (the alpha/ksize/id/immediate neighbors)
to a cache file with the given fname. |
388,225 | def RgbToWebSafe(r, g, b, alt=False):
web safe(%g, %g, %g)(1, 0.6, 0)
webSafeComponent = Color._WebSafeComponent
return tuple((webSafeComponent(v, alt) for v in (r, g, b))) | Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color instead of the nearest one.
Can be used fo... |
388,226 | def apply_widget_css_class(self, field_name):
field = self.fields[field_name]
class_name = self.get_widget_css_class(field_name, field)
if class_name:
field.widget.attrs[] = join_css_class(
field.widget.attrs.get(, None), class_name) | Applies CSS classes to widgets if available.
The method uses the `get_widget_css_class` method to determine if the widget
CSS class should be changed. If a CSS class is returned, it is appended to
the current value of the class property of the widget instance.
:param field_name: A fiel... |
388,227 | def labels(self, include_missing=False, include_transforms_for_dims=False):
return [
dim.labels(include_missing, include_transforms_for_dims)
for dim in self.dimensions
] | Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension |
388,228 | def analyze_all(self, analysis_directory = None):
for analysis_set in self.analysis_sets:
self.analyze(analysis_set, analysis_directory = analysis_directory) | This function runs the analysis and creates the plots and summary file. |
388,229 | def get_rate_limits(self):
resp, body = self.method_get("/limits")
rate_limits = body.get("limits", {}).get("rate")
ret = []
for rate_limit in rate_limits:
limits = rate_limit["limit"]
uri_limits = {"uri": rate_limit["uri"],
"limits": ... | Returns a dict with the current rate limit information for domain
and status requests. |
388,230 | def validate(self, skip_utf8_validation=False):
if self.rsv1 or self.rsv2 or self.rsv3:
raise WebSocketProtocolException("rsv is not implemented, yet")
if self.opcode not in ABNF.OPCODES:
raise WebSocketProtocolException("Invalid opcode %r", self.opcode)
if sel... | validate the ABNF frame.
skip_utf8_validation: skip utf8 validation. |
388,231 | def normalized_energy_at_conditions(self, pH, V):
return self.energy_at_conditions(pH, V) * self.normalization_factor | Energy at an electrochemical condition, compatible with
numpy arrays for pH/V input
Args:
pH (float): pH at condition
V (float): applied potential at condition
Returns:
energy normalized by number of non-O/H atoms at condition |
388,232 | def create_default_units_and_dimensions():
default_units_file_location = os.path.realpath(\
os.path.join(os.path.dirname(os.path.realpath(__file__)),
,
,
))
d=None
with open(default_units_file_location) as json_data:
d = j... | Adds the units and the dimensions reading a json file. It adds only dimensions and units that are not inside the db
It is possible adding new dimensions and units to the DB just modifiyin the json file |
388,233 | def callCount(cls, spy, number):
cls.__is_spy(spy)
if not (spy.callCount == number):
raise cls.failException(cls.message) | Checking the inspector is called number times
Args: SinonSpy, number |
388,234 | def run(self, clock, generalLedger):
if not self._meet_execution_criteria(clock.timestep_ix):
return
generalLedger.create_transaction(
self.description if self.description is not None else self.name,
description=,
tx_date=clock.get_datetime(),
... | Execute the activity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions. |
388,235 | def _children(self):
if self.declarations:
yield self.declarations
if isinstance(self.condition, CodeExpression):
yield self.condition
if self.increment:
yield self.increment
for codeobj in self.body._children():
yield codeobj | Yield all direct children of this object. |
388,236 | def protect(self, password=None, read_protect=False, protect_from=0):
return super(NTAG203, self).protect(
password, read_protect, protect_from) | Set lock bits to disable future memory modifications.
If *password* is None, all memory pages except the 16-bit
counter in page 41 are protected by setting the relevant lock
bits (note that lock bits can not be reset). If valid NDEF
management data is found in page 4, protect() also set... |
388,237 | def deprecated(msg=):
@decorator.decorator
def wrap(function, *args, **kwargs):
if not kwargs.pop(, False):
warn(msg, DeprecationWarning)
return function(*args, **kwargs)
return wrap | Deprecate decorated method. |
388,238 | def clear(self):
for slot in self._slots:
slot.grid_forget()
slot.destroy()
self._slots = [] | Clear out the multi-frame
:return: |
388,239 | def match_agent_id(self, agent_id, match):
self._add_match(, str(agent_id), bool(match)) | Matches the agent identified by the given ``Id``.
arg: agent_id (osid.id.Id): the Id of the ``Agent``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``agent_id`` is ``null``
*compliance: mandatory -- This m... |
388,240 | def member_create(self, params, member_id):
member_config = params.get(, {})
server_id = params.pop(, None)
version = params.pop(, self._version)
proc_params = {: self.repl_id}
proc_params.update(params.get(, {}))
if self.enable_ipv6:
enable_ipv6_sing... | start new mongod instances as part of replica set
Args:
params - member params
member_id - member index
return member config |
388,241 | def sync_next_id(self):
if self.next_id is not None:
if len(self):
n = max(self.getColumnByName(self.next_id.column_name)) + 1
else:
n = type(self.next_id)(0)
if n > self.next_id:
self.set_next_id(n)
return self.next_id | Determines the highest-numbered ID in this table, and sets
the table's .next_id attribute to the next highest ID in
sequence. If the .next_id attribute is already set to a
value greater than the highest value found, then it is left
unmodified. The return value is the ID identified by this
method. If the ta... |
388,242 | def gp_ccX():
inDir, outDir = getWorkDirs()
data, alldata = OrderedDict(), None
for infile in os.listdir(inDir):
key = os.path.splitext(infile)[0].replace(, )
data_import = np.loadtxt(open(os.path.join(inDir, infile), ))
data_import[:,3] = 0.434*(data_import[:,... | fit experimental data |
388,243 | def get_file_info_web(self, fname, delim=):
txt =
f = mod_file.File(fname[0])
txt += + f.name + + delim
txt += + fname[1] + + delim
txt += + f.GetDateAsString(f.date_modified)[2:10] + + delim
txt += + str(f.size) + + delim
return txt + | gathers info on a python program in list and formats as string |
388,244 | def qurl(url, add=None, exclude=None, remove=None):
urlp = list(urlparse(url))
qp = parse_qsl(urlp[4])
add = add if add else {}
for name, value in add.items():
if isinstance(value, (list, tuple)):
value = [smart_str(v) for v in value]
qp = [p for p... | Returns the url with changed parameters |
388,245 | def sigmask(self, sigsetsize=None):
if self._sigmask is None:
if sigsetsize is not None:
sc = self.state.solver.eval(sigsetsize)
self.state.add_constraints(sc == sigsetsize)
self._sigmask = self.state.solver.BVS(, sc*self.state.arch.byte_width... | Gets the current sigmask. If it's blank, a new one is created (of sigsetsize).
:param sigsetsize: the size (in *bytes* of the sigmask set)
:return: the sigmask |
388,246 | def monitor_module(module, summary_writer,
track_data=True,
track_grad=True,
track_update=True,
track_update_ratio=False,
bins=51):
module.track_data = track_data
module.track_grad = track_grad
module... | Allows for remote monitoring of a module's params and buffers.
The following may be monitored:
1. Forward Values - Histograms of the values for parameter and buffer tensors
2. Gradient Values - Histograms of the gradients for parameter and buffer tensors
3. Update Values - Histograms of the change... |
388,247 | def shell(filepath, wsgiapp, interpreter, models):
model_base_classes = get_model_base_classes()
imported_objects = {}
if models and model_base_classes:
insert_import_path_to_sys_modules(filepath)
for module in find_modules_from_path(filepath):
for name in dir(module):
... | Runs a python shell.
Usage:
$ wsgicli shell app.py app -i ipython |
388,248 | def _authenticated_call_geocoder(self, url, timeout=DEFAULT_SENTINEL):
if self.token is None or int(time()) > self.token_expiry:
self._refresh_authentication_token()
request = Request(
"&".join((url, urlencode({"token": self.token}))),
headers={"Referer": sel... | Wrap self._call_geocoder, handling tokens. |
388,249 | def main(argv: Sequence[str] = SYS_ARGV) -> int:
args = default_parser().parse_args(argv)
try:
seq = POPULATIONS[args.population]
except KeyError:
try:
with open(args.population, , encoding=args.encoding) as file_:
seq = list(file_)
except (OSError... | Execute CLI commands. |
388,250 | def map_E_to_height(self, alat, alon, height, newheight, E):
return self._map_EV_to_height(alat, alon, height, newheight, E, ) | Performs mapping of electric field along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude... |
388,251 | def get_module_functions(modules):
module_fns = set()
for module in modules:
for key in dir(module):
attr = getattr(module, key)
if isinstance(
attr, (types.BuiltinFunctionType, types.FunctionType, numpy.ufunc)):
module_fns.add(attr)
return module_fns | Finds functions that do not have implemented derivatives.
Args:
modules: A list of Python modules. Functions contained in these modules
will be checked for membership in 'implemented', and if not found,
will be added to an 'unimplemented' set
implemented: A Python object containing implemente... |
388,252 | def iter_schemas(self, schema: Schema) -> Iterable[Tuple[str, Any]]:
if not schema:
return
yield self.to_tuple(schema)
for name, field in self.iter_fields(schema):
if isinstance(field, Nested):
yield self.to_tuple(field.schema)
y... | Build zero or more JSON schemas for a marshmallow schema.
Generates: name, schema pairs. |
388,253 | def get_field_label(self, field_name, field=None):
label = None
if field is not None:
label = getattr(field, , None)
if label is None:
label = getattr(field, , None)
if label is None:
label = field_name
return label.capitalize(... | Return a label to display for a field |
388,254 | def apply(self, q, bindings, cuts):
info = []
for (ref, operator, value) in self.parse(cuts):
if map_is_class and isinstance(value, map):
value = list(value)
self._check_type(ref, value)
info.append({: ref, : operator, : value})
ta... | Apply a set of filters, which can be given as a set of tuples in
the form (ref, operator, value), or as a string in query form. If it
is ``None``, no filter will be applied. |
388,255 | def make_url_absolute(self, url, resolve_base=False):
if self.config[]:
if resolve_base:
ubody = self.doc.unicode_body()
base_url = find_base_url(ubody)
if base_url:
return urljoin(base_url, url)
return urljoin... | Make url absolute using previous request url as base url. |
388,256 | def _init_usrgos(self, goids):
usrgos = set()
goids_missing = set()
_go2obj = self.gosubdag.go2obj
for goid in goids:
if goid in _go2obj:
usrgos.add(goid)
else:
goids_missing.add(goid)
if goids_missing:
... | Return user GO IDs which have GO Terms. |
388,257 | def text_height(text):
(d1, d2, ymin, ymax) = get_dimension(text)
return (ymax - ymin, ymax) | Return the total height of the <text> and the length from the
base point to the top of the text box. |
388,258 | def read_links_file(self,file_path):
IPOwww.cs.columbia.edu
articles = []
with open(file_path) as f:
for line in f:
line = line.strip()
if len(line) != 0:
link,category = line.split()
articles.a... | Read links and associated categories for specified articles
in text file seperated by a space
Args:
file_path (str): The path to text file with news article links
and category
Returns:
articles: Array of tuples that contains article link & ... |
388,259 | def parse_keypair_lines(content, delim=, kv_sep=):
r = []
if content:
for row in [line for line in content if line]:
item_dict = {}
for item in row.split(delim):
key, value = [i.strip("'\"").strip() for i in item.strip().split(kv_sep)]
item_di... | Parses a set of entities, where each entity is a set of key-value pairs
contained all on one line. Each entity is parsed into a dictionary and
added to the list returned from this function. |
388,260 | def render_pdf_file_to_image_files__ghostscript_png(pdf_file_name,
root_output_file_path,
res_x=150, res_y=150):
if not gs_executable: init_and_test_gs_executable(exit_on_fail=True)
comman... | Use Ghostscript to render a PDF file to .png images. The root_output_file_path
is prepended to all the output files, which have numbers and extensions added.
Return the command output. |
388,261 | def exchange_additional_URL(self, handle, old, new):
LOGGER.debug()
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg =
raise HandleNotFoundException(
handle=handle,
msg=msg
... | Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL. |
388,262 | def render(self, template=None, additional=None):
template_path = template or self.get_template_path()
template_vars = {: self}
if additional:
template_vars.update(additional)
rendered = render_to_string(template_path, template_vars)
return mark_safe(render... | Render single model to its html representation.
You may set template path in render function argument,
or model's variable named 'template_path',
or get default name: $app_label$/models/$model_name$.html
Settings:
* MODEL_RENDER_DEFAULT_EXTENSION
set default... |
388,263 | def set_item(filename, item):
with atomic_write(os.fsencode(str(filename))) as temp_file:
with open(os.fsencode(str(filename))) as products_file:
products_data = json.load(products_file)
uuid_list = [i for i in filter(
lambda z: z["uuid"] == str(ite... | Save entry to JSON file |
388,264 | def _get_measure_outcome(self, qubit):
axis = list(range(self._number_of_qubits))
axis.remove(self._number_of_qubits - 1 - qubit)
probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis))
random_number = self._local_random.rand()
if rando... | Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probability of the returned outcome. |
388,265 | def server_list_detailed(self):
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
: {},
: {},
: item.accessIPv4,
: item.accessIPv6,
... | Detailed list of servers |
388,266 | def match(self, path):
this = self.segments
that = path.split()
current_var = None
bindings = {}
segment_count = self.segment_count
j = 0
for i in range(0, len(this)):
if j >= len(that):
break
if this[i].kind == _TE... | Matches a fully qualified path template string.
Args:
path (str): A fully qualified path template string.
Returns:
dict: Var names to matched binding values.
Raises:
ValidationException: If path can't be matched to the template. |
388,267 | def bft(self):
queue = deque([self])
while queue:
node = queue.pop()
yield node
if hasattr(node, "childs"):
queue.extendleft(node.childs) | Generator that returns each element of the tree in Breadth-first order |
388,268 | def build_subtree_strut(self, result, *args, **kwargs):
return self.service.build_subtree_strut(result=result, *args, **kwargs) | Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return: |
388,269 | def get_group_summary(self, group_id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.get_group_summary_with_http_info(group_id, **kwargs)
else:
(data) = self.get_group_summary_with_http_info(group_id, **kwargs)
return data | Get group information. # noqa: E501
An endpoint for getting general information about the group. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by default. To make... |
388,270 | def load_remotes(extra_path=None, load_user=True):
from os.path import getmtime
try:
remotes_file = find_config_file(REMOTES_FILE, extra_path=extra_path, load_user=load_user)
except ConfigurationError:
remotes_file = None
if remotes_file is not None and os.path.exists(remotes_fi... | Load the YAML remotes file, which sort of combines the Accounts file with part of the
remotes sections from the main config
:return: An `AttrDict` |
388,271 | def addKwdArgsToSig(sigStr, kwArgsDict):
retval = sigStr
if len(kwArgsDict) > 0:
retval = retval.strip()
for k in kwArgsDict:
if retval[-1] != : retval += ", "
retval += str(k)+"="+str(kwArgsDict[k])
retval +=
retval = retval
return retval | Alter the passed function signature string to add the given kewords |
388,272 | def _generate_union(self, union_type):
union_name = fmt_type_name(union_type)
self._emit_jsdoc_header(union_type.doc)
self.emit( % union_name)
variant_types = []
for variant in union_type.all_fields:
variant_types.append("" % variant.name)
variant... | Emits a JSDoc @typedef for a union type. |
388,273 | def snapshot(self, filename="tmp.png"):
if not filename:
filename = "tmp.png"
if self.handle:
try:
screenshot(filename, self.handle)
except win32gui.error:
self.handle = None
screenshot(filename)
else:
... | Take a screenshot and save it to `tmp.png` filename by default
Args:
filename: name of file where to store the screenshot
Returns:
display the screenshot |
388,274 | def render_field_errors(field):
if field.errors:
html = .format(
errors=.join(field.errors)
)
return HTMLString(html)
return None | Render field errors as html. |
388,275 | def detect(self, app):
script = os.path.join(self.folder, , )
cmd = % (script, app.folder)
result = run(cmd)
return result.status_code == 0 | Given an app, run detect script on it to determine whether it can be
built with this pack. Return True/False. |
388,276 | def get_model_spec_ting(atomic_number):
DATA_DIR = "/Users/annaho/Data/LAMOST/Mass_And_Age"
temp = np.load("%s/X_u_template_KGh_res=1800.npz" %DATA_DIR)
X_u_template = temp["X_u_template"]
wl = temp["wavelength"]
grad_spec = X_u_template[:,atomic_number]
return wl, grad_spec | X_u_template[0:2] are teff, logg, vturb in km/s
X_u_template[:,3] -> onward, put atomic number
atomic_number is 6 for C, 7 for N |
388,277 | def event(self, *topics, **kwargs):
workers = kwargs.pop("workers", 1)
multi = kwargs.pop("multi", False)
queue_limit = kwargs.pop("queue_limit", 10000)
def wrapper(func):
for topic in topics:
queues = [Queue() for _ in range(workers)]
... | Topic callback registry.
callback func should receive two args: topic and pk, and then process
the replication job.
Note: The callback func must return True/False. When passed a list of
pks, the func should return a list of True/False with the same length
of pks.
:para... |
388,278 | def launch_image(
player: Player,
nth_player: int,
num_players: int,
headless: bool,
game_name: str,
map_name: str,
game_type: GameType,
game_speed: int,
timeout: Optional[int],
hide_names: bool,
random_names: boo... | :raises docker,errors.APIError
:raises DockerException |
388,279 | def data_parallelism(daisy_chain_variables=True,
all_workers=False,
ps_replicas=0,
ps_job="/job:ps",
ps_gpu=0,
schedule="continuous_train_and_eval",
sync=False,
worker_gpu=1... | See data_parallelism_from_flags. |
388,280 | def op(name,
data,
bucket_count=None,
display_name=None,
description=None,
collections=None):
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name, descripti... | Create a legacy histogram summary op.
Arguments:
name: A unique name for the generated summary node.
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_count: Optional positive `int`. The output will have this
many buckets, except in two edge cases. If there is no data, then
... |
388,281 | def _wait_for_result(self):
basetime = 0.018 if self._low_res else 0.128
sleep(basetime * (self._mtreg / 69.0) + self._delay) | Wait for the sensor to be ready for measurement. |
388,282 | def del_team(self, team, sync=True):
LOGGER.debug("OSInstance.del_team")
if not sync:
self.team_2_rm.append(team)
else:
if team.id is None:
team.sync()
if self.id is not None and team.id is not None:
params = {
... | delete team from this OS instance
:param team: the team to be deleted from this OS instance
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the team object on list to be removed on next save().
:return: |
388,283 | def _build_id_tuple(params, spec):
if spec is None:
return (None, None)
required_class = spec.class_
required_tag = spec.tag
_tag_type_to_explicit_implicit(params)
if in params:
if isinstance(params[], tuple):
required_class, required_tag = params[]
... | Builds a 2-element tuple used to identify fields by grabbing the class_
and tag from an Asn1Value class and the params dict being passed to it
:param params:
A dict of params to pass to spec
:param spec:
An Asn1Value class
:return:
A 2-element integer tuple in the form (class_... |
388,284 | def format_output(old_maps, new_maps):
if isinstance(old_maps, record.FieldArray):
keys = new_maps.keys()
values = [new_maps[key] for key in keys]
for key, vals in zip(keys, values):
try:
old_maps = old_maps.add_fields([v... | This function takes the returned dict from `transform` and converts
it to the same datatype as the input.
Parameters
----------
old_maps : {FieldArray, dict}
The mapping object to add new maps to.
new_maps : dict
A dict with key as parameter name and valu... |
388,285 | def subsite_upcoming_events(context):
request = context[]
home = request.site.root_page
return {: request,
: getAllUpcomingEvents(request, home=home)} | Displays a list of all upcoming events in this site. |
388,286 | def get_student_item_dict(self, anonymous_user_id=None):
item_id = self._serialize_opaque_key(self.scope_ids.usage_id)
if hasattr(self, "xmodule_runtime"):
course_id = self.get_course_id()
if anonymous_user_id:
student_id = anonymou... | Create a student_item_dict from our surrounding context.
See also: submissions.api for details.
Args:
anonymous_user_id(str): A unique anonymous_user_id for (user, course) pair.
Returns:
(dict): The student item associated with this XBlock instance. This
... |
388,287 | def rotate(self, img):
try:
exif = image2exif.get_exif(img)
except AttributeError:
landscape = img.height < img.width
if orientation == 6 and landscape:
print("ROTATING")
return img.rotate(-90)
return img | Rotate image if exif says it needs it |
388,288 | def all_hosts(self):
return set(imap(common.clean_node, itertools.chain(
self._doc.get(, []),
self._doc.get(, []),
self._doc.get(, [])))) | List of hosts, passives, and arbiters known to this server. |
388,289 | def _generate_union_class(self, ns, data_type):
self.emit(self._class_declaration_for_type(ns, data_type))
with self.indent():
self.emit()
self.emit()
self._generate_union_class_vars(data_type)
self._generate_union_class_variant_creators... | Defines a Python class that represents a union in Stone. |
388,290 | def aitoffImageToSphere(x, y):
x = x - 360.*(x>180)
x = np.asarray(np.radians(x))
y = np.asarray(np.radians(y))
z = np.sqrt(1. - (x / 4.)**2 - (y / 2.)**2)
lon = 2. * np.arctan2((2. * z**2) - 1, (z / 2.) * x)
lat = np.arcsin( y * z)
return ((180. - np.degrees(lon)) % 360.), np.degrees(... | Inverse Hammer-Aitoff projection (deg). |
388,291 | def sortedbyAge(self):
ageAll = numpy.zeros(self.length)
for i in range(self.length):
ageAll[i] = self.Ind[i].age
ageSorted = ageAll.argsort()
return ageSorted[::-1] | Sorting the pop. base of the age |
388,292 | def _print_checker_doc(checker_name, info, stream=None):
if not stream:
stream = sys.stdout
doc = info.get("doc")
module = info.get("module")
msgs = info.get("msgs")
options = info.get("options")
reports = info.get("reports")
checker_title =... | Helper method for print_full_documentation.
Also used by doc/exts/pylint_extensions.py. |
388,293 | def sort_by_ref(vcf_file, data):
out_file = "%s-prep.vcf.gz" % utils.splitext_plus(vcf_file)[0]
if not utils.file_uptodate(out_file, vcf_file):
with file_transaction(data, out_file) as tx_out_file:
header_file = "%s-header.txt" % utils.splitext_plus(tx_out_file)[0]
with open... | Sort a VCF file by genome reference and position, adding contig information. |
388,294 | def do_POST(self):
if not self.is_rpc_path_valid():
self.report_404()
return
try:
max_chunk_size = 10 * 1024 * 1024
size_remaining = int(self.headers["content-length"])
L =... | Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling. |
388,295 | def act(self, cmd_name, params=None):
command = getattr(self, cmd_name)
if params:
command(params)
else:
command() | Run the specified command with its parameters. |
388,296 | def discrete_rainbow(N=7, cmap=cm.Set1, usepreset=True, shuffle=False, \
plot=False):
import random
from scipy import interpolate
if usepreset:
if 0 < N <= 5:
cmap = cm.gist_rainbow
elif N <= 20:
cmap = cm.Set1
else:
sys.... | Return a discrete colormap and the set of colors.
modified from
<http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations>
cmap: colormap instance, eg. cm.jet.
N: Number of colors.
Example
>>> x = resize(arange(100), (5,100))
>>> djet = cmap_discretize(cm.jet, 5)
>>> imshow(x,... |
388,297 | def normalize_unicode(text):
if isinstance(text, six.text_type):
return unicodedata.normalize(, text).encode(, ).decode()
else:
return text | Normalize any unicode characters to ascii equivalent
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize |
388,298 | def convert_tkinter_size_to_Wx(size):
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF:
qtsize = size[0]*DEFAULT_PIXELS_TO_CHARS_SCALING[0], size[1]*DEFAULT_PIXELS_TO_CHARS_SCALING[1]
return qtsize | Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels |
388,299 | def iterate(t_table, wordlist, stanzas, schemes, rprobs, maxsteps):
data_probs = numpy.zeros(len(stanzas))
old_data_probs = None
probs = None
num_words = len(wordlist)
ctr = 0
for ctr in range(maxsteps):
logging.info("Iteration {}".format(ctr))
old_data_probs = data_probs
... | Iterate EM and return final probabilities |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.