Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,200 | def inline(self, article):
return self._query_zendesk(self.endpoint.inline, , id=article) | Returns all inline attachments associated with article_id where (Such attachments has ``inline=True`` flag).
Inline attachments and its url can be referenced in the HTML body of the article.
:param article: Numeric article id or :class:`Article` object.
:return: Generator with all associated i... |
360,201 | def get_assessment_taken_admin_session(self, proxy):
if not self.supports_assessment_taken_admin():
raise errors.Unimplemented()
return sessions.AssessmentTakenAdminSession(proxy=proxy, runtime=self._runtime) | Gets the ``OsidSession`` associated with the assessment taken administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentTakenAdminSession) - an
``AssessmentTakenAdminSession``
raise: NullArgument - ``proxy`` is ``null``
raise: ... |
360,202 | def clip_boxes(boxes, im_shape):
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)
boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0)
boxes[:, 3::4] = n... | Clip boxes to image boundaries.
:param boxes: [N, 4* num_classes]
:param im_shape: tuple of 2
:return: [N, 4* num_classes] |
360,203 | def transform_tensor(self, tensor):
dim = tensor.shape
rank = len(dim)
assert all([i == 3 for i in dim])
lc = string.ascii_lowercase
indices = lc[:rank], lc[rank:2 * rank]
einsum_string = .join([a + i for a, i in zip(*indices)])
einsum_string += ... | Applies rotation portion to a tensor. Note that tensor has to be in
full form, not the Voigt form.
Args:
tensor (numpy array): a rank n tensor
Returns:
Transformed tensor. |
360,204 | def subscribe(self, objectID, varIDs=None, begin=0, end=2**31 - 1):
if varIDs is None:
if tc.LAST_STEP_VEHICLE_NUMBER in self._retValFunc:
varIDs = (tc.LAST_STEP_VEHICLE_NUMBER,)
else:
varIDs = (tc.ID_LIST,)
self._connection._subscribe(
... | subscribe(string, list(integer), double, double) -> None
Subscribe to one or more object values for the given interval. |
360,205 | def sign(xml, stream, password=None):
import xmlsec
from saml.schema.base import _element_registry
element = _element_registry.get(xml.tag)
signature_node = xmlsec.template.create(
xml,
xmlsec.Transform.EXCL_C14N,
xmlsec.Transform.RSA_SHA1)
x... | Sign an XML document with the given private key file. This will add a
<Signature> element to the document.
:param lxml.etree._Element xml: The document to sign
:param file stream: The private key to sign the document with
:param str password: The password used to access the private key
:rtype: Non... |
360,206 | def _mantissa(dval):
bb = _double_as_bytes(dval)
mantissa = bb[1] & 0x0f << 48
mantissa += bb[2] << 40
mantissa += bb[3] << 32
mantissa += bb[4]
return mantissa | Extract the _mantissa bits from a double-precision floating
point value. |
360,207 | def status(name, sig=None):
*
if sig:
return bool(__salt__[](sig))
contains_globbing = bool(re.search(r, name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = _service_cmd(s... | Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signature... |
360,208 | def connect(dbapi_connection, connection_record):
try:
cursor = dbapi_connection.cursor()
try:
cursor.execute("PRAGMA foreign_keys = ON;")
cursor.execute("PRAGMA foreign_keys;")
if cursor.fetchone()[0] != 1:
rai... | Called once by SQLAlchemy for each new SQLite DB-API connection.
Here is where we issue some PRAGMA statements to configure how we're
going to access the SQLite database.
@param dbapi_connection:
A newly connected raw SQLite DB-API connection.
@param connection_record:
... |
360,209 | def _parse_ip_stats_link_show(raw_result):
show_re = (
r
r
r
r
r
r
)
re_result = match(show_re, raw_result, DOTALL)
result = None
if (re_result):
result = re_result.groupdict()
for key, value in result.items():
if va... | Parse the 'ip -s link show dev <dev>' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show interface command in a \
dictionary of the form:
::
{
'rx_bytes': 0,
'rx_packets': 0,
'rx_... |
360,210 | def swapWH(self):
width = self.width
self.width = self.height
self.height = width | !
\~english Swap width and height of rectangles
\~chinese 交换矩形高宽边数据 |
360,211 | def copy(self, copy_backends=True, copy_default_backend=True,
copy_cache=None, copy_history=None):
copied = Circuit(self.n_qubits, self.ops.copy())
if copy_backends:
copied._backends = {k: v.copy() for k, v in self._backends.items()}
if copy_default_backend:
... | Copy the circuit.
:params
copy_backends :bool copy backends if True.
copy_default_backend :bool copy default_backend if True. |
360,212 | def set(self, key, val):
self._create_file_if_none_exists()
with open(self.filename, ) as file_object:
cache_pickle = pickle.load(file_object)
cache_pickle[key] = val
file_object.seek(0)
pickle.dump(cache_pickle, file_object) | Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value. |
360,213 | def _valmatch(vs, ss, op, varsort, semi, section):
if op in _EQUAL_OPS or semi is None:
return all(
s == v or
(s == and v is not None) or
(
v is None and (
s == or
(s[0], s[-1], s[1:-1]) == (, , varsort)... | Return `True` if for every paired *v* and *s* from *vs* and *ss*:
v <> s (subsumption or equality if *semi* is `None`)
v == s (equality)
s == '*'
s == '!' and v == `None`
s == '[xyz]' and varsort == 'xyz' |
360,214 | def unique_ordered(list_):
list_ = list(list_)
flag_list = flag_unique_items(list_)
unique_list = compress(list_, flag_list)
return unique_list | Returns unique items in ``list_`` in the order they were seen.
Args:
list_ (list):
Returns:
list: unique_list - unique list which maintains order
CommandLine:
python -m utool.util_list --exec-unique_ordered
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_lis... |
360,215 | def charge_credit_card(self, credit_card_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]:
pass | :param credit_card_psp_object: an instance representing the credit card in the psp
:param amount: the amount to charge
:param client_ref: a reference that will appear on the customer's credit card report
:return: a tuple (success, payment_psp_object) |
360,216 | def read_wv_master_file(wv_master_file, lines=, debugplot=0):
if lines not in [, ]:
raise ValueError( + str(lines))
master_table = np.genfromtxt(wv_master_file)
wv_master = read_wv_master_from_array(master_table, lines)
if abs(debugplot) >= 10:
print("Reading master ta... | read arc line wavelengths from external file.
Parameters
----------
wv_master_file : string
File name of txt file containing the wavelength database.
lines : string
Indicates which lines to read. For files with a single column
or two columns this parameter is irrelevant. For fil... |
360,217 | def show_clock_output_clock_time_timezone(self, **kwargs):
config = ET.Element("config")
show_clock = ET.Element("show_clock")
config = show_clock
output = ET.SubElement(show_clock, "output")
clock_time = ET.SubElement(output, "clock-time")
timezone = ET.SubEleme... | Auto Generated Code |
360,218 | def add_basic_block(self, basic_block):
assert(isinstance(basic_block, BasicBlock))
self.basic_block_list.append(basic_block) | Adds the given basic block in the function |
360,219 | def _loop_thread_main(self):
asyncio.set_event_loop(self.loop)
self._loop_check.inside_loop = True
try:
self._logger.debug("Starting loop in background thread")
self.loop.run_forever()
self._logger.debug("Finished loop in background thread")
... | Main background thread running the event loop. |
360,220 | def parse_skypos(ra, dec):
rval = make_val_float(ra)
dval = make_val_float(dec)
if rval is None:
rval, dval = radec_hmstodd(ra, dec)
return rval, dval | Function to parse RA and Dec input values and turn them into decimal
degrees
Input formats could be:
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
nn.nnnnnnnn
"nn.nnnnnnn" |
360,221 | def plot_as_routes(route_shapes, ax=None, spatial_bounds=None, map_alpha=0.8, plot_scalebar=True, legend=True,
return_smopy_map=False, line_width_attribute=None, line_width_scale=1.0, map_style=None):
lon_min = spatial_bounds[]
lon_max = spatial_bounds[]
lat_min = spatial_bounds[]
... | Parameters
----------
route_shapes: list of dicts that should have the following keys
name, type, agency, lats, lons
with types
list, list, str, list, list
ax: axis object
spatial_bounds: dict
map_alpha:
plot_scalebar: bool
legend:
return_smopy_map:
... |
360,222 | def accept_proposed_value(self):
if self.proposed_value is not None:
self.current_value = self.proposed_value
self.proposed_value = None
return | Changes the current value to the proposed value. |
360,223 | def getObjectForProxy(self, proxy):
obj = self.proxied_objects.get(id(proxy))
if obj is None:
from pyamf import flex
obj = flex.unproxy_object(proxy)
self.addProxyObject(obj, proxy)
return obj | Returns the unproxied version of C{proxy} as stored in the context, or
unproxies the proxy and returns that 'raw' object.
@see: L{pyamf.flex.unproxy_object}
@since: 0.6 |
360,224 | def polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs):
data = get_data(hist, cumulative=False, flatten=True,
density=kwargs.pop("density", False))
cmap = _get_cmap(kwargs)
norm, cmap_data = _get_cmap_data(data, kwargs)
color... | Polar map of polar histograms.
Similar to map, but supports less parameters. |
360,225 | def _cells(nb):
if nb.nbformat < 4:
for ws in nb.worksheets:
for cell in ws.cells:
yield cell
else:
for cell in nb.cells:
yield cell | Yield all cells in an nbformat-insensitive manner |
360,226 | def write_svg(self):
import plantuml
puml = self.write_puml()
server = plantuml.PlantUML(url=self.url)
svg = server.processes(puml)
return svg | Returns PUML from the system as a SVG image. Requires plantuml library. |
360,227 | def __assert_param_consistency(args, argx_list_):
if util_arg.NO_ASSERTS:
return
if len(argx_list_) == 0:
return True
argx_flags = [util_iter.isiterable(args[argx]) for argx in argx_list_]
try:
assert all([argx_flags[0] == flag for flag in argx_flags]), (
)
e... | debugging function for accepts_scalar_input2
checks to make sure all the iterable inputs are of the same length |
360,228 | def calculate_shanten(self, tiles_34, open_sets_34=None, chiitoitsu=True, kokushi=True):
tiles_34 = copy.deepcopy(tiles_34)
self._init(tiles_34)
count_of_tiles = sum(tiles_34)
if count_of_tiles > 14:
return -2
if open_sets_34:
... | Return the count of tiles before tempai
:param tiles_34: 34 tiles format array
:param open_sets_34: array of array of 34 tiles format
:param chiitoitsu: bool
:param kokushi: bool
:return: int |
360,229 | def modify(self, contact_id, contact_name, province, city, addr, session, **kwargs):
request = TOPRequest()
request[] = contact_id
request[] = contact_name
request[] = province
request[] = city
request[] = addr
for k, v in kwargs.iteritems():
... | taobao.logistics.address.modify 卖家地址库修改
卖家地址库修改 |
360,230 | def language_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
return self._get_name(, language, min_score) | Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are named in English:
>>> Language.get('fr').language_name()
'French'
>>> Langua... |
360,231 | def tuple_signature_for_components(components: Sequence[Mapping[str, Any]]) -> str:
ts = []
for c in components:
t: str = c[]
if t.startswith():
assert len(t) == 5 or t[5] ==
t = SolidityMetadata.tuple_signature_for_components(c[]) + t[5:... | Equivalent to ``function_signature_for_name_and_inputs('', components)``. |
360,232 | def setimdi(self, node):
ns = {: }
self.metadatatype = MetaDataType.IMDI
if LXE:
self.metadata = ElementTree.tostring(node, xml_declaration=False, pretty_print=True, encoding=)
else:
self.metadata = ElementTree.tostring(node, encoding=)
n = node.... | OBSOLETE |
360,233 | def preferences(self, section=None):
if section is None:
return [self[section][name] for section in self for name in self[section]]
else:
return [self[section][name] for name in self[section]] | Return a list of all registered preferences
or a list of preferences registered for a given section
:param section: The section name under which the preference is registered
:type section: str.
:return: a list of :py:class:`prefs.BasePreference` instances |
360,234 | def value(self, view, template=None):
if view.exists():
value, _ = view.first()
return self.convert(value, view)
elif self.default is REQUIRED:
raise NotFoundError(u"{0} not found".format(view.name))
else:
return ... | Get the value for a `ConfigView`.
May raise a `NotFoundError` if the value is missing (and the
template requires it) or a `ConfigValueError` for invalid values. |
360,235 | def remove_acl(path):
| Remove the ACL of the file or folder located on the given path.
Also remove the ACL of any file and folder below the given one,
recursively.
Args:
path (str): Path to the file or folder to remove the ACL for,
recursively. |
360,236 | def get_all_keys(reactor, key_type, value_type, etcd_address):
etcd = Client(reactor, etcd_address)
result = yield etcd.get(b, range_end=b)
res = {}
for item in result.kvs:
if key_type == u:
key = item.key.decode()
elif key_type == u:
key = binascii.b2a_base... | Returns all keys from etcd.
:param reactor: reference to Twisted' reactor.
:param etcd_address: Address with port number where etcd is
running.
:return: An instance of txaioetcd.Range containing all keys and
their values. |
360,237 | def _convertTmp(self, tmpCacheEntry):
from analyser.common.signal import loadSignalFromWav
tmpCacheEntry[] =
logger.info("Loading " + tmpCacheEntry[])
signal = loadSignalFromWav(tmpCacheEntry[])
logger.info("Loaded " + tmpCacheEntry[])
if Path(tmpCacheEntry[]).e... | Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries.
:param tmpCacheEntry: the cache entry.
:return: |
360,238 | def set_video_mode_hint(self, display, enabled, change_origin, origin_x, origin_y, width, height, bits_per_pixel):
if not isinstance(display, baseinteger):
raise TypeError("display can only be an instance of type baseinteger")
if not isinstance(enabled, bool):
raise Type... | Asks VirtualBox to request the given video mode from
the guest. This is just a hint and it cannot be guaranteed
that the requested resolution will be used. Guest Additions
are required for the request to be seen by guests. The caller
should issue the request and wait for a resolution cha... |
360,239 | def _collectAsArrow(self):
with SCCallSiteSync(self._sc) as css:
sock_info = self._jdf.collectAsArrowToPython()
results = list(_load_from_socket(sock_info, ArrowCollectSerializer()))
batches = results[:-1]
batch_order = results[-1]
return ... | Returns all records as a list of ArrowRecordBatches, pyarrow must be installed
and available on driver and worker Python environments.
.. note:: Experimental. |
360,240 | def select_postponed_date(self):
_form = forms.JsonForm(title="Postponed Workflow")
_form.start_date = fields.DateTime("Start Date")
_form.finish_date = fields.DateTime("Finish Date")
_form.save_button = fields.Button("Save")
self.form_out(_form) | The time intervals at which the workflow is to be extended are determined.
.. code-block:: python
# request:
{
'task_inv_key': string,
} |
360,241 | async def _send(self, http_verb, api_url, req_args):
res = await self._request(
http_verb=http_verb, api_url=api_url, req_args=req_args
)
data = {
"client": self,
"http_verb": http_verb,
"api_url": api_url,
"req_args": req_args... | Sends the request out for transmission.
Args:
http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'.
api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage'
req_args (dict): The request arguments to be attached to the request.
e.g.
... |
360,242 | def _remove_remote_node_data_bag():
node_data_bag_path = os.path.join(env.node_work_path, , )
if exists(node_data_bag_path):
sudo("rm -rf {0}".format(node_data_bag_path)) | Removes generated 'node' data_bag from the remote node |
360,243 | def ready(self):
if self._last_failed:
delta = time.time() - self._last_failed
return delta >= self.backoff()
return True | Whether or not enough time has passed since the last failure |
360,244 | def contains_one_of(*fields):
message = .format(.join(fields))
def check_contains(endpoint_fields):
for field in fields:
if field in endpoint_fields:
return
errors = {}
for field in fields:
errors[field] =
return errors
check_co... | Enables ensuring that one of multiple optional fields is set |
360,245 | def _get_query_sets_for_object(o):
if o:
if isinstance(o, Literal):
query_sets = [models.LiteralStatement.objects]
else:
query_sets = [models.URIStatement.objects]
else:
query_sets = [models.URIStatement.objects, models.LiteralStatement.objects]
return qu... | Determines the correct query set based on the object.
If the object is a literal, it will return a query set over LiteralStatements.
If the object is a URIRef or BNode, it will return a query set over Statements.
If the object is unknown, it will return both the LiteralStatement and Statement query sets.
... |
360,246 | def _pick_keywords(db):
for key, val in tqdm(db.iteritems(), total=len(db)):
if key == "last_id":
continue
piece = val[:500] if len(val) > 500 else val
if not in piece.lower():
continue
parsed = MARCXMLRecord(val)
co... | Go thru downloaded data stored in `db` and filter keywords, which are
parsed and then yielded.
Shows nice progress bar.
Args:
db (obj): Opened database connection.
Yields:
obj: :class:`KeywordInfo` instances for yeach keyword. |
360,247 | def _convert_agg_to_wx_bitmap(agg, bbox):
if bbox is None:
return wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),
agg.buffer_rgba())
else:
return _WX28_clipped_agg_as_bitmap(agg, bbox) | Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance. |
360,248 | def _default_config(self, return_type):
if return_type == list:
return [k for k in self.config_file_contents]
return return_type() | Generates a default instance of whatever the type requested was (in case of miss)
:param return_type: type, type of object requested
:return: object, instance of return_type |
360,249 | def standardize_language(language, plugin):
if not language:
return None
if plugin:
plugin = plugin.split()[-1].split()[0].split()[0]
standardized = get_language_from_json(language, plugin)
if standardized is not None:
return standardized
return ... | Maps a string to the equivalent Pygments language.
Returns the standardized language string. |
360,250 | def set_record(self, name, record_id, record):
if name not in self._cache:
self._cache[name] = {}
self._cache[name][record_id] = record | Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model |
360,251 | def to_html(self, table_width=5):
env = self.jinja2_environment
template = env.get_template(self.TEMPLATE_NAMES[])
return template.render(program=self, table_width=table_width) | Write the program information to HTML code, which can be saved,
printed and brought to the gym.
Parameters
----------
table_width
The table with of the HTML code.
Returns
-------
string
HTML code. |
360,252 | def Read(self, file_object):
file_object.seek(self.last_read, os.SEEK_SET)
read_data = file_object.read(self._MAXIMUM_READ_SIZE)
self.last_read = file_object.get_offset()
compressed_data = b.join([self._compressed_data, read_data])
decompressed, extra_compressed = self._decompressor.Decompress(... | Reads the next uncompressed data from the gzip stream.
Args:
file_object (FileIO): file object that contains the compressed stream.
Returns:
bytes: next uncompressed data from the compressed stream. |
360,253 | def source_path(self):
names = [k for k, _, _ in self._name_parts]
parts = [self.source]
if self.bspace:
parts.append(self.bspace)
parts.append(
self._path_join(names=names, excludes=[, , ], sep=self.NAME_PART_SEP))
return os... | The name in a form suitable for use in a filesystem.
Excludes the revision |
360,254 | def make_csv(data):
for entry in data:
rval = entry
if isinstance(data, dict):
rval = data[entry]
todel = []
toadd = {}
for key, val in rval.items():
if isinstance(val, dict):
for key2, val2 in val.items():
... | Returns the content of a CSV file with the data of the dict/list data |
360,255 | def all_intersects_all(self, other):
return set(self) == set(other) and all(other[key].intersects(value) for key, value in self.iteritems()) and bool(self) | Returns True if self and other have the same keys, and each
segmentlist intersects the corresponding segmentlist in the
other; returns False if this is not the case or if either
dictionary is empty.
See also:
.intersects(), .all_intersects(), .intersects_all() |
360,256 | def route(
self,
path: str,
methods: Optional[List[str]]=None,
endpoint: Optional[str]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
provide_automatic_options: O... | Add a route to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.route`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.route('/')
def route():
.... |
360,257 | def render_pdf_file_to_image_files(pdf_file_name, output_filename_root, program_to_use):
res_x = str(args.resX)
res_y = str(args.resY)
if program_to_use == "Ghostscript":
if ex.system_os == "Windows":
ex.render_pdf_file_to_image_files__ghostscript_bmp(
... | Render all the pages of the PDF file at pdf_file_name to image files with
path and filename prefix given by output_filename_root. Any directories must
have already been created, and the calling program is responsible for
deleting any directories or image files. The program program_to_use,
currently ei... |
360,258 | def ellipse(data, channels,
center, a, b, theta=0,
log=False, full_output=False):
if len(channels) != 2:
raise ValueError()
data_ch = data[:,channels].view(np.ndarray)
if log:
data_ch = np.log10(data_ch)
center = np.array(center)
data_cen... | Gate that preserves events inside an ellipse-shaped region.
Events are kept if they satisfy the following relationship::
(x/a)**2 + (y/b)**2 <= 1
where `x` and `y` are the coordinates of the event list, after
substracting `center` and rotating by -`theta`. This is mathematically
equivalent to... |
360,259 | def get_subsequence_from_property(self, property_key, property_value, condition,
return_resnums=False, copy_letter_annotations=True):
if property_key not in self.letter_annotations:
log.error(.format(self.id, property_key))
return
... | Get a subsequence as a new SeqProp object given a certain property you want to find in the
original SeqProp's letter_annotation
This can be used to do something like extract the subsequence of exposed residues, so you can can run
calculations on that subsequence. Useful if you have questions li... |
360,260 | def get_field_min_max(self, name, **query_dict):
param_dict = query_dict.copy()
param_dict.update({: 1, : name, : % name})
try:
min_resp_dict = self._post_query(**param_dict)
param_dict[] = % name
max_resp_dict = self._post_query(**param_dict)
... | Returns the minimum and maximum values of the specified field. This requires
two search calls to the service, each requesting a single value of a single
field.
@param name(string) Name of the field
@param q(string) Query identifying range of records for min and max values
@param... |
360,261 | def to_vec4(self, isPoint):
vec4 = Vector4()
vec4.x = self.x
vec4.y = self.y
vec4.z = self.z
if isPoint:
vec4.w = 1
else:
vec4.w = 0
return vec4 | Converts this vector3 into a vector4 instance. |
360,262 | def exit_config_mode(self, exit_config="return", pattern=r">"):
return super(HPComwareBase, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) | Exit config mode. |
360,263 | def iter_cookie_browse_sorting(cookies):
try:
data = cookies.get(, ).encode()
for path, prop in json.loads(base64.b64decode(data).decode()):
yield path, prop
except (ValueError, TypeError, KeyError) as e:
logger.exception(e) | Get sorting-cookie from cookies dictionary.
:yields: tuple of path and sorting property
:ytype: 2-tuple of strings |
360,264 | def load(self, filething):
data = _APEv2Data(filething.fileobj)
if data.tag:
self.clear()
self.__parse_tag(data.tag, data.items)
else:
raise APENoHeaderError("No APE tag found") | Load tags from a filename.
Raises apev2.error |
360,265 | def getParser():
"Creates and returns the argparse parser object."
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=__description__)
parser.add_argument(, help=)
parser.add_argument(, help=)
parser.add_argument(, type=argparseu.sequenceOfIntegersGt, ... | Creates and returns the argparse parser object. |
360,266 | def clear(self):
for clear_data in self.profile.get() or []:
if clear_data.get() == :
self.clear_redis(clear_data.get(), )
elif clear_data.get() == :
self.clear_tc(clear_data.get(), clear_data, ) | Clear Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data_type": "redis",
"variable": "#App:4768:tc.adversary!TCEntity"
}
ThreatConnect Data:
.. code-block:: javascript
{
... |
360,267 | def read_graph(filename, directed=False, weighted=False, default_weight=None):
with open(filename, ) as f:
while True:
line = f.readline()
if line[0] != :
break
nb_nodes, nb_edges = tuple(map(int, line.split()))
graph = [[] for u in range... | Read a graph from a text file
:param filename: plain text file. All numbers are separated by space.
Starts with a line containing n (#vertices) and m (#edges).
Then m lines follow, for each edge.
Vertices are numbered from 0 to n-1.
Line for unweighted edge u... |
360,268 | def to_superuser(email_class, **data):
for user in get_user_model().objects.filter(is_superuser=True):
try:
email_class().send([user.email], user.language, **data)
except AttributeError:
email_class().send([user.email], translation.get_language(), **data) | Email superusers |
360,269 | def package(self):
logger.info(.format(self.lambda_name))
zfh = io.BytesIO()
if os.path.exists(os.path.join(self.lambda_dir, )):
logger.warn(
t want uploaded to AWS!w.env\n{} = {}requirements.txtinstall-rrequirements.txt-tda... | Packages lambda data for deployment into a zip |
360,270 | def main():
do_help = pmag.get_flag_arg_from_sys()
if do_help:
print(main.__doc__)
return False
res_file = pmag.get_named_arg(, )
crit_file = pmag.get_named_arg(, )
spec_file = pmag.get_named_arg(, )
age_file = pmag.get_named_arg(, )
grade = pmag.get_flag_arg_from_sys()
... | NAME
pmag_results_extract.py
DESCRIPTION
make a tab delimited output file from pmag_results table
SYNTAX
pmag_results_extract.py [command line options]
OPTIONS
-h prints help message and quits
-f RFILE, specify pmag_results table; default is pmag_results.txt
... |
360,271 | def get_view_and_name(self, attname):
view = getattr(self, attname, None)
if attname in self._children:
view = self._get_bundle_from_promise(attname)
if view:
if attname in self._children:
return view, view.name
elif isinstance(view, ... | Gets a view or bundle and returns it
and it's url_name. |
360,272 | def parse_response(self, response):
payload = None
try:
if isinstance(response.json, collections.Callable):
payload = response.json()
else:
else:
return payload | Parses the API response and raises appropriate
errors if raise_errors was set to True
:param response: response from requests http call
:returns: dictionary of response
:rtype: dict |
360,273 | def mark_best_classification(text_log_error, classified_failure):
text_log_error.metadata.best_classification = classified_failure
text_log_error.metadata.save(update_fields=[])
text_log_error.metadata.failure_line.elastic_search_insert() | Wrapper for setting best_classification on both TextLogError and FailureLine.
Set the given ClassifiedFailure as best_classification for the given
TextLogError. Handles the duplication of best_classification on FailureLine
so you don't have to! |
360,274 | def is_edge_consistent(graph, u, v):
if not graph.has_edge(u, v):
raise ValueError(.format(graph, u, v))
return 0 == len(set(d[RELATION] for d in graph.edge[u][v].values())) | Check if all edges between two nodes have the same relation.
:param pybel.BELGraph graph: A BEL Graph
:param tuple u: The source BEL node
:param tuple v: The target BEL node
:return: If all edges from the source to target node have the same relation
:rtype: bool |
360,275 | def strategy(self, *names, **kwargs):
def decorator(func):
keep_name = kwargs.pop("keep_name", False)
if kwargs:
key = next(iter(kwargs))
raise TypeError("Unknown keyword argument ".format(key))
if not keep_name:
func.__name__ = str(names[0])
self[names] = func
... | StrategyDict wrapping method for adding a new strategy.
Parameters
----------
*names :
Positional arguments with all names (strings) that could be used to
call the strategy to be added, to be used both as key items and as
attribute names.
keep_name :
Boolean keyword-only paramet... |
360,276 | def multinterp(x, y, xquery, slow=False):
x, y, xquery = map(np.asarray, (x, y, xquery))
assert x.ndim == 1
assert xquery.ndim == 1
assert y.shape == x.shape + xquery.shape
xquery = np.clip(xquery, x.min(), x.max())
if slow:
from scipy.interpolate import interp1d
retu... | Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of query values
slow : boolean, default=False
... |
360,277 | def daterange_(self, datecol, date_start, op, **args):
df = self._daterange(datecol, date_start, op, **args)
if df is None:
self.err("Can not select date range data")
return self._duplicate_(df) | Returns a DataSwim instance with rows in a date range |
360,278 | def add_data_flow_to_state(from_port, to_port):
from rafcon.gui.mygaphas.items.ports import InputPortView, OutputPortView, ScopedVariablePortView
from rafcon.gui.models.container_state import ContainerStateModel
from_state_v = from_port.parent
to_state_v = to_port.parent
from_state_m = from_s... | Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports.
:param from_port: Port... |
360,279 | def _interfaces_added(self, object_path, interfaces_and_properties):
added = object_path not in self._objects
self._objects.setdefault(object_path, {})
old_state = copy(self._objects[object_path])
self._objects[object_path].update(interfaces_and_properties)
new_state = s... | Internal method. |
360,280 | def http_error_handler(f):
def hrefs_to_resources(hrefs):
for href in hrefs.replace(, ).split():
type, uuid = href.split()[-2:]
yield Resource(type, uuid=uuid)
def hrefs_list_to_resources(hrefs_list):
for href in eval(hrefs_list):
type, uuid = href.spli... | Handle 404 errors returned by the API server |
360,281 | def to_internal_value(self, data):
if self.kwargs[]:
serializer = self.serializer.child
if not isinstance(data, list):
raise ParseError(" value must be a list" % self.field_name)
return [
self.to_internal_value_single(
... | Return the underlying object(s), given the serialized form. |
360,282 | def logical_size(self, name):
digest = self._digest_for_link(name)
logical_size = self.db.get(.format(digest).encode())
if logical_size:
return int(logical_size.decode())
else:
raise RuntimeError(
t have :logical_size in DB: try recov... | Returns the logical size (before compression) of file `name`. |
360,283 | def customData( self, key, default = None ):
key = nativestring(key)
menu = self
while (not key in menu._customData and \
isinstance(menu.parent(), XMenu)):
menu = menu.parent()
return menu._customData.get(nativestring(key), default) | Returns data that has been stored on this menu.
:param key | <str>
default | <variant>
:return <variant> |
360,284 | def _all_get_node_by_name(self, name):
path_name = name.replace(, )
where = % (self._trajectory_name, path_name)
return self._hdf5file.get_node(where=where) | Returns an HDF5 node by the path specified in `name` |
360,285 | async def _make_connection(self):
return await aioredis.create_redis(
.format(
self._redis_params.get(, ),
self._redis_params.get(, 6379)
),
db=int(self._redis_params.get(, 1))
) | Construct a connection to Redis. |
360,286 | def aggregations(self):
prev_month_start = get_prev_month(self.end, self.query.interval_)
self.query.since(prev_month_start)
self.query.get_terms("author_name")
return self.query.get_list(dataframe=True) | Override parent method. Obtain list of the terms and their corresponding
values using "terms" aggregations for the previous time period.
:returns: a data frame containing terms and their corresponding values |
360,287 | def _find_matching_expectation(self, args, kwargs):
for expectation in self._expectations:
if expectation.satisfy_exact_match(args, kwargs):
return expectation
for expectation in self._expectations:
if expectation.satisfy_custom_matcher(args, kwargs):
... | Return a matching expectation.
Returns the first expectation that matches the ones declared. Tries one with specific
arguments first, then falls back to an expectation that allows arbitrary arguments.
:return: The matching ``Expectation``, if one was found.
:rtype: Expectation, None |
360,288 | def group_keys_by_replica(session, keyspace, table, keys):
cluster = session.cluster
partition_keys = cluster.metadata.keyspaces[keyspace].tables[table].partition_key
serializers = list(types._cqltypes[partition_key.cql_type] for partition_key in partition_keys)
keys_per_host = defaultdict(list)
... | Returns a :class:`dict` with the keys grouped per host. This can be
used to more accurately group by IN clause or to batch the keys per host.
If a valid replica is not found for a particular key it will be grouped under
:class:`~.NO_VALID_REPLICA`
Example usage::
result = group_keys_by_replica... |
360,289 | def deref(self, data):
deref = copy.deepcopy(jsonref.JsonRef.replace_refs(data))
self.write_template(deref, filename=)
return deref | AWS doesn't quite have Swagger 2.0 validation right and will fail
on some refs. So, we need to convert to deref before
upload. |
360,290 | def parse_contact(self):
self.parse_whitespace()
name = self.parse_name()
if not name:
raise PartpyError(self, )
self.parse_whitespace()
if not self.match_any_char():
raise PartpyError(self, )
self.eat_length(1)
self.... | Parse a top level contact expression, these consist of a name
expression a special char and an email expression.
The characters found in a name and email expression are returned. |
360,291 | def get_filetypes2wildcards(filetypes):
def is_available(filetype):
return filetype not in FILETYPE_AVAILABILITY or \
FILETYPE_AVAILABILITY[filetype]
available_filetypes = filter(is_available, filetypes)
return OrderedDict((ft, FILETYPE2WILDCARD[ft])
for... | Returns OrderedDict of filetypes to wildcards
The filetypes that are provided in the filetypes parameter are checked for
availability. Only available filetypes are inluded in the return ODict.
Parameters
----------
filetypes: Iterable of strings
\tFiletype list |
360,292 | def get_geometry_from_name(self, name):
for gg in self.cg_list:
if gg.name == name or name in gg.alternative_names:
return gg
raise LookupError(
.format(
name=name)) | Returns the coordination geometry of the given name.
:param name: The name of the coordination geometry. |
360,293 | def oqi(ql, qs, ns=None, rc=None, ot=None, coe=None, moc=None):
return CONN.OpenQueryInstances(FilterQueryLanguage=ql,
FilterQuery=qs,
namespace=ns,
ReturnQueryResultClass=rc,
... | This function is a wrapper for
:meth:`~pywbem.WBEMConnection.OpenQueryInstances`.
Open an enumeration session to execute a query in a namespace and to
retrieve the instances representing the query result.
Use the :func:`~wbemcli.pi` function to retrieve the next set of
instances or the :func:`~wbc... |
360,294 | def my_import(name, path=None):
if hasattr(importlib, ):
importlib.invalidate_caches()
if path is not None:
directory, src_file = os.path.split(path)
sys.path.insert(0, directory)
try:
mod = importlib.import_module(name)
fin... | Return imported module for the given name. |
360,295 | def recursiveRepr(self, stuff, thunk=repr):
ID = id(stuff)
if ID in self.active:
return % (stuff.__class__.__name__,)
else:
try:
self.active[ID] = stuff
return thunk(stuff)
finally:
del self.active[ID] | Recursive repr(). |
360,296 | def calculate_category_probability(self):
total_tally = 0.0
probs = {}
for category, bayes_category in \
self.categories.get_categories().items():
count = bayes_category.get_tally()
total_tally += count
probs[category] = count
... | Caches the individual probabilities for each category |
360,297 | def locateChild(self, context, segments):
childDeferred = maybeDeferred(
self.wrappedResource.locateChild, context, segments)
def childLocated((resource, segments)):
if (resource, segments) == NotFound:
return NotFound
return _SecureWrapper(se... | Delegate child lookup to the wrapped resource but wrap whatever results
in another instance of this wrapper. |
360,298 | def set_reprompt_text(self, text):
self.response.reprompt.outputSpeech.type =
self.response.reprompt.outputSpeech.text = text | Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters. |
360,299 | def doc_id(self):
if self.id:
return % (self.doc_type, self.id.lower())
return self._hashed_key | Returns the couchbase document's id, object property.
:returns: The document id (that is created from :attr:'doc_type' and
:attr:'__key_field__' value, or auto-hashed document id at first
saving).
:rtype: unicode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.