Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
12,600 | def fetch_blob(cls, username, password, multifactor_password=None, client_id=None):
session = fetcher.login(username, password, multifactor_password, client_id)
blob = fetcher.fetch(session)
fetcher.logout(session)
return blob | Just fetches the blob, could be used to store it locally |
12,601 | def create_gre_tunnel_no_encryption(cls, name, local_endpoint, remote_endpoint,
mtu=0, pmtu_discovery=True, ttl=0,
enabled=True, comment=None):
return cls.create_gre_tunnel_mode(
name, local_endpoint, remote_endpoint, policy_vpn=None,
... | Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for
constructor descriptions. |
12,602 | def _prune_penalty_box(self):
added = False
for client in self.penalty_box.get():
log.info("Client %r is back up.", client)
self.active_clients.append(client)
added = True
if added:
self._sort_clients() | Restores clients that have reconnected.
This function should be called first for every public method. |
12,603 | def get_signature_candidate(lines):
non_empty = [i for i, line in enumerate(lines) if line.strip()]
if len(non_empty) <= 1:
return []
candidate = candidate[-SIGNATURE_MAX_LINES:]
markers = _mark_candidate_indexes(lines, candidate)
candidate = _process_marked_candidate_... | Return lines that could hold signature
The lines should:
* be among last SIGNATURE_MAX_LINES non-empty lines.
* not include first line
* be shorter than TOO_LONG_SIGNATURE_LINE
* not include more than one line that starts with dashes |
12,604 | def check_node_parent(
self, resource_id, new_parent_id, db_session=None, *args, **kwargs
):
return self.service.check_node_parent(
resource_id=resource_id,
new_parent_id=new_parent_id,
db_session=db_session,
*args,
**kwargs
... | Checks if parent destination is valid for node
:param resource_id:
:param new_parent_id:
:param db_session:
:return: |
12,605 | def get_subclass_tree(cls, ensure_unique=True):
subclasses = []
for subcls in type.__subclasses__(cls):
subclasses.append(subcls)
subclasses.extend(get_subclass_tree(subcls, ensure_unique))
return list(set(subclasses)) if ensure_unique else subclasses | Returns all subclasses (direct and recursive) of cls. |
12,606 | def get_json_response_object(self, datatable):
datatable.populate_records()
draw = getattr(self.request, self.request.method).get(, None)
if draw is not None:
draw = escape_uri_path(draw)
response_data = {
: draw,
... | Returns the JSON-compatible dictionary that will be serialized for an AJAX response.
The value names are in the form "s~" for strings, "i~" for integers, and "a~" for arrays,
if you're unfamiliar with the old C-style jargon used in dataTables.js. "aa~" means
"array of arrays". In some instanc... |
12,607 | def get_callback_function(setting_name, default=None):
func = getattr(settings, setting_name, None)
if not func:
return default
if callable(func):
return func
if isinstance(func, str):
func = import_string(func)
if not callable(func):
raise ImproperlyConfigured("{name} must be callable.".format(name=s... | Resolve a callback function based on a setting name.
If the setting value isn't set, default is returned. If the setting value
is already a callable function, that value is used - If the setting value
is a string, an attempt is made to import it. Anything else will result in
a failed import causing ImportError t... |
12,608 | def add_load(self, lv_load):
if lv_load not in self._loads and isinstance(lv_load,
LVLoadDing0):
self._loads.append(lv_load)
self.graph_add_node(lv_load) | Adds a LV load to _loads and grid graph if not already existing
Parameters
----------
lv_load :
Description #TODO |
12,609 | def compare(left: Union[str, pathlib.Path, _Entity],
right: Union[str, pathlib.Path, _Entity]) -> Comparison:
def normalise(param: Union[str, pathlib.Path, _Entity]) -> _Entity:
if isinstance(param, str):
param = pathlib.Path(param)
if isinstance(param, pathlib... | Compare two paths.
:param left: The left side or "before" entity.
:param right: The right side or "after" entity.
:return: A comparison details what has changed from the left side to the
right side. |
12,610 | def _split_input_slice(batch_size, work_load_list):
total_work_load = sum(work_load_list)
batch_num_list = [round(work_load * batch_size / total_work_load)
for work_load in work_load_list]
batch_num_sum = sum(batch_num_list)
if batch_num_sum < batch_size:
batch_num_lis... | Get input slice from the input shape.
Parameters
----------
batch_size : int
The number of samples in a mini-batch.
work_load_list : list of float or int, optional
The list of work load for different devices,
in the same order as `ctx`.
Returns
-------
slices : list... |
12,611 | def get_column_at_index(self, index):
if index is None:
return None
url = self.build_url(self._endpoints.get())
response = self.session.post(url, data={: index})
if not response:
return None
return self.column_constructor(parent=self, **{self._... | Returns a table column by it's index
:param int index: the zero-indexed position of the column in the table |
12,612 | def upload_file(request):
if request.method == :
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
context_dict = {}
try:
context_dict[] = update_media_file(
request.FILES[])
except Exception as e:
... | Upload a Zip File Containing a single file containing media. |
12,613 | def standard_block(self, bytes_):
self.out(self.LH(len(bytes_) + 1))
checksum = 0
for i in bytes_:
checksum ^= (int(i) & 0xFF)
self.out(i)
self.out(checksum) | Adds a standard block of bytes. For TAP files, it's just the
Low + Hi byte plus the content (here, the bytes plus the checksum) |
12,614 | def apply_plugin_settings(self, options):
color_scheme_n =
color_scheme_o = self.get_color_scheme()
font_n =
font_o = self.get_plugin_font()
wrap_n =
wrap_o = self.get_option(wrap_n)
self.wrap_action.setChecked(wrap_o)
linenb_n =
... | Apply configuration file's plugin settings |
12,615 | def _allowAnotherAt(cls, parent):
site = parent.get_site()
if site is None:
return False
return not cls.peers().descendant_of(site.root_page).exists() | You can only create one of these pages per site. |
12,616 | def wheel_dist_name(self):
components = (safer_name(self.distribution.get_name()),
safer_version(self.distribution.get_version()))
if self.build_number:
components += (self.build_number,)
return .join(components) | Return distribution full name with - replaced with _ |
12,617 | def cPrint(self, level, message, *args, **kw):
if level > self.consolePrinterVerbosity:
return
if len(kw) > 1:
raise KeyError("Invalid keywords for cPrint: %s" % str(kw.keys()))
newline = kw.get("newline", True)
if len(kw) == 1 and not in kw:
raise KeyError("Invalid keyword fo... | Print a message to the console.
Prints only if level <= self.consolePrinterVerbosity
Printing with level 0 is equivalent to using a print statement,
and should normally be avoided.
:param level: (int) indicating the urgency of the message with
lower values meaning more urgent (messages at l... |
12,618 | def get_filtered_register_graph(register_uri, g):
import requests
from pyldapi.exceptions import ViewsFormatsException
assert isinstance(g, Graph)
logging.debug( + register_uri.replace(, ))
try:
r = requests.get(register_uri)
print( + register_uri)
except ViewsFormatsExcepti... | Gets a filtered version (label, comment, contained item classes & subregisters only) of the each register for the
Register of Registers
:param register_uri: the public URI of the register
:type register_uri: string
:param g: the rdf graph to append registers to
:type g: Graph
:return: True if o... |
12,619 | def _combine(self, applied, shortcut=False):
applied_example, applied = peek_at(applied)
coord, dim, positions = self._infer_concat_args(applied_example)
if shortcut:
combined = self._concat_shortcut(applied, dim, positions)
else:
combined = concat(applie... | Recombine the applied objects like the original. |
12,620 | def state_province_region(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError(
.format(value))
if in value:
raise ValueError(
... | Corresponds to IDD Field `state_province_region`
Args:
value (str): value for IDD Field `state_province_region`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value... |
12,621 | def reboot_node(node_id, profile, **libcloud_kwargs):
s reboot_node method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-block:: bash
salt myminion libcloud_compute.reboot_node as-2346 profile1
'
conn = _get_driver(profile=profile)
node = _get_by_id(conn.list_nodes(**libcl... | Reboot a node in the cloud
:param node_id: Unique ID of the node to reboot
:type node_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's reboot_node method
:type libcloud_kwargs: ``dict``
CLI Example:
.. cod... |
12,622 | def _request(self, method, uri, headers={}, body=, stream=False):
response = None
headers.setdefault(,
)
if self._client._credentials:
self._security_auth_headers(self._client._credentials.username,
self._cl... | Given a Method, URL, Headers, and Body, perform and HTTP
request, and return a 3-tuple containing the response status,
response headers (as httplib.HTTPMessage), and response body. |
12,623 | def create_endpoint_folder(self, endpoint_id, folder):
try:
res = self.transfer_client.operation_mkdir(endpoint_id, folder)
bot.info("%s --> %s" %(res[], folder))
except TransferAPIError:
bot.info( %folder) | create an endpoint folder, catching the error if it exists.
Parameters
==========
endpoint_id: the endpoint id parameters
folder: the relative path of the folder to create |
12,624 | def p_union_patch(self, p):
p[0] = AstUnionPatch(
path=self.path,
lineno=p[2][1],
lexpos=p[2][2],
name=p[3],
fields=p[6],
examples=p[7],
closed=p[2][0] == ) | union_patch : PATCH uniont ID NL INDENT field_list examples DEDENT |
12,625 | def refresh(self, data):
modules = data.get("module")
update_i3status = False
for module_name in self.find_modules(modules):
module = self.py3_wrapper.output_modules[module_name]
if self.debug:
self.py3_wrapper.log("refresh %s" % module)
... | refresh the module(s) |
12,626 | def getCachedOrUpdatedValue(self, key):
try:
return self._VALUES[key]
except KeyError:
return self.getValue(key) | Gets the device's value with the given key.
If the key is not found in the cache, the value is queried from the host. |
12,627 | def add_attribute(self, tag, name, value):
self.add_tag(tag)
d = self._tags[tag]
d[name] = value | add an attribute (nam, value pair) to the named tag |
12,628 | def plot_world(*args, **kwargs):
interactive = kwargs.pop(, True)
if interactive:
plot_world_with_elegans(*args, **kwargs)
else:
plot_world_with_matplotlib(*args, **kwargs) | Generate a plot from received instance of World and show it.
See also plot_world_with_elegans and plot_world_with_matplotlib.
Parameters
----------
world : World or str
World or a HDF5 filename to render.
interactive : bool, default True
Choose a visualizer. If False, show the plot ... |
12,629 | def _get_tick_frac_labels(self):
minor_num = 4
if (self.axis.scale_type == ):
domain = self.axis.domain
if domain[1] < domain[0]:
flip = True
domain = domain[::-1]
else:
flip = False
offset = domai... | Get the major ticks, minor ticks, and major labels |
12,630 | def make_ns(self, ns):
if self.namespace:
val = {}
val.update(self.namespace)
val.update(ns)
return val
else:
return ns | Returns the `lazily` created template namespace. |
12,631 | def user(self):
try:
return self._user
except AttributeError:
self._user = MatrixUser(self.mxid, self.Api(identity=self.mxid))
return self._user | Creates a User object when requested. |
12,632 | def smoother_step(F, filt, next_pred, next_smth):
J = dotdot(filt.cov, F.T, inv(next_pred.cov))
smth_cov = filt.cov + dotdot(J, next_smth.cov - next_pred.cov, J.T)
smth_mean = filt.mean + np.matmul(next_smth.mean - next_pred.mean, J.T)
return MeanAndCov(mean=smth_mean, cov=smth_cov) | Smoothing step of Kalman filter/smoother.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
filt: MeanAndCov object
filtering distribution at time t
next_pred: MeanAndCov object
predictive distribution at time t+1
next_smth: MeanAndCov ... |
12,633 | def execute(self):
stack = self._stack
callbacks = self._callbacks
promises = []
if stack:
def process():
pipe = ConnectionManager.get(self.connection_name)
call_stack = []
... | Invoke the redispy pipeline.execute() method and take all the values
returned in sequential order of commands and map them to the
Future objects we returned when each command was queued inside
the pipeline.
Also invoke all the callback functions queued up.
:param raise_on_error: ... |
12,634 | def api_request(
self,
method,
path,
query_params=None,
data=None,
content_type=None,
headers=None,
api_base_url=None,
api_version=None,
expect_json=True,
_target_object=None,
):
url = self.build_api_url(
... | Make a request over the HTTP transport to the API.
You shouldn't need to use this method, but if you plan to
interact with the API using these primitives, this is the
correct one to use.
:type method: str
:param method: The HTTP method name (ie, ``GET``, ``POST``, etc).
... |
12,635 | def create_constants(self, rdbms):
| Factory for creating a Constants objects (i.e. objects for creating constants based on column widths, and auto
increment columns and labels).
:param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql).
:rtype: pystratum.Constants.Constants |
12,636 | def reload_cache_config(self, call_params):
path = + self.api_version +
method =
return self.request(path, method, call_params) | REST Reload Plivo Cache Config helper |
12,637 | def get_window_settings(self):
window_size = (self.window_size.width(), self.window_size.height())
is_fullscreen = self.isFullScreen()
if is_fullscreen:
is_maximized = self.maximized_flag
else:
is_maximized = self.isMaximized()
pos = (self... | Return current window settings
Symetric to the 'set_window_settings' setter |
12,638 | def recv(sock, size):
data = sock.recv(size, socket.MSG_WAITALL)
if len(data) < size:
raise socket.error(ECONNRESET, )
return data | Receives exactly `size` bytes. This function blocks the thread. |
12,639 | def fork(self, server_address: str = None, *, namespace: str = None) -> "State":
r
if server_address is None:
server_address = self.server_address
if namespace is None:
namespace = self.namespace
return self.__class__(server_address, namespace=namespace) | r"""
"Forks" this State object.
Takes the same args as the :py:class:`State` constructor,
except that they automatically default to the values provided during the creation of this State object.
If no args are provided to this function,
then it shall create a new :py:class:`Stat... |
12,640 | def timeout(seconds=None, use_signals=True, timeout_exception=TimeoutError, exception_message=None):
def decorate(function):
if not seconds:
return function
if use_signals:
def handler(signum, frame):
_raise_exception(timeout_exception, exception_messag... | Add a timeout parameter to a function and return it.
:param seconds: optional time limit in seconds or fractions of a second. If None is passed, no timeout is applied.
This adds some flexibility to the usage: you can disable timing out depending on the settings.
:type seconds: float
:param use_sign... |
12,641 | def process_rst_and_summaries(content_generators):
for generator in content_generators:
if isinstance(generator, generators.ArticlesGenerator):
for article in (
generator.articles +
generator.translations +
generator.drafts):
... | Ensure mathjax script is applied to RST and summaries are
corrected if specified in user settings.
Handles content attached to ArticleGenerator and PageGenerator objects,
since the plugin doesn't know how to handle other Generator types.
For reStructuredText content, examine both articles and pages.
... |
12,642 | def parse_epsv_response(s):
matches = tuple(re.finditer(r"\((.)\1\1\d+\1\)", s))
s = matches[-1].group()
port = int(s[4:-2])
return None, port | Parsing `EPSV` (`message (|||port|)`) response.
:param s: response line
:type s: :py:class:`str`
:return: (ip, port)
:rtype: (:py:class:`None`, :py:class:`int`) |
12,643 | def predict(self, X):
return [self.classes[prediction.argmax()] for prediction in self.predict_proba(X)] | Predict the class for X.
The predicted class for each sample in X is returned.
Parameters
----------
X : List of ndarrays, one for each training example.
Each training example's shape is (string1_len,
string2_len, n_features), where string1_len and
s... |
12,644 | def regions(self):
url = "%s/regions" % self.root
params = {"f": "json"}
return self._get(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | gets the regions value |
12,645 | def output_to_json(sources):
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
source_name = source.get_source_name()
results[source_name] = source.get_sensors_summary()
print(json.dumps(results, indent=4))
sys.e... | Print statistics to the terminal in Json format |
12,646 | def minimumBelow(requestContext, seriesList, n):
results = []
for series in seriesList:
val = safeMin(series)
if val is None or val <= n:
results.append(series)
return results | Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a minimum value below n.
Example::
&target=minimumBelow(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent at one point less than
1000 packets/min. |
12,647 | def fromlineno(self):
lineno = super(Arguments, self).fromlineno
return max(lineno, self.parent.fromlineno or 0) | The first line that this node appears on in the source code.
:type: int or None |
12,648 | def permission_required(perm, *lookup_variables, **kwargs):
login_url = kwargs.pop(, settings.LOGIN_URL)
redirect_field_name = kwargs.pop(, REDIRECT_FIELD_NAME)
redirect_to_login = kwargs.pop(, True)
def decorate(view_func):
def decorated(request, *args, **kwargs):
if request.u... | Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary. |
12,649 | def update(self, item, dry_run=None):
logger.debug(.format(
item=item,
namespace=self.namespace
))
if not dry_run:
self.table.put_item(Item=item)
return item | Updates item info in file. |
12,650 | def create_session(self, session_id, register=True, session_factory=None):
if session_factory is not None:
sess_factory, sess_args, sess_kwargs = session_factory
s = sess_factory(*sess_args, **sess_kwargs)
else:
s = sess... | Creates new session object and returns it.
@param session_id: Session id. If not provided, will generate a
new session id.
@param register: Should be the session registered in a storage.
Websockets don't need it.
@param session_factory: Use ... |
12,651 | def is_data_diverging(data_container):
assert infer_data_type(data_container) in [
"ordinal",
"continuous",
], "Data type should be ordinal or continuous"
has_negative = False
has_positive = False
for i in data_container:
if i < 0:
has_negative = True
... | We want to use this to check whether the data are diverging or not.
This is a simple check, can be made much more sophisticated.
:param data_container: A generic container of data points.
:type data_container: `iterable` |
12,652 | def _fix_up_properties(cls):
kind = cls._get_kind()
if not isinstance(kind, basestring):
raise KindError(
% (cls.__name__, kind))
if not isinstance(kind, str):
try:
kind = kind.encode()
except UnicodeEncodeError:
raise KindError(
... | Fix up the properties by calling their _fix_up() method.
Note: This is called by MetaModel, but may also be called manually
after dynamically updating a model class. |
12,653 | def analyze(data, normalize=None, reduce=None, ndims=None, align=None, internal=False):
return aligner(reducer(normalizer(data, normalize=normalize, internal=internal),
reduce=reduce, ndims=ndims, internal=internal), align=align) | Wrapper function for normalize -> reduce -> align transformations.
Parameters
----------
data : numpy array, pandas df, or list of arrays/dfs
The data to analyze
normalize : str or False or None
If set to 'across', the columns of the input data will be z-scored
across lists (de... |
12,654 | def lset(self, key, index, value):
redis_list = self._get_list(key, )
if redis_list is None:
raise ResponseError("no such key")
try:
redis_list[index] = self._encode(value)
except IndexError:
raise ResponseError("index out of range") | Emulate lset. |
12,655 | def create(self, **kwargs):
resource = self.resource_class(self.client)
resource.update_from_dict(kwargs)
resource.save(force_create=True)
return resource | Create a resource on the server
:params kwargs: Attributes (field names and values) of the new resource |
12,656 | def get_stored_content_length(headers):
length = headers.get()
if length is None:
length = headers.get()
return length | Return the content length (in bytes) of the object as stored in GCS.
x-goog-stored-content-length should always be present except when called via
the local dev_appserver. Therefore if it is not present we default to the
standard content-length header.
Args:
headers: a dict of headers from the http respons... |
12,657 | def make_key(table_name, objid):
key = datastore.Key()
path = key.path_element.add()
path.kind = table_name
path.name = str(objid)
return key | Create an object key for storage. |
12,658 | def main():
ctx = {}
def pretty_json(data):
return json.dumps(data, indent=2, sort_keys=True)
client = server.create_app().test_client()
host =
res = client.get(, environ_overrides={: host})
res_data = json.loads(res.data.decode())
ctx[] = pretty_json(res_data)
... | Main function |
12,659 | def sort(self, values):
for level in self:
for wire1, wire2 in level:
if values[wire1] > values[wire2]:
values[wire1], values[wire2] = values[wire2], values[wire1] | Sort the values in-place based on the connectors in the network. |
12,660 | def plistfilename(self):
t exist.
'
if self._plist_fname is None:
self._plist_fname = discover_filename(self.label)
return self._plist_fname | This is a lazily detected absolute filename of the corresponding
property list file (*.plist). None if it doesn't exist. |
12,661 | def _error_if_word_invalid(word,
valid_words_dictionary,
technical_words_dictionary,
line_offset,
col_offset):
word_lower = word.lower()
valid_words_result = valid_words_dictionary.corrections(word_l... | Return SpellcheckError if this non-technical word is invalid. |
12,662 | def _assert_command_dict(self, struct, name, path=None, extra_info=None):
self._assert_dict(struct, name, path, extra_info)
if len(struct) != 1:
err = [self._format_error_path(path + [name])]
err.append(
.format(len(struct), struct))
if... | Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair. |
12,663 | def create_api(name, description, cloneFrom=None,
region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if cloneFrom:
api = conn.create_rest_api(name=name, description=description, cloneFrom=clone... | Create a new REST API Service with the given name
Returns {created: True} if the rest api was created and returns
{created: False} if the rest api was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.create_api myapi_name api_description |
12,664 | def cur_time(typ=, tz=DEFAULT_TZ) -> (datetime.date, str):
dt = pd.Timestamp(, tz=tz)
if typ == : return dt.strftime()
if typ == : return dt.strftime()
if typ == : return dt.strftime()
if typ == : return dt
return dt.date() | Current time
Args:
typ: one of ['date', 'time', 'time_path', 'raw', '']
tz: timezone
Returns:
relevant current time or date
Examples:
>>> cur_dt = pd.Timestamp('now')
>>> cur_time(typ='date') == cur_dt.strftime('%Y-%m-%d')
True
>>> cur_time(typ='tim... |
12,665 | def do_refresh(self,args):
response = AwsConnectionFactory.getLogClient().describe_log_groups(logGroupNamePrefix=self.stackResource.physical_resource_id)
if not in response:
raise Exception("Expected log group description to have logGroups entry. Got {}".format(response))... | Refresh the view of the log group |
12,666 | def patch_sys(self, inherit_path):
def patch_dict(old_value, new_value):
old_value.clear()
old_value.update(new_value)
def patch_all(path, path_importer_cache, modules):
sys.path[:] = path
patch_dict(sys.path_importer_cache, path_importer_cache)
patch_dict(sys.modules, module... | Patch sys with all site scrubbed. |
12,667 | def _attach_record_as_json(mfg_event, record):
attachment = mfg_event.attachment.add()
attachment.name = TEST_RECORD_ATTACHMENT_NAME
test_record_dict = htf_data.convert_to_base_types(record)
attachment.value_binary = _convert_object_to_json(test_record_dict)
attachment.type = test_runs_pb2.TEXT_UTF8 | Attach a copy of the record as JSON so we have an un-mangled copy. |
12,668 | def filesfile_string(self):
lines = []
app = lines.append
app(self.input_file.path)
app(os.path.join(self.workdir, "unused"))
app(os.path.join(self.workdir, self.prefix.odata))
return "\n".join(... | String with the list of files and prefixes needed to execute ABINIT. |
12,669 | def update_stats(stats, start_time, data):
end_time = time.time()
cmd = data[]
try:
jid = data[]
except KeyError:
try:
jid = data[][]
except KeyError:
log.info()
return stats
create_time = int(time.mktime(time.strptime(jid, )))
... | Calculate the master stats and return the updated stat info |
12,670 | def slaveraise(self, type, error, traceback):
message = * 1 + pickle.dumps((type,
.join(tb.format_exception(type, error, traceback))))
if self.pipe is not None:
self.pipe.put(message) | slave only |
12,671 | def perform_iteration(self):
stats = self.get_all_stats()
self.redis_client.publish(
self.redis_key,
jsonify_asdict(stats),
) | Get any changes to the log files and push updates to Redis. |
12,672 | def laplacian(script, iterations=1, boundary=True, cotangent_weight=True,
selected=False):
filter_xml = .join([
,
,
.format(iterations),
,
,
,
,
.format(str(boundary).lower()),
,
,
,
,
.format(... | Laplacian smooth of the mesh: for each vertex it calculates the average
position with nearest vertex
Args:
script: the FilterScript object or script filename to write
the filter to.
iterations (int): The number of times that the whole algorithm (normal
smoothing + ve... |
12,673 | def one_line(self):
ret = self.get()
if ret is None:
return False
else:
return ret.lower().startswith() | Return True|False if the AMP shoukd be displayed in oneline (one_lineline=true|false). |
12,674 | def speed(self):
if self._stalled:
return 0
time_sum = 0
data_len_sum = 0
for time_diff, data_len in self._samples:
time_sum += time_diff
data_len_sum += data_len
if time_sum:
return data_len_sum / time_sum
else:... | Return the current transfer speed.
Returns:
int: The speed in bytes per second. |
12,675 | def add_to_manifest(self, manifest):
manifest.add_service(self.service.name)
varname = predix.config.set_env_value(self.use_class, ,
self._get_uri())
manifest.add_env_var(varname, self._get_uri())
manifest.write_manifest() | Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry app. |
12,676 | def chunks(iterable, size=1):
iterator = iter(iterable)
for element in iterator:
yield chain([element], islice(iterator, size - 1)) | Splits iterator in chunks. |
12,677 | def nvmlDeviceGetPcieReplayCounter(handle):
r
c_replay = c_uint()
fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieReplayCounter")
ret = fn(handle, byref(c_replay))
_nvmlCheckReturn(ret)
return bytes_to_str(c_replay.value) | r"""
/**
* Retrieve the PCIe replay counter.
*
* For Kepler &tm; or newer fully supported devices.
*
* @param device The identifier of the target device
* @param value Reference in which to return the counter's value
*
... |
12,678 | def parse_san(self, san: str) -> Move:
try:
if san in ["O-O", "O-O+", "O-O
return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move))
elif san in ["O-O-O", "O-O-O+", "O-O-O
return next(move for move in... | Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous. |
12,679 | def get_separator_words(toks1):
tab_toks1 = nltk.FreqDist(word.lower() for word in toks1)
if(os.path.isfile(ESSAY_COR_TOKENS_PATH)):
toks2 = pickle.load(open(ESSAY_COR_TOKENS_PATH, ))
else:
essay_corpus = open(ESSAY_CORPUS_PATH).read()
essay_corpus = sub_chars(essay_corpus)
... | Finds the words that separate a list of tokens from a background corpus
Basically this generates a list of informative/interesting words in a set
toks1 is a list of words
Returns a list of separator words |
12,680 | def _soap_client_call(method_name, *args):
soap_client = _build_soap_client()
soap_args = _convert_soap_method_args(*args)
if PYSIMPLESOAP_1_16_2:
return getattr(soap_client, method_name)(*soap_args)
else:
return getattr(soap_client, method_name)(soap_client, *soap_ar... | Wrapper to call SoapClient method |
12,681 | def _configure_registry(self, include_process_stats: bool = False):
if include_process_stats:
self.registry.register_additional_collector(
ProcessCollector(registry=None)) | Configure the MetricRegistry. |
12,682 | def configure(config={}, datastore=None, nested=False):
if nested:
config = nested_config(config)
| Useful for when you need to control Switchboard's setup |
12,683 | def loads(s, encoding=None, cls=None, object_hook=None, **kw):
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw[] = object_hook
return cls(encoding=encoding, **kw).decode(s) | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (s... |
12,684 | def emit(
self, tup, stream=None, anchors=None, direct_task=None, need_task_ids=False
):
if anchors is None:
anchors = self._current_tups if self.auto_anchor else []
anchors = [a.id if isinstance(a, Tuple) else a for a in anchors]
return super(Bolt, self).emit(
... | Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
JSON-serializable data.
:type tup: :class:`list` or :class:`pystorm.component.Tuple`
:param stream: the ID of the stream to emit this Tuple to. Specify
``... |
12,685 | def _restore_file_lmt(self):
if not self._restore_file_properties.lmt or self._ase.lmt is None:
return
ts = time.mktime(self._ase.lmt.timetuple())
os.utime(str(self.final_path), (ts, ts)) | Restore file lmt for file
:param Descriptor self: this |
12,686 | def compare_mim_panels(self, existing_panel, new_panel):
existing_genes = set([gene[] for gene in existing_panel[]])
new_genes = set([gene[] for gene in new_panel[]])
return new_genes.difference(existing_genes) | Check if the latest version of OMIM differs from the most recent in database
Return all genes that where not in the previous version.
Args:
existing_panel(dict)
new_panel(dict)
Returns:
new_genes(set(str)) |
12,687 | def cd(path):
t exist'
old_dir = os.getcwd()
try:
os.makedirs(path)
except OSError:
pass
os.chdir(path)
try:
yield
finally:
os.chdir(old_dir) | Creates the path if it doesn't exist |
12,688 | def service_define(self, service, ty):
assert service not in self._data
assert service not in self._algebs + self._states
self._service.append(service)
self._service_ty.append(ty) | Add a service variable of type ``ty`` to this model
:param str service: variable name
:param type ty: variable type
:return: None |
12,689 | def get_my_ip():
ip = subprocess.check_output(GET_IP_CMD, shell=True).decode()[:-1]
return ip.strip() | Returns this computers IP address as a string. |
12,690 | def cast_item(cls, item):
if not isinstance(item, cls.subtype):
incompatible = isinstance(item, Base) and not any(
issubclass(cls.subtype, tag_type) and isinstance(item, tag_type)
for tag_type in cls.all_tags.values()
)
if incom... | Cast list item to the appropriate tag type. |
12,691 | def capture_working_directory(self):
workdir = os.path.join(self._path, "tmp", "captures")
if not self._deleted:
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not creat... | Returns a working directory where to temporary store packet capture files.
:returns: path to the directory |
12,692 | def _histogram_fixed_binsize(a, start, width, n):
return flib.fixed_binsize(a, start, width, n) | histogram_even(a, start, width, n) -> histogram
Return an histogram where the first bin counts the number of lower
outliers and the last bin the number of upper outliers. Works only with
fixed width bins.
:Stochastics:
a : array
Array of samples.
start : float
Left-most bin... |
12,693 | def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True, add_diff=False):
result_train = []
result_test = []
y = None
for model in self.models:
result = model.stack(k=k, stratify=stratify, shuffle=shuffle, seed=seed, full_test=full_test)
... | Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : int, default 100
full_test : bool, default True
If True then evaluate test dataset on ... |
12,694 | def filter_data(data, filter_dict):
for key, match_string in filter_dict.items():
if key not in data:
logger.warning("{0} doesn't match a top level key".format(key))
continue
values = data[key]
matcher = re.compile(match_string)
if isinstance(values, list... | filter a data dictionary for values only matching the filter |
12,695 | def threadpooled(
func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
*,
loop_getter: typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop],
loop_getter_need_context: bool = False,
) -> typing.Callable[..., "asyncio.Task[typing.Any]"]:... | Overload: function callable, loop getter available. |
12,696 | def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS[], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(sel... | Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pan... |
12,697 | def fmt(self):
tmpl = string.Template(self.template)
kw = {}
for key, val in self.kw.items():
if key == :
kw[key] = val
else:
kw[key] = val.fmt()
return tmpl.substitute(kw) | Make printable representation out of this instance. |
12,698 | def find_by_id(self, section, params={}, **options):
path = "/sections/%s" % (section)
return self.client.get(path, params, **options) | Returns the complete record for a single section.
Parameters
----------
section : {Id} The section to get.
[params] : {Object} Parameters for the request |
12,699 | def get_header(self, hdrclass, returnval=None):
t
found.
'
if isinstance(hdrclass, str):
return self.get_header_by_name(hdrclass)
for hdr in self._headers:
if isinstance(hdr, hdrclass):
return hdr
return returnval | Return the first header object that is of
class hdrclass, or None if the header class isn't
found. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.