Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
380,300 | def __view_add_actions(self):
self.Components_Manager_Ui_treeView.addAction(self.__engine.actions_manager.register_action(
"Actions|Umbra|Components|factory.ComponentsManagerUi|Activate Component(s)",
slot=self.__view_activate_components_action__triggered))
self.Compone... | Sets the **Components_Manager_Ui_treeView** actions. |
380,301 | def name(self):
if self.chosen_name:
return self.chosen_name
else:
name = self.process.get_name()
if name:
return os.path.basename(name)
return | The name for the window as displayed in the title bar and status bar. |
380,302 | def support_scripting(self):
if not hasattr(self, ):
try:
self._support_scripting = self.redis_version >= (2, 5) \
and hasattr(self.connection, )
except:
self._support_scripting = False
return self._support_scripting | Returns True if scripting is available. Checks are done in the client
library (redis-py) AND the redis server. Result is cached, so done only
one time. |
380,303 | def add_node(self, id, label=None, type=, meta=None):
g = self.get_graph()
if meta is None:
meta={}
g.add_node(id, label=label, type=type, meta=meta) | Add a new node to the ontology |
380,304 | def moment1(self):
delays, response = self.delay_response_series
return statstools.calc_mean_time(delays, response) | The first time delay weighted statistical moment of the
instantaneous unit hydrograph. |
380,305 | def nl_msg_in_handler_debug(msg, arg):
ofd = arg or _LOGGER.debug
ofd()
nl_msg_dump(msg, ofd)
return NL_OK | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L114. |
380,306 | def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):
if remove_all_metadata_fields:
for df in concated_meta_dfs:
df.drop(df.columns, axis=1, inplace=True)
all_concated_meta_df = pd.concat(concated_meta_dfs, axis=0)
n_rows = all_concated_met... | Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pandas dfs)
Returns:
all_concated_meta_df_sorted (pandas df) |
380,307 | def check_length_of_initial_values(self, init_values):
num_nests = self.rows_to_nests.shape[1]
num_index_coefs = self.design.shape[1]
assumed_param_dimensions = num_index_coefs + num_nests
if init_values.shape[0] != assumed_param_dimensions:
msg = ... | Ensures that the initial values are of the correct length. |
380,308 | def template_class_from_name(name):
term = TerminalView()
template_name = name +
try:
__import__( + template_name)
template_mod = sys.modules[ + template_name]
except ImportError:
term.print_error_and_exit("Unable to find {}".format(name))
try:
templa... | Return the template class object from agiven name. |
380,309 | def train(*tf_records: "Records to train on"):
tf.logging.set_verbosity(tf.logging.INFO)
estimator = dual_net.get_estimator()
effective_batch_size = FLAGS.train_batch_size
if FLAGS.use_tpu:
effective_batch_size *= FLAGS.num_tpu_cores
if FLAGS.use_tpu:
if FLAGS.use_bt:
... | Train on examples. |
380,310 | def _set_value(self, new_value):
if self.min_value is not None and new_value < self.min_value:
raise SettingOutOfBounds(
"Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}".format(
self.name, new_value, self.min_value))
... | Sets the current value of the parameter, ensuring that it is within the allowed range. |
380,311 | def predict(data, training_dir=None, model_name=None, model_version=None, cloud=False):
if cloud:
if not model_version or not model_name:
raise ValueError()
if training_dir:
raise ValueError()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return cloud_predict(m... | Runs prediction locally or on the cloud.
Args:
data: List of csv strings or a Pandas DataFrame that match the model schema.
training_dir: local path to the trained output folder.
model_name: deployed model name
model_version: depoyed model version
cloud: bool. If False, does local prediction and ... |
380,312 | def _get_styles(self, style_urls, asset_url_path):
styles = []
for style_url in style_urls:
urls_inline = STYLE_ASSET_URLS_INLINE_FORMAT.format(
asset_url_path.rstrip())
asset_content = self._download(style_url)
content = re.sub(urls_inline, s... | Gets the content of the given list of style URLs and
inlines assets. |
380,313 | def pv_absent(name):
ret = {: {},
: ,
: name,
: True}
if not __salt__[](name, quiet=True):
ret[] = .format(name)
elif __opts__[]:
ret[] = .format(name)
ret[] = None
return ret
else:
changes = __salt__[](name)
if __sa... | Ensure that a Physical Device is not being used by lvm
name
The device name to initialize. |
380,314 | def make_venv(self, dj_version):
venv_path = self._get_venv_path(dj_version)
self.logger.info( % dj_version)
try:
create_venv(venv_path, **VENV_CREATE_KWARGS)
except ValueError:
self.logger.warning()
self.venv_install( % dj_version, venv_path)
... | Creates a virtual environment for a given Django version.
:param str dj_version:
:rtype: str
:return: path to created virtual env |
380,315 | def header(self, name, default=None):
wsgi_header = "HTTP_{0}".format(name.upper())
try:
return self.env_raw[wsgi_header]
except KeyError:
return default | Returns the value of the HTTP header identified by `name`. |
380,316 | def execute(self, request):
url = request.uri
if request.parameters:
url += + urlencode(request.parameters)
if request.headers:
headers = dict(self._headers, **request.headers)
else:
headers = self._headers
retry = 0
... | Execute a request and return a response |
380,317 | def convex_hull_image(image):
labels = image.astype(int)
points, counts = convex_hull(labels, np.array([1]))
output = np.zeros(image.shape, int)
for i in range(counts[0]):
inext = (i+1) % counts[0]
draw_line(output, points[i,1:], points[inext,1:],1)
output = fill_labeled_holes(o... | Given a binary image, return an image of the convex hull |
380,318 | def set_speed(self, value):
self._combined_speed = float(value)
speed_per_min = int(self._combined_speed * SEC_PER_MIN)
command = GCODES[] + str(speed_per_min)
log.debug("set_speed: {}".format(command))
self._send_command(command) | set total axes movement speed in mm/second |
380,319 | def dict_to_etree(d, root):
u
def _to_etree(d, node):
if d is None or len(d) == 0:
return
elif isinstance(d, basestring):
node.text = d
elif isinstance(d, dict):
for k, v in d.items():
assert isinstance(k, basestring)
if... | u"""Converts a dict to lxml.etree object.
>>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS
<Element root at 0x...>
:param dict d: dict representing the XML tree
:param etree.Element root: XML node which will be assigned the resulting tree
... |
380,320 | def main(args=sys.argv[1:]):
opt = docopt(main.__doc__.strip(), args, options_first=True)
config_logging(opt[])
if opt[]:
check_backends(opt[])
elif opt[]:
handler = fulltext.get
if opt[]:
handler = _handle_open
for path in opt[]:
print(ha... | Extract text from a file.
Commands:
extract - extract text from path
check - make sure all deps are installed
Usage:
fulltext extract [-v] [-f] <path>...
fulltext check [-t]
Options:
-f, --file Open file first.
-t, --title Check deps fo... |
380,321 | def multi_curve_fit(xs, ys, verbose):
functions = {
exponential: p0_exponential,
reciprocal: p0_reciprocal,
simple_reciprocal: p0_simple_reciprocal,
simple_2reciprocal: p0_simple_2reciprocal,
simple_4reciprocal: p0_simple_4reciprocal,
simple_5recipr... | fit multiple functions to the x, y data, return the best fit |
380,322 | def get_channel_id(turn_context: TurnContext) -> str:
if turn_context.activity.channel_id is None:
return ""
else:
return turn_context.activity.channel_id | Get the Channel Id from the current Activity on the Turn Context.
Args:
turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from.
Returns:
str: The Channel Id from the Turn Context's Activity. |
380,323 | def _get_desired_pkg(name, desired):
if not desired[name] or desired[name].startswith((, , )):
oper =
else:
oper =
return .format(name, oper,
if not desired[name] else desired[name]) | Helper function that retrieves and nicely formats the desired pkg (and
version if specified) so that helpful information can be printed in the
comment for the state. |
380,324 | def enrich_relations(rdf, enrich_mappings, use_narrower, use_transitive):
if enrich_mappings:
infer.skos_symmetric_mappings(rdf)
infer.skos_hierarchical_mappings(rdf, use_narrower)
infer.skos_related(rdf)
for s, o in rdf.subject_objects(SKOSEXT.broaderGeneric):
... | Enrich the SKOS relations according to SKOS semantics, including
subproperties of broader and symmetric related properties. If use_narrower
is True, include inverse narrower relations for all broader relations. If
use_narrower is False, instead remove all narrower relations, replacing
them with inverse ... |
380,325 | def show_taghistory():
if not nav:
sys.exit(1)
ecode = 0
try:
result = nav.get_taghistory()
if result:
anchore_utils.print_result(config, result)
except:
anchore_print_err("operation failed")
ecode = 1
contexts[].clear()
sys.exit(ecod... | Show history of all known repo/tags for image |
380,326 | def toFilter(self, property):
if self.leftedge == self.rightedge and self.leftop is ge and self.rightop is le:
return Filter(style.SelectorAttributeTest(property, , self.leftedge))
try:
return Filter(style.SelectorAttributeTest(property, opstr[self.left... | Convert this range to a Filter with a tests having a given property. |
380,327 | def _set_get_vnetwork_hosts(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=get_vnetwork_hosts.get_vnetwork_hosts, is_leaf=True, yang_name="get-vnetwork-hosts", rest_name="get-vnetwork-hosts", parent=self, path_helper=self._path_helper, extmethods=sel... | Setter method for get_vnetwork_hosts, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_hosts (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vnetwork_hosts is considered as a private
method. Backends looking to populate this variable should
do so via... |
380,328 | def get_instruction(self, idx, off=None):
if self.code is not None:
return self.code.get_bc().get_instruction(idx, off)
return None | Get a particular instruction by using (default) the index of the address if specified
:param idx: index of the instruction (the position in the list of the instruction)
:type idx: int
:param off: address of the instruction
:type off: int
:rtype: an :class:`Instruction` object |
380,329 | def get_params_type(descriptor):
params = descriptor.split()[0][1:].split()
if params:
return [param for param in params]
return [] | Return the parameters type of a descriptor (e.g (IC)V) |
380,330 | def _repr_html_(self):
if self._info_repr():
buf = StringIO("")
self.info(buf=buf)
val = buf.getvalue().replace(, r, 1)
val = val.replace(, r, 1)
return + val +
if get_option("display.notebook_repr_html"):
m... | Return a html representation for a particular DataFrame.
Mainly for IPython notebook. |
380,331 | def _init_edges_relationships(rel2src2dsts, rel2dst2srcs):
edge_rel2fromto = {}
relationships = set(rel2src2dsts).union(rel2dst2srcs)
for reltype in relationships:
edge_from_to = []
if reltype in rel2src2dsts:
for parent, children in rel2src2dsts[... | Get the directed edges from GO term to GO term using relationships. |
380,332 | def log_calls(function):
def wrapper(self,*args,**kwargs):
self.log.log(group=function.__name__,message=)
function(self,*args,**kwargs)
self.log.log(group=function.__name__,message=)
return wrapper | Decorator that logs function calls in their self.log |
380,333 | def line_break(s, length=76):
x = .join(s[pos:pos + length] for pos in range(0, len(s), length))
return x | 将字符串分割成一行一行
:param s:
:param length:
:return: |
380,334 | def run_sex_check(in_prefix, in_type, out_prefix, base_dir, options):
os.mkdir(out_prefix)
required_type = "bfile"
check_input_files(in_prefix, in_type, required_type)
script_prefix = os.path.join(out_prefix, "sexcheck")
options += ["--{}".format(required_type), in_prefix,... | Runs step6 (sexcheck).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
:type in_type: str
:type out_prefix... |
380,335 | def restore(name=None, **kwargs):
**
if not status(name):
raise CommandExecutionError()
frozen_pkgs = {}
frozen_repos = {}
for name, content in zip(_paths(name), (frozen_pkgs, frozen_repos)):
with fopen(name) as fp:
content.update(json.load(fp))
... | Make sure that the system contains the packages and repos from a
frozen state.
Read the list of packages and repositories from the freeze file,
and compare it with the current list of packages and repos. If
there is any difference, all the missing packages are repos will
be installed, and all the e... |
380,336 | def onReactionRemoved(
self,
mid=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
log.info(
"{} removed reaction from {} message in {} ({})".format(
author_id, mid, thread_id, thread_typ... | Called when the client is listening, and somebody removes reaction from a message
:param mid: Message ID, that user reacted to
:param author_id: The ID of the person who removed reaction
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type... |
380,337 | def mimeData( self, items ):
func = self.dataCollector()
if ( func ):
return func(self, items)
return super(XTableWidget, self).mimeData(items) | Returns the mime data for dragging for this instance.
:param items | [<QTableWidgetItem>, ..] |
380,338 | def messages(self):
if self._messages is None:
self._messages = MessageList(self._version, session_sid=self._solution[], )
return self._messages | Access the messages
:returns: twilio.rest.messaging.v1.session.message.MessageList
:rtype: twilio.rest.messaging.v1.session.message.MessageList |
380,339 | def copy(self):
stat_result = copy(self)
stat_result.use_float = self.use_float
return stat_result | Return a copy where the float usage is hard-coded to mimic the
behavior of the real os.stat_result. |
380,340 | def delete_all_objects(self, nms, async_=False):
if nms is None:
nms = self.api.list_object_names(self.name, full_listing=True)
return self.api.bulk_delete(self.name, nms, async_=async_) | Deletes all objects from this container.
By default the call will block until all objects have been deleted. By
passing True for the 'async_' parameter, this method will not block, and
instead return an object that can be used to follow the progress of the
deletion. When deletion is com... |
380,341 | def remove(self, key, value):
check_not_none(key, "key cant be none")
return self._encode_invoke(transactional_multi_map_remove_entry_codec, key=self._to_data(key),
value=self._to_data(value)) | Transactional implementation of :func:`MultiMap.remove(key, value)
<hazelcast.proxy.multi_map.MultiMap.remove>`
:param key: (object), the key of the entry to remove.
:param value: (object), the value of the entry to remove.
:return: |
380,342 | def create_build_paths(context: Context):
paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path]
for path in filter(None, paths):
os.makedirs(path, exist_ok=True) | Creates directories needed for build outputs |
380,343 | def lines2mecab(lines, **kwargs):
sents = []
for line in lines:
sent = txt2mecab(line, **kwargs)
sents.append(sent)
return sents | Use mecab to parse many lines |
380,344 | def aggregate(self, block_size):
raster2 = block_reduce(self.raster, block_size, func=np.ma.sum)
geot = self.geot
geot = (geot[0], block_size[0] * geot[1], geot[2], geot[3], geot[4],
block_size[1] * geot[-1])
return GeoRaster(raster2, geot, nodata_value=self.noda... | geo.aggregate(block_size)
Returns copy of raster aggregated to smaller resolution, by adding cells. |
380,345 | def list_port_fwd(zone, permanent=True):
*
ret = []
cmd = .format(zone)
if permanent:
cmd +=
for i in __firewall_cmd(cmd).splitlines():
(src, proto, dest, addr) = i.split()
ret.append(
{: src.split()[1],
: proto.split()[1],
: dest.sp... | List port forwarding
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_port_fwd public |
380,346 | def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port):
_, block_index = rhs.index_in_block(in_port)
rest = tuple(rest)
bs = rhs.block_structure
(nbefore, nblock, nafter) = (sum(bs[:block_index]),
bs[block_index],
sum(bs[b... | Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a
series product self-feedback. |
380,347 | def configure_logging(level):
global logging_level
logging_level = logging.ERROR
if "info" == level.lower():
logging_level = logging.INFO
elif "warn" == level.lower():
logging_level = logging.WARNING
elif "debug" == level.lower():
logging_level = logging.DEBUG | Configure global log level to given one
:param level: Level (INFO | DEBUG | WARN | ERROR)
:return: |
380,348 | def _get_grammar_errors(self,pos,text,tokens):
word_counts = [max(len(t),1) for t in tokens]
good_pos_tags = []
min_pos_seq=2
max_pos_seq=4
bad_pos_positions=[]
for i in xrange(0, len(text)):
pos_seq = [tag[1] for tag in pos[i]]
pos_ngrams... | Internal function to get the number of grammar errors in given text
pos - part of speech tagged text (list)
text - normal text (list)
tokens - list of lists of tokenized text |
380,349 | def render_xml_to_string(template, input, params=None):
xsl_path = find_template_path(template)
result = transform(input, str(xsl_path), params)
return result | Transforms ``input`` using ``template``, which should be an xslt.
:param template: an xslt template name.
:param input: an string that contains xml
:param params: A dictionary containing xslt parameters. Use :func:`~easymode.xslt.prepare_string_param`\
on strings you want to pass in.
:rtype... |
380,350 | def load_locale(locale, icu=False):
if locale not in locales:
raise NotImplementedError("The locale is not supported" % locale)
if locale not in __locale_caches:
mod = __import__(__name__, fromlist=[locale], level=0)
__locale_caches[locale] = getattr(mod, locale)
return __local... | Return data of locale
:param locale:
:return: |
380,351 | def _compute_f3(self, C, mag):
if mag <= 5.8:
return C[]
elif 5.8 < mag < C[]:
return (
C[] +
(C[] - C[]) * (mag - 5.8) / (C[] - 5.8)
)
else:
return C[] | Compute f3 term (eq.6, page 106)
NOTE: In the original manuscript, for the case 5.8 < mag < c1,
the term in the numerator '(mag - 5.8)' is missing, while is
present in the software used for creating the verification tables |
380,352 | def size(self):
return (0 if self.shape == () else
int(np.prod(self.shape, dtype=))) | Total number of grid points. |
380,353 | def domains(request):
url =
query =
if settings.SEARCH_TYPE == :
url = % (settings.SEARCH_URL, query)
if settings.SEARCH_TYPE == :
url = % (settings.SEARCH_URL, query)
LOGGER.debug(url)
response = urllib2.urlopen(url)
data = response.read().replace(, )
layer... | A page with number of services and layers faceted on domains. |
380,354 | def data_vector_from_blurred_mapping_matrix_and_data(blurred_mapping_matrix, image_1d, noise_map_1d):
mapping_shape = blurred_mapping_matrix.shape
data_vector = np.zeros(mapping_shape[1])
for image_index in range(mapping_shape[0]):
for pix_index in range(mapping_shape[1]):
data_v... | Compute the hyper vector *D* from a blurred mapping matrix *f* and the 1D image *d* and 1D noise-map *\sigma* \
(see Warren & Dye 2003).
Parameters
-----------
blurred_mapping_matrix : ndarray
The matrix representing the blurred mappings between sub-grid pixels and pixelization pixels.
... |
380,355 | def dump(self):
data = dict(
sessions_active=self.sess_active,
connections_active=self.conn_active,
connections_ps=self.conn_ps.last_average,
packets_sent_ps=self.pack_sent_ps.last_average,
packets_recv... | Return dictionary with current statistical information |
380,356 | def DeserializeTX(buffer):
mstream = MemoryStream(buffer)
reader = BinaryReader(mstream)
tx = Transaction.DeserializeFrom(reader)
return tx | Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction: |
380,357 | def reserve(self, location=None, force=False, wait_for_up=True, timeout=80):
if not location or is_local_host(location):
return
hostname, card, port = location.split()
chassis = self.root.hw.get_chassis(hostname)
if force:
chassis.get_card(int... | Reserve port and optionally wait for port to come up.
:param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration.
:param force: whether to revoke existing reservation (True) or not (False).
:param wait_for_up: True - wait for port to come up, ... |
380,358 | def enable_contactgroup_svc_notifications(self, contactgroup):
for contact_id in contactgroup.get_contacts():
self.enable_contact_svc_notifications(self.daemon.contacts[contact_id]) | Enable service notifications for a contactgroup
Format of the line that triggers function call::
ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to enable
:type contactgroup: alignak.objects.contactgroup.Contactgroup
:return: None |
380,359 | def read_dependencies(filename):
dependencies = []
filepath = os.path.join(, filename)
with open(filepath, ) as stream:
for line in stream:
package = line.strip().split()[0].strip()
if package and package.split()[0] != :
dependencies.append(package)
r... | Read in the dependencies from the virtualenv requirements file. |
380,360 | def run(self):
plays = []
matched_tags_all = set()
unmatched_tags_all = set()
self.callbacks.on_start()
for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
play = Play(self, play_ds, play_basedir)
matched_tags, unmatch... | run all patterns in the playbook |
380,361 | def write(self, handle):
handle.write(u"\t".join(self.columns))
handle.write(u"\n")
for row in self.rows:
row.write(handle) | Write metadata to handle. |
380,362 | def read(self):
if self._current >= len(self._data):
return None
self._current += 1
return self._data[self._current - 1] | Read one character from buffer.
:Returns:
Current character or None if end of buffer is reached |
380,363 | def pool_function(args):
is_valid = True
try:
checker = emailahoy.VerifyEmail()
status, message = checker.verify_email_smtp(args, from_host=, from_email=)
if status == 250:
print("\t[*] Verification of status: {}. Details:\n\t\t{}".format(general.success(args), general... | A wrapper for being able to launch all the threads.
We will use python-emailahoy library for the verification.
Args:
-----
args: reception of the parameters for getPageWrapper as a tuple.
Returns:
--------
A dictionary representing whether the verification was ended
succes... |
380,364 | def pixel_to_q(self, row: float, column: float):
qrow = 4 * np.pi * np.sin(
0.5 * np.arctan(
(row - float(self.header.beamcentery)) *
float(self.header.pixelsizey) /
float(self.header.distance))) / float(self.header.wavelength)
qcol = ... | Return the q coordinates of a given pixel.
Inputs:
row: float
the row (vertical) coordinate of the pixel
column: float
the column (horizontal) coordinate of the pixel
Coordinates are 0-based and calculated from the top left corner. |
380,365 | def collapse(self, msgpos):
MT = self._tree[msgpos]
MT.collapse(MT.root)
self.focus_selected_message() | collapse message at given position |
380,366 | def _cas_2(self):
lonc_left = self._format_lon(self.lonm)
lonc_right = self._format_lon(self.lonM)
latc = self._format_lat(self.latm)
print(lonc_left, lonc_right, self.lonm, self.lonM)
img_name_left = self._format_name_map(lonc_left, latc)
print(img_name_left)
... | Longitude overlap (2 images). |
380,367 | def _make_return_edges(self):
for func_addr, func in self.functions.items():
if func.returning is False:
continue
if func.startpoint is None:
l.warning(, func_addr)
continue
startpoint = self.model.get_a... | For each returning function, create return edges in self.graph.
:return: None |
380,368 | def create_win_salt_restart_task():
*
cmd =
args = \
return __salt__[](name=,
user_name=,
force=True,
action_type=,
cmd=cmd,
... | Create a task in Windows task scheduler to enable restarting the salt-minion
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' service.create_win_salt_restart_task() |
380,369 | def dict_table(cls,
d,
order=None,
header=None,
sort_keys=True,
show_none="",
max_width=40):
def _keys():
all_keys = []
for e in d:
keys = d[e].keys... | prints a pretty table from an dict of dicts
:param d: A a dict with dicts of the same type.
Each key will be a column
:param order: The order in which the columns are printed.
The order is specified by the key names of the dict.
:param header: The Hea... |
380,370 | def edge_betweenness_bin(G):
n = len(G)
BC = np.zeros((n,))
EBC = np.zeros((n, n))
for u in range(n):
D = np.zeros((n,))
D[u] = 1
NP = np.zeros((n,))
NP[u] = 1
P = np.zeros((n, n))
Q = np.zeros((n,), dtype=int)
q = n - 1
... | Edge betweenness centrality is the fraction of all shortest paths in
the network that contain a given edge. Edges with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
A : NxN np.ndarray
binary directed/undirected connection matrix... |
380,371 | def check(self, src_tgt, actual_deps):
if self._check_missing_direct_deps or self._check_unnecessary_deps:
missing_file_deps, missing_direct_tgt_deps = \
self._compute_missing_deps(src_tgt, actual_deps)
buildroot = get_buildroot()
def shorten(path):
if path.startswith(buil... | Check for missing deps.
See docstring for _compute_missing_deps for details. |
380,372 | def returner(ret):
_options = _get_options(ret)
channel = _options.get()
username = _options.get()
as_user = _options.get()
api_key = _options.get()
changes = _options.get()
only_show_failed = _options.get()
yaml_format = _options.get()
if not channel:
log.error()
... | Send an slack message with the data |
380,373 | async def rows(self, offs, size=None, iden=None):
if iden is not None:
self.setOffset(iden, offs)
for i, (indx, byts) in enumerate(self._items.rows(offs)):
if size is not None and i >= size:
return
yield indx, byts | Yield a number of raw items from the CryoTank starting at a given offset.
Args:
offs (int): The index of the desired datum (starts at 0)
size (int): The max number of items to yield.
Yields:
((indx, bytes)): Index and msgpacked bytes. |
380,374 | def sponsor_image_url(sponsor, name):
if sponsor.files.filter(name=name).exists():
return sponsor.files.filter(name=name).first().item.url
return | Returns the corresponding url from the sponsors images |
380,375 | def get_auth(self):
url = self.h_url + self.server + ":" + self.port
auth = requests.auth.HTTPDigestAuth(self.username,self.password)
auth_url = "/imcrs"
f_url = url + auth_url
try:
r = requests.get(f_url, auth=auth, headers=headers, verify=False)
... | This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object
:return: |
380,376 | def run_job(self, section_id, session=None):
if not self.parser.has_section(section_id):
raise KeyError(.format(section_id))
session = session or Session()
for name, looter_cls in six.iteritems(self._CLS_MAP):
targets = self.get_targets(self._get(... | Run a job as described in the section named ``section_id``.
Raises:
KeyError: when the section could not be found. |
380,377 | def parse_events(content, start=None, end=None, default_span=timedelta(days=7)):
if not start:
start = now()
if not end:
end = start + default_span
if not content:
raise ValueError()
calendar = Calendar.from_ical(content)
break;
else:
cal... | Query the events occurring in a given time range.
:param content: iCal URL/file content as String
:param start: start date for search, default today
:param end: end date for search
:param default_span: default query length (one week)
:return: events as list |
380,378 | def send(self, *args, **kwargs):
conn = SMTP(*args, **kwargs)
send_result = conn.send(self)
return conn, send_result | Sends the envelope using a freshly created SMTP connection. *args*
and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP`
constructor.
Returns a tuple of SMTP object and whatever its send method returns. |
380,379 | def displayText(self, value, blank=, joiner=):
if value is None:
return
labels = []
for key, my_value in sorted(self.items(), key=lambda x: x[1]):
if value & my_value:
labels.append(self._labels.get(my_value, text.pretty(key)))
return j... | Returns the display text for the value associated with
the inputted text. This will result in a comma separated
list of labels for the value, or the blank text provided if
no text is found.
:param value | <variant>
blank | <str>
jo... |
380,380 | def _kmp_construct_next(self, pattern):
next = [[0 for state in pattern] for input_token in self.ALPHABETA_KMP]
next[pattern[0]][0] = 1
restart_state = 0
for state in range(1, len(pattern)):
for input_token in self.... | the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern. |
380,381 | def open_addnew_win(self, *args, **kwargs):
if self.reftrackadderwin:
self.reftrackadderwin.close()
self.reftrackadderwin = ReftrackAdderWin(self.refobjinter, self.root, parent=self)
self.reftrackadderwin.destroyed.connect(self.addnewwin_destroyed)
self.reftrackadder... | Open a new window so the use can choose to add new reftracks
:returns: None
:rtype: None
:raises: NotImplementedError |
380,382 | def delete_nsg(access_token, subscription_id, resource_group, nsg_name):
endpoint = .join([get_rm_endpoint(),
, subscription_id,
, resource_group,
, nsg_name,
, NETWORK_API])
return do_delete(endpoint, access_to... | Delete network security group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
nsg_name (str): Name of the NSG.
Returns:
HTTP response. |
380,383 | def load_datafile(self, name, search_path=None, **kwargs):
if not search_path:
search_path = self.define_dir
self.debug_msg( % (name, str(search_path)))
return codec.load_datafile(name, search_path, **kwargs) | find datafile and load them from codec |
380,384 | def stopContext(self, context):
if ((self.clear_context[] and inspect.ismodule(context)) or
(self.clear_context[] and inspect.isclass(context))):
self.connection.drop_database(self.database_name) | Clear the database if so configured for this |
380,385 | def copy_ssh_keys_to_host(self, host, password=None, no_add_host=False, known_hosts=DEFAULT_KNOWN_HOSTS):
client = None
try:
client = paramiko.SSHClient()
if not no_add_host:
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
... | Copy the SSH keys to the given host.
:param host: the `Host` object to copy the SSH keys to.
:param password: the SSH password for the given host.
:param no_add_host: if the host is not in the known_hosts file, write an error instead of adding it to the
known_hosts.
... |
380,386 | def is_admin(self):
return self.role == self.roles.administrator.value and self.state == State.approved | Is the user a system administrator |
380,387 | def add_sma(self,periods=20,column=None,name=,
str=None,**kwargs):
if not column:
column=self._d[]
study={:,
:name,
:{:periods,:column,
:str},
:utils.merge_dict({:False},kwargs)}
self._add_study(study) | Add Simple Moving Average (SMA) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
column :string
Defines the data column name that contains the
data over which the study will be applied.
Default: 'close'
name : string
Name given to the study
str :... |
380,388 | def dmrs_tikz_dependency(xs, **kwargs):
def link_label(link):
return .format(link.rargname or , link.post)
def label_edge(link):
if link.post == H_POST and link.rargname == RSTR_ROLE:
return
elif link.post == EQ_POST:
return
else:
retur... | Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs.
DMRSs use the `tikz-dependency` package for visualization. |
380,389 | def update_reflexrules_workflow_state(portal):
wf_tool = getToolByName(portal, )
logger.info("Updating Reflex Rulesinactive_stateportal_catalogReflexRule s were updated.") | Updates Reflex Rules' inactive_state, otherwise they don't have it by
default.
:param portal: Portal object
:return: None |
380,390 | def callback(self, request, **kwargs):
access_token = Pocket.get_access_token(consumer_key=self.consumer_key, code=request.session[])
kwargs = {: access_token}
return super(ServicePocket, self).callback(request, **kwargs) | Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template |
380,391 | def name(self):
if self.cadence == :
return self.__class__.__name__
else:
return % self.__class__.__name__ | Returns the name of the current :py:class:`Detrender` subclass. |
380,392 | def getStates(self):
cust_attr = (self.raw_data.get("rtc_cm:state")
.get("@rdf:resource")
.split("/")[-2])
return self.rtc_obj._get_paged_resources("State",
projectarea_id=self.contextId,
... | Get all :class:`rtcclient.models.State` objects of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.State` objects
:rtype: list |
380,393 | def parents(self, resources):
if self.docname == :
return []
parents = []
parent = resources.get(self.parent)
while parent is not None:
parents.append(parent)
parent = resources.get(parent.parent)
return parents | Split the path in name and get parents |
380,394 | def send_workflow(self):
task_invitation = TaskInvitation.objects.get(self.task_invitation_key)
wfi = task_invitation.instance
select_role = self.input[][]
if wfi.current_actor == self.current.role:
task_invitation.role = RoleModel.objects.get(select_role)
... | With the workflow instance and the task invitation is assigned a role. |
380,395 | def uriref_matches_iriref(v1: URIRef, v2: Union[str, ShExJ.IRIREF]) -> bool:
return str(v1) == str(v2) | Compare :py:class:`rdflib.URIRef` value with :py:class:`ShExJ.IRIREF` value |
380,396 | async def load_cache(self, archive: bool = False) -> int:
LOGGER.debug(, archive)
rv = int(time())
box_ids = json.loads(await self.get_box_ids_json())
for s_id in box_ids[]:
with SCHEMA_CACHE.lock:
await self.get_schema(s_id)
for cd_id in bo... | Load caches and archive enough to go offline and be able to generate proof
on all credentials in wallet.
Return timestamp (epoch seconds) of cache load event, also used as subdirectory
for cache archives.
:return: cache load event timestamp (epoch seconds) |
380,397 | def _check_fields(self, x, y):
if x is None:
if self.x is None:
self.err(
self._check_fields,
"X field is not set: please specify a parameter")
return
x = self.x
if y is None:
if self.y is None:
self.err(
self._check_fields,
"Y field is not set: please specify a parameter... | Check x and y fields parameters and initialize |
380,398 | def validate(self, value, validator):
try:
validator.validate(value)
except Exception as e:
logging.debug(e, exc_info=e)
if isinstance(e, DoctorError):
raise
else:
validation_errors = sorted(
... | Validates and returns the value.
If the value does not validate against the schema, SchemaValidationError
will be raised.
:param value: A value to validate (usually a dict).
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().... |
380,399 | def _get_goroot(self, goids_all, namespace):
root_goid = self.consts.NAMESPACE2GO[namespace]
if root_goid in goids_all:
return root_goid
root_goids = set()
for goid in goids_all:
goterm = self.gosubdag.go2obj[goid]
if goterm.depth == 0:
... | Get the top GO for the set of goids_all. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.